From 2b8b004fc2d95cb3c7da9c4fe8c1a3a38be37134 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:22:58 -0800 Subject: [PATCH 1/2] fix(monitoring): name alerts as Home Assistant shows the circuit, and refuse an unloaded panel Current monitoring notifications name a circuit by its Home Assistant name, {name} in custom templates included, and the span_panel_current_alert event gains alert_display_name while alert_name stays as it was. {entity_id} carries the circuit's Current sensor, else its Power sensor, or the mains leg's. Every monitoring service now finds its panel through one path: a config entry that is not a SPAN Panel's is refused as monitoring_panel_unknown, an unloaded panel as monitoring_panel_not_loaded, and monitoring_not_enabled is left for a loaded panel with monitoring off. Get monitoring status no longer answers "off" for an unloaded panel, and turning monitoring off on one no longer reports success while doing nothing. The legacy enable_current_monitoring option is moved into the monitoring store once at setup and removed from the entry, so monitoring turned off stays off across a restart. --- CHANGELOG.md | 26 +- custom_components/span_panel/__init__.py | 12 +- .../span_panel/alert_dispatcher.py | 56 ++- custom_components/span_panel/const.py | 1 - .../span_panel/current_monitor.py | 100 +++- custom_components/span_panel/entry_reloads.py | 24 +- custom_components/span_panel/services.py | 159 +++--- custom_components/span_panel/strings.json | 11 +- .../span_panel/translations/en.json | 11 +- .../span_panel/translations/es.json | 11 +- .../span_panel/translations/fr.json | 11 +- .../span_panel/translations/ja.json | 11 +- .../span_panel/translations/pt.json | 11 +- custom_components/span_panel/util.py | 35 ++ frontend.md | 61 +-- tests/replayed_panel.py | 30 +- tests/test_alert_display_names.py | 456 ++++++++++++++++++ tests/test_current_monitor.py | 49 +- tests/test_current_monitor_services.py | 345 ++++++++++++- tests/test_current_monitor_setup.py | 99 +++- tests/test_device_id_migration.py | 13 +- tests/test_package_rating_services.py | 6 +- tests/test_package_ratings.py | 3 +- tests/test_remote_ct_inverter_naming.py | 7 +- 24 files changed, 1316 insertions(+), 232 deletions(-) create mode 100644 tests/test_alert_display_names.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 33ea9e2b..307b44f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,24 @@ All notable changes to this project will be documented in this file. - **An error from a breaker, circuit priority, charger or adopted-device control now names the circuit or device by the name you gave it in Home Assistant**, where it kept the name the panel or the integration gave it. +- **Current monitoring notifications now name a circuit by the name you gave it in Home Assistant, including through `{name}` in a custom title or message**, + where they used its name in the SPAN app; the `span_panel_current_alert` event carries that name in a new `alert_display_name` field and leaves `alert_name` + as it was. + +- **The Get monitoring status action now fails with an error when the panel it is asked about has not finished loading, such as while Home Assistant starts, or + when the config entry it names is not a SPAN Panel's**, where it answered that monitoring was off, so a script step that calls it then stops unless it is set + to continue on error, and Home Assistant logs the error. + +- **Changing a panel's current monitoring while the panel is not loaded, or naming a config entry that is not a SPAN Panel's, now fails with an error, turning + monitoring off included**, where turning it off reported success and left monitoring to start again once the panel loaded, and turning it on, changing its + settings or a threshold named by circuit id or leg, or sending a test notification said monitoring was not enabled. + +- **The `{entity_id}` placeholder in a current monitoring notification's title or message now carries the entity ID of the circuit's Current sensor, or its + Power sensor where it has none, or of the mains leg's Current sensor**, where it carried the circuit's internal id or the leg's name. + +- **Current monitoring turned off now stays off after Home Assistant restarts on a panel whose options still hold the monitoring switch an earlier release + stored there**, where it came back on at every restart. + ## [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, @@ -72,8 +90,8 @@ setting and favorite across to them, and each entity keeps its entity ID and his - **A panel reloads once, not twice, after reauthentication, reconfiguration or re-pinning its certificate authority.** Reconfiguring no longer logs Home Assistant's warning that the integration "has an update listener and should use it for scheduling a reload". -- **A reload no longer starts in the middle of the panel's own update**, and a change that nothing in the integration reads, such as the system option for - new entities, or a rediscovery that changes nothing, no longer reloads the panel. +- **A reload no longer starts in the middle of the panel's own update**, and a change that nothing in the integration reads, such as the system option for new + entities, or a rediscovery that changes nothing, no longer reloads the panel. - **A change made while a panel is setting up is applied.** An options save that landed during setup was stored but not used until the next restart, and a reconfigure completed while the panel was retrying waited for Home Assistant's next retry, up to ten minutes later. Both now reload the panel straight away. @@ -99,8 +117,8 @@ Home Assistant 2026.11. ### Fixed -- **Discovering or adding a panel no longer logs a warning that its credentials are being sent over plaintext HTTP**, which the schema read that set it off never - carries. +- **Discovering or adding a panel no longer logs a warning that its credentials are being sent over plaintext HTTP**, which the schema read that set it off + never carries. ## [2.3.1] - 11/2026 diff --git a/custom_components/span_panel/__init__.py b/custom_components/span_panel/__init__.py index 63cc1142..2eac1be3 100644 --- a/custom_components/span_panel/__init__.py +++ b/custom_components/span_panel/__init__.py @@ -79,7 +79,6 @@ DEFAULT_MQTTS_PORT, DEFAULT_SNAPSHOT_INTERVAL, DOMAIN, - ENABLE_CURRENT_MONITORING, PANEL_CA_PENDING, ) from .control_gate import ControlGate, ControlLock, ControlPolicy @@ -90,7 +89,11 @@ ) from .coordinator import SpanPanelCoordinator from .curation import async_forget_curation, async_load_curation -from .current_monitor import CurrentMonitor, async_forget_monitoring +from .current_monitor import ( + CurrentMonitor, + async_adopt_legacy_enable_option, + async_forget_monitoring, +) from .device_id_rekey import async_migrate_device_ids, entry_holds_old_ids from .entry_issues import async_clear_unlinked_issues, entry_removed from .entry_reloads import ( @@ -914,9 +917,8 @@ async def _async_setup_entry(hass: HomeAssistant, entry: SpanPanelConfigEntry) - await coordinator.async_setup_streaming() - if entry.options.get( - ENABLE_CURRENT_MONITORING, False - ) or await CurrentMonitor.async_is_enabled(hass, entry): + await async_adopt_legacy_enable_option(hass, entry) + if await CurrentMonitor.async_is_enabled(hass, entry): # Held, not judged: the first judgement, and any alert it raises, # is the next update's. monitor = CurrentMonitor( diff --git a/custom_components/span_panel/alert_dispatcher.py b/custom_components/span_panel/alert_dispatcher.py index 14c64b61..d3a6ec8b 100644 --- a/custom_components/span_panel/alert_dispatcher.py +++ b/custom_components/span_panel/alert_dispatcher.py @@ -39,8 +39,8 @@ def format_notification( *, alert_type: str, - alert_name: str, - alert_id: str, + display_name: str, + entity_id: str, current_a: float, monitoring_rating_a: float, threshold_pct: int, @@ -52,13 +52,22 @@ def format_notification( ) -> tuple[str, str]: """Format notification title and message using templates. - `monitoring_rating_a` is the rating the point was judged against, which the - `{breaker_rating_a}` placeholder carries. + `display_name` is the point's name as Home Assistant shows it, which the + `{name}` placeholder carries, and `entity_id` the entity it is shown under, + which `{entity_id}` carries. `monitoring_rating_a` is the rating the point + was judged against, which the `{breaker_rating_a}` placeholder carries. Available placeholders: - {name} - The circuit's name in the SPAN app, or the mains leg + {name} - The circuit's name as Home Assistant shows it: the + name the user gave its device, else the name the + device is registered under, those of circuits that + share a meter joined with " + "; or the mains leg (e.g. "Mains Upstream L1") - {entity_id} - Entity ID (e.g. sensor.kitchen_current) + {entity_id} - The entity ID of the circuit's Current sensor, or + its Power sensor where it has none, that of the + circuit `alert_id` names for circuits that share a + meter; for the mains, the leg's Current sensor + (e.g. sensor.kitchen_current) {alert_type} - "spike" or "continuous_overload" {current_a} - Current draw in amps (e.g. 18.3) {breaker_rating_a}- The rating in amps the circuit is judged against (e.g. 20): @@ -73,8 +82,8 @@ def format_notification( """ window_m = (window_duration_s or 0) // 60 template_vars = { - "name": alert_name, - "entity_id": alert_id, + "name": display_name, + "entity_id": entity_id, "alert_type": alert_type, "current_a": f"{current_a:.1f}", "breaker_rating_a": f"{monitoring_rating_a:.0f}", @@ -86,12 +95,12 @@ def format_notification( try: title = title_template.format_map(template_vars) except (KeyError, ValueError): - title = f"SPAN: {alert_name} {alert_type}" + title = f"SPAN: {display_name} {alert_type}" try: message = message_template.format_map(template_vars) except (KeyError, ValueError): message = ( - f"{alert_name} at {current_a:.1f}A " + f"{display_name} at {current_a:.1f}A " f"({utilization_pct}% of {monitoring_rating_a:.0f}A rating) at {local_time or ''}" ) return title, message @@ -163,7 +172,9 @@ def dispatch_alert( *, alert_type: str, alert_name: str, + display_name: str, alert_id: str, + entity_id: str, alert_source: str, current_a: float, breaker_rating_a: float | None, @@ -179,6 +190,15 @@ def dispatch_alert( ) -> None: """Dispatch alert through all enabled notification channels. + `alert_name` is the panel's name for the point and `display_name` the name + Home Assistant shows for it, the user's where they renamed the circuit's + device. The event carries both, as `alert_name` and `alert_display_name`: + automations read `alert_name`, so a rename in Home Assistant never changes + it. The title and message are read by a person, so their `{name}` is the + name that person finds the circuit under. `alert_id` is the point's id, + which the event carries, and `entity_id` the entity the point is shown + under, which only the text's `{entity_id}` carries. + The event payload carries the ratings as `get_monitoring_status` does: `breaker_rating_a` is the panel's rating (a shared meter's capacity over its members' ratings, None if any is unknown), `monitoring_rating_a` the rating the @@ -199,6 +219,7 @@ def dispatch_alert( "alert_source": alert_source, "alert_id": alert_id, "alert_name": alert_name, + "alert_display_name": display_name, "alert_type": alert_type, "current_a": round(current_a, 1), "breaker_rating_a": breaker_rating_a, @@ -227,8 +248,8 @@ def dispatch_alert( title, message = format_notification( alert_type=alert_type, - alert_name=alert_name, - alert_id=alert_id, + display_name=display_name, + entity_id=entity_id, current_a=current_a, monitoring_rating_a=monitoring_rating_a, threshold_pct=threshold_pct, @@ -274,7 +295,13 @@ def dispatch_test_alert( """Dispatch a test notification using sample values through all enabled channels.""" alert_type = "spike" alert_name = "Kitchen Oven" + # The sample circuit is one nobody renamed, so Home Assistant shows it by + # the panel's name. + display_name = alert_name alert_id = "sensor.kitchen_oven_current" + # The sample's id has always been its sensor's entity ID, so the text's + # `{entity_id}` carries the same one. + entity_id = alert_id alert_source = "circuit" current_a = 18.3 breaker_rating_a = 20.0 @@ -296,6 +323,7 @@ def dispatch_test_alert( "alert_source": alert_source, "alert_id": alert_id, "alert_name": alert_name, + "alert_display_name": display_name, "alert_type": alert_type, "current_a": current_a, "breaker_rating_a": breaker_rating_a, @@ -316,8 +344,8 @@ def dispatch_test_alert( title, message = format_notification( alert_type=alert_type, - alert_name=alert_name, - alert_id=alert_id, + display_name=display_name, + entity_id=entity_id, current_a=current_a, monitoring_rating_a=monitoring_rating_a, threshold_pct=threshold_pct, diff --git a/custom_components/span_panel/const.py b/custom_components/span_panel/const.py index 4e029670..e4c83172 100644 --- a/custom_components/span_panel/const.py +++ b/custom_components/span_panel/const.py @@ -114,7 +114,6 @@ """The config flow's starting choice for a new install, which it stores.""" # Current monitoring configuration -ENABLE_CURRENT_MONITORING = "enable_current_monitoring" DEFAULT_CONTINUOUS_THRESHOLD_PCT = 80 DEFAULT_SPIKE_THRESHOLD_PCT = 100 DEFAULT_WINDOW_DURATION_M = 15 diff --git a/custom_components/span_panel/current_monitor.py b/custom_components/span_panel/current_monitor.py index e871f571..5896ddc9 100644 --- a/custom_components/span_panel/current_monitor.py +++ b/custom_components/span_panel/current_monitor.py @@ -15,13 +15,13 @@ from dataclasses import dataclass from datetime import datetime import logging -from typing import TYPE_CHECKING, Any, Literal, TypedDict +from typing import TYPE_CHECKING, Any, Final, Literal, TypedDict -from homeassistant.helpers import entity_registry as er +from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.storage import Store from span_panel_api import SpanPanelSnapshot, shared_meter_groups -from .alert_dispatcher import dispatch_alert, format_notification +from .alert_dispatcher import dispatch_alert from .const import ( DEFAULT_CONTINUOUS_THRESHOLD_PCT, DEFAULT_COOLDOWN_DURATION_M, @@ -34,6 +34,7 @@ ) from .device_id_migration import rekeyed from .entity_resolver import resolve_circuit_id +from .entry_reloads import async_update_entry_options_applied from .helpers import build_circuit_unique_id, build_panel_unique_id, construct_circuit_label from .meter_capacity import meter_capacity_a from .options import ( @@ -59,6 +60,7 @@ is_monitoring_disabled, resolve_thresholds, ) +from .util import circuit_display_name if TYPE_CHECKING: from homeassistant.config_entries import ConfigEntry @@ -85,6 +87,12 @@ _STORAGE_VERSION = 1 _STORAGE_KEY_PREFIX = "span_panel_current_monitor" +_LEGACY_ENABLE_OPTION: Final = "enable_current_monitoring" +"""The option a release before the monitoring store switched monitoring on by. + +Read only by `async_adopt_legacy_enable_option`, which moves it into the store. +""" + StoredMonitoring = TypedDict( "StoredMonitoring", { @@ -175,6 +183,11 @@ class MonitoredCircuit: its first member: that key is stable while the membership is, which is enough for alerts and overrides, neither of which is an entity. + `name` is the panel's name for the point, each member's label joined with " + ": + the alert event's `alert_name`, which automations read, so a rename in Home + Assistant never changes it. The alert's text names the point as Home + Assistant shows it instead (`CurrentMonitor._display_name`). + `rating_a` is the rating judged against and `panel_rating_a` the breaker rating the panel published, each None where a circuit, or the capacity of a group, is unknown. For a group, both are capacities by the same rule, `rating_a` over the ratings its @@ -461,10 +474,13 @@ def set_global_settings(self, settings: MonitoringSettings) -> None: self._hass.async_create_task(self.async_save_overrides()) def _resolve_circuit_entity_id(self, circuit_id: str) -> str: - """Resolve circuit_id to a sensor entity_id for monitoring status keys. + """Return the entity a circuit is shown under: its monitoring status key, and its alert's `{entity_id}`. - Tries the current sensor first, then falls back to power, matching - the frontend lookup order (circuit.entities.current ?? .power). + Its Current sensor, else its Power sensor, matching the frontend lookup + order (circuit.entities.current ?? .power): a circuit that never publishes + a current has no Current sensor, nor does one whose current first arrived + after setup until the next reload. The circuit's id where Home Assistant + holds neither, as for a circuit the panel added since the entry was set up. """ serial = self._last_snapshot.serial_number entity_reg = er.async_get(self._hass) @@ -524,7 +540,12 @@ def resolve_entity_to_mains_leg(self, entity_id: str) -> str: return entity_id def _resolve_mains_entity_id(self, leg: str) -> str: - """Resolve mains leg to its current sensor entity_id, or fall back to leg name.""" + """Return a mains leg's Current sensor, which its alert's `{entity_id}` carries. + + Upstream L1's is also the key the monitoring status shows the mains + under. The leg's name where Home Assistant holds no such sensor, as for a + leg whose current first arrived after setup. + """ serial = self._last_snapshot.serial_number # The sensor key matches the leg name + "_current" (e.g., "upstream_l1_current") unique_id = build_panel_unique_id(serial, f"{leg}_current") @@ -761,6 +782,7 @@ def _evaluate_circuits(self, snapshot: SpanPanelSnapshot) -> None: self.get_global_settings(), alert_type=alert.alert_type, alert_name=point.name, + display_name=self._display_name(point, snapshot), alert_id=circuit_id, alert_source="circuit", current_a=alert.current_a, @@ -772,6 +794,7 @@ def _evaluate_circuits(self, snapshot: SpanPanelSnapshot) -> None: threshold_pct=alert.threshold_pct, utilization_pct=alert.utilization_pct, panel_serial=snapshot.serial_number, + entity_id=self._resolve_circuit_entity_id(circuit_id), ) alert = check_continuous(state, current, rating, cont_pct, window_m, cooldown_m) @@ -781,6 +804,7 @@ def _evaluate_circuits(self, snapshot: SpanPanelSnapshot) -> None: self.get_global_settings(), alert_type=alert.alert_type, alert_name=point.name, + display_name=self._display_name(point, snapshot), alert_id=circuit_id, alert_source="circuit", current_a=alert.current_a, @@ -794,8 +818,29 @@ def _evaluate_circuits(self, snapshot: SpanPanelSnapshot) -> None: panel_serial=snapshot.serial_number, window_duration_s=alert.window_duration_s, over_threshold_since=alert.over_threshold_since, + entity_id=self._resolve_circuit_entity_id(circuit_id), ) + def _display_name(self, point: MonitoredCircuit, snapshot: SpanPanelSnapshot) -> str: + """Name a point as Home Assistant shows it, for the text of the alert it raises. + + Each member's device as Home Assistant shows it (`util.circuit_display_name`), + joined as `MonitoredCircuit.name` joins the panel's names. Asked when an + alert fires rather than held, so a device renamed since setup is named + by its new name in the next alert. + """ + device_registry = dr.async_get(self._hass) + return " + ".join( + circuit_display_name( + device_registry, + snapshot.serial_number, + snapshot.circuits[member], + member, + config_entry_id=self._entry.entry_id, + ) + for member in point.members + ) + # --- Mains evaluation --- def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: @@ -819,7 +864,9 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: self._mains_overrides.get(leg, {}), self.get_global_settings() ) - leg_label = leg.replace("_", " ").title() + # The mains has no device of its own, so its text and its event both + # name the leg by its own name. + leg_name = f"Mains {leg.replace('_', ' ').title()}" alert = check_spike(state, current, rating, spike_pct, cooldown_m) if alert is not None: @@ -827,7 +874,8 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: self._hass, self.get_global_settings(), alert_type=alert.alert_type, - alert_name=f"Mains {leg_label}", + alert_name=leg_name, + display_name=leg_name, alert_id=leg, alert_source="mains", current_a=alert.current_a, @@ -840,6 +888,7 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: threshold_pct=alert.threshold_pct, utilization_pct=alert.utilization_pct, panel_serial=snapshot.serial_number, + entity_id=self._resolve_mains_entity_id(leg), ) alert = check_continuous(state, current, rating, cont_pct, window_m, cooldown_m) @@ -848,7 +897,8 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: self._hass, self.get_global_settings(), alert_type=alert.alert_type, - alert_name=f"Mains {leg_label}", + alert_name=leg_name, + display_name=leg_name, alert_id=leg, alert_source="mains", current_a=alert.current_a, @@ -863,17 +913,41 @@ def _evaluate_mains(self, snapshot: SpanPanelSnapshot) -> None: panel_serial=snapshot.serial_number, window_duration_s=alert.window_duration_s, over_threshold_since=alert.over_threshold_since, + entity_id=self._resolve_mains_entity_id(leg), ) - # Backward-compatible static alias kept for existing callers/tests. - _format_notification = staticmethod(format_notification) - def _store_for(hass: HomeAssistant, entry: ConfigEntry) -> Store[StoredMonitoring]: """Return the store holding one panel's monitoring settings.""" return Store(hass, _STORAGE_VERSION, f"{_STORAGE_KEY_PREFIX}.{entry.entry_id}") +async def async_adopt_legacy_enable_option(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Move an entry's legacy `enable_current_monitoring` option into the monitoring store, once. + + Monitoring is switched on and off in the store alone, which turning it off + writes; an option left in the entry turned it on again at every setup, so an + entry holding it could not stay off across a restart. Setup calls this + before it reads the store. Where the store already holds a flag, that flag + is the user's last word and the option carries nothing; otherwise an option + that is on is recorded as on, and one that is off needs no record, since a + store holding no flag is off. Either way the option leaves the entry, through + a write that asks for no reload, because this setup has already applied it. + """ + if _LEGACY_ENABLE_OPTION not in entry.options: + return + store = _store_for(hass, entry) + data = _read_stored(await store.async_load(), entry) or StoredMonitoring() + if "enabled" not in data and entry.options[_LEGACY_ENABLE_OPTION]: + data["enabled"] = True + await store.async_save(data) + async_update_entry_options_applied( + hass, + entry, + {key: value for key, value in entry.options.items() if key != _LEGACY_ENABLE_OPTION}, + ) + + async def async_forget_monitoring(hass: HomeAssistant, entry: ConfigEntry) -> None: """Drop the monitoring settings when the config entry is removed. diff --git a/custom_components/span_panel/entry_reloads.py b/custom_components/span_panel/entry_reloads.py index 597d67c7..e3f1320a 100644 --- a/custom_components/span_panel/entry_reloads.py +++ b/custom_components/span_panel/entry_reloads.py @@ -36,9 +36,9 @@ A preference or a discovery key written to the entry asks for nothing: Home Assistant reloads for the polling preference itself, and nothing here reads the others. A writer that applies its own change, as setup does when it pins a CA or -renames an entry titled with its serial, writes through -`async_update_entry_data_applied` or `async_update_entry_title_applied` and asks -for nothing either. +renames an entry titled with its serial, or removes the legacy monitoring option, +writes through `async_update_entry_data_applied`, `async_update_entry_title_applied` +or `async_update_entry_options_applied` and asks for nothing either. """ from __future__ import annotations @@ -197,6 +197,24 @@ def async_update_entry_title_applied(hass: HomeAssistant, entry: ConfigEntry, ti ) +@callback +def async_update_entry_options_applied( + hass: HomeAssistant, entry: ConfigEntry, options: Mapping[str, object] +) -> bool: + """Write the entry's options for a writer that applies them itself, asking for no reload. + + For setup's removal of the legacy `enable_current_monitoring` option, which + it has already carried into the monitoring store. Only the options are + written and recorded; see `_async_write_applied`. + """ + return _async_write_applied( + hass, + entry, + lambda applied: replace(applied, options=copy.deepcopy(dict(options))), + lambda: hass.config_entries.async_update_entry(entry, options=options), + ) + + @callback def _async_write_applied( hass: HomeAssistant, diff --git a/custom_components/span_panel/services.py b/custom_components/span_panel/services.py index a231f421..b4f8d4c0 100644 --- a/custom_components/span_panel/services.py +++ b/custom_components/span_panel/services.py @@ -309,28 +309,51 @@ def _service_name(call: ServiceCall) -> str: return f"{call.domain}.{call.service}" -def _raise_if_entitys_panel_not_loaded( - hass: HomeAssistant, target: str, panel_entry_id: str | None -) -> None: - """Refuse a threshold call whose entity's own panel is chosen but not loaded. +def _named_panel_entry_id(hass: HomeAssistant, call: ServiceCall) -> str | None: + """Return the config entry a monitoring call names, or None where it names none. - Said as that, rather than as monitoring being off, which nothing has read. A - loaded panel, no chosen panel, and a raw id, which belongs to no entity, are - all left to the caller's own refusal. + Refused where the id is no SPAN Panel's entry, whether no entry has it or + another integration's does: said as that, rather than as a panel that is + not loaded, which a caller waiting for it to load would wait on for good. """ - if panel_entry_id is None: - return - config_entry = hass.config_entries.async_get_entry(panel_entry_id) - if config_entry is not None and loaded_runtime_data(config_entry) is not None: - return - entity_entry = er.async_get(hass).async_get(target) - if entity_entry is not None and entity_entry.platform == DOMAIN: + entry_id: str | None = call.data.get("config_entry_id") + if entry_id is None: + return None + entry = hass.config_entries.async_get_entry(entry_id) + if entry is None or entry.domain != DOMAIN: raise ServiceValidationError( - f"The SPAN Panel that entity {target} belongs to is not loaded.", + f"No SPAN Panel has config entry {entry_id}.", translation_domain=DOMAIN, - translation_key="favorite_panel_not_loaded", - translation_placeholders={"entity_id": target}, + translation_key="monitoring_panel_unknown", + translation_placeholders={"config_entry_id": entry_id}, ) + return entry_id + + +def _loaded_monitoring_panel( + hass: HomeAssistant, config_entry_id: str | None +) -> tuple[SpanPanelRuntimeData, ConfigEntry]: + """Return the loaded panel a monitoring service acts on: the one chosen, else the first loaded. + + Every monitoring service, read or write, finds its panel here. One that is + not loaded is refused, in every state that keeps it so (setting up, + retrying, failed, disabled), and said as that, never as monitoring being + off, which nothing has read: a script asking while Home Assistant started + was told monitoring was off on a panel that had it on, and turning it off + was answered with success while the stored setting turned it on again once + the panel loaded. For a status read, the card waits for the entry to load on + this refusal, by its error code, translation domain and key; it waits on no + write's. + """ + for entry in hass.config_entries.async_loaded_entries(DOMAIN): + runtime_data = loaded_runtime_data(entry) + if runtime_data is not None and config_entry_id in (None, entry.entry_id): + return runtime_data, entry + raise ServiceValidationError( + "The SPAN Panel is not loaded, so its monitoring cannot be read or changed.", + translation_domain=DOMAIN, + translation_key="monitoring_panel_not_loaded", + ) def _threshold_panel_entry_id( @@ -387,25 +410,10 @@ def _async_register_monitoring_services(hass: HomeAssistant) -> None: """Register current monitoring services. Every service here but `get_monitoring_status` changes monitoring, so each - is registered through `_async_register_monitoring_write`. + is registered through `_async_register_monitoring_write`. Each finds its + panel through `_named_panel_entry_id` and `_loaded_monitoring_panel`. """ - def _get_runtime_data( - config_entry_id: str | None = None, - ) -> tuple[SpanPanelRuntimeData, ConfigEntry] | None: - """Find SPAN panel runtime data and entry. - - When config_entry_id is provided, returns that specific entry. - Otherwise falls back to the first loaded entry. - """ - for entry in hass.config_entries.async_loaded_entries(DOMAIN): - runtime_data = loaded_runtime_data(entry) - if runtime_data is None: - continue - if config_entry_id is None or entry.entry_id == config_entry_id: - return runtime_data, entry - return None - def _get_monitored( call: ServiceCall, target: str ) -> tuple[CurrentMonitor, SpanPanelRuntimeData]: @@ -416,32 +424,24 @@ def _get_monitored( live snapshot, as every service resolves its target, rather than the monitor's own, which is the last it judged or, before the first, the one it was built holding. - """ - panel_entry_id = _threshold_panel_entry_id(hass, target, call.data.get("config_entry_id")) - result = _get_runtime_data(panel_entry_id) - if result is not None: - runtime_data, _entry = result - if runtime_data.coordinator.current_monitor is not None: - return runtime_data.coordinator.current_monitor, runtime_data - _raise_if_entitys_panel_not_loaded(hass, target, panel_entry_id) - raise ServiceValidationError( - "No SPAN panel with current monitoring enabled.", - translation_domain=DOMAIN, - translation_key="monitoring_not_enabled", - ) - async def _get_or_create_monitor( - config_entry_id: str | None = None, - ) -> CurrentMonitor: - """Find or bootstrap a CurrentMonitor for the specified panel.""" - result = _get_runtime_data(config_entry_id) - if result is None: + `monitoring_not_enabled` is this refusal alone: the panel is loaded, and + its monitoring is off. + """ + panel_entry_id = _threshold_panel_entry_id(hass, target, _named_panel_entry_id(hass, call)) + runtime_data, _entry = _loaded_monitoring_panel(hass, panel_entry_id) + monitor = runtime_data.coordinator.current_monitor + if monitor is None: raise ServiceValidationError( - "No SPAN panel integration loaded.", + "Current monitoring is off on this SPAN Panel.", translation_domain=DOMAIN, translation_key="monitoring_not_enabled", ) - runtime_data, entry = result + return monitor, runtime_data + + async def _get_or_create_monitor(config_entry_id: str | None) -> CurrentMonitor: + """Find or bootstrap a CurrentMonitor for the specified panel.""" + runtime_data, entry = _loaded_monitoring_panel(hass, config_entry_id) if runtime_data.coordinator.current_monitor is not None: return runtime_data.coordinator.current_monitor monitor = CurrentMonitor( @@ -493,11 +493,7 @@ async def async_handle_clear_mains_threshold(call: ServiceCall) -> None: async def async_handle_get_monitoring_status( call: ServiceCall, ) -> ServiceResponse: - entry_id = call.data.get("config_entry_id") - result = _get_runtime_data(entry_id) - if result is None: - return {"enabled": False} - runtime_data, _entry = result + runtime_data, _entry = _loaded_monitoring_panel(hass, _named_panel_entry_id(hass, call)) monitor = runtime_data.coordinator.current_monitor if monitor is None: return {"enabled": False} @@ -545,18 +541,19 @@ async def async_handle_get_monitoring_status( async def async_handle_set_global_monitoring(call: ServiceCall) -> None: data = dict(call.data) enabled = data.pop("enabled", None) - entry_id = data.pop("config_entry_id", None) + data.pop("config_entry_id", None) + entry_id = _named_panel_entry_id(hass, call) if enabled is False: - # Disable monitoring: stop the monitor and mark storage as disabled - result = _get_runtime_data(entry_id) - if result is not None: - runtime_data, entry = result - monitor = runtime_data.coordinator.current_monitor - if monitor is not None: - monitor.async_stop() - await monitor.async_save_disabled() - runtime_data.coordinator.current_monitor = None + # Disable monitoring: stop the monitor and mark storage as disabled. + # Only a loaded panel's: one that is not loaded is refused, where a + # success would have left its stored setting to turn it on again. + runtime_data, _entry = _loaded_monitoring_panel(hass, entry_id) + monitor = runtime_data.coordinator.current_monitor + if monitor is not None: + monitor.async_stop() + await monitor.async_save_disabled() + runtime_data.coordinator.current_monitor = None return monitor = await _get_or_create_monitor(entry_id) @@ -580,8 +577,7 @@ async def async_handle_set_global_monitoring(call: ServiceCall) -> None: async def async_handle_test_notification(call: ServiceCall) -> None: from .alert_dispatcher import dispatch_test_alert # pylint: disable=import-outside-toplevel - entry_id = call.data.get("config_entry_id") - monitor = await _get_or_create_monitor(entry_id) + monitor = await _get_or_create_monitor(_named_panel_entry_id(hass, call)) settings = monitor.get_global_settings() dispatch_test_alert(hass, settings) @@ -609,21 +605,12 @@ def _get_runtime_data(call: ServiceCall, target: str) -> SpanPanelRuntimeData: The panel is `_threshold_panel_entry_id`'s choice, as for the threshold services: an entity belongs to one panel, and a raw circuit id goes to the - panel the call names, or else the first loaded. + panel the call names, or else the first loaded. Refused as every other + monitoring write is, by `_named_panel_entry_id` and `_loaded_monitoring_panel`. """ - panel_entry_id = _threshold_panel_entry_id(hass, target, call.data.get("config_entry_id")) - for entry in hass.config_entries.async_loaded_entries(DOMAIN): - runtime_data = loaded_runtime_data(entry) - if runtime_data is None: - continue - if panel_entry_id is None or entry.entry_id == panel_entry_id: - return runtime_data - _raise_if_entitys_panel_not_loaded(hass, target, panel_entry_id) - raise ServiceValidationError( - "No SPAN panel is loaded.", - translation_domain=DOMAIN, - translation_key="package_ratings_panel_not_loaded", - ) + panel_entry_id = _threshold_panel_entry_id(hass, target, _named_panel_entry_id(hass, call)) + runtime_data, _entry = _loaded_monitoring_panel(hass, panel_entry_id) + return runtime_data async def async_handle_set_circuit_package_ratings(call: ServiceCall) -> None: target = call.data["circuit_id"] diff --git a/custom_components/span_panel/strings.json b/custom_components/span_panel/strings.json index 7625542f..70d6a297 100644 --- a/custom_components/span_panel/strings.json +++ b/custom_components/span_panel/strings.json @@ -530,7 +530,13 @@ "message": "Entity {entity_id} belongs to a different SPAN Panel than config entry {config_entry_id}. Leave config_entry_id out, or name the entity's own panel." }, "monitoring_not_enabled": { - "message": "No SPAN panel with current monitoring enabled." + "message": "Current monitoring is off on this SPAN Panel. Turn it on before changing its thresholds." + }, + "monitoring_panel_not_loaded": { + "message": "The SPAN Panel is not loaded, so its current monitoring, and the ratings it judges against, cannot be read or changed." + }, + "monitoring_panel_unknown": { + "message": "No SPAN Panel has config entry {config_entry_id}, so there is no monitoring to read or change." }, "panel_auth_failed": { "message": "Authentication with the SPAN Panel failed. Please reauthenticate." @@ -612,9 +618,6 @@ }, "package_ratings_circuit_unknown": { "message": "This panel has no circuit with that id." - }, - "package_ratings_panel_not_loaded": { - "message": "No SPAN Panel is loaded, so no ratings can be copied or cleared." } }, "options": { diff --git a/custom_components/span_panel/translations/en.json b/custom_components/span_panel/translations/en.json index 7625542f..70d6a297 100644 --- a/custom_components/span_panel/translations/en.json +++ b/custom_components/span_panel/translations/en.json @@ -530,7 +530,13 @@ "message": "Entity {entity_id} belongs to a different SPAN Panel than config entry {config_entry_id}. Leave config_entry_id out, or name the entity's own panel." }, "monitoring_not_enabled": { - "message": "No SPAN panel with current monitoring enabled." + "message": "Current monitoring is off on this SPAN Panel. Turn it on before changing its thresholds." + }, + "monitoring_panel_not_loaded": { + "message": "The SPAN Panel is not loaded, so its current monitoring, and the ratings it judges against, cannot be read or changed." + }, + "monitoring_panel_unknown": { + "message": "No SPAN Panel has config entry {config_entry_id}, so there is no monitoring to read or change." }, "panel_auth_failed": { "message": "Authentication with the SPAN Panel failed. Please reauthenticate." @@ -612,9 +618,6 @@ }, "package_ratings_circuit_unknown": { "message": "This panel has no circuit with that id." - }, - "package_ratings_panel_not_loaded": { - "message": "No SPAN Panel is loaded, so no ratings can be copied or cleared." } }, "options": { diff --git a/custom_components/span_panel/translations/es.json b/custom_components/span_panel/translations/es.json index 433bf900..f9a5b97e 100644 --- a/custom_components/span_panel/translations/es.json +++ b/custom_components/span_panel/translations/es.json @@ -484,9 +484,6 @@ "package_ratings_circuit_unknown": { "message": "Este panel no tiene ningún circuito con ese identificador." }, - "package_ratings_panel_not_loaded": { - "message": "No hay ningún SPAN Panel cargado, por lo que no se pueden copiar ni borrar capacidades." - }, "circuit_priority_failed": { "message": "Se rechazó el cambio de prioridad para {circuit}: {reason}. No se envió nada al panel, por lo que la prioridad no ha cambiado." }, @@ -560,7 +557,13 @@ "message": "La entidad {entity_id} pertenece a un SPAN Panel distinto de la entrada de configuración {config_entry_id}. Omita config_entry_id o indique el panel propio de la entidad." }, "monitoring_not_enabled": { - "message": "Ningún SPAN Panel tiene el monitoreo de corriente habilitado." + "message": "El monitoreo de corriente está desactivado en este SPAN Panel. Actívelo antes de cambiar sus umbrales." + }, + "monitoring_panel_not_loaded": { + "message": "El SPAN Panel no está cargado, por lo que su monitoreo de corriente, y las capacidades con las que lo evalúa, no se pueden leer ni cambiar." + }, + "monitoring_panel_unknown": { + "message": "Ningún SPAN Panel tiene la entrada de configuración {config_entry_id}, por lo que no hay monitoreo que leer ni cambiar." }, "panel_auth_failed": { "message": "La autenticación con el SPAN Panel falló. Por favor vuelva a autenticarse." diff --git a/custom_components/span_panel/translations/fr.json b/custom_components/span_panel/translations/fr.json index 0f1a837b..0de5fbe9 100644 --- a/custom_components/span_panel/translations/fr.json +++ b/custom_components/span_panel/translations/fr.json @@ -484,9 +484,6 @@ "package_ratings_circuit_unknown": { "message": "Ce panneau n'a aucun circuit avec cet identifiant." }, - "package_ratings_panel_not_loaded": { - "message": "Aucun SPAN Panel n'est chargé ; aucun calibre ne peut donc être copié ni effacé." - }, "circuit_priority_failed": { "message": "Le changement de priorité pour {circuit} a été refusé : {reason}. Rien n'a été envoyé au panneau, la priorité est donc inchangée." }, @@ -560,7 +557,13 @@ "message": "L'entité {entity_id} appartient à un autre SPAN Panel que l'entrée de configuration {config_entry_id}. Omettez config_entry_id ou indiquez le panneau de l'entité." }, "monitoring_not_enabled": { - "message": "Aucun panneau SPAN n'a la surveillance de courant activée." + "message": "La surveillance du courant est désactivée sur ce SPAN Panel. Activez-la avant de modifier ses seuils." + }, + "monitoring_panel_not_loaded": { + "message": "Le SPAN Panel n'est pas chargé, sa surveillance du courant, et les calibres auxquels elle se compare, ne peuvent donc être ni lus ni modifiés." + }, + "monitoring_panel_unknown": { + "message": "Aucun SPAN Panel n'a l'entrée de configuration {config_entry_id} ; il n'y a donc aucune surveillance à lire ni à modifier." }, "panel_auth_failed": { "message": "L'authentification avec le SPAN Panel a échoué. Veuillez vous réauthentifier." diff --git a/custom_components/span_panel/translations/ja.json b/custom_components/span_panel/translations/ja.json index a6a210f5..a11b56a6 100644 --- a/custom_components/span_panel/translations/ja.json +++ b/custom_components/span_panel/translations/ja.json @@ -484,9 +484,6 @@ "package_ratings_circuit_unknown": { "message": "このパネルには、その ID の回路がありません。" }, - "package_ratings_panel_not_loaded": { - "message": "SPAN Panel が読み込まれていないため、定格をコピーすることもクリアすることもできません。" - }, "circuit_priority_failed": { "message": "{circuit}の優先度変更は拒否されました: {reason}。パネルには何も送信されていないため、優先度は変わっていません。" }, @@ -560,7 +557,13 @@ "message": "エンティティ {entity_id} は、設定エントリ {config_entry_id} とは別の SPAN Panel に属しています。config_entry_id を省略するか、エンティティ自身のパネルを指定してください。" }, "monitoring_not_enabled": { - "message": "電流監視が有効なSPANパネルがありません。" + "message": "この SPAN Panel では電流監視がオフになっています。しきい値を変更する前にオンにしてください。" + }, + "monitoring_panel_not_loaded": { + "message": "SPAN Panel が読み込まれていないため、電流監視とその判定に使う定格を読み取ることも変更することもできません。" + }, + "monitoring_panel_unknown": { + "message": "設定エントリ {config_entry_id} を持つ SPAN Panel がないため、読み取りや変更ができる監視はありません。" }, "panel_auth_failed": { "message": "SPAN Panelとの認証に失敗しました。再認証してください。" diff --git a/custom_components/span_panel/translations/pt.json b/custom_components/span_panel/translations/pt.json index 70f91148..f57efd21 100644 --- a/custom_components/span_panel/translations/pt.json +++ b/custom_components/span_panel/translations/pt.json @@ -484,9 +484,6 @@ "package_ratings_circuit_unknown": { "message": "Este painel não tem nenhum circuito com esse identificador." }, - "package_ratings_panel_not_loaded": { - "message": "Não há nenhum SPAN Panel carregado, por isso não é possível copiar nem limpar capacidades." - }, "circuit_priority_failed": { "message": "A alteração de prioridade para {circuit} foi recusada: {reason}. Nada foi enviado ao painel, portanto a prioridade permanece inalterada." }, @@ -560,7 +557,13 @@ "message": "A entidade {entity_id} pertence a um SPAN Panel diferente da entrada de configuração {config_entry_id}. Omita config_entry_id ou indique o painel da própria entidade." }, "monitoring_not_enabled": { - "message": "Nenhum painel SPAN com monitoramento de corrente ativado." + "message": "A monitorização de corrente está desativada neste SPAN Panel. Ative-a antes de alterar os seus limiares." + }, + "monitoring_panel_not_loaded": { + "message": "O SPAN Panel não está carregado, por isso a sua monitorização de corrente, e as capacidades com que a avalia, não podem ser lidas nem alteradas." + }, + "monitoring_panel_unknown": { + "message": "Nenhum SPAN Panel tem a entrada de configuração {config_entry_id}, por isso não há monitorização para ler nem alterar." }, "panel_auth_failed": { "message": "A autenticação com o SPAN Panel falhou. Por favor, reautentique." diff --git a/custom_components/span_panel/util.py b/custom_components/span_panel/util.py index 55dd7c4e..25416b27 100644 --- a/custom_components/span_panel/util.py +++ b/custom_components/span_panel/util.py @@ -597,3 +597,38 @@ def effective_circuit_device_name( if device is not None and device.name_by_user: return device.name_by_user return circuit_device_name(circuit, circuit_id) + + +def circuit_display_name( + device_registry: DeviceRegistry, + serial: str, + circuit: SpanCircuitSnapshot, + circuit_id: str, + *, + config_entry_id: str, +) -> str: + """Return a circuit's name as Home Assistant shows it, for text that names the circuit to a person. + + Its own device's name (`device_display_name`): the user's where they renamed + the device, else the name it is registered under. Read from the registry + each time it is asked, so a rename made since setup is the name the next + message carries. Unlike `effective_circuit_device_name`, a registered + device's `name` is read rather than the one it is about to be given: + between a rename on the panel and the reload that renames the device, Home + Assistant still shows the old one. + + A circuit with no device takes the name `circuit_device_info` would give it + (`circuit_device_name`). A charger's feed circuit has none where it has + neither a breaker switch nor a priority select, and on the first setup after + an upgrade from a release before circuits had devices, the monitor judges + pushes before they are registered. + + A circuit's device is always registered under a name, and Home Assistant + offers a user no way to clear it. + """ + device = circuit_device(device_registry, serial, circuit_id, config_entry_id=config_entry_id) + if device is None: + return circuit_device_name(circuit, circuit_id) + if not (name := device_display_name(device)): + raise RuntimeError(f"The device of circuit {circuit_id} has no name to show") + return name diff --git a/frontend.md b/frontend.md index a1a9ff88..c6620671 100644 --- a/frontend.md +++ b/frontend.md @@ -80,42 +80,43 @@ user. Any user can read monitoring's settings and status. - **Priority** — Notification priority level (controls iOS interruption level and Android notification channel) - **Title/Message Templates** — Customizable templates with the following variables: - | Variable | Description | Example | - | -------------------- | ---------------------------------------------------- | --------------------------- | - | `{name}` | The circuit's name in the SPAN app, or the mains leg | Kitchen Oven | - | `{entity_id}` | HA entity ID | sensor.kitchen_oven_current | - | `{alert_type}` | Alert category | spike, continuous_overload | - | `{current_a}` | Current draw in amps | 18.3 | - | `{breaker_rating_a}` | Rating in amps the circuit is judged against | 20 | - | `{threshold_pct}` | Configured threshold percentage | 80 | - | `{utilization_pct}` | Actual utilization percentage | 91.5 | - | `{window_m}` | Window duration in minutes | 5 | - | `{local_time}` | Local time of the alert | 2:15 PM | + | Variable | Description | Example | + | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | + | `{name}` | The circuit's name as Home Assistant shows it, the name you gave its device where you renamed it, or the mains leg; for circuits that share a meter, their names joined with " + " | Kitchen Oven | + | `{entity_id}` | The entity ID of the circuit's Current sensor, or its Power sensor where it has none; for circuits that share a meter, that of the circuit the event's `alert_id` names; for the mains, the leg's Current sensor | sensor.kitchen_oven_current | + | `{alert_type}` | Alert category | spike, continuous_overload | + | `{current_a}` | Current draw in amps | 18.3 | + | `{breaker_rating_a}` | Rating in amps the circuit is judged against | 20 | + | `{threshold_pct}` | Configured threshold percentage | 80 | + | `{utilization_pct}` | Actual utilization percentage | 91.5 | + | `{window_m}` | Window duration in minutes | 5 | + | `{local_time}` | Local time of the alert | 2:15 PM | `{breaker_rating_a}` keeps its name so existing templates still work, but it carries the rating the circuit is judged against: both breakers of a tandem whose ratings you copied from the SPAN app, else the breaker rating the panel publishes. - **Event bus** — With the HA event bus selected, each alert fires a `span_panel_current_alert` event for automations. Its data: - | Key | Description | - | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | - | `alert_source` | `circuit` or `mains` | - | `alert_id` | The circuit's id, or the mains leg (such as `upstream_l1`) | - | `alert_name` | The circuit's name in the SPAN app, or the mains leg | - | `alert_type` | `spike` or `continuous_overload` | - | `current_a` | Current draw in amps | - | `breaker_rating_a` | The breaker rating the panel publishes; for circuits that share a meter, the group's capacity over those ratings, and null if any has none | - | `monitoring_rating_a` | The rating the alert judged against: both breakers of a tandem whose ratings you copied from the SPAN app, else the panel's rating | - | `monitoring_rating_user_set` | Whether `monitoring_rating_a` comes from ratings you copied | - | `package_ratings_a` | The ratings you copied from the SPAN app, such as `[20, 30]`; null where there are none, and for a shared meter and the mains | - | `package_ratings_state` | `applies`, or `averaged_legs` where a copy across two spaces is kept but not applied; null where `package_ratings_a` is | - | `threshold_pct` | Configured threshold percentage | - | `utilization_pct` | Actual utilization percentage, against `monitoring_rating_a` | - | `panel_serial` | The panel's serial number | - | `local_time` | Local time of the alert | - | `window_duration_s` | Seconds spent over the continuous threshold (continuous overloads; the test event carries a sample) | - | `over_threshold_since` | When the circuit went over the continuous threshold, as an ISO 8601 time (continuous overloads only) | - | `test` | Present, and true, only on the event the test notification fires | + | Key | Description | + | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | + | `alert_source` | `circuit` or `mains` | + | `alert_id` | The circuit's id, or the mains leg (such as `upstream_l1`) | + | `alert_name` | The circuit's name in the SPAN app, or the mains leg; renaming the circuit's device in Home Assistant leaves it as it is | + | `alert_display_name` | The circuit's name as Home Assistant shows it, the name you gave its device where you renamed it, which the notification's `{name}` carries; for circuits that share a meter, their names joined with " + "; for the mains, the same as `alert_name` | + | `alert_type` | `spike` or `continuous_overload` | + | `current_a` | Current draw in amps | + | `breaker_rating_a` | The breaker rating the panel publishes; for circuits that share a meter, the group's capacity over those ratings, and null if any has none | + | `monitoring_rating_a` | The rating the alert judged against: both breakers of a tandem whose ratings you copied from the SPAN app, else the panel's rating | + | `monitoring_rating_user_set` | Whether `monitoring_rating_a` comes from ratings you copied | + | `package_ratings_a` | The ratings you copied from the SPAN app, such as `[20, 30]`; null where there are none, and for a shared meter and the mains | + | `package_ratings_state` | `applies`, or `averaged_legs` where a copy across two spaces is kept but not applied; null where `package_ratings_a` is | + | `threshold_pct` | Configured threshold percentage | + | `utilization_pct` | Actual utilization percentage, against `monitoring_rating_a` | + | `panel_serial` | The panel's serial number | + | `local_time` | Local time of the alert | + | `window_duration_s` | Seconds spent over the continuous threshold (continuous overloads; the test event carries a sample) | + | `over_threshold_since` | When the circuit went over the continuous threshold, as an ISO 8601 time (continuous overloads only) | + | `test` | Present, and true, only on the event the test notification fires | Copied ratings never change `breaker_rating_a`, which is the panel's rating, as the Breaker Rating sensor shows. The rating the `{breaker_rating_a}` text placeholder carries is `monitoring_rating_a` here. For the mains both are its rating, `monitoring_rating_user_set` is false and `package_ratings_a` and diff --git a/tests/replayed_panel.py b/tests/replayed_panel.py index a459f66b..f17847b0 100644 --- a/tests/replayed_panel.py +++ b/tests/replayed_panel.py @@ -28,8 +28,8 @@ CONF_EBUS_BROKER_PORT, CONF_EBUS_BROKER_USERNAME, DOMAIN, - ENABLE_CURRENT_MONITORING, ) +from custom_components.span_panel.current_monitor import StoredMonitoring, _store_for from custom_components.span_panel.id_builder import ( build_circuit_device_identifier, build_circuit_unique_id, @@ -45,12 +45,6 @@ PANEL_NAME: Final = "Span Panel" -MONITORED_OPTIONS: Final[Mapping[str, object]] = { - **FRESH_INSTALL_OPTIONS, - ENABLE_CURRENT_MONITORING: True, -} -"""A fresh install's options, with current monitoring switched on.""" - # --------------------------------------------------------------------------- # One panel, over the trees a test sets it up on @@ -64,7 +58,10 @@ class Panel: hass: HomeAssistant entry: MockConfigEntry tree: RetainedTree + monitored: bool = False + """Whether current monitoring was switched on before the first setup, as the store records it.""" clients: list[ReplayClient] = field(default_factory=list) + _seeded: bool = False def client(self) -> ReplayClient: """Build the client a setup connects with, over the tree served now.""" @@ -92,11 +89,25 @@ def serial(self) -> str: async def set_up(self, tree: RetainedTree) -> None: """Set the entry up over `tree`, then stream it once, as a live panel's first push.""" self.tree = tree + if self.monitored and not self._seeded: + await self._switch_monitoring_on() assert await self.hass.config_entries.async_setup(self.entry.entry_id) is True await self.hass.async_block_till_done() assert self.entry.state is ConfigEntryState.LOADED await self.push(tree) + async def _switch_monitoring_on(self) -> None: + """Record monitoring as on in the store, keeping whatever else a test seeded there. + + Once, before the first setup: a later setup reads whatever the test has + made of it since. + """ + store = _store_for(self.hass, self.entry) + stored = await store.async_load() or StoredMonitoring() + stored["enabled"] = True + await store.async_save(stored) + self._seeded = True + async def push(self, tree: RetainedTree) -> None: """Stream `tree` to the running session, as the panel publishing it does.""" await self.clients[-1].push(replay(tree)) @@ -158,7 +169,8 @@ def replayed_panels(hass: HomeAssistant) -> Iterator[Callable[..., Panel]]: def make( tree: RetainedTree, *, - options: Mapping[str, object] = MONITORED_OPTIONS, + options: Mapping[str, object] = FRESH_INSTALL_OPTIONS, + monitored: bool = True, entry_id: str = "entry-device-ids", ) -> Panel: serial = snapshot(tree).serial_number @@ -181,7 +193,7 @@ def make( minor_version=CURRENT_CONFIG_MINOR_VERSION, ) entry.add_to_hass(hass) - made[serial] = Panel(hass, entry, tree) + made[serial] = Panel(hass, entry, tree, monitored=monitored) return made[serial] def client_for(_host: str, serial: str, *_args: object, **_kwargs: object) -> ReplayClient: diff --git a/tests/test_alert_display_names.py b/tests/test_alert_display_names.py new file mode 100644 index 00000000..a1ab43d0 --- /dev/null +++ b/tests/test_alert_display_names.py @@ -0,0 +1,456 @@ +"""A current alert's text names the circuit as Home Assistant shows it; its event keeps the panel's name. + +A user who renames a circuit's device in Home Assistant finds it under that name +everywhere Home Assistant shows it, so a notification naming the circuit by the +panel's name names one they cannot find. The notification's title and message, +through `{name}`, carry the device's name as Home Assistant shows it +(`util.circuit_display_name`), read when the alert fires, so a rename made since +setup reaches the next alert. Their `{entity_id}` is the entity ID of the +point's Current sensor, as the documentation has always said. + +The `span_panel_current_alert` event is read by automations, so its +`alert_name` stays the panel's name and its `alert_id` the circuit's id, and +`alert_display_name` carries the name the text uses beside them. +""" + +from __future__ import annotations + +from dataclasses import replace +from datetime import UTC, datetime, timedelta +from typing import Final + +from homeassistant.core import Event, HomeAssistant, ServiceCall +from homeassistant.helpers import device_registry as dr, entity_registry as er +import pytest +from pytest_homeassistant.common import MockConfigEntry, async_capture_events, async_mock_service +from span_panel_api import FieldMetadata, SpanCircuitSnapshot, SpanPanelSnapshot + +from custom_components.span_panel.alert_dispatcher import dispatch_test_alert +from custom_components.span_panel.const import DOMAIN, EVENT_CURRENT_ALERT +from custom_components.span_panel.current_monitor import CurrentMonitor +from custom_components.span_panel.id_builder import build_circuit_unique_id, build_panel_unique_id +from custom_components.span_panel.options import ( + CONTINUOUS_THRESHOLD_PCT, + NOTIFICATION_MESSAGE_TEMPLATE, + NOTIFICATION_TITLE_TEMPLATE, + NOTIFY_TARGETS, + SPIKE_THRESHOLD_PCT, + WINDOW_DURATION_M, +) +from custom_components.span_panel.package_rating_manager import PackageRatingManager + +from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory +from .helpers import register_circuit_device, register_panel_device + +SERIAL: Final = "sp3-display-001" +_DECLARED: Final = {"panel.main_breaker_rating_a": FieldMetadata(unit="A", datatype="integer")} +_NOTIFY_SERVICE: Final = "synthetic_phone" +_TITLE: Final = "SPAN: {name} {alert_type}" +_MESSAGE: Final = "{name} at {current_a}A" + + +def _circuit( + circuit_id: str, + name: str, + tab: int, + *, + current_a: float = 25.0, + device_type: str = "circuit", +) -> SpanCircuitSnapshot: + """Return a 20 A circuit drawing `current_a`, over its rating by default, so it spikes.""" + return SpanCircuitSnapshotFactory.create( + circuit_id=circuit_id, + name=name, + tabs=[tab], + breaker_rating_a=20.0, + current_a=current_a, + device_type=device_type, + ) + + +def _panel(*circuits: SpanCircuitSnapshot) -> SpanPanelSnapshot: + """Return a panel whose mains draw too little to alert, so every alert is a circuit's.""" + return SpanPanelSnapshotFactory.create( + serial_number=SERIAL, + circuits={c.circuit_id: c for c in circuits}, + main_breaker_rating_a=200, + upstream_l1_current_a=1.0, + upstream_l2_current_a=1.0, + downstream_l1_current_a=1.0, + downstream_l2_current_a=1.0, + ) + + +class _Panel: + """One panel's entry, its registered panel device and its monitor.""" + + def __init__( + self, hass: HomeAssistant, entry: MockConfigEntry, monitor: CurrentMonitor + ) -> None: + self.hass = hass + self.entry = entry + self.monitor = monitor + self.panel_device_id = register_panel_device(hass, entry, SERIAL) + + def register(self, circuit: SpanCircuitSnapshot) -> dr.ChildDeviceEntry: + """Register the circuit's own device, as its first entity would.""" + return register_circuit_device( + self.hass, self.entry, SERIAL, circuit, panel_device_id=self.panel_device_id + ) + + def rename(self, device: dr.ChildDeviceEntry, name: str) -> None: + """Rename the device in Home Assistant, as a user does on its page.""" + dr.async_get(self.hass).async_update_child_device(device.id, name_by_user=name) + + def sensor(self, unique_id: str, object_id: str) -> str: + """Register one of the panel's sensors under `unique_id`, as its platform would, and return its entity ID.""" + return ( + er.async_get(self.hass) + .async_get_or_create( + "sensor", DOMAIN, unique_id, config_entry=self.entry, suggested_object_id=object_id + ) + .entity_id + ) + + +async def _set_up(hass: HomeAssistant, snapshot: SpanPanelSnapshot, **options: object) -> _Panel: + entry = MockConfigEntry( + domain=DOMAIN, + data={}, + unique_id=SERIAL, + options={ + SPIKE_THRESHOLD_PCT: 100, + NOTIFY_TARGETS: f"event_bus, notify.{_NOTIFY_SERVICE}", + NOTIFICATION_TITLE_TEMPLATE: _TITLE, + NOTIFICATION_MESSAGE_TEMPLATE: _MESSAGE, + **options, + }, + ) + entry.add_to_hass(hass) + manager = PackageRatingManager(hass, entry) + await manager.async_load() + manager.begin(snapshot, _DECLARED) + return _Panel(hass, entry, CurrentMonitor(hass, entry, manager, snapshot)) + + +async def _judge(panel: _Panel, snapshot: SpanPanelSnapshot) -> None: + panel.monitor.process_snapshot(snapshot) + await panel.hass.async_block_till_done() + + +def _texts(calls: list[ServiceCall]) -> list[tuple[object, object]]: + return [(call.data["title"], call.data["message"]) for call in calls] + + +def _names(events: list[Event]) -> list[tuple[object, object]]: + return [(event.data["alert_name"], event.data["alert_display_name"]) for event in events] + + +@pytest.fixture +def notified(hass: HomeAssistant) -> list[ServiceCall]: + """Every call to the notify target the panel's alerts are sent to.""" + return async_mock_service(hass, "notify", _NOTIFY_SERVICE) + + +@pytest.fixture +def alerts(hass: HomeAssistant) -> list[Event]: + """Every `span_panel_current_alert` event fired.""" + return async_capture_events(hass, EVENT_CURRENT_ALERT) + + +async def test_a_renamed_circuits_notification_carries_the_rename( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The title and message name the circuit by the user's name, and the event's `alert_name` stays the panel's.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + panel.rename(panel.register(circuit), "Synthetic Workshop") + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Synthetic Workshop spike", "Synthetic Workshop at 25.0A")] + assert _names(alerts) == [("Panel Name Seven", "Synthetic Workshop")] + + +async def test_a_rename_after_setup_reaches_the_next_alert( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The name is read when the alert fires, not when the monitor is built.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + device = panel.register(circuit) + await _judge(panel, snapshot) + + panel.rename(device, "Synthetic Workshop") + state = panel.monitor.get_circuit_state("circuit-7") + assert state is not None + # Past the cooldown, so the same spike alerts again. + state.last_spike_alert = datetime.now(UTC) - timedelta(hours=1) + await _judge(panel, snapshot) + + assert _texts(notified) == [ + ("SPAN: Panel Name Seven spike", "Panel Name Seven at 25.0A"), + ("SPAN: Synthetic Workshop spike", "Synthetic Workshop at 25.0A"), + ] + assert _names(alerts) == [ + ("Panel Name Seven", "Panel Name Seven"), + ("Panel Name Seven", "Synthetic Workshop"), + ] + + +async def test_an_unrenamed_circuit_is_named_as_before( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """A circuit nobody renamed is named by the panel's name, in its text and in both event fields.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + panel.register(circuit) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Panel Name Seven spike", "Panel Name Seven at 25.0A")] + assert _names(alerts) == [("Panel Name Seven", "Panel Name Seven")] + + +async def test_a_circuit_with_no_device_is_named_as_its_device_would_be( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """A circuit with no device takes the name `circuit_device_info` would give it (`circuit_device_name`). + + A charger's feed circuit has none where it has neither a breaker switch nor + a priority select, and on the first setup after an upgrade from a release + before circuits had devices, the monitor judges pushes before they are + registered. + """ + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Panel Name Seven spike", "Panel Name Seven at 25.0A")] + assert _names(alerts) == [("Panel Name Seven", "Panel Name Seven")] + + +async def test_a_shared_meter_is_named_by_each_members_name_as_home_assistant_shows_it( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """A shared meter's alert joins its members' names, each the user's where they renamed it. + + Two 20 A circuits at one space carry 40 A together, so both report 45 A. + """ + first = replace( + _circuit("circuit-52", "Panel Name A", 44, current_a=45.0), + meter_shared_with=("circuit-53",), + relay_shared_with=("circuit-53",), + ) + second = replace( + _circuit("circuit-53", "Panel Name B", 44, current_a=45.0), + meter_shared_with=("circuit-52",), + relay_shared_with=("circuit-52",), + ) + snapshot = replace(_panel(first, second), publishes_shared_meters=True) + panel = await _set_up(hass, snapshot) + panel.rename(panel.register(first), "Synthetic Fan") + panel.register(second) + + await _judge(panel, snapshot) + + assert _texts(notified) == [ + ("SPAN: Synthetic Fan + Panel Name B spike", "Synthetic Fan + Panel Name B at 45.0A") + ] + assert _names(alerts) == [("Panel Name A + Panel Name B", "Synthetic Fan + Panel Name B")] + + +async def test_the_mains_is_named_by_its_own_name( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The mains has no device of its own: its text and both event fields carry the leg's name.""" + snapshot = replace(_panel(), upstream_l1_current_a=250.0) + panel = await _set_up(hass, snapshot) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Mains Upstream L1 spike", "Mains Upstream L1 at 250.0A")] + assert _names(alerts) == [("Mains Upstream L1", "Mains Upstream L1")] + + +async def test_the_test_event_carries_the_display_name_too( + hass: HomeAssistant, alerts: list[Event] +) -> None: + """An automation written against the test event finds `alert_display_name` beside `alert_name`.""" + dispatch_test_alert(hass, {NOTIFY_TARGETS: "event_bus"}) + await hass.async_block_till_done() + + assert _names(alerts) == [("Kitchen Oven", "Kitchen Oven")] + + +async def test_an_unnamed_solar_circuit_with_no_device_is_named_solar( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """Its device would be named "Solar", so its text is, while `alert_name` keeps its positions. + + The name its device would be given, not the label a message used before: + once the device is registered, Home Assistant shows "Solar". + """ + circuit = _circuit("circuit-7", "", 7, device_type="pv") + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Solar spike", "Solar at 25.0A")] + assert _names(alerts) == [("Circuit 7", "Solar")] + + +async def test_a_continuous_overload_names_the_circuit_as_home_assistant_shows_it( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The sustained alert's text carries the rename, as the spike's does.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7, current_a=18.0) + snapshot = _panel(circuit) + panel = await _set_up( + hass, + snapshot, + **{SPIKE_THRESHOLD_PCT: 500, CONTINUOUS_THRESHOLD_PCT: 80, WINDOW_DURATION_M: 15}, + ) + panel.rename(panel.register(circuit), "Synthetic Workshop") + await _judge(panel, snapshot) + state = panel.monitor.get_circuit_state("circuit-7") + assert state is not None + # Over the threshold for longer than the window. + state.over_threshold_since = datetime.now(UTC) - timedelta(minutes=16) + + await _judge(panel, snapshot) + + assert _texts(notified) == [ + ("SPAN: Synthetic Workshop continuous_overload", "Synthetic Workshop at 18.0A") + ] + assert _names(alerts) == [("Panel Name Seven", "Synthetic Workshop")] + + +async def test_a_circuit_renamed_on_the_panel_keeps_the_name_home_assistant_shows_until_its_reload( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """Between a rename on the panel and the reload that renames its device, Home Assistant shows the old name. + + So the text carries the name the device is registered under, not the one it + is about to be given, which `effective_circuit_device_name` answers for an + entity id. The event's `alert_name` is the panel's, so it already carries the + new one. + """ + registered = _circuit("circuit-7", "Old Panel Name", 7) + snapshot = _panel(replace(registered, name="New Panel Name")) + panel = await _set_up(hass, snapshot) + panel.register(registered) + + await _judge(panel, snapshot) + + assert _texts(notified) == [("SPAN: Old Panel Name spike", "Old Panel Name at 25.0A")] + assert _names(alerts) == [("New Panel Name", "Old Panel Name")] + + +@pytest.mark.usefixtures("notified") +async def test_the_monitoring_status_keeps_the_panels_name_after_a_rename( + hass: HomeAssistant, +) -> None: + """Scripts read the status's `name`, so a rename in Home Assistant leaves it the panel's.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot) + panel.rename(panel.register(circuit), "Synthetic Workshop") + + await _judge(panel, snapshot) + + assert [c["name"] for c in panel.monitor.get_monitoring_status()["circuits"].values()] == [ + "Panel Name Seven" + ] + + +_ENTITY_TITLE: Final = {NOTIFICATION_TITLE_TEMPLATE: "{entity_id}"} + + +def _titles(calls: list[ServiceCall]) -> list[object]: + return [call.data["title"] for call in calls] + + +def _alert_ids(events: list[Event]) -> list[object]: + return [event.data["alert_id"] for event in events] + + +async def test_entity_id_is_the_circuits_current_sensor( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """`{entity_id}` carries the circuit's Current sensor, while the event's `alert_id` stays the circuit's id.""" + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot, **_ENTITY_TITLE) + panel.sensor(build_circuit_unique_id(SERIAL, "circuit-7", "instantPowerW"), "seven_power") + current = panel.sensor(build_circuit_unique_id(SERIAL, "circuit-7", "current"), "seven_current") + + await _judge(panel, snapshot) + + assert _titles(notified) == [current] + assert current == "sensor.seven_current" + assert _alert_ids(alerts) == ["circuit-7"] + + +async def test_entity_id_is_the_power_sensor_of_a_circuit_without_a_current_sensor( + hass: HomeAssistant, notified: list[ServiceCall] +) -> None: + """A circuit whose current arrived after setup has no Current sensor yet, so its Power sensor stands in. + + The Monitoring tab shows the circuit under the same entity. + """ + circuit = _circuit("circuit-7", "Panel Name Seven", 7) + snapshot = _panel(circuit) + panel = await _set_up(hass, snapshot, **_ENTITY_TITLE) + power = panel.sensor( + build_circuit_unique_id(SERIAL, "circuit-7", "instantPowerW"), "seven_power" + ) + + await _judge(panel, snapshot) + + assert _titles(notified) == [power] + + +async def test_entity_id_of_a_shared_meter_is_the_sensor_of_the_circuit_alert_id_names( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """A shared meter is judged under its first member's id, and `{entity_id}` is that member's sensor.""" + first = replace( + _circuit("circuit-52", "Panel Name A", 44, current_a=45.0), + meter_shared_with=("circuit-53",), + relay_shared_with=("circuit-53",), + ) + second = replace( + _circuit("circuit-53", "Panel Name B", 44, current_a=45.0), + meter_shared_with=("circuit-52",), + relay_shared_with=("circuit-52",), + ) + snapshot = replace(_panel(first, second), publishes_shared_meters=True) + panel = await _set_up(hass, snapshot, **_ENTITY_TITLE) + current = panel.sensor(build_circuit_unique_id(SERIAL, "circuit-52", "current"), "a_current") + panel.sensor(build_circuit_unique_id(SERIAL, "circuit-53", "current"), "b_current") + + await _judge(panel, snapshot) + + assert _titles(notified) == [current] + assert _alert_ids(alerts) == ["circuit-52"] + + +async def test_entity_id_of_the_mains_is_the_legs_current_sensor( + hass: HomeAssistant, notified: list[ServiceCall], alerts: list[Event] +) -> None: + """The mains leg's Current sensor, while the event's `alert_id` stays the leg.""" + snapshot = replace(_panel(), upstream_l1_current_a=250.0) + panel = await _set_up(hass, snapshot, **_ENTITY_TITLE) + leg = panel.sensor(build_panel_unique_id(SERIAL, "upstream_l1_current"), "upstream_l1_current") + + await _judge(panel, snapshot) + + assert _titles(notified) == [leg] + assert _alert_ids(alerts) == ["upstream_l1"] diff --git a/tests/test_current_monitor.py b/tests/test_current_monitor.py index c05812d0..b778c075 100644 --- a/tests/test_current_monitor.py +++ b/tests/test_current_monitor.py @@ -16,12 +16,13 @@ DEFAULT_SPIKE_THRESHOLD_PCT, DEFAULT_WINDOW_DURATION_M, DOMAIN, - ENABLE_CURRENT_MONITORING, EVENT_CURRENT_ALERT, ) from homeassistant.core import CoreState from homeassistant.exceptions import ServiceValidationError +from homeassistant.helpers import device_registry as dr +from custom_components.span_panel.alert_dispatcher import format_notification from custom_components.span_panel.package_rating_manager import PackageRatingManager from custom_components.span_panel.current_monitor import CurrentMonitor from custom_components.span_panel.curation import CurationOverlay @@ -47,7 +48,6 @@ def _make_options(**overrides): """Create options dict with monitoring enabled and defaults.""" opts = { - ENABLE_CURRENT_MONITORING: True, CONTINUOUS_THRESHOLD_PCT: DEFAULT_CONTINUOUS_THRESHOLD_PCT, SPIKE_THRESHOLD_PCT: DEFAULT_SPIKE_THRESHOLD_PCT, WINDOW_DURATION_M: DEFAULT_WINDOW_DURATION_M, @@ -106,6 +106,9 @@ def _make_hass(): hass.states = MagicMock() hass.states.get = MagicMock(return_value=None) hass.async_create_task = MagicMock(side_effect=_run_coro) + # Its device registry holds no device, as before a panel's entities register + # theirs, so an alert names each circuit by the name its device will be given. + dr.async_get(hass).async_get_child_device_by_identifier.return_value = None return hass @@ -664,8 +667,16 @@ def _panel_with_a_fresh_monitor( def _loaded(hass: MagicMock, *entries: MagicMock) -> None: - """Make these the loaded entries, in this order: the first is the old default panel.""" + """Make these the loaded entries, in this order: the first is the old default panel. + + They are the SPAN Panel entries Home Assistant holds too, so a call naming + one finds it, and a call naming any other id names no panel. + """ + for entry in entries: + entry.domain = DOMAIN + by_id = {entry.entry_id: entry for entry in entries} hass.config_entries.async_loaded_entries = MagicMock(return_value=list(entries)) + hass.config_entries.async_get_entry = MagicMock(side_effect=by_id.get) def _call(**data: Any) -> MagicMock: @@ -719,7 +730,10 @@ async def test_the_override_of_a_circuit_that_left_the_panel_is_cleared(self): assert "gone" not in monitor._circuit_overrides async def test_an_entity_whose_panel_is_not_loaded_says_so(self): - """Not that monitoring is off: nothing about monitoring was read.""" + """Not that monitoring is off: nothing about monitoring was read. + + Said as every monitoring service says it, which the card waits on. + """ hass = _make_hass() entry, _monitor, _snapshot = _panel_with_a_fresh_monitor(hass, "panel_a", "c-1") _loaded(hass, entry) @@ -731,8 +745,7 @@ async def test_an_entity_whose_panel_is_not_loaded_says_so(self): ): await handlers["clear_circuit_threshold"](_call(circuit_id="sensor.b_c_1_current")) - assert raised.value.translation_key == "favorite_panel_not_loaded" - assert raised.value.translation_placeholders == {"entity_id": "sensor.b_c_1_current"} + assert raised.value.translation_key == "monitoring_panel_not_loaded" def _drawing(current_a: float) -> SpanPanelSnapshot: @@ -1072,10 +1085,10 @@ def test_no_notifications_during_startup(self): def test_notification_message_format_spike(self): """Spike notification message includes current and rating.""" - title, message = CurrentMonitor._format_notification( + title, message = format_notification( alert_type="spike", - alert_name="Kitchen", - alert_id="sensor.kitchen_current", + display_name="Kitchen", + entity_id="sensor.kitchen_current", current_a=22.1, monitoring_rating_a=20.0, threshold_pct=100, @@ -1091,10 +1104,10 @@ def test_notification_message_format_spike(self): def test_notification_message_format_continuous(self): """Continuous notification message includes window duration.""" - title, message = CurrentMonitor._format_notification( + title, message = format_notification( alert_type="continuous_overload", - alert_name="Kitchen", - alert_id="sensor.kitchen_current", + display_name="Kitchen", + entity_id="sensor.kitchen_current", current_a=18.4, monitoring_rating_a=20.0, threshold_pct=80, @@ -1114,10 +1127,10 @@ def test_notification_message_format_continuous(self): def test_notification_custom_template_with_entity_id(self): """Custom templates produce expected output with entity_id placeholder.""" - title, message = CurrentMonitor._format_notification( + title, message = format_notification( alert_type="spike", - alert_name="Kitchen", - alert_id="sensor.kitchen_current", + display_name="Kitchen", + entity_id="sensor.kitchen_current", current_a=22.1, monitoring_rating_a=20.0, threshold_pct=100, @@ -1131,10 +1144,10 @@ def test_notification_custom_template_with_entity_id(self): def test_notification_invalid_template_falls_back(self): """Invalid template placeholders fall back to defaults.""" - title, message = CurrentMonitor._format_notification( + title, message = format_notification( alert_type="spike", - alert_name="Kitchen", - alert_id="sensor.kitchen_current", + display_name="Kitchen", + entity_id="sensor.kitchen_current", current_a=22.1, monitoring_rating_a=20.0, threshold_pct=100, diff --git a/tests/test_current_monitor_services.py b/tests/test_current_monitor_services.py index edf8833f..68c5b72f 100644 --- a/tests/test_current_monitor_services.py +++ b/tests/test_current_monitor_services.py @@ -2,23 +2,30 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import replace -from typing import Final -from unittest.mock import MagicMock +from typing import Any, Final +from unittest.mock import AsyncMock, MagicMock -from homeassistant.config_entries import ConfigEntryState +from homeassistant.config_entries import ConfigEntryDisabler, ConfigEntryState from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ServiceValidationError import probatio as vol import pytest from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.typing import WebSocketGenerator from span_panel_api import FieldMetadata, SpanPanelSnapshot from custom_components.span_panel.const import DOMAIN from custom_components.span_panel.curation import CurationOverlay from custom_components.span_panel.current_monitor import CurrentMonitor +from custom_components.span_panel.options import SPIKE_THRESHOLD_PCT from custom_components.span_panel.package_rating_manager import PackageRatingManager from custom_components.span_panel.runtime import SpanPanelRuntimeData -from custom_components.span_panel.services import _async_register_monitoring_services +from custom_components.span_panel.services import ( + _async_register_monitoring_services, + _async_register_package_rating_services, +) from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory, pv_binding_for from .helpers import register_panel_device @@ -82,8 +89,10 @@ def _rated_panel(*, publishes_shared_meters: bool | None) -> SpanPanelSnapshot: return replace(snapshot, publishes_shared_meters=publishes_shared_meters) -async def _monitoring_status(hass: HomeAssistant, snapshot: SpanPanelSnapshot) -> dict[str, object]: - """Answer `get_monitoring_status` for a panel set up on, and still holding, `snapshot`.""" +async def _load_panel( + hass: HomeAssistant, snapshot: SpanPanelSnapshot, *, monitored: bool = True +) -> MockConfigEntry: + """Return the entry of a panel set up on, and still holding, `snapshot`, with monitoring on or off.""" entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=snapshot.serial_number) entry.add_to_hass(hass) manager = PackageRatingManager(hass, entry) @@ -92,7 +101,11 @@ async def _monitoring_status(hass: HomeAssistant, snapshot: SpanPanelSnapshot) - coordinator = MagicMock() coordinator.data = snapshot coordinator.package_rating_manager = manager - coordinator.current_monitor = CurrentMonitor(hass, entry, manager, snapshot) + # Awaited when the harness unloads the entry at teardown. + coordinator.async_shutdown = AsyncMock() + coordinator.current_monitor = ( + CurrentMonitor(hass, entry, manager, snapshot) if monitored else None + ) entry.runtime_data = SpanPanelRuntimeData( coordinator=coordinator, panel_device_id=register_panel_device(hass, entry, snapshot.serial_number), @@ -101,15 +114,25 @@ async def _monitoring_status(hass: HomeAssistant, snapshot: SpanPanelSnapshot) - setup_snapshot=snapshot, ) entry.mock_state(hass, ConfigEntryState.LOADED) - _async_register_monitoring_services(hass) + return entry + +async def _ask_for_status(hass: HomeAssistant, **fields: str) -> dict[str, object]: + """Call `get_monitoring_status` with `fields` and return its answer.""" response = await hass.services.async_call( - DOMAIN, "get_monitoring_status", {}, blocking=True, return_response=True + DOMAIN, "get_monitoring_status", fields, blocking=True, return_response=True ) assert response is not None return dict(response) +async def _monitoring_status(hass: HomeAssistant, snapshot: SpanPanelSnapshot) -> dict[str, object]: + """Answer `get_monitoring_status` for a panel set up on, and still holding, `snapshot`.""" + await _load_panel(hass, snapshot) + _async_register_monitoring_services(hass) + return await _ask_for_status(hass) + + class TestMonitoringStatusSaysWhetherThePanelTakesCopies: """The status root says, as the topology root does, whether the panel takes copied package ratings.""" @@ -130,3 +153,307 @@ async def test_the_root_carries_monitoring_rating_offered( assert status["enabled"] is True assert status["monitoring_rating_offered"] is offered + + +def _unloaded_entry( + hass: HomeAssistant, state: ConfigEntryState, *, disabled: bool = False +) -> MockConfigEntry: + """Return a SPAN Panel entry Home Assistant holds in `state`, which is not loaded.""" + entry = MockConfigEntry( + domain=DOMAIN, + data={}, + unique_id="sp3-unloaded-001", + disabled_by=ConfigEntryDisabler.USER if disabled else None, + ) + entry.add_to_hass(hass) + entry.mock_state(hass, state) + return entry + + +def _another_integrations_entry(hass: HomeAssistant) -> MockConfigEntry: + """Return a loaded config entry that belongs to another integration.""" + entry = MockConfigEntry(domain="synthetic_other", data={}) + entry.add_to_hass(hass) + entry.mock_state(hass, ConfigEntryState.LOADED) + return entry + + +class TestMonitoringStatusRefusesAPanelThatIsNotLoaded: + """A panel that is not loaded is refused, never reported as having monitoring off. + + A script asking while Home Assistant starts, or while the integration retries + a panel it cannot reach, was told `{"enabled": False}` of a panel whose + monitoring is on. The card waits for the entry to load on exactly this + refusal: Core's `service_validation_error`, under this integration's + translation domain and the `monitoring_panel_not_loaded` key. + """ + + @pytest.mark.parametrize( + ("state", "disabled"), + [ + pytest.param(ConfigEntryState.NOT_LOADED, False, id="not loaded"), + pytest.param(ConfigEntryState.NOT_LOADED, True, id="disabled"), + pytest.param(ConfigEntryState.SETUP_IN_PROGRESS, False, id="setting up"), + pytest.param(ConfigEntryState.SETUP_RETRY, False, id="retrying setup"), + pytest.param(ConfigEntryState.SETUP_ERROR, False, id="setup failed"), + ], + ) + async def test_an_entry_that_is_not_loaded_is_refused( + self, hass: HomeAssistant, state: ConfigEntryState, disabled: bool + ) -> None: + """The entry the call names is refused while it is not loaded, whatever keeps it so.""" + entry = _unloaded_entry(hass, state, disabled=disabled) + _async_register_monitoring_services(hass) + + with pytest.raises(ServiceValidationError) as refused: + await _ask_for_status(hass, config_entry_id=entry.entry_id) + + assert (refused.value.translation_domain, refused.value.translation_key) == ( + DOMAIN, + "monitoring_panel_not_loaded", + ) + + async def test_an_entry_that_is_not_loaded_is_refused_while_another_panel_is_loaded( + self, hass: HomeAssistant + ) -> None: + """The panel the call names decides: another panel being loaded answers nothing for it.""" + await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + entry = _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _async_register_monitoring_services(hass) + + with pytest.raises(ServiceValidationError) as refused: + await _ask_for_status(hass, config_entry_id=entry.entry_id) + + assert refused.value.translation_key == "monitoring_panel_not_loaded" + + @pytest.mark.parametrize( + "configured", [False, True], ids=["no entry", "an entry retrying setup"] + ) + async def test_a_call_naming_no_entry_is_refused_while_no_panel_is_loaded( + self, hass: HomeAssistant, configured: bool + ) -> None: + """With no entry named and none loaded, there is no panel to answer for.""" + if configured: + _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _async_register_monitoring_services(hass) + + with pytest.raises(ServiceValidationError) as refused: + await _ask_for_status(hass) + + assert (refused.value.translation_domain, refused.value.translation_key) == ( + DOMAIN, + "monitoring_panel_not_loaded", + ) + + @pytest.mark.parametrize( + "named", ["no-such-entry", None], ids=["an id no entry has", "another integration's entry"] + ) + async def test_an_entry_id_that_is_no_panels_is_refused_as_unknown( + self, hass: HomeAssistant, named: str | None + ) -> None: + """An id that names no SPAN Panel's entry is refused as such, not as a panel still loading. + + A loaded panel is there too, so the refusal is about the id the call named. + """ + await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + entry_id = named if named is not None else _another_integrations_entry(hass).entry_id + _async_register_monitoring_services(hass) + + with pytest.raises(ServiceValidationError) as refused: + await _ask_for_status(hass, config_entry_id=entry_id) + + assert ( + refused.value.translation_domain, + refused.value.translation_key, + refused.value.translation_placeholders, + ) == (DOMAIN, "monitoring_panel_unknown", {"config_entry_id": entry_id}) + + async def test_a_loaded_panel_with_monitoring_off_still_says_so( + self, hass: HomeAssistant + ) -> None: + """Only a loaded panel can say its monitoring is off.""" + entry = await _load_panel(hass, _rated_panel(publishes_shared_meters=None), monitored=False) + _async_register_monitoring_services(hass) + + assert await _ask_for_status(hass, config_entry_id=entry.entry_id) == {"enabled": False} + assert await _ask_for_status(hass) == {"enabled": False} + + async def test_a_loaded_panel_with_monitoring_on_answers_its_status( + self, hass: HomeAssistant + ) -> None: + """A loaded, monitored panel answers its status, named or not.""" + entry = await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + _async_register_monitoring_services(hass) + + for status in ( + await _ask_for_status(hass, config_entry_id=entry.entry_id), + await _ask_for_status(hass), + ): + assert status["enabled"] is True + circuits = status["circuits"] + assert isinstance(circuits, dict) + assert [c["name"] for c in circuits.values() if isinstance(c, dict)] == [ + "Synthetic Circuit" + ] + + async def test_the_card_reads_the_refusal_over_the_websocket( + self, hass: HomeAssistant, hass_ws_client: WebSocketGenerator + ) -> None: + """The refusal reaches a WebSocket caller as the contract the card waits on.""" + entry = _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _async_register_monitoring_services(hass) + client = await hass_ws_client(hass) + + await client.send_json_auto_id( + { + "type": "call_service", + "domain": DOMAIN, + "service": "get_monitoring_status", + "service_data": {"config_entry_id": entry.entry_id}, + "return_response": True, + } + ) + reply = await client.receive_json() + + assert reply["success"] is False + error = reply["error"] + assert (error["code"], error["translation_domain"], error["translation_key"]) == ( + "service_validation_error", + "span_panel", + "monitoring_panel_not_loaded", + ) + + +_WRITES: Final[list[Any]] = [ + pytest.param("set_global_monitoring", {"enabled": True}, id="turn monitoring on"), + pytest.param("set_global_monitoring", {"enabled": False}, id="turn monitoring off"), + pytest.param("set_global_monitoring", {SPIKE_THRESHOLD_PCT: 90}, id="change settings"), + pytest.param("test_notification", {}, id="test notification"), + pytest.param( + "set_circuit_threshold", + {"circuit_id": "circuit-5", SPIKE_THRESHOLD_PCT: 90}, + id="set circuit", + ), + pytest.param("clear_circuit_threshold", {"circuit_id": "circuit-5"}, id="clear circuit"), + pytest.param( + "set_mains_threshold", {"leg": "upstream_l1", SPIKE_THRESHOLD_PCT: 90}, id="set mains" + ), + pytest.param("clear_mains_threshold", {"leg": "upstream_l1"}, id="clear mains"), + pytest.param( + "set_circuit_package_ratings", + {"circuit_id": "circuit-5", "package_ratings_a": [20, 30]}, + id="copy ratings", + ), + pytest.param("clear_circuit_package_ratings", {"circuit_id": "circuit-5"}, id="clear ratings"), +] +"""Every monitoring write, with data its schema accepts, naming a raw circuit id or leg.""" + + +def _register_every_monitoring_service(hass: HomeAssistant) -> None: + _async_register_monitoring_services(hass) + _async_register_package_rating_services(hass) + + +async def _refusal( + hass: HomeAssistant, service: str, data: Mapping[str, object] +) -> ServiceValidationError: + """Call `service` with `data` and return the refusal it must raise.""" + with pytest.raises(ServiceValidationError) as refused: + await hass.services.async_call(DOMAIN, service, dict(data), blocking=True) + return refused.value + + +class TestMonitoringWritesRefuseAPanelThatIsNotLoaded: + """A monitoring write says the panel is not loaded, or is no panel, never that monitoring is off. + + `monitoring_not_enabled` is left to a loaded panel whose monitoring is off, so + a caller can tell a panel still loading from one it has to turn monitoring on + for. + """ + + @pytest.mark.parametrize(("service", "data"), _WRITES) + async def test_a_write_to_a_panel_that_is_not_loaded_is_refused( + self, hass: HomeAssistant, service: str, data: Mapping[str, object] + ) -> None: + """The panel the call names decides, though another panel is loaded with monitoring on.""" + await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + entry = _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _register_every_monitoring_service(hass) + + refusal = await _refusal(hass, service, {**data, "config_entry_id": entry.entry_id}) + + assert (refusal.translation_domain, refusal.translation_key) == ( + DOMAIN, + "monitoring_panel_not_loaded", + ) + + @pytest.mark.parametrize(("service", "data"), _WRITES) + async def test_a_write_with_no_panel_loaded_is_refused( + self, hass: HomeAssistant, service: str, data: Mapping[str, object] + ) -> None: + """With no entry named and none loaded, there is no panel to change.""" + _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + _register_every_monitoring_service(hass) + + refusal = await _refusal(hass, service, data) + + assert refusal.translation_key == "monitoring_panel_not_loaded" + + @pytest.mark.parametrize(("service", "data"), _WRITES) + async def test_a_write_naming_an_entry_that_is_no_panels_is_refused_as_unknown( + self, hass: HomeAssistant, service: str, data: Mapping[str, object] + ) -> None: + """An id no SPAN Panel's entry has is refused as such, though a panel is loaded.""" + await _load_panel(hass, _rated_panel(publishes_shared_meters=None)) + _register_every_monitoring_service(hass) + + refusal = await _refusal(hass, service, {**data, "config_entry_id": "no-such-entry"}) + + assert (refusal.translation_key, refusal.translation_placeholders) == ( + "monitoring_panel_unknown", + {"config_entry_id": "no-such-entry"}, + ) + + async def test_turning_monitoring_off_on_a_panel_that_is_not_loaded_leaves_it_on( + self, hass: HomeAssistant, hass_storage: dict[str, Any] + ) -> None: + """Refused rather than answered with success, since nothing is turned off. + + The panel's stored monitoring is still on, so it monitors once it loads, + which a success would have told the caller it would not. + """ + entry = _unloaded_entry(hass, ConfigEntryState.SETUP_RETRY) + hass_storage[f"span_panel_current_monitor.{entry.entry_id}"] = { + "version": 1, + "minor_version": 1, + "key": f"span_panel_current_monitor.{entry.entry_id}", + "data": {"enabled": True}, + } + _register_every_monitoring_service(hass) + + refusal = await _refusal( + hass, "set_global_monitoring", {"enabled": False, "config_entry_id": entry.entry_id} + ) + + assert refusal.translation_key == "monitoring_panel_not_loaded" + assert await CurrentMonitor.async_is_enabled(hass, entry) is True + + @pytest.mark.parametrize( + ("service", "data"), + [ + ("set_circuit_threshold", {"circuit_id": "circuit-5", SPIKE_THRESHOLD_PCT: 90}), + ("clear_circuit_threshold", {"circuit_id": "circuit-5"}), + ("set_mains_threshold", {"leg": "upstream_l1", SPIKE_THRESHOLD_PCT: 90}), + ("clear_mains_threshold", {"leg": "upstream_l1"}), + ], + ) + async def test_a_threshold_on_a_loaded_panel_with_monitoring_off_says_monitoring_is_off( + self, hass: HomeAssistant, service: str, data: Mapping[str, object] + ) -> None: + """The one refusal that says monitoring is off: the panel is loaded, and its monitoring is.""" + entry = await _load_panel(hass, _rated_panel(publishes_shared_meters=None), monitored=False) + _register_every_monitoring_service(hass) + + refusal = await _refusal(hass, service, {**data, "config_entry_id": entry.entry_id}) + + assert refusal.translation_key == "monitoring_not_enabled" diff --git a/tests/test_current_monitor_setup.py b/tests/test_current_monitor_setup.py index 251aa6ba..7d397ae1 100644 --- a/tests/test_current_monitor_setup.py +++ b/tests/test_current_monitor_setup.py @@ -33,13 +33,17 @@ from custom_components.span_panel.options import NOTIFY_TARGETS from .captures_replay import ReplayClient, RetainedTree, capture, snapshot -from .replayed_panel import MONITORED_OPTIONS, Panel, replayed_panels +from .replayed_panel import Panel, replayed_panels +from .test_expected_entities import FRESH_INSTALL_OPTIONS _NOTIFY_SERVICE: Final = "synthetic_phone" """A notify service standing in for a user's phone.""" -_OPTIONS: Final = {**MONITORED_OPTIONS, NOTIFY_TARGETS: f"event_bus, notify.{_NOTIFY_SERVICE}"} -"""Monitoring on, alerting through both channels: the event bus and a notify service.""" +_OPTIONS: Final = {**FRESH_INSTALL_OPTIONS, NOTIFY_TARGETS: f"event_bus, notify.{_NOTIFY_SERVICE}"} +"""Alerting through both channels: the event bus and a notify service.""" + +_LEGACY_OPTION: Final = "enable_current_monitoring" +"""The option a release before the monitoring store switched monitoring on by, as entries still hold it.""" _BETWEEN: Final = timedelta(seconds=30) """Time let pass after the monitor is built, and again before the first push.""" @@ -217,3 +221,92 @@ async def live_until_built(client: ReplayClient) -> SpanPanelSnapshot: assert [(event.data["alert_id"], event.data["alert_type"]) for event in alerts] == [ (circuit_id, "spike") ] + + +# --------------------------------------------------------------------------- +# The legacy `enable_current_monitoring` option +# --------------------------------------------------------------------------- + + +async def _stored_monitoring(hass: HomeAssistant, panel: Panel) -> bool: + return await CurrentMonitor.async_is_enabled(hass, panel.entry) + + +async def test_an_entry_with_the_legacy_option_and_no_stored_flag_starts_monitoring_and_loses_the_option( + hass: HomeAssistant, panels: Callable[..., Panel] +) -> None: + """The option is moved into the store once, at setup, and asks for no reload in leaving the options.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, _LEGACY_OPTION: True}, monitored=False) + + await panel.set_up(tree) + runtime = panel.runtime + await hass.async_block_till_done() + + assert panel.runtime is runtime + assert runtime.coordinator.current_monitor is not None + assert _LEGACY_OPTION not in panel.entry.options + assert dict(panel.entry.options) == dict(FRESH_INSTALL_OPTIONS) + assert await _stored_monitoring(hass, panel) is True + + +async def test_an_entry_with_the_legacy_option_off_stays_off_and_loses_the_option( + hass: HomeAssistant, panels: Callable[..., Panel] +) -> None: + """An option that is off needs no record: a store holding no flag is off.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, _LEGACY_OPTION: False}, monitored=False) + + await panel.set_up(tree) + + assert panel.runtime.coordinator.current_monitor is None + assert dict(panel.entry.options) == dict(FRESH_INSTALL_OPTIONS) + assert await _stored_monitoring(hass, panel) is False + + +async def test_monitoring_turned_off_stays_off_across_a_restart_on_an_entry_that_held_the_option( + hass: HomeAssistant, panels: Callable[..., Panel] +) -> None: + """Turning monitoring off writes only the store, so the option must not turn it on again.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, _LEGACY_OPTION: True}, monitored=False) + await panel.set_up(tree) + + await panel.call("set_global_monitoring", enabled=False) + await panel.restart_on(tree) + + assert panel.runtime.coordinator.current_monitor is None + assert await _stored_monitoring(hass, panel) is False + + +async def test_a_stored_off_wins_over_the_legacy_option( + hass: HomeAssistant, panels: Callable[..., Panel], hass_storage: dict[str, object] +) -> None: + """Where the store already holds a flag, the option carries nothing over, and still leaves the options.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, _LEGACY_OPTION: True}, monitored=False) + key = f"span_panel_current_monitor.{panel.entry.entry_id}" + hass_storage[key] = {"version": 1, "minor_version": 1, "key": key, "data": {"enabled": False}} + + await panel.set_up(tree) + assert panel.runtime.coordinator.current_monitor is None + await panel.restart_on(tree) + + assert panel.runtime.coordinator.current_monitor is None + assert _LEGACY_OPTION not in panel.entry.options + assert await _stored_monitoring(hass, panel) is False + + +@pytest.mark.parametrize("monitored", [True, False], ids=["monitoring on", "monitoring off"]) +async def test_an_entry_without_the_legacy_option_is_unchanged( + hass: HomeAssistant, panels: Callable[..., Panel], monitored: bool +) -> None: + """Its options are left as they are, and monitoring follows the store alone.""" + tree, _circuit_id, _rating = _overloaded() + panel = panels(tree, options=FRESH_INSTALL_OPTIONS, monitored=monitored) + + await panel.set_up(tree) + + assert dict(panel.entry.options) == dict(FRESH_INSTALL_OPTIONS) + assert (panel.runtime.coordinator.current_monitor is not None) is monitored + assert await _stored_monitoring(hass, panel) is monitored diff --git a/tests/test_device_id_migration.py b/tests/test_device_id_migration.py index e8792e07..5a6d8e66 100644 --- a/tests/test_device_id_migration.py +++ b/tests/test_device_id_migration.py @@ -86,7 +86,8 @@ without_topics, ) from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory -from .replayed_panel import MONITORED_OPTIONS, PANEL_NAME, Panel, replayed_panels +from .replayed_panel import PANEL_NAME, Panel, replayed_panels +from .test_expected_entities import FRESH_INSTALL_OPTIONS BEFORE: Final = "r202639-e" AFTER: Final = "r202645-e" @@ -415,7 +416,7 @@ async def install_and_update( panels: Callable[..., Panel], hass_storage: dict[str, object], *, - options: Mapping[str, object] = MONITORED_OPTIONS, + options: Mapping[str, object] = FRESH_INSTALL_OPTIONS, serial: str | None = None, ) -> tuple[Panel, Registered, str]: """Install on r202639-e with every setting the panel can hold, then restart on r202645-e.""" @@ -484,9 +485,11 @@ def with_first_letters_upper_cased(serial: str) -> str: @pytest.mark.parametrize( ("options", "serial"), [ - pytest.param(MONITORED_OPTIONS, None, id="circuit-names"), - pytest.param({**MONITORED_OPTIONS, USE_CIRCUIT_NUMBERS: True}, None, id="circuit-numbers"), - pytest.param(MONITORED_OPTIONS, MIXED_CASE_SERIAL, id="a-mixed-case-serial"), + pytest.param(FRESH_INSTALL_OPTIONS, None, id="circuit-names"), + pytest.param( + {**FRESH_INSTALL_OPTIONS, USE_CIRCUIT_NUMBERS: True}, None, id="circuit-numbers" + ), + pytest.param(FRESH_INSTALL_OPTIONS, MIXED_CASE_SERIAL, id="a-mixed-case-serial"), ], ) async def test_an_install_keeps_everything_across_the_update( diff --git a/tests/test_package_rating_services.py b/tests/test_package_rating_services.py index a7594d2d..81c36271 100644 --- a/tests/test_package_rating_services.py +++ b/tests/test_package_rating_services.py @@ -360,21 +360,21 @@ async def test_an_entity_whose_panel_is_not_loaded_says_so(self, hass: HomeAssis with pytest.raises(ServiceValidationError) as raised: await _set(hass, circuit_id=entity_id, package_ratings_a=[20, 30]) - assert raised.value.translation_key == "favorite_panel_not_loaded" + assert raised.value.translation_key == "monitoring_panel_not_loaded" assert entry_a.state is ConfigEntryState.LOADED @pytest.mark.parametrize("service", ["set", "clear"]) async def test_with_no_panel_loaded_the_call_says_so( self, hass: HomeAssistant, service: str ) -> None: - """With no panel loaded either call says so, with the one message that fits both.""" + """With no panel loaded either call says so, as every monitoring service does.""" with pytest.raises(ServiceValidationError) as raised: if service == "set": await _set(hass, circuit_id="circuit-2", package_ratings_a=[20, 30]) else: await _clear(hass, circuit_id="circuit-2") - assert raised.value.translation_key == "package_ratings_panel_not_loaded" + assert raised.value.translation_key == "monitoring_panel_not_loaded" def _panel_of(*circuit_ids: str) -> SpanPanelSnapshot: diff --git a/tests/test_package_ratings.py b/tests/test_package_ratings.py index e50b5b70..00383c4b 100644 --- a/tests/test_package_ratings.py +++ b/tests/test_package_ratings.py @@ -548,5 +548,4 @@ def test_every_reason_the_rule_removes_an_entry_for_is_a_refusal_for_entered_rat def test_every_refusal_has_its_own_message_and_every_message_a_refusal() -> None: strings = json.loads((Path(__file__).parent.parent / "custom_components/span_panel/strings.json").read_text(encoding="utf-8")) keys = {key for key in strings["exceptions"] if key.startswith("package_ratings_")} - # Raised by the services, before any rule is asked: no panel to judge by. - assert keys - {"package_ratings_panel_not_loaded"} == {f"package_ratings_{reason}" for reason in get_args(Refusal.__value__)} + assert keys == {f"package_ratings_{reason}" for reason in get_args(Refusal.__value__)} diff --git a/tests/test_remote_ct_inverter_naming.py b/tests/test_remote_ct_inverter_naming.py index 6ca8147b..c85116d6 100644 --- a/tests/test_remote_ct_inverter_naming.py +++ b/tests/test_remote_ct_inverter_naming.py @@ -33,7 +33,8 @@ from custom_components.span_panel.util import pv_inverter_device_identifier from .captures_replay import RetainedTree, capture, panel_device_id, snapshot -from .replayed_panel import MONITORED_OPTIONS, Panel, replayed_panels +from .replayed_panel import Panel, replayed_panels +from .test_expected_entities import FRESH_INSTALL_OPTIONS TREE: Final = "r202645-a" DONOR: Final = "main32_r202639-upstream-pv" @@ -167,7 +168,7 @@ async def test_an_inverter_a_remote_ct_feeds_is_named_by_its_label( remote CT does not have. """ tree, remote = derived_tree() - panel = panels(tree, options={**MONITORED_OPTIONS, USE_CIRCUIT_NUMBERS: numbers}) + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, USE_CIRCUIT_NUMBERS: numbers}) await panel.set_up(tree) card, rows = card_and_rows(panel, remote) @@ -222,7 +223,7 @@ async def test_an_install_the_earlier_naming_built_keeps_its_entity_ids( the wire id. """ tree, remote = derived_tree(name) - panel = panels(tree, options={**MONITORED_OPTIONS, USE_CIRCUIT_NUMBERS: numbers}) + panel = panels(tree, options={**FRESH_INSTALL_OPTIONS, USE_CIRCUIT_NUMBERS: numbers}) with patch("custom_components.span_panel.helpers.resolve_pv_display_suffix", _earlier_suffix): await panel.set_up(tree) card, rows = card_and_rows(panel, remote) From 22e7dbce14ffc245331a8e3988f0ddb7bcf5eb9c Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:33:51 -0800 Subject: [PATCH 2/2] build: bundle span-card v0.12.1-beta.3 The release build of span-card v0.12.1-beta.3 (8151fac), which handles the monitoring_panel_not_loaded refusal; span-panel-card.js is byte-identical to the release asset. --- .../frontend/dist/span-panel-card.js | 32 +++++++-------- .../span_panel/frontend/dist/span-panel.js | 39 +++++++------------ 2 files changed, 31 insertions(+), 40 deletions(-) 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 46454b6f..32e76a09 100644 --- a/custom_components/span_panel/frontend/dist/span-panel-card.js +++ b/custom_components/span_panel/frontend/dist/span-panel-card.js @@ -1,4 +1,4 @@ -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; +let t="en";const e={en:{"tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","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.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...","card.setup_failed":"SPAN Panel could not be set up. Check Settings → Devices & services.","card.panel_disabled":"This SPAN Panel is disabled. Enable it in Settings → Devices & services.","card.restart_needed":"SPAN Panel could not be loaded. Restart Home Assistant to try again.","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}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","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","panel.no_panels":"No SPAN Panel found. Add one in Settings → Devices & services.","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.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.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","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.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...","card.setup_failed":"No se pudo configurar el SPAN Panel. Revise Ajustes → Dispositivos y servicios.","card.panel_disabled":"Este SPAN Panel está deshabilitado. Habilítelo en Ajustes → Dispositivos y servicios.","card.restart_needed":"No se pudo cargar el SPAN Panel. Reinicie Home Assistant para volver a intentarlo.","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}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN 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","panel.no_panels":"No se encontró ningún SPAN Panel. Agregue uno en Ajustes → Dispositivos y servicios.","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.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.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","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.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...","card.setup_failed":"Le SPAN Panel n'a pas pu être configuré. Consultez Paramètres → Appareils et services.","card.panel_disabled":"Ce SPAN Panel est désactivé. Activez-le dans Paramètres → Appareils et services.","card.restart_needed":"Le SPAN Panel n'a pas pu être chargé. Redémarrez Home Assistant pour réessayer.","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}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","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","panel.no_panels":"Aucun SPAN Panel trouvé. Ajoutez-en un dans Paramètres → Appareils et services.","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.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.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","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.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パネルの読み込みを待機中...","card.setup_failed":"SPANパネルをセットアップできませんでした。設定 → デバイスとサービス を確認してください。","card.panel_disabled":"このSPANパネルは無効になっています。設定 → デバイスとサービス で有効にしてください。","card.restart_needed":"SPANパネルを読み込めませんでした。Home Assistant を再起動してもう一度お試しください。","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","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":"お気に入り","panel.no_panels":"SPANパネルが見つかりません。設定 → デバイスとサービス で追加してください。","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","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.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","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.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...","card.setup_failed":"Não foi possível configurar o SPAN Panel. Verifique Configurações → Dispositivos e serviços.","card.panel_disabled":"Este SPAN Panel está desativado. Ative-o em Configurações → Dispositivos e serviços.","card.restart_needed":"Não foi possível carregar o SPAN Panel. Reinicie o Home Assistant para tentar novamente.","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}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","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","panel.no_panels":"Nenhum SPAN Panel encontrado. Adicione um em Configurações → Dispositivos e serviços.","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.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 @@ -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 Ft="span_panel_list_columns";function $t(){try{const t=localStorage.getItem(Ft);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function Vt(t){try{localStorage.setItem(Ft,String(t))}catch{}}const Wt={"&":"&","<":"<",">":">",'"':""","'":"'"};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;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){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}const Ue=new Set(["not_loaded","unknown_command"]);function Ge(t){return!!qe(t)||"object"==typeof t&&null!==t&&("code"in t&&Ue.has(t.code)||function(t){return"code"in t&&"service_validation_error"===t.code&&"translation_domain"in t&&t.translation_domain===l&&"translation_key"in t&&"monitoring_panel_not_loaded"===t.translation_key}(t))}const Xe=new Set(["migration_error","failed_unload"]);const Ye={waiting:()=>({text:i("card.waiting_for_load"),role:"status",color:"var(--secondary-text-color)"}),setup_failed:()=>({text:i("card.setup_failed"),role:"alert",color:"var(--error-color)"}),restart_needed:()=>({text:i("card.restart_needed"),role:"alert",color:"var(--error-color)"}),disabled:()=>({text:i("card.panel_disabled"),role:"alert",color:"var(--error-color)"})};function Ze(t){return new Promise(e=>setTimeout(e,t))}class Ke{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=await this._retry.callWS(t,o,{errorId:"fetch:monitoring",errorMessage:i("error.monitoring_failed")}),s=Qe(a?.response);return r===this._generation&&(this._status=s,this._lastFetch=Date.now(),this._awaitingLoad=!1),s}catch(t){const e=Ge(t);return r===this._generation&&(this._status=null,this._awaitingLoad=e),e||console.warn("SPAN Panel: monitoring status fetch failed",t),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._awaitingLoad=!1,this._generation++}}class tn{constructor(t){this._errorStore=t,this._caches=new Map}awaitingLoad(t){return!0===this._caches.get(t)?.awaitingLoad}async fetchOne(t,e){let n=this._caches.get(e);return n||(n=new Je(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 en(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 nn(t){return{continuousPct:t?.continuous_threshold_pct??80,spikePct:t?.spike_threshold_pct??100}}function rn(t,e){const{continuousPct:n,spikePct:i}=nn(e);return t>=i?"alert":t>=n?"warning":"normal"}function on(t,e){return`utilization-${rn(t,e)}`}function an(t){return(void 0===t.monitoring_rating_a?t.breaker_rating_a:t.monitoring_rating_a)??null}function sn(t){return null!=t&&!1!==t.monitoring_enabled}function ln(t,e){return sn(e)?an(t):t.breaker_rating_a??null}const cn=["continuous_threshold_pct","spike_threshold_pct"];function un(t,e){return sn(e)?function(t,e){return"averaged_legs"===t?.package_ratings_state&&sn(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)&&cn.some(t=>(e[t]??0)>100)?!0===e.has_override?"own":"global":null}(t,e):null}function dn(t){return t.packageRatings?.length&&t.panelAmps?r("monitoringRating.copied",{package:t.packageRatings.join("-"),panel:String(t.panelAmps)}):i("monitoringRating.copied_unnamed")}function hn(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 pn(t,e){return Ie(t)||Sn(t,e)}function fn(t,e){const n=t.entities?.power;return qt(n?e.states[n]:void 0)}function gn(t,e){const n=t.entities?.current;return qt(n?e.states[n]:void 0)}function mn(t){return t.is_generation??"pv"===t.device_type}function vn(t,e){return mn(t)||null!==e&&e<0}function yn(t,e,n){const i=gn(t,e);if(t.entities?.current&&null===i)return null;const r=n?.utilization_pct??null,o=ln(t,n);return null===r&&null!==i&&o?Math.round(Math.abs(i)/o*1e3)/10:r}const _n=new Set(x),bn={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function xn(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function wn(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 Sn(t,e){const n=xn(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(wn(t,e,"relay_state")??t.relay_state)}function Cn(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=xn(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function kn(t){return void 0===t?void 0:bn[t]}function Mn(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function Tn(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=Mn(t,e);return void 0!==n&&_n.has(n)?n:kn(wn(t,e,"shed_priority"))??kn(t.priority)??"unknown"}function An(t,e){return _e(t)||(e?i("grid.shared_switch"):"")}function In(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=An(n,r);return`
\n ${i(t?"grid.on":"grid.off")}\n \n
`}function Dn(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=An(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 Pn(t){return"unknown"===t?void 0:b[t]}const Ln="display:none;";function En(t){const e=Pn(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 Nn(t,e){const n=t.querySelector(".shedding-composite");if(!n)return;const i=Pn(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 Rn(t,e,n,r,o,a,s,l,c,u,d=[e],h=!1){const p=fn(e,a),f=vn(e,p),g=Sn(e,a),m=Cn(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(gn(e,a)):Jt(p),x=En(c||"unknown"),w=``;let S="";const C=yn(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 ${In(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 On(t,e){return`\n
\n —\n
\n `}function zn(t){return"function"==typeof globalThis.CSS?.escape?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function Hn(t){return Object.entries(t.circuits).filter(([,t])=>Ie(t))}function Bn(t,e){return!1!==e.show_panel&&Hn(t).length>0}function Fn(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 $n(t,e,n){const r=fn(t,e),o=null===r||0===r?"":i(r>0?"meters.importing":"meters.exporting");return`\n ${"current"===Re(n).entityRole?te(gn(t,e)):Jt(r)}\n ${jt(o)}\n ${Fn(e,t.entities?.consumed_energy,i("meters.imported"))}\n ${Fn(e,t.entities?.produced_energy,i("meters.exported"))}\n `}const Vn={names:["power","battery power"],suffixes:["_power"]},Wn={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},jn={names:["state of energy"],suffixes:["_soe_kwh"]};function qn(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 Un(t){return qn(t,Wn)}function Gn(t){return qn(t,jn)}function Xn(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,qn(n,Vn)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function Yn(t){const{headlineEid:e,siteTotalEid:n}=Xn(t),i=[e,n];return t.type===f&&i.push(Un(t),Gn(t)),new Set(i.filter(t=>null!==t))}function Zn(t){const e=[{role:"power",entityId:Xn(t).headlineEid}];return t.type===f&&e.push({role:"soc",entityId:Un(t)},{role:"soe",entityId:Gn(t)}),e.filter(t=>null!==t.entityId)}function Kn(t,e){return qt(t.states[e])}function Qn(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 Jn(t,e){return Zn(t).length>0||e&&null!==Qn(t.entities)}function ti(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 ei(t,e){return void 0!==t.config_entry_id&&e.has(t.config_entry_id)&&!t.via_device_id&&!t.parent_device_id}function ni(t){return(t.name_by_user||t.name||"").trim()}function ii(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=ti(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=Xn(i),o=i.type===f,a=o?Un(i):null,s=o?Gn(i):null,l=si(i,e,n,Yn(i)),u=li(t,i,o,r.headlineEid,a,s),d=i.solar?oi(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=ri(n),p=o.headlineIsSiteTotal?`${jt(i("subdevice.site_total"))}`:"",m=o.headlineEid?`${p}${Qt(Kn(e,o.headlineEid))}`:"",v=Jn(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 ri(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 oi(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=Kn(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 ai(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&&ni(r)||e}function si(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||ai(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 li(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 ci(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 ui(t){const e=s[t];return e?e.ms:s[a].ms}function di(t){const e=t/1e3;return e<=600?Math.ceil(e):Math.min(5e3,Math.ceil(e/5))}function hi(t){return Math.max(500,Math.floor(t/5e3))}function pi(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 fi(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 gi(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 mi(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 vi(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=di(i),l=hi(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,fi(n,s,l))}}}function yi(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 Zn(i))e.push({entityId:r,key:`${v}${n}_${t}`,devId:n});return e}async function _i(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)?ui(r.get(t)):ci(n),gi(a,o,e,t)}for(const{entityId:t,key:i,devId:r}of yi(e)){let e;e=o&&o.has(r)?ui(o.get(r)):ci(n),gi(a,e,t,i)}const s=[];for(const[e,n]of a){if(0===n.entityIds.length)continue;e>2592e5?s.push(mi(t,n.entityIds,n.keysByEntity,e,i)):s.push(vi(t,n.entityIds,n.keysByEntity,e,i))}await Promise.all(s)}var bi=function(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1},xi=new function(){this.browser=new bi,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?(xi.wxa=!0,xi.touchEventsSupported=!0):"undefined"==typeof document&&"undefined"!=typeof self?xi.worker=!0:!xi.hasGlobalWindow||"Deno"in window||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Node.js")>-1?(xi.node=!0,xi.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,xi);var wi="sans-serif",Si="12px "+wi;var Ci,ki,Mi=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(){Yi(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?Xr(s,a):Xr(a,s))}(a,o,r);if(s)return s(t,n,i),!0}return!1}function Qr(t){return"CANVAS"===t.nodeName.toUpperCase()}var Jr=/([&<>"'])/g,to={"&":"&","<":"<",">":">",'"':""","'":"'"};function eo(t){return null==t?"":(t+"").replace(Jr,function(t,e){return to[e]})}var no=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,io=[],ro=xi.browser.firefox&&+xi.browser.version.split(".")[0]<39;function oo(t,e,n,i){return n=n||{},i?ao(t,e,n):ro&&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):ao(t,e,n),n}function ao(t,e,n){if(xi.domSupported&&t.getBoundingClientRect){var i=e.clientX,r=e.clientY;if(Qr(t)){var o=t.getBoundingClientRect();return n.zrX=i-o.left,void(n.zrY=r-o.top)}if(Kr(io,t,i,r))return n.zrX=io[0],void(n.zrY=io[1])}n.zrX=n.zrY=0}function so(t){return t||window.event}function lo(t,e,n){if(null!=(e=so(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&&oo(t,r,e,n)}else{oo(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&&no.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function co(t,e,n,i){t.removeEventListener(e,n,i)}var uo=function(t){t.preventDefault(),t.stopPropagation(),t.cancelBubble=!0},ho=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=po(r)/po(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 go(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function mo(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 vo(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 yo(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 _o(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 bo(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 xo=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}(),wo=Math.min,So=Math.max,Co=Math.abs,ko=["x","y"],Mo=["width","height"],To=new xo,Ao=new xo,Io=new xo,Do=new xo,Po=Bo(),Lo=Po.minTv,Eo=Po.maxTv,No=[0,0],Ro=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=wo(t.x,this.x),n=wo(t.y,this.y);isFinite(this.x)&&isFinite(this.width)?this.width=So(t.x+t.width,this.x+this.width)-e:this.width=t.width,isFinite(this.y)&&isFinite(this.height)?this.height=So(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 yo(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]),yo(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&&xo.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(Oo,e.x,e.y,e.width,e.height)),n instanceof t||(n=t.set(zo,n.x,n.y,n.width,n.height));var s=!!i;Po.reset(r,s);var l=Po.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))}To.x=Io.x=n.x,To.y=Do.y=n.y,Ao.x=Do.x=n.x+n.width,Ao.y=Io.y=n.y+n.height,To.transform(i),Do.transform(i),Ao.transform(i),Io.transform(i),e.x=wo(To.x,Ao.x,Io.x,Do.x),e.y=wo(To.y,Ao.y,Io.y,Do.y);var l=So(To.x,Ao.x,Io.x,Do.x),c=So(To.y,Ao.y,Io.y,Do.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Oo=new Ro(0,0,0,0),zo=new Ro(0,0,0,0);function Ho(t,e,n,i,r,o,a,s){var l=Co(e-n),c=Co(i-t),u=wo(l,c),d=ko[r],h=ko[1-r],p=Mo[r];e=c||!Po.bidirectional)&&(Lo[d]=-c,Lo[h]=0,Po.useDir&&Po.calcDirMTV())))}function Bo(){var t=0,e=new xo,n=new xo,i={minTv:new xo,maxTv:new xo,useDir:!1,dirMinTv:new xo,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(r,o){i.touchThreshold=0,r&&null!=r.touchThreshold&&(i.touchThreshold=So(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||(qo.copy(u.getBoundingRect()),u.transform&&qo.applyTransform(u.transform),qo.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=Go(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==Fo)){e.target=a;break}}}function Yo(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}Yi(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){Uo.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=Yo(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||Hr(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function Zo(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 Ko(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 Qo(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 Jo(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 ta(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=Jo(t[u],t,l,c,0,e);l+=h,0!==(c-=h)&&0!==(d=Qo(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-Qo(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=Zo(t,n,i,e))s&&(l=s),Ko(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 na=!1;function ia(){na||(na=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function ra(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var oa,aa=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=ra}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}();oa=xi.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){return setTimeout(t,16)};var sa={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-sa.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*sa.bounceIn(2*t):.5*sa.bounceOut(2*t-1)+.5}},la=Math.pow,ca=Math.sqrt,ua=1e-8,da=1e-4,ha=ca(3),pa=1/3,fa=Pr(),ga=Pr(),ma=Pr();function va(t){return t>-1e-8&&tua||t<-1e-8}function _a(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 ba(t,e,n,i,r){var o=1-r;return 3*(((e-t)*o+2*(n-e)*r)*o+(i-n)*r*r)}function xa(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(va(u)&&va(d)){if(va(s))o[0]=0;else(C=-l/s)>=0&&C<=1&&(o[p++]=C)}else{var f=d*d-4*u*h;if(va(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=ca(f),y=u*s+1.5*a*(-d+v),_=u*s+1.5*a*(-d-v);(C=(-s-((y=y<0?-la(-y,pa):la(y,pa))+(_=_<0?-la(-_,pa):la(_,pa))))/(3*a))>=0&&C<=1&&(o[p++]=C)}else{var b=(2*u*s-3*a*d)/(2*ca(u*u*u)),x=Math.acos(b)/3,w=ca(u),S=Math.cos(x),C=(-s-2*w*S)/(3*a),k=(m=(-s+w*(S+ha*Math.sin(x)))/(3*a),(-s+w*(S-ha*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 wa(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(va(a)){if(ya(o))(u=-s/o)>=0&&u<=1&&(r[l++]=u)}else{var c=o*o-4*a*s;if(va(c))r[0]=-o/(2*a);else if(c>0){var u,d=ca(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 Sa(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 Ca(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=_a(t,n,r,a,f),m=_a(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 ka(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function Ma(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function Ta(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function Aa(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 Ia(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=ka(t,n,r,h),f=ka(e,i,o,h),g=p-s,m=f-l;c+=Math.sqrt(g*g+m*m),s=p,l=f}return c}var Da=/cubic-bezier\(([0-9,\.e ]+)\)/;function Pa(t){var e=t&&Da.exec(t);if(e){var n=e[1].split(","),i=+_r(n[0]),r=+_r(n[1]),o=+_r(n[2]),a=+_r(n[3]);if(isNaN(i+r+o+a))return;var s=[];return function(t){return t<=0?0:t>=1?1:xa(0,i,o,1,t,s)&&_a(0,r,a,1,s[0])}}}var La=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||Ir,this.ondestroy=t.ondestroy||Ir,this.onrestart=t.onrestart||Ir,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=ir(t)?t:sa[t]||Pa(t)},t}(),Ea=function(t){this.value=t},Na=function(){function t(){this._len=0}return t.prototype.insert=function(t){var e=new Ea(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}(),Ra=function(){function t(t){this._list=new Na,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 Ea(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}(),Oa={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 za(t){return(t=Math.round(t))<0?0:t>255?255:t}function Ha(t){return t<0?0:t>1?1:t}function Ba(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?za(parseFloat(e)/100*255):za(parseInt(e,10))}function Fa(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Ha(parseFloat(e)/100):Ha(parseFloat(e))}function $a(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 Va(t,e,n){return t+(e-t)*n}function Wa(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function ja(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}var qa=new Ra(20),Ua=null;function Ga(t,e){Ua&&ja(Ua,e),Ua=qa.put(t,Ua||e.slice())}function Xa(t,e){if(t){e=e||[];var n=qa.get(t);if(n)return ja(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in Oa)return ja(e,Oa[i]),Ga(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?(Wa(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),Ga(t,e),e):void Wa(e,0,0,0,1):7===o||9===o?(r=parseInt(i.slice(1,7),16))>=0&&r<=16777215?(Wa(e,(16711680&r)>>16,(65280&r)>>8,255&r,9===o?parseInt(i.slice(7),16)/255:1),Ga(t,e),e):void Wa(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?Wa(e,+c[0],+c[1],+c[2],1):Wa(e,0,0,0,1);u=Fa(c.pop());case"rgb":return c.length>=3?(Wa(e,Ba(c[0]),Ba(c[1]),Ba(c[2]),3===c.length?u:Fa(c[3])),Ga(t,e),e):void Wa(e,0,0,0,1);case"hsla":return 4!==c.length?void Wa(e,0,0,0,1):(c[3]=Fa(c[3]),Ya(c,e),Ga(t,e),e);case"hsl":return 3!==c.length?void Wa(e,0,0,0,1):(Ya(c,e),Ga(t,e),e);default:return}}Wa(e,0,0,0,1)}}function Ya(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=Fa(t[1]),r=Fa(t[2]),o=r<=.5?r*(i+1):r+i-r*i,a=2*r-o;return Wa(e=e||[],za(255*$a(a,o,n+1/3)),za(255*$a(a,o,n)),za(255*$a(a,o,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function Za(t,e){var n=Xa(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 Qa(n,4===n.length?"rgba":"rgb")}}function Ka(t,e,n,i){var r=Xa(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]=Fa(ir(n)?n(r[1]):n)),null!=i&&(r[2]=Fa(ir(i)?i(r[2]):i)),Qa(Ya(r),"rgba")}function Qa(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 Ja(t,e){var n=Xa(t);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*e:0}var ts=new Ra(100);function es(t){if(rr(t)){var e=ts.get(t);return e||(e=Za(t,-.1),ts.put(t,e)),e}if(dr(t)){var n=ji({},t);return n.colorStops=Zi(t.colorStops,function(t){return{offset:t.offset,color:Za(t.color,-.1)}}),n}return t}var ns=Math.round;function is(t){var e;if(t&&"transparent"!==t){if("string"==typeof t&&t.indexOf("rgba")>-1){var n=Xa(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 rs=1e-4;function os(t){return t-1e-4}function as(t){return ns(1e3*t)/1e3}function ss(t){return ns(1e4*t)/1e4}var ls={left:"start",right:"end",center:"middle",middle:"middle"};function cs(t){return t&&!!t.image}function us(t){return cs(t)||function(t){return t&&!!t.svgElement}(t)}function ds(t){return"linear"===t.type}function hs(t){return"radial"===t.type}function ps(t){return t&&("linear"===t.type||"radial"===t.type)}function fs(t){return"url(#"+t+")"}function gs(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 ms(t){var e=t.x||0,n=t.y||0,i=(t.rotation||0)*Dr,r=fr(t.scaleX,1),o=fr(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("+ns(a*Dr)+"deg, "+ns(s*Dr)+"deg)"),l.join(" ")}var vs=xi.hasGlobalWindow&&ir(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},ys=Array.prototype.slice;function _s(t,e,n){return(e-t)*n+t}function bs(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(Xi(e)){var l=function(t){return Xi(t&&t[0])?2:1}(e);a=l,(1===l&&!ar(e[0])||2===l&&!ar(e[0][0]))&&(o=!0)}else if(ar(e)&&!hr(e))a=0;else if(rr(e))if(isNaN(+e)){var c=Xa(e);c&&(s=c,a=3)}else a=0;else if(dr(e)){var u=ji({},s);u.colorStops=Zi(e.colorStops,function(t){return{offset:t.offset,color:Xa(t.color)}}),ds(e)?a=4:hs(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=ir(n)?n:sa[n]||Pa(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=As(i),l=Ts(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?Is:t[u];if(!As(s)&&!d||m||(m=this._additiveValue=[]),this.discrete)t[u]=g<1?i.rawValue:r.rawValue;else if(As(s))1===s?bs(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,ks(l),i),this._trackKeys.push(a)}s.addKeyframe(t,ks(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 Ls(){return(new Date).getTime()}var Es,Ns,Rs=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=Ls()-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,oa(function e(){t._running&&(oa(e),!t._paused&&t.update())})},e.prototype.start=function(){this._running||(this._time=Ls(),this._pausedTime=0,this._startLoop())},e.prototype.stop=function(){this._running=!1},e.prototype.pause=function(){this._paused||(this._pauseStart=Ls(),this._paused=!0)},e.prototype.resume=function(){this._paused&&(this._pausedTime+=Ls()-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 Ps(t,e.loop);return this.addAnimator(n),n},e}(qr),Os=xi.domSupported,zs=(Ns={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},{mouse:Es=["click","dblclick","mousewheel","wheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],touch:["touchstart","touchend","touchmove"],pointer:Zi(Es,function(t){var e=t.replace("mouse","pointer");return Ns.hasOwnProperty(e)?e:t})}),Hs=["mousemove","mouseup"],Bs=["pointermove","pointerup"],Fs=!1;function $s(t){var e=t.pointerType;return"pen"===e||"touch"===e}function Vs(t){t&&(t.zrByTouch=!0)}function Ws(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 js=function(t,e){this.stopPropagation=Ir,this.stopImmediatePropagation=Ir,this.preventDefault=Ir,this.type=e.type,this.target=this.currentTarget=t.dom,this.pointerType=e.pointerType,this.clientX=e.clientX,this.clientY=e.clientY},qs={mousedown:function(t){t=lo(this.dom,t),this.__mayPointerCapture=[t.zrX,t.zrY],this.trigger("mousedown",t)},mousemove:function(t){t=lo(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=lo(this.dom,t),this.__togglePointerCapture(!1),this.trigger("mouseup",t)},mouseout:function(t){Ws(this,(t=lo(this.dom,t)).toElement||t.relatedTarget)||(this.__pointerCapturing&&(t.zrEventControl="no_globalout"),this.trigger("mouseout",t))},wheel:function(t){Fs=!0,t=lo(this.dom,t),this.trigger("mousewheel",t)},mousewheel:function(t){Fs||(t=lo(this.dom,t),this.trigger("mousewheel",t))},touchstart:function(t){Vs(t=lo(this.dom,t)),this.__lastTouchMoment=new Date,this.handler.processGesture(t,"start"),qs.mousemove.call(this,t),qs.mousedown.call(this,t)},touchmove:function(t){Vs(t=lo(this.dom,t)),this.handler.processGesture(t,"change"),qs.mousemove.call(this,t)},touchend:function(t){Vs(t=lo(this.dom,t)),this.handler.processGesture(t,"end"),qs.mouseup.call(this,t),+new Date-+this.__lastTouchMoment<300&&qs.click.call(this,t)},pointerdown:function(t){qs.mousedown.call(this,t)},pointermove:function(t){$s(t)||qs.mousemove.call(this,t)},pointerup:function(t){qs.mouseup.call(this,t)},pointerout:function(t){$s(t)||qs.mouseout.call(this,t)}};Yi(["click","dblclick","contextmenu"],function(t){qs[t]=function(e){e=lo(this.dom,e),this.trigger(t,e)}});var Us={pointermove:function(t){$s(t)||Us.mousemove.call(this,t)},pointerup:function(t){Us.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 Gs(t,e){var n=e.domHandlers;xi.pointerEventsSupported?Yi(zs.pointer,function(i){Ys(e,i,function(e){n[i].call(t,e)})}):(xi.touchEventsSupported&&Yi(zs.touch,function(i){Ys(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)})}),Yi(zs.mouse,function(i){Ys(e,i,function(r){r=so(r),e.touching||n[i].call(t,r)})}))}function Xs(t,e){function n(n){Ys(e,n,function(i){i=so(i),Ws(t,i.target)||(i=function(t,e){return lo(t.dom,new js(t,e),!0)}(t,i),e.domHandlers[n].call(t,i))},{capture:!0})}xi.pointerEventsSupported?Yi(Bs,n):xi.touchEventsSupported||Yi(Hs,n)}function Ys(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 Zs(t){var e=t.mounted;for(var n in e)e.hasOwnProperty(n)&&co(t.domTarget,n,e[n],t.listenerOpts[n]);t.mounted={}}var Ks=function(t,e){this.mounted={},this.listenerOpts={},this.touching=!1,this.domTarget=t,this.domHandlers=e},Qs=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 Ks(e,qs),Os&&(i._globalHandlerScope=new Ks(document,Us)),Gs(i,i._localHandlerScope),i}return S(e,t),e.prototype.dispose=function(){Zs(this._localHandlerScope),Os&&Zs(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,Os&&+this.__pointerCapturing^+t){this.__pointerCapturing=t;var e=this._globalHandlerScope;t?Xs(this,e):Zs(e)}},e}(qr),Js=1;xi.hasGlobalWindow&&(Js=Math.max(window.devicePixelRatio||window.screen&&window.screen.deviceXDPI/window.screen.logicalXDPI||1,1));var tl=Js,el="#333",nl="#ccc",il=go,rl=5e-5;function ol(t){return t>rl||t<-5e-5}var al,sl=[],ll=[],cl=[1,0,0,1,0,0],ul=Math.abs,dl=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 ol(this.rotation)||ol(this.x)||ol(this.y)||ol(this.scaleX-1)||ol(this.scaleY-1)||ol(this.skewX)||ol(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):il(n),t&&(e?vo(n,t,n):mo(n,t)),this.transform=n,this._resolveGlobalScaleRatio(n)):n&&(il(n),this.invTransform=null)},t.prototype._resolveGlobalScaleRatio=function(t){var e=this.globalScaleRatio;if(null!=e&&1!==e){this.getGlobalScale(sl);var n=sl[0]<0?-1:1,i=sl[1]<0?-1:1,r=((sl[0]-n)*e+n)/sl[0]||0,o=((sl[1]-i)*e+i)/sl[1]||0;t[0]*=r,t[1]*=r,t[2]*=o,t[3]*=o}this.invTransform=this.invTransform||[1,0,0,1,0,0],bo(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],vo(ll,t.invTransform,e),e=ll);var n=this.originX,i=this.originY;(n||i)&&(cl[4]=n,cl[5]=i,vo(ll,e,cl),ll[4]-=n,ll[5]-=i,e=ll),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&&Fr(n,n,i),n},t.prototype.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&Fr(n,n,i),n},t.prototype.getLineScale=function(){var t=this.transform;return t&&ul(t[0]-1)>1e-10&&ul(t[3]-1)>1e-10?Math.sqrt(ul(t[0]*t[3]-t[2]*t[1])):1},t.prototype.copyTransform=function(t){pl(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&&_o(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}(),hl=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function pl(t,e){for(var n=0;n=ml)){t=t||Si;for(var e=[],n=+new Date,i=0;i<=127;i++)e[i]=Ti.measureText(String.fromCharCode(i),t).width;var r=+new Date-n;return r>16?gl=ml:r>2&&gl++,e}}(t.font),t.asciiWidthMapTried=!0),0<=e&&e<=127?null!=t.asciiWidthMap?t.asciiWidthMap[e]:t.asciiCharWidth:t.stWideCharWidth}function yl(t,e){var n=t.strWidthCache,i=n.get(e);return null==i&&(i=Ti.measureText(e,t.font).width,n.put(e,i)),i}function _l(t,e,n,i){var r=yl(fl(e),t),o=Sl(e),a=xl(0,r,n),s=wl(0,o,i);return new Ro(a,s,r,o)}function bl(t,e,n,i){var r=((t||"")+"").split("\n");if(1===r.length)return _l(r[0],e,n,i);for(var o=new Ro(0,0,0,0),a=0;a=0?parseFloat(t)/100*e:parseFloat(t):t}function kl(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+=Cl(i[0],n.width),c+=Cl(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 Ml="__zr_normal__",Tl=hl.concat(["ignore"]),Al=Ki(hl,function(t,e){return t[e]=!0,t},{ignore:!1}),Il={},Dl=new Ro(0,0,0,0),Pl=[],Ll=function(){function t(t){this.id=Fi(),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=Dl,n.layoutRect?d.copy(n.layoutRect):d.copy(this.getBoundingRect()),i||d.applyTransform(this.transform)),c){this.calculateTextPosition?this.calculateTextPosition(Il,n,d):kl(Il,n,d),r.x=Il.x,r.y=Il.y,o=Il.align,a=Il.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=Cl(h[0],d.width),f=Cl(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 Ro(0,0,0,0);r.getLocalTransform(Pl),bo(Pl,Pl),Ro.copy(v,d),v.applyTransform(Pl)}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()?nl:el},t.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),n="string"==typeof e&&Xa(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,Qa(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||{},ji(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(sr(t))for(var n=Ji(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(Ml,!1,t)},t.prototype.useState=function(t,e,n,i){var r=t===Ml;if(this.hasState()||!r){var o=this.currentStates,a=this.stateTransition;if(!(Ui(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}$i("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=Ui(i,t),o=Ui(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]]=ks(n[v]),Rl(n,i,v)}}(w=new Ps(n,!1,!1,d?Qi(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)}}Gi(Ll,qr),Gi(Ll,dl);var zl=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=Ui(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=Ui(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 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` +var Hl={},Bl={};var Fl,$l=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 aa,o=n.renderer||"canvas";Hl[o]||(o=Ji(Hl)[0]),n.useDirtyRect=null!=n.useDirtyRect&&n.useDirtyRect;var a=new Hl[o](e,r,n,t),s=n.ssr||a.ssrOnly;this.storage=r,this.painter=a;var l,c=xi.node||xi.worker||s?null:new Qs(a.getViewportRoot(),a.root),u=n.useCoarsePointer;(null==u||"auto"===u?xi.touchEventsSupported:!!u)&&(l=fr(n.pointerSize,44)),this.handler=new Uo(r,a,c,a.root,l),this.animation=new Rs({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 Ja(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 Xl=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 Yl(t,e,n)};function Yl(t,e,n){return rr(t)?(i=t,i.replace(/^\s+|\s+$/g,"")).match(/%$/)?parseFloat(t)/100*e+(n||0):parseFloat(t):null==t?NaN:+t;var i}function Zl(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function Kl(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 Ql(t,e){var n=Math.max(Kl(t),Kl(e)),i=t+e;return n>20?i:Zl(i,n)}function Jl(t){var e=2*Math.PI;return(t%e+e)%e}function tc(t){return t>-1e-4&&t=10&&e++,e}function rc(t,e){var n=ic(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 oc(t){var e=parseFloat(t);return e==t&&(0!==e||!rr(t)||t.indexOf("x")<=0)?e:NaN}function ac(){return Math.round(9*Math.random())}function sc(t,e){return 0===e?t:sc(e,t%e)}function lc(t,e){return null==t?e:null==e?t:t*e/sc(t,e)}var cc="undefined"!=typeof console&&console.warn&&console.log;function uc(t,e){!function(t,e){cc&&console[t]("[ECharts] "+e)}("error",t)}function dc(t){throw new Error(t)}function hc(t,e,n){return(e-t)*n+t}var pc="series\0";function fc(t){return t instanceof Array?t:null==t?[]:[t]}function gc(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&&Ui(r,s)<0)){var l=n.getShallow(s,e);null!=l&&(o[t[a][0]]=l)}}return o}}var Wc=Vc([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),jc=function(){function t(){}return t.prototype.getAreaStyle=function(t,e){return Wc(this,t,e)},t}(),qc=new Ra(50);function Uc(t){if("string"==typeof t){var e=qc.get(t);return e&&e.image}return t}function Gc(t,e,n,i,r){if(t){if("string"==typeof t){if(e&&e.__zrImageSrc===t||!n)return e;var o=qc.get(t),a={hostEl:n,cb:i,cbPayload:r};return o?!Yc(e=o.image)&&o.pending.push(a):((e=Ti.loadImage(t,Xc,Xc)).__zrImageSrc=t,qc.put(t,e.__cachedImgObj={image:e,pending:[a]})),e}return t}return e}function Xc(){var t=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=s;c++)l-=s;var u=yl(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 Jc(t,e,n){var i=n.containerWidth,r=n.contentWidth,o=n.fontMeasureInfo;if(!i)return t.textLine="",void(t.isTruncated=!1);var a=yl(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?tu(e,r,o):a>0?Math.floor(e.length*r/a):0;a=yl(o,e=e.substr(0,l))}""===e&&(e=n.placeholder),t.textLine=e,t.isTruncated=!0}function tu(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=su(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=fl(u),v=0;v=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}(t)||!!ou[t]}function su(t,e,n,i,r){for(var o=[],a=[],s="",l="",c=0,u=0,d=fl(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 lu(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;Ro.set(cu,xl(n,a,r),wl(i,s,o),a,s),Ro.intersect(e,cu,null,uu);var l=uu.outIntersectRect;t.outerWidth=l.width,t.outerHeight=l.height,t.baseX=xl(l.x,l.width,r,!0),t.baseY=wl(l.y,l.height,o,!0)}}var cu=new Ro(0,0,0,0),uu={outIntersectRect:{},clamp:!0};function du(t){return null!=t?t+="":t=""}function hu(t,e,n,i){var r=new Ro(xl(t.x||0,e,t.textAlign),wl(t.y||0,n,t.textBaseline),e,n),o=null!=i?i:pu(t)?t.lineWidth:0;return o>0&&(r.x-=o/2,r.y-=o/2,r.width+=o,r.height+=o),r}function pu(t){var e=t.stroke;return null!=e&&"none"!==e&&t.lineWidth>0}var fu="__zr_style_"+Math.round(10*Math.random()),gu={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},mu={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};gu[fu]=!0;var vu=["z","z2","invisible"],yu=["invisible"],_u=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=Ji(e),i=0;i1e-4)return s[0]=t-n,s[1]=e-i,l[0]=t+n,void(l[1]=e+i);if(Tu[0]=ku(r)*n+t,Tu[1]=Cu(r)*i+e,Au[0]=ku(o)*n+t,Au[1]=Cu(o)*i+e,c(s,Tu,Au),u(l,Tu,Au),(r%=Mu)<0&&(r+=Mu),(o%=Mu)<0&&(o+=Mu),r>o&&!a?o+=Mu:rr&&(Iu[0]=ku(p)*n+t,Iu[1]=Cu(p)*i+e,c(s,Iu,s),u(l,Iu,l))}var Ou={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},zu=[],Hu=[],Bu=[],Fu=[],$u=[],Vu=[],Wu=Math.min,ju=Math.max,qu=Math.cos,Uu=Math.sin,Gu=Math.abs,Xu=Math.PI,Yu=2*Xu,Zu="undefined"!=typeof Float32Array,Ku=[];function Qu(t){return Math.round(t/Xu*1e8)/1e8%2*Xu}var Ju=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=Gu(n/tl/t)||0,this._uy=Gu(n/tl/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(Ou.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=Gu(t-this._xi),i=Gu(e-this._yi),r=n>this._ux||i>this._uy;if(this.addData(Ou.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(Ou.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(Ou.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(),Ku[0]=i,Ku[1]=r,function(t,e){var n=Qu(t[0]);n<0&&(n+=Yu);var i=n-t[0],r=t[1];r+=i,!e&&r-n>=Yu?r=n+Yu:e&&n-r>=Yu?r=n-Yu:!e&&n>r?r=n+(Yu-Qu(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(){Bu[0]=Bu[1]=$u[0]=$u[1]=Number.MAX_VALUE,Fu[0]=Fu[1]=Vu[0]=Vu[1]=-Number.MAX_VALUE;var t,e=this.data,n=0,i=0,r=0,o=0;for(t=0;tn||Gu(m)>i||d===e-1)&&(f=Math.sqrt(I*I+m*m),r=g,o=_);break;case Ou.C:var v=t[d++],y=t[d++],_=(g=t[d++],t[d++]),b=t[d++],x=t[d++];f=Ca(r,o,v,y,g,_,b,x,10),r=b,o=x;break;case Ou.Q:f=Ia(r,o,v=t[d++],y=t[d++],g=t[d++],_=t[d++],10),r=g,o=_;break;case Ou.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=qu(M)*C+w,s=Uu(M)*k+S),f=ju(C,k)*Wu(Yu,Math.abs(T)),r=qu(A)*C+w,o=Uu(A)*k+S;break;case Ou.R:a=r=t[d++],s=o=t[d++],f=2*t[d++]+2*t[d++];break;case Ou.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 Ou.M:n=r=h[b++],i=o=h[b++],t.moveTo(r,o);break;case Ou.L:a=h[b++],s=h[b++];var S=Gu(a-r),C=Gu(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 Ou.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){Sa(r,T,I,P,k=(c-v)/X,zu),Sa(o,A,D,L,k,Hu),t.bezierCurveTo(zu[1],Hu[1],zu[2],Hu[2],zu[3],Hu[3]);break t}v+=X}t.bezierCurveTo(T,A,I,D,P,L),r=P,o=L;break;case Ou.Q:T=h[b++],A=h[b++],I=h[b++],D=h[b++];if(m){if(v+(X=l[y++])>c){Aa(r,T,I,k=(c-v)/X,zu),Aa(o,A,D,k,Hu),t.quadraticCurveTo(zu[1],Hu[1],zu[2],Hu[2]);break t}v+=X}t.quadraticCurveTo(T,A,I,D),r=I,o=D;break;case Ou.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=Gu(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=qu(z)*R+E,i=Uu(z)*O+N),r=qu(W)*R+E,o=Uu(W)*O+N;break;case Ou.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+Wu(G,q),s),(G-=q)>0&&t.lineTo(a+q,s+Wu(G,U)),(G-=U)>0&&t.lineTo(a+ju(q-G,0),s+U),(G-=q)>0&&t.lineTo(a,s+ju(U-G,0));break t}v+=X}t.rect(a,s,q,U);break;case Ou.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=Ou,t.initDefaultProps=((e=t.prototype)._saveData=!0,e._ux=0,e._uy=0,e._pendingPtDist=0,void(e._version=0)),t}();function td(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+=od);var h=Math.atan2(l,s);return h<0&&(h+=od),h>=i&&h<=r||h+od>=i&&h+od<=r}function sd(t,e,n,i,r,o){if(o>e&&o>i||or?s:0}var ld=Ju.CMD,cd=2*Math.PI;var ud=[-1,-1,-1],dd=[-1,-1];function hd(){var t=dd[0];dd[0]=dd[1],dd[1]=t}function pd(t,e,n,i,r,o,a,s,l,c){if(c>e&&c>i&&c>o&&c>s||c1&&hd(),p=_a(e,i,o,s,dd[0]),h>1&&(f=_a(e,i,o,s,dd[1]))),2===h?me&&s>i&&s>o||s=0&&u<=1&&(r[l++]=u);else{var c=a*a-4*o*s;if(va(c))(u=-a/(2*o))>=0&&u<=1&&(r[l++]=u);else if(c>0){var u,d=ca(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,ud);if(0===l)return 0;var c=Ta(e,i,o);if(c>=0&&c<=1){for(var u=0,d=ka(e,i,o,c),h=0;hn||s<-n)return 0;var l=Math.sqrt(n*n-s*s);ud[0]=-l,ud[1]=l;var c=Math.abs(i-r);if(c<1e-4)return 0;if(c>=cd-1e-4){i=0,r=cd;var u=o?1:-1;return a>=ud[0]+t&&a<=ud[1]+t?u:0}if(i>r){var d=i;i=r,r=d}i<0&&(i+=cd,r+=cd);for(var h=0,p=0;p<2;p++){var f=ud[p];if(f+t>a){var g=Math.atan2(s,f);u=o?1:-1;g<0&&(g=cd+g),(g>=i&&g<=r||g+cd>=i&&g+cd<=r)&&(g>Math.PI/2&&g<1.5*Math.PI&&(u=-u),h+=u)}}return h}function md(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+=sd(u,d,h,p,i,r))),m&&(h=u=s[f],p=d=s[f+1]),g){case ld.M:u=h=s[f++],d=p=s[f++];break;case ld.L:if(n){if(td(u,d,s[f],s[f+1],e,i,r))return!0}else c+=sd(u,d,s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case ld.C:if(n){if(ed(u,d,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=pd(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 ld.Q:if(n){if(nd(u,d,s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=fd(u,d,s[f++],s[f++],s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case ld.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+=sd(u,d,o,a,i,r);var C=(i-v)*b/_+v;if(n){if(ad(v,y,b,x,x+w,S,e,C,r))return!0}else c+=gd(v,y,b,x,x+w,S,C,r);u=Math.cos(x+w)*_+v,d=Math.sin(x+w)*b+y;break;case ld.R:if(h=u=s[f++],p=d=s[f++],o=h+s[f++],a=p+s[f++],n){if(td(h,p,o,p,e,i,r)||td(o,p,o,a,e,i,r)||td(o,a,h,a,e,i,r)||td(h,a,h,p,e,i,r))return!0}else c+=sd(o,p,o,a,i,r),c+=sd(h,a,h,p,i,r);break;case ld.Z:if(n){if(td(u,d,h,p,e,i,r))return!0}else c+=sd(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+=sd(u,d,h,p,i,r)||0),0!==c}var vd=qi({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},gu),yd={style:qi({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},mu.style)},_d=hl.concat(["invisible","culling","z","z2","zlevel","parent"]),bd=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<_d.length;++s)r[_d[s]]=this[_d[s]];r.__dirty|=1}else this._decalEl&&(this._decalEl=null)},e.prototype.getDecalElement=function(){return this._decalEl},e.prototype._init=function(e){var n=Ji(e);this.shape=this.getDefaultShape();var i=this.getDefaultStyle();i&&this.useStyle(i);for(var r=0;r.5?el:e>.2?"#eee":nl}if(t)return nl}return el},e.prototype.getInsideTextStroke=function(t){var e=this.style.fill;if(rr(e)){var n=this.__zr;if(!(!n||!n.isDarkMode())===Ja(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 Ju(!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 md(t,e,!0,n,i)}(o,a/s,t,e)))return!0}if(this.hasFill())return function(t,e,n){return md(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:ji(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(4&this.__dirty)},e.prototype.createStyle=function(t){return Tr(vd,t)},e.prototype._innerSaveToNormal=function(e){t.prototype._innerSaveToNormal.call(this,e);var n=this._normalState;e.shape&&!n.shape&&(n.shape=ji({},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=ji({},i.shape),ji(s,n.shape)):(s=ji({},r?this.shape:i.shape),ji(s,n.shape)):l&&(s=i.shape),s)if(o){this.shape=ji({},this.shape);for(var c={},u=Ji(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}(bd);Ld.prototype.type="rect";var Ed={fill:"#000"},Nd={},Rd={style:qi({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},mu.style)},Od=function(t){function e(e){var n=t.call(this)||this;return n.type="text",n._children=[],n._defaultStyle=Ed,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=Qc(g,c,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),x={},w=0;w0,k=0;kg&&ru(o,a.substring(g,m),e,f),ru(o,h[2],e,f,h[1]),g=Zc.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&&Xd(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=Ud(r,o,d),c-=t.height/2-d[0]-t.innerHeight/2);var h=this._getOrCreateChild(wd),p=h.createStyle();h.useStyle(p);var f=this._defaultStyle,g=!1,m=0,v=!1,y=qd("fill"in s?s.fill:"fill"in e?e.fill:(g=!0,f.fill)),_=jd("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||Si,p.opacity=gr(s.opacity,e.opacity,1),$d(p,s),_&&(p.lineWidth=gr(s.lineWidth,e.lineWidth,m),p.lineDash=fr(s.lineDash,e.lineDash),p.lineDashOffset=e.lineDashOffset||0,p.stroke=_),y&&(p.fill=y),h.setBoundingRect(hu(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(Ld)).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=fr(t.fillOpacity,1);else if(h){(s=this._getOrCreateChild(kd)).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=fr(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=gr(t.opacity,e.opacity,1)},e.makeFont=function(t){var e="";return Vd(t)&&(e=[t.fontStyle,t.fontWeight,Fd(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),e&&_r(e)||t.textFont||t.font},e}(_u),zd={left:!0,right:1,center:1},Hd={top:1,bottom:1,middle:1},Bd=["fontStyle","fontWeight","fontSize","fontFamily"];function Fd(t){return"string"!=typeof t||-1===t.indexOf("px")&&-1===t.indexOf("rem")&&-1===t.indexOf("em")?isNaN(+t)?"12px":t+"px":t}function $d(t,e){for(var n=0;n=0,o=!1;if(t instanceof bd){var a=Qd(t),s=r&&a.selectFill||a.normalFill,l=r&&a.selectStroke||a.normalStroke;if(lh(s)||lh(l)){var c=(i=i||{}).style||{};"inherit"===c.fill?(o=!0,i=ji({},i),(c=ji({},c)).fill=s):!lh(c.fill)&&lh(s)?(o=!0,i=ji({},i),(c=ji({},c)).fill=es(s)):!lh(c.stroke)&&lh(l)&&(o||(i=ji({},i),c=ji({},c)),c.stroke=es(l)),i.style=c}}if(i&&null==i.z2){o||(i=ji({},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=Ui(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 Rh(t,e,n){Fh(t,!0),vh(t,bh),function(t,e,n){var i=Yd(t);null!=e?(i.focus=e,i.blurScope=n):i.focus&&(i.focus=null)}(t,e,n)}function Oh(t,e,n,i){i?function(t){Fh(t,!1)}(t):Rh(t,e,n)}var zh=["emphasis","blur","select"],Hh={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function Bh(t,e,n,i){n=n||"itemStyle";for(var r=0;r1&&(a*=Xh(f),s*=Xh(f));var g=(r===o?-1:1)*Xh((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+Zh(d)*m-Yh(d)*v,_=(e+i)/2+Yh(d)*m+Zh(d)*v,b=tp([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=tp(x,w);if(Jh(x,w)<=-1&&(S=Kh),Jh(x,w)>=1&&(S=0),S<0){var C=Math.round(S/Kh*1e6)/1e6;S=2*Kh+C%2*Kh}u.addData(c,y,_,a,s,b,S,d,o)}var np=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,ip=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;var rp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.applyTransform=function(t){},e}(bd);function op(t){return null!=t.setData}function ap(t,e){var n=function(t){var e=new Ju;if(!t)return e;var n,i=0,r=0,o=i,a=r,s=Ju.CMD,l=t.match(np);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 Sp(t,e){var n,i=_p(e.r,0),r=_p(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=vp(l-s),p=h>hp&&h%hp;if(p>xp&&(h=p),i>xp)if(h>hp-xp)t.moveTo(c+i*fp(s),u+i*pp(s)),t.arc(c,u,i,s,l,!d),r>xp&&(t.moveTo(c+r*fp(l),u+r*pp(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*fp(s),P=i*pp(s),L=r*fp(l),E=r*pp(l),N=h>xp;if(N){var R=e.cornerRadius;R&&(n=function(t){var e;if(nr(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=vp(i-r)/2;if(y=bp(O,m),_=bp(O,v),b=bp(O,f),x=bp(O,g),C=w=_p(y,_),k=S=_p(b,x),(w>xp||S>xp)&&(M=i*fp(l),T=i*pp(l),A=r*fp(s),I=r*pp(s),hxp){var j=bp(m,C),q=bp(v,C),U=wp(A,I,D,P,i,j,d),G=wp(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,mp(U.y0,U.x0),mp(U.y1,U.x1),!d),t.arc(c,u,i,mp(U.cy+U.y1,U.cx+U.x1),mp(G.cy+G.y1,G.cx+G.x1),!d),q>0&&t.arc(c+G.cx,u+G.cy,q,mp(G.y1,G.x1),mp(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>xp&&N)if(k>xp){j=bp(f,k),U=wp(L,E,M,T,r,-(q=bp(g,k)),d),G=wp(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,mp(U.y0,U.x0),mp(U.y1,U.x1),!d),t.arc(c,u,r,mp(U.cy+U.y1,U.cx+U.x1),mp(G.cy+G.y1,G.cx+G.x1),d),j>0&&t.arc(c+G.cx,u+G.cy,j,mp(G.y1,G.x1),mp(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 Cp=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},kp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new Cp},e.prototype.buildPath=function(t,e){Sp(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(bd);kp.prototype.type="sector";var Mp=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},Tp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new Mp},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}(bd);function Ap(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;hZp[1]){if(r=!1,Kp.negativeSize||n)return r;var s=Xp(Zp[0]-Yp[1]),l=Xp(Yp[0]-Zp[1]);Up(s,l)>Jp.len()&&(s=l||!Kp.bidirectional)&&(xo.scale(Qp,a,-l*i),Kp.useDir&&Kp.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 af(t,e,n,i,r,o){of("update",t,e,n,i,r,o)}function sf(t,e,n,i,r,o){of("enter",t,e,n,i,r,o)}function lf(t){if(!t.__zr)return!0;for(var e=0;e=-1e-6)return!1;var f=t-r,g=e-o,m=Af(f,g,c,u)/p;if(m<0||m>1)return!1;var v=Af(f,g,d,h)/p;return!(v<0||v>1)}function Af(t,e,n,i){return t*i-n*e}function If(t,e,n,i,r){return null==e||(ar(e)?Df[0]=Df[1]=Df[2]=Df[3]=e:(Df[0]=e[0],Df[1]=e[1],Df[2]=e[2],Df[3]=e[3]),i&&(Df[0]=ql(0,Df[0]),Df[1]=ql(0,Df[1]),Df[2]=ql(0,Df[2]),Df[3]=ql(0,Df[3])),n&&(Df[0]=-Df[0],Df[1]=-Df[1],Df[2]=-Df[2],Df[3]=-Df[3]),Pf(t,Df,"x","width",3,1,r&&r[0]||0),Pf(t,Df,"y","height",0,2,r&&r[1]||0)),t}var Df=[0,0,0,0];function Pf(t,e,n,i,r,o,a){var s=e[o]+e[r],l=t[i];t[i]+=s,a=ql(0,jl(a,l)),t[i]=0?-e[r]:e[o]>=0?l+e[o]:Ul(s)>1e-8?(l-a)*e[r]/s:0):t[n]-=e[r]}function Lf(t){var e=t.itemTooltipOption,n=t.componentModel,i=t.itemName,r=rr(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&&Yi(Ji(l),function(t){Ar(s,t)||(s[t]=l[t],s.$vars.push(t))});var c=Yd(t.el);c.componentMainType=o,c.componentIndex=a,c.tooltipConfig={name:i,option:qi({content:i,encodeHTMLContent:!0,formatterParams:s},r)}}function Ef(t,e){var n;t.isGroup&&(n=e(t)),n||t.traverse(e)}function Nf(t,e){if(t)if(nr(t))for(var n=0;ne&&(e=i),ie&&(n=e=0),{min:n,max:e}},clipPointsByRect:function(t,e){return Zi(t,function(t){var n=t[0];n=ql(n,e.x),n=jl(n,e.x+e.width);var i=t[1];return i=ql(i,e.y),[n,i=jl(i,e.y+e.height)]})},clipRectByRect:function(t,e){var n=ql(t.x,e.x),i=jl(t.x+t.width,e.x+e.width),r=ql(t.y,e.y),o=jl(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:Mf,ensureCopyRect:zf,ensureCopyTransform:Hf,expandOrShrinkRect:If,extendPath:function(t,e){return ff(t,e)},extendShape:function(t){return bd.extend(t)},getShapeClass:function(t){if(df.hasOwnProperty(t))return df[t]},getTransform:function(t,e){for(var n=go([]);t&&t!==e;)vo(n,t.getLocalTransform(),n),t=t.parent;return n},groupTransition:kf,initProps:sf,isBoundingRectAxisAligned:Rf,isElementRemoved:lf,lineLineIntersect:Tf,linePolygonIntersect:function(t,e,n,i,r){for(var o=0,a=r[r.length-1];oUl(o[1])?o[0]>0?"right":"left":o[1]>0?"bottom":"top"},traverseElements:Nf,traverseUpdateZ:Ff,updateProps:af}),Wf={};function jf(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=ir(t.defaultText)?t.defaultText(o,t,n):t.defaultText);for(var l={normal:i},c=0;c-1?mg:yg;function wg(t,e){t=t.toUpperCase(),bg[t]=new pg(e),_g[t]=e}wg(vg,{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:". "}}}}),wg(mg,{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 Sg(){return null}var Cg=1e3,kg=6e4,Mg=36e5,Tg=864e5,Ag=31536e6,Ig={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})/},Dg={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}"},Pg="{yyyy}-{MM}-{dd}",Lg={year:"{yyyy}",month:"{yyyy}-{MM}",day:Pg,hour:Pg+" "+Dg.hour,minute:Pg+" "+Dg.minute,second:Pg+" "+Dg.second,millisecond:"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}"},Eg=["year","month","day","hour","minute","second","millisecond"],Ng=["year","half-year","quarter","month","week","half-week","day","half-day","quarter-day","hour","minute","second","millisecond"];function Rg(t){return rr(t)||ir(t)?t:function(t){t=t||{};var e={},n=!0;return Yi(Eg,function(e){n&&(n=null==t[e])}),Yi(Eg,function(i,r){var o=t[i];e[i]={};for(var a=null,s=r;s>=0;s--){var l=Eg[s],c=sr(o)&&!nr(o)?o[l]:o,u=void 0;nr(c)?a=(u=c.slice())[0]||"":rr(c)?u=[a=c]:(null==a?a=Dg[i]:Ig[l].test(a)||(a=e[l][l][0]+" "+a),u=[a],n&&(u[1]="{primary|"+a+"}")),e[i][l]=u}}),e}(t)}function Og(t,e){return"0000".substr(0,e-(t+="").length)+t}function zg(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 Hg(t){return t===zg(t)}function Bg(t,e,n,i){var r=nc(t),o=r[Vg(n)](),a=r[Wg(n)]()+1,s=Math.floor((a-1)/3)+1,l=r[jg(n)](),c=r["get"+(n?"UTC":"")+"Day"](),u=r[qg(n)](),d=(u-1)%12+1,h=r[Ug(n)](),p=r[Gg(n)](),f=r[Xg(n)](),g=u>=12?"pm":"am",m=g.toUpperCase(),v=i instanceof pg?i:function(t){return bg[t]}(i||xg)||bg[yg],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,Og(o%100+"",2)).replace(/{Q}/g,s+"").replace(/{MMMM}/g,_[a-1]).replace(/{MMM}/g,b[a-1]).replace(/{MM}/g,Og(a,2)).replace(/{M}/g,a+"").replace(/{dd}/g,Og(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,x[c]).replace(/{ee}/g,w[c]).replace(/{e}/g,c+"").replace(/{HH}/g,Og(u,2)).replace(/{H}/g,u+"").replace(/{hh}/g,Og(d+"",2)).replace(/{h}/g,d+"").replace(/{mm}/g,Og(h,2)).replace(/{m}/g,h+"").replace(/{ss}/g,Og(p,2)).replace(/{s}/g,p+"").replace(/{SSS}/g,Og(f,3)).replace(/{S}/g,f+"")}function Fg(t,e){var n=nc(t),i=n[Wg(e)]()+1,r=n[jg(e)](),o=n[qg(e)](),a=n[Ug(e)](),s=n[Gg(e)](),l=0===n[Xg(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 $g(t,e,n){switch(e){case"year":t[Zg(n)](0);case"month":t[Kg(n)](1);case"day":t[Qg(n)](0);case"hour":t[Jg(n)](0);case"minute":t[tm(n)](0);case"second":t[em(n)](0)}return t}function Vg(t){return t?"getUTCFullYear":"getFullYear"}function Wg(t){return t?"getUTCMonth":"getMonth"}function jg(t){return t?"getUTCDate":"getDate"}function qg(t){return t?"getUTCHours":"getHours"}function Ug(t){return t?"getUTCMinutes":"getMinutes"}function Gg(t){return t?"getUTCSeconds":"getSeconds"}function Xg(t){return t?"getUTCMilliseconds":"getMilliseconds"}function Yg(t){return t?"setUTCFullYear":"setFullYear"}function Zg(t){return t?"setUTCMonth":"setMonth"}function Kg(t){return t?"setUTCDate":"setDate"}function Qg(t){return t?"setUTCHours":"setHours"}function Jg(t){return t?"setUTCMinutes":"setMinutes"}function tm(t){return t?"setUTCSeconds":"setSeconds"}function em(t){return t?"setUTCMilliseconds":"setMilliseconds"}function nm(t){if(isNaN(oc(t)))return rr(t)?t:"-";var e=(t+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function im(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 rm=vr;function om(t,e,n){function i(t){return t&&_r(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?nc(t):t;if(!isNaN(+s))return Bg(s,"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}",n);if(a)return"-"}if("ordinal"===e)return or(t)?i(t):ar(t)&&r(t)?t+"":"-";var l=oc(t);return r(l)?nm(l):or(t)?i(t):"boolean"==typeof t?t+"":"-"}var am=["a","b","c","d","e","f","g"],sm=function(t,e){return"{"+t+(null==e?"":e)+"}"};function lm(t,e,n){nr(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 Cm(t,e,n){n=rm(n||0);var i=e.width,r=e.height,o=Xl(t.left,i),a=Xl(t.top,r),s=Xl(t.right,i),l=Xl(t.bottom,r),c=Xl(t.width,i),u=Xl(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 Ro((e.x||0)+o+n[3],(e.y||0)+a+n[0],c,u);return f.margin=n,f}er(Sm,"vertical"),er(Sm,"horizontal");var km=1;function Mm(t,e,n){var i,r,o,a,s=t.boxCoordinateSystem;if(s){var l=function(t){var e=t.getShallow("coord",!0),n=pm;if(null==e){var i=gm.get(t.type);i&&i.getCoord2&&(n=fm,e=i.getCoord2(t))}return{coord:e,from:n}}(t),c=l.coord,u=l.from;if(s.dataToLayout){o=km,a=u;var d=s.dataToLayout(c);i=d.contentRect||d.rect}}return null==o&&(o=km),o===km&&(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 Tm(t){var e=t.layoutMode||t.constructor.layoutMode;return sr(e)?e:e?{type:e}:null}function Am(t,e,n){var i=n&&n.ignoreSize;!nr(i)&&(i=[i,i]);var r=a(wm[0],0),o=a(wm[1],1);function a(n,r){var o={},a=0,l={},c=0;if(bm(n,function(e){l[e]=t[e]}),bm(n,function(t){Ar(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=Wi(o,n[a],!0);e.defaultOption=o}return e.defaultOption},e.prototype.getReferringComponents=function(t,e){var n=t+"Index",i=t+"Id";return Pc(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}(pg);zc(Pm,pg),$c(Pm),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){var i=Rc(t);e[i.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var o=Rc(n).main;t.hasSubTypes(n)&&e[o]&&(r=e[o](i))}return r}}(Pm),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 Yi(t,function(o){var a=n(i,o),s=function(t,e){var n=[];return Yi(t,function(t){Ui(e,t)>=0&&n.push(t)}),n}(a.originalDeps=e(o),t);a.entryCount=s.length,0===a.entryCount&&r.push(o),Yi(s,function(t){Ui(a.predecessor,t)<0&&a.predecessor.push(t);var e=n(i,t);Ui(e.successor,t)<0&&e.successor.push(o)})}),{graph:i,noEntryList:r}}(i),s=a.graph,l=a.noEntryList,c={};for(Yi(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]),Yi(d.successor,h?f:p)}Yi(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)}}}(Pm,function(t){var e=[];Yi(Pm.getClassesByMainType(t),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=Zi(e,function(t){return Rc(t).main}),"dataset"!==t&&Ui(e,"dataset")<=0&&e.unshift("dataset");return e});var Lm={color:{},darkColor:{},size:{}},Em=Lm.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 Nm in ji(Em,{primary:Em.neutral80,secondary:Em.neutral70,tertiary:Em.neutral60,quaternary:Em.neutral50,disabled:Em.neutral20,border:Em.neutral30,borderTint:Em.neutral20,borderShade:Em.neutral40,background:Em.neutral05,backgroundTint:"rgba(234,237,245,0.5)",backgroundTransparent:"rgba(255,255,255,0)",backgroundShade:Em.neutral10,shadow:"rgba(0,0,0,0.2)",shadowTint:"rgba(129,130,136,0.2)",axisLine:Em.neutral70,axisLineTint:Em.neutral40,axisTick:Em.neutral70,axisTickMinor:Em.neutral60,axisLabel:Em.neutral70,axisSplitLine:Em.neutral15,axisMinorSplitLine:Em.neutral05}),Em)if(Em.hasOwnProperty(Nm)){var Rm=Em[Nm];"theme"===Nm?Lm.darkColor.theme=Em.theme.slice():"highlight"===Nm?Lm.darkColor.highlight="rgba(255,231,130,0.4)":0===Nm.indexOf("accent")?Lm.darkColor[Nm]=Ka(Rm,0,function(t){return.5*t},function(t){return Math.min(1,1.3-t)}):Lm.darkColor[Nm]=Ka(Rm,0,function(t){return.9*t},function(t){return 1-Math.pow(t,1.5)})}Lm.size={xxs:2,xs:5,s:10,m:15,l:20,xl:30,xxl:40,xxxl:50};var Om="";"undefined"!=typeof navigator&&(Om=navigator.platform||"");var zm="rgba(0, 0, 0, 0.2)",Hm=Lm.color.theme[0],Bm=Ka(Hm,0,null,.9),Fm={darkMode:"auto",colorBy:"series",color:Lm.color.theme,gradientColor:[Bm,Hm],aria:{decal:{decals:[{color:zm,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:zm,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:zm,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:zm,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:zm,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:zm,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:Om.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},$m=Mr(["tooltip","label","itemName","itemId","itemGroupId","itemChildGroupId","seriesName"]),Vm="original",Wm="arrayRows",jm="objectRows",qm="keyedColumns",Um="typedArray",Gm="unknown",Xm="column",Ym="row",Zm=1,Km=2,Qm=3,Jm=Mc();function tv(t,e,n){var i={},r=ev(e);if(!r||!t)return i;var o,a,s=[],l=[],c=e.ecModel,u=Jm(c).datasetMap,d=r.uid+"_"+n.seriesLayoutBy;Yi(t=t.slice(),function(e,n){var r=sr(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,rv,i,r,t,e,n)},t.prototype.clearColorPalette=function(){!function(t,e){e(t).paletteIdx=0,e(t).paletteNameMap={}}(this,rv)},t}();var cv="\0_ec_inner",uv=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 pg(i),this._locale=new pg(r),this._optionManager=o},e.prototype.setOption=function(t,e,n){var i=pv(e);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,e){return this._resetOption(t,pv(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)):sv(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&&Yi(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=Mr(),s=e&&e.replaceMergeMainTypeMap;Jm(this).datasetMap=Mr(),Yi(t,function(t,e){null!=t&&(Pm.hasClass(e)?e&&(o.push(e),a.set(e,!0)):n[e]=null==n[e]?Vi(t):Wi(n[e],t,!0))}),s&&s.each(function(t,e){Pm.hasClass(e)&&!a.get(e)&&(o.push(e),a.set(e,!0))}),Pm.topologicalTravel(o,Pm.getAllClassMainTypes(),function(e){var o=function(t,e,n){var i=iv.get(e);if(!i)return n;var r=i(t);return r?n.concat(r):n}(this,e,fc(t[e])),a=i.get(e),l=a?s&&s.get(e)?"replaceMerge":"normalMerge":"replaceAll",c=_c(a,o,l);(function(t,e,n){Yi(t,function(t){var i=t.newOption;sr(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,Pm),n[e]=null,i.set(e,null),r.set(e,0);var u,d=[],h=[],p=0;Yi(c,function(t,n){var i=t.existing,r=t.newOption;if(r){var o="series"===e,a=Pm.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=ji({componentIndex:n},t.keyInfo);ji(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&&ov(this)},this),this._seriesIndices||ov(this)},e.prototype.getOption=function(){var t=Vi(this.option);return Yi(t,function(e,n){if(Pm.hasClass(n)){for(var i=fc(e),r=i.length,o=!1,a=r-1;a>=0;a--)i[a]&&!Cc(i[a])?o=!0:(i[a]=null,!o&&r--);i.length=r,t[n]=i}}),delete t[cv],t},e.prototype.setTheme=function(t){this._theme=new pg(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 _v=Yi,bv=sr,xv=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function wv(t){var e=t&&t.itemStyle;if(e)for(var n=0,i=xv.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 dy(this.getData(e),t)},t.prototype.formatTooltip=function(t,e,n){},t}();function fy(t){var e,n;return sr(t)?t.type&&(n=t):e=t,{text:e,frag:n}}function gy(t){return new my(t)}var my=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}(),by=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 yy(t,e)},t}();function xy(t){if(!Ty(t.sourceFormat)){dc("")}return t.data}function wy(t){var e=t.sourceFormat,n=t.data;if(!Ty(e)){dc("")}if(e===Wm){for(var i=[],r=0,o=n.length;r65535?Dy:Py}function Oy(){return[1/0,-1/0]}function zy(t){var e=t.constructor;return e===Array?t.slice():new e(t)}function Hy(t,e,n,i,r){var o=Ny[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=Zi(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(Ry(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 yy(t[i],this._dimensions[i])}Ay={arrayRows:t,objectRows:function(t,e,n,i){return yy(t[e],this._dimensions[i])},keyedColumns:t,original:function(t,e,n,i){var r=t&&(null==t.value?t:t.value);return yy(r instanceof Array?r[i]:r,this._dimensions[i])},typedArray:function(t,e,n,i){return t[i]}}}(),t}(),Fy=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($y(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=cr(a=o.get("data",!0))?Um:Vm,e=[];var u=this._getSourceMetaRawOption()||{},d=l&&l.metaRawOption||{},h=fr(u.seriesLayoutBy,d.seriesLayoutBy)||null,p=fr(u.sourceHeader,d.sourceHeader),f=fr(u.dimensions,d.dimensions);t=h!==d.seriesLayoutBy||!!p!=!!d.sourceHeader||f?[Gv(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=[Gv(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&&Vy("")}var o,a=[],s=[];return Yi(t,function(t){t.prepareSource();var e=t.getSource(r||0);null==r||e||Vy(""),a.push(e),s.push(t._getVersionSign())}),i?e=function(t,e){var n=fc(t),i=n.length;i||dc("");for(var r=0,o=i;r1||n>0&&!t.noHeader;return Yi(t.blocks,function(t){var n=Zy(t);n>=e&&(e=n+ +(i&&(!n||Xy(t)&&!t.noHeader)))}),e}return 0}function Ky(t,e,n,i){var r,o=e.noHeader,a=(r=Zy(e),{html:qy[r],richText:Uy[r]}),s=[],l=e.blocks||[];yr(!l||nr(l)),l=l||[];var c=t.orderMode;if(e.sortBlocks&&c){l=l.slice();var u={valueAsc:"asc",valueDesc:"desc"};if(Ar(u,c)){var d=new _y(u[c],null);l.sort(function(t,e){return d.evaluate(t.sortParam,e.sortParam)})}else"seriesDesc"===c&&l.reverse()}Yi(l,function(n,r){var o=e.valueFormatter,l=Yy(n)(o?ji(ji({},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):t_(i,s.join(""),o?n:a.html);if(o)return h;var p=om(e.header,"ordinal",t.useUTC),f=jy(i,t.renderMode).nameStyle,g=Wy(i);return"richText"===t.renderMode?e_(t,p,f)+a.richText+h:t_(i,'
'+eo(p)+"
"+h,n)}function Qy(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 Zi(t=nr(t)?t:[t],function(t,e){return om(t,nr(p)?p[e]:p,c)})};if(!o||!a){var d=s?"":t.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||Lm.color.secondary,r),h=o?"":om(l,"ordinal",c),p=e.valueType,f=a?[]:u(e.value,e.dataIndex),g=!s||!o,m=!s&&o,v=jy(i,r),y=v.nameStyle,_=v.valueStyle;return"richText"===r?(s?"":d)+(o?"":e_(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(nr(e)?e.join(" "):e,o)}(t,f,g,m,_)):t_(i,(s?"":d)+(o?"":function(t,e,n){return''+eo(t)+""}(h,!s,y))+(a?"":function(t,e,n,i){var r=n?"10px":"20px",o=e?"float:right;margin-left:"+r:"";return t=nr(t)?t:[t],''+Zi(t,function(t){return eo(t)}).join("  ")+""}(f,g,m,_)),n)}}function Jy(t,e,n,i,r,o){if(t)return Yy(t)({useUTC:r,renderMode:n,orderMode:i,markupStyleCreator:e,valueFormatter:t.valueFormatter},t,0,o)}function t_(t,e,n){return'
'+e+'
'}function e_(t,e,n){return t.markupStyleCreator.wrapRichTextStyle(e,n)}function n_(t,e){var n=t.get("padding");return null!=n?n:"richText"===e?[8,10]:10}var i_=function(){function t(){this.richTextStyles={},this._nextStyleNameId=ac()}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=rr(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 rr(r)?r:(this.richTextStyles[i]=r.style,r.content)},t.prototype.wrapRichTextStyle=function(t,e){var n={};nr(e)?Yi(e,function(t){return ji(n,t)}):ji(n,e);var i=this._generateStyleName();return this.richTextStyles[i]=n,"{"+i+"|"+t+"}"},t}();function r_(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=nr(d),p=function(t,e){return cm(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=Ki(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(Gy("nameValue",{markerType:"subItem",markerColor:r,name:n.displayName,value:t,valueType:n.type})):(s.push(t),l.push(n.type)))}return i.length?Yi(i,function(t){u(dy(o,n,t),t)}):Yi(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=dy(l,a,c[0]),n=g.type}else r=e=h?d[0]:d;var m=Sc(o),v=m&&o.name||"",y=l.getName(a),_=s?v:y;return Gy("section",{header:v,noHeader:s||!m,sortParam:r,blocks:[Gy("nameValue",{markerType:"item",markerColor:p,name:_,noName:!_r(_),value:e,valueType:n,dataIndex:a})].concat(i||[])})}var o_=Mc();function a_(t,e){return t.getName(e)||t.getId(e)}var s_=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=gy({count:c_,reset:u_}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),(o_(this).sourceManager=new Fy(this)).prepareSource();var i=this.getInitialData(t,n);h_(i,this),this.dataTask.context.data=i,o_(this).dataBeforeProcessed=i,l_(this),this._initSelectedMapFromData(i)},e.prototype.mergeDefaultAndTheme=function(t,e){var n=Tm(this),i=n?Im(t):{},r=this.subType;Pm.hasClass(r)&&(r+="Series"),Wi(t,e.getTheme().get(this.subType)),Wi(t,this.getDefaultOption()),gc(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&Am(t,i,n)},e.prototype.mergeOption=function(t,e){t=Wi(this.option,t,!0),this.fillDataTextStyle(t.data);var n=Tm(this);n&&Am(this.option,t,n);var i=o_(this).sourceManager;i.dirty(),i.prepareSource();var r=this.getInitialData(t,e);h_(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,o_(this).dataBeforeProcessed=r,l_(this),this._initSelectedMapFromData(r)},e.prototype.fillDataTextStyle=function(t){if(t&&!cr(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 r_({series:this,dataIndex:t,multipleSeries:e})},e.prototype.isAnimationEnabled=function(){var t=this.ecModel;if(xi.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=lv.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[a_(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){sr(r.selectedMap)||(r.selectedMap={});for(var s=r.selectedMap,l=0;l0&&this._innerSelect(t,e)}},e.registerClass=function(t){return Pm.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}(Pm);function l_(t){var e=t.name;Sc(t)||(t.name=function(t){var e=t.getRawData(),n=e.mapDimensionsAll("seriesName"),i=[];return Yi(n,function(t){var n=e.getDimensionInfo(t);n.displayName&&i.push(n.displayName)}),i.join(" ")}(t)||e)}function c_(t){return t.model.getRawData().count()}function u_(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),d_}function d_(t,e){e.outputData&&t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function h_(t,e){Yi(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 I_(t,e,n,i){var r=t[e];if(r){var o=r[k_]||r,a=r[T_];if(r[M_]!==n||a!==i){if(null==n||!i)return t[e]=o;(r=t[e]=A_(o,n,"debounce"===i))[k_]=o,r[T_]=i,r[M_]=n}return r}}function D_(t,e){var n=t[e];n&&n[k_]&&(n.clear&&n.clear(),t[e]=n[k_])}var P_=Mc(),L_={itemStyle:Vc(ug,!0),lineStyle:Vc(sg,!0)},E_={lineStyle:"stroke",itemStyle:"fill"};function N_(t,e){var n=t.visualStyleMapper||L_[e];return n||(console.warn("Unknown style type '"+e+"'."),L_.itemStyle)}function R_(t,e){var n=t.visualDrawType||E_[e];return n||(console.warn("Unknown style type '"+e+"'."),"fill")}var O_={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=t.getModel(i),o=N_(t,i)(r),a=r.getShallow("decal");a&&(n.setVisual("decal",a),a.dirty=!0);var s=R_(t,i),l=o[s],c=ir(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||ir(o.fill)?d:o.fill,o.stroke="auto"===o.stroke||ir(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=ji({},o);r[s]=c(i),e.setItemVisual(n,"style",r)}}}},z_=new pg,H_={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){if(!t.ignoreStyleOnData&&!e.isSeriesFiltered(t)){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=N_(t,i),o=n.getVisual("drawType");return{dataEach:n.hasItemOption?function(t,e){var n=t.getRawDataItem(e);if(n&&n[i]){z_.option=n[i];var a=r(z_);ji(t.ensureUniqueItemVisual(e,"style"),a),z_.option.decal&&(t.setItemVisual(e,"decal",z_.option.decal),z_.option.decal.dirty=!0),o in a&&t.setItemVisual(e,"colorFromPalette",!1)}}:null}}}},B_={performRawSeries:!0,overallReset:function(t){var e=Mr();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)),P_(t).scope=r}}),t.eachSeries(function(e){if(!e.isColorBySeries()&&!t.isSeriesFiltered(e)){var n=e.getRawData(),i={},r=e.getData(),o=P_(e).scope,a=e.visualStyleAccessPath||"itemStyle",s=R_(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)}})}})}},F_=Math.PI;var $_=function(){function t(t,e,n,i){this._stageTaskMap=Mr(),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=Mr();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;Yi(this._allHandlers,function(i){var r=t.get(i.uid)||t.set(i.uid,{});yr(!(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))}Yi(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=Mr(),s=t.seriesType,l=t.getTargetSeries;function c(e){var s=e.uid,l=a.set(s,o&&o.get(s)||gy({plan:U_,reset:G_,count:Z_}));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||gy({reset:V_});o.context={ecModel:n,api:i,overallReset:t.overallReset,scheduler:r};var a=o.agentStubMap,s=o.agentStubMap=Mr(),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,gy({reset:W_,onDirty:q_})));n.context={model:t,overallProgress:u},n.agent=o,n.__block=u,r._pipe(t,n)}yr(!t.createOnAllSeries,""),l?n.eachRawSeriesByType(l,h):c?c(n,i).each(h):(u=!1,Yi(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 ir(t)&&(t={overallReset:t,seriesType:K_(t)}),t.uid=gg("stageHandler"),e&&(t.visualType=e),t},t}();function V_(t){t.overallReset(t.ecModel,t.api,t.payload)}function W_(t){return t.overallProgress&&j_}function j_(){this.agent.dirty(),this.getDownstream().dirty()}function q_(){this.agent&&this.agent.dirty()}function U_(t){return t.plan?t.plan(t.model,t.ecModel,t.api,t.payload):null}function G_(t){t.useClearVisual&&t.data.clearAllVisual();var e=t.resetDefines=fc(t.reset(t.model,t.ecModel,t.api,t.payload));return e.length>1?Zi(e,function(t,e){return Y_(e)}):X_}var X_=Y_(0);function Y_(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}(),cb=["symbol","symbolSize","symbolRotate","symbolOffset"],ub=cb.concat(["symbolKeepAspect"]),db={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&&Ab(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=Ab(i)?i:0,r=Ab(r)?r:1,o=Ab(o)?o:0,a=Ab(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]:ar(e)?[e]:nr(e)?e:null:null),o=i.lineDashOffset;if(r){var a=i.strokeNoScale&&t.getLineScale?t.getLineScale():1;a&&1!==a&&(r=Zi(r,function(t){return t/a}),o/=a)}return[r,o]}var Eb=new Ju(!0);function Nb(t){var e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))}function Rb(t){return"string"==typeof t&&"none"!==t}function Ob(t){var e=t.fill;return null!=e&&"none"!==e}function zb(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 Hb(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 Bb(t,e,n){var i=Gc(e.image,e.__image,n);if(Yc(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)*Dr),o.scaleSelf(e.scaleX||1,e.scaleY||1),r.setTransform(o)}return r}}var Fb=["shadowBlur","shadowOffsetX","shadowOffsetY"],$b=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function Vb(t,e,n,i,r){var o=!1;if(!i&&e===(n=n||{}))return!1;if(i||e.opacity!==n.opacity){qb(t,r),o=!0;var a=Math.max(Math.min(e.opacity,1),0);t.globalAlpha=isNaN(a)?gu.opacity:a}(i||e.blend!==n.blend)&&(o||(qb(t,r),o=!0),t.globalCompositeOperation=e.blend||gu.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[ax])if(this._disposed)this.id;else{var i,r,o;if(sr(e)&&(n=e.lazyUpdate,i=e.silent,r=e.replaceMerge,o=e.transition,e=e.notMerge),this[ax]=!0,Nx(this),!this._model||e){var a=new vv(this._api),s=this._theme,l=this._model=new uv;l.scheduler=this._scheduler,l.ssr=this._ssr,l.init(null,null,null,s,this._locale,a)}this._model.setOption(t,{replaceMerge:r},jx);var c={seriesTransition:o,optionChanged:!0};if(n)this[lx]={silent:i,updateParams:c},this[ax]=!1,this.getZr().wakeUp();else{try{gx(this),yx.update.call(this,null,c)}catch(t){throw this[lx]=null,this[ax]=!1,t}this._ssr||this._zr.flush(),this[lx]=null,this[ax]=!1,Sx.call(this,i),Cx.call(this,i)}}},e.prototype.setTheme=function(t,e){if(!this[ax])if(this._disposed)this.id;else{var n=this._model;if(n){var i=e&&e.silent,r=null;this[lx]&&(null==i&&(i=this[lx].silent),r=this[lx].updateParams,this[lx]=null),this[ax]=!0,Nx(this);try{this._updateTheme(t),n.setTheme(this._theme),gx(this),yx.update.call(this,{type:"setTheme"},r)}catch(t){throw this[ax]=!1,t}this[ax]=!1,Sx.call(this,i),Cx.call(this,i)}}},e.prototype._updateTheme=function(t){rr(t)&&(t=Ux[t]),t&&((t=Vi(t))&&Hv(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||xi.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 Yi(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;Yi(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 Yi(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(Yx[n]){var a=o,s=o,l=-1/0,c=-1/0,u=[],d=t&&t.pixelRatio||this.getDevicePixelRatio();Yi(Xx,function(o,d){if(o.group===n){var h=e?o.getZr().painter.getSvgDom().innerHTML:o.renderToCanvas(Vi(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=Ti.createCanvas(),g=Vl(f,{renderer:e?"svg":"canvas"});if(g.resize({width:h,height:p}),e){var m="";return Yi(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 Ld({shape:{x:0,y:0,width:h,height:p},style:{fill:t.connectedBackgroundColor}})),Yi(u,function(t){var e=new kd({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 _x(this,"convertToPixel",t,e,n)},e.prototype.convertToLayout=function(t,e,n){return _x(this,"convertToLayout",t,e,n)},e.prototype.convertFromPixel=function(t,e,n){return _x(this,"convertFromPixel",t,e,n)},e.prototype.containPixel=function(t,e){var n;if(!this._disposed)return Yi(Ac(this._model,t),function(t,i){i.indexOf("Models")>=0&&Yi(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=Ac(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;Yi(Bx,function(e){var n=function(n){var i,r=t.getModel(),o=n.target;if("globalout"===e?i={}:o&&fb(o,function(t){var e=Yd(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=ji({},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;Yi(Vx,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?(pb("map","selectchanged",e,i,t),pb("pie","selectchanged",e,i,t)):"select"===t.fromAction?(pb("map","selected",e,i,t),pb("pie","selected",e,i,t)):"unselect"===t.fromAction&&(pb("map","unselected",e,i,t),pb("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()&&Lc(this.getDom(),Kx,"");var t=this,e=t._api,n=t._model;Yi(t._componentsViews,function(t){t.dispose(n,e)}),Yi(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 Xx[t.id]}},e.prototype.resize=function(t){if(!this[ax])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[lx]&&(null==i&&(i=this[lx].silent),n=!0,this[lx]=null),this[ax]=!0,Nx(this);try{n&&gx(this),yx.update.call(this,{type:"resize",animation:ji({duration:0},t&&t.animation)})}catch(t){throw this[ax]=!1,t}this[ax]=!1,Sx.call(this,i),Cx.call(this,i)}}},e.prototype.showLoading=function(t,e){if(this._disposed)this.id;else if(sr(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),Gx[t]){var n=Gx[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=ji({},t);return e.type=$x[t.type],e},e.prototype.dispatchAction=function(t,e){if(this._disposed)this.id;else if(sr(e)||(e={silent:!!e}),Fx[t.type]&&this._model)if(this[ax])this._pendingActions.push(t);else{var n=e.silent;xx.call(this,t,n);var i=e.flush;i?this._zr.flush():!1!==i&&xi.browser.weChat&&this._throttledZrFlush(),Sx.call(this,n),Cx.call(this,n)}},e.prototype.updateLabelLayout=function(){ex.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(lf(t))return;if(t instanceof bd&&function(t){var e=Qd(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)}})}gx=function(t){var e=t._scheduler;e.restorePipelines(t._model),e.prepareStageTasks(),mx(t,!0),mx(t,!1),e.plan()},mx=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")&&!xi.node&&!xi.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),ex.trigger("series:afterupdate",e,o,s)},Lx=function(t){t[cx]=!0,t.getZr().wakeUp()},Nx=function(t){t[sx]=(t[sx]+1)%1e3},Ex=function(t){t[cx]&&(t.getZr().storage.traverse(function(t){lf(t)||e(t)}),t[cx]=!1)},Dx=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){Sh(e,n),Lx(t)},n.prototype.leaveEmphasis=function(e,n){Ch(e,n),Lx(t)},n.prototype.enterBlur=function(e){!function(t){vh(t,hh)}(e),Lx(t)},n.prototype.leaveBlur=function(e){kh(e),Lx(t)},n.prototype.enterSelect=function(e){Mh(e),Lx(t)},n.prototype.leaveSelect=function(e){Th(e),Lx(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[sx]},n}(gv))(t)},Px=function(t){function e(t,e){for(var n=0;n=0)){ow.push(n);var o=$_.wrapStageHandler(n,r);o.__prio=e,o.__raw=n,t.push(o)}}function sw(t,e){Gx[t]=e}var lw=function(t){var e=(t=Vi(t)).type;e||dc("");var n=e.split(":");2!==n.length&&dc("");var i=!1;"echarts"===n[0]&&(e=n[1],i=!0),t.__isBuiltIn=i,ky.set(e,t)};function cw(t,e,n,i){return{eventContent:{selected:Nh(n),isFromClick:e.isFromClick||!1}}}function uw(t){return null==t?0:t.length||1}function dw(t){return t}rw(ix,O_),rw(rx,H_),rw(rx,B_),rw(ix,db),rw(rx,hb),rw(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=Kb(n,e))});var r=i.getVisual("decal");if(r)i.getVisual("style").decal=Kb(r,e)}})}),tw(Hv),ew(900,function(t){var e=Mr();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(),Yi(t,function(e,n){e.data.setCalculationInfo("stackedOnSeries",n>0?t[n-1].seriesModel:null)}),function(t){Yi(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=Ql(p,v),f=v;break}}}return i[0]=p,i[1]=f,i})})}(t))})}),sw("default",function(t,e){qi(e=e||{},{text:"loading",textColor:Lm.color.primary,fontSize:12,fontWeight:"normal",fontStyle:"normal",fontFamily:"sans-serif",maskColor:"rgba(255,255,255,0.8)",showSpinner:!0,color:Lm.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new zl,i=new Ld({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});n.add(i);var r,o=new Od({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 Ld({style:{fill:"none"},textContent:o,textConfig:{position:"right",distance:10},zlevel:e.zlevel,z:10001});return n.add(a),e.showSpinner&&((r=new $p({shape:{startAngle:-F_/2,endAngle:-F_/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*F_/2}).start("circularInOut"),r.animateShape(!0).when(1e3,{startAngle:3*F_/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}),iw({type:nh,event:nh,update:nh},Ir),iw({type:ih,event:ih,update:ih},Ir),iw({type:rh,event:sh,update:rh,action:Ir,refineEvent:cw,publishNonRefinedEvent:!0}),iw({type:oh,event:sh,update:oh,action:Ir,refineEvent:cw,publishNonRefinedEvent:!0}),iw({type:ah,event:sh,update:ah,action:Ir,refineEvent:cw,publishNonRefinedEvent:!0}),Jx("default",{}),Jx("dark",sb);var hw=function(){function t(t,e,n,i,r,o){this._old=t,this._new=e,this._oldKeyGetter=n||dw,this._newKeyGetter=i||dw,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 Sw,Cw,kw,Mw,Tw,Aw,Iw,Dw=sr,Pw=Zi,Lw="undefined"==typeof Int32Array?Array:Int32Array,Ew=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],Nw=["_approximateExtent"],Rw=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;_w(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===Vm&&!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&&(nr(r=this.getVisual(e))?r=r.slice():Dw(r)&&(r=ji({},r)),i[e]=r),r},t.prototype.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{};this._itemVisuals[t]=i,Dw(e)?ji(i,e):i[e]=n},t.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},t.prototype.setLayout=function(t,e){Dw(t)?ji(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?ji(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=Yd(i);r.dataIndex=n,r.dataType=e,r.seriesIndex=t,r.ssrType="chart","group"===i.type&&i.traverse(function(i){var r=Yd(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){Yi(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:Pw(this.dimensions,this._getDimInfo,this),this.hostModel)),Tw(e,this),e._store=this._store,e},t.prototype.wrapMethod=function(t,e){var n=this[t];ir(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(t),this[t]=function(){var t=n.apply(this,arguments);return e.apply(this,[t].concat(mr(arguments)))})},t.internalField=(Sw=function(t){var e=t._invertedIndicesMap;Yi(e,function(n,i){var r=t._dimInfos[i],o=r.ordinalMeta,a=t._store;if(o){n=e[i]=new Lw(o.categories.length);for(var s=0;s1&&(s+="__ec__"+c),i[e]=s}})),t}();function Ow(t,e){Uv(t)||(t=Xv(t));var n=(e=e||{}).coordDimensions||[],i=e.dimensionsDefine||t.dimensionsDefine||[],r=Mr(),o=[],a=function(t,e,n,i){var r=Math.max(t.dimensionsDetectedCount||1,e.length,n.length,i||0);return Yi(e,function(t){var e;sr(t)&&(e=t.dimsDef)&&(r=Math.max(r,e.length))}),r}(t,n,i,e.dimensionsCount),s=e.canOmitUnusedDimensions&&ww(a),l=i===t.dimensionsDefine,c=l?xw(t):bw(i),u=e.encodeDefine;!u&&e.encodeDefaulter&&(u=e.encodeDefaulter(t,a));for(var d=Mr(u),h=new Ly(a),p=0;p0&&(i.name=r+(o-1)),o++,e.set(r,o)}}(o),new yw({source:t,dimensions:o,fullDimensionCount:a,dimensionOmitted:s})}function zw(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 Hw=function(t){this.coordSysDims=[],this.axisMap=Mr(),this.categoryAxisMap=Mr(),this.coordSysName=t};var Bw={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis",Dc).models[0],o=t.getReferringComponents("yAxis",Dc).models[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",o),Fw(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),Fw(o)&&(i.set("y",o),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis",Dc).models[0];e.coordSysDims=["single"],n.set("single",r),Fw(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar",Dc).models[0],o=r.findAxisModel("radiusAxis"),a=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",o),n.set("angle",a),Fw(o)&&(i.set("radius",o),e.firstCategoryDimIndex=0),Fw(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();Yi(o.parallelAxisIndex,function(t,o){var s=r.getComponent("parallelAxis",t),l=a[o];n.set(l,s),Fw(s)&&(i.set(l,s),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=o))})},matrix:function(t,e,n,i){var r=t.getReferringComponents("matrix",Dc).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 Fw(t){return"category"===t.get("type")}function $w(t,e,n){var i,r,o,a=(n=n||{}).byIndex,s=n.stackedCoordDimension;!function(t){return!_w(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(Yi(i,function(t,e){rr(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;Yi(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 Vw(t,e){return!!e&&e===t.getCalculationInfo("stackedDimension")}function Ww(t,e,n){n=n||{};var i,r,o=e.getSourceManager();r=(i=o.getSource()).sourceFormat===Vm;var a=function(t){var e=t.get("coordinateSystem"),n=new Hw(e),i=Bw[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}(e),s=function(t,e){var n,i=t.get("coordinateSystem"),r=hm.get(i);return e&&e.coordSysDims&&(n=Zi(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=ir(l)?l:l?er(tv,s,e):null,u=Ow(i,{coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:e.getEncode(),encodeDefaulter:c,canOmitUnusedDimensions:!r}),d=function(t,e,n){var i,r;return n&&Yi(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=$w(e,{schema:u,store:h}),f=new Rw(u,e);f.setCalculationInfo(p);var g=null!=d&&function(t){if(t.sourceFormat===Vm){var e=function(t){var e=0;for(;er&&(a=o.interval=r);var s=o.intervalPrecision=Gw(a);return function(t,e){!isFinite(t[0])&&(t[0]=e[0]),!isFinite(t[1])&&(t[1]=e[1]),Xw(t,0,e),Xw(t,1,e),t[0]>t[1]&&(t[0]=t[1])}(o.niceTickExtent=[Zl(Math.ceil(t[0]/a)*a,s),Zl(Math.floor(t[1]/a)*a,s)],t),o}function Uw(t){var e=Math.pow(10,ic(t)),n=t/e;return n?2===n?n=3:3===n?n=5:n*=2:n=1,Zl(n*e)}function Gw(t){return Kl(t)+2}function Xw(t,e,n){t[e]=Math.max(Math.min(t[e],n[1]),n[0])}function Yw(t,e){return t>=e[0]&&t<=e[1]}var Zw=function(){function t(){this.normalize=Kw,this.scale=Qw}return t.prototype.updateMethods=function(t){t.hasBreaks()?(this.normalize=tr(t.normalize,t),this.scale=tr(t.scale,t)):(this.normalize=Kw,this.scale=Qw)},t}();function Kw(t,e){return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])}function Qw(t,e){return t*(e[1]-e[0])+e[0]}function Jw(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 tS=function(){function t(t){this._calculator=new Zw,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}();$c(tS);var eS=0,nS=function(){function t(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this.uid=++eS,this._onCollect=t.onCollect}return t.createByAxisModel=function(e){var n=e.option,i=n.data,r=i&&Zi(i,iS);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(!rr(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=Mr(this.categories))},t}();function iS(t){return sr(t)&&null!=t.value?t.value:t+""}var rS=function(t){function e(e){var n=t.call(this,e)||this;n.type="ordinal";var i=n.getSetting("ordinalMeta");return i||(i=new nS({})),nr(i)&&(i=new nS({categories:Zi(i,function(t){return sr(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:rr(t)?this._ordinalMeta.getOrdinal(t):Math.round(t)},e.prototype.contain=function(t){return Yw(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}(tS);tS.registerClass(rS);var oS=Zl,aS=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 Yw(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=Gw(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=oS(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:oS(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 Yi(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=Xl(t.get("barWidth"),i),p=Xl(t.get("barMaxWidth"),i),f=Xl(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:dS(r),stackId:uS(t)})}),function(t){var e={};Yi(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 Yi(e,function(t,e){n[e]={};var i=t.stacks,r=t.bandWidth,o=t.categoryGap;if(null==o){var a=Ji(i).length;o=Math.max(35-4*a,15)+"%"}var s=Xl(o,r),l=Xl(t.gap,1),c=t.remainedWidth,u=t.autoWidthCount,d=(c-s)/(u+(u-1)*l);d=Math.max(d,0),Yi(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;Yi(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;Yi(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 pS=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 Bg(t.value,Lg[function(t){switch(t){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}(zg(this._minLevelUnit))]||Lg.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(rr(n))o=n;else if(ir(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=Fg(t.value,r);o=n[u][u][0]}}return Bg(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=Fg(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=Ng,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 $g(new Date(e),t,i).getTime()===$g(new Date(n),t,i).getTime()}(zg(t),i[0],i[1],n)){s&&(r=[{value:bS(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=Qi(Zi(d,function(t){return Qi(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=fS.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 mS(t){return(t/=2592e6)>6?6:t>3?3:t>2?2:1}function vS(t){return(t/=Mg)>12?12:t>6?6:t>3.5?4:t>2?2:1}function yS(t,e){return(t/=e?kg:Cg)>30?30:t>20?20:t>15?15:t>10?10:t>5?5:t>2?2:1}function _S(t){return rc(t)}function bS(t,e,n){var i=Math.max(0,Ui(Eg,e)-1);return $g(new Date(t),Eg[i],n).getTime()}tS.registerClass(pS);var xS=Zl,wS=Math.floor,SS=Math.ceil,CS=Math.pow,kS=Math.log,MS=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="log",e.base=10,e._originalScale=new aS,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(),Zi(r,function(t){var e=t.value,r=null,a=CS(o,e);return e===n[0]&&this._fixMin?r=i[0]:e===n[1]&&this._fixMax&&(r=i[1]),null!=r&&(a=TS(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=Jw(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]=CS(e,n[0]),n[1]=CS(e,n[1]);var i=this._originalScale.getExtent();return this._fixMin&&(n[0]=TS(n[0],i[0])),this._fixMax&&(n[1]=TS(n[1],i[1])),n},e.prototype.unionExtentFromData=function(t,e){this._originalScale.unionExtentFromData(t,e);var n=Jw(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,ic(i)));for(t/n*r<=.5&&(r*=10);!isNaN(r)&&Math.abs(r)<1&&Math.abs(r)>0;)r*=10;var o=[xS(SS(e[0]/r)*r),xS(wS(e[1]/r)*r)];this._interval=r,this._intervalPrecision=Gw(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=kS(e)/kS(this.base),t.prototype.contain.call(this,e)},e.prototype.normalize=function(e){return e=kS(e)/kS(this.base),t.prototype.normalize.call(this,e)},e.prototype.scale=function(e){return e=t.prototype.scale.call(this,e),CS(this.base,e)},e.prototype.setBreaksFromOption=function(t){},e.type="log",e}(aS);function TS(t,e){return xS(t,Kl(e))}tS.registerClass(MS);var AS=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[DS[t]]=e},t.prototype.setDeterminedMinMax=function(t,e){this[IS[t]]=e},t.prototype.freeze=function(){this.frozen=!0},t}(),IS={min:"_determinedMin",max:"_determinedMax"},DS={min:"_dataMin",max:"_dataMax"};function PS(t,e){return null==e?null:hr(e)?NaN:t.parse(e)}function LS(t,e){var n=t.type,i=function(t,e,n){var i=t.rawExtentInfo;return i||(i=new AS(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(Yi(s,function(t){l=l||t.getBaseAxis()===e.axis}),l){var c=hS(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[dS(e)]}(i,n.axis);if(void 0===a)return{min:t,max:e};var s=1/0;Yi(a,function(t){s=Math.min(t.offset,s)});var l=-1/0;Yi(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 ES(t,e){var n=e,i=LS(t,n),r=i.extent,o=n.get("splitNumber");t instanceof MS&&(t.base=n.get("logBase"));var a=t.type,s=n.get("interval"),l="interval"===a||"time"===a;t.setBreaksFromOption($S(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 NS(t){var e=t.getLabelModel().get("formatter");if("time"===t.type){var n=Rg(e);return function(e,i){return t.scale.getFormattedLabel(e,i,n)}}if(rr(e))return function(n){var i=t.scale.getLabel(n);return e.replace("{value}",null!=i?i:"")};if(ir(e)){if("category"===t.type)return function(n,i){return e(RS(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(RS(t,n),r,o)}}return function(e){return t.scale.getLabel(e)}}function RS(t,e){return"category"===t.type?t.scale.getLabel(e):e.value}function OS(t){var e=t.get("interval");return null==e?"auto":e}function zS(t){return"category"===t.type&&0===OS(t.getLabelModel())}function HS(t,e){var n={};return Yi(t.mapDimensionsAll(e),function(e){n[function(t,e){return Vw(t,e)?t.getCalculationInfo("stackResultDimension"):e}(t,e)]=!0}),Ji(n)}function BS(t){return"middle"===t||"center"===t}function FS(t){return t.getShallow("show")}function $S(t){t.get("breaks",!0)}var VS=function(){function t(){}return t.prototype.getNeedCrossZero=function(){return!this.option.scale},t.prototype.getCoordSysModel=function(){},t}(),WS=[],jS={registerPreprocessor:tw,registerProcessor:ew,registerPostInit:function(t){nw("afterinit",t)},registerPostUpdate:function(t){nw("afterupdate",t)},registerUpdateLifecycle:nw,registerAction:iw,registerCoordinateSystem:function(t,e){hm.register(t,e)},registerLayout:function(t,e){aw(qx,t,e,1e3,"layout")},registerVisual:rw,registerTransform:lw,registerLoading:sw,registerMap:function(t,e,n){var i=nx["registerMap"];i&&i(t,e,n)},registerImpl:function(t,e){nx[t]=e},PRIORITY:ox,ComponentModel:Pm,ComponentView:g_,SeriesModel:s_,ChartView:__,registerComponentModel:function(t){Pm.registerClass(t)},registerComponentView:function(t){g_.registerClass(t)},registerSeriesModel:function(t){s_.registerClass(t)},registerChartView:function(t){__.registerClass(t)},registerCustomSeries:function(t,e){},registerSubTypeDefaulter:function(t,e){Pm.registerSubTypeDefaulter(t,e)},registerPainter:function(t,e){var n;n=e,Hl[t]=n}};function qS(t){nr(t)?Yi(t,function(t){qS(t)}):Ui(WS,t)>=0||(WS.push(t),ir(t)&&(t={install:t}),t.install(jS))}var US=Mc(),GS=Mc(),XS=1,YS=2;function ZS(t){return{out:{noPxChangeTryDetermine:[]},kind:t}}function KS(t,e){var n=Zi(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 QS(t,e){var n=t.getLabelModel().get("customValues");if(n){var i=NS(t),r=t.scale.getExtent();return{labels:Zi(Qi(KS(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=tC(t,n,e);return!n.get("show")||t.scale.isBlank()?{labels:[]}:i}(t,e):function(t){var e=t.scale.getTicks(),n=NS(t);return{labels:Zi(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 JS(t,e,n){var i=t.getTickModel().get("customValues");if(i){var r=t.scale.getExtent();return{ticks:Qi(KS(t,i),function(t){return t>=r[0]&&t<=r[1]})}}return"category"===t.type?function(t,e){var n,i,r=eC(t),o=OS(e),a=rC(r,o);if(a)return a;e.get("show")&&!t.scale.isBlank()||(n=[]);if(ir(o))n=cC(t,o,!0);else if("auto"===o){var s=tC(t,t.getLabelModel(),ZS(YS));i=s.labelCategoryInterval,n=Zi(s.labels,function(t){return t.tickValue})}else n=lC(t,i=o,!0);return oC(r,o,{ticks:n,tickCategoryInterval:i})}(t,e):{ticks:Zi(t.scale.getTicks(n),function(t){return t.value})}}function tC(t,e,n){var i,r,o=nC(t),a=OS(e),s=n.kind===XS;if(!s){var l=rC(o,a);if(l)return l}ir(a)?i=cC(t,a):(r="auto"===a?function(t,e){if(e.kind===XS){var n=t.calculateCategoryInterval(e);return e.out.noPxChangeTryDetermine.push(function(){return GS(t).autoInterval=n,!0}),n}var i=GS(t).autoInterval;return null!=i?i:GS(t).autoInterval=t.calculateCategoryInterval(e)}(t,n):a,i=lC(t,r));var c={labels:i,labelCategoryInterval:r};return s?n.out.noPxChangeTryDetermine.push(function(){return oC(o,a,c),!0}):oC(o,a,c),c}var eC=iC("axisTick"),nC=iC("axisLabel");function iC(t){return function(e){return GS(e)[t]||(GS(e)[t]={list:[]})}}function rC(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 lC(t,e,n){var i=NS(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=zS(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 cC(t,e,n){var i=t.scale,r=NS(t),o=[];return Yi(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 uC=[0,1],dC=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(Ul(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&&hC(n=n.slice(),i.count()),Gl(t,uC,n,e)},t.prototype.coordToData=function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&hC(n=n.slice(),i.count());var r=Gl(t,n,uC,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=Zi(JS(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;Yi(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=Zl(t),e=Zl(e),d?t>e:t0&&t<100||(t=5),Zi(this.scale.getMinorTicks(t),function(t){return Zi(t,function(t){return{coord:this.dataToCoord(t),tickValue:t}},this)},this)},t.prototype.getViewLabels=function(t){return QS(this,t=t||ZS(YS)).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=NS(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=bl(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===XS)return e.out.noPxChangeTryDetermine.push(tr(aC,null,t,x,l)),x;var w=sC(t,x,l);return null!=w?w:x}(this,t=t||ZS(YS))},t}();function hC(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}var pC=["label","labelLine","layoutOption","priority","defaultAttr","marginForce","minMarginForce","marginDefault","suggestIgnore"];function fC(t,e,n){n=n||3,e?t.dirty|=n:t.dirty&=~n}function gC(t,e){return e=e||3,null==t.dirty||!!(t.dirty&e)}function mC(t){if(t)return gC(t)&&function(t,e,n){var i=e.getComputedTransform();t.transform=Hf(t.transform,i);var r=t.localRect=zf(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=ng.textMargin);for(var d=0;d<4;d++)vC[d]=u===ng.minMargin&&l&&null!=l[d]?l[d]:s&&null!=s[d]?s[d]:a?a[d]:0;u===ng.textMargin&&If(r,vC,!1,!1);var h=t.rect=zf(t.rect,r);i&&h.applyTransform(i);u===ng.minMargin&&If(h,vC,!1,!1);t.axisAligned=Rf(i),(t.label=t.label||{}).ignore=e.ignore,fC(t,!1),fC(t,!0,2)}(t,t.label,t),t}var vC=[0,0,0,0];function yC(t,e){for(var n=0;n-1&&(s.style.stroke=s.style.fill,s.style.fill=Lm.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}(s_);function wC(t,e){var n=t.mapDimensionsAll("defaultedLabel"),i=n.length;if(1===i){var r=dy(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),Oh(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=Yd(this).dataIndex,o=n&&n.animation;if(this.silent=i.silent=!0,n&&n.fadeLabel){var a=i.getTextContent();a&&cf(a,{style:{opacity:0}},e,{dataIndex:r,removeOpt:o,cb:function(){i.removeTextContent()}})}else i.removeTextContent();cf(i,{style:{opacity:0},scaleX:0,scaleY:0},e,{dataIndex:r,cb:t,removeOpt:o})},e.getSymbolSize=function(t,e){return nr(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}(zl);function CC(t,e){this.parent.drift(t,e)}function kC(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 MC(t){return null==t||sr(t)||(t={isIgnore:t}),t||{}}function TC(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:Uf(e),cursorStyle:e.get("cursor")}}var AC=function(){function t(t){this.group=new zl,this._SymbolCtor=t||SC}return t.prototype.updateData=function(t,e){this._progressiveEls=null,e=MC(e);var n=this.group,i=t.hostModel,r=this._data,o=this._SymbolCtor,a=e.disableAnimation,s=TC(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(kC(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(kC(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):af(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=TC(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=MC(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=Zi(t.dimensions,function(t){return e.mapDimension(t)}),h=!1,p=e.getCalculationInfo("stackResultDimension");return Vw(e,d[0])&&(h=!0,d[0]=p),Vw(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 DC(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 PC=Math.min,LC=Math.max;function EC(t,e){return isNaN(t)||isNaN(e)}function NC(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(EC(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||EC(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=PC(A=v+M*a*k,LC(w,v)),I=PC(I,LC(S,y)),A=LC(A,PC(w,v)),f=y-(T=(I=LC(I,PC(S,y)))-y)*N/R,p=PC(p=v-(M=A-v)*N/R,LC(c,v)),f=PC(f,LC(u,y)),A=v+(M=v-(p=LC(p,PC(c,v))))*R/N,I=y+(T=y-(f=LC(f,PC(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 RC=function(){this.smooth=0,this.smoothConstraint=!0},OC=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:Lm.color.neutral99,fill:null}},e.prototype.getDefaultShape=function(){return new RC},e.prototype.buildPath=function(t,e){var n=e.points,i=0,r=n.length/2;if(e.connectNulls){for(;r>0&&EC(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?xa(n,c,d,p,t,s):xa(i,u,h,f,t,s);if(v>0)for(var y=0;y=0){m=a?_a(i,u,h,f,_):_a(n,c,d,p,_);return a?[t,m]:[m,t]}}n=p,i=f}}},e}(bd),zC=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e}(RC),HC=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 zC},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&&EC(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=Xa(e[r]),s=Xa(e[o]),l=i-r,c=Qa([za(Va(a[0],s[0],l)),za(Va(a[1],s[1],l)),za(Va(a[2],s[2],l)),Ha(Va(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 qC(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 Yi(o.getViewLabels(),function(t){var e=o.scale.getRawOrdinalNumber(t.tickValue);s[e]=1}),function(t){return!s.hasOwnProperty(e.get(a,t))}}}}function UC(t,e){return isNaN(t)||isNaN(e)}function GC(t,e){return[t[2*e],t[2*e+1]]}function XC(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=Zi(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=jC(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";Yi(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 jp(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,cm(M));var T=f.getClipPath();if(T)sf(T,{shape:YC(this,i,!1,t).shape},t);else f.setClipPath(YC(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]]}}),BC(this._stackedOnPoints,_)&&BC(this._points,l)||(g?this._doUpdateAnimation(o,_,i,n,k,v,x):(k&&(_&&(_=WC(_,l,i,k,x)),l=WC(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&&(_&&(_=WC(_,l,i,k,x)),l=WC(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,cm(M)),f.setClipPath(YC(this,i,!0,t));var A=t.getModel("emphasis"),I=A.get("focus"),D=A.get("blurScope"),P=A.get("disabled");(h.useStyle(qi(a.getLineStyle(),{fill:"none",stroke:M,lineJoin:"bevel"})),Bh(h,t,"lineStyle"),h.style.lineWidth>0&&"bolder"===t.get(["emphasis","lineStyle","width"]))&&(h.getState("emphasis").style.lineWidth=+h.style.lineWidth+1);Yd(h).seriesIndex=t.seriesIndex,Oh(h,I,D,P);var L=VC(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(qi(s.getAreaStyle(),{fill:M,opacity:.7,lineJoin:"bevel",decal:o.getVisual("style").decal})),N&&(R=VC(N.get("smooth"))),p.setShape({smooth:L,stackedOnSmooth:R,smoothMonotone:E,connectNulls:x}),Bh(p,t,"areaStyle"),Yd(p).seriesIndex=t.seriesIndex,Oh(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){Yd(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=kc(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 SC(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 __.prototype.highlight.call(this,t,e,n,i)},e.prototype.downplay=function(t,e,n,i){var r=t.getData(),o=kc(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 __.prototype.downplay.call(this,t,e,n,i)},e.prototype._changePolyState=function(t){var e=this._polygon;yh(this._polyline,t),e&&yh(e,t)},e.prototype._newPolyline=function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new OC({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 HC({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");ir(l)&&(l=l(null));var c=s.get("animationDelay")||0,u=ir(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 _=ir(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(XC(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 Od({z2:200})).ignoreClip=!0,o.setTextContent(this._endLabel),o.disableLabelAnimation=!0);var l=function(t){for(var e=t.length/2;e>0&&UC(t[2*e-2],t[2*e-1]);e--);return e-1}(a);l>=0&&(qf(o,Uf(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(!nr(e))return e+"";for(var i=[],r=0;r=0&&i.push(e[o])}return i.join(" ")}(r,n):wC(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=GC(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(ar(i))return Zl(f=hc(n||0,i,r),o?Math.max(Kl(n||0),Kl(i)):e);if(rr(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=GC(c,I);r&&(k=u.getRawValue(I)),s.attr({x:M[0]+_,y:M[1]+b})}if(r){var D=eg(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=IC(r,e,a),m=t.getLayout("points")||[],v=e.getLayout("points")||[],y=0;y3e3||l&&$C(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(),af(s,g,c),l&&(l.setShape({points:d,stackedOnPoints:h}),l.stopAnimation(),af(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}(dC),gk="expandAxisBreak",mk=Math.PI,vk=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],yk=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],_k=Mc(),bk=Mc(),xk=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 wk=[1,0,0,1,0,0],Sk=new Ro(0,0,0,0),Ck=function(t,e,n,i,r,o){if(BS(t.nameLocation)){var a=o.stOccupiedRect;a&&kk(function(t,e,n){return t.transform=Hf(t.transform,n),t.localRect=zf(t.localRect,e),t.rect=zf(t.rect,e),n&&t.rect.applyTransform(n),t.axisAligned=Rf(n),t.obb=void 0,(t.label=t.label||{}).ignore=!1,t}({},a,o.transGroup.transform),i,r)}else Mk(o.labelInfoList,o.dirVec,i,r)};function kk(t,e,n){var i=new xo;bC(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 Mk(t,e,n,i){for(var r=xo.dot(i,e)>=0,o=0,a=t.length;o0?"top":"bottom",i="center"):tc(o-mk)?(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}(),Ak=["axisLine","axisTickLabelEstimate","axisTickLabelDetermine","axisName"],Ik={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&&(Fr(u,u,c),Fr(d,d,c));var p=ji({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 Rp(ji({shape:{x1:u[0],y1:u[1],x2:d[0],y2:d[1]}},f));xf(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"]);rr(m)&&(m=[m,m]),(rr(v)||ar(v))&&(v=[v,v]);var y=Tb(i.get(["axisLine","symbolOffset"])||0,v),_=v[0],b=v[1];Yi([{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=Mb(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){Ek(e,r,s)&&Dk(t,e,n,i,r,o,a,XS)},axisTickLabelDetermine:function(t,e,n,i,r,o,a,s){Ek(e,r,s)&&Dk(t,e,n,i,r,o,a,YS);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=Lk(r.getTicksCoords(),n.transform,l,qi(s.getLineStyle(),{stroke:i.get(["axisLine","lineStyle","color"])}),"ticks"),u=0;ui[1],l="start"===e&&!s||"start"!==e&&s;tc(a-mk/2)?(o=l?"bottom":"top",r="center"):tc(a-1.5*mk)?(o=l?"top":"bottom",r="center"):(o="middle",r=a<1.5*mk&&a>mk/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=pr(t.raw.nameTruncateMaxWidth,S.maxWidth,b),M=s.nameMarginLevel||0,T=new Od({x:m.x,y:m.y,rotation:_.rotation,silent:Tk.isLabelSilent(i),style:Gf(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(Lf({el:T,componentModel:i,itemName:c}),T.__fullText=c,T.anid="name",i.get("triggerEvent")){var A=Tk.makeAxisEventDataBase(i);A.targetType="axisName",A.name=c,Yd(T).eventData=A}o.add(T),T.updateTransform(),e.nameEl=T;var I=l.nameLayout=mC({label:T,priority:T.z2,defaultAttr:{ignore:T.ignore},marginDefault:BS(u)?vk[M]:yk[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 Dk(t,e,n,i,r,o,a,s){Nk(e)||function(t,e,n,i,r,o){var a=r.axis,s=pr(t.raw.axisLabelShow,r.get(["axisLabel","show"])),l=new zl;n.add(l);var c=ZS(i);if(!s||a.scale.isBlank())return void Rk(e,[],l,c);var u=r.getModel("axisLabel"),d=a.getViewLabels(c),h=(pr(t.raw.labelRotate,u.get("rotate"))||0)*mk/180,p=Tk.innerTextLayout(t.rotation,h,t.labelDirection),f=r.getCategories&&r.getCategories(!0),g=[],m=r.get("triggerEvent"),v=1/0,y=-1/0;Yi(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];sr(_)&&_.textStyle&&(h=new pg(_.textStyle,u,r.ecModel))}var b=h.getTextColor()||r.get(["axisLine","lineStyle","color"]),x=h.getShallow("align",!0)||p.textAlign,w=fr(h.getShallow("alignMinLabel",!0),x),S=fr(h.getShallow("alignMaxLabel",!0),x),C=h.getShallow("verticalAlign",!0)||h.getShallow("baseline",!0)||p.textVerticalAlign,k=fr(h.getShallow("verticalAlignMinLabel",!0),C),M=fr(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 Od({x:0,y:0,rotation:0,silent:Tk.isLabelSilent(r),z2:T,style:Gf(h,{text:s,align:0===e?w:e===d.length-1?S:x,verticalAlign:0===e?k:e===d.length-1?M:C,fill:ir(b)?b("category"===a.type?c:"value"===a.type?i+"":i,e):b})});A.anid="label_"+i;var I=_k(A);if(I.break=t.break,I.tickValue=i,I.layoutRotation=p.rotation,Lf({el:A,componentModel:r,itemName:s,formatterParamsExtra:{isTruncated:function(){return A.isTruncated},value:c,tickIndex:e}}),m){var D=Tk.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),Yd(A).eventData=D,t.break&&function(t,e,n,i){n.on("click",function(n){var r={type:gk,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 _=Zi(g,function(t){return{label:t,priority:_k(t).break?t.z2+(y-v+1):t.z2,defaultAttr:{ignore:t.ignore}}});Rk(e,_,l,c)}(t,e,r,s,i,a);var l=e.labelLayoutList;!function(t,e,n,i){var r=e.get(["axisLabel","margin"]);Yi(n,function(n,o){var a=mC(n);if(a){var s=a.label,l=_k(s);a.suggestIgnore=s.ignore,s.ignore=!1,pl(Ok,zk),Ok.x=e.axis.dataToCoord(l.tickValue),Ok.y=t.labelOffset+t.labelDirection*r,Ok.rotation=l.layoutRotation,i.add(Ok),Ok.updateTransform(),i.remove(Ok),Ok.decomposeTransform(),pl(s,Ok),s.markRedraw(),fC(a,!0),mC(a)}})}(t,i,l,o),t.rotation;var c=t.optionHideOverlap;!function(t,e,n){if(zS(t.axis))return;function i(t,i,r){var o=mC(e[i]),a=mC(e[r]);if(o&&a)if(!1===t||o.suggestIgnore)Pk(o.label);else if(a.suggestIgnore)Pk(a.label);else{var s=.1;if(!n){var l=[0,0,0,0];o=yC({marginForce:l},o),a=yC({marginForce:l},a)}bC(o,a,null,{touchThreshold:s})&&Pk(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 Ro(h,0,p,1))}a.stOccupiedRect=r,a.labelInfoList=s}(t,n,i,l)}function Pk(t){t&&(t.ignore=!0)}function Lk(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;jw(l)&&s.get("alignTicks")&&null==s.get("interval")?r.push(a):(ES(l,s),jw(l)&&(e=a))}r.length&&(e||ES((e=r.pop()).scale,e.model),Yi(r,function(t){!function(t,e,n){var i=aS.prototype,r=i.getTicks.call(n),o=i.getTicks.call(n,{expandToNicedExtent:!0}),a=r.length-1,s=i.getInterval.call(n),l=LS(t,e),c=l.extent,u=l.fixMin,d=l.fixMax;"log"===t.type&&(c=Jw(t.base,c,!0)),t.setBreaksFromOption($S(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=Uw(p),f=c[1]-p*a;else{t.getTicks().length-1>a&&(p=Uw(p));var m=p*a;(f=Zl((g=Math.ceil(c[1]/p)*p)-m))<0&&c[0]>=0?(f=0,g=Zl(m)):g>0&&c[1]<=0&&(g=0,f=-Zl(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={};Yi(n.x,function(t){jk(n,"y",t,r)}),Yi(n.y,function(t){jk(n,"x",t,r)}),this.resize(this.model,e)},t.prototype.resize=function(t,e,n){var i=Mm(t,e),r=this._rect=Cm(t.getBoxLayoutParams(),i.refContainer),o=this._axesMap,a=this._coordsList,s=t.get("containLabel");if(Uk(o,r),!n){var l=function(t,e,n,i,r){var o=new xk(Zk);return Yi(n,function(n){return Yi(n,function(n){if(FS(n.model)){var a=!i;n.axisBuilder=function(t,e,n,i,r,o){for(var a=Bk(t,n),s=!1,l=!1,c=0;c0&&i>0||n<0&&i<0)}(t)}function Uk(t,e){Yi(t.x,function(t){return Gk(t,e.x,e.width)}),Yi(t.y,function(t){return Gk(t,e.y,e.height)})}function Gk(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 Xk(t,e,n,i,r,o,a){Yk(i,r,XS,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 If(i,s,!0,!0,n),Uk(r,i),l;function c(t){Yi(r[hf[t]],function(e){if(FS(e.model)){var n=o.ensureRecord(e.model),i=n.labelInfoList;if(i)for(var r=0;r0&&!hr(e)&&e>1e-4&&(t/=e),t}}function Yk(t,e,n,i,r,o){var a=n===YS;Yi(e,function(e){return Yi(e,function(e){FS(e.model)&&(!function(t,e,n){var i=Bk(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[hf[1-e]]=t[pf[e]]<=.5*o.refContainer[pf[e]]?0:1-e==1?2:1}l(0),l(1),Yi(e,function(t,e){return Yi(t,function(t){FS(t.model)&&(("all"===i||a)&&t.axisBuilder.build({axisName:!0},{nameMarginLevel:s[e]}),a&&t.axisBuilder.build({axisLine:!0}))})})}var Zk=function(t,e,n,i,r,o){var a="x"===n.axis.dim?"y":"x";Ck(t,0,0,i,r,o),BS(t.nameLocation)||Yi(e.recordMap[a],function(t){t&&t.labelInfoList&&t.dirVec&&Mk(t.labelInfoList,t.dirVec,i,r)})};function Kk(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=[];Yi(n.getCoordinateSystems(),function(n){if(n.axisPointerEnabled){var s=eM(n.model),l=t.coordSysAxesInfo[s]={};t.coordSysMap[s]=n;var c=n.model.getModel("tooltip",i);if(Yi(n.getAxes(),er(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)&&Yi(h.baseAxes,er(p,!d||"cross",u)),d&&Yi(h.otherAxes,er(p,"cross",!1))}}function p(i,s,u){var d=u.model.getModel("axisPointer",r),h=d.get("show");if(h&&("auto"!==h||i||tM(d))){null==s&&(s=d.get("triggerTooltip")),d=i?function(t,e,n,i,r,o){var a=e.getModel("axisPointer"),s={};Yi(["type","snap","lineStyle","shadowStyle","label","animation","animationDurationUpdate","animationEasingUpdate","z"],function(t){s[t]=Vi(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&&qi(l,u.textStyle)}}return t.model.getModel("axisPointer",new pg(s,n,i))}(u,c,r,e,i,s):d;var p=d.get("snap"),f=d.get("triggerEmphasis"),g=eM(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:tM(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 Jk(t){var e=(t.ecModel.getComponent("axisPointer")||{}).coordSysAxesInfo;return e&&e.axesInfo[eM(t)]}function tM(t){return!!t.get(["handle","show"])}function eM(t){return t.type+"||"+t.id}var nM={},iM=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=Jk(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=tM(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=Jk(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=pM(t).pointerEl=new Vf[r.type](fM(e.pointer));t.add(o)}},t.prototype.createLabelEl=function(t,e,n,i){if(e.label){var r=pM(t).labelEl=new Od(fM(e.label));t.add(r),_M(r,i)}},t.prototype.updatePointerEl=function(t,e,n){var i=pM(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=pM(t).labelEl;r&&(r.setStyle(e.label.style),n(r,{x:e.label.x,y:e.label.y}),_M(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=Mf(o.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(t){uo(t.event)},onmousedown:gM(this._onHandleDragMove,this,0,0),drift:gM(this._onHandleDragMove,this),ondragend:gM(this._onHandleDragEnd,this)}),i.add(r)),xM(r,n,!1),r.setStyle(o.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var s=o.get("size");nr(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,I_(this,"_doDispatchAxisPointer",o.get("throttle")||0,"fixRate"),this._moveHandleToValue(t,e)}},t.prototype._moveHandleToValue=function(t,e){vM(this._axisPointerModel,!e&&this._moveAnimation,this._handle,bM(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(bM(n),[t,e],this._axisModel,this._axisPointerModel);this._payloadInfo=i,n.stopAnimation(),n.attr(bM(i)),pM(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),D_(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 vM(t,e,n,i){yM(pM(n).lastProp,i)||(pM(n).lastProp=i,e?af(n,i,t):(n.stopAnimation(),n.attr(i)))}function yM(t,e){if(sr(t)&&sr(e)){var n=!0;return Yi(e,function(e,i){n=n&&yM(t[i],e)}),!!n}return t===e}function _M(t,e){t[e.get(["label","show"])?"show":"hide"]()}function bM(t){return{x:t.x||0,y:t.y||0,rotation:t.rotation||0}}function xM(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 wM(t,e,n,i,r){var o=SM(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=rm(a.get("padding")||0),l=a.getFont(),c=bl(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:Gf(a,{text:o,font:l,fill:a.getTextColor(),padding:s,backgroundColor:g}),z2:10}}function SM(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:RS(e,{value:t}),axisDimension:e.dim,axisIndex:e.index,seriesData:[]};Yi(i,function(t){var e=n.getSeriesByIndex(t.seriesIndex),i=t.dataIndexInside,r=e&&e.getDataParams(i);r&&s.seriesData.push(r)}),rr(a)?o=a.replace("{value}",o):ir(a)&&(o=a(s))}return o}function CM(t,e,n){var i=[1,0,0,1,0,0];return _o(i,i,n.rotation),yo(i,i,n.position),Sf([t.dataToCoord(e),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],i)}var kM=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=MM(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=TM[s](o,c,l);d.style=u,t.graphicKey=d.type,t.pointer=d}!function(t,e,n,i,r,o){var a=Tk.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=r.get(["label","margin"]),wM(e,i,r,o,{position:CM(i.axis,t,n),align:a.textAlign,verticalAlign:a.textVerticalAlign})}(e,t,Bk(a.getRect(),n),n,i,r)},e.prototype.getHandleTransform=function(t,e,n){var i=Bk(e.axis.grid.getRect(),e,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var r=CM(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=MM(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}(mM);function MM(t,e){var n={};return n[e.dim+"AxisIndex"]=e.index,t.getCartesian(n)}var TM={line:function(t,e,n){var i,r,o;return{type:"Line",subPixelOptimize:!0,shape:(i=[e,n[0]],r=[e,n[1]],o=AM(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=AM(t),{x:i[o=o||0],y:i[1-o],width:r[o],height:r[1-o]})}}};function AM(t){return"x"===t.dim?0:1}var IM=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:Lm.color.border,width:1,type:"dashed"},shadowStyle:{color:Lm.color.shadowTint},label:{show:!0,formatter:null,precision:"auto",margin:3,color:Lm.color.neutral00,padding:[5,7,5,7],backgroundColor:Lm.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:Lm.color.accent40,throttle:40}},e}(Pm),DM=Mc(),PM=Yi;function LM(t,e,n){if(!xi.node){var i=e.getZr();DM(i).records||(DM(i).records={}),function(t,e){if(DM(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);PM(DM(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)})}DM(t).initialized=!0,n("click",er(NM,"click")),n("mousemove",er(NM,"mousemove")),n("globalout",EM)}(i,e),(DM(i).records[t]||(DM(i).records[t]={})).handler=n}}function EM(t,e,n){t.handler("leave",null,n)}function NM(t,e,n,i){e.handler(t,n,i)}function RM(t,e){if(!xi.node){var n=e.getZr();(DM(n).records||{})[t]&&(DM(n).records[t]=null)}}var OM=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";LM("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){RM("axisPointer",e)},e.prototype.dispose=function(t,e){RM("axisPointer",e)},e.type="axisPointer",e}(g_);function zM(t,e){var n,i=[],r=t.seriesIndex;if(null==r||!(n=e.getSeriesByIndex(r)))return{point:[]};var o=n.getData(),a=kc(o,t);if(null==a||a<0||nr(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(Zi(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 HM=Mc();function BM(t,e,n){var i=t.currTrigger,r=[t.x,t.y],o=t,a=t.dispatchAction||tr(n.dispatchAction,n),s=e.getComponent("axisPointer").coordSysAxesInfo;if(s){jM(r)&&(r=zM({seriesIndex:o.seriesIndex,dataIndex:o.dataIndex},e).point);var l=jM(r),c=o.axesInfo,u=s.axesInfo,d="leave"===i||jM(r),h={},p={},f={list:[],map:{}},g={showPointer:er($M,p),showTooltip:er(VM,f)};Yi(s.coordSysMap,function(t,e){var n=l||t.containPoint(r);Yi(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&&FM(t,a,g,!1,h)}})});var m={};return Yi(u,function(t,e){var n=t.linkGroup;n&&!p[e]&&Yi(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,WM(e),WM(t)))),m[t.key]=o}})}),Yi(m,function(t,e){FM(u[e],t,g,!0,h)}),function(t,e,n){var i=n.axesInfo=[];Yi(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(jM(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=HM(i)[r]||{},a=HM(i)[r]={};Yi(t,function(t,e){var n=t.axisPointerModel.option;"show"===n.status&&t.triggerEmphasis&&Yi(n.seriesDataIndices,function(t){var e=t.seriesIndex+" | "+t.dataIndex;a[e]=t})});var s=[],l=[];Yi(o,function(t,e){!a[e]&&l.push(t)}),Yi(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 FM(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 Yi(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),Yi(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&&ji(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 $M(t,e,n,i){t[e.key]={value:n,payloadBatch:i}}function VM(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=eM(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 WM(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 jM(t){return!t||null==t[0]||isNaN(t[0])||null==t[1]||isNaN(t[1])}function qM(t){iM.registerAxisPointerClass("CartesianAxisPointer",kM),t.registerComponentModel(IM),t.registerComponentView(OM),t.registerPreprocessor(function(t){if(t){(!t.axisPointer||0===t.axisPointer.length)&&(t.axisPointer={});var e=t.axisPointer.link;e&&!nr(e)&&(t.axisPointer.link=[e])}}),t.registerProcessor(t.PRIORITY.PROCESSOR.STATISTIC,function(t,e){t.getComponent("axisPointer").coordSysAxesInfo=Kk(t,e)}),t.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},BM)}var UM=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:Lm.color.neutral00,shadowBlur:10,shadowColor:"rgba(0, 0, 0, .2)",shadowOffsetX:1,shadowOffsetY:2,borderRadius:4,borderWidth:1,defaultBorderColor:Lm.color.border,padding:null,extraCssText:"",axisPointer:{type:"line",axis:"auto",animation:"auto",animationDurationUpdate:200,animationEasingUpdate:"exponentialOut",crossStyle:{color:Lm.color.borderShade,width:1,type:"dashed",textStyle:{}}},textStyle:{color:Lm.color.tertiary,fontSize:14}},e}(Pm);function GM(t){var e=t.get("confine");return null!=e?!!e:"richText"===t.get("renderMode")}function XM(t){if(xi.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?",":"")+(xi.transformSupported?""+QM+r:",left"+r+",top"+r)),KM+":"+o}(o,n,i)),a&&r.push("background-color:"+a),Yi(["width","color","radius"],function(e){var n="border-"+e,i=im(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=fr(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),Yi(["decoration","align"],function(n){var i=t.get(n);i&&e.push("text-"+n+":"+i)}),e.join(";")}(d)),null!=h&&r.push("padding:"+rm(h).join("px ")+"px"),r.join(";")+";"}function nT(t,e,n,i,r){var o=e&&e.painter;if(n){var a=o&&o.getViewportRoot();a&&function(t,e,n,i,r){Kr(Zr,e,i,r,!0)&&Kr(t,n,Zr[0],Zr[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 iT=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,xi.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&&(rr(r)?document.querySelector(r):ur(r)?r:ir(r)&&r(t.getDom()));nT(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;lo(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=JM+eT(t,!this._firstShow,this._longHide,this._enableDisplayTransition)+tT(r[0],r[1],!0)+"border-color:"+cm(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(rr(r)&&"item"===n.get("trigger")&&!GM(n)&&(a=function(t,e,n){if(!rr(n)||"inside"===n)return"";var i=t.get("backgroundColor"),r=t.get("borderWidth");e=cm(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=QM+":";Ui(["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)),rr(t))o.innerHTML=t+a;else if(t){o.innerHTML="",nr(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&&!xi.node&&n.getDom()){var r=dT(i,n);this._ticket="";var o=i.dataByCoordSys,a=function(t,e,n){var i=Ic(t).queryOptionMap,r=i.keys()[0];if(!r||"series"===r)return;var o=Pc(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=Yd(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=lT;l.x=i.x,l.y=i.y,l.update(),Yd(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=zM(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(dT(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"===uT([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"===Yd(n).ssrType)return;this._lastDataByCoordSys=null,fb(n,function(t){if(t.tooltipDisabled)return r=o=null,!0;r||o||(null!=Yd(t).dataIndex?r=t:null!=Yd(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=tr(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=uT([e.tooltipOption],i),a=this._renderMode,s=[],l=Gy("section",{blocks:[],noHeader:!0}),c=[],u=new i_;Yi(t,function(t){Yi(t.dataByAxis,function(t){var e=n.getComponent(t.axisDim+"Axis",t.axisIndex),r=t.value;if(e&&null!=r){var o=SM(r,e.axis,n,t.seriesDataIndices,t.valueLabelOpt),d=Gy("section",{header:o,noHeader:!_r(o),sortBlocks:!0,blocks:[]});l.blocks.push(d),Yi(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=RS(e.axis,{value:r}),f.axisValueLabel=o,f.marker=u.makeTooltipMarker("item",cm(f.color),a);var g=fy(h.formatTooltip(p,!0,null)),m=g.frag;if(m){var v=uT([h],i).get("valueFormatter");d.blocks.push(v?ji({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=Jy(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=Yd(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=uT([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 i_;g.marker=m.makeTooltipMarker("item",cm(g.color),d);var v=fy(s.formatTooltip(l,!1,c)),y=p.get("order"),_=p.get("valueFormatter"),b=v.frag,x=b?Jy(_?ji({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=Yd(e),o=r.tooltipConfig.option||{},a=o.encodeHTMLContent;if(rr(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=Vi(o)).content=eo(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=uT(s,this._tooltipModel,c?{position:c}:null),d=u.get("content"),h=Math.random()+"",p=new i_;this._showOrMove(u,function(){var n=Vi(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(rr(u)){var p=t.ecModel.get("useUTC"),f=nr(n)?n[0]:n;d=u,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(d=Bg(f.axisValue,d,p)),d=lm(d,n,!0)}else if(ir(u)){var g=tr(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||nr(e)?{color:i||r}:nr(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),ir(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),nr(e))n=Xl(e[0],s),i=Xl(e[1],l);else if(sr(e)){var p=e;p.width=c[0],p.height=c[1];var f=Cm(p,{width:s,height:l});n=f.x,i=f.y,u=null,d=null}else if(rr(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-=hT(u)?c[0]/2:"right"===u?c[0]:0),d&&(i-=hT(d)?c[1]/2:"bottom"===d?c[1]:0),GM(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&&Yi(n,function(n,o){var a=n.dataByAxis||[],s=(t[o]||{}).dataByAxis||[];(r=r&&a.length===s.length)&&Yi(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)&&Yi(a,function(t,e){var n=l[e];r=r&&t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex}),i&&Yi(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){!xi.node&&e.getDom()&&(D_(this,"_updatePosition"),this._tooltipContent.dispose(),RM("itemTooltip",e))},e.type="tooltip",e}(g_);function uT(t,e,n){var i,r=e.ecModel;n?(i=new pg(n,r,r),i=new pg(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof pg&&(a=a.get("tooltip",!0)),rr(a)&&(a={formatter:a}),a&&(i=new pg(a,i,r)))}return i}function dT(t,e){return t.dispatchAction||tr(e.dispatchAction,e)}function hT(t){return"center"===t||"middle"===t}var pT=Math.sin,fT=Math.cos,gT=Math.PI,mT=2*Math.PI,vT=180/gT,yT=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=os(u-mT)||(c?l>=mT:-l>=mT),h=l>0?l%mT:l%mT+mT,p=!1;p=!!d||!os(u)&&h>=gT==!!c;var f=t+n*fT(o),g=e+i*pT(o);this._start&&this._add("M",f,g);var m=Math.round(r*vT);if(d){var v=1/this._p,y=(c?1:-1)*(mT-v);this._add("A",n,i,m,1,+c,t+n*fT(o+y),e+i*pT(o+y)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var _=t+n*fT(a),b=e+i*pT(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?eo(a):a||"")+(i?""+n+Zi(i,function(e){return t(e)}).join(n)+n:"")+("")}(t)}function DT(t){return{zrId:t,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function PT(t,e,n,i){return AT("svg","root",{width:t,height:e,xmlns:CT,"xmlns:xlink":kT,version:"1.1",baseProfile:"full",viewBox:!!i&&"0 0 "+t+" "+e},n)}var LT=0;function ET(){return LT++}var NT={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"},RT="transform-origin";function OT(t,e,n){var i=ji({},t.shape);ji(i,e),t.buildPath(n,i);var r=new yT;return r.reset(gs(t)),n.rebuildPath(r,1),r.generateStr(),r.getStr()}function zT(t,e){var n=e.originX,i=e.originY;(n||i)&&(t[RT]=n+"px "+i+"px")}var HT={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function BT(t,e){var n=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[n]=t,n}function FT(t){return rr(t)?NT[t]?"cubic-bezier("+NT[t]+")":Pa(t)?t:"":""}function $T(t,e,n,i){var r=t.animators,o=r.length,a=[];if(t instanceof Vp){var s=function(t,e,n){var i,r,o=t.shape.paths,a={};if(Yi(o,function(t){var e=DT(n.zrId);e.animation=!0,$T(t,{},e,!0);var o=e.cssAnims,s=e.cssNodes,l=Ji(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=BT(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 BT(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-"+ET();n.cssNodes["."+v]={animation:a.join(",")},e.class=v}}function VT(t,e,n,i){var r=JSON.stringify(t),o=n.cssStyleCache[r];o||(o=n.zrId+"-cls-"+ET(),n.cssStyleCache[r]=o,n.cssNodes["."+o+":hover"]=t),e.class=e.class?e.class+" "+o:o}var WT=Math.round;function jT(t){return t&&rr(t.src)}function qT(t){return t&&ir(t.toDataURL)}function UT(t,e,n,i){ST(function(r,o){var a="fill"===r||"stroke"===r;a&&ps(o)?iA(e,t,r,i):a&&us(o)?rA(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=is(i.shadowColor),f=p.opacity,g=p.color,m=h/2/l+" "+h/2/c;a=n.zrId+"-s"+n.shadowIdx++,n.defs[a]=AT("filter",a,{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},[AT("feDropShadow","",{dx:u/l,dy:d/c,stdDeviation:m,"flood-color":g,"flood-opacity":f})]),o[r]=a}e.filter=fs(a)}}(n,t,i)}function GT(t,e){var n=function(t){if("function"==typeof Fl)return Fl(t)}(e);n&&(n.each(function(e,n){null!=e&&(t[(MT+n).toLowerCase()]=e+"")}),e.isSilent()&&(t[MT+"silent"]="true"))}function XT(t){return os(t[0]-1)&&os(t[1])&&os(t[2])&&os(t[3]-1)}function YT(t,e,n){if(e&&(!function(t){return os(t[4])&&os(t[5])}(e)||!XT(e))){var i=1e4;t.transform=XT(e)?"translate("+WT(e[4]*i)/i+" "+WT(e[5]*i)/i+")":function(t){return"matrix("+as(t[0])+","+as(t[1])+","+as(t[2])+","+as(t[3])+","+ss(t[4])+","+ss(t[5])+")"}(e)}}function ZT(t,e,n){for(var i=t.points,r=[],o=0;o=0&&a||o;s&&(r=es(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),VT(c,e,n)}}(t,o,e),AT(s,t.id+"",o)}function nA(t,e){return t instanceof bd?eA(t,e):t instanceof kd?function(t,e){var n=t.style,i=n.image;if(i&&!rr(i)&&(jT(i)?i=i.src:qT(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),YT(a,t.transform),UT(a,n,t,e),GT(a,t),e.animation&&$T(t,a,e),AT("image",t.id+"",a)}}(t,e):t instanceof wd?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||Si,o=n.x||0,a=function(t,e,n){return"top"===n?t+=e/2:"bottom"===n&&(t-=e/2),t}(n.y||0,Sl(r),n.textBaseline),s={"dominant-baseline":"central","text-anchor":ls[n.textAlign]||n.textAlign};if(Vd(n)){var l="",c=n.fontStyle,u=Fd(n.fontSize);if(!parseFloat(u))return;var d=n.fontFamily||wi,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),YT(s,t.transform),UT(s,n,t,e),GT(s,t),e.animation&&$T(t,s,e),AT("text",t.id+"",s,void 0,i)}}(t,e):void 0}function iA(t,e,n,i){var r,o=t[n],a={gradientUnits:o.global?"userSpaceOnUse":"objectBoundingBox"};if(ds(o))r="linearGradient",a.x1=o.x,a.y1=o.y,a.x2=o.x2,a.y2=o.y2;else{if(!hs(o))return;r="radialGradient",a.cx=fr(o.x,.5),a.cy=fr(o.y,.5),a.r=fr(o.r,.5)}for(var s=o.colorStops,l=[],c=0,u=s.length;cl?_A(t,null==n[d+1]?null:n[d+1].elm,n,s,d):bA(t,e,a,l))}(n,i,r):gA(r)?(gA(t.text)&&hA(n,""),_A(n,null,r,0,r.length-1)):gA(i)?bA(n,i,0,i.length-1):gA(t.text)&&hA(n,""):t.text!==e.text&&(gA(i)&&bA(n,i,0,i.length-1),hA(n,e.text)))}var SA=0,CA=function(){function t(t,e,n){if(this.type="svg",this.refreshHover=function(){},this.configLayer=function(){},this.storage=e,this._opts=n=ji({},n),this.root=t,this._id="zr"+SA++,this._oldVNode=PT(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=TT("svg");xA(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(vA(t,e))wA(t,e);else{var n=t.elm,i=uA(n);yA(e),null!==i&&(sA(i,e.elm,dA(n)),bA(i,[t],0,0))}}(this._oldVNode,t),this._oldVNode=t}},t.prototype.renderOneToVNode=function(t){return nA(t,DT(this._id))},t.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),n=this._width,i=this._height,r=DT(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=AT("rect","bg",{width:t,height:e,x:"0",y:"0"}),ps(n))iA({fill:n},r.attrs,"fill",i);else if(us(n))rA({style:{fill:n},dirty:Ir,getBoundingRect:function(){return{width:t,height:e}}},r.attrs,"fill",i);else{var o=is(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=AT("g","main",{},[]);this._paintList(e,r,s?s.children:o),s&&o.push(s);var l=Zi(Ji(r.defs),function(t){return r.defs[t]});if(l.length&&o.push(AT("defs","defs",{},l)),t.animation){var c=function(t,e,n){var i=(n=n||{}).newline?"\n":"",r=" {"+i,o=i+"}",a=Zi(Ji(t),function(e){return e+r+Zi(Ji(t[e]),function(n){return n+":"+t[e][n]+";"}).join(i)+o}).join(i),s=Zi(Ji(e),function(t){return"@keyframes "+t+r+Zi(Ji(e[t]),function(n){return n+r+Zi(Ji(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=AT("style","stl",{},[],c);o.push(u)}}return PT(n,i,o,t.useViewBox)},t.prototype.renderToString=function(t){return t=t||{},IT(this.renderToVNode({animation:fr(t.cssAnimation,!0),emphasis:fr(t.cssEmphasis,!0),willUpdate:!1,compress:!0,useViewBox:fr(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;rr(r)?p=KC[r]:ir(r)&&(p=r),p&&t.setData(i.downSample(i.mapDimension(l.dim),1/h,p,QC))}}}}}("line"))},function(t){qS(hM),qS(qM)},function(t){qS(qM),t.registerComponentModel(UM),t.registerComponentView(cT),t.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},Ir),t.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},Ir)},function(t){t.registerPainter("svg",CA)}]);class kA 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=Qx(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)}}kA.styles=P` :host { display: block; width: 100%; @@ -55,13 +55,13 @@ var El={},Nl={};var Rl,Ol=function(){function t(t,e,n){var i=this;this._sleepAft width: 100%; height: 100%; } - `,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` + `,C([Ht({attribute:!1})],kA.prototype,"options",void 0),C([Ht({attribute:!1})],kA.prototype,"data",void 0),C([Ht({type:String})],kA.prototype,"height",void 0);try{customElements.get("span-chart")||customElements.define("span-chart",kA)}catch{}function MA(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 TA(t){return null===t?Xt:function(t){return(Math.abs(t)/1e3).toFixed(1)}(t)}function AA(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=TA(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=TA(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=TA(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=TA(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 IA(t,e,n,i){const{hass:r,powerHistory:o,horizonMap:a,defaultDurationMs:s,chartMetric:l,monitoringStatus:c}=i,u=fn(n,r),d=vn(n,u),h=pn(n,r),p=t.querySelector(".power-value");p&&(p.innerHTML="current"===l.entityRole?te(gn(n,r)):Jt(u)),Dn(t,h,Cn(n,r),ge(i.topology,e)),t.classList.toggle("circuit-off",!h),t.classList.toggle("circuit-producer",d),Nn(t,Tn(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)?ui(a.get(e)):s,h=mn(n),p=en(c,n),g=ln(n,p);MA(f,0,i,u,l,d,r,g?{ratingA:g,...nn(p)}:void 0,h)}}class DA{constructor(t){this._settings=null,this._lastFetch=0,this._fetching=!1,this._retry=new Ke(t)}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=await this._retry.callWS(t,r,{errorId:"fetch:graph_settings",errorMessage:i("error.graph_settings_failed")});this._settings=o?.response??null,this._lastFetch=Date.now()}catch(t){console.warn("SPAN Panel: graph settings fetch failed",t),this._settings=null}finally{this._fetching=!1}return this._settings}invalidate(){this._lastFetch=0}get settings(){return this._settings}clear(){this._settings=null,this._lastFetch=0}}function PA(t,e){if(!t)return a;const n=t.circuits?.[e];return n?.has_override?n.horizon:t.global_horizon??a}function LA(t,e){if(!t)return a;const n=t.sub_devices?.[e];return n?.has_override?n.horizon:t.global_horizon??a}function EA(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 NA{constructor(t){this.errorStore=t,this.powerHistory=new Map,this.horizonMap=new Map,this.subDeviceHorizonMap=new Map,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,this.monitoringCache=new Je(t),this.monitoringMultiCache=new tn(t),this.graphSettingsCache=new DA(t)}get hass(){return this._hass}set hass(t){this._hass=t}get _drawnHass(){const t=this._hass;if(!t)throw new Error("dashboard controller: acted on before it was given Home Assistant");return 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,PA(t,e));if(t&&this._topology?.sub_devices)for(const e of Object.keys(this._topology.sub_devices))this.subDeviceHorizonMap.set(e,LA(t,e))}async fetchAndBuildHorizonMaps(){this._favRefs?await this._buildFavoritesHorizonMaps():(await this.graphSettingsCache.fetch(this._hass,this._configEntryId),this.buildHorizonMaps(this.graphSettingsCache.settings))}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,PA(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,LA(i,r))}}async loadHistory(){await _i(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=ui(i),c=di(l),u=hi(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 yi(this._topology))n.has(e)&&r.add(t);const o=new Map;try{await _i(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=ci(i),l=Fe(n),c=[];for(const{circuit:t}of l){if(!t.entities?.power||mn(t)||Ie(t))continue;const n=fn(t,e);c.push(null===n?null:Math.abs(n))}AA(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="${zn(n.uuid)}"]`);if(!i)continue;const r=n.uuid===e.uuid?e.circuit:Be(n.circuit,e);IA(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=ci(i);for(const[i,s]of Object.entries(n.sub_devices)){const n=t.querySelector(`[data-subdev="${zn(i)}"]`);if(!n)continue;const l=Xn(s);if(l.headlineEid){const t=n.querySelector(".sub-power-value");t&&(t.innerHTML=Qt(Kn(e,l.headlineEid)))}if(l.siteTotalEid){const t=Kn(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");MA(t,0,n,o?.has(i)?ui(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="${zn(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 Hn(n)){const n=t.querySelector(`.meter-tile[data-meter-uuid="${zn(r)}"] .meter-readings`);n&&(n.innerHTML=$n(o,e,i))}}(t,this._hass,this._topology,this._config))}async onGraphSettingsChanged(t){const e=this._drawnHass;this._favRefs?await this._buildFavoritesHorizonMaps():(this.graphSettingsCache.invalidate(),await this.graphSettingsCache.fetch(e,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"!==Cn(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=en(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,...EA(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:Zn(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=en(l,a);r.refreshRating({...EA(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){const e=this._drawnHass;try{const n={};t&&(n.config_entry_id=t);const r={type:"call_service",domain:l,service:"get_graph_settings",service_data:n,return_response:!0},o=await new Ke(this.errorStore).callWS(e,r,{errorId:"fetch:graph_settings",errorMessage:i("error.graph_settings_failed")});return o?.response??null}catch(t){return console.warn("SPAN Panel: fresh graph settings fetch failed",t),null}}async _fetchMonitoringStatusFresh(t){const e=this._drawnHass;try{const n={};t&&(n.config_entry_id=t);const r={type:"call_service",domain:l,service:"get_monitoring_status",service_data:n,return_response:!0},o=await new Ke(this.errorStore,{passThrough:Ge}).callWS(e,r,{errorId:"fetch:monitoring",errorMessage:i("error.monitoring_failed")});return Qe(o?.response)}catch(t){return Ge(t)||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 RA(t=""){const e=t?` value="${jt(t)}"`:"",n=t?"":"display:none;";return`\n
\n \n \n
\n `}function OA(t,e,n,r,o,a,s,l,c){const u=pn(e,n),d=Cn(e,n),h=Ve([e]),p=jt(e.name||i("grid.unknown")),f="current"===Re(r).entityRole;let g;g=u?f?te(gn(e,n)):Jt(fn(e,n)):"";const m=En(a||"unknown");let v="";const y=yn(l,n,o);null!==y&&(v=`${Math.round(y)}%`);const _=``,b=Ie(e)?"":"none"===d?`${u?"ON":"OFF"}`:In(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 zA(t,e,n,i,r){const o=vn(e,fn(e,n)),a=hn(0,r,pn(e,n),o),s=jt(t);return`\n
\n
\n
\n
\n
\n `}function HA(t){return`
${jt(t)}
`}function BA(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 FA(t,e,n){return{isOn:pn(t,e),value:"current"===(n.chart_metric||"power")?gn(t,e):fn(t,e)}}function $A(t,e,n,i){const r=FA(t,n,i),o=FA(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 VA(t,e,n){return t.sort((t,i)=>$A(t[1],i[1],e,n))}class WA{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=VA(Object.entries(n.circuits),e,i),s=He(Fe(n));let l=o+RA(this._searchQuery);l+=`
`;for(const[t,o]of a){const a=en(r,o),c=Tn(o,e),u=this._expandedUuids.has(t);l+=`
`,l+=OA(t,o,e,i,a,c,u,Be(o,s.get(t)),ge(n,t)),u&&(l+=zA(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+RA(this._searchQuery);d+=`
`;for(const t of u){const i=c.get(t);if(!i)continue;const a=VA(i,e,r);d+=HA(t);for(const[t,i]of a){const a=en(o,i),s=Tn(i,e),c=this._expandedUuids.has(t);d+=`
`,d+=OA(t,i,e,r,a,s,c,Be(i,l.get(t)),ge(n,t)),c&&(d+=zA(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}=FA(a,e,i),c=t.querySelector(".list-power-value");c&&(c.innerHTML=s?r?te(l):Jt(l):""),Dn(t,s,Cn(a,e),ge(n,o)),Nn(t,Tn(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)=>$A(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=BA(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=zn(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=en(this._monitoringStatus,e),o=zA(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 jA=["entity_registry_updated","area_registry_updated","device_registry_updated"];async function qA(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 UA=["name","name_by_user"];async function GA(t,e,n){return t.connection.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:UA.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 XA="loaded";async function YA(t,e,n,{initialIsReseed:i,onStatus:r,onSeed:o}){const a=new Map,s=new Map;let l=!1;const c=t=>{const e=function({state:t,disabled_by:e}){return e?"disabled":"loaded"===t?"loaded":"setup_error"===t?"setup_failed":Xe.has(t)?"restart_needed":"loading"}(t);s.get(t.entry_id)!==e&&(s.set(t.entry_id,e),r?.(t.entry_id,e))},u=t=>{s.delete(t),r?.(t,null)};return t.connection.subscribeMessage(t=>{if(t.every(t=>null===t.type)){const r=l||i;l=!0,a.clear();for(const{entry:i}of t)e(i)&&(a.set(i.entry_id,i.state),c(i),r&&i.state===XA&&n(i.entry_id));for(const t of[...s.keys()])a.has(t)||u(t);return void o?.()}for(const{type:i,entry:r}of t){if(!e(r))continue;if("removed"===i){a.delete(r.entry_id),u(r.entry_id);continue}const t=a.get(r.entry_id);a.set(r.entry_id,r.state),c(r),"updated"===i&&r.state===XA&&t!==XA&&n(r.entry_id)}},{type:"config_entries/subscribe",type_filter:["device"]})}function ZA(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 KA(t,e,n){return t.connection.subscribeEvents(t=>{(function(t){const e=ZA(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=ZA(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 QA(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 JA(){let t=0;return()=>{t+=1;const e=t;return()=>t!==e}}class tI{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 eI(t){const e=await t.callWS({type:"config_entries/get",domain:l});return new Set(e.map(t=>t.entry_id))}function nI(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}async function iI(t,e,n){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?ni(t):"";i&&(e.name=i)}}(o.circuits,c),await qA(t,o),{topology:o,panelSize:a}}async function rI(t,e){const[n,i]=await Promise.all([t.callWS({type:"config/device_registry/list"}),eI(t)]),r=t=>{const e=n.find(e=>e.id===t)?.config_entry_id;return void 0!==e&&i.has(e)?e:null};if(n.some(t=>t.id===e))return r(e);const o=(await t.callWS({type:"config/device_registry/list_composite_splits"}))[e];return o?o.split_ids.map(r).find(t=>null!==t)??null:null}async function oI(t,e,n){let i;try{i=await rI(t,e)}catch(i){if(!qe(i))throw i;return async function(t,e,n){let i,r=!1,o=!1;const a=async()=>{if(o)return;let a;o=!0;try{a=await rI(t,e)}catch(t){if(o=!1,!qe(t))throw t;return}if(r)return;const s=i;i=aI(t,a,n),await(await s)()};return i=YA(t,t=>t.domain===l,()=>n.onLoaded(),{initialIsReseed:!0,onSeed:()=>{a()}}),await i,async()=>{r=!0,await(await i)()}}(t,e,n)}return aI(t,i,n)}function aI(t,e,{onLoaded:n,onStatus:i}){if(null===e)return i(null),Promise.resolve(async()=>{});return YA(t,t=>t.entry_id===e,()=>n(),{initialIsReseed:!0,onStatus:(t,e)=>i(e)})}function sI(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function lI(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)=>lI(t,e[n]));if(!sI(t)||!sI(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=>lI(t[n],e[n]))}function cI(t){const e={...t};for(const t of le)delete e[t];return e}function uI(t){const e=Object.fromEntries(Object.entries(t.circuits).map(([t,e])=>[t,cI(e)]));return{...t,circuits:e}}function dI(t){const e=t.getRootNode();return e instanceof Document||e instanceof ShadowRoot?e.activeElement:null}function hI(t){return null!==t&&dI(t)===t}function pI(t){if(!t)return!1;const e=dI(t);return null!==e&&t.contains(e)}function fI(t){return function(t){if(!t)return null;const e=dI(t);return e instanceof HTMLElement&&t.contains(e)?e:null}(t)?.dataset.role??null}function gI(t,e){t.addEventListener("blur",()=>{queueMicrotask(()=>{t.isConnected&&e()})})}const mI={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 vI(t){t.addEventListener("wheel",e=>{hI(t)&&e.preventDefault()},{passive:!1})}function yI(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 _I(t){return t.circuit.package_ratings_a?.[1]??null}class bI{constructor(t){this._host=t,this._section=null,this._field=null}get element(){return this._section}mount(t){this._field=null;const e=yI(this._host.ratingsView);this._section=e?this._build(e):null,this._section&&t.after(this._section)}sync(t){const e=yI(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=fI(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=_I(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){vI(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()}),gI(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=_I(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?(hI(l)&&a?.focus(),l.remove()):null!==i&&!l&&s&&s.appendChild(this._buildReset(n.uuid)),this._syncWarning(t,n)}_storedInForce(){const t=yI(this._host.ratingsView);return t?_I(t.member):null}_save(t){const e=yI(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&&yI(this._host.ratingsView)?.member.uuid===t&&r.answerRefusal(e)&&(null===document.activeElement||document.activeElement===document.body||pI(n))&&i.focus()}_syncWarning(t,e){const n=t.querySelector('[data-role="rating-warning-region"]');if(!n)return;const i=un(e.circuit,this._host.ratingsView?.monitoringInfo??null),r=n.firstElementChild instanceof HTMLElement?n.firstElementChild:null;if(r&&r.dataset.kind===i)return;const o=pI(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 xI(t){return!0===t?.user?.is_admin}function wI(){return i("monitoring.admin_only")}class SI extends Error{constructor(){super(wI()),this.name="MonitoringChangeRefused"}}function CI(t){const e=e=>n=>async function(t,e,n){if(!t||!xI(t))throw new SI;try{await t.callWS({type:"call_service",domain:l,service:e,service_data:n})}catch(t){throw ie(t)?new SI: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 kI(t,e){return t instanceof SI?t.message:e}function MI(t,e,n){console.warn(`SPAN Panel: ${n} failed`,e),t.add({key:"service:monitoring",level:"error",message:kI(e,i("error.threshold_failed")),persistent:!1})}const TI=new Set(["number","text"]);function AI(t){for(let e=t;e;e=e.parentElement)if(""!==e.style.opacity&&Number(e.style.opacity)<1)return!0;return!1}const II="favorites-changed";async function DI(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 PI={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"},LI="relay-label",EI="priority-label",NI="controls-note";class RI{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 OI extends HTMLElement{get errorStore(){const t=this._errorStore;if(!t)throw new Error("span-side-panel: acted on before its host gave it an error store");return t}set errorStore(t){this._errorStore=t}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 bI(this)}set hass(t){const e=xI(this._hass)!==xI(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}get _drawnHass(){const t=this._hass;if(!t)throw new Error("span-side-panel: acted on before its host gave it Home Assistant");return t}open(t){this._config=t,this._storedMonitoring=t.panelMode||t.subDeviceMode||t.favoritesMode?null:new RI(t.uuid,sn(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=Zn(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=NI);for(const t of e)n?t.setAttribute("aria-describedby",NI):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=Qn(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){const r=this._drawnHass,o=t.classList.contains("active"),a=!o;t.classList.toggle("active",a),e.setAttribute("icon",a?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(a));try{a?await async function(t,e){const n=await DI(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(II)),n?.favorites??{}}(r,n):await async function(t,e){const n=await DI(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(II)),n?.favorites??{}}(r,n)}catch(n){throw t.classList.toggle("active",o),e.setAttribute("icon",o?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(o)),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=Qn(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"===Cn(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=LI,o.textContent=i("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle",a.setAttribute("aria-labelledby",LI);const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{const t=this._hass;t&&s&&"operable"===Cn(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=EI,o.textContent=i("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select",a.setAttribute("aria-labelledby",EI);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 CI(this._hass).setCircuitPackageRatings(this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return CI(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 CI(this._hass).clearCircuitThreshold(o)}catch(e){return MI(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(sn(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,pI(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:dn(t)}):r("sidepanel.judged_against",{rating:`${t.amps} A`}):r("sidepanel.judged_against",{rating:i("monitoringRating.none")})}({amps:(e=t)?an(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=sn(s);l&&a.setAttribute("checked",""),r.appendChild(o),r.appendChild(a),n.appendChild(r),xI(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=wI(),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&&!xI(this._hass)&&function(t){const e=wI();for(const n of t.querySelectorAll("input, select, textarea, button, span-switch"))n instanceof HTMLInputElement&&TI.has(n.type)||n instanceof HTMLTextAreaElement?n.readOnly=!0:n.setAttribute("disabled",""),n.title=e,"span-switch"!==n.localName&&(AI(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 CI(this._hass).setCircuitThreshold(n),!0}catch(t){return MI(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&&pI(r);r.style.display=e?"block":"none",t&&i?.focus()}this._monitoringChanged(t,{monitoring_enabled:e})}_createLimitRow(t,e,n,i,o){const a=PI[e],{min:s,max:l}=mI[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}=mI[e];vI(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()}),gI(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){CI(this._hass).setCircuitThreshold(e).then(()=>this._readThresholds(t,e),t=>MI(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){const n=this._drawnHass,i=this._controlAccess;t.disabled=!i.mayOperate||"operable"!==Cn(e,n),ke(t,i),Sn(e,n)?t.setAttribute("checked",""):t.removeAttribute("checked")}_applySheddingSelect(t,e){const n=this._drawnHass,i=this._controlAccess,r=Tn(e,n);x.includes(r)?t.value=r:t.selectedIndex=-1,t.disabled=!i.mayOperate||!function(t,e){const n=Mn(t,e);return void 0!==n&&_n.has(n)}(e,n),ke(t,i)}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=en(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){const e=await this._drawnHass.callWS({type:"call_service",domain:l,service:"get_monitoring_status",service_data:t?{config_entry_id:t}:{},return_response:!0});return Qe(e?.response)}_callDomainService(t,e){return this._drawnHass.callWS({type:"call_service",domain:l,service:t,service_data:e})}_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",OI)}catch{}class zI extends Nt{constructor(){super(...arguments),this._store=null,this._unsub=null,this._errors=[]}set store(t){this._store=t,this._errors=t.active,this._unsub=t.subscribe(()=>{this._errors=t.active})}get _hostStore(){const t=this._store;if(!t)throw new Error("span-error-banner: attached before its host gave it an error store");return t}connectedCallback(){if(super.connectedCallback(),!this._unsub){const t=this._hostStore;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"}}}DI.styles=P` + `)}`}_iconForLevel(t){switch(t){case"error":return"mdi:alert-circle";case"warning":return"mdi:alert";default:return"mdi:information"}}}zI.styles=P` :host { display: block; } @@ -111,7 +111,7 @@ var El={},Nl={};var Rl,Ol=function(){function t(t,e,n){var i=this;this._sleepAft .retry-btn:hover { opacity: 0.8; } - `,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` + `,C([Bt()],zI.prototype,"_errors",void 0);try{customElements.get("span-error-banner")||customElements.define("span-error-banner",zI)}catch{}const HI=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"}),BI=new Set;class FI extends Nt{constructor(){super(...arguments),this.icon=""}render(){if(!this.icon)return yt;const t=HI[this.icon];return t?gt``:(e=this.icon,BI.has(e)||(BI.add(e),console.warn(`SPAN: unknown icon "${e}". Add it to MDI_PATHS in span-icon.ts.`)),yt);var e}}FI.styles=P` :host { display: inline-flex; align-items: center; @@ -128,11 +128,11 @@ var El={},Nl={};var Rl,Ol=function(){function t(t,e,n){var i=this;this._sleepAft display: block; fill: currentColor; } - `,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` + `,C([Ht({type:String})],FI.prototype,"icon",void 0);try{customElements.get("span-icon")||customElements.define("span-icon",FI)}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`
- `}}NI.styles=P` + `}}$I.styles=P` :host { --span-switch-track-w: 36px; --span-switch-track-h: 20px; @@ -234,12 +234,7 @@ var El={},Nl={};var Rl,Ol=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})],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` -
- - ${this._discoveryFailed?yt:gt`
${t}
`} -
- `}return gt` + `,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 VI=[{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 WI=class extends Nt{constructor(){super(...arguments),this._config={},this._discovered=!1,this._discovering=!1,this._awaitingLoad=!1,this._entryLoad=void 0,this._discoveryFailed=!1,this._topology=null,this._activeTab="panel",this._positions=null,this._historyLoaded=!1,this._errorStore=new tI,this._ctrl=new NA(this._errorStore),this._listCtrl=new WA(this._ctrl),this._areaSub=null,this._renameSub=null,this._reloadSub=null,this._ratingSub=null,this._loadWait=null,this._topologyRefresh=QA(()=>this._refreshTopology()),this._askOnEntryLoad=function(t){let e=!1;return()=>{e||(e=!0,Promise.resolve().then(()=>{e=!1,t()}))}}(()=>{this._discoveryOnEntryLoad()}),this._discoveryOnEntryLoad=QA(async()=>{this._awaitingLoad&&await this._runDiscovery()}),this._beginDiscoveryRun=JA(),this._beginTopologyEpoch=JA(),this._tabBarCleanup=null}get _configEntryId(){return this._topology?.config_entry_id??null}get _deviceId(){const t=this._config.device_id;if(!t)throw new Error("span-panel-card: no device_id is configured");return t}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)}getCardSize(){const t=this._topology?(e=this._topology,n=this._config,Bn(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(){return n(this.hass?.language),this._config.device_id?this._discovered?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` + `:gt` +
+ + ${this._discoveryFailed?yt:this._renderStatusLine()} +
+ `:this._renderPreview()}_renderStatusLine(){if(!this._awaitingLoad)return gt`
${i("card.connecting")}
`;const t=(e=this._entryLoad,Ye[void 0===e||"loading"===e||"loaded"===e?"waiting":e]());var e;return gt`
${t.text}
`}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,e=this._beginDiscoveryRun(),n=new Ke(this._errorStore,{passThrough:Ge});let i;try{i=await iI(t,this._deviceId,n)}catch(t){if(e())return;return Ge(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=oI(this.hass,this._deviceId,{onLoaded:()=>{this._loadWait===t&&this._askOnEntryLoad()},onStatus:e=>{this._loadWait===t&&(null===e?this._failDiscovery():this._entryLoad=e)}});this._loadWait=t}_endEntryLoadWait(){this._awaitingLoad=!1,this._dropEntryLoadWait()}_dropEntryLoadWait(){const t=this._loadWait;this._loadWait=null,this._entryLoad=void 0,t?.then(t=>t())}async _refreshTopology(){if(!this._discovered)return;const t=this._beginTopologyEpoch();let e;try{e=await iI(this.hass,this._deviceId,null)}catch(t){return void console.warn("SPAN Panel: topology refresh failed; keeping the current topology:",ee(t))}if(t())return;if(lI(e.topology,this._topology))return;const n=(i=e.topology,!(null!==(r=this._topology)&&lI(uI(i),uI(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._areaSub=async function(t,e,n,r){const o=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 qA(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})}},a=await Promise.all(jA.map(e=>t.connection.subscribeEvents(o,e)));return()=>{for(const t of a)t()}}(this.hass,()=>this._topology,()=>{"area"===this._activeTab&&this._discovered&&this._populateCardContent()},this._errorStore),this._renameSub=GA(this.hass,()=>this._topology,()=>{this._topologyRefresh()}),this._reloadSub=YA(this.hass,t=>t.entry_id===this._configEntryId,()=>{this._onEntryReloaded()},{initialIsReseed:t}),this._syncRatingSubscription(),this._watchPanelStatus()}async _onEntryReloaded(){const t=this._ctrl.monitoringCache;t.awaitingLoad&&(await t.fetch(this.hass,this._configEntryId),this._discovered&&this._ctrl.updateDOM(this._root)),await this._topologyRefresh()}_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=KA(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?[rn(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:en(r,e.circuit),sheddingPriority:Tn(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+=Rn(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+=On(e,"2"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=Rn(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+=On(e,"4"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(g);p+=Rn(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=ii(this._topology,this.hass,this._config,{showFavorites:this._ctrl.showFavorites}),l=function(t,e,n){if(!Bn(t,n))return"";const r=Hn(t).map(([t,r])=>`\n
\n ${jt(r.name||i("grid.unknown"))}\n ${$n(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=VI.map(t=>gt`
${t.name} @@ -276,4 +276,4 @@ var El={},Nl={};var Rl,Ol=function(){function t(t,e,n){var i=this;this._sleepAft
${i("card.no_device")}
- `}};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;"); + `}};function jI(t,e){return ti(Object.entries(t)).filter(([,t])=>t.type===e).map(([t,e])=>{const n=Yn(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}})}WI.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})],WI.prototype,"hass",void 0),C([Bt()],WI.prototype,"_config",void 0),C([Bt()],WI.prototype,"_discovered",void 0),C([Bt()],WI.prototype,"_discovering",void 0),C([Bt()],WI.prototype,"_awaitingLoad",void 0),C([Bt()],WI.prototype,"_entryLoad",void 0),C([Bt()],WI.prototype,"_discoveryFailed",void 0),C([Bt()],WI.prototype,"_topology",void 0),C([Bt()],WI.prototype,"_activeTab",void 0),WI=C([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})(c)],WI);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,n]=await Promise.all([t.callWS({type:"config/device_registry/list"}),eI(t)]);return e.filter(t=>ei(t,n))}(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=nI(t),n=Object.values(t.devices??{}).find(t=>ei(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&&ei(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,nI(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.3 ","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 eb1f905c..92172e91 100644 --- a/custom_components/span_panel/frontend/dist/span-panel.js +++ b/custom_components/span_panel/frontend/dist/span-panel.js @@ -1,4 +1,4 @@ -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; +let t="en";const e={en:{"tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","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.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...","card.setup_failed":"SPAN Panel could not be set up. Check Settings → Devices & services.","card.panel_disabled":"This SPAN Panel is disabled. Enable it in Settings → Devices & services.","card.restart_needed":"SPAN Panel could not be loaded. Restart Home Assistant to try again.","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}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","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","panel.no_panels":"No SPAN Panel found. Add one in Settings → Devices & services.","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.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.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","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.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...","card.setup_failed":"No se pudo configurar el SPAN Panel. Revise Ajustes → Dispositivos y servicios.","card.panel_disabled":"Este SPAN Panel está deshabilitado. Habilítelo en Ajustes → Dispositivos y servicios.","card.restart_needed":"No se pudo cargar el SPAN Panel. Reinicie Home Assistant para volver a intentarlo.","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}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN 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","panel.no_panels":"No se encontró ningún SPAN Panel. Agregue uno en Ajustes → Dispositivos y servicios.","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.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.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","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.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...","card.setup_failed":"Le SPAN Panel n'a pas pu être configuré. Consultez Paramètres → Appareils et services.","card.panel_disabled":"Ce SPAN Panel est désactivé. Activez-le dans Paramètres → Appareils et services.","card.restart_needed":"Le SPAN Panel n'a pas pu être chargé. Redémarrez Home Assistant pour réessayer.","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}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","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","panel.no_panels":"Aucun SPAN Panel trouvé. Ajoutez-en un dans Paramètres → Appareils et services.","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.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.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","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.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パネルの読み込みを待機中...","card.setup_failed":"SPANパネルをセットアップできませんでした。設定 → デバイスとサービス を確認してください。","card.panel_disabled":"このSPANパネルは無効になっています。設定 → デバイスとサービス で有効にしてください。","card.restart_needed":"SPANパネルを読み込めませんでした。Home Assistant を再起動してもう一度お試しください。","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","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":"お気に入り","panel.no_panels":"SPANパネルが見つかりません。設定 → デバイスとサービス で追加してください。","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","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.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","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.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...","card.setup_failed":"Não foi possível configurar o SPAN Panel. Verifique Configurações → Dispositivos e serviços.","card.panel_disabled":"Este SPAN Panel está desativado. Ative-o em Configurações → Dispositivos e serviços.","card.restart_needed":"Não foi possível carregar o SPAN Panel. Reinicie o Home Assistant para tentar novamente.","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}","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","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","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","panel.no_panels":"Nenhum SPAN Panel encontrado. Adicione um em Configurações → Dispositivos e serviços.","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.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 @@ -46,13 +46,13 @@ 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 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` + */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){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}const De=new Set(["not_loaded","unknown_command"]);function Le(t){return!!Pe(t)||"object"==typeof t&&null!==t&&("code"in t&&De.has(t.code)||function(t){return"code"in t&&"service_validation_error"===t.code&&"translation_domain"in t&&t.translation_domain===s&&"translation_key"in t&&"monitoring_panel_not_loaded"===t.translation_key}(t))}const Ee="awaiting_load",Re=new Set(["migration_error","failed_unload"]);const Ne={waiting:()=>({text:n("card.waiting_for_load"),role:"status",color:"var(--secondary-text-color)"}),setup_failed:()=>({text:n("card.setup_failed"),role:"alert",color:"var(--error-color)"}),restart_needed:()=>({text:n("card.restart_needed"),role:"alert",color:"var(--error-color)"}),disabled:()=>({text:n("card.panel_disabled"),role:"alert",color:"var(--error-color)"})};function Oe(t){return Ne[t]()}function ze(t){return new Promise(e=>setTimeout(e,t))}class $e{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=await this._retry.callWS(t,o,{errorId:"fetch:monitoring",errorMessage:n("error.monitoring_failed")}),l=He(a?.response);return r===this._generation&&(this._status=l,this._lastFetch=Date.now(),this._awaitingLoad=!1),l}catch(t){const e=Le(t);return r===this._generation&&(this._status=null,this._awaitingLoad=e),e||console.warn("SPAN Panel: monitoring status fetch failed",t),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._awaitingLoad=!1,this._generation++}}class Be{constructor(t){this._errorStore=t,this._caches=new Map}awaitingLoad(t){return!0===this._caches.get(t)?.awaitingLoad}async fetchOne(t,e){let n=this._caches.get(e);return n||(n=new Fe(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 Ve(t){return t.entities?.current??t.entities?.power??""}function je(t,e){return function(t,e){return t?.circuits?t.circuits[e]??null:null}(t,Ve(e))}function qe(t){return{continuousPct:t?.continuous_threshold_pct??80,spikePct:t?.spike_threshold_pct??100}}function We(t,e){const{continuousPct:n,spikePct:i}=qe(e);return t>=i?"alert":t>=n?"warning":"normal"}function Ue(t,e){return`utilization-${We(t,e)}`}function Ge(t){return!0===t?.user?.is_admin}function Xe(){return n("monitoring.admin_only")}class Ye extends Error{constructor(){super(Xe()),this.name="MonitoringChangeRefused"}}function Ze(t){const e=e=>n=>async function(t,e,n){if(!t||!Ge(t))throw new Ye;try{await t.callWS({type:"call_service",domain:s,service:e,service_data:n})}catch(t){throw ee(t)?new Ye: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 Ke(t,e){return t instanceof Ye?t.message:e}function Qe(t,e,i){console.warn(`SPAN Panel: ${i} failed`,e),t.add({key:"service:monitoring",level:"error",message:Ke(e,n("error.threshold_failed")),persistent:!1})}const Je=new Set(["number","text"]);function tn(t){for(let e=t;e;e=e.parentElement)if(""!==e.style.opacity&&Number(e.style.opacity)<1)return!0;return!1}function en(t,e){const n=Xe();for(const i of t.querySelectorAll("input, select, textarea, button, span-switch"))void 0!==e&&i.matches(e)||(i instanceof HTMLInputElement&&Je.has(i.type)||i instanceof HTMLTextAreaElement?i.readOnly=!0:i.setAttribute("disabled",""),i.title=n,"span-switch"!==i.localName&&(tn(i)||(i.style.opacity="0.5"),i.style.cursor="not-allowed"))}function nn(){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=Xe(),t}const rn=["relay_state","relay_state_target","priority","priority_target"];function on(t){return"_favoriteRefs"in t}const an=Object.freeze({mayOperate:!0,reason:null}),sn=Object.freeze({mayOperate:!1,reason:null}),ln=["control_disabled","admin_only","read_only"];function cn(t){const e=t?.control_access;return"object"==typeof e&&null!==e&&"may_operate"in e&&"boolean"==typeof e.may_operate?e.may_operate?an:{mayOperate:!1,reason:"reason"in e&&(n=e.reason,ln.some(t=>t===n))?e.reason:null}:an;var n}function dn(t){return"circuit"===t?.kind}function un(t,e){if(!t||!on(t))return cn(t);const n=t._favoriteRefs[e];return dn(n)?n.controlAccess:sn}function hn(t){if(!t||!on(t))return cn(t);const e=[...gn(t,pn).values()],[n]=e;return!n||e.some(t=>t.mayOperate)?an:n}function pn(t){return!!t?.entities?.switch&&!1!==t.is_user_controllable}function fn(t){return pn(t)||!!t?.entities?.select}function gn(t,e){const n=new Map;for(const[i,r]of Object.entries(t._favoriteRefs))dn(r)&&e(t.circuits[i])&&n.set(r.panelDeviceId,r.controlAccess);return n}const mn={control_disabled:()=>n("controls.disabled"),admin_only:()=>n("controls.admin_only"),read_only:()=>n("controls.read_only")};function vn(t){return t.mayOperate?"":t.reason?mn[t.reason]():n("controls.not_operable")}class _n extends Error{constructor(t){super(t),this.name="ControlChangeRefused"}}function yn(t,e){return{setRelay:(n,i)=>bn(t,e,"switch",i?"turn_on":"turn_off",n,{}),setPriority:(n,i)=>bn(t,e,"select","select_option",n,{option:i})}}async function bn(t,e,i,r,o,a){if(!e.mayOperate)throw new _n(vn(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 _n(n("controls.entity_unauthorized")):t}}const xn={relay:{key:"service:relay",fallback:()=>n("error.relay_failed")},priority:{key:"service:shedding",fallback:()=>n("error.shedding_failed")}};function wn(t,e,n,i){console.warn(`SPAN Panel: ${i} change failed`,n);const{key:r,fallback:o}=xn[i];oe(t,n,s,o()).then(t=>{e.add({key:r,level:"error",message:t,persistent:!1})})}function Sn(t,e){const n=vn(e);n?t.title=n:t.removeAttribute("title")}function Cn(t){const e=vn(t);return e?`

${Ft(e)}

`:""}const kn="favorites-changed";async function Mn(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 Tn{constructor(t){this._map=null,this._lastFetch=0,this._inflight=null,this._generation=0,this._retry=new $e(t)}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=await this._retry.callWS(t,e,{errorId:"fetch:favorites",errorMessage:n("error.favorites_fetch_failed")}),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._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 An(t){return Object.keys(t).some(e=>In(t,e))}function In(t,e){const n=t[e];return(n?.circuits?.length??0)>0||(n?.sub_devices?.length??0)>0}const Pn={names:["power","battery power"],suffixes:["_power"]},Dn={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},Ln={names:["state of energy"],suffixes:["_soe_kwh"]};function En(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 Rn(t){return En(t,Dn)}function Nn(t){return En(t,Ln)}function On(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}function zn(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,En(n,Pn)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function $n(t){const{headlineEid:e,siteTotalEid:n}=zn(t),i=[e,n];return t.type===l&&i.push(Rn(t),Nn(t)),new Set(i.filter(t=>null!==t))}function Hn(t){const e=[{role:"power",entityId:zn(t).headlineEid}];return t.type===l&&e.push({role:"soc",entityId:Rn(t)},{role:"soe",entityId:Nn(t)}),e.filter(t=>null!==t.entityId)}function Fn(t,e){return On(t.states[e])}function Bn(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 Vn(t,e){return Hn(t).length>0||e&&null!==Bn(t.entities)}function jn(t){return"number"==typeof t&&Number.isInteger(t)&&t>0}function qn(t){return!0===t.outside_panel}function Wn(t,e){if(!t)return null;let n=null,i=null;const{first_position:r,last_position:o}=t;jn(r)&&jn(o)&&r<=o?(n=r,i=o):jn(e)&&(n=1,i=e);for(const e of Object.values(t.circuits))if(e&&!qn(e))for(const t of e.tabs??[])jn(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 Un(t){return Math.ceil(t/2)}function Gn(t){return t%2==0?1:0}function Xn(t){if(2!==t.length)return null;const[e,n]=[Math.min(...t),Math.max(...t)];return Un(e)===Un(n)?"row-span":Gn(e)===Gn(n)?"col-span":"row-span"}function Yn(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 Zn(t,e){return qn(t)||ai(t,e)}function Kn(t,e){const n=t.entities?.power;return On(n?e.states[n]:void 0)}function Qn(t,e){const n=t.entities?.current;return On(n?e.states[n]:void 0)}function Jn(t){return t.is_generation??"pv"===t.device_type}function ti(t,e){return Jn(t)||null!==e&&e<0}function ei(t,e,n){const i=Qn(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 ni=new Set(g),ii={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function ri(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function oi(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 ai(t,e){const n=ri(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(oi(t,e,"relay_state")??t.relay_state)}function si(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=ri(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function li(t){return void 0===t?void 0:ii[t]}function ci(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function di(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=ci(t,e);return void 0!==n&&ni.has(n)?n:li(oi(t,e,"shed_priority"))??li(t.priority)??"unknown"}const ui={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"},hi="relay-label",pi="priority-label",fi="controls-note";class gi{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 mi extends HTMLElement{get errorStore(){const t=this._errorStore;if(!t)throw new Error("span-side-panel: acted on before its host gave it an error store");return t}set errorStore(t){this._errorStore=t}constructor(){super(),this._errorStore=null,this._thresholdReads=0,this._limitFields=[],this._storedMonitoring=null,this._controlAccess=sn,this.attachShadow({mode:"open"}),this._hass=null,this._config=null,this._debounceTimers={},this._ratingsEditor=new Ie(this)}set hass(t){const e=Ge(this._hass)!==Ge(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}get _drawnHass(){const t=this._hass;if(!t)throw new Error("span-side-panel: acted on before its host gave it Home Assistant");return t}open(t){this._config=t,this._storedMonitoring=t.panelMode||t.subDeviceMode||t.favoritesMode?null:new gi(t.uuid,Wt(t.monitoringInfo)),this._controlAccess=t.panelMode||t.subDeviceMode||t.favoritesMode?sn: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=sn,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=Hn(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",Cn(this._controlAccess));const n=t.querySelector('[data-role="controls-note"]');n&&(n.id=fi);for(const t of e)n?t.setAttribute("aria-describedby",fi):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=Bn(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){const r=this._drawnHass,o=t.classList.contains("active"),a=!o;t.classList.toggle("active",a),e.setAttribute("icon",a?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(a));try{a?await async function(t,e){const n=await Mn(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(kn)),n?.favorites??{}}(r,i):await async function(t,e){const n=await Mn(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(kn)),n?.favorites??{}}(r,i)}catch(i){throw t.classList.toggle("active",o),e.setAttribute("icon",o?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(o)),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=Bn(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"===si(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=hi,o.textContent=n("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle",a.setAttribute("aria-labelledby",hi);const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{const t=this._hass;t&&s&&"operable"===si(e,t)&&yn(t,this._controlAccess).setRelay(s,a.checked).catch(n=>{wn(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=pi,o.textContent=n("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select",a.setAttribute("aria-labelledby",pi);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&&yn(t,this._controlAccess).setPriority(s,a.value).catch(n=>{wn(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 Ze(this._hass).setCircuitPackageRatings(this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return Ze(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 Ze(this._hass).clearCircuitThreshold(o)}catch(e){return Qe(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),Ge(this._hass)||i.appendChild(nn());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&&!Ge(this._hass)&&en(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 Ze(this._hass).setCircuitThreshold(n),!0}catch(t){return Qe(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=ui[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){Ze(this._hass).setCircuitThreshold(e).then(()=>this._readThresholds(t,e),t=>Qe(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){const n=this._drawnHass,i=this._controlAccess;t.disabled=!i.mayOperate||"operable"!==si(e,n),Sn(t,i),ai(e,n)?t.setAttribute("checked",""):t.removeAttribute("checked")}_applySheddingSelect(t,e){const n=this._drawnHass,i=this._controlAccess,r=di(e,n);g.includes(r)?t.value=r:t.selectedIndex=-1,t.disabled=!i.mayOperate||!function(t,e){const n=ci(t,e);return void 0!==n&&ni.has(n)}(e,n),Sn(t,i)}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=je(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){const e=await this._drawnHass.callWS({type:"call_service",domain:s,service:"get_monitoring_status",service_data:t?{config_entry_id:t}:{},return_response:!0});return He(e?.response)}_callDomainService(t,e){return this._drawnHass.callWS({type:"call_service",domain:s,service:t,service_data:e})}_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",mi)}catch{}class vi extends At{constructor(){super(...arguments),this._store=null,this._unsub=null,this._errors=[]}set store(t){this._store=t,this._errors=t.active,this._unsub=t.subscribe(()=>{this._errors=t.active})}get _hostStore(){const t=this._store;if(!t)throw new Error("span-error-banner: attached before its host gave it an error store");return t}connectedCallback(){if(super.connectedCallback(),!this._unsub){const t=this._hostStore;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` - `)}`}_iconForLevel(t){switch(t){case"error":return"mdi:alert-circle";case"warning":return"mdi:alert";default:return"mdi:information"}}}ui.styles=k` + `)}`}_iconForLevel(t){switch(t){case"error":return"mdi:alert-circle";case"warning":return"mdi:alert";default:return"mdi:information"}}}vi.styles=k` :host { display: block; } @@ -102,7 +102,7 @@ const Pt={attribute:!0,type:String,converter:$,reflect:!1,hasChanged:H},Dt=(t=Pt .retry-btn:hover { opacity: 0.8; } - `,_([Et()],ui.prototype,"_errors",void 0);try{customElements.get("span-error-banner")||customElements.define("span-error-banner",ui)}catch{}var hi="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z";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":hi,"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"}),fi=new Set;class gi extends At{constructor(){super(...arguments),this.icon=""}render(){if(!this.icon)return ht;const t=pi[this.icon];return t?ct``:(e=this.icon,fi.has(e)||(fi.add(e),console.warn(`SPAN: unknown icon "${e}". Add it to MDI_PATHS in span-icon.ts.`)),ht);var e}}gi.styles=k` + `,_([Et()],vi.prototype,"_errors",void 0);try{customElements.get("span-error-banner")||customElements.define("span-error-banner",vi)}catch{}var _i="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z";const yi=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":_i,"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"}),bi=new Set;class xi extends At{constructor(){super(...arguments),this.icon=""}render(){if(!this.icon)return ht;const t=yi[this.icon];return t?ct``:(e=this.icon,bi.has(e)||(bi.add(e),console.warn(`SPAN: unknown icon "${e}". Add it to MDI_PATHS in span-icon.ts.`)),ht);var e}}xi.styles=k` :host { display: inline-flex; align-items: center; @@ -119,11 +119,11 @@ const Pt={attribute:!0,type:String,converter:$,reflect:!1,hasChanged:H},Dt=(t=Pt display: block; fill: currentColor; } - `,_([Lt({type:String})],gi.prototype,"icon",void 0);try{customElements.get("span-icon")||customElements.define("span-icon",gi)}catch{}class mi extends At{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 ct` + `,_([Lt({type:String})],xi.prototype,"icon",void 0);try{customElements.get("span-icon")||customElements.define("span-icon",xi)}catch{}class wi extends At{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 ct`
- `}}mi.styles=k` + `}}wi.styles=k` :host { --span-switch-track-w: 36px; --span-switch-track-h: 20px; @@ -225,11 +225,11 @@ const Pt={attribute:!0,type:String,converter:$,reflect:!1,hasChanged:H},Dt=(t=Pt outline: var(--wa-focus-ring, 2px solid var(--ha-color-focus, var(--primary-color, #4dd9af))); outline-offset: var(--wa-focus-ring-offset, 2px); } - `,_([Lt({type:Boolean,reflect:!0})],mi.prototype,"checked",void 0),_([Lt({type:Boolean,reflect:!0})],mi.prototype,"disabled",void 0);try{customElements.get("span-switch")||customElements.define("span-switch",mi)}catch{}class vi extends At{constructor(){super(...arguments),this.narrow=!1,this._toggle=()=>{this.dispatchEvent(new CustomEvent("hass-toggle-menu",{bubbles:!0,composed:!0}))}}render(){return ct` + `,_([Lt({type:Boolean,reflect:!0})],wi.prototype,"checked",void 0),_([Lt({type:Boolean,reflect:!0})],wi.prototype,"disabled",void 0);try{customElements.get("span-switch")||customElements.define("span-switch",wi)}catch{}class Si extends At{constructor(){super(...arguments),this.narrow=!1,this._toggle=()=>{this.dispatchEvent(new CustomEvent("hass-toggle-menu",{bubbles:!0,composed:!0}))}}render(){return ct` - `}}vi.styles=k` + `}}Si.styles=k` :host { display: none; align-items: center; @@ -263,7 +263,7 @@ const Pt={attribute:!0,type:String,converter:$,reflect:!1,hasChanged:H},Dt=(t=Pt height: 24px; fill: currentColor; } - `,_([Lt({type:Boolean,reflect:!0})],vi.prototype,"narrow",void 0);try{customElements.get("span-menu-button")||customElements.define("span-menu-button",vi)}catch{}const _i=["entity_registry_updated","area_registry_updated","device_registry_updated"];async function yi(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,d=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=[d(t.device_id),...e.map(t=>a.get(t)),...e.map(t=>d(s.get(t))),d(c)];t.area=n.map(t=>t?o.get(t):void 0).find(t=>!!t)}}const bi="loaded";function xi(t){return(t.name_by_user||t.name||"").trim()}async function wi(t,e,i){if(!e)throw new Error(n("card.device_not_found"));const r={type:`${s}/panel_topology`,device_id:e},o=i?await i.callWS(t,r,{errorId:"fetch:topology"}):await t.callWS(r),a=zn(o.panel_size)?o.panel_size:function(t){let e=0;for(const n of Object.values(t))if(n&&!$n(n))for(const t of n.tabs)t>e&&(e=t);return e>0?e+e%2:0}(o.circuits);if(!Hn(o,a))throw new Error(n("card.topology_error"));const l={type:"config/device_registry/list"},c=i?await i.callWS(t,l,{errorId:"fetch:topology"}):await t.callWS(l);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?xi(t):"";i&&(e.name=i)}}(o.circuits,c),await yi(t,o),{topology:o,panelSize:a}}const Si=h.power,Ci=h.current,ki="--",Mi=`${ki}`;function Ti(t){return Si.unit(t)}function Ai(t){return(t<0?"-":"")+Si.format(t)}function Ii(t){return null===t?Mi:`${Ai(t)} ${Ti(t)}`}function Pi(t){return null===t?Mi:`${Ai(t)}${Ti(t)}`}function Di(t){return null===t?Mi:`${Ci.format(t)}A`}function Li(t,e={}){const i=!t.mayOperate;return`
\n ${Ft(n("header.enable_switches"))}\n
\n \n
\n
${!1===e.note?"":_n(t)}`}function Ei(){return`
\n ${Object.entries(f).filter(([t])=>"unknown"!==t).map(([,t])=>{const e=Ft(t.icon),n=Ft(t.color),i=Ft(t.label());let r;if(t.icon2){r=``}else if(t.textLabel){r=`${Ft(t.textLabel)}`}else r=``;return`
${r}${i}
`}).join("")}\n
`}function Ri(t,e,i){const r="current"===(e.chart_metric||"power"),o=!!t.panel_entities?.site_power,a=!!t.panel_entities?.dsm_state,s=!!t.panel_entities?.current_power,l=!!t.panel_entities?.feedthrough_power,c=!!t.panel_entities?.pv_power,d=!!t.panel_entities?.battery_level;return`\n
\n ${o?`\n
\n ${n("header.site")}\n
\n ${ki}\n ${r?"A":"kW"}\n
\n
`:""}\n ${a?`\n
\n ${n("header.grid")}\n
\n ${ki}\n
\n
`:""}\n ${s?`\n
\n ${n("header.upstream")}\n
\n ${ki}\n ${r?"A":"kW"}\n
\n
`:""}\n ${l?`\n
\n ${n("header.downstream")}\n
\n ${ki}\n ${r?"A":"kW"}\n
\n
`:""}\n ${c?`\n
\n ${n("header.solar")}\n
\n ${ki}\n ${r?"A":"kW"}\n
\n
`:""}\n ${d?`\n
\n ${n("header.battery")}\n
\n ${ki}\n %\n
\n
`:""}\n
\n `}function Ni(t,e,i={}){const r=Ft(t.device_name||n("header.default_name")),o=Ft(t.serial||""),a=Ft(t.firmware||""),s="current"===(e.chart_metric||"power"),l=!1!==i.showSwitches;return`\n
\n
\n
\n

${r}

\n ${o}\n \n ${l?Li(an(t)):""}\n
\n ${Ri(t,e)}\n
\n
\n
\n ${a}\n
\n \n \n
\n
\n ${Ei()}\n
\n
\n `}function Oi(t){const e=t.chart_metric??r;return h[e]??h[r]}function zi(t,e){const n=function(t){return Oi(t).entityRole}(e);return t.entities?.[n]??t.entities?.power??null}function $i(t,e){return un(t)||(e?n("grid.shared_switch"):"")}function Hi(t,e,i,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"),i.mayOperate||o.push("toggle-forbidden");const a=$i(i,r);return`
\n ${n(t?"grid.on":"grid.off")}\n \n
`}function Fi(t,e,i,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"!==i),o.classList.toggle("toggle-forbidden",!r.mayOperate);const a=$i(r,o.classList.contains("toggle-shared"));a?o.title=a:o.removeAttribute("title");const s=o.querySelector(".toggle-label");s&&(s.textContent=n(e?"grid.on":"grid.off"))}function Bi(t){return"unknown"===t?void 0:f[t]}const Vi="display:none;";function ji(t){const e=Bi(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 qi(t,e){const n=t.querySelector(".shedding-composite");if(!n)return;const i=Bi(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 Wi(t,e,i,r,o,a,s,l,c,d,u=[e],h=!1){const p=Wn(e,a),f=Xn(e,p),g=ti(e,a),m=ei(e,a),v=u.length>1,_=Ce(u),y=Ft(u.map(t=>t.name||n("grid.unknown")).join(" · ")),b="current"===Oi(s).entityRole?Di(Un(e,a)):Pi(p),x=ji(c||"unknown"),w=``;let S="";const C=Yn(e,a,l);null!==C&&(S=`${Math.round(C)}%`);return`\n
\n
\n
\n ${_?`${_}`:""}\n ${S}\n ${y}\n
\n
\n \n ${b}\n \n ${Hi(g,m,d,v&&function(t){const e=t[0]?.shared_relay_group;return!!e&&t.every(t=>t.shared_relay_group===e)}(u))}\n
\n
\n
\n ${x}\n ${w}\n
\n
\n
\n `}function Ui(t,e){return`\n
\n —\n
\n `}function Gi(t){return"function"==typeof globalThis.CSS?.escape?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function Xi(t){return Object.entries(t.circuits).filter(([,t])=>$n(t))}function Yi(t,e,n){return`${Ft(function(t){const e=Pn(t);if(null===e)return ki;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 Zi(t,e,i){const r=Wn(t,e),o=null===r||0===r?"":n(r>0?"meters.importing":"meters.exporting");return`\n ${"current"===Oi(i).entityRole?Di(Un(t,e)):Pi(r)}\n ${Ft(o)}\n ${Yi(e,t.entities?.consumed_energy,n("meters.imported"))}\n ${Yi(e,t.entities?.produced_energy,n("meters.exported"))}\n `}function Ki(t,e,i){if(!function(t,e){return!1!==e.show_panel&&Xi(t).length>0}(t,i))return"";const r=Xi(t).map(([t,r])=>`\n
\n ${Ft(r.name||n("grid.unknown"))}\n ${Zi(r,e,i)}\n
`).join("");return`\n
\n
${Ft(n("meters.title"))}
\n ${r}\n
\n `}function Qi(t,e,i,r){const o=!1!==i.show_battery,a=!1!==i.show_evse,s=!1!==i.show_solar;if(!t.sub_devices)return"";const u=function(t,e=()=>""){const n=t=>"site"===t.solar?.role?0:1,i=new Map;for(const n of t){if(n[1].type!==d)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!==d){r.push(n);continue}const t=e(n[0]);o.has(t)||(o.add(t),r.push(...i.get(t)??[]))}return r}(Object.entries(t.sub_devices).filter(([,t])=>!(t.type===l&&!o)&&(!(t.type===c&&!a)&&!(t.type===d&&!s))),function(t){if(!Qe(t))return()=>"";const e=t._favoriteRefs;return t=>e[t]?.panelDeviceId??""}(t));if(0===u.length)return"";const h=[];for(const[t,n]of u){const r=Dn(n),o=n.type===l,a=o?An(n):null,s=o?In(n):null,c=nr(n,e,i,Ln(n)),d=ir(t,n,o,r.headlineEid,a,s),u=n.solar?tr(n.solar,r,e):"";(r.headlineEid||d||c||u)&&h.push({devId:t,sub:n,power:r,chartsHTML:d,entHTML:c,solarHTML:u})}if(0===h.length)return"";const p=h.filter(t=>t.sub.type===c).length;let f=0,g="";for(const{devId:t,sub:i,power:o,chartsHTML:a,entHTML:s,solarHTML:d}of h){const u=Ji(i),h=o.headlineIsSiteTotal?`${Ft(n("subdevice.site_total"))}`:"",m=o.headlineEid?`${h}${Ii(Rn(e,o.headlineEid))}`:"",v=On(i,r.showFavorites)?``:"",_=i.type===l,y=i.type===c;let b="";_?b="sub-device-bess":y&&(f++,f===p&&p%2==1&&(b="sub-device-full")),g+=`\n
\n
\n ${Ft(u)}\n ${Ft(i.name||"")}\n ${m}\n ${v}\n
\n ${a}\n ${d}\n ${s}\n
\n `}return g}function Ji(t){return t.type===d?"inverter"===t.solar?.role?n("subdevice.solar_inverter"):n("subdevice.solar"):t.type===c?n("subdevice.ev_charger"):t.type===l?n("subdevice.battery"):n("subdevice.fallback")}function tr(t,e,i){let r="";const o="role"===t.identity?"":[t.vendor,t.model].filter(t=>!!t).join(" · ");if(o&&(r+=`
${Ft(o)}
`),e.siteTotalEid){const t=Rn(i,e.siteTotalEid);r+=`\n
\n ${Ft(n("subdevice.site_total"))}:\n ${Ii(t)}\n
`}return"inverter"!==t.role||e.headlineEid||(r+=`
${Ft(n("subdevice.in_site_total"))}
`),r}function er(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&&xi(r)||e}function nr(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||er(e,n);const c=t.name||"";let d;if(l.startsWith(c+" ")&&(l=l.slice(c.length+1)),e.formatEntityState)d=e.formatEntityState(s);else{d=s.state;const t=s.attributes.unit_of_measurement||"";t&&(d+=" "+t)}if("Wh"===(s.attributes.unit_of_measurement||"")){const t=Pn(s);null!==t&&(d=(t/1e3).toFixed(1)+" kWh")}o+=`\n
\n ${Ft(l)}:\n ${Ft(d)}\n
\n `}return o}function ir(t,e,i,r,o,a){if(i){const e=[{key:`${u}${t}_soc`,title:n("subdevice.soc"),available:!!o},{key:`${u}${t}_soe`,title:n("subdevice.soe"),available:!!a},{key:`${u}${t}_power`,title:n("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 rr(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 or(t){const e=a[t];return e?e.ms:a[o].ms}function ar(t){const e=t/1e3;return e<=600?Math.ceil(e):Math.min(5e3,Math.ceil(e/5))}function sr(t){return Math.max(500,Math.floor(t/5e3))}function lr(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 cr(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 dr(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 ur(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 hr(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=ar(i),l=sr(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,cr(n,s,l))}}}function pr(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 En(i))e.push({entityId:r,key:`${u}${n}_${t}`,devId:n});return e}async function fr(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=zi(i,n);if(!e)continue;let o;o=r&&r.has(t)?or(r.get(t)):rr(n),dr(a,o,e,t)}for(const{entityId:t,key:i,devId:r}of pr(e)){let e;e=o&&o.has(r)?or(o.get(r)):rr(n),dr(a,e,t,i)}const s=[];for(const[e,n]of a){if(0===n.entityIds.length)continue;e>2592e5?s.push(ur(t,n.entityIds,n.keysByEntity,e,i)):s.push(hr(t,n.entityIds,n.keysByEntity,e,i))}await Promise.all(s)}var gr=function(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1},mr=new function(){this.browser=new gr,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?(mr.wxa=!0,mr.touchEventsSupported=!0):"undefined"==typeof document&&"undefined"!=typeof self?mr.worker=!0:!mr.hasGlobalWindow||"Deno"in window||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Node.js")>-1?(mr.node=!0,mr.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,mr);var vr="sans-serif",_r="12px "+vr;var yr,br,xr=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(){qr(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 d=t[c].getBoundingClientRect(),u=2*c,h=d.left,p=d.top;a.push(h,p),l=l&&o&&h===o[u]&&p===o[u+1],s.push(t[c].offsetLeft,t[c].offsetTop)}return l&&r?r:(e.srcCoords=a,e[i]=n?qo(s,a):qo(a,s))}(a,o,r);if(s)return s(t,n,i),!0}return!1}function Xo(t){return"CANVAS"===t.nodeName.toUpperCase()}var Yo=/([&<>"'])/g,Zo={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ko(t){return null==t?"":(t+"").replace(Yo,function(t,e){return Zo[e]})}var Qo=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Jo=[],ta=mr.browser.firefox&&+mr.browser.version.split(".")[0]<39;function ea(t,e,n,i){return n=n||{},i?na(t,e,n):ta&&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):na(t,e,n),n}function na(t,e,n){if(mr.domSupported&&t.getBoundingClientRect){var i=e.clientX,r=e.clientY;if(Xo(t)){var o=t.getBoundingClientRect();return n.zrX=i-o.left,void(n.zrY=r-o.top)}if(Go(Jo,t,i,r))return n.zrX=Jo[0],void(n.zrY=Jo[1])}n.zrX=n.zrY=0}function ia(t){return t||window.event}function ra(t,e,n){if(null!=(e=ia(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&&ea(t,r,e,n)}else{ea(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&&Qo.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function oa(t,e,n,i){t.removeEventListener(e,n,i)}var aa=function(t){t.preventDefault(),t.stopPropagation(),t.cancelBubble=!0},sa=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=la(r)/la(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 da(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function ua(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 ha(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 pa(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 fa(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],d=Math.sin(n),u=Math.cos(n);return t[0]=r*u+s*d,t[1]=-r*d+s*u,t[2]=o*u+l*d,t[3]=-o*d+u*l,t[4]=u*(a-i[0])+d*(c-i[1])+i[0],t[5]=u*(c-i[1])-d*(a-i[0])+i[1],t}function ga(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 ma=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}(),va=Math.min,_a=Math.max,ya=Math.abs,ba=["x","y"],xa=["width","height"],wa=new ma,Sa=new ma,Ca=new ma,ka=new ma,Ma=Ra(),Ta=Ma.minTv,Aa=Ma.maxTv,Ia=[0,0],Pa=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=va(t.x,this.x),n=va(t.y,this.y);isFinite(this.x)&&isFinite(this.width)?this.width=_a(t.x+t.width,this.x+this.width)-e:this.width=t.width,isFinite(this.y)&&isFinite(this.height)?this.height=_a(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 pa(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]),pa(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&&ma.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(Da,e.x,e.y,e.width,e.height)),n instanceof t||(n=t.set(La,n.x,n.y,n.width,n.height));var s=!!i;Ma.reset(r,s);var l=Ma.touchThreshold,c=e.x+l,d=e.x+e.width-l,u=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>d||u>h||p>f||g>m)return!1;var v=!(d=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))}wa.x=Ca.x=n.x,wa.y=ka.y=n.y,Sa.x=ka.x=n.x+n.width,Sa.y=Ca.y=n.y+n.height,wa.transform(i),ka.transform(i),Sa.transform(i),Ca.transform(i),e.x=va(wa.x,Sa.x,Ca.x,ka.x),e.y=va(wa.y,Sa.y,Ca.y,ka.y);var l=_a(wa.x,Sa.x,Ca.x,ka.x),c=_a(wa.y,Sa.y,Ca.y,ka.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Da=new Pa(0,0,0,0),La=new Pa(0,0,0,0);function Ea(t,e,n,i,r,o,a,s){var l=ya(e-n),c=ya(i-t),d=va(l,c),u=ba[r],h=ba[1-r],p=xa[r];e=c||!Ma.bidirectional)&&(Ta[u]=-c,Ta[h]=0,Ma.useDir&&Ma.calcDirMTV())))}function Ra(){var t=0,e=new ma,n=new ma,i={minTv:new ma,maxTv:new ma,useDir:!1,dirMinTv:new ma,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(r,o){i.touchThreshold=0,r&&null!=r.touchThreshold&&(i.touchThreshold=_a(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),d=l*o.y+c*o.x;r(d)?r(o.x)&&r(o.y)&&a.set(0,0):(n.x=s*c/d,n.y=s*l/d,r(n.x)&&r(n.y)?a.set(0,0):(i.bidirectional||e.dot(n)>0)&&n.len()=0;c--){var d=i[c];d===n||d.ignore||d.ignoreCoarsePointer||d.parent&&d.parent.ignoreCoarsePointer||(Fa.copy(d.getBoundingRect()),d.transform&&Fa.applyTransform(d.transform),Fa.intersect(l)&&o.push(d))}if(o.length)for(var u=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=Va(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==Na)){e.target=a;break}}}function qa(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}qr(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){Ba.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=qa(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||Ro(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function Wa(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 Ua(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 Ga(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+d])>0?a=d+1:l=d}return l}function Xa(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+d])<0?l=d:a=d+1}return l}function Ya(t,e){var n,i,r=7,o=0,a=[];function s(s){var l=n[s],c=i[s],d=n[s+1],u=i[s+1];i[s]=c+u,s===o-3&&(n[s+1]=n[s+2],i[s+1]=i[s+2]),o--;var h=Xa(t[d],t,l,c,0,e);l+=h,0!==(c-=h)&&0!==(u=Ga(t[l+c-1],t,d,u,u-1,e))&&(c<=u?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[u]=a[d])}var f=r;for(;;){var g=0,m=0,v=!1;do{if(e(a[d],t[c])<0){if(t[u--]=t[c--],g++,m=0,0===--i){v=!0;break}}else if(t[u--]=a[d--],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[u--]=a[d--],1===--s){v=!0;break}if(0!==(m=s-Ga(t[c],a,0,s,s-1,e))){for(s-=m,p=(u-=m)+1,h=(d-=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=(u-=i)+1,h=(c-=i)+1,l=i-1;l>=0;l--)t[p+l]=t[h+l];t[u]=a[d]}else{if(0===s)throw new Error;for(h=u-(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=Wa(t,n,i,e))s&&(l=s),Ua(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 Ka=!1;function Qa(){Ka||(Ka=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function Ja(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var ts,es=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=Ja}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}();ts=mr.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){return setTimeout(t,16)};var ns={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-ns.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*ns.bounceIn(2*t):.5*ns.bounceOut(2*t-1)+.5}},is=Math.pow,rs=Math.sqrt,os=1e-8,as=1e-4,ss=rs(3),ls=1/3,cs=To(),ds=To(),us=To();function hs(t){return t>-1e-8&&tos||t<-1e-8}function fs(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 gs(t,e,n,i,r){var o=1-r;return 3*(((e-t)*o+2*(n-e)*r)*o+(i-n)*r*r)}function ms(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,d=s*s-3*a*l,u=s*l-9*a*c,h=l*l-3*s*c,p=0;if(hs(d)&&hs(u)){if(hs(s))o[0]=0;else(C=-l/s)>=0&&C<=1&&(o[p++]=C)}else{var f=u*u-4*d*h;if(hs(f)){var g=u/d,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=rs(f),_=d*s+1.5*a*(-u+v),y=d*s+1.5*a*(-u-v);(C=(-s-((_=_<0?-is(-_,ls):is(_,ls))+(y=y<0?-is(-y,ls):is(y,ls))))/(3*a))>=0&&C<=1&&(o[p++]=C)}else{var b=(2*d*s-3*a*u)/(2*rs(d*d*d)),x=Math.acos(b)/3,w=rs(d),S=Math.cos(x),C=(-s-2*w*S)/(3*a),k=(m=(-s+w*(S+ss*Math.sin(x)))/(3*a),(-s+w*(S-ss*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 vs(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(hs(a)){if(ps(o))(d=-s/o)>=0&&d<=1&&(r[l++]=d)}else{var c=o*o-4*a*s;if(hs(c))r[0]=-o/(2*a);else if(c>0){var d,u=rs(c),h=(-o-u)/(2*a);(d=(-o+u)/(2*a))>=0&&d<=1&&(r[l++]=d),h>=0&&h<=1&&(r[l++]=h)}}return l}function _s(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,d=(l-s)*r+s,u=(d-c)*r+c;o[0]=t,o[1]=a,o[2]=c,o[3]=u,o[4]=u,o[5]=d,o[6]=l,o[7]=i}function ys(t,e,n,i,r,o,a,s,l){for(var c=t,d=e,u=0,h=1/l,p=1;p<=l;p++){var f=p*h,g=fs(t,n,r,a,f),m=fs(e,i,o,s,f),v=g-c,_=m-d;u+=Math.sqrt(v*v+_*_),c=g,d=m}return u}function bs(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function xs(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function ws(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function Ss(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 Cs(t,e,n,i,r,o,a){for(var s=t,l=e,c=0,d=1/a,u=1;u<=a;u++){var h=u*d,p=bs(t,n,r,h),f=bs(e,i,o,h),g=p-s,m=f-l;c+=Math.sqrt(g*g+m*m),s=p,l=f}return c}var ks=/cubic-bezier\(([0-9,\.e ]+)\)/;function Ms(t){var e=t&&ks.exec(t);if(e){var n=e[1].split(","),i=+go(n[0]),r=+go(n[1]),o=+go(n[2]),a=+go(n[3]);if(isNaN(i+r+o+a))return;var s=[];return function(t){return t<=0?0:t>=1?1:ms(0,i,o,1,t,s)&&fs(0,r,a,1,s[0])}}}var Ts=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||ko,this.ondestroy=t.ondestroy||ko,this.onrestart=t.onrestart||ko,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=Qr(t)?t:ns[t]||Ms(t)},t}(),As=function(t){this.value=t},Is=function(){function t(){this._len=0}return t.prototype.insert=function(t){var e=new As(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}(),Ps=function(){function t(t){this._list=new Is,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 As(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}(),Ds={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 Ls(t){return(t=Math.round(t))<0?0:t>255?255:t}function Es(t){return t<0?0:t>1?1:t}function Rs(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Ls(parseFloat(e)/100*255):Ls(parseInt(e,10))}function Ns(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Es(parseFloat(e)/100):Es(parseFloat(e))}function Os(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 zs(t,e,n){return t+(e-t)*n}function $s(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function Hs(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}var Fs=new Ps(20),Bs=null;function Vs(t,e){Bs&&Hs(Bs,e),Bs=Fs.put(t,Bs||e.slice())}function js(t,e){if(t){e=e||[];var n=Fs.get(t);if(n)return Hs(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in Ds)return Hs(e,Ds[i]),Vs(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?($s(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),Vs(t,e),e):void $s(e,0,0,0,1):7===o||9===o?(r=parseInt(i.slice(1,7),16))>=0&&r<=16777215?($s(e,(16711680&r)>>16,(65280&r)>>8,255&r,9===o?parseInt(i.slice(7),16)/255:1),Vs(t,e),e):void $s(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(","),d=1;switch(l){case"rgba":if(4!==c.length)return 3===c.length?$s(e,+c[0],+c[1],+c[2],1):$s(e,0,0,0,1);d=Ns(c.pop());case"rgb":return c.length>=3?($s(e,Rs(c[0]),Rs(c[1]),Rs(c[2]),3===c.length?d:Ns(c[3])),Vs(t,e),e):void $s(e,0,0,0,1);case"hsla":return 4!==c.length?void $s(e,0,0,0,1):(c[3]=Ns(c[3]),qs(c,e),Vs(t,e),e);case"hsl":return 3!==c.length?void $s(e,0,0,0,1):(qs(c,e),Vs(t,e),e);default:return}}$s(e,0,0,0,1)}}function qs(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=Ns(t[1]),r=Ns(t[2]),o=r<=.5?r*(i+1):r+i-r*i,a=2*r-o;return $s(e=e||[],Ls(255*Os(a,o,n+1/3)),Ls(255*Os(a,o,n)),Ls(255*Os(a,o,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function Ws(t,e){var n=js(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 Gs(n,4===n.length?"rgba":"rgb")}}function Us(t,e,n,i){var r=js(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 d=((s-i)/6+l/2)/l,u=((s-r)/6+l/2)/l,h=((s-o)/6+l/2)/l;i===s?e=h-u:r===s?e=1/3+d-h:o===s&&(e=2/3+u-d),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]=Ns(Qr(n)?n(r[1]):n)),null!=i&&(r[2]=Ns(Qr(i)?i(r[2]):i)),Gs(qs(r),"rgba")}function Gs(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 Xs(t,e){var n=js(t);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*e:0}var Ys=new Ps(100);function Zs(t){if(Jr(t)){var e=Ys.get(t);return e||(e=Ws(t,-.1),Ys.put(t,e)),e}if(ao(t)){var n=Hr({},t);return n.colorStops=Wr(t.colorStops,function(t){return{offset:t.offset,color:Ws(t.color,-.1)}}),n}return t}var Ks=Math.round;function Qs(t){var e;if(t&&"transparent"!==t){if("string"==typeof t&&t.indexOf("rgba")>-1){var n=js(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 Js=1e-4;function tl(t){return t-1e-4}function el(t){return Ks(1e3*t)/1e3}function nl(t){return Ks(1e4*t)/1e4}var il={left:"start",right:"end",center:"middle",middle:"middle"};function rl(t){return t&&!!t.image}function ol(t){return rl(t)||function(t){return t&&!!t.svgElement}(t)}function al(t){return"linear"===t.type}function sl(t){return"radial"===t.type}function ll(t){return t&&("linear"===t.type||"radial"===t.type)}function cl(t){return"url(#"+t+")"}function dl(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 ul(t){var e=t.x||0,n=t.y||0,i=(t.rotation||0)*Mo,r=co(t.scaleX,1),o=co(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("+Ks(a*Mo)+"deg, "+Ks(s*Mo)+"deg)"),l.join(" ")}var hl=mr.hasGlobalWindow&&Qr(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},pl=Array.prototype.slice;function fl(t,e,n){return(e-t)*n+t}function gl(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(jr(e)){var l=function(t){return jr(t&&t[0])?2:1}(e);a=l,(1===l&&!eo(e[0])||2===l&&!eo(e[0][0]))&&(o=!0)}else if(eo(e)&&!so(e))a=0;else if(Jr(e))if(isNaN(+e)){var c=js(e);c&&(s=c,a=3)}else a=0;else if(ao(e)){var d=Hr({},s);d.colorStops=Wr(e.colorStops,function(t){return{offset:t.offset,color:js(t.color)}}),al(e)?a=4:sl(e)&&(a=5),s=d}0===r?this.valType=a:a===this.valType&&6!==a||(o=!0),this.discrete=this.discrete||o;var u={time:t,value:s,rawValue:e,percent:0};return n&&(u.easing=n,u.easingFunc=Qr(n)?n:ns[n]||Ms(n)),i.push(u),u},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=Sl(i),l=wl(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:u?Cl:t[d];if(!Sl(s)&&!u||m||(m=this._additiveValue=[]),this.discrete)t[d]=g<1?i.rawValue:r.rawValue;else if(Sl(s))1===s?gl(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,bl(l),i),this._trackKeys.push(a)}s.addKeyframe(t,bl(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 Tl(){return(new Date).getTime()}var Al,Il,Pl=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 v(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=Tl()-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,ts(function e(){t._running&&(ts(e),!t._paused&&t.update())})},e.prototype.start=function(){this._running||(this._time=Tl(),this._pausedTime=0,this._startLoop())},e.prototype.stop=function(){this._running=!1},e.prototype.pause=function(){this._paused||(this._pauseStart=Tl(),this._paused=!0)},e.prototype.resume=function(){this._paused&&(this._pausedTime+=Tl()-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 Ml(t,e.loop);return this.addAnimator(n),n},e}(Bo),Dl=mr.domSupported,Ll=(Il={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},{mouse:Al=["click","dblclick","mousewheel","wheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],touch:["touchstart","touchend","touchmove"],pointer:Wr(Al,function(t){var e=t.replace("mouse","pointer");return Il.hasOwnProperty(e)?e:t})}),El=["mousemove","mouseup"],Rl=["pointermove","pointerup"],Nl=!1;function Ol(t){var e=t.pointerType;return"pen"===e||"touch"===e}function zl(t){t&&(t.zrByTouch=!0)}function $l(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 Hl=function(t,e){this.stopPropagation=ko,this.stopImmediatePropagation=ko,this.preventDefault=ko,this.type=e.type,this.target=this.currentTarget=t.dom,this.pointerType=e.pointerType,this.clientX=e.clientX,this.clientY=e.clientY},Fl={mousedown:function(t){t=ra(this.dom,t),this.__mayPointerCapture=[t.zrX,t.zrY],this.trigger("mousedown",t)},mousemove:function(t){t=ra(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=ra(this.dom,t),this.__togglePointerCapture(!1),this.trigger("mouseup",t)},mouseout:function(t){$l(this,(t=ra(this.dom,t)).toElement||t.relatedTarget)||(this.__pointerCapturing&&(t.zrEventControl="no_globalout"),this.trigger("mouseout",t))},wheel:function(t){Nl=!0,t=ra(this.dom,t),this.trigger("mousewheel",t)},mousewheel:function(t){Nl||(t=ra(this.dom,t),this.trigger("mousewheel",t))},touchstart:function(t){zl(t=ra(this.dom,t)),this.__lastTouchMoment=new Date,this.handler.processGesture(t,"start"),Fl.mousemove.call(this,t),Fl.mousedown.call(this,t)},touchmove:function(t){zl(t=ra(this.dom,t)),this.handler.processGesture(t,"change"),Fl.mousemove.call(this,t)},touchend:function(t){zl(t=ra(this.dom,t)),this.handler.processGesture(t,"end"),Fl.mouseup.call(this,t),+new Date-+this.__lastTouchMoment<300&&Fl.click.call(this,t)},pointerdown:function(t){Fl.mousedown.call(this,t)},pointermove:function(t){Ol(t)||Fl.mousemove.call(this,t)},pointerup:function(t){Fl.mouseup.call(this,t)},pointerout:function(t){Ol(t)||Fl.mouseout.call(this,t)}};qr(["click","dblclick","contextmenu"],function(t){Fl[t]=function(e){e=ra(this.dom,e),this.trigger(t,e)}});var Bl={pointermove:function(t){Ol(t)||Bl.mousemove.call(this,t)},pointerup:function(t){Bl.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 Vl(t,e){var n=e.domHandlers;mr.pointerEventsSupported?qr(Ll.pointer,function(i){ql(e,i,function(e){n[i].call(t,e)})}):(mr.touchEventsSupported&&qr(Ll.touch,function(i){ql(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)})}),qr(Ll.mouse,function(i){ql(e,i,function(r){r=ia(r),e.touching||n[i].call(t,r)})}))}function jl(t,e){function n(n){ql(e,n,function(i){i=ia(i),$l(t,i.target)||(i=function(t,e){return ra(t.dom,new Hl(t,e),!0)}(t,i),e.domHandlers[n].call(t,i))},{capture:!0})}mr.pointerEventsSupported?qr(Rl,n):mr.touchEventsSupported||qr(El,n)}function ql(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 Wl(t){var e=t.mounted;for(var n in e)e.hasOwnProperty(n)&&oa(t.domTarget,n,e[n],t.listenerOpts[n]);t.mounted={}}var Ul=function(t,e){this.mounted={},this.listenerOpts={},this.touching=!1,this.domTarget=t,this.domHandlers=e},Gl=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 Ul(e,Fl),Dl&&(i._globalHandlerScope=new Ul(document,Bl)),Vl(i,i._localHandlerScope),i}return v(e,t),e.prototype.dispose=function(){Wl(this._localHandlerScope),Dl&&Wl(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,Dl&&+this.__pointerCapturing^+t){this.__pointerCapturing=t;var e=this._globalHandlerScope;t?jl(this,e):Wl(e)}},e}(Bo),Xl=1;mr.hasGlobalWindow&&(Xl=Math.max(window.devicePixelRatio||window.screen&&window.screen.deviceXDPI/window.screen.logicalXDPI||1,1));var Yl=Xl,Zl="#333",Kl="#ccc",Ql=da,Jl=5e-5;function tc(t){return t>Jl||t<-5e-5}var ec,nc=[],ic=[],rc=[1,0,0,1,0,0],oc=Math.abs,ac=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 tc(this.rotation)||tc(this.x)||tc(this.y)||tc(this.scaleX-1)||tc(this.scaleY-1)||tc(this.skewX)||tc(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):Ql(n),t&&(e?ha(n,t,n):ua(n,t)),this.transform=n,this._resolveGlobalScaleRatio(n)):n&&(Ql(n),this.invTransform=null)},t.prototype._resolveGlobalScaleRatio=function(t){var e=this.globalScaleRatio;if(null!=e&&1!==e){this.getGlobalScale(nc);var n=nc[0]<0?-1:1,i=nc[1]<0?-1:1,r=((nc[0]-n)*e+n)/nc[0]||0,o=((nc[1]-i)*e+i)/nc[1]||0;t[0]*=r,t[1]*=r,t[2]*=o,t[3]*=o}this.invTransform=this.invTransform||[1,0,0,1,0,0],ga(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],ha(ic,t.invTransform,e),e=ic);var n=this.originX,i=this.originY;(n||i)&&(rc[4]=n,rc[5]=i,ha(ic,e,rc),ic[4]-=n,ic[5]-=i,e=ic),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&&Oo(n,n,i),n},t.prototype.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&Oo(n,n,i),n},t.prototype.getLineScale=function(){var t=this.transform;return t&&oc(t[0]-1)>1e-10&&oc(t[3]-1)>1e-10?Math.sqrt(oc(t[0]*t[3]-t[2]*t[1])):1},t.prototype.copyTransform=function(t){lc(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,d=t.y,u=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-u*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]=u*o,l&&fa(e,e,l),e[4]+=n+c,e[5]+=i+d,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}(),sc=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function lc(t,e){for(var n=0;n=uc)){t=t||_r;for(var e=[],n=+new Date,i=0;i<=127;i++)e[i]=wr.measureText(String.fromCharCode(i),t).width;var r=+new Date-n;return r>16?dc=uc:r>2&&dc++,e}}(t.font),t.asciiWidthMapTried=!0),0<=e&&e<=127?null!=t.asciiWidthMap?t.asciiWidthMap[e]:t.asciiCharWidth:t.stWideCharWidth}function pc(t,e){var n=t.strWidthCache,i=n.get(e);return null==i&&(i=wr.measureText(e,t.font).width,n.put(e,i)),i}function fc(t,e,n,i){var r=pc(cc(e),t),o=_c(e),a=mc(0,r,n),s=vc(0,o,i);return new Pa(a,s,r,o)}function gc(t,e,n,i){var r=((t||"")+"").split("\n");if(1===r.length)return fc(r[0],e,n,i);for(var o=new Pa(0,0,0,0),a=0;a=0?parseFloat(t)/100*e:parseFloat(t):t}function bc(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,d="left",u="top";if(i instanceof Array)l+=yc(i[0],n.width),c+=yc(i[1],n.height),d=null,u=null;else switch(i){case"left":l-=r,c+=s,d="right",u="middle";break;case"right":l+=r+a,c+=s,u="middle";break;case"top":l+=a/2,c-=r,d="center",u="bottom";break;case"bottom":l+=a/2,c+=o+r,d="center";break;case"inside":l+=a/2,c+=s,d="center",u="middle";break;case"insideLeft":l+=r,c+=s,u="middle";break;case"insideRight":l+=a-r,c+=s,d="right",u="middle";break;case"insideTop":l+=a/2,c+=r,d="center";break;case"insideBottom":l+=a/2,c+=o-r,d="center",u="bottom";break;case"insideTopLeft":l+=r,c+=r;break;case"insideTopRight":l+=a-r,c+=r,d="right";break;case"insideBottomLeft":l+=r,c+=o-r,u="bottom";break;case"insideBottomRight":l+=a-r,c+=o-r,d="right",u="bottom"}return(t=t||{}).x=l,t.y=c,t.align=d,t.verticalAlign=u,t}var xc="__zr_normal__",wc=sc.concat(["ignore"]),Sc=Ur(sc,function(t,e){return t[e]=!0,t},{ignore:!1}),Cc={},kc=new Pa(0,0,0,0),Mc=[],Tc=function(){function t(t){this.id=Nr(),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,d=n.autoOverflowArea,u=void 0;if((d||c)&&(u=kc,n.layoutRect?u.copy(n.layoutRect):u.copy(this.getBoundingRect()),i||u.applyTransform(this.transform)),c){this.calculateTextPosition?this.calculateTextPosition(Cc,n,u):bc(Cc,n,u),r.x=Cc.x,r.y=Cc.y,o=Cc.align,a=Cc.verticalAlign;var h=n.origin;if(h&&null!=n.rotation){var p=void 0,f=void 0;"center"===h?(p=.5*u.width,f=.5*u.height):(p=yc(h[0],u.width),f=yc(h[1],u.height)),l=!0,r.originX=-r.x+p+(i?0:u.x),r.originY=-r.y+f+(i?0:u.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(d){var v=m.overflowRect=m.overflowRect||new Pa(0,0,0,0);r.getLocalTransform(Mc),ga(Mc,Mc),Pa.copy(v,u),v.applyTransform(Mc)}else m.overflowRect=null;var _=void 0,y=void 0,b=void 0;(null==n.inside?"string"==typeof n.position&&n.position.indexOf("inside")>=0:n.inside)&&this.canBeInsideText()?(_=n.insideFill,y=n.insideStroke,null!=_&&"auto"!==_||(_=this.getInsideTextFill()),null!=y&&"auto"!==y||(y=this.getInsideTextStroke(_),b=!0)):(_=n.outsideFill,y=n.outsideStroke,null!=_&&"auto"!==_||(_=this.getOutsideFill()),null!=y&&"auto"!==y||(y=this.getOutsideStroke(_),b=!0)),(_=_||"#000")===m.fill&&y===m.stroke&&b===m.autoStroke&&o===m.align&&a===m.verticalAlign||(s=!0,m.fill=_,m.stroke=y,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()?Kl:Zl},t.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),n="string"==typeof e&&js(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,Gs(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||{},Hr(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(no(t))for(var n=Xr(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(xc,!1,t)},t.prototype.useState=function(t,e,n,i){var r=t===xc;if(this.hasState()||!r){var o=this.currentStates,a=this.stateTransition;if(!(Br(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,d=this._textGuide;return c&&c.useState(t,e,n,l),d&&d.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}Or("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,u),g&&g.useStates(t,e,u),this._updateAnimationTargets(),this.currentStates=t.slice(),this.markRedraw(),!u&&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=Br(i,t),o=Br(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=0&&(n.splice(i,0,t),this._doAdd(t))}return this},e.prototype.replace=function(t,e){var n=Br(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=Br(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;nt?l.get(t):void 0;for(const t of Object.values(e.circuits)){const e=Object.values(t.entities).filter(t=>!!t),n=[d(t.device_id),...e.map(t=>a.get(t)),...e.map(t=>d(s.get(t))),d(c)];t.area=n.map(t=>t?o.get(t):void 0).find(t=>!!t)}}const Mi="loaded";async function Ti(t,e,n,{initialIsReseed:i,onStatus:r,onSeed:o}){const a=new Map,s=new Map;let l=!1;const c=t=>{const e=function({state:t,disabled_by:e}){return e?"disabled":"loaded"===t?"loaded":"setup_error"===t?"setup_failed":Re.has(t)?"restart_needed":"loading"}(t);s.get(t.entry_id)!==e&&(s.set(t.entry_id,e),r?.(t.entry_id,e))},d=t=>{s.delete(t),r?.(t,null)};return t.connection.subscribeMessage(t=>{if(t.every(t=>null===t.type)){const r=l||i;l=!0,a.clear();for(const{entry:i}of t)e(i)&&(a.set(i.entry_id,i.state),c(i),r&&i.state===Mi&&n(i.entry_id));for(const t of[...s.keys()])a.has(t)||d(t);return void o?.()}for(const{type:i,entry:r}of t){if(!e(r))continue;if("removed"===i){a.delete(r.entry_id),d(r.entry_id);continue}const t=a.get(r.entry_id);a.set(r.entry_id,r.state),c(r),"updated"===i&&r.state===Mi&&t!==Mi&&n(r.entry_id)}},{type:"config_entries/subscribe",type_filter:["device"]})}function Ai(t){return(t.name_by_user||t.name||"").trim()}async function Ii(t){const e=await t.callWS({type:"config_entries/get",domain:s});return new Set(e.map(t=>t.entry_id))}async function Pi(t){const[e,n]=await Promise.all([t.callWS({type:"config/device_registry/list"}),Ii(t)]);return e.filter(t=>function(t,e){return void 0!==t.config_entry_id&&e.has(t.config_entry_id)&&!t.via_device_id&&!t.parent_device_id}(t,n))}async function Di(t,e,i){const r={type:`${s}/panel_topology`,device_id:e},o=i?await i.callWS(t,r,{errorId:"fetch:topology"}):await t.callWS(r),a=jn(o.panel_size)?o.panel_size:function(t){let e=0;for(const n of Object.values(t))if(n&&!qn(n))for(const t of n.tabs)t>e&&(e=t);return e>0?e+e%2:0}(o.circuits);if(!Wn(o,a))throw new Error(n("card.topology_error"));const l={type:"config/device_registry/list"},c=i?await i.callWS(t,l,{errorId:"fetch:topology"}):await t.callWS(l);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?Ai(t):"";i&&(e.name=i)}}(o.circuits,c),await ki(t,o),{topology:o,panelSize:a}}const Li=h.power,Ei=h.current,Ri="--",Ni=`${Ri}`;function Oi(t){return Li.unit(t)}function zi(t){return(t<0?"-":"")+Li.format(t)}function $i(t){return null===t?Ni:`${zi(t)} ${Oi(t)}`}function Hi(t){return null===t?Ni:`${zi(t)}${Oi(t)}`}function Fi(t){return null===t?Ni:`${Ei.format(t)}A`}function Bi(t,e={}){const i=!t.mayOperate;return`
\n ${Ft(n("header.enable_switches"))}\n
\n \n
\n
${!1===e.note?"":Cn(t)}`}function Vi(){return`
\n ${Object.entries(f).filter(([t])=>"unknown"!==t).map(([,t])=>{const e=Ft(t.icon),n=Ft(t.color),i=Ft(t.label());let r;if(t.icon2){r=``}else if(t.textLabel){r=`${Ft(t.textLabel)}`}else r=``;return`
${r}${i}
`}).join("")}\n
`}function ji(t,e,i){const r="current"===(e.chart_metric||"power"),o=!!t.panel_entities?.site_power,a=!!t.panel_entities?.dsm_state,s=!!t.panel_entities?.current_power,l=!!t.panel_entities?.feedthrough_power,c=!!t.panel_entities?.pv_power,d=!!t.panel_entities?.battery_level;return`\n
\n ${o?`\n
\n ${n("header.site")}\n
\n ${Ri}\n ${r?"A":"kW"}\n
\n
`:""}\n ${a?`\n
\n ${n("header.grid")}\n
\n ${Ri}\n
\n
`:""}\n ${s?`\n
\n ${n("header.upstream")}\n
\n ${Ri}\n ${r?"A":"kW"}\n
\n
`:""}\n ${l?`\n
\n ${n("header.downstream")}\n
\n ${Ri}\n ${r?"A":"kW"}\n
\n
`:""}\n ${c?`\n
\n ${n("header.solar")}\n
\n ${Ri}\n ${r?"A":"kW"}\n
\n
`:""}\n ${d?`\n
\n ${n("header.battery")}\n
\n ${Ri}\n %\n
\n
`:""}\n
\n `}function qi(t,e,i={}){const r=Ft(t.device_name||n("header.default_name")),o=Ft(t.serial||""),a=Ft(t.firmware||""),s="current"===(e.chart_metric||"power"),l=!1!==i.showSwitches;return`\n
\n
\n
\n

${r}

\n ${o}\n \n ${l?Bi(hn(t)):""}\n
\n ${ji(t,e)}\n
\n
\n
\n ${a}\n
\n \n \n
\n
\n ${Vi()}\n
\n
\n `}function Wi(t){const e=t.chart_metric??r;return h[e]??h[r]}function Ui(t,e){const n=function(t){return Wi(t).entityRole}(e);return t.entities?.[n]??t.entities?.power??null}function Gi(t,e){return vn(t)||(e?n("grid.shared_switch"):"")}function Xi(t,e,i,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"),i.mayOperate||o.push("toggle-forbidden");const a=Gi(i,r);return`
\n ${n(t?"grid.on":"grid.off")}\n \n
`}function Yi(t,e,i,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"!==i),o.classList.toggle("toggle-forbidden",!r.mayOperate);const a=Gi(r,o.classList.contains("toggle-shared"));a?o.title=a:o.removeAttribute("title");const s=o.querySelector(".toggle-label");s&&(s.textContent=n(e?"grid.on":"grid.off"))}function Zi(t){return"unknown"===t?void 0:f[t]}const Ki="display:none;";function Qi(t){const e=Zi(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 Ji(t,e){const n=t.querySelector(".shedding-composite");if(!n)return;const i=Zi(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 tr(t,e,i,r,o,a,s,l,c,d,u=[e],h=!1){const p=Kn(e,a),f=ti(e,p),g=ai(e,a),m=si(e,a),v=u.length>1,_=Ce(u),y=Ft(u.map(t=>t.name||n("grid.unknown")).join(" · ")),b="current"===Wi(s).entityRole?Fi(Qn(e,a)):Hi(p),x=Qi(c||"unknown"),w=``;let S="";const C=ei(e,a,l);null!==C&&(S=`${Math.round(C)}%`);return`\n
\n
\n
\n ${_?`${_}`:""}\n ${S}\n ${y}\n
\n
\n \n ${b}\n \n ${Xi(g,m,d,v&&function(t){const e=t[0]?.shared_relay_group;return!!e&&t.every(t=>t.shared_relay_group===e)}(u))}\n
\n
\n
\n ${x}\n ${w}\n
\n
\n
\n `}function er(t,e){return`\n
\n —\n
\n `}function nr(t){return"function"==typeof globalThis.CSS?.escape?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function ir(t){return Object.entries(t.circuits).filter(([,t])=>qn(t))}function rr(t,e,n){return`${Ft(function(t){const e=On(t);if(null===e)return Ri;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 or(t,e,i){const r=Kn(t,e),o=null===r||0===r?"":n(r>0?"meters.importing":"meters.exporting");return`\n ${"current"===Wi(i).entityRole?Fi(Qn(t,e)):Hi(r)}\n ${Ft(o)}\n ${rr(e,t.entities?.consumed_energy,n("meters.imported"))}\n ${rr(e,t.entities?.produced_energy,n("meters.exported"))}\n `}function ar(t,e,i){if(!function(t,e){return!1!==e.show_panel&&ir(t).length>0}(t,i))return"";const r=ir(t).map(([t,r])=>`\n
\n ${Ft(r.name||n("grid.unknown"))}\n ${or(r,e,i)}\n
`).join("");return`\n
\n
${Ft(n("meters.title"))}
\n ${r}\n
\n `}function sr(t,e,i,r){const o=!1!==i.show_battery,a=!1!==i.show_evse,s=!1!==i.show_solar;if(!t.sub_devices)return"";const u=function(t,e=()=>""){const n=t=>"site"===t.solar?.role?0:1,i=new Map;for(const n of t){if(n[1].type!==d)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!==d){r.push(n);continue}const t=e(n[0]);o.has(t)||(o.add(t),r.push(...i.get(t)??[]))}return r}(Object.entries(t.sub_devices).filter(([,t])=>!(t.type===l&&!o)&&(!(t.type===c&&!a)&&!(t.type===d&&!s))),function(t){if(!on(t))return()=>"";const e=t._favoriteRefs;return t=>e[t]?.panelDeviceId??""}(t));if(0===u.length)return"";const h=[];for(const[t,n]of u){const r=zn(n),o=n.type===l,a=o?Rn(n):null,s=o?Nn(n):null,c=ur(n,e,i,$n(n)),d=hr(t,n,o,r.headlineEid,a,s),u=n.solar?cr(n.solar,r,e):"";(r.headlineEid||d||c||u)&&h.push({devId:t,sub:n,power:r,chartsHTML:d,entHTML:c,solarHTML:u})}if(0===h.length)return"";const p=h.filter(t=>t.sub.type===c).length;let f=0,g="";for(const{devId:t,sub:i,power:o,chartsHTML:a,entHTML:s,solarHTML:d}of h){const u=lr(i),h=o.headlineIsSiteTotal?`${Ft(n("subdevice.site_total"))}`:"",m=o.headlineEid?`${h}${$i(Fn(e,o.headlineEid))}`:"",v=Vn(i,r.showFavorites)?``:"",_=i.type===l,y=i.type===c;let b="";_?b="sub-device-bess":y&&(f++,f===p&&p%2==1&&(b="sub-device-full")),g+=`\n
\n
\n ${Ft(u)}\n ${Ft(i.name||"")}\n ${m}\n ${v}\n
\n ${a}\n ${d}\n ${s}\n
\n `}return g}function lr(t){return t.type===d?"inverter"===t.solar?.role?n("subdevice.solar_inverter"):n("subdevice.solar"):t.type===c?n("subdevice.ev_charger"):t.type===l?n("subdevice.battery"):n("subdevice.fallback")}function cr(t,e,i){let r="";const o="role"===t.identity?"":[t.vendor,t.model].filter(t=>!!t).join(" · ");if(o&&(r+=`
${Ft(o)}
`),e.siteTotalEid){const t=Fn(i,e.siteTotalEid);r+=`\n
\n ${Ft(n("subdevice.site_total"))}:\n ${$i(t)}\n
`}return"inverter"!==t.role||e.headlineEid||(r+=`
${Ft(n("subdevice.in_site_total"))}
`),r}function dr(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&&Ai(r)||e}function ur(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||dr(e,n);const c=t.name||"";let d;if(l.startsWith(c+" ")&&(l=l.slice(c.length+1)),e.formatEntityState)d=e.formatEntityState(s);else{d=s.state;const t=s.attributes.unit_of_measurement||"";t&&(d+=" "+t)}if("Wh"===(s.attributes.unit_of_measurement||"")){const t=On(s);null!==t&&(d=(t/1e3).toFixed(1)+" kWh")}o+=`\n
\n ${Ft(l)}:\n ${Ft(d)}\n
\n `}return o}function hr(t,e,i,r,o,a){if(i){const e=[{key:`${u}${t}_soc`,title:n("subdevice.soc"),available:!!o},{key:`${u}${t}_soe`,title:n("subdevice.soe"),available:!!a},{key:`${u}${t}_power`,title:n("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 pr(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 fr(t){const e=a[t];return e?e.ms:a[o].ms}function gr(t){const e=t/1e3;return e<=600?Math.ceil(e):Math.min(5e3,Math.ceil(e/5))}function mr(t){return Math.max(500,Math.floor(t/5e3))}function vr(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 _r(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 yr(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 br(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 xr(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=gr(i),l=mr(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,_r(n,s,l))}}}function wr(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 Hn(i))e.push({entityId:r,key:`${u}${n}_${t}`,devId:n});return e}async function Sr(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=Ui(i,n);if(!e)continue;let o;o=r&&r.has(t)?fr(r.get(t)):pr(n),yr(a,o,e,t)}for(const{entityId:t,key:i,devId:r}of wr(e)){let e;e=o&&o.has(r)?fr(o.get(r)):pr(n),yr(a,e,t,i)}const s=[];for(const[e,n]of a){if(0===n.entityIds.length)continue;e>2592e5?s.push(br(t,n.entityIds,n.keysByEntity,e,i)):s.push(xr(t,n.entityIds,n.keysByEntity,e,i))}await Promise.all(s)}var Cr=function(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1},kr=new function(){this.browser=new Cr,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?(kr.wxa=!0,kr.touchEventsSupported=!0):"undefined"==typeof document&&"undefined"!=typeof self?kr.worker=!0:!kr.hasGlobalWindow||"Deno"in window||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Node.js")>-1?(kr.node=!0,kr.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,kr);var Mr="sans-serif",Tr="12px "+Mr;var Ar,Ir,Pr=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(){Jr(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 d=t[c].getBoundingClientRect(),u=2*c,h=d.left,p=d.top;a.push(h,p),l=l&&o&&h===o[u]&&p===o[u+1],s.push(t[c].offsetLeft,t[c].offsetTop)}return l&&r?r:(e.srcCoords=a,e[i]=n?Jo(s,a):Jo(a,s))}(a,o,r);if(s)return s(t,n,i),!0}return!1}function ia(t){return"CANVAS"===t.nodeName.toUpperCase()}var ra=/([&<>"'])/g,oa={"&":"&","<":"<",">":">",'"':""","'":"'"};function aa(t){return null==t?"":(t+"").replace(ra,function(t,e){return oa[e]})}var sa=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,la=[],ca=kr.browser.firefox&&+kr.browser.version.split(".")[0]<39;function da(t,e,n,i){return n=n||{},i?ua(t,e,n):ca&&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):ua(t,e,n),n}function ua(t,e,n){if(kr.domSupported&&t.getBoundingClientRect){var i=e.clientX,r=e.clientY;if(ia(t)){var o=t.getBoundingClientRect();return n.zrX=i-o.left,void(n.zrY=r-o.top)}if(na(la,t,i,r))return n.zrX=la[0],void(n.zrY=la[1])}n.zrX=n.zrY=0}function ha(t){return t||window.event}function pa(t,e,n){if(null!=(e=ha(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&&da(t,r,e,n)}else{da(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&&sa.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function fa(t,e,n,i){t.removeEventListener(e,n,i)}var ga=function(t){t.preventDefault(),t.stopPropagation(),t.cancelBubble=!0},ma=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=va(r)/va(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 ya(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function ba(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 xa(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 wa(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 Sa(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],d=Math.sin(n),u=Math.cos(n);return t[0]=r*u+s*d,t[1]=-r*d+s*u,t[2]=o*u+l*d,t[3]=-o*d+u*l,t[4]=u*(a-i[0])+d*(c-i[1])+i[0],t[5]=u*(c-i[1])-d*(a-i[0])+i[1],t}function Ca(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 ka=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}(),Ma=Math.min,Ta=Math.max,Aa=Math.abs,Ia=["x","y"],Pa=["width","height"],Da=new ka,La=new ka,Ea=new ka,Ra=new ka,Na=ja(),Oa=Na.minTv,za=Na.maxTv,$a=[0,0],Ha=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=Ma(t.x,this.x),n=Ma(t.y,this.y);isFinite(this.x)&&isFinite(this.width)?this.width=Ta(t.x+t.width,this.x+this.width)-e:this.width=t.width,isFinite(this.y)&&isFinite(this.height)?this.height=Ta(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 wa(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]),wa(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&&ka.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(Fa,e.x,e.y,e.width,e.height)),n instanceof t||(n=t.set(Ba,n.x,n.y,n.width,n.height));var s=!!i;Na.reset(r,s);var l=Na.touchThreshold,c=e.x+l,d=e.x+e.width-l,u=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>d||u>h||p>f||g>m)return!1;var v=!(d=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))}Da.x=Ea.x=n.x,Da.y=Ra.y=n.y,La.x=Ra.x=n.x+n.width,La.y=Ea.y=n.y+n.height,Da.transform(i),Ra.transform(i),La.transform(i),Ea.transform(i),e.x=Ma(Da.x,La.x,Ea.x,Ra.x),e.y=Ma(Da.y,La.y,Ea.y,Ra.y);var l=Ta(Da.x,La.x,Ea.x,Ra.x),c=Ta(Da.y,La.y,Ea.y,Ra.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Fa=new Ha(0,0,0,0),Ba=new Ha(0,0,0,0);function Va(t,e,n,i,r,o,a,s){var l=Aa(e-n),c=Aa(i-t),d=Ma(l,c),u=Ia[r],h=Ia[1-r],p=Pa[r];e=c||!Na.bidirectional)&&(Oa[u]=-c,Oa[h]=0,Na.useDir&&Na.calcDirMTV())))}function ja(){var t=0,e=new ka,n=new ka,i={minTv:new ka,maxTv:new ka,useDir:!1,dirMinTv:new ka,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(r,o){i.touchThreshold=0,r&&null!=r.touchThreshold&&(i.touchThreshold=Ta(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),d=l*o.y+c*o.x;r(d)?r(o.x)&&r(o.y)&&a.set(0,0):(n.x=s*c/d,n.y=s*l/d,r(n.x)&&r(n.y)?a.set(0,0):(i.bidirectional||e.dot(n)>0)&&n.len()=0;c--){var d=i[c];d===n||d.ignore||d.ignoreCoarsePointer||d.parent&&d.parent.ignoreCoarsePointer||(Ya.copy(d.getBoundingRect()),d.transform&&Ya.applyTransform(d.transform),Ya.intersect(l)&&o.push(d))}if(o.length)for(var u=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=Ka(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==qa)){e.target=a;break}}}function Ja(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}Jr(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){Za.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=Ja(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||jo(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function ts(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 es(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 ns(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+d])>0?a=d+1:l=d}return l}function is(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+d])<0?l=d:a=d+1}return l}function rs(t,e){var n,i,r=7,o=0,a=[];function s(s){var l=n[s],c=i[s],d=n[s+1],u=i[s+1];i[s]=c+u,s===o-3&&(n[s+1]=n[s+2],i[s+1]=i[s+2]),o--;var h=is(t[d],t,l,c,0,e);l+=h,0!==(c-=h)&&0!==(u=ns(t[l+c-1],t,d,u,u-1,e))&&(c<=u?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[u]=a[d])}var f=r;for(;;){var g=0,m=0,v=!1;do{if(e(a[d],t[c])<0){if(t[u--]=t[c--],g++,m=0,0===--i){v=!0;break}}else if(t[u--]=a[d--],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[u--]=a[d--],1===--s){v=!0;break}if(0!==(m=s-ns(t[c],a,0,s,s-1,e))){for(s-=m,p=(u-=m)+1,h=(d-=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=(u-=i)+1,h=(c-=i)+1,l=i-1;l>=0;l--)t[p+l]=t[h+l];t[u]=a[d]}else{if(0===s)throw new Error;for(h=u-(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=ts(t,n,i,e))s&&(l=s),es(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 as=!1;function ss(){as||(as=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function ls(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var cs,ds=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=ls}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}();cs=kr.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){return setTimeout(t,16)};var us={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-us.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*us.bounceIn(2*t):.5*us.bounceOut(2*t-1)+.5}},hs=Math.pow,ps=Math.sqrt,fs=1e-8,gs=1e-4,ms=ps(3),vs=1/3,_s=Oo(),ys=Oo(),bs=Oo();function xs(t){return t>-1e-8&&tfs||t<-1e-8}function Ss(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 Cs(t,e,n,i,r){var o=1-r;return 3*(((e-t)*o+2*(n-e)*r)*o+(i-n)*r*r)}function ks(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,d=s*s-3*a*l,u=s*l-9*a*c,h=l*l-3*s*c,p=0;if(xs(d)&&xs(u)){if(xs(s))o[0]=0;else(C=-l/s)>=0&&C<=1&&(o[p++]=C)}else{var f=u*u-4*d*h;if(xs(f)){var g=u/d,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=ps(f),_=d*s+1.5*a*(-u+v),y=d*s+1.5*a*(-u-v);(C=(-s-((_=_<0?-hs(-_,vs):hs(_,vs))+(y=y<0?-hs(-y,vs):hs(y,vs))))/(3*a))>=0&&C<=1&&(o[p++]=C)}else{var b=(2*d*s-3*a*u)/(2*ps(d*d*d)),x=Math.acos(b)/3,w=ps(d),S=Math.cos(x),C=(-s-2*w*S)/(3*a),k=(m=(-s+w*(S+ms*Math.sin(x)))/(3*a),(-s+w*(S-ms*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 Ms(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(xs(a)){if(ws(o))(d=-s/o)>=0&&d<=1&&(r[l++]=d)}else{var c=o*o-4*a*s;if(xs(c))r[0]=-o/(2*a);else if(c>0){var d,u=ps(c),h=(-o-u)/(2*a);(d=(-o+u)/(2*a))>=0&&d<=1&&(r[l++]=d),h>=0&&h<=1&&(r[l++]=h)}}return l}function Ts(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,d=(l-s)*r+s,u=(d-c)*r+c;o[0]=t,o[1]=a,o[2]=c,o[3]=u,o[4]=u,o[5]=d,o[6]=l,o[7]=i}function As(t,e,n,i,r,o,a,s,l){for(var c=t,d=e,u=0,h=1/l,p=1;p<=l;p++){var f=p*h,g=Ss(t,n,r,a,f),m=Ss(e,i,o,s,f),v=g-c,_=m-d;u+=Math.sqrt(v*v+_*_),c=g,d=m}return u}function Is(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function Ps(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function Ds(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function Ls(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 Es(t,e,n,i,r,o,a){for(var s=t,l=e,c=0,d=1/a,u=1;u<=a;u++){var h=u*d,p=Is(t,n,r,h),f=Is(e,i,o,h),g=p-s,m=f-l;c+=Math.sqrt(g*g+m*m),s=p,l=f}return c}var Rs=/cubic-bezier\(([0-9,\.e ]+)\)/;function Ns(t){var e=t&&Rs.exec(t);if(e){var n=e[1].split(","),i=+Co(n[0]),r=+Co(n[1]),o=+Co(n[2]),a=+Co(n[3]);if(isNaN(i+r+o+a))return;var s=[];return function(t){return t<=0?0:t>=1?1:ks(0,i,o,1,t,s)&&Ss(0,r,a,1,s[0])}}}var Os=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||Ro,this.ondestroy=t.ondestroy||Ro,this.onrestart=t.onrestart||Ro,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=so(t)?t:us[t]||Ns(t)},t}(),zs=function(t){this.value=t},$s=function(){function t(){this._len=0}return t.prototype.insert=function(t){var e=new zs(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}(),Hs=function(){function t(t){this._list=new $s,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 zs(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}(),Fs={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 Bs(t){return(t=Math.round(t))<0?0:t>255?255:t}function Vs(t){return t<0?0:t>1?1:t}function js(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Bs(parseFloat(e)/100*255):Bs(parseInt(e,10))}function qs(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Vs(parseFloat(e)/100):Vs(parseFloat(e))}function Ws(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 Us(t,e,n){return t+(e-t)*n}function Gs(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function Xs(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}var Ys=new Hs(20),Zs=null;function Ks(t,e){Zs&&Xs(Zs,e),Zs=Ys.put(t,Zs||e.slice())}function Qs(t,e){if(t){e=e||[];var n=Ys.get(t);if(n)return Xs(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in Fs)return Xs(e,Fs[i]),Ks(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?(Gs(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),Ks(t,e),e):void Gs(e,0,0,0,1):7===o||9===o?(r=parseInt(i.slice(1,7),16))>=0&&r<=16777215?(Gs(e,(16711680&r)>>16,(65280&r)>>8,255&r,9===o?parseInt(i.slice(7),16)/255:1),Ks(t,e),e):void Gs(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(","),d=1;switch(l){case"rgba":if(4!==c.length)return 3===c.length?Gs(e,+c[0],+c[1],+c[2],1):Gs(e,0,0,0,1);d=qs(c.pop());case"rgb":return c.length>=3?(Gs(e,js(c[0]),js(c[1]),js(c[2]),3===c.length?d:qs(c[3])),Ks(t,e),e):void Gs(e,0,0,0,1);case"hsla":return 4!==c.length?void Gs(e,0,0,0,1):(c[3]=qs(c[3]),Js(c,e),Ks(t,e),e);case"hsl":return 3!==c.length?void Gs(e,0,0,0,1):(Js(c,e),Ks(t,e),e);default:return}}Gs(e,0,0,0,1)}}function Js(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=qs(t[1]),r=qs(t[2]),o=r<=.5?r*(i+1):r+i-r*i,a=2*r-o;return Gs(e=e||[],Bs(255*Ws(a,o,n+1/3)),Bs(255*Ws(a,o,n)),Bs(255*Ws(a,o,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function tl(t,e){var n=Qs(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 nl(n,4===n.length?"rgba":"rgb")}}function el(t,e,n,i){var r=Qs(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 d=((s-i)/6+l/2)/l,u=((s-r)/6+l/2)/l,h=((s-o)/6+l/2)/l;i===s?e=h-u:r===s?e=1/3+d-h:o===s&&(e=2/3+u-d),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]=qs(so(n)?n(r[1]):n)),null!=i&&(r[2]=qs(so(i)?i(r[2]):i)),nl(Js(r),"rgba")}function nl(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 il(t,e){var n=Qs(t);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*e:0}var rl=new Hs(100);function ol(t){if(lo(t)){var e=rl.get(t);return e||(e=tl(t,-.1),rl.put(t,e)),e}if(mo(t)){var n=Xr({},t);return n.colorStops=to(t.colorStops,function(t){return{offset:t.offset,color:tl(t.color,-.1)}}),n}return t}var al=Math.round;function sl(t){var e;if(t&&"transparent"!==t){if("string"==typeof t&&t.indexOf("rgba")>-1){var n=Qs(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 ll=1e-4;function cl(t){return t-1e-4}function dl(t){return al(1e3*t)/1e3}function ul(t){return al(1e4*t)/1e4}var hl={left:"start",right:"end",center:"middle",middle:"middle"};function pl(t){return t&&!!t.image}function fl(t){return pl(t)||function(t){return t&&!!t.svgElement}(t)}function gl(t){return"linear"===t.type}function ml(t){return"radial"===t.type}function vl(t){return t&&("linear"===t.type||"radial"===t.type)}function _l(t){return"url(#"+t+")"}function yl(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 bl(t){var e=t.x||0,n=t.y||0,i=(t.rotation||0)*No,r=yo(t.scaleX,1),o=yo(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("+al(a*No)+"deg, "+al(s*No)+"deg)"),l.join(" ")}var xl=kr.hasGlobalWindow&&so(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},wl=Array.prototype.slice;function Sl(t,e,n){return(e-t)*n+t}function Cl(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(Qr(e)){var l=function(t){return Qr(t&&t[0])?2:1}(e);a=l,(1===l&&!uo(e[0])||2===l&&!uo(e[0][0]))&&(o=!0)}else if(uo(e)&&!vo(e))a=0;else if(lo(e))if(isNaN(+e)){var c=Qs(e);c&&(s=c,a=3)}else a=0;else if(mo(e)){var d=Xr({},s);d.colorStops=to(e.colorStops,function(t){return{offset:t.offset,color:Qs(t.color)}}),gl(e)?a=4:ml(e)&&(a=5),s=d}0===r?this.valType=a:a===this.valType&&6!==a||(o=!0),this.discrete=this.discrete||o;var u={time:t,value:s,rawValue:e,percent:0};return n&&(u.easing=n,u.easingFunc=so(n)?n:us[n]||Ns(n)),i.push(u),u},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=Ll(i),l=Dl(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:u?El:t[d];if(!Ll(s)&&!u||m||(m=this._additiveValue=[]),this.discrete)t[d]=g<1?i.rawValue:r.rawValue;else if(Ll(s))1===s?Cl(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,Il(l),i),this._trackKeys.push(a)}s.addKeyframe(t,Il(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 Ol(){return(new Date).getTime()}var zl,$l,Hl=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 v(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=Ol()-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,cs(function e(){t._running&&(cs(e),!t._paused&&t.update())})},e.prototype.start=function(){this._running||(this._time=Ol(),this._pausedTime=0,this._startLoop())},e.prototype.stop=function(){this._running=!1},e.prototype.pause=function(){this._paused||(this._pauseStart=Ol(),this._paused=!0)},e.prototype.resume=function(){this._paused&&(this._pausedTime+=Ol()-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 Nl(t,e.loop);return this.addAnimator(n),n},e}(Zo),Fl=kr.domSupported,Bl=($l={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},{mouse:zl=["click","dblclick","mousewheel","wheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],touch:["touchstart","touchend","touchmove"],pointer:to(zl,function(t){var e=t.replace("mouse","pointer");return $l.hasOwnProperty(e)?e:t})}),Vl=["mousemove","mouseup"],jl=["pointermove","pointerup"],ql=!1;function Wl(t){var e=t.pointerType;return"pen"===e||"touch"===e}function Ul(t){t&&(t.zrByTouch=!0)}function Gl(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 Xl=function(t,e){this.stopPropagation=Ro,this.stopImmediatePropagation=Ro,this.preventDefault=Ro,this.type=e.type,this.target=this.currentTarget=t.dom,this.pointerType=e.pointerType,this.clientX=e.clientX,this.clientY=e.clientY},Yl={mousedown:function(t){t=pa(this.dom,t),this.__mayPointerCapture=[t.zrX,t.zrY],this.trigger("mousedown",t)},mousemove:function(t){t=pa(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=pa(this.dom,t),this.__togglePointerCapture(!1),this.trigger("mouseup",t)},mouseout:function(t){Gl(this,(t=pa(this.dom,t)).toElement||t.relatedTarget)||(this.__pointerCapturing&&(t.zrEventControl="no_globalout"),this.trigger("mouseout",t))},wheel:function(t){ql=!0,t=pa(this.dom,t),this.trigger("mousewheel",t)},mousewheel:function(t){ql||(t=pa(this.dom,t),this.trigger("mousewheel",t))},touchstart:function(t){Ul(t=pa(this.dom,t)),this.__lastTouchMoment=new Date,this.handler.processGesture(t,"start"),Yl.mousemove.call(this,t),Yl.mousedown.call(this,t)},touchmove:function(t){Ul(t=pa(this.dom,t)),this.handler.processGesture(t,"change"),Yl.mousemove.call(this,t)},touchend:function(t){Ul(t=pa(this.dom,t)),this.handler.processGesture(t,"end"),Yl.mouseup.call(this,t),+new Date-+this.__lastTouchMoment<300&&Yl.click.call(this,t)},pointerdown:function(t){Yl.mousedown.call(this,t)},pointermove:function(t){Wl(t)||Yl.mousemove.call(this,t)},pointerup:function(t){Yl.mouseup.call(this,t)},pointerout:function(t){Wl(t)||Yl.mouseout.call(this,t)}};Jr(["click","dblclick","contextmenu"],function(t){Yl[t]=function(e){e=pa(this.dom,e),this.trigger(t,e)}});var Zl={pointermove:function(t){Wl(t)||Zl.mousemove.call(this,t)},pointerup:function(t){Zl.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 Kl(t,e){var n=e.domHandlers;kr.pointerEventsSupported?Jr(Bl.pointer,function(i){Jl(e,i,function(e){n[i].call(t,e)})}):(kr.touchEventsSupported&&Jr(Bl.touch,function(i){Jl(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)})}),Jr(Bl.mouse,function(i){Jl(e,i,function(r){r=ha(r),e.touching||n[i].call(t,r)})}))}function Ql(t,e){function n(n){Jl(e,n,function(i){i=ha(i),Gl(t,i.target)||(i=function(t,e){return pa(t.dom,new Xl(t,e),!0)}(t,i),e.domHandlers[n].call(t,i))},{capture:!0})}kr.pointerEventsSupported?Jr(jl,n):kr.touchEventsSupported||Jr(Vl,n)}function Jl(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 tc(t){var e=t.mounted;for(var n in e)e.hasOwnProperty(n)&&fa(t.domTarget,n,e[n],t.listenerOpts[n]);t.mounted={}}var ec=function(t,e){this.mounted={},this.listenerOpts={},this.touching=!1,this.domTarget=t,this.domHandlers=e},nc=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 ec(e,Yl),Fl&&(i._globalHandlerScope=new ec(document,Zl)),Kl(i,i._localHandlerScope),i}return v(e,t),e.prototype.dispose=function(){tc(this._localHandlerScope),Fl&&tc(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,Fl&&+this.__pointerCapturing^+t){this.__pointerCapturing=t;var e=this._globalHandlerScope;t?Ql(this,e):tc(e)}},e}(Zo),ic=1;kr.hasGlobalWindow&&(ic=Math.max(window.devicePixelRatio||window.screen&&window.screen.deviceXDPI/window.screen.logicalXDPI||1,1));var rc=ic,oc="#333",ac="#ccc",sc=ya,lc=5e-5;function cc(t){return t>lc||t<-5e-5}var dc,uc=[],hc=[],pc=[1,0,0,1,0,0],fc=Math.abs,gc=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 cc(this.rotation)||cc(this.x)||cc(this.y)||cc(this.scaleX-1)||cc(this.scaleY-1)||cc(this.skewX)||cc(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):sc(n),t&&(e?xa(n,t,n):ba(n,t)),this.transform=n,this._resolveGlobalScaleRatio(n)):n&&(sc(n),this.invTransform=null)},t.prototype._resolveGlobalScaleRatio=function(t){var e=this.globalScaleRatio;if(null!=e&&1!==e){this.getGlobalScale(uc);var n=uc[0]<0?-1:1,i=uc[1]<0?-1:1,r=((uc[0]-n)*e+n)/uc[0]||0,o=((uc[1]-i)*e+i)/uc[1]||0;t[0]*=r,t[1]*=r,t[2]*=o,t[3]*=o}this.invTransform=this.invTransform||[1,0,0,1,0,0],Ca(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],xa(hc,t.invTransform,e),e=hc);var n=this.originX,i=this.originY;(n||i)&&(pc[4]=n,pc[5]=i,xa(hc,e,pc),hc[4]-=n,hc[5]-=i,e=hc),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&&Wo(n,n,i),n},t.prototype.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&Wo(n,n,i),n},t.prototype.getLineScale=function(){var t=this.transform;return t&&fc(t[0]-1)>1e-10&&fc(t[3]-1)>1e-10?Math.sqrt(fc(t[0]*t[3]-t[2]*t[1])):1},t.prototype.copyTransform=function(t){vc(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,d=t.y,u=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-u*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]=u*o,l&&Sa(e,e,l),e[4]+=n+c,e[5]+=i+d,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}(),mc=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function vc(t,e){for(var n=0;n=bc)){t=t||Tr;for(var e=[],n=+new Date,i=0;i<=127;i++)e[i]=Dr.measureText(String.fromCharCode(i),t).width;var r=+new Date-n;return r>16?yc=bc:r>2&&yc++,e}}(t.font),t.asciiWidthMapTried=!0),0<=e&&e<=127?null!=t.asciiWidthMap?t.asciiWidthMap[e]:t.asciiCharWidth:t.stWideCharWidth}function wc(t,e){var n=t.strWidthCache,i=n.get(e);return null==i&&(i=Dr.measureText(e,t.font).width,n.put(e,i)),i}function Sc(t,e,n,i){var r=wc(_c(e),t),o=Tc(e),a=kc(0,r,n),s=Mc(0,o,i);return new Ha(a,s,r,o)}function Cc(t,e,n,i){var r=((t||"")+"").split("\n");if(1===r.length)return Sc(r[0],e,n,i);for(var o=new Ha(0,0,0,0),a=0;a=0?parseFloat(t)/100*e:parseFloat(t):t}function Ic(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,d="left",u="top";if(i instanceof Array)l+=Ac(i[0],n.width),c+=Ac(i[1],n.height),d=null,u=null;else switch(i){case"left":l-=r,c+=s,d="right",u="middle";break;case"right":l+=r+a,c+=s,u="middle";break;case"top":l+=a/2,c-=r,d="center",u="bottom";break;case"bottom":l+=a/2,c+=o+r,d="center";break;case"inside":l+=a/2,c+=s,d="center",u="middle";break;case"insideLeft":l+=r,c+=s,u="middle";break;case"insideRight":l+=a-r,c+=s,d="right",u="middle";break;case"insideTop":l+=a/2,c+=r,d="center";break;case"insideBottom":l+=a/2,c+=o-r,d="center",u="bottom";break;case"insideTopLeft":l+=r,c+=r;break;case"insideTopRight":l+=a-r,c+=r,d="right";break;case"insideBottomLeft":l+=r,c+=o-r,u="bottom";break;case"insideBottomRight":l+=a-r,c+=o-r,d="right",u="bottom"}return(t=t||{}).x=l,t.y=c,t.align=d,t.verticalAlign=u,t}var Pc="__zr_normal__",Dc=mc.concat(["ignore"]),Lc=eo(mc,function(t,e){return t[e]=!0,t},{ignore:!1}),Ec={},Rc=new Ha(0,0,0,0),Nc=[],Oc=function(){function t(t){this.id=qr(),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,d=n.autoOverflowArea,u=void 0;if((d||c)&&(u=Rc,n.layoutRect?u.copy(n.layoutRect):u.copy(this.getBoundingRect()),i||u.applyTransform(this.transform)),c){this.calculateTextPosition?this.calculateTextPosition(Ec,n,u):Ic(Ec,n,u),r.x=Ec.x,r.y=Ec.y,o=Ec.align,a=Ec.verticalAlign;var h=n.origin;if(h&&null!=n.rotation){var p=void 0,f=void 0;"center"===h?(p=.5*u.width,f=.5*u.height):(p=Ac(h[0],u.width),f=Ac(h[1],u.height)),l=!0,r.originX=-r.x+p+(i?0:u.x),r.originY=-r.y+f+(i?0:u.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(d){var v=m.overflowRect=m.overflowRect||new Ha(0,0,0,0);r.getLocalTransform(Nc),Ca(Nc,Nc),Ha.copy(v,u),v.applyTransform(Nc)}else m.overflowRect=null;var _=void 0,y=void 0,b=void 0;(null==n.inside?"string"==typeof n.position&&n.position.indexOf("inside")>=0:n.inside)&&this.canBeInsideText()?(_=n.insideFill,y=n.insideStroke,null!=_&&"auto"!==_||(_=this.getInsideTextFill()),null!=y&&"auto"!==y||(y=this.getInsideTextStroke(_),b=!0)):(_=n.outsideFill,y=n.outsideStroke,null!=_&&"auto"!==_||(_=this.getOutsideFill()),null!=y&&"auto"!==y||(y=this.getOutsideStroke(_),b=!0)),(_=_||"#000")===m.fill&&y===m.stroke&&b===m.autoStroke&&o===m.align&&a===m.verticalAlign||(s=!0,m.fill=_,m.stroke=y,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()?ac:oc},t.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),n="string"==typeof e&&Qs(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,nl(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||{},Xr(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(ho(t))for(var n=io(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(Pc,!1,t)},t.prototype.useState=function(t,e,n,i){var r=t===Pc;if(this.hasState()||!r){var o=this.currentStates,a=this.stateTransition;if(!(Zr(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,d=this._textGuide;return c&&c.useState(t,e,n,l),d&&d.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}Wr("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,u),g&&g.useStates(t,e,u),this._updateAnimationTargets(),this.currentStates=t.slice(),this.markRedraw(),!u&&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=Zr(i,t),o=Zr(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=0&&(n.splice(i,0,t),this._doAdd(t))}return this},e.prototype.replace=function(t,e){var n=Zr(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=Zr(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 jc=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 qc(t,e,n)};function qc(t,e,n){return Jr(t)?(i=t,i.replace(/^\s+|\s+$/g,"")).match(/%$/)?parseFloat(t)/100*e+(n||0):parseFloat(t):null==t?NaN:+t;var i}function Wc(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function Uc(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 Gc(t,e){var n=Math.max(Uc(t),Uc(e)),i=t+e;return n>20?i:Wc(i,n)}function Xc(t){var e=2*Math.PI;return(t%e+e)%e}function Yc(t){return t>-1e-4&&t<$c}var Zc=/^(?:(\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 Kc(t){if(t instanceof Date)return t;if(Jr(t)){var e=Zc.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 Qc(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 Jc(t,e){var n=Qc(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 td(t){var e=parseFloat(t);return e==t&&(0!==e||!Jr(t)||t.indexOf("x")<=0)?e:NaN}function ed(){return Math.round(9*Math.random())}function nd(t,e){return 0===e?t:nd(e,t%e)}function id(t,e){return null==t?e:null==e?t:t*e/nd(t,e)}var rd="undefined"!=typeof console&&console.warn&&console.log;function od(t,e){!function(t,e){rd&&console[t]("[ECharts] "+e)}("error",t)}function ad(t){throw new Error(t)}function sd(t,e,n){return(e-t)*n+t}var ld="series\0";function cd(t){return t instanceof Array?t:null==t?[]:[t]}function dd(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&&Br(r,s)<0)){var l=n.getShallow(s,e);null!=l&&(o[t[a][0]]=l)}}return o}}var $d=zd([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),Hd=function(){function t(){}return t.prototype.getAreaStyle=function(t,e){return $d(this,t,e)},t}(),Fd=new Ps(50);function Bd(t){if("string"==typeof t){var e=Fd.get(t);return e&&e.image}return t}function Vd(t,e,n,i,r){if(t){if("string"==typeof t){if(e&&e.__zrImageSrc===t||!n)return e;var o=Fd.get(t),a={hostEl:n,cb:i,cbPayload:r};return o?!qd(e=o.image)&&o.pending.push(a):((e=wr.loadImage(t,jd,jd)).__zrImageSrc=t,Fd.put(t,e.__cachedImgObj={image:e,pending:[a]})),e}return t}return e}function jd(){var t=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=s;c++)l-=s;var d=pc(a,n);return d>l&&(n="",d=0),l=t-d,r.ellipsis=n,r.ellipsisWidth=d,r.contentWidth=l,r.containerWidth=t,r}function Xd(t,e,n){var i=n.containerWidth,r=n.contentWidth,o=n.fontMeasureInfo;if(!i)return t.textLine="",void(t.isTruncated=!1);var a=pc(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?Yd(e,r,o):a>0?Math.floor(e.length*r/a):0;a=pc(o,e=e.substr(0,l))}""===e&&(e=n.placeholder),t.textLine=e,t.isTruncated=!0}function Yd(t,e,n){for(var i=0,r=0,o=t.length;r0&&f+i.accumWidth>i.width&&(o=e.split("\n"),u=!0),i.accumWidth=f}else{var g=nu(e,d,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=cc(d),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,d=0,u=cc(e),h=0;hn:r+d+f>n)?d?(s||l)&&(g?(s||(s=l,l="",d=c=0),o.push(s),a.push(d-c),l+=p,s="",d=c+=f):(l&&(s+=l,l="",c=0),o.push(s),a.push(d),s=p,d=f)):g?(o.push(l),a.push(c),l=p,c=f):(o.push(p),a.push(f)):(d+=f,g?(l+=p,c+=f):(l&&(s+=l,l="",c=0),s+=p))}else l&&(s+=l,d+=c),o.push(s),a.push(d),s="",l="",c=0,d=0}return l&&(s+=l),s&&(o.push(s),a.push(d)),1===o.length&&(d+=r),{accumWidth:d,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;Pa.set(ru,mc(n,a,r),vc(i,s,o),a,s),Pa.intersect(e,ru,null,ou);var l=ou.outIntersectRect;t.outerWidth=l.width,t.outerHeight=l.height,t.baseX=mc(l.x,l.width,r,!0),t.baseY=vc(l.y,l.height,o,!0)}}var ru=new Pa(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 Pa(mc(t.x||0,e,t.textAlign),vc(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()),du={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},uu={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};du[cu]=!0;var hu=["z","z2","invisible"],pu=["invisible"],fu=function(t){function e(e){return t.call(this,e)||this}var n;return v(e,t),e.prototype._init=function(e){for(var n=Xr(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]=yu(r)*i+e,Su[0]=bu(o)*n+t,Su[1]=yu(o)*i+e,c(s,wu,Su),d(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]=yu(p)*i+e,c(s,Cu,s),d(l,Cu,l))}var Du={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},Lu=[],Eu=[],Ru=[],Nu=[],Ou=[],zu=[],$u=Math.min,Hu=Math.max,Fu=Math.cos,Bu=Math.sin,Vu=Math.abs,ju=Math.PI,qu=2*ju,Wu="undefined"!=typeof Float32Array,Uu=[];function Gu(t){return Math.round(t/ju*1e8)/1e8%2*ju}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/Yl/t)||0,this._uy=Vu(n/Yl/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(Du.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(Du.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(Du.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(Du.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+=qu);var i=n-t[0],r=t[1];r+=i,!e&&r-n>=qu?r=n+qu:e&&n-r>=qu?r=n-qu:!e&&n>r?r=n+(qu-Gu(n-r)):e&&n0&&o))for(var a=0;ac.length&&(this._expandData(),c=this.data);for(var d=0;d0&&(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(){Ru[0]=Ru[1]=Ou[0]=Ou[1]=Number.MAX_VALUE,Nu[0]=Nu[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||u===e-1)&&(f=Math.sqrt(I*I+m*m),r=g,o=y);break;case Du.C:var v=t[u++],_=t[u++],y=(g=t[u++],t[u++]),b=t[u++],x=t[u++];f=ys(r,o,v,_,g,y,b,x,10),r=b,o=x;break;case Du.Q:f=Cs(r,o,v=t[u++],_=t[u++],g=t[u++],y=t[u++],10),r=g,o=y;break;case Du.A:var w=t[u++],S=t[u++],C=t[u++],k=t[u++],M=t[u++],T=t[u++],A=T+M;u+=1,p&&(a=Fu(M)*C+w,s=Bu(M)*k+S),f=Hu(C,k)*$u(qu,Math.abs(T)),r=Fu(A)*C+w,o=Bu(A)*k+S;break;case Du.R:a=r=t[u++],s=o=t[u++],f=2*t[u++]+2*t[u++];break;case Du.Z:var I=a-r;m=s-o;f=Math.sqrt(I*I+m*m),r=a,o=s}f>=0&&(l[d++]=f,c+=f)}return this._pathLen=c,c},t.prototype.rebuildPath=function(t,e){var n,i,r,o,a,s,l,c,d,u,h=this.data,p=this._ux,f=this._uy,g=this._len,m=e<1,v=0,_=0,y=0;if(!m||(this._pathSegLen||this._calculateLength(),l=this._pathSegLen,c=e*this._pathLen))t:for(var b=0;b0&&(t.lineTo(d,u),y=0),x){case Du.M:n=r=h[b++],i=o=h[b++],t.moveTo(r,o);break;case Du.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[_++])>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,y=0}else{var M=S*S+C*C;M>y&&(d=a,u=s,y=M)}break;case Du.C:var T=h[b++],A=h[b++],I=h[b++],P=h[b++],D=h[b++],L=h[b++];if(m){if(v+(X=l[_++])>c){_s(r,T,I,D,k=(c-v)/X,Lu),_s(o,A,P,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,P,D,L),r=D,o=L;break;case Du.Q:T=h[b++],A=h[b++],I=h[b++],P=h[b++];if(m){if(v+(X=l[_++])>c){Ss(r,T,I,k=(c-v)/X,Lu),Ss(o,A,P,k,Eu),t.quadraticCurveTo(Lu[1],Eu[1],Lu[2],Eu[2]);break t}v+=X}t.quadraticCurveTo(T,A,I,P),r=I,o=P;break;case Du.A:var E=h[b++],R=h[b++],N=h[b++],O=h[b++],z=h[b++],$=h[b++],H=h[b++],F=!h[b++],B=N>O?N:O,V=Vu(N-O)>.001,j=z+$,q=!1;if(m)v+(X=l[_++])>c&&(j=z+$*(c-v)/X,q=!0),v+=X;if(V&&t.ellipse?t.ellipse(E,R,N,O,H,z,j,F):t.arc(E,R,B,z,j,F),q)break t;w&&(n=Fu(z)*N+E,i=Bu(z)*O+R),r=Fu(j)*N+E,o=Bu(j)*O+R;break;case Du.R:n=r=h[b],i=o=h[b+1],a=h[b++],s=h[b++];var W=h[b++],U=h[b++];if(m){if(v+(X=l[_++])>c){var G=c-v;t.moveTo(a,s),t.lineTo(a+$u(G,W),s),(G-=W)>0&&t.lineTo(a+W,s+$u(G,U)),(G-=U)>0&&t.lineTo(a+Hu(W-G,0),s+U),(G-=W)>0&&t.lineTo(a,s+Hu(U-G,0));break t}v+=X}t.rect(a,s,W,U);break;case Du.Z:if(m){var X;if(v+(X=l[_++])>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=Du,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+u&&d>i+u&&d>o+u&&d>s+u||dt+u&&c>n+u&&c>r+u&&c>a+u||c=0&&pe+c&&l>i+c&&l>o+c||lt+c&&s>n+c&&s>r+c||s=0&&gn||d+cr&&(r+=th);var h=Math.atan2(l,s);return h<0&&(h+=th),h>=i&&h<=r||h+th>=i&&h+th<=r}function nh(t,e,n,i,r,o){if(o>e&&o>i||or?s:0}var ih=Xu.CMD,rh=2*Math.PI;var oh=[-1,-1,-1],ah=[-1,-1];function sh(){var t=ah[0];ah[0]=ah[1],ah[1]=t}function lh(t,e,n,i,r,o,a,s,l,c){if(c>e&&c>i&&c>o&&c>s||c1&&sh(),p=fs(e,i,o,s,ah[0]),h>1&&(f=fs(e,i,o,s,ah[1]))),2===h?me&&s>i&&s>o||s=0&&d<=1&&(r[l++]=d);else{var c=a*a-4*o*s;if(hs(c))(d=-a/(2*o))>=0&&d<=1&&(r[l++]=d);else if(c>0){var d,u=rs(c),h=(-a-u)/(2*o);(d=(-a+u)/(2*o))>=0&&d<=1&&(r[l++]=d),h>=0&&h<=1&&(r[l++]=h)}}return l}(e,i,o,s,oh);if(0===l)return 0;var c=ws(e,i,o);if(c>=0&&c<=1){for(var d=0,u=bs(e,i,o,c),h=0;hn||s<-n)return 0;var l=Math.sqrt(n*n-s*s);oh[0]=-l,oh[1]=l;var c=Math.abs(i-r);if(c<1e-4)return 0;if(c>=rh-1e-4){i=0,r=rh;var d=o?1:-1;return a>=oh[0]+t&&a<=oh[1]+t?d:0}if(i>r){var u=i;i=r,r=u}i<0&&(i+=rh,r+=rh);for(var h=0,p=0;p<2;p++){var f=oh[p];if(f+t>a){var g=Math.atan2(s,f);d=o?1:-1;g<0&&(g=rh+g),(g>=i&&g<=r||g+rh>=i&&g+rh<=r)&&(g>Math.PI/2&&g<1.5*Math.PI&&(d=-d),h+=d)}}return h}function uh(t,e,n,i,r){for(var o,a,s=t.data,l=t.len(),c=0,d=0,u=0,h=0,p=0,f=0;f1&&(n||(c+=nh(d,u,h,p,i,r))),m&&(h=d=s[f],p=u=s[f+1]),g){case ih.M:d=h=s[f++],u=p=s[f++];break;case ih.L:if(n){if(Yu(d,u,s[f],s[f+1],e,i,r))return!0}else c+=nh(d,u,s[f],s[f+1],i,r)||0;d=s[f++],u=s[f++];break;case ih.C:if(n){if(Zu(d,u,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=lh(d,u,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],i,r)||0;d=s[f++],u=s[f++];break;case ih.Q:if(n){if(Ku(d,u,s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=ch(d,u,s[f++],s[f++],s[f],s[f+1],i,r)||0;d=s[f++],u=s[f++];break;case ih.A:var v=s[f++],_=s[f++],y=s[f++],b=s[f++],x=s[f++],w=s[f++];f+=1;var S=!!(1-s[f++]);o=Math.cos(x)*y+v,a=Math.sin(x)*b+_,m?(h=o,p=a):c+=nh(d,u,o,a,i,r);var C=(i-v)*b/y+v;if(n){if(eh(v,_,b,x,x+w,S,e,C,r))return!0}else c+=dh(v,_,b,x,x+w,S,C,r);d=Math.cos(x+w)*y+v,u=Math.sin(x+w)*b+_;break;case ih.R:if(h=d=s[f++],p=u=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+=nh(o,p,o,a,i,r),c+=nh(h,a,h,p,i,r);break;case ih.Z:if(n){if(Yu(d,u,h,p,e,i,r))return!0}else c+=nh(d,u,h,p,i,r);d=h,u=p}}return n||function(t,e){return Math.abs(t-e)<1e-4}(u,p)||(c+=nh(d,u,h,p,i,r)||0),0!==c}var hh=Fr({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},du),ph={style:Fr({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},uu.style)},fh=sc.concat(["invisible","culling","z","z2","zlevel","parent"]),gh=function(t){function e(e){return t.call(this,e)||this}var n;return v(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?Zl:e>.2?"#eee":Kl}if(t)return Kl}return Zl},e.prototype.getInsideTextStroke=function(t){var e=this.style.fill;if(Jr(e)){var n=this.__zr;if(!(!n||!n.isDarkMode())===Xs(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 uh(t,e,!0,n,i)}(o,a/s,t,e)))return!0}if(this.hasFill())return function(t,e,n){return uh(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:Hr(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(4&this.__dirty)},e.prototype.createStyle=function(t){return So(hh,t)},e.prototype._innerSaveToNormal=function(e){t.prototype._innerSaveToNormal.call(this,e);var n=this._normalState;e.shape&&!n.shape&&(n.shape=Hr({},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=Hr({},i.shape),Hr(s,n.shape)):(s=Hr({},r?this.shape:i.shape),Hr(s,n.shape)):l&&(s=i.shape),s)if(o){this.shape=Hr({},this.shape);for(var c={},d=Xr(s),u=0;uc&&(n*=c/(a=n+i),i*=c/a),r+o>c&&(r*=c/(a=r+o),o*=c/a),i+r>d&&(i*=d/(a=i+r),r*=d/a),n+o>d&&(n*=d/(a=n+o),o*=d/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+d-r),0!==r&&t.arc(s+c-r,l+d-r,r,0,Math.PI/2),t.lineTo(s+o,l+d),0!==o&&t.arc(s+o,l+d-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}(gh);Th.prototype.type="rect";var Ah={fill:"#000"},Ih={},Ph={style:Fr({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},uu.style)},Dh=function(t){function e(e){var n=t.call(this)||this;return n.type="text",n._children=[],n._defaultStyle=Ah,n.attr(e),n}return v(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 y=Math.floor(v/h);f=f||m.length>y,_=(m=m.slice(0,y)).length*h}if(r&&d&&null!=g)for(var b=Gd(g,c,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),x={},w=0;w0,k=0;kg&&Jd(o,a.substring(g,m),e,f),Jd(o,h[2],e,f,h[1]),g=Wd.lastIndex}gu){var R=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=y[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=y[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&&jh(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 d=!!s.backgroundColor,u=t.textPadding;u&&(r=Bh(r,o,u),c-=t.height/2-u[0]-t.innerHeight/2);var h=this._getOrCreateChild(vh),p=h.createStyle();h.useStyle(p);var f=this._defaultStyle,g=!1,m=0,v=!1,_=Fh("fill"in s?s.fill:"fill"in e?e.fill:(g=!0,f.fill)),y=Hh("stroke"in s?s.stroke:"stroke"in e?e.stroke:d||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||_r,p.opacity=uo(s.opacity,e.opacity,1),Oh(p,s),y&&(p.lineWidth=uo(s.lineWidth,e.lineWidth,m),p.lineDash=co(s.lineDash,e.lineDash),p.lineDashOffset=e.lineDashOffset||0,p.stroke=y),_&&(p.fill=_),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,d=t.borderWidth,u=t.borderColor,h=c&&c.image,p=c&&!h,f=t.borderRadius,g=this;if(p||t.lineHeight||d&&u){(a=this._getOrCreateChild(Th)).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=co(t.fillOpacity,1);else if(h){(s=this._getOrCreateChild(bh)).onload=function(){g.dirtyStyle()};var v=s.style;v.image=c.image,v.x=n,v.y=i,v.width=r,v.height=o}d&&u&&((l=a.style).lineWidth=d,l.stroke=u,l.strokeOpacity=co(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 _=(a||s).style;_.shadowBlur=t.shadowBlur||0,_.shadowColor=t.shadowColor||"transparent",_.shadowOffsetX=t.shadowOffsetX||0,_.shadowOffsetY=t.shadowOffsetY||0,_.opacity=uo(t.opacity,e.opacity,1)},e.makeFont=function(t){var e="";return zh(t)&&(e=[t.fontStyle,t.fontWeight,Nh(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),e&&go(e)||t.textFont||t.font},e}(fu),Lh={left:!0,right:1,center:1},Eh={top:1,bottom:1,middle:1},Rh=["fontStyle","fontWeight","fontSize","fontFamily"];function Nh(t){return"string"!=typeof t||-1===t.indexOf("px")&&-1===t.indexOf("rem")&&-1===t.indexOf("em")?isNaN(+t)?"12px":t+"px":t}function Oh(t,e){for(var n=0;n=0,o=!1;if(t instanceof gh){var a=Gh(t),s=r&&a.selectFill||a.normalFill,l=r&&a.selectStroke||a.normalStroke;if(ip(s)||ip(l)){var c=(i=i||{}).style||{};"inherit"===c.fill?(o=!0,i=Hr({},i),(c=Hr({},c)).fill=s):!ip(c.fill)&&ip(s)?(o=!0,i=Hr({},i),(c=Hr({},c)).fill=Zs(s)):!ip(c.stroke)&&ip(l)&&(o||(i=Hr({},i),c=Hr({},c)),c.stroke=Zs(l)),i.style=c}}if(i&&null==i.z2){o||(i=Hr({},i));var d=t.z2EmphasisLift;i.z2=t.z2+(null!=d?d:10)}return i}(this,0,e,n);if("blur"===t)return function(t,e,n){var i=Br(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 Pp(t,e,n){Np(t,!0),hp(t,gp),function(t,e,n){var i=qh(t);null!=e?(i.focus=e,i.blurScope=n):i.focus&&(i.focus=null)}(t,e,n)}function Dp(t,e,n,i){i?function(t){Np(t,!1)}(t):Pp(t,e,n)}var Lp=["emphasis","blur","select"],Ep={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function Rp(t,e,n,i){n=n||"itemStyle";for(var r=0;r1&&(a*=jp(f),s*=jp(f));var g=(r===o?-1:1)*jp((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,_=(t+n)/2+Wp(u)*m-qp(u)*v,y=(e+i)/2+qp(u)*m+Wp(u)*v,b=Yp([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=Yp(x,w);if(Xp(x,w)<=-1&&(S=Up),Xp(x,w)>=1&&(S=0),S<0){var C=Math.round(S/Up*1e6)/1e6;S=2*Up+C%2*Up}d.addData(c,_,y,a,s,b,S,u,o)}var Kp=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,Qp=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;var Jp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e.prototype.applyTransform=function(t){},e}(gh);function tf(t){return null!=t.setData}function ef(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(Kp);if(!l)return e;for(var c=0;cP*P+D*D&&(C=M,k=T),{cx:C,cy:k,x0:-d,y0:-u,x1:C*(r/x-1),y1:k*(r/x-1)}}function yf(t,e){var n,i=gf(e.r,0),r=gf(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,d=e.cy,u=!!e.clockwise,h=pf(l-s),p=h>lf&&h%lf;if(p>vf&&(h=p),i>vf)if(h>lf-vf)t.moveTo(c+i*df(s),d+i*cf(s)),t.arc(c,d,i,s,l,!u),r>vf&&(t.moveTo(c+r*df(l),d+r*cf(l)),t.arc(c,d,r,l,s,u));else{var f=void 0,g=void 0,m=void 0,v=void 0,_=void 0,y=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,P=i*df(s),D=i*cf(s),L=r*df(l),E=r*cf(l),R=h>vf;if(R){var N=e.cornerRadius;N&&(n=function(t){var e;if(Kr(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}(N),f=n[0],g=n[1],m=n[2],v=n[3]);var O=pf(i-r)/2;if(_=mf(O,m),y=mf(O,v),b=mf(O,f),x=mf(O,g),C=w=gf(_,y),k=S=gf(b,x),(w>vf||S>vf)&&(M=i*df(l),T=i*cf(l),A=r*df(s),I=r*cf(s),hvf){var q=mf(m,C),W=mf(v,C),U=_f(A,I,P,D,i,q,u),G=_f(M,T,L,E,i,W,u);t.moveTo(c+U.cx+U.x0,d+U.cy+U.y0),C0&&t.arc(c+U.cx,d+U.cy,q,hf(U.y0,U.x0),hf(U.y1,U.x1),!u),t.arc(c,d,i,hf(U.cy+U.y1,U.cx+U.x1),hf(G.cy+G.y1,G.cx+G.x1),!u),W>0&&t.arc(c+G.cx,d+G.cy,W,hf(G.y1,G.x1),hf(G.y0,G.x0),!u))}else t.moveTo(c+P,d+D),t.arc(c,d,i,s,l,!u);else t.moveTo(c+P,d+D);if(r>vf&&R)if(k>vf){q=mf(f,k),U=_f(L,E,M,T,r,-(W=mf(g,k)),u),G=_f(P,D,A,I,r,-q,u);t.lineTo(c+U.cx+U.x0,d+U.cy+U.y0),k0&&t.arc(c+U.cx,d+U.cy,W,hf(U.y0,U.x0),hf(U.y1,U.x1),!u),t.arc(c,d,r,hf(U.cy+U.y1,U.cx+U.x1),hf(G.cy+G.y1,G.cx+G.x1),u),q>0&&t.arc(c+G.cx,d+G.cy,q,hf(G.y1,G.x1),hf(G.y0,G.x0),!u))}else t.lineTo(c+L,d+E),t.arc(c,d,r,l,s,u);else t.lineTo(c+L,d+E)}else t.moveTo(c,d);t.closePath()}}}var bf=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},xf=function(t){function e(e){return t.call(this,e)||this}return v(e,t),e.prototype.getDefaultShape=function(){return new bf},e.prototype.buildPath=function(t,e){yf(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(gh);xf.prototype.type="sector";var wf=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},Sf=function(t){function e(e){return t.call(this,e)||this}return v(e,t),e.prototype.getDefaultShape=function(){return new wf},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}(gh);function Cf(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=[],d=[],u=[];if(i){a=[1/0,1/0],s=[-1/0,-1/0];for(var h=0,p=t.length;hUf[1]){if(r=!1,Gf.negativeSize||n)return r;var s=qf(Uf[0]-Wf[1]),l=qf(Wf[0]-Uf[1]);Vf(s,l)>Yf.len()&&(s=l||!Gf.bidirectional)&&(ma.scale(Xf,a,-l*i),Gf.useDir&&Gf.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 u={duration:d.duration,delay:d.delay||0,easing:d.easing,done:o,force:!!o||!!a,setToFinal:!c,scope:t,during:a};l?e.animateFrom(n,u):e.animateTo(n,u)}else e.stopAnimation(),!l&&e.attr(n),a&&a(1),o&&o()}function eg(t,e,n,i,r,o){tg("update",t,e,n,i,r,o)}function ng(t,e,n,i,r,o){tg("enter",t,e,n,i,r,o)}function ig(t){if(!t.__zr)return!0;for(var e=0;e=-1e-6)return!1;var f=t-r,g=e-o,m=Sg(f,g,c,d)/p;if(m<0||m>1)return!1;var v=Sg(f,g,u,h)/p;return!(v<0||v>1)}function Sg(t,e,n,i){return t*i-n*e}function Cg(t,e,n,i,r){return null==e||(eo(e)?kg[0]=kg[1]=kg[2]=kg[3]=e:(kg[0]=e[0],kg[1]=e[1],kg[2]=e[2],kg[3]=e[3]),i&&(kg[0]=Fc(0,kg[0]),kg[1]=Fc(0,kg[1]),kg[2]=Fc(0,kg[2]),kg[3]=Fc(0,kg[3])),n&&(kg[0]=-kg[0],kg[1]=-kg[1],kg[2]=-kg[2],kg[3]=-kg[3]),Mg(t,kg,"x","width",3,1,r&&r[0]||0),Mg(t,kg,"y","height",0,2,r&&r[1]||0)),t}var kg=[0,0,0,0];function Mg(t,e,n,i,r,o,a){var s=e[o]+e[r],l=t[i];t[i]+=s,a=Fc(0,Hc(a,l)),t[i]=0?-e[r]:e[o]>=0?l+e[o]:Bc(s)>1e-8?(l-a)*e[r]/s:0):t[n]-=e[r]}function Tg(t){var e=t.itemTooltipOption,n=t.componentModel,i=t.itemName,r=Jr(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&&qr(Xr(l),function(t){Co(s,t)||(s[t]=l[t],s.$vars.push(t))});var c=qh(t.el);c.componentMainType=o,c.componentIndex=a,c.tooltipConfig={name:i,option:Fr({content:i,encodeHTMLContent:!0,formatterParams:s},r)}}function Ag(t,e){var n;t.isGroup&&(n=e(t)),n||t.traverse(e)}function Ig(t,e){if(t)if(Kr(t))for(var n=0;ne&&(e=i),ie&&(n=e=0),{min:n,max:e}},clipPointsByRect:function(t,e){return Wr(t,function(t){var n=t[0];n=Fc(n,e.x),n=Hc(n,e.x+e.width);var i=t[1];return i=Fc(i,e.y),[n,i=Hc(i,e.y+e.height)]})},clipRectByRect:function(t,e){var n=Fc(t.x,e.x),i=Hc(t.x+t.width,e.x+e.width),r=Fc(t.y,e.y),o=Hc(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:xg,ensureCopyRect:Lg,ensureCopyTransform:Eg,expandOrShrinkRect:Cg,extendPath:function(t,e){return cg(t,e)},extendShape:function(t){return gh.extend(t)},getShapeClass:function(t){if(ag.hasOwnProperty(t))return ag[t]},getTransform:function(t,e){for(var n=da([]);t&&t!==e;)ha(n,t.getLocalTransform(),n),t=t.parent;return n},groupTransition:bg,initProps:ng,isBoundingRectAxisAligned:Pg,isElementRemoved:ig,lineLineIntersect:wg,linePolygonIntersect:function(t,e,n,i,r){for(var o=0,a=r[r.length-1];oBc(o[1])?o[0]>0?"right":"left":o[1]>0?"bottom":"top"},traverseElements:Ig,traverseUpdateZ:Ng,updateProps:eg}),$g={};function Hg(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=Qr(t.defaultText)?t.defaultText(o,t,n):t.defaultText);for(var l={normal:i},c=0;c-1?um:pm;function vm(t,e){t=t.toUpperCase(),gm[t]=new lm(e),fm[t]=e}vm(hm,{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:". "}}}}),vm(um,{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 _m(){return null}var ym=1e3,bm=6e4,xm=36e5,wm=864e5,Sm=31536e6,Cm={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})/},km={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}"},Mm="{yyyy}-{MM}-{dd}",Tm={year:"{yyyy}",month:"{yyyy}-{MM}",day:Mm,hour:Mm+" "+km.hour,minute:Mm+" "+km.minute,second:Mm+" "+km.second,millisecond:"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}"},Am=["year","month","day","hour","minute","second","millisecond"],Im=["year","half-year","quarter","month","week","half-week","day","half-day","quarter-day","hour","minute","second","millisecond"];function Pm(t){return Jr(t)||Qr(t)?t:function(t){t=t||{};var e={},n=!0;return qr(Am,function(e){n&&(n=null==t[e])}),qr(Am,function(i,r){var o=t[i];e[i]={};for(var a=null,s=r;s>=0;s--){var l=Am[s],c=no(o)&&!Kr(o)?o[l]:o,d=void 0;Kr(c)?a=(d=c.slice())[0]||"":Jr(c)?d=[a=c]:(null==a?a=km[i]:Cm[l].test(a)||(a=e[l][l][0]+" "+a),d=[a],n&&(d[1]="{primary|"+a+"}")),e[i][l]=d}}),e}(t)}function Dm(t,e){return"0000".substr(0,e-(t+="").length)+t}function Lm(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 Em(t){return t===Lm(t)}function Rm(t,e,n,i){var r=Kc(t),o=r[zm(n)](),a=r[$m(n)]()+1,s=Math.floor((a-1)/3)+1,l=r[Hm(n)](),c=r["get"+(n?"UTC":"")+"Day"](),d=r[Fm(n)](),u=(d-1)%12+1,h=r[Bm(n)](),p=r[Vm(n)](),f=r[jm(n)](),g=d>=12?"pm":"am",m=g.toUpperCase(),v=i instanceof lm?i:function(t){return gm[t]}(i||mm)||gm[pm],_=v.getModel("time"),y=_.get("month"),b=_.get("monthAbbr"),x=_.get("dayOfWeek"),w=_.get("dayOfWeekAbbr");return(e||"").replace(/{a}/g,g+"").replace(/{A}/g,m+"").replace(/{yyyy}/g,o+"").replace(/{yy}/g,Dm(o%100+"",2)).replace(/{Q}/g,s+"").replace(/{MMMM}/g,y[a-1]).replace(/{MMM}/g,b[a-1]).replace(/{MM}/g,Dm(a,2)).replace(/{M}/g,a+"").replace(/{dd}/g,Dm(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,x[c]).replace(/{ee}/g,w[c]).replace(/{e}/g,c+"").replace(/{HH}/g,Dm(d,2)).replace(/{H}/g,d+"").replace(/{hh}/g,Dm(u+"",2)).replace(/{h}/g,u+"").replace(/{mm}/g,Dm(h,2)).replace(/{m}/g,h+"").replace(/{ss}/g,Dm(p,2)).replace(/{s}/g,p+"").replace(/{SSS}/g,Dm(f,3)).replace(/{S}/g,f+"")}function Nm(t,e){var n=Kc(t),i=n[$m(e)]()+1,r=n[Hm(e)](),o=n[Fm(e)](),a=n[Bm(e)](),s=n[Vm(e)](),l=0===n[jm(e)](),c=l&&0===s,d=c&&0===a,u=d&&0===o,h=u&&1===r;return h&&1===i?"year":h?"month":u?"day":d?"hour":c?"minute":l?"second":"millisecond"}function Om(t,e,n){switch(e){case"year":t[Wm(n)](0);case"month":t[Um(n)](1);case"day":t[Gm(n)](0);case"hour":t[Xm(n)](0);case"minute":t[Ym(n)](0);case"second":t[Zm(n)](0)}return t}function zm(t){return t?"getUTCFullYear":"getFullYear"}function $m(t){return t?"getUTCMonth":"getMonth"}function Hm(t){return t?"getUTCDate":"getDate"}function Fm(t){return t?"getUTCHours":"getHours"}function Bm(t){return t?"getUTCMinutes":"getMinutes"}function Vm(t){return t?"getUTCSeconds":"getSeconds"}function jm(t){return t?"getUTCMilliseconds":"getMilliseconds"}function qm(t){return t?"setUTCFullYear":"setFullYear"}function Wm(t){return t?"setUTCMonth":"setMonth"}function Um(t){return t?"setUTCDate":"setDate"}function Gm(t){return t?"setUTCHours":"setHours"}function Xm(t){return t?"setUTCMinutes":"setMinutes"}function Ym(t){return t?"setUTCSeconds":"setSeconds"}function Zm(t){return t?"setUTCMilliseconds":"setMilliseconds"}function Km(t){if(isNaN(td(t)))return Jr(t)?t:"-";var e=(t+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function Qm(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 Jm=po;function tv(t,e,n){function i(t){return t&&go(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?Kc(t):t;if(!isNaN(+s))return Rm(s,"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}",n);if(a)return"-"}if("ordinal"===e)return to(t)?i(t):eo(t)&&r(t)?t+"":"-";var l=td(t);return r(l)?Km(l):to(t)?i(t):"boolean"==typeof t?t+"":"-"}var ev=["a","b","c","d","e","f","g"],nv=function(t,e){return"{"+t+(null==e?"":e)+"}"};function iv(t,e,n){Kr(e)||(e=[e]);var i=e.length;if(!i)return"";for(var r=e[0].$vars||[],o=0;oi||l.newline?(o=0,d=g,a+=s+n,s=h.height):s=Math.max(s,h.height)}else{var m=h.height+(f?-f.y+h.y:0);(u=a+m)>r||l.newline?(o+=s+n,a=0,u=m,s=h.width):s=Math.max(s,h.width)}l.newline||(l.x=o,l.y=a,l.markRedraw(),"horizontal"===t?o=d+n:a=u+n)})}function yv(t,e,n){n=Jm(n||0);var i=e.width,r=e.height,o=jc(t.left,i),a=jc(t.top,r),s=jc(t.right,i),l=jc(t.bottom,r),c=jc(t.width,i),d=jc(t.height,r),u=n[2]+n[0],h=n[1]+n[3],p=t.aspect;switch(isNaN(c)&&(c=i-s-h-o),isNaN(d)&&(d=r-l-u-a),null!=p&&(isNaN(c)&&isNaN(d)&&(p>i/r?c=.8*i:d=.8*r),isNaN(c)&&(c=p*d),isNaN(d)&&(d=c/p)),isNaN(o)&&(o=i-s-c-h),isNaN(a)&&(a=r-l-d-u),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-d/2-n[0];break;case"bottom":a=r-d-u}o=o||0,a=a||0,isNaN(c)&&(c=i-h-o-(s||0)),isNaN(d)&&(d=r-u-a-(l||0));var f=new Pa((e.x||0)+o+n[3],(e.y||0)+a+n[0],c,d);return f.margin=n,f}Zr(_v,"vertical"),Zr(_v,"horizontal");var bv=1;function xv(t,e,n){var i,r,o,a,s=t.boxCoordinateSystem;if(s){var l=function(t){var e=t.getShallow("coord",!0),n=lv;if(null==e){var i=dv.get(t.type);i&&i.getCoord2&&(n=cv,e=i.getCoord2(t))}return{coord:e,from:n}}(t),c=l.coord,d=l.from;if(s.dataToLayout){o=bv,a=d;var u=s.dataToLayout(c);i=u.contentRect||u.rect}}return null==o&&(o=bv),o===bv&&(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 wv(t){var e=t.layoutMode||t.constructor.layoutMode;return no(e)?e:e?{type:e}:null}function Sv(t,e,n){var i=n&&n.ignoreSize;!Kr(i)&&(i=[i,i]);var r=a(vv[0],0),o=a(vv[1],1);function a(n,r){var o={},a=0,l={},c=0;if(gv(n,function(e){l[e]=t[e]}),gv(n,function(t){Co(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 d=0;d=0;a--)o=$r(o,n[a],!0);e.defaultOption=o}return e.defaultOption},e.prototype.getReferringComponents=function(t,e){var n=t+"Index",i=t+"Id";return Md(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}(lm);Ld(Mv,lm),Od(Mv),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){var i=Pd(t);e[i.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var o=Pd(n).main;t.hasSubTypes(n)&&e[o]&&(r=e[o](i))}return r}}(Mv),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 qr(t,function(o){var a=n(i,o),s=function(t,e){var n=[];return qr(t,function(t){Br(e,t)>=0&&n.push(t)}),n}(a.originalDeps=e(o),t);a.entryCount=s.length,0===a.entryCount&&r.push(o),qr(s,function(t){Br(a.predecessor,t)<0&&a.predecessor.push(t);var e=n(i,t);Br(e.successor,t)<0&&e.successor.push(o)})}),{graph:i,noEntryList:r}}(i),s=a.graph,l=a.noEntryList,c={};for(qr(t,function(t){c[t]=!0});l.length;){var d=l.pop(),u=s[d],h=!!c[d];h&&(r.call(o,d,u.originalDeps.slice()),delete c[d]),qr(u.successor,h?f:p)}qr(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)}}}(Mv,function(t){var e=[];qr(Mv.getClassesByMainType(t),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=Wr(e,function(t){return Pd(t).main}),"dataset"!==t&&Br(e,"dataset")<=0&&e.unshift("dataset");return e});var Tv={color:{},darkColor:{},size:{}},Av=Tv.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 Iv in Hr(Av,{primary:Av.neutral80,secondary:Av.neutral70,tertiary:Av.neutral60,quaternary:Av.neutral50,disabled:Av.neutral20,border:Av.neutral30,borderTint:Av.neutral20,borderShade:Av.neutral40,background:Av.neutral05,backgroundTint:"rgba(234,237,245,0.5)",backgroundTransparent:"rgba(255,255,255,0)",backgroundShade:Av.neutral10,shadow:"rgba(0,0,0,0.2)",shadowTint:"rgba(129,130,136,0.2)",axisLine:Av.neutral70,axisLineTint:Av.neutral40,axisTick:Av.neutral70,axisTickMinor:Av.neutral60,axisLabel:Av.neutral70,axisSplitLine:Av.neutral15,axisMinorSplitLine:Av.neutral05}),Av)if(Av.hasOwnProperty(Iv)){var Pv=Av[Iv];"theme"===Iv?Tv.darkColor.theme=Av.theme.slice():"highlight"===Iv?Tv.darkColor.highlight="rgba(255,231,130,0.4)":0===Iv.indexOf("accent")?Tv.darkColor[Iv]=Us(Pv,0,function(t){return.5*t},function(t){return Math.min(1,1.3-t)}):Tv.darkColor[Iv]=Us(Pv,0,function(t){return.9*t},function(t){return 1-Math.pow(t,1.5)})}Tv.size={xxs:2,xs:5,s:10,m:15,l:20,xl:30,xxl:40,xxxl:50};var Dv="";"undefined"!=typeof navigator&&(Dv=navigator.platform||"");var Lv="rgba(0, 0, 0, 0.2)",Ev=Tv.color.theme[0],Rv=Us(Ev,0,null,.9),Nv={darkMode:"auto",colorBy:"series",color:Tv.color.theme,gradientColor:[Rv,Ev],aria:{decal:{decals:[{color:Lv,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:Lv,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:Lv,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:Lv,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:Lv,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:Lv,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:Dv.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},Ov=wo(["tooltip","label","itemName","itemId","itemGroupId","itemChildGroupId","seriesName"]),zv="original",$v="arrayRows",Hv="objectRows",Fv="keyedColumns",Bv="typedArray",Vv="unknown",jv="column",qv="row",Wv=1,Uv=2,Gv=3,Xv=xd();function Yv(t,e,n){var i={},r=Zv(e);if(!r||!t)return i;var o,a,s=[],l=[],c=e.ecModel,d=Xv(c).datasetMap,u=r.uid+"_"+n.seriesLayoutBy;qr(t=t.slice(),function(e,n){var r=no(e)?e:t[n]={name:e};"ordinal"===r.type&&null==o&&(o=n,a=f(r)),i[r.name]=[]});var h=d.get(u)||d.set(u,{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(d=d||n,!d||!d.length)return;var u=d[l];r&&(c[r]=u);return s.paletteIdx=(l+1)%d.length,u}(this,Jv,i,r,t,e,n)},t.prototype.clearColorPalette=function(){!function(t,e){e(t).paletteIdx=0,e(t).paletteNameMap={}}(this,Jv)},t}();var r_="\0_ec_inner",o_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e.prototype.init=function(t,e,n,i,r,o){i=i||{},this.option=null,this._theme=new lm(i),this._locale=new lm(r),this._optionManager=o},e.prototype.setOption=function(t,e,n){var i=l_(e);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,e){return this._resetOption(t,l_(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)):n_(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&&qr(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=wo(),s=e&&e.replaceMergeMainTypeMap;Xv(this).datasetMap=wo(),qr(t,function(t,e){null!=t&&(Mv.hasClass(e)?e&&(o.push(e),a.set(e,!0)):n[e]=null==n[e]?zr(t):$r(n[e],t,!0))}),s&&s.each(function(t,e){Mv.hasClass(e)&&!a.get(e)&&(o.push(e),a.set(e,!0))}),Mv.topologicalTravel(o,Mv.getAllClassMainTypes(),function(e){var o=function(t,e,n){var i=Qv.get(e);if(!i)return n;var r=i(t);return r?n.concat(r):n}(this,e,cd(t[e])),a=i.get(e),l=a?s&&s.get(e)?"replaceMerge":"normalMerge":"replaceAll",c=fd(a,o,l);(function(t,e,n){qr(t,function(t){var i=t.newOption;no(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,Mv),n[e]=null,i.set(e,null),r.set(e,0);var d,u=[],h=[],p=0;qr(c,function(t,n){var i=t.existing,r=t.newOption;if(r){var o="series"===e,a=Mv.getClass(e,t.keyInfo.subType,!o);if(!a)return;if("tooltip"===e){if(d)return;d=!0}if(i&&i.constructor===a)i.name=t.keyInfo.name,i.mergeOption(r,this),i.optionUpdated(r,!1);else{var s=Hr({componentIndex:n},t.keyInfo);Hr(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?(u.push(i.option),h.push(i),p++):(u.push(void 0),h.push(void 0))},this),n[e]=u,i.set(e,h),r.set(e,p),"series"===e&&t_(this)},this),this._seriesIndices||t_(this)},e.prototype.getOption=function(){var t=zr(this.option);return qr(t,function(e,n){if(Mv.hasClass(n)){for(var i=cd(e),r=i.length,o=!1,a=r-1;a>=0;a--)i[a]&&!yd(i[a])?o=!0:(i[a]=null,!o&&r--);i.length=r,t[n]=i}}),delete t[r_],t},e.prototype.setTheme=function(t){this._theme=new lm(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 f_=qr,g_=no,m_=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function v_(t){var e=t&&t.itemStyle;if(e)for(var n=0,i=m_.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 no(t)?t.type&&(n=t):e=t,{text:e,frag:n}}function dy(t){return new uy(t)}var uy=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=d(this._modBy),s=this._modDataCount||0,l=d(t&&t.modBy),c=t&&t.modDataCount||0;function d(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 u=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!=u?this._dueIndex+u: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)){ad("")}return t.data}function vy(t){var e=t.sourceFormat,n=t.data;if(!wy(e)){ad("")}if(e===$v){for(var i=[],r=0,o=n.length;r65535?ky:My}function Dy(){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=Wr(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&&y<=d||isNaN(y))&&(a[s++]=p),p++}h=!0}else if(2===r){f=u[i[0]];var m=u[i[1]],v=t[i[1]][0],_=t[i[1]][1];for(g=0;g=c&&y<=d||isNaN(y))&&(b>=v&&b<=_||isNaN(b))&&(a[s++]=p),p++}h=!0}}if(!h)if(1===r)for(g=0;g=c&&y<=d||isNaN(y))&&(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),d=this.getRawIndex(0),u=new(Py(this._rawCount))(Math.min(2*(Math.ceil(s/c)+2),s));u[l++]=d;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(d),_=this.getRawIndex(h);dc-p&&(s=c-p,a.length=s);for(var f=0;fd[1]&&(d[1]=m),u[h++]=v}return r._count=h,r._indices=u,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}(),Ny=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=ro(a=o.get("data",!0))?Bv:zv,e=[];var d=this._getSourceMetaRawOption()||{},u=l&&l.metaRawOption||{},h=co(d.seriesLayoutBy,u.seriesLayoutBy)||null,p=co(d.sourceHeader,u.sourceHeader),f=co(d.dimensions,u.dimensions);t=h!==u.seriesLayoutBy||!!p!=!!u.sourceHeader||f?[V_(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=[V_(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 qr(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=cd(t),i=n.length;i||ad("");for(var r=0,o=i;r1||n>0&&!t.noHeader;return qr(t.blocks,function(t){var n=Wy(t);n>=e&&(e=n+ +(i&&(!n||jy(t)&&!t.noHeader)))}),e}return 0}function Uy(t,e,n,i){var r,o=e.noHeader,a=(r=Wy(e),{html:Fy[r],richText:By[r]}),s=[],l=e.blocks||[];fo(!l||Kr(l)),l=l||[];var c=t.orderMode;if(e.sortBlocks&&c){l=l.slice();var d={valueAsc:"asc",valueDesc:"desc"};if(Co(d,c)){var u=new fy(d[c],null);l.sort(function(t,e){return u.evaluate(t.sortParam,e.sortParam)})}else"seriesDesc"===c&&l.reverse()}qr(l,function(n,r){var o=e.valueFormatter,l=qy(n)(o?Hr(Hr({},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=tv(e.header,"ordinal",t.useUTC),f=Hy(i,t.renderMode).nameStyle,g=$y(i);return"richText"===t.renderMode?Zy(t,p,f)+a.richText+h:Yy(i,'
'+Ko(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,d=e.valueFormatter||t.valueFormatter||function(t){return Wr(t=Kr(t)?t:[t],function(t,e){return tv(t,Kr(p)?p[e]:p,c)})};if(!o||!a){var u=s?"":t.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||Tv.color.secondary,r),h=o?"":tv(l,"ordinal",c),p=e.valueType,f=a?[]:d(e.value,e.dataIndex),g=!s||!o,m=!s&&o,v=Hy(i,r),_=v.nameStyle,y=v.valueStyle;return"richText"===r?(s?"":u)+(o?"":Zy(t,h,_))+(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(Kr(e)?e.join(" "):e,o)}(t,f,g,m,y)):Yy(i,(s?"":u)+(o?"":function(t,e,n){return''+Ko(t)+""}(h,!s,_))+(a?"":function(t,e,n,i){var r=n?"10px":"20px",o=e?"float:right;margin-left:"+r:"";return t=Kr(t)?t:[t],''+Wr(t,function(t){return Ko(t)}).join("  ")+""}(f,g,m,y)),n)}}function Xy(t,e,n,i,r,o){if(t)return qy(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=ed()}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=Jr(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 Jr(r)?r:(this.richTextStyles[i]=r.style,r.content)},t.prototype.wrapRichTextStyle=function(t,e){var n={};Kr(e)?qr(e,function(t){return Hr(n,t)}):Hr(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"),d=c.length,u=o.getRawValue(a),h=Kr(u),p=function(t,e){return rv(t.getData().getItemVisual(e,"style")[t.visualDrawType])}(o,a);if(d>1||h&&!d){var f=function(t,e,n,i,r){var o=e.getData(),a=Ur(t,function(t,e,n){var i=o.getDimensionInfo(n);return t||i&&!1!==i.tooltip&&null!=i.displayName},!1),s=[],l=[],c=[];function d(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?qr(i,function(t){d(ay(o,n,t),t)}):qr(t,d),{inlineValues:s,inlineValueTypes:l,blocks:c}}(u,o,a,c,p);e=f.inlineValues,n=f.inlineValueTypes,i=f.blocks,r=f.inlineValues[0]}else if(d){var g=l.getDimensionInfo(c[0]);r=e=ay(l,a,c[0]),n=g.type}else r=e=h?u[0]:u;var m=_d(o),v=m&&o.name||"",_=l.getName(a),y=s?v:_;return Vy("section",{header:v,noHeader:s||!m,sortParam:r,blocks:[Vy("nameValue",{markerType:"item",markerColor:p,name:y,noName:!go(y),value:e,valueType:n,dataIndex:a})].concat(i||[])})}var tb=xd();function eb(t,e){return t.getName(e)||t.getId(e)}var nb=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._selectedDataIndicesMap={},e}var n;return v(e,t),e.prototype.init=function(t,e,n){this.seriesIndex=this.componentIndex,this.dataTask=dy({count:rb,reset:ob}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),(tb(this).sourceManager=new Ny(this)).prepareSource();var i=this.getInitialData(t,n);sb(i,this),this.dataTask.context.data=i,tb(this).dataBeforeProcessed=i,ib(this),this._initSelectedMapFromData(i)},e.prototype.mergeDefaultAndTheme=function(t,e){var n=wv(this),i=n?Cv(t):{},r=this.subType;Mv.hasClass(r)&&(r+="Series"),$r(t,e.getTheme().get(this.subType)),$r(t,this.getDefaultOption()),dd(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&Sv(t,i,n)},e.prototype.mergeOption=function(t,e){t=$r(this.option,t,!0),this.fillDataTextStyle(t.data);var n=wv(this);n&&Sv(this.option,t,n);var i=tb(this).sourceManager;i.dirty(),i.prepareSource();var r=this.getInitialData(t,e);sb(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,tb(this).dataBeforeProcessed=r,ib(this),this._initSelectedMapFromData(r)},e.prototype.fillDataTextStyle=function(t){if(t&&!ro(t))for(var e=["show"],n=0;n=0&&d<0)&&(c=o,d=r,u=0),r===d&&(l[u++]=e))}),l.length=u,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(mr.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=i_.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[eb(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){no(r.selectedMap)||(r.selectedMap={});for(var s=r.selectedMap,l=0;l0&&this._innerSelect(t,e)}},e.registerClass=function(t){return Mv.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}(Mv);function ib(t){var e=t.name;_d(t)||(t.name=function(t){var e=t.getRawData(),n=e.mapDimensionsAll("seriesName"),i=[];return qr(n,function(t){var n=e.getDimensionInfo(t);n.displayName&&i.push(n.displayName)}),i.join(" ")}(t)||e)}function rb(t){return t.model.getRawData().count()}function ob(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),ab}function ab(t,e){e.outputData&&t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function sb(t,e){qr(function(t,e){for(var n=new t.constructor(t.length+e.length),i=0;i=0?u():d=setTimeout(u,-r),l=i};return h.clear=function(){d&&(clearTimeout(d),d=null)},h.debounceNextCall=function(t){s=t},h}function Cb(t,e,n,i){var r=t[e];if(r){var o=r[bb]||r,a=r[wb];if(r[xb]!==n||a!==i){if(null==n||!i)return t[e]=o;(r=t[e]=Sb(o,n,"debounce"===i))[bb]=o,r[wb]=i,r[xb]=n}return r}}function kb(t,e){var n=t[e];n&&n[bb]&&(n.clear&&n.clear(),t[e]=n[bb])}var Mb=xd(),Tb={itemStyle:zd(om,!0),lineStyle:zd(nm,!0)},Ab={lineStyle:"stroke",itemStyle:"fill"};function Ib(t,e){var n=t.visualStyleMapper||Tb[e];return n||(console.warn("Unknown style type '"+e+"'."),Tb.itemStyle)}function Pb(t,e){var n=t.visualDrawType||Ab[e];return n||(console.warn("Unknown style type '"+e+"'."),"fill")}var Db={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=t.getModel(i),o=Ib(t,i)(r),a=r.getShallow("decal");a&&(n.setVisual("decal",a),a.dirty=!0);var s=Pb(t,i),l=o[s],c=Qr(l)?l:null,d="auto"===o.fill||"auto"===o.stroke;if(!o[s]||c||d){var u=t.getColorFromPalette(t.name,null,e.getSeriesCount());o[s]||(o[s]=u,n.setVisual("colorFromPalette",!0)),o.fill="auto"===o.fill||Qr(o.fill)?u:o.fill,o.stroke="auto"===o.stroke||Qr(o.stroke)?u: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=Hr({},o);r[s]=c(i),e.setItemVisual(n,"style",r)}}}},Lb=new lm,Eb={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){if(!t.ignoreStyleOnData&&!e.isSeriesFiltered(t)){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=Ib(t,i),o=n.getVisual("drawType");return{dataEach:n.hasItemOption?function(t,e){var n=t.getRawDataItem(e);if(n&&n[i]){Lb.option=n[i];var a=r(Lb);Hr(t.ensureUniqueItemVisual(e,"style"),a),Lb.option.decal&&(t.setItemVisual(e,"decal",Lb.option.decal),Lb.option.decal.dirty=!0),o in a&&t.setItemVisual(e,"colorFromPalette",!1)}}:null}}}},Rb={performRawSeries:!0,overallReset:function(t){var e=wo();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)),Mb(t).scope=r}}),t.eachSeries(function(e){if(!e.isColorBySeries()&&!t.isSeriesFiltered(e)){var n=e.getRawData(),i={},r=e.getData(),o=Mb(e).scope,a=e.visualStyleAccessPath||"itemStyle",s=Pb(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+"",d=n.count();l[s]=e.getColorFromPalette(c,o,d)}})}})}},Nb=Math.PI;var Ob=function(){function t(t,e,n,i){this._stageTaskMap=wo(),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=wo();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;qr(this._allHandlers,function(i){var r=t.get(i.uid)||t.set(i.uid,{});fo(!(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))}qr(t,function(t,s){if(!i.visualType||i.visualType===t.visualType){var l=o._stageTaskMap.get(t.uid),c=l.seriesTaskMap,d=l.overallTask;if(d){var u,h=d.agentStubMap;h.each(function(t){a(i,t)&&(t.dirty(),u=!0)}),u&&d.dirty(),o.updatePayload(d,n);var p=o.getPerformArgs(d,i.block);h.each(function(t){t.perform(p)}),d.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=wo(),s=t.seriesType,l=t.getTargetSeries;function c(e){var s=e.uid,l=a.set(s,o&&o.get(s)||dy({plan:Bb,reset:Vb,count:Wb}));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||dy({reset:zb});o.context={ecModel:n,api:i,overallReset:t.overallReset,scheduler:r};var a=o.agentStubMap,s=o.agentStubMap=wo(),l=t.seriesType,c=t.getTargetSeries,d=!0,u=!1;function h(t){var e=t.uid,n=s.set(e,a&&a.get(e)||(u=!0,dy({reset:$b,onDirty:Fb})));n.context={model:t,overallProgress:d},n.agent=o,n.__block=d,r._pipe(t,n)}fo(!t.createOnAllSeries,""),l?n.eachRawSeriesByType(l,h):c?c(n,i).each(h):(d=!1,qr(n.getSeries(),h)),u&&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 Qr(t)&&(t={overallReset:t,seriesType:Ub(t)}),t.uid=dm("stageHandler"),e&&(t.visualType=e),t},t}();function zb(t){t.overallReset(t.ecModel,t.api,t.payload)}function $b(t){return t.overallProgress&&Hb}function Hb(){this.agent.dirty(),this.getDownstream().dirty()}function Fb(){this.agent&&this.agent.dirty()}function Bb(t){return t.plan?t.plan(t.model,t.ecModel,t.api,t.payload):null}function Vb(t){t.useClearVisual&&t.data.clearAllVisual();var e=t.resetDefines=cd(t.reset(t.model,t.ecModel,t.api,t.payload));return e.length>1?Wr(e,function(t,e){return qb(e)}):jb}var jb=qb(0);function qb(t){return function(e,n){var i=n.data,r=n.resetDefines[t];if(r&&r.dataEach)for(var o=e.start;o0&&d===r.length-c.length){var u=r.slice(0,d);"data"!==u&&(e.mainType=u,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}(),rx=["symbol","symbolSize","symbolRotate","symbolOffset"],ox=rx.concat(["symbolKeepAspect"]),ax={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&&Cx(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=Cx(i)?i:0,r=Cx(r)?r:1,o=Cx(o)?o:0,a=Cx(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]:eo(e)?[e]:Kr(e)?e:null:null),o=i.lineDashOffset;if(r){var a=i.strokeNoScale&&t.getLineScale?t.getLineScale():1;a&&1!==a&&(r=Wr(r,function(t){return t/a}),o/=a)}return[r,o]}var Ix=new Xu(!0);function Px(t){var e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))}function Dx(t){return"string"==typeof t&&"none"!==t}function Lx(t){var e=t.fill;return null!=e&&"none"!==e}function Ex(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 Rx(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 Nx(t,e,n){var i=Vd(e.image,e.__image,n);if(qd(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)*Mo),o.scaleSelf(e.scaleX||1,e.scaleY||1),r.setTransform(o)}return r}}var Ox=["shadowBlur","shadowOffsetX","shadowOffsetY"],zx=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function $x(t,e,n,i,r){var o=!1;if(!i&&e===(n=n||{}))return!1;if(i||e.opacity!==n.opacity){Bx(t,r),o=!0;var a=Math.max(Math.min(e.opacity,1),0);t.globalAlpha=isNaN(a)?du.opacity:a}(i||e.blend!==n.blend)&&(o||(Bx(t,r),o=!0),t.globalCompositeOperation=e.blend||du.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[nw])if(this._disposed)this.id;else{var i,r,o;if(no(e)&&(n=e.lazyUpdate,i=e.silent,r=e.replaceMerge,o=e.transition,e=e.notMerge),this[nw]=!0,Iw(this),!this._model||e){var a=new h_(this._api),s=this._theme,l=this._model=new o_;l.scheduler=this._scheduler,l.ssr=this._ssr,l.init(null,null,null,s,this._locale,a)}this._model.setOption(t,{replaceMerge:r},Hw);var c={seriesTransition:o,optionChanged:!0};if(n)this[rw]={silent:i,updateParams:c},this[nw]=!1,this.getZr().wakeUp();else{try{uw(this),fw.update.call(this,null,c)}catch(t){throw this[rw]=null,this[nw]=!1,t}this._ssr||this._zr.flush(),this[rw]=null,this[nw]=!1,_w.call(this,i),yw.call(this,i)}}},e.prototype.setTheme=function(t,e){if(!this[nw])if(this._disposed)this.id;else{var n=this._model;if(n){var i=e&&e.silent,r=null;this[rw]&&(null==i&&(i=this[rw].silent),r=this[rw].updateParams,this[rw]=null),this[nw]=!0,Iw(this);try{this._updateTheme(t),n.setTheme(this._theme),uw(this),fw.update.call(this,{type:"setTheme"},r)}catch(t){throw this[nw]=!1,t}this[nw]=!1,_w.call(this,i),yw.call(this,i)}}},e.prototype._updateTheme=function(t){Jr(t)&&(t=Bw[t]),t&&((t=zr(t))&&E_(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||mr.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 qr(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;qr(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 qr(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(qw[n]){var a=o,s=o,l=-1/0,c=-1/0,d=[],u=t&&t.pixelRatio||this.getDevicePixelRatio();qr(jw,function(o,u){if(o.group===n){var h=e?o.getZr().painter.getSvgDom().innerHTML:o.renderToCanvas(zr(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),d.push({dom:h,left:p.left,top:p.top})}});var h=(l*=u)-(a*=u),p=(c*=u)-(s*=u),f=wr.createCanvas(),g=zc(f,{renderer:e?"svg":"canvas"});if(g.resize({width:h,height:p}),e){var m="";return qr(d,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 Th({shape:{x:0,y:0,width:h,height:p},style:{fill:t.connectedBackgroundColor}})),qr(d,function(t){var e=new bh({style:{x:t.left*u-a,y:t.top*u-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 gw(this,"convertToPixel",t,e,n)},e.prototype.convertToLayout=function(t,e,n){return gw(this,"convertToLayout",t,e,n)},e.prototype.convertFromPixel=function(t,e,n){return gw(this,"convertFromPixel",t,e,n)},e.prototype.containPixel=function(t,e){var n;if(!this._disposed)return qr(Sd(this._model,t),function(t,i){i.indexOf("Models")>=0&&qr(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=Sd(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;qr(Rw,function(e){var n=function(n){var i,r=t.getModel(),o=n.target;if("globalout"===e?i={}:o&&cx(o,function(t){var e=qh(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=Hr({},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;qr(zw,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?(lx("map","selectchanged",e,i,t),lx("pie","selectchanged",e,i,t)):"select"===t.fromAction?(lx("map","selected",e,i,t),lx("pie","selected",e,i,t)):"unselect"===t.fromAction&&(lx("map","unselected",e,i,t),lx("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()&&Td(this.getDom(),Uw,"");var t=this,e=t._api,n=t._model;qr(t._componentsViews,function(t){t.dispose(n,e)}),qr(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 jw[t.id]}},e.prototype.resize=function(t){if(!this[nw])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[rw]&&(null==i&&(i=this[rw].silent),n=!0,this[rw]=null),this[nw]=!0,Iw(this);try{n&&uw(this),fw.update.call(this,{type:"resize",animation:Hr({duration:0},t&&t.animation)})}catch(t){throw this[nw]=!1,t}this[nw]=!1,_w.call(this,i),yw.call(this,i)}}},e.prototype.showLoading=function(t,e){if(this._disposed)this.id;else if(no(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),Vw[t]){var n=Vw[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=Hr({},t);return e.type=Ow[t.type],e},e.prototype.dispatchAction=function(t,e){if(this._disposed)this.id;else if(no(e)||(e={silent:!!e}),Nw[t.type]&&this._model)if(this[nw])this._pendingActions.push(t);else{var n=e.silent;vw.call(this,t,n);var i=e.flush;i?this._zr.flush():!1!==i&&mr.browser.weChat&&this._throttledZrFlush(),_w.call(this,n),yw.call(this,n)}},e.prototype.updateLabelLayout=function(){Kx.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(ig(t))return;if(t instanceof gh&&function(t){var e=Gh(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)}})}uw=function(t){var e=t._scheduler;e.restorePipelines(t._model),e.prepareStageTasks(),hw(t,!0),hw(t,!1),e.plan()},hw=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")&&!mr.node&&!mr.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),Kx.trigger("series:afterupdate",e,o,s)},Tw=function(t){t[ow]=!0,t.getZr().wakeUp()},Iw=function(t){t[iw]=(t[iw]+1)%1e3},Aw=function(t){t[ow]&&(t.getZr().storage.traverse(function(t){ig(t)||e(t)}),t[ow]=!1)},kw=function(t){return new(function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return v(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){_p(e,n),Tw(t)},n.prototype.leaveEmphasis=function(e,n){yp(e,n),Tw(t)},n.prototype.enterBlur=function(e){!function(t){hp(t,sp)}(e),Tw(t)},n.prototype.leaveBlur=function(e){bp(e),Tw(t)},n.prototype.enterSelect=function(e){xp(e),Tw(t)},n.prototype.leaveSelect=function(e){wp(e),Tw(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[iw]},n}(d_))(t)},Mw=function(t){function e(t,e){for(var n=0;n=0)){tS.push(n);var o=Ob.wrapStageHandler(n,r);o.__prio=e,o.__raw=n,t.push(o)}}function nS(t,e){Vw[t]=e}var iS=function(t){var e=(t=zr(t)).type;e||ad("");var n=e.split(":");2!==n.length&&ad("");var i=!1;"echarts"===n[0]&&(e=n[1],i=!0),t.__isBuiltIn=i,by.set(e,t)};function rS(t,e,n,i){return{eventContent:{selected:Ip(n),isFromClick:e.isFromClick||!1}}}function oS(t){return null==t?0:t.length||1}function aS(t){return t}Jw(Jx,Db),Jw(tw,Eb),Jw(tw,Rb),Jw(Jx,ax),Jw(tw,sx),Jw(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=Gx(n,e))});var r=i.getVisual("decal");if(r)i.getVisual("style").decal=Gx(r,e)}})}),Yw(E_),Zw(900,function(t){var e=wo();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(),qr(t,function(e,n){e.data.setCalculationInfo("stackedOnSeries",n>0?t[n-1].seriesModel:null)}),function(t){qr(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,d){var u,h,p=a.get(e.stackedDimension,d);if(isNaN(p))return r;s?h=a.getRawIndex(d):u=a.get(e.stackedByDimension,d);for(var f=NaN,g=n-1;g>=0;g--){var m=t[g];if(s||(h=m.data.rawIndexOf(m.stackedByDimension,u)),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=Gc(p,v),f=v;break}}}return i[0]=p,i[1]=f,i})})}(t))})}),nS("default",function(t,e){Fr(e=e||{},{text:"loading",textColor:Tv.color.primary,fontSize:12,fontWeight:"normal",fontStyle:"normal",fontFamily:"sans-serif",maskColor:"rgba(255,255,255,0.8)",showSpinner:!0,color:Tv.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new Lc,i=new Th({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});n.add(i);var r,o=new Dh({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 Th({style:{fill:"none"},textContent:o,textConfig:{position:"right",distance:10},zlevel:e.zlevel,z:10001});return n.add(a),e.showSpinner&&((r=new zf({shape:{startAngle:-Nb/2,endAngle:-Nb/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*Nb/2}).start("circularInOut"),r.animateShape(!0).when(1e3,{startAngle:3*Nb/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}),Qw({type:Kh,event:Kh,update:Kh},ko),Qw({type:Qh,event:Qh,update:Qh},ko),Qw({type:Jh,event:np,update:Jh,action:ko,refineEvent:rS,publishNonRefinedEvent:!0}),Qw({type:tp,event:np,update:tp,action:ko,refineEvent:rS,publishNonRefinedEvent:!0}),Qw({type:ep,event:np,update:ep,action:ko,refineEvent:rS,publishNonRefinedEvent:!0}),Xw("default",{}),Xw("dark",nx);var sS=function(){function t(t,e,n,i,r,o){this._old=t,this._new=e,this._oldKeyGetter=n||aS,this._newKeyGetter=i||aS,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===u)this._updateManyToOne&&this._updateManyToOne(c,l),i[s]=null;else if(1===d&&u>1)this._updateOneToMany&&this._updateOneToMany(c,l),i[s]=null;else if(1===d&&1===u)this._update&&this._update(c,l),i[s]=null;else if(d>1&&u>1)this._updateManyToMany&&this._updateManyToMany(c,l),i[s]=null;else if(d>1)for(var h=0;h1)for(var a=0;a30}var _S,yS,bS,xS,wS,SS,CS,kS=no,MS=Wr,TS="undefined"==typeof Int32Array?Array:Int32Array,AS=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],IS=["_approximateExtent"],PS=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;fS(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===zv&&!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&&(Kr(r=this.getVisual(e))?r=r.slice():kS(r)&&(r=Hr({},r)),i[e]=r),r},t.prototype.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{};this._itemVisuals[t]=i,kS(e)?Hr(i,e):i[e]=n},t.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},t.prototype.setLayout=function(t,e){kS(t)?Hr(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?Hr(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=qh(i);r.dataIndex=n,r.dataType=e,r.seriesIndex=t,r.ssrType="chart","group"===i.type&&i.traverse(function(i){var r=qh(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){qr(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:MS(this.dimensions,this._getDimInfo,this),this.hostModel)),wS(e,this),e._store=this._store,e},t.prototype.wrapMethod=function(t,e){var n=this[t];Qr(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(t),this[t]=function(){var t=n.apply(this,arguments);return e.apply(this,[t].concat(ho(arguments)))})},t.internalField=(_S=function(t){var e=t._invertedIndicesMap;qr(e,function(n,i){var r=t._dimInfos[i],o=r.ordinalMeta,a=t._store;if(o){n=e[i]=new TS(o.categories.length);for(var s=0;s1&&(s+="__ec__"+c),i[e]=s}})),t}();function DS(t,e){B_(t)||(t=j_(t));var n=(e=e||{}).coordDimensions||[],i=e.dimensionsDefine||t.dimensionsDefine||[],r=wo(),o=[],a=function(t,e,n,i){var r=Math.max(t.dimensionsDetectedCount||1,e.length,n.length,i||0);return qr(e,function(t){var e;no(t)&&(e=t.dimsDef)&&(r=Math.max(r,e.length))}),r}(t,n,i,e.dimensionsCount),s=e.canOmitUnusedDimensions&&vS(a),l=i===t.dimensionsDefine,c=l?mS(t):gS(i),d=e.encodeDefine;!d&&e.encodeDefaulter&&(d=e.encodeDefaulter(t,a));for(var u=wo(d),h=new Ty(a),p=0;p0&&(i.name=r+(o-1)),o++,e.set(r,o)}}(o),new pS({source:t,dimensions:o,fullDimensionCount:a,dimensionOmitted:s})}function LS(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 ES=function(t){this.coordSysDims=[],this.axisMap=wo(),this.categoryAxisMap=wo(),this.coordSysName=t};var RS={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis",kd).models[0],o=t.getReferringComponents("yAxis",kd).models[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",o),NS(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),NS(o)&&(i.set("y",o),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis",kd).models[0];e.coordSysDims=["single"],n.set("single",r),NS(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar",kd).models[0],o=r.findAxisModel("radiusAxis"),a=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",o),n.set("angle",a),NS(o)&&(i.set("radius",o),e.firstCategoryDimIndex=0),NS(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();qr(o.parallelAxisIndex,function(t,o){var s=r.getComponent("parallelAxis",t),l=a[o];n.set(l,s),NS(s)&&(i.set(l,s),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=o))})},matrix:function(t,e,n,i){var r=t.getReferringComponents("matrix",kd).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 NS(t){return"category"===t.get("type")}function OS(t,e,n){var i,r,o,a=(n=n||{}).byIndex,s=n.stackedCoordDimension;!function(t){return!fS(t.schema)}(e)?(r=e.schema,i=r.dimensions,o=e.store):i=e;var l,c,d,u,h=!(!t||!t.get("stack"));if(qr(i,function(t,e){Jr(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){d="__\0ecstackresult_"+t.id,u="__\0ecstackedover_"+t.id,l&&(l.createInvertedIndices=!0);var p=c.coordDim,f=c.type,g=0;qr(i,function(t){t.coordDim===p&&g++});var m={name:d,coordDim:p,coordDimIndex:g,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length},v={name:u,coordDim:u,coordDimIndex:g+1,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length+1};r?(o&&(m.storeDimIndex=o.ensureCalculationDimension(u,f),v.storeDimIndex=o.ensureCalculationDimension(d,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:u,stackResultDimension:d}}function zS(t,e){return!!e&&e===t.getCalculationInfo("stackedDimension")}function $S(t,e,n){n=n||{};var i,r,o=e.getSourceManager();r=(i=o.getSource()).sourceFormat===zv;var a=function(t){var e=t.get("coordinateSystem"),n=new ES(e),i=RS[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}(e),s=function(t,e){var n,i=t.get("coordinateSystem"),r=sv.get(i);return e&&e.coordSysDims&&(n=Wr(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=Qr(l)?l:l?Zr(Yv,s,e):null,d=DS(i,{coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:e.getEncode(),encodeDefaulter:c,canOmitUnusedDimensions:!r}),u=function(t,e,n){var i,r;return n&&qr(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}(d.dimensions,n.createInvertedIndices,a),h=r?null:o.getSharedDataStore(d),p=OS(e,{schema:d,store:h}),f=new PS(d,e);f.setCalculationInfo(p);var g=null!=u&&function(t){if(t.sourceFormat===zv){var e=function(t){var e=0;for(;er&&(a=o.interval=r);var s=o.intervalPrecision=VS(a);return function(t,e){!isFinite(t[0])&&(t[0]=e[0]),!isFinite(t[1])&&(t[1]=e[1]),jS(t,0,e),jS(t,1,e),t[0]>t[1]&&(t[0]=t[1])}(o.niceTickExtent=[Wc(Math.ceil(t[0]/a)*a,s),Wc(Math.floor(t[1]/a)*a,s)],t),o}function BS(t){var e=Math.pow(10,Qc(t)),n=t/e;return n?2===n?n=3:3===n?n=5:n*=2:n=1,Wc(n*e)}function VS(t){return Uc(t)+2}function jS(t,e,n){t[e]=Math.max(Math.min(t[e],n[1]),n[0])}function qS(t,e){return t>=e[0]&&t<=e[1]}var WS=function(){function t(){this.normalize=US,this.scale=GS}return t.prototype.updateMethods=function(t){t.hasBreaks()?(this.normalize=Yr(t.normalize,t),this.scale=Yr(t.scale,t)):(this.normalize=US,this.scale=GS)},t}();function US(t,e){return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])}function GS(t,e){return t*(e[1]-e[0])+e[0]}function XS(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 YS=function(){function t(t){this._calculator=new WS,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}();Od(YS);var ZS=0,KS=function(){function t(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this.uid=++ZS,this._onCollect=t.onCollect}return t.createByAxisModel=function(e){var n=e.option,i=n.data,r=i&&Wr(i,QS);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(!Jr(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=wo(this.categories))},t}();function QS(t){return no(t)&&null!=t.value?t.value:t+""}var JS=function(t){function e(e){var n=t.call(this,e)||this;n.type="ordinal";var i=n.getSetting("ordinalMeta");return i||(i=new KS({})),Kr(i)&&(i=new KS({categories:Wr(i,function(t){return no(t)?t.value:t})})),n._ordinalMeta=i,n._extent=n.getSetting("extent")||[0,i.categories.length-1],n}return v(e,t),e.prototype.parse=function(t){return null==t?NaN:Jr(t)?this._ordinalMeta.getOrdinal(t):Math.round(t)},e.prototype.contain=function(t){return qS(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}(YS);YS.registerClass(JS);var tC=Wc,eC=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 v(e,t),e.prototype.parse=function(t){return null==t||""===t?NaN:Number(t)},e.prototype.contain=function(t){return qS(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=VS(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=tC(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:tC(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]&&u0&&(o=null===o?s:Math.min(o,s))}n[i]=o}}return n}(t),n=[];return qr(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(),d=Math.abs(c[1]-c[0]);i=s?l/d*s:l}else{var u=t.getData();i=Math.abs(o[1]-o[0])/u.count()}var h=jc(t.get("barWidth"),i),p=jc(t.get("barMaxWidth"),i),f=jc(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:aC(r),stackId:oC(t)})}),function(t){var e={};qr(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 d=t.barMinWidth;d&&(a[s].minWidth=d);var u=t.barGap;null!=u&&(o.gap=u);var h=t.barCategoryGap;null!=h&&(o.categoryGap=h)});var n={};return qr(e,function(t,e){n[e]={};var i=t.stacks,r=t.bandWidth,o=t.categoryGap;if(null==o){var a=Xr(i).length;o=Math.max(35-4*a,15)+"%"}var s=jc(o,r),l=jc(t.gap,1),c=t.remainedWidth,d=t.autoWidthCount,u=(c-s)/(d+(d-1)*l);u=Math.max(u,0),qr(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,d--}else{var i=u;e&&ei&&(i=n),i!==u&&(t.width=i,c-=i+l*i,d--)}}),u=(c-s)/(d+(d-1)*l),u=Math.max(u,0);var h,p=0;qr(i,function(t,e){t.width||(t.width=u),h=t,p+=t.width*(1+l)}),h&&(p-=h.width*l);var f=-p/2;qr(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 lC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="time",n}return v(e,t),e.prototype.getLabel=function(t){var e=this.getSetting("useUTC");return Rm(t.value,Tm[function(t){switch(t){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}(Lm(this._minLevelUnit))]||Tm.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(Jr(n))o=n;else if(Qr(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 d=Nm(t.value,r);o=n[d][d][0]}}return Rm(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=Nm(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=Im,l=0;function c(t,e,n,r,s,c,d){for(var u=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,u);f>0&&(p[s](p[r]()+f*t),h=p.getTime())}d.push({value:h,notAdd:!0})}function d(t,r,o){var a=[],s=!r.length;if(!function(t,e,n,i){return Om(new Date(e),t,i).getTime()===Om(new Date(n),t,i).getTime()}(Lm(t),i[0],i[1],n)){s&&(r=[{value:gC(i[0],t,n)},{value:i[1]}]);for(var l=0;l=i[0]&&d<=i[1]&&c(h,d,u,p,f,g,a),"year"===t&&o.length>1&&0===l&&o.unshift({value:o[0].value-h})}}for(l=0;l=i[0]&&y<=i[1]&&p++)}var b=r/e;if(p>1.5*b&&f>b/1.5)break;if(u.push(v),p>b||t===s[g])break}h=[]}}var x=Gr(Wr(u,function(t){return Gr(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=cC.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 uC(t){return(t/=2592e6)>6?6:t>3?3:t>2?2:1}function hC(t){return(t/=xm)>12?12:t>6?6:t>3.5?4:t>2?2:1}function pC(t,e){return(t/=e?bm:ym)>30?30:t>20?20:t>15?15:t>10?10:t>5?5:t>2?2:1}function fC(t){return Jc(t)}function gC(t,e,n){var i=Math.max(0,Br(Am,e)-1);return Om(new Date(t),Am[i],n).getTime()}YS.registerClass(lC);var mC=Wc,vC=Math.floor,_C=Math.ceil,yC=Math.pow,bC=Math.log,xC=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="log",e.base=10,e._originalScale=new eC,e}return v(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(),Wr(r,function(t){var e=t.value,r=null,a=yC(o,e);return e===n[0]&&this._fixMin?r=i[0]:e===n[1]&&this._fixMax&&(r=i[1]),null!=r&&(a=wC(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=XS(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]=yC(e,n[0]),n[1]=yC(e,n[1]);var i=this._originalScale.getExtent();return this._fixMin&&(n[0]=wC(n[0],i[0])),this._fixMax&&(n[1]=wC(n[1],i[1])),n},e.prototype.unionExtentFromData=function(t,e){this._originalScale.unionExtentFromData(t,e);var n=XS(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,Qc(i)));for(t/n*r<=.5&&(r*=10);!isNaN(r)&&Math.abs(r)<1&&Math.abs(r)>0;)r*=10;var o=[mC(_C(e[0]/r)*r),mC(vC(e[1]/r)*r)];this._interval=r,this._intervalPrecision=VS(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=bC(e)/bC(this.base),t.prototype.contain.call(this,e)},e.prototype.normalize=function(e){return e=bC(e)/bC(this.base),t.prototype.normalize.call(this,e)},e.prototype.scale=function(e){return e=t.prototype.scale.call(this,e),yC(this.base,e)},e.prototype.setBreaksFromOption=function(t){},e.type="log",e}(eC);function wC(t,e){return mC(t,Uc(e))}YS.registerClass(xC);var SC=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 u=this._determinedMin,h=this._determinedMax;return null!=u&&(a=u,l=!0),null!=h&&(s=h,c=!0),{min:a,max:s,minFixed:l,maxFixed:c,isBlank:d}},t.prototype.modifyDataMinMax=function(t,e){this[kC[t]]=e},t.prototype.setDeterminedMinMax=function(t,e){this[CC[t]]=e},t.prototype.freeze=function(){this.frozen=!0},t}(),CC={min:"_determinedMin",max:"_determinedMax"},kC={min:"_dataMin",max:"_dataMax"};function MC(t,e){return null==e?null:so(e)?NaN:t.parse(e)}function TC(t,e){var n=t.type,i=function(t,e,n){var i=t.rawExtentInfo;return i||(i=new SC(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(qr(s,function(t){l=l||t.getBaseAxis()===e.axis}),l){var c=sC(s),d=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[aC(e)]}(i,n.axis);if(void 0===a)return{min:t,max:e};var s=1/0;qr(a,function(t){s=Math.min(t.offset,s)});var l=-1/0;qr(a,function(t){l=Math.max(t.offset+t.width,l)}),s=Math.abs(s),l=Math.abs(l);var c=s+l,d=e-t,u=d/(1-(s+l)/o)-d;return e+=u*(l/c),t-=u*(s/c),{min:t,max:e}}(r,o,e,c);r=d.min,o=d.max}}return{extent:[r,o],fixMin:i.minFixed,fixMax:i.maxFixed}}function AC(t,e){var n=e,i=TC(t,n),r=i.extent,o=n.get("splitNumber");t instanceof xC&&(t.base=n.get("logBase"));var a=t.type,s=n.get("interval"),l="interval"===a||"time"===a;t.setBreaksFromOption(OC(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 IC(t){var e=t.getLabelModel().get("formatter");if("time"===t.type){var n=Pm(e);return function(e,i){return t.scale.getFormattedLabel(e,i,n)}}if(Jr(e))return function(n){var i=t.scale.getLabel(n);return e.replace("{value}",null!=i?i:"")};if(Qr(e)){if("category"===t.type)return function(n,i){return e(PC(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(PC(t,n),r,o)}}return function(e){return t.scale.getLabel(e)}}function PC(t,e){return"category"===t.type?t.scale.getLabel(e):e.value}function DC(t){var e=t.get("interval");return null==e?"auto":e}function LC(t){return"category"===t.type&&0===DC(t.getLabelModel())}function EC(t,e){var n={};return qr(t.mapDimensionsAll(e),function(e){n[function(t,e){return zS(t,e)?t.getCalculationInfo("stackResultDimension"):e}(t,e)]=!0}),Xr(n)}function RC(t){return"middle"===t||"center"===t}function NC(t){return t.getShallow("show")}function OC(t){t.get("breaks",!0)}var zC=function(){function t(){}return t.prototype.getNeedCrossZero=function(){return!this.option.scale},t.prototype.getCoordSysModel=function(){},t}(),$C=[],HC={registerPreprocessor:Yw,registerProcessor:Zw,registerPostInit:function(t){Kw("afterinit",t)},registerPostUpdate:function(t){Kw("afterupdate",t)},registerUpdateLifecycle:Kw,registerAction:Qw,registerCoordinateSystem:function(t,e){sv.register(t,e)},registerLayout:function(t,e){eS(Fw,t,e,1e3,"layout")},registerVisual:Jw,registerTransform:iS,registerLoading:nS,registerMap:function(t,e,n){var i=Qx["registerMap"];i&&i(t,e,n)},registerImpl:function(t,e){Qx[t]=e},PRIORITY:ew,ComponentModel:Mv,ComponentView:db,SeriesModel:nb,ChartView:fb,registerComponentModel:function(t){Mv.registerClass(t)},registerComponentView:function(t){db.registerClass(t)},registerSeriesModel:function(t){nb.registerClass(t)},registerChartView:function(t){fb.registerClass(t)},registerCustomSeries:function(t,e){},registerSubTypeDefaulter:function(t,e){Mv.registerSubTypeDefaulter(t,e)},registerPainter:function(t,e){var n;n=e,Ec[t]=n}};function FC(t){Kr(t)?qr(t,function(t){FC(t)}):Br($C,t)>=0||($C.push(t),Qr(t)&&(t={install:t}),t.install(HC))}var BC=xd(),VC=xd(),jC=1,qC=2;function WC(t){return{out:{noPxChangeTryDetermine:[]},kind:t}}function UC(t,e){var n=Wr(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 GC(t,e){var n=t.getLabelModel().get("customValues");if(n){var i=IC(t),r=t.scale.getExtent();return{labels:Wr(Gr(UC(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=YC(t,n,e);return!n.get("show")||t.scale.isBlank()?{labels:[]}:i}(t,e):function(t){var e=t.scale.getTicks(),n=IC(t);return{labels:Wr(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 XC(t,e,n){var i=t.getTickModel().get("customValues");if(i){var r=t.scale.getExtent();return{ticks:Gr(UC(t,i),function(t){return t>=r[0]&&t<=r[1]})}}return"category"===t.type?function(t,e){var n,i,r=ZC(t),o=DC(e),a=JC(r,o);if(a)return a;e.get("show")&&!t.scale.isBlank()||(n=[]);if(Qr(o))n=rk(t,o,!0);else if("auto"===o){var s=YC(t,t.getLabelModel(),WC(qC));i=s.labelCategoryInterval,n=Wr(s.labels,function(t){return t.tickValue})}else n=ik(t,i=o,!0);return tk(r,o,{ticks:n,tickCategoryInterval:i})}(t,e):{ticks:Wr(t.scale.getTicks(n),function(t){return t.value})}}function YC(t,e,n){var i,r,o=KC(t),a=DC(e),s=n.kind===jC;if(!s){var l=JC(o,a);if(l)return l}Qr(a)?i=rk(t,a):(r="auto"===a?function(t,e){if(e.kind===jC){var n=t.calculateCategoryInterval(e);return e.out.noPxChangeTryDetermine.push(function(){return VC(t).autoInterval=n,!0}),n}var i=VC(t).autoInterval;return null!=i?i:VC(t).autoInterval=t.calculateCategoryInterval(e)}(t,n):a,i=ik(t,r));var c={labels:i,labelCategoryInterval:r};return s?n.out.noPxChangeTryDetermine.push(function(){return tk(o,a,c),!0}):tk(o,a,c),c}var ZC=QC("axisTick"),KC=QC("axisLabel");function QC(t){return function(e){return VC(e)[t]||(VC(e)[t]={list:[]})}}function JC(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 ik(t,e,n){var i=IC(t),r=t.scale,o=r.getExtent(),a=t.getLabelModel(),s=[],l=Math.max((e||0)+1,1),c=o[0],d=r.count();0!==c&&l>1&&d/l>2&&(c=Math.round(Math.ceil(c/l)*l));var u=LC(t),h=a.get("showMinLabel")||u,p=a.get("showMaxLabel")||u;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 rk(t,e,n){var i=t.scale,r=IC(t),o=[];return qr(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 ok=[0,1],ak=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(Bc(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&&sk(n=n.slice(),i.count()),Vc(t,ok,n,e)},t.prototype.coordToData=function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&sk(n=n.slice(),i.count());var r=Vc(t,n,ok,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=Wr(XC(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;qr(e,function(t){t.coord-=c/2,t.onBand=!0});var d=t.scale.getExtent();a=1+d[1]-e[r-1].tickValue,o={coord:e[r-1].coord+c*a,tickValue:d[1]+1,onBand:!0},e.push(o)}var u=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=Wc(t),e=Wc(e),u?t>e:t0&&t<100||(t=5),Wr(this.scale.getMinorTicks(t),function(t){return Wr(t,function(t){return{coord:this.dataToCoord(t),tickValue:t}},this)},this)},t.prototype.getViewLabels=function(t){return GC(this,t=t||WC(qC)).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=IC(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 d=s[0],u=t.dataToCoord(d+1)-t.dataToCoord(d),h=Math.abs(u*Math.cos(o)),p=Math.abs(u*Math.sin(o)),f=0,g=0;d<=s[1];d+=c){var m,v,_=gc(r({value:d}),i.font,"center","top");m=1.3*_.width,v=1.3*_.height,f=Math.max(f,m,7),g=Math.max(g,v,7)}var y=f/h,b=g/p;isNaN(y)&&(y=1/0),isNaN(b)&&(b=1/0);var x=Math.max(0,Math.floor(Math.min(y,b)));if(n===jC)return e.out.noPxChangeTryDetermine.push(Yr(ek,null,t,x,l)),x;var w=nk(t,x,l);return null!=w?w:x}(this,t=t||WC(qC))},t}();function sk(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}var lk=["label","labelLine","layoutOption","priority","defaultAttr","marginForce","minMarginForce","marginDefault","suggestIgnore"];function ck(t,e,n){n=n||3,e?t.dirty|=n:t.dirty&=~n}function dk(t,e){return e=e||3,null==t.dirty||!!(t.dirty&e)}function uk(t){if(t)return dk(t)&&function(t,e,n){var i=e.getComputedTransform();t.transform=Eg(t.transform,i);var r=t.localRect=Lg(t.localRect,e.getBoundingRect()),o=e.style,a=o.margin,s=n&&n.marginForce,l=n&&n.minMarginForce,c=n&&n.marginDefault,d=o.__marginType;null==d&&c&&(a=c,d=Kg.textMargin);for(var u=0;u<4;u++)hk[u]=d===Kg.minMargin&&l&&null!=l[u]?l[u]:s&&null!=s[u]?s[u]:a?a[u]:0;d===Kg.textMargin&&Cg(r,hk,!1,!1);var h=t.rect=Lg(t.rect,r);i&&h.applyTransform(i);d===Kg.minMargin&&Cg(h,hk,!1,!1);t.axisAligned=Pg(i),(t.label=t.label||{}).ignore=e.ignore,ck(t,!1),ck(t,!0,2)}(t,t.label,t),t}var hk=[0,0,0,0];function pk(t,e){for(var n=0;n-1&&(s.style.stroke=s.style.fill,s.style.fill=Tv.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}(nb);function vk(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),Dp(this,l,c,d)},e.prototype.setSymbolScale=function(t){this.scaleX=this.scaleY=t},e.prototype.fadeOut=function(t,e,n){var i=this.childAt(0),r=qh(this).dataIndex,o=n&&n.animation;if(this.silent=i.silent=!0,n&&n.fadeLabel){var a=i.getTextContent();a&&rg(a,{style:{opacity:0}},e,{dataIndex:r,removeOpt:o,cb:function(){i.removeTextContent()}})}else i.removeTextContent();rg(i,{style:{opacity:0},scaleX:0,scaleY:0},e,{dataIndex:r,cb:t,removeOpt:o})},e.getSymbolSize=function(t,e){return Kr(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}(Lc);function yk(t,e){this.parent.drift(t,e)}function bk(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 xk(t){return null==t||no(t)||(t={isIgnore:t}),t||{}}function wk(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:Bg(e),cursorStyle:e.get("cursor")}}var Sk=function(){function t(t){this.group=new Lc,this._SymbolCtor=t||_k}return t.prototype.updateData=function(t,e){this._progressiveEls=null,e=xk(e);var n=this.group,i=t.hostModel,r=this._data,o=this._SymbolCtor,a=e.disableAnimation,s=wk(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(bk(t,r,i,e)){var a=new o(t,i,s,l);a.setPosition(r),t.setItemGraphicEl(i,a),n.add(a)}}).update(function(d,u){var h=r.getItemGraphicEl(u),p=c(d);if(bk(t,p,d,e)){var f=t.getItemVisual(d,"symbol")||"circle",g=h&&h.getSymbolType&&h.getSymbolType();if(!h||g&&g!==f)n.remove(h),(h=new o(t,d,s,l)).setPosition(p);else{h.updateData(t,d,s,l);var m={x:p[0],y:p[1]};a?h.attr(m):eg(h,m,i)}n.add(h),t.setItemGraphicEl(d,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=wk(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=xk(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),d="x"===s||"radius"===s?1:0,u=Wr(t.dimensions,function(t){return e.mapDimension(t)}),h=!1,p=e.getCalculationInfo("stackResultDimension");return zS(e,u[0])&&(h=!0,u[0]=p),zS(e,u[1])&&(h=!0,u[1]=p),{dataDimsForPoint:u,valueStart:o,valueAxisDim:s,baseAxisDim:a,stacked:!!h,valueDim:l,baseDim:c,baseDataOffset:d,stackedOverDimension:e.getCalculationInfo("stackedOverDimension")}}function kk(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 Mk=Math.min,Tk=Math.max;function Ak(t,e){return isNaN(t)||isNaN(e)}function Ik(t,e,n,i,r,o,a,s,l){for(var c,d,u,h,p,f,g=n,m=0;m=r||g<0)break;if(Ak(v,_)){if(l){g+=o;continue}break}if(g===n)t[o>0?"moveTo":"lineTo"](v,_),u=v,h=_;else{var y=v-c,b=_-d;if(y*y+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===_&&m=i||Ak(w,S))p=v,f=_;else{M=w-c,T=S-d;var P=v-c,D=w-v,L=_-d,E=S-_,R=void 0,N=void 0;if("x"===s){var O=M>0?1:-1;p=v-O*(R=Math.abs(P))*a,f=_,A=v+O*(N=Math.abs(D))*a,I=_}else if("y"===s){var z=T>0?1:-1;p=v,f=_-z*(R=Math.abs(L))*a,A=v,I=_+z*(N=Math.abs(E))*a}else R=Math.sqrt(P*P+L*L),p=v-M*a*(1-(k=(N=Math.sqrt(D*D+E*E))/(N+R))),f=_-T*a*(1-k),I=_+T*a*k,A=Mk(A=v+M*a*k,Tk(w,v)),I=Mk(I,Tk(S,_)),A=Tk(A,Mk(w,v)),f=_-(T=(I=Tk(I,Mk(S,_)))-_)*R/N,p=Mk(p=v-(M=A-v)*R/N,Tk(c,v)),f=Mk(f,Tk(d,_)),A=v+(M=v-(p=Tk(p,Mk(c,v))))*N/R,I=_+(T=_-(f=Tk(f,Mk(d,_))))*N/R}t.bezierCurveTo(u,h,p,f,v,_),u=A,h=I}else t.lineTo(v,_)}c=v,d=_,g+=o}return m}var Pk=function(){this.smooth=0,this.smoothConstraint=!0},Dk=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polyline",n}return v(e,t),e.prototype.getDefaultStyle=function(){return{stroke:Tv.color.neutral99,fill:null}},e.prototype.getDefaultShape=function(){return new Pk},e.prototype.buildPath=function(t,e){var n=e.points,i=0,r=n.length/2;if(e.connectNulls){for(;r>0&&Ak(n[2*r-2],n[2*r-1]);r--);for(;i=0){var m=a?(d-i)*g+i:(c-n)*g+n;return a?[t,m]:[m,t]}n=c,i=d;break;case o.C:c=r[l++],d=r[l++],u=r[l++],h=r[l++],p=r[l++],f=r[l++];var v=a?ms(n,c,u,p,t,s):ms(i,d,h,f,t,s);if(v>0)for(var _=0;_=0){m=a?fs(i,d,h,f,y):fs(n,c,u,p,y);return a?[t,m]:[m,t]}}n=p,i=f}}},e}(gh),Lk=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e}(Pk),Ek=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polygon",n}return v(e,t),e.prototype.getDefaultShape=function(){return new Lk},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&&Ak(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=js(e[r]),s=js(e[o]),l=i-r,c=Gs([Ls(zs(a[0],s[0],l)),Ls(zs(a[1],s[1],l)),Ls(zs(a[2],s[2],l)),Es(zs(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 Fk(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 qr(o.getViewLabels(),function(t){var e=o.scale.getRawOrdinalNumber(t.tickValue);s[e]=1}),function(t){return!s.hasOwnProperty(e.get(a,t))}}}}function Bk(t,e){return isNaN(t)||isNaN(e)}function Vk(t,e){return[t[2*e],t[2*e+1]]}function jk(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=Wr(o.stops,function(t){return{coord:l.toGlobalCoord(l.dataToCoord(t.value)),color:t.color}}),d=c.length,u=o.outerColors.slice();d&&c[0].coord>c[d-1].coord&&(c.reverse(),u.reverse());var h=Hk(c,"x"===r?n.getWidth():n.getHeight()),p=h.length;if(!p&&d)return c[0].coord<0?u[1]?u[1]:c[d-1].color:u[0]?u[0]:c[0].color;var f=h[0].coord-10,g=h[p-1].coord+10,m=g-f;if(m<.001)return"transparent";qr(h,function(t){t.offset=(t.coord-f)/m}),h.push({offset:p?h[p-1].offset:.5,color:u[1]||"transparent"}),h.unshift({offset:p?h[0].offset:.5,color:u[0]||"transparent"});var v=new Ff(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&&d.type===i.type&&k===this._step){m&&!p?p=this._newPolygon(l,y):p&&!m&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,rv(M));var T=f.getClipPath();if(T)ng(T,{shape:qk(this,i,!1,t).shape},t);else f.setClipPath(qk(this,i,!0,t));b&&u.updateData(o,{isIgnore:w,clipShape:C,disableAnimation:!0,getSymbolPoint:function(t){return[l[2*t],l[2*t+1]]}}),Rk(this._stackedOnPoints,y)&&Rk(this._points,l)||(g?this._doUpdateAnimation(o,y,i,n,k,v,x):(k&&(y&&(y=$k(y,l,i,k,x)),l=$k(l,null,i,k,x)),h.setShape({points:l}),p&&p.setShape({points:l,stackedOnPoints:y})))}else b&&u.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&&(y&&(y=$k(y,l,i,k,x)),l=$k(l,null,i,k,x)),h=this._newPolyline(l),m?p=this._newPolygon(l,y):p&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,rv(M)),f.setClipPath(qk(this,i,!0,t));var A=t.getModel("emphasis"),I=A.get("focus"),P=A.get("blurScope"),D=A.get("disabled");(h.useStyle(Fr(a.getLineStyle(),{fill:"none",stroke:M,lineJoin:"bevel"})),Rp(h,t,"lineStyle"),h.style.lineWidth>0&&"bolder"===t.get(["emphasis","lineStyle","width"]))&&(h.getState("emphasis").style.lineWidth=+h.style.lineWidth+1);qh(h).seriesIndex=t.seriesIndex,Dp(h,I,P,D);var L=zk(t.get("smooth")),E=t.get("smoothMonotone");if(h.setShape({smooth:L,smoothMonotone:E,connectNulls:x}),p){var R=o.getCalculationInfo("stackedOnSeries"),N=0;p.useStyle(Fr(s.getAreaStyle(),{fill:M,opacity:.7,lineJoin:"bevel",decal:o.getVisual("style").decal})),R&&(N=zk(R.get("smooth"))),p.setShape({smooth:L,stackedOnSmooth:N,smoothMonotone:E,connectNulls:x}),Rp(p,t,"areaStyle"),qh(p).seriesIndex=t.seriesIndex,Dp(p,I,P,D)}var O=this._changePolyState;o.eachItemGraphicEl(function(t){t&&(t.onHoverStateChange=O)}),this._polyline.onHoverStateChange=O,this._data=o,this._coordSys=i,this._stackedOnPoints=y,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){qh(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=bd(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 d=t.get("zlevel")||0,u=t.get("z")||0;(s=new _k(r,o)).x=l,s.y=c,s.setZ(d,u);var h=s.getSymbolPath().getTextContent();h&&(h.zlevel=d,h.z=u,h.z2=this._polyline.z2+1),s.__temp=!0,r.setItemGraphicEl(o,s),s.stopSymbolAnimation(!0),this.group.add(s)}s.highlight()}else fb.prototype.highlight.call(this,t,e,n,i)},e.prototype.downplay=function(t,e,n,i){var r=t.getData(),o=bd(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 fb.prototype.downplay.call(this,t,e,n,i)},e.prototype._changePolyState=function(t){var e=this._polygon;pp(this._polyline,t),e&&pp(e,t)},e.prototype._newPolyline=function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new Dk({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 Ek({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");Qr(l)&&(l=l(null));var c=s.get("animationDelay")||0,d=Qr(c)?c(null):c;t.eachItemGraphicEl(function(t,o){var s=t;if(s){var u=[t.x,t.y],h=void 0,p=void 0,f=void 0;if(n)if(r){var g=n,m=e.pointToCoord(u);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 _=p===h?0:(f-h)/(p-h);a&&(_=1-_);var y=Qr(c)?c(o):l*_+d,b=s.getSymbolPath(),x=b.getTextContent();s.attr({scaleX:0,scaleY:0}),s.animateTo({scaleX:1,scaleY:1},{duration:200,setToFinal:!0,delay:y}),x&&x.animateFrom({style:{opacity:0}},{duration:300,delay:y}),b.disableLabelAnimation=!0}})},e.prototype._initOrUpdateEndLabel=function(t,e,n){var i=t.getModel("endLabel");if(jk(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 Dh({z2:200})).ignoreClip=!0,o.setTextContent(this._endLabel),o.disableLabelAnimation=!0);var l=function(t){for(var e=t.length/2;e>0&&Bk(t[2*e-2],t[2*e-1]);e--);return e-1}(a);l>=0&&(Fg(o,Bg(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(!Kr(e))return e+"";for(var i=[],r=0;r=0&&i.push(e[o])}return i.join(" ")}(r,n):vk(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"),d=n.hostModel,u=d.get("connectNulls"),h=o.get("precision"),p=o.get("distance")||0,f=a.getBaseAxis(),g=f.isHorizontal(),m=f.inverse,v=e.shape,_=m?g?v.x:v.y+v.height:g?v.x+v.width:v.y,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,_,x),S=w.range,C=S[1]-S[0],k=void 0;if(C>=1){if(C>1&&!u){var M=Vk(c,S[0]);s.attr({x:M[0]+y,y:M[1]+b}),r&&(k=d.getRawValue(S[0]))}else{(M=l.getPointOn(_,x))&&s.attr({x:M[0]+y,y:M[1]+b});var T=d.getRawValue(S[0]),A=d.getRawValue(S[1]);r&&(k=function(t,e,n,i,r){var o=null==e||"auto"===e;if(null==i)return i;if(eo(i))return Wc(f=sd(n||0,i,r),o?Math.max(Uc(n||0),Uc(i)):e);if(Jr(i))return r<1?n:i;for(var a=[],s=n,l=i,c=Math.max(s?s.length:0,l.length),d=0;d0?S[0]:0;M=Vk(c,I);r&&(k=d.getRawValue(I)),s.attr({x:M[0]+y,y:M[1]+b})}if(r){var P=Zg(s);"function"==typeof P.setLabelText&&P.setLabelText(k)}}},e.prototype._doUpdateAnimation=function(t,e,n,i,r,o,a){var s=this._polyline,l=this._polygon,c=t.hostModel,d=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=[],d=[],u=[],h=[],p=[],f=[],g=Ck(r,e,a),m=t.getLayout("points")||[],v=e.getLayout("points")||[],_=0;_3e3||l&&Ok(h,f)>3e3)return s.stopAnimation(),s.setShape({points:p}),void(l&&(l.stopAnimation(),l.setShape({points:p,stackedOnPoints:f})));s.shape.__points=d.current,s.shape.points=u;var g={shape:{points:p}};d.current!==u&&(g.shape.__points=d.next),s.stopAnimation(),eg(s,g,c),l&&(l.setShape({points:u,stackedOnPoints:h}),l.stopAnimation(),eg(l,{shape:{stackedOnPoints:f}},c),s.shape.points!==l.shape.points&&(l.shape.points=s.shape.points));for(var m=[],v=d.status,_=0;_e&&(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}(ak),dM="expandAxisBreak",uM=Math.PI,hM=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],pM=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],fM=xd(),gM=xd(),mM=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 vM=[1,0,0,1,0,0],_M=new Pa(0,0,0,0),yM=function(t,e,n,i,r,o){if(RC(t.nameLocation)){var a=o.stOccupiedRect;a&&bM(function(t,e,n){return t.transform=Eg(t.transform,n),t.localRect=Lg(t.localRect,e),t.rect=Lg(t.rect,e),n&&t.rect.applyTransform(n),t.axisAligned=Pg(n),t.obb=void 0,(t.label=t.label||{}).ignore=!1,t}({},a,o.transGroup.transform),i,r)}else xM(o.labelInfoList,o.dirVec,i,r)};function bM(t,e,n){var i=new ma;gk(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 xM(t,e,n,i){for(var r=ma.dot(i,e)>=0,o=0,a=t.length;o0?"top":"bottom",i="center"):Yc(o-uM)?(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}(),SM=["axisLine","axisTickLabelEstimate","axisTickLabelDetermine","axisName"],CM={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,d=[l[0],0],u=[l[1],0],h=d[0]>u[0];c&&(Oo(d,d,c),Oo(u,u,c));var p=Hr({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 Df(Hr({shape:{x1:d[0],y1:d[1],x2:u[0],y2:u[1]}},f));mg(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"]);Jr(m)&&(m=[m,m]),(Jr(v)||eo(v))&&(v=[v,v]);var _=Sx(i.get(["axisLine","symbolOffset"])||0,v),y=v[0],b=v[1];qr([{rotate:t.rotation+Math.PI/2,offset:_[0],r:0},{rotate:t.rotation-Math.PI/2,offset:_[1],r:Math.sqrt((d[0]-u[0])*(d[0]-u[0])+(d[1]-u[1])*(d[1]-u[1]))}],function(e,n){if("none"!==m[n]&&null!=m[n]){var i=xx(m[n],-y/2,-b/2,y,b,p.stroke,!0),o=e.r+e.offset,a=h?u:d;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){AM(e,r,s)&&kM(t,e,n,i,r,o,a,jC)},axisTickLabelDetermine:function(t,e,n,i,r,o,a,s){AM(e,r,s)&&kM(t,e,n,i,r,o,a,qC);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=TM(r.getTicksCoords(),n.transform,l,Fr(s.getLineStyle(),{stroke:i.get(["axisLine","lineStyle","color"])}),"ticks"),d=0;di[1],l="start"===e&&!s||"start"!==e&&s;Yc(a-uM/2)?(o=l?"bottom":"top",r="center"):Yc(a-1.5*uM)?(o=l?"top":"bottom",r="center"):(o="middle",r=a<1.5*uM&&a>uM/2?l?"left":"right":l?"right":"left");return{rotation:a,textAlign:r,textVerticalAlign:o}}(t.rotation,d,x||0,f),null!=(b=t.raw.axisNameAvailableWidth)&&(b=Math.abs(b/Math.sin(y.rotation)),!isFinite(b)&&(b=null)));var w=h.getFont(),S=i.get("nameTruncate",!0)||{},C=S.ellipsis,k=lo(t.raw.nameTruncateMaxWidth,S.maxWidth,b),M=s.nameMarginLevel||0,T=new Dh({x:m.x,y:m.y,rotation:y.rotation,silent:wM.isLabelSilent(i),style:Vg(h,{text:c,font:w,overflow:"truncate",width:k,ellipsis:C,fill:h.getTextColor()||i.get(["axisLine","lineStyle","color"]),align:h.get("align")||y.textAlign,verticalAlign:h.get("verticalAlign")||y.textVerticalAlign}),z2:1});if(Tg({el:T,componentModel:i,itemName:c}),T.__fullText=c,T.anid="name",i.get("triggerEvent")){var A=wM.makeAxisEventDataBase(i);A.targetType="axisName",A.name=c,qh(T).eventData=A}o.add(T),T.updateTransform(),e.nameEl=T;var I=l.nameLayout=uk({label:T,priority:T.z2,defaultAttr:{ignore:T.ignore},marginDefault:RC(d)?hM[M]:pM[M]});if(l.nameLocation=d,r.add(T),T.decomposeTransform(),t.shouldNameMoveOverlap&&I){var P=n.ensureRecord(i);n.resolveAxisNameOverlap(t,n,i,I,v,P)}}}};function kM(t,e,n,i,r,o,a,s){IM(e)||function(t,e,n,i,r,o){var a=r.axis,s=lo(t.raw.axisLabelShow,r.get(["axisLabel","show"])),l=new Lc;n.add(l);var c=WC(i);if(!s||a.scale.isBlank())return void PM(e,[],l,c);var d=r.getModel("axisLabel"),u=a.getViewLabels(c),h=(lo(t.raw.labelRotate,d.get("rotate"))||0)*uM/180,p=wM.innerTextLayout(t.rotation,h,t.labelDirection),f=r.getCategories&&r.getCategories(!0),g=[],m=r.get("triggerEvent"),v=1/0,_=-1/0;qr(u,function(t,e){var n,i="ordinal"===a.scale.type?a.scale.getRawOrdinalNumber(t.tickValue):t.tickValue,s=t.formattedLabel,c=t.rawLabel,h=d;if(f&&f[i]){var y=f[i];no(y)&&y.textStyle&&(h=new lm(y.textStyle,d,r.ecModel))}var b=h.getTextColor()||r.get(["axisLine","lineStyle","color"]),x=h.getShallow("align",!0)||p.textAlign,w=co(h.getShallow("alignMinLabel",!0),x),S=co(h.getShallow("alignMaxLabel",!0),x),C=h.getShallow("verticalAlign",!0)||h.getShallow("baseline",!0)||p.textVerticalAlign,k=co(h.getShallow("verticalAlignMinLabel",!0),C),M=co(h.getShallow("verticalAlignMaxLabel",!0),C),T=10+((null===(n=t.time)||void 0===n?void 0:n.level)||0);v=Math.min(v,T),_=Math.max(_,T);var A=new Dh({x:0,y:0,rotation:0,silent:wM.isLabelSilent(r),z2:T,style:Vg(h,{text:s,align:0===e?w:e===u.length-1?S:x,verticalAlign:0===e?k:e===u.length-1?M:C,fill:Qr(b)?b("category"===a.type?c:"value"===a.type?i+"":i,e):b})});A.anid="label_"+i;var I=fM(A);if(I.break=t.break,I.tickValue=i,I.layoutRotation=p.rotation,Tg({el:A,componentModel:r,itemName:s,formatterParamsExtra:{isTruncated:function(){return A.isTruncated},value:c,tickIndex:e}}),m){var P=wM.makeAxisEventDataBase(r);P.targetType="axisLabel",P.value=c,P.tickIndex=e,t.break&&(P.break={start:t.break.parsedBreak.vmin,end:t.break.parsedBreak.vmax}),"category"===a.type&&(P.dataIndex=i),qh(A).eventData=P,t.break&&function(t,e,n,i){n.on("click",function(n){var r={type:dM,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 y=Wr(g,function(t){return{label:t,priority:fM(t).break?t.z2+(_-v+1):t.z2,defaultAttr:{ignore:t.ignore}}});PM(e,y,l,c)}(t,e,r,s,i,a);var l=e.labelLayoutList;!function(t,e,n,i){var r=e.get(["axisLabel","margin"]);qr(n,function(n,o){var a=uk(n);if(a){var s=a.label,l=fM(s);a.suggestIgnore=s.ignore,s.ignore=!1,lc(DM,LM),DM.x=e.axis.dataToCoord(l.tickValue),DM.y=t.labelOffset+t.labelDirection*r,DM.rotation=l.layoutRotation,i.add(DM),DM.updateTransform(),i.remove(DM),DM.decomposeTransform(),lc(s,DM),s.markRedraw(),ck(a,!0),uk(a)}})}(t,i,l,o),t.rotation;var c=t.optionHideOverlap;!function(t,e,n){if(LC(t.axis))return;function i(t,i,r){var o=uk(e[i]),a=uk(e[r]);if(o&&a)if(!1===t||o.suggestIgnore)MM(o.label);else if(a.suggestIgnore)MM(a.label);else{var s=.1;if(!n){var l=[0,0,0,0];o=pk({marginForce:l},o),a=pk({marginForce:l},a)}gk(o,a,null,{touchThreshold:s})&&MM(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",d=a.transGroup[c];if(s.sort(function(t,e){return Math.abs(t.label[c]-d)-Math.abs(e.label[c]-d)}),l&&r){var u=o.getExtent(),h=Math.min(u[0],u[1]),p=Math.max(u[0],u[1])-h;r.union(new Pa(h,0,p,1))}a.stOccupiedRect=r,a.labelInfoList=s}(t,n,i,l)}function MM(t){t&&(t.ignore=!0)}function TM(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;HS(l)&&s.get("alignTicks")&&null==s.get("interval")?r.push(a):(AC(l,s),HS(l)&&(e=a))}r.length&&(e||AC((e=r.pop()).scale,e.model),qr(r,function(t){!function(t,e,n){var i=eC.prototype,r=i.getTicks.call(n),o=i.getTicks.call(n,{expandToNicedExtent:!0}),a=r.length-1,s=i.getInterval.call(n),l=TC(t,e),c=l.extent,d=l.fixMin,u=l.fixMax;"log"===t.type&&(c=XS(t.base,c,!0)),t.setBreaksFromOption(OC(e)),t.setExtent(c[0],c[1]),t.calcNiceExtent({splitNumber:a,fixMin:d,fixMax:u});var h=i.getExtent.call(t);d&&(c[0]=h[0]),u&&(c[1]=h[1]);var p=i.getInterval.call(t),f=c[0],g=c[1];if(d&&u)p=(g-f)/a;else if(d)for(g=c[0]+p*a;gc[0]&&isFinite(f)&&isFinite(c[0]);)p=BS(p),f=c[1]-p*a;else{t.getTicks().length-1>a&&(p=BS(p));var m=p*a;(f=Wc((g=Math.ceil(c[1]/p)*p)-m))<0&&c[0]>=0?(f=0,g=Wc(m)):g>0&&c[1]<=0&&(g=0,f=-Wc(m))}var v=(r[0].value-o[0].value)/s,_=(r[a].value-o[a].value)/s;i.setExtent.call(t,f+p*v,g+p*_),i.setInterval.call(t,p),(v||_)&&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={};qr(n.x,function(t){HM(n,"y",t,r)}),qr(n.y,function(t){HM(n,"x",t,r)}),this.resize(this.model,e)},t.prototype.resize=function(t,e,n){var i=xv(t,e),r=this._rect=yv(t.getBoxLayoutParams(),i.refContainer),o=this._axesMap,a=this._coordsList,s=t.get("containLabel");if(BM(o,r),!n){var l=function(t,e,n,i,r){var o=new mM(WM);return qr(n,function(n){return qr(n,function(n){if(NC(n.model)){var a=!i;n.axisBuilder=function(t,e,n,i,r,o){for(var a=RM(t,n),s=!1,l=!1,c=0;c0&&i>0||n<0&&i<0)}(t)}function BM(t,e){qr(t.x,function(t){return VM(t,e.x,e.width)}),qr(t.y,function(t){return VM(t,e.y,e.height)})}function VM(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 jM(t,e,n,i,r,o,a){qM(i,r,jC,e,!1,a);var s=[0,0,0,0];c(0),c(1),d(i,0,NaN),d(i,1,NaN);var l=null==function(t,e,n){if(t&&e)for(var i=0,r=t.length;i0});return Cg(i,s,!0,!0,n),BM(r,i),l;function c(t){qr(r[sg[t]],function(e){if(NC(e.model)){var n=o.ensureRecord(e.model),i=n.labelInfoList;if(i)for(var r=0;r0&&!so(e)&&e>1e-4&&(t/=e),t}}function qM(t,e,n,i,r,o){var a=n===qC;qr(e,function(e){return qr(e,function(e){NC(e.model)&&(!function(t,e,n){var i=RM(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[sg[1-e]]=t[lg[e]]<=.5*o.refContainer[lg[e]]?0:1-e==1?2:1}l(0),l(1),qr(e,function(t,e){return qr(t,function(t){NC(t.model)&&(("all"===i||a)&&t.axisBuilder.build({axisName:!0},{nameMarginLevel:s[e]}),a&&t.axisBuilder.build({axisLine:!0}))})})}var WM=function(t,e,n,i,r,o){var a="x"===n.axis.dim?"y":"x";yM(t,0,0,i,r,o),RC(t.nameLocation)||qr(e.recordMap[a],function(t){t&&t.labelInfoList&&t.dirVec&&xM(t.labelInfoList,t.dirVec,i,r)})};function UM(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=[];qr(n.getCoordinateSystems(),function(n){if(n.axisPointerEnabled){var s=ZM(n.model),l=t.coordSysAxesInfo[s]={};t.coordSysMap[s]=n;var c=n.model.getModel("tooltip",i);if(qr(n.getAxes(),Zr(p,!1,null)),n.getTooltipAxes&&i&&c.get("show")){var d="axis"===c.get("trigger"),u="cross"===c.get(["axisPointer","type"]),h=n.getTooltipAxes(c.get(["axisPointer","axis"]));(d||u)&&qr(h.baseAxes,Zr(p,!u||"cross",d)),u&&qr(h.otherAxes,Zr(p,"cross",!1))}}function p(i,s,d){var u=d.model.getModel("axisPointer",r),h=u.get("show");if(h&&("auto"!==h||i||YM(u))){null==s&&(s=u.get("triggerTooltip")),u=i?function(t,e,n,i,r,o){var a=e.getModel("axisPointer"),s={};qr(["type","snap","lineStyle","shadowStyle","label","animation","animationDurationUpdate","animationEasingUpdate","z"],function(t){s[t]=zr(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 d=s.lineStyle=a.get("crossStyle");d&&Fr(l,d.textStyle)}}return t.model.getModel("axisPointer",new lm(s,n,i))}(d,c,r,e,i,s):u;var p=u.get("snap"),f=u.get("triggerEmphasis"),g=ZM(d.model),m=s||p||"category"===d.type,v=t.axesInfo[g]={key:g,axis:d,coordSys:n,axisPointerModel:u,triggerTooltip:s,triggerEmphasis:f,involveSeries:m,snap:p,useHandle:YM(u),seriesModels:[],linkGroup:null};l[g]=v,t.seriesInvolved=t.seriesInvolved||m;var _=function(t,e){for(var n=e.model,i=e.dim,r=0;r=0||t===e}function XM(t){var e=(t.ecModel.getComponent("axisPointer")||{}).coordSysAxesInfo;return e&&e.axesInfo[ZM(t)]}function YM(t){return!!t.get(["handle","show"])}function ZM(t){return t.type+"||"+t.id}var KM={},QM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return v(e,t),e.prototype.render=function(e,n,i,r){this.axisPointerClass&&function(t){var e=XM(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=YM(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=XM(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=lT(t).pointerEl=new zg[r.type](cT(e.pointer));t.add(o)}},t.prototype.createLabelEl=function(t,e,n,i){if(e.label){var r=lT(t).labelEl=new Dh(cT(e.label));t.add(r),fT(r,i)}},t.prototype.updatePointerEl=function(t,e,n){var i=lT(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=lT(t).labelEl;r&&(r.setStyle(e.label.style),n(r,{x:e.label.x,y:e.label.y}),fT(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=xg(o.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(t){aa(t.event)},onmousedown:dT(this._onHandleDragMove,this,0,0),drift:dT(this._onHandleDragMove,this),ondragend:dT(this._onHandleDragEnd,this)}),i.add(r)),mT(r,n,!1),r.setStyle(o.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var s=o.get("size");Kr(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,Cb(this,"_doDispatchAxisPointer",o.get("throttle")||0,"fixRate"),this._moveHandleToValue(t,e)}},t.prototype._moveHandleToValue=function(t,e){hT(this._axisPointerModel,!e&&this._moveAnimation,this._handle,gT(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(gT(n),[t,e],this._axisModel,this._axisPointerModel);this._payloadInfo=i,n.stopAnimation(),n.attr(gT(i)),lT(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),kb(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 hT(t,e,n,i){pT(lT(n).lastProp,i)||(lT(n).lastProp=i,e?eg(n,i,t):(n.stopAnimation(),n.attr(i)))}function pT(t,e){if(no(t)&&no(e)){var n=!0;return qr(e,function(e,i){n=n&&pT(t[i],e)}),!!n}return t===e}function fT(t,e){t[e.get(["label","show"])?"show":"hide"]()}function gT(t){return{x:t.x||0,y:t.y||0,rotation:t.rotation||0}}function mT(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 vT(t,e,n,i,r){var o=_T(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=Jm(a.get("padding")||0),l=a.getFont(),c=gc(o,l),d=r.position,u=c.width+s[1]+s[3],h=c.height+s[0]+s[2],p=r.align;"right"===p&&(d[0]-=u),"center"===p&&(d[0]-=u/2);var f=r.verticalAlign;"bottom"===f&&(d[1]-=h),"middle"===f&&(d[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)}(d,u,h,i);var g=a.get("backgroundColor");g&&"auto"!==g||(g=e.get(["axisLine","lineStyle","color"])),t.label={x:d[0],y:d[1],style:Vg(a,{text:o,font:l,fill:a.getTextColor(),padding:s,backgroundColor:g}),z2:10}}function _T(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:PC(e,{value:t}),axisDimension:e.dim,axisIndex:e.index,seriesData:[]};qr(i,function(t){var e=n.getSeriesByIndex(t.seriesIndex),i=t.dataIndexInside,r=e&&e.getDataParams(i);r&&s.seriesData.push(r)}),Jr(a)?o=a.replace("{value}",o):Qr(a)&&(o=a(s))}return o}function yT(t,e,n){var i=[1,0,0,1,0,0];return fa(i,i,n.rotation),pa(i,i,n.position),_g([t.dataToCoord(e),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],i)}var bT=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e.prototype.makeElOption=function(t,e,n,i,r){var o=n.axis,a=o.grid,s=i.get("type"),l=xT(a,o).getOtherAxis(o).getGlobalExtent(),c=o.toGlobalCoord(o.dataToCoord(e,!0));if(s&&"none"!==s){var d=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),u=wT[s](o,c,l);u.style=d,t.graphicKey=u.type,t.pointer=u}!function(t,e,n,i,r,o){var a=wM.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=r.get(["label","margin"]),vT(e,i,r,o,{position:yT(i.axis,t,n),align:a.textAlign,verticalAlign:a.textVerticalAlign})}(e,t,RM(a.getRect(),n),n,i,r)},e.prototype.getHandleTransform=function(t,e,n){var i=RM(e.axis.grid.getRect(),e,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var r=yT(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=xT(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 d=(s[1]+s[0])/2,u=[d,d];u[l]=c[l];return{x:c[0],y:c[1],rotation:t.rotation,cursorPoint:u,tooltipOption:[{verticalAlign:"middle"},{align:"center"}][l]}},e}(uT);function xT(t,e){var n={};return n[e.dim+"AxisIndex"]=e.index,t.getCartesian(n)}var wT={line:function(t,e,n){var i,r,o;return{type:"Line",subPixelOptimize:!0,shape:(i=[e,n[0]],r=[e,n[1]],o=ST(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=ST(t),{x:i[o=o||0],y:i[1-o],width:r[o],height:r[1-o]})}}};function ST(t){return"x"===t.dim?0:1}var CT=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return v(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:Tv.color.border,width:1,type:"dashed"},shadowStyle:{color:Tv.color.shadowTint},label:{show:!0,formatter:null,precision:"auto",margin:3,color:Tv.color.neutral00,padding:[5,7,5,7],backgroundColor:Tv.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:Tv.color.accent40,throttle:40}},e}(Mv),kT=xd(),MT=qr;function TT(t,e,n){if(!mr.node){var i=e.getZr();kT(i).records||(kT(i).records={}),function(t,e){if(kT(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);MT(kT(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)})}kT(t).initialized=!0,n("click",Zr(IT,"click")),n("mousemove",Zr(IT,"mousemove")),n("globalout",AT)}(i,e),(kT(i).records[t]||(kT(i).records[t]={})).handler=n}}function AT(t,e,n){t.handler("leave",null,n)}function IT(t,e,n,i){e.handler(t,n,i)}function PT(t,e){if(!mr.node){var n=e.getZr();(kT(n).records||{})[t]&&(kT(n).records[t]=null)}}var DT=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return v(e,t),e.prototype.render=function(t,e,n){var i=e.getComponent("tooltip"),r=t.get("triggerOn")||i&&i.get("triggerOn")||"mousemove|click";TT("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){PT("axisPointer",e)},e.prototype.dispose=function(t,e){PT("axisPointer",e)},e.type="axisPointer",e}(db);function LT(t,e){var n,i=[],r=t.seriesIndex;if(null==r||!(n=e.getSeriesByIndex(r)))return{point:[]};var o=n.getData(),a=bd(o,t);if(null==a||a<0||Kr(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(),d=l.getOtherAxis(c).dim,u=c.dim,h="x"===d||"radius"===d?1:0,p=o.mapDimension(u),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(Wr(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 ET=xd();function RT(t,e,n){var i=t.currTrigger,r=[t.x,t.y],o=t,a=t.dispatchAction||Yr(n.dispatchAction,n),s=e.getComponent("axisPointer").coordSysAxesInfo;if(s){HT(r)&&(r=LT({seriesIndex:o.seriesIndex,dataIndex:o.dataIndex},e).point);var l=HT(r),c=o.axesInfo,d=s.axesInfo,u="leave"===i||HT(r),h={},p={},f={list:[],map:{}},g={showPointer:Zr(OT,p),showTooltip:Zr(zT,f)};qr(s.coordSysMap,function(t,e){var n=l||t.containPoint(r);qr(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(!u&&n&&(!c||o)){var a=o&&o.value;null!=a||l||(a=i.pointToData(r)),null!=a&&NT(t,a,g,!1,h)}})});var m={};return qr(d,function(t,e){var n=t.linkGroup;n&&!p[e]&&qr(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,$T(e),$T(t)))),m[t.key]=o}})}),qr(m,function(t,e){NT(d[e],t,g,!0,h)}),function(t,e,n){var i=n.axesInfo=[];qr(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,d,h),function(t,e,n,i){if(HT(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=ET(i)[r]||{},a=ET(i)[r]={};qr(t,function(t,e){var n=t.axisPointerModel.option;"show"===n.status&&t.triggerEmphasis&&qr(n.seriesDataIndices,function(t){var e=t.seriesIndex+" | "+t.dataIndex;a[e]=t})});var s=[],l=[];qr(o,function(t,e){!a[e]&&l.push(t)}),qr(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})}(d,0,n),h}}function NT(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 qr(e.seriesModels,function(e,l){var c,d,u=e.getData().mapDimensionsAll(i);if(e.getAxisTooltipData){var h=e.getAxisTooltipData(u,t,n);d=h.dataIndices,c=h.nestestValue}else{if(!(d=e.indicesOfNearest(i,u[0],t,"category"===n.type?.5:null)).length)return;c=e.getData().get(u[0],d[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),qr(d,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&&Hr(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 OT(t,e,n,i){t[e.key]={value:n,payloadBatch:i}}function zT(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=ZM(l),d=t.map[c];d||(d=t.map[c]={coordSysId:l.id,coordSysIndex:l.componentIndex,coordSysType:l.type,coordSysMainType:l.mainType,dataByAxis:[]},t.list.push(d)),d.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 $T(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 HT(t){return!t||null==t[0]||isNaN(t[0])||null==t[1]||isNaN(t[1])}function FT(t){QM.registerAxisPointerClass("CartesianAxisPointer",bT),t.registerComponentModel(CT),t.registerComponentView(DT),t.registerPreprocessor(function(t){if(t){(!t.axisPointer||0===t.axisPointer.length)&&(t.axisPointer={});var e=t.axisPointer.link;e&&!Kr(e)&&(t.axisPointer.link=[e])}}),t.registerProcessor(t.PRIORITY.PROCESSOR.STATISTIC,function(t,e){t.getComponent("axisPointer").coordSysAxesInfo=UM(t,e)}),t.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},RT)}var BT=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return v(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:Tv.color.neutral00,shadowBlur:10,shadowColor:"rgba(0, 0, 0, .2)",shadowOffsetX:1,shadowOffsetY:2,borderRadius:4,borderWidth:1,defaultBorderColor:Tv.color.border,padding:null,extraCssText:"",axisPointer:{type:"line",axis:"auto",animation:"auto",animationDurationUpdate:200,animationEasingUpdate:"exponentialOut",crossStyle:{color:Tv.color.borderShade,width:1,type:"dashed",textStyle:{}}},textStyle:{color:Tv.color.tertiary,fontSize:14}},e}(Mv);function VT(t){var e=t.get("confine");return null!=e?!!e:"richText"===t.get("renderMode")}function jT(t){if(mr.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?",":"")+(mr.transformSupported?""+GT+r:",left"+r+",top"+r)),UT+":"+o}(o,n,i)),a&&r.push("background-color:"+a),qr(["width","color","radius"],function(e){var n="border-"+e,i=Qm(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=co(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),qr(["decoration","align"],function(n){var i=t.get(n);i&&e.push("text-"+n+":"+i)}),e.join(";")}(u)),null!=h&&r.push("padding:"+Jm(h).join("px ")+"px"),r.join(";")+";"}function KT(t,e,n,i,r){var o=e&&e.painter;if(n){var a=o&&o.getViewportRoot();a&&function(t,e,n,i,r){Go(Uo,e,i,r,!0)&&Go(t,n,Uo[0],Uo[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 QT=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,mr.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&&(Jr(r)?document.querySelector(r):oo(r)?r:Qr(r)&&r(t.getDom()));KT(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;ra(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=XT+ZT(t,!this._firstShow,this._longHide,this._enableDisplayTransition)+YT(r[0],r[1],!0)+"border-color:"+rv(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(Jr(r)&&"item"===n.get("trigger")&&!VT(n)&&(a=function(t,e,n){if(!Jr(n)||"inside"===n)return"";var i=t.get("backgroundColor"),r=t.get("borderWidth");e=rv(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="",d=GT+":";Br(["left","right"],s)>-1?(c+="top:50%",d+="translateY(-50%) rotate("+(a="left"===s?-225:-45)+"deg)"):(c+="left:50%",d+="translateX(-50%) rotate("+(a="top"===s?225:45)+"deg)");var u=a*Math.PI/180,h=l+r,p=h*Math.abs(Math.cos(u))+h*Math.abs(Math.sin(u)),f=e+" solid "+r+"px;";return'
'}(n,i,r)),Jr(t))o.innerHTML=t+a;else if(t){o.innerHTML="",Kr(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&&!mr.node&&n.getDom()){var r=aA(i,n);this._ticket="";var o=i.dataByCoordSys,a=function(t,e,n){var i=Cd(t).queryOptionMap,r=i.keys()[0];if(!r||"series"===r)return;var o=Md(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=qh(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=iA;l.x=i.x,l.y=i.y,l.update(),qh(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=LT(i,e),d=c.point[0],u=c.point[1];null!=d&&null!=u&&this._tryShow({offsetX:d,offsetY:u,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(aA(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"===oA([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"===qh(n).ssrType)return;this._lastDataByCoordSys=null,cx(n,function(t){if(t.tooltipDisabled)return r=o=null,!0;r||o||(null!=qh(t).dataIndex?r=t:null!=qh(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=Yr(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=oA([e.tooltipOption],i),a=this._renderMode,s=[],l=Vy("section",{blocks:[],noHeader:!0}),c=[],d=new Qy;qr(t,function(t){qr(t.dataByAxis,function(t){var e=n.getComponent(t.axisDim+"Axis",t.axisIndex),r=t.value;if(e&&null!=r){var o=_T(r,e.axis,n,t.seriesDataIndices,t.valueLabelOpt),u=Vy("section",{header:o,noHeader:!go(o),sortBlocks:!0,blocks:[]});l.blocks.push(u),qr(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=PC(e.axis,{value:r}),f.axisValueLabel=o,f.marker=d.makeTooltipMarker("item",rv(f.color),a);var g=cy(h.formatTooltip(p,!0,null)),m=g.frag;if(m){var v=oA([h],i).get("valueFormatter");u.blocks.push(v?Hr({valueFormatter:v},m):m)}g.text&&c.push(g.text),s.push(f)}})}})}),l.blocks.reverse(),c.reverse();var u=e.position,h=o.get("order"),p=Xy(l,d,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,u,r[0],r[1],this._tooltipContent,s):this._showTooltipContent(o,g,s,Math.random()+"",r[0],r[1],u,null,d)})},e.prototype._showSeriesItemTooltip=function(t,e,n){var i=this._ecModel,r=qh(e),o=r.seriesIndex,a=i.getSeriesByIndex(o),s=r.dataModel||a,l=r.dataIndex,c=r.dataType,d=s.getData(c),u=this._renderMode,h=t.positionDefault,p=oA([d.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",rv(g.color),u);var v=cy(s.formatTooltip(l,!1,c)),_=p.get("order"),y=p.get("valueFormatter"),b=v.frag,x=b?Xy(y?Hr({valueFormatter:y},b):b,m,u,_,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:d.getRawIndex(l),seriesIndex:o,from:this.uid})}},e.prototype._showComponentItemTooltip=function(t,e,n){var i="html"===this._renderMode,r=qh(e),o=r.tooltipConfig.option||{},a=o.encodeHTMLContent;if(Jr(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=zr(o)).content=Ko(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,d=oA(s,this._tooltipModel,c?{position:c}:null),u=d.get("content"),h=Math.random()+"",p=new Qy;this._showOrMove(d,function(){var n=zr(d.get("formatterParams")||{});this._showTooltipContent(d,u,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 d=t.get("formatter");a=a||t.get("position");var u=e,h=this._getNearestPoint([r,o],n,t.get("trigger"),t.get("borderColor"),t.get("defaultBorderColor",!0)).color;if(d)if(Jr(d)){var p=t.ecModel.get("useUTC"),f=Kr(n)?n[0]:n;u=d,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(u=Rm(f.axisValue,u,p)),u=iv(u,n,!0)}else if(Qr(d)){var g=Yr(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,u=d(n,i,g)}else u=d;c.setContent(u,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||Kr(e)?{color:i||r}:Kr(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(),d=t.get("align"),u=t.get("verticalAlign"),h=a&&a.getBoundingRect().clone();if(a&&h.applyTransform(a.transform),Qr(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),Kr(e))n=jc(e[0],s),i=jc(e[1],l);else if(no(e)){var p=e;p.width=c[0],p.height=c[1];var f=yv(p,{width:s,height:l});n=f.x,i=f.y,d=null,u=null}else if(Jr(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,d=e.height;switch(t){case"inside":s=e.x+c/2-r/2,l=e.y+d/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+d+a;break;case"left":s=e.x-r-a,l=e.y+d/2-o/2;break;case"right":s=e.x+c+a,l=e.y+d/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,d?null:20,u?null:20);n=g[0],i=g[1]}if(d&&(n-=sA(d)?c[0]/2:"right"===d?c[0]:0),u&&(i-=sA(u)?c[1]/2:"bottom"===u?c[1]:0),VT(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&&qr(n,function(n,o){var a=n.dataByAxis||[],s=(t[o]||{}).dataByAxis||[];(r=r&&a.length===s.length)&&qr(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)&&qr(a,function(t,e){var n=l[e];r=r&&t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex}),i&&qr(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){!mr.node&&e.getDom()&&(kb(this,"_updatePosition"),this._tooltipContent.dispose(),PT("itemTooltip",e))},e.type="tooltip",e}(db);function oA(t,e,n){var i,r=e.ecModel;n?(i=new lm(n,r,r),i=new lm(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof lm&&(a=a.get("tooltip",!0)),Jr(a)&&(a={formatter:a}),a&&(i=new lm(a,i,r)))}return i}function aA(t,e){return t.dispatchAction||Yr(e.dispatchAction,e)}function sA(t){return"center"===t||"middle"===t}var lA=Math.sin,cA=Math.cos,dA=Math.PI,uA=2*Math.PI,hA=180/dA,pA=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,d=Math.abs(l),u=tl(d-uA)||(c?l>=uA:-l>=uA),h=l>0?l%uA:l%uA+uA,p=!1;p=!!u||!tl(d)&&h>=dA==!!c;var f=t+n*cA(o),g=e+i*lA(o);this._start&&this._add("M",f,g);var m=Math.round(r*hA);if(u){var v=1/this._p,_=(c?1:-1)*(uA-v);this._add("A",n,i,m,1,+c,t+n*cA(o+_),e+i*lA(o+_)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var y=t+n*cA(a),b=e+i*lA(a);this._add("A",n,i,m,+p,+c,y,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=[],d=this._p,u=1;u"}(r,o)+("style"!==r?Ko(a):a||"")+(i?""+n+Wr(i,function(e){return t(e)}).join(n)+n:"")+("")}(t)}function kA(t){return{zrId:t,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function MA(t,e,n,i){return SA("svg","root",{width:t,height:e,xmlns:yA,"xmlns:xlink":bA,version:"1.1",baseProfile:"full",viewBox:!!i&&"0 0 "+t+" "+e},n)}var TA=0;function AA(){return TA++}var IA={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"},PA="transform-origin";function DA(t,e,n){var i=Hr({},t.shape);Hr(i,e),t.buildPath(n,i);var r=new pA;return r.reset(dl(t)),n.rebuildPath(r,1),r.generateStr(),r.getStr()}function LA(t,e){var n=e.originX,i=e.originY;(n||i)&&(t[PA]=n+"px "+i+"px")}var EA={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function RA(t,e){var n=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[n]=t,n}function NA(t){return Jr(t)?IA[t]?"cubic-bezier("+IA[t]+")":Ms(t)?t:"":""}function OA(t,e,n,i){var r=t.animators,o=r.length,a=[];if(t instanceof $f){var s=function(t,e,n){var i,r,o=t.shape.paths,a={};if(qr(o,function(t){var e=kA(n.zrId);e.animation=!0,OA(t,{},e,!0);var o=e.cssAnims,s=e.cssNodes,l=Xr(o),c=l.length;if(c){var d=o[r=l[c-1]];for(var u in d){var h=d[u];a[u]=a[u]||{d:""},a[u].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=RA(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 RA(d,n)+" "+r[0]+" both"}for(var m in l){(s=g(l[m]))&&a.push(s)}if(a.length){var v=n.zrId+"-cls-"+AA();n.cssNodes["."+v]={animation:a.join(",")},e.class=v}}function zA(t,e,n,i){var r=JSON.stringify(t),o=n.cssStyleCache[r];o||(o=n.zrId+"-cls-"+AA(),n.cssStyleCache[r]=o,n.cssNodes["."+o+":hover"]=t),e.class=e.class?e.class+" "+o:o}var $A=Math.round;function HA(t){return t&&Jr(t.src)}function FA(t){return t&&Qr(t.toDataURL)}function BA(t,e,n,i){_A(function(r,o){var a="fill"===r||"stroke"===r;a&&ll(o)?QA(e,t,r,i):a&&ol(o)?JA(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 d=i.shadowOffsetX||0,u=i.shadowOffsetY||0,h=i.shadowBlur,p=Qs(i.shadowColor),f=p.opacity,g=p.color,m=h/2/l+" "+h/2/c;a=n.zrId+"-s"+n.shadowIdx++,n.defs[a]=SA("filter",a,{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},[SA("feDropShadow","",{dx:d/l,dy:u/c,stdDeviation:m,"flood-color":g,"flood-opacity":f})]),o[r]=a}e.filter=cl(a)}}(n,t,i)}function VA(t,e){var n=function(t){if("function"==typeof Nc)return Nc(t)}(e);n&&(n.each(function(e,n){null!=e&&(t[(xA+n).toLowerCase()]=e+"")}),e.isSilent()&&(t[xA+"silent"]="true"))}function jA(t){return tl(t[0]-1)&&tl(t[1])&&tl(t[2])&&tl(t[3]-1)}function qA(t,e,n){if(e&&(!function(t){return tl(t[4])&&tl(t[5])}(e)||!jA(e))){var i=1e4;t.transform=jA(e)?"translate("+$A(e[4]*i)/i+" "+$A(e[5]*i)/i+")":function(t){return"matrix("+el(t[0])+","+el(t[1])+","+el(t[2])+","+el(t[3])+","+nl(t[4])+","+nl(t[5])+")"}(e)}}function WA(t,e,n){for(var i=t.points,r=[],o=0;o=0&&a||o;s&&(r=Zs(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),zA(c,e,n)}}(t,o,e),SA(s,t.id+"",o)}function KA(t,e){return t instanceof gh?ZA(t,e):t instanceof bh?function(t,e){var n=t.style,i=n.image;if(i&&!Jr(i)&&(HA(i)?i=i.src:FA(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),qA(a,t.transform),BA(a,n,t,e),VA(a,t),e.animation&&OA(t,a,e),SA("image",t.id+"",a)}}(t,e):t instanceof vh?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||_r,o=n.x||0,a=function(t,e,n){return"top"===n?t+=e/2:"bottom"===n&&(t-=e/2),t}(n.y||0,_c(r),n.textBaseline),s={"dominant-baseline":"central","text-anchor":il[n.textAlign]||n.textAlign};if(zh(n)){var l="",c=n.fontStyle,d=Nh(n.fontSize);if(!parseFloat(d))return;var u=n.fontFamily||vr,h=n.fontWeight;l+="font-size:"+d+";font-family:"+u+";",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),qA(s,t.transform),BA(s,n,t,e),VA(s,t),e.animation&&OA(t,s,e),SA("text",t.id+"",s,void 0,i)}}(t,e):void 0}function QA(t,e,n,i){var r,o=t[n],a={gradientUnits:o.global?"userSpaceOnUse":"objectBoundingBox"};if(al(o))r="linearGradient",a.x1=o.x,a.y1=o.y,a.x2=o.x2,a.y2=o.y2;else{if(!sl(o))return;r="radialGradient",a.cx=co(o.x,.5),a.cy=co(o.y,.5),a.r=co(o.r,.5)}for(var s=o.colorStops,l=[],c=0,d=s.length;cl?fI(t,null==n[u+1]?null:n[u+1].elm,n,s,u):gI(t,e,a,l))}(n,i,r):dI(r)?(dI(t.text)&&sI(n,""),fI(n,null,r,0,r.length-1)):dI(i)?gI(n,i,0,i.length-1):dI(t.text)&&sI(n,""):t.text!==e.text&&(dI(i)&&gI(n,i,0,i.length-1),sI(n,e.text)))}var _I=0,yI=function(){function t(t,e,n){if(this.type="svg",this.refreshHover=function(){},this.configLayer=function(){},this.storage=e,this._opts=n=Hr({},n),this.root=t,this._id="zr"+_I++,this._oldVNode=MA(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=wA("svg");mI(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(hI(t,e))vI(t,e);else{var n=t.elm,i=oI(n);pI(e),null!==i&&(nI(i,e.elm,aI(n)),gI(i,[t],0,0))}}(this._oldVNode,t),this._oldVNode=t}},t.prototype.renderOneToVNode=function(t){return KA(t,kA(this._id))},t.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),n=this._width,i=this._height,r=kA(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=SA("rect","bg",{width:t,height:e,x:"0",y:"0"}),ll(n))QA({fill:n},r.attrs,"fill",i);else if(ol(n))JA({style:{fill:n},dirty:ko,getBoundingRect:function(){return{width:t,height:e}}},r.attrs,"fill",i);else{var o=Qs(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=SA("g","main",{},[]);this._paintList(e,r,s?s.children:o),s&&o.push(s);var l=Wr(Xr(r.defs),function(t){return r.defs[t]});if(l.length&&o.push(SA("defs","defs",{},l)),t.animation){var c=function(t,e,n){var i=(n=n||{}).newline?"\n":"",r=" {"+i,o=i+"}",a=Wr(Xr(t),function(e){return e+r+Wr(Xr(t[e]),function(n){return n+":"+t[e][n]+";"}).join(i)+o}).join(i),s=Wr(Xr(e),function(t){return"@keyframes "+t+r+Wr(Xr(e[t]),function(n){return n+r+Wr(Xr(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 d=SA("style","stl",{},[],c);o.push(d)}}return MA(n,i,o,t.useViewBox)},t.prototype.renderToString=function(t){return t=t||{},CA(this.renderToVNode({animation:co(t.cssAnimation,!0),emphasis:co(t.cssEmphasis,!0),willUpdate:!1,compress:!0,useViewBox:co(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&&(!u||!r||u[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(),d=n.getDevicePixelRatio(),u=Math.abs(c[1]-c[0])*(d||1),h=Math.round(a/u);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;Jr(r)?p=Uk[r]:Qr(r)&&(p=r),p&&t.setData(i.downSample(i.mapDimension(l.dim),1/h,p,Gk))}}}}}("line"))},function(t){FC(sT),FC(FT)},function(t){FC(FT),t.registerComponentModel(BT),t.registerComponentView(rA),t.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},ko),t.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},ko)},function(t){t.registerPainter("svg",yI)}]);class bI extends At{constructor(){super(...arguments),this.options=null,this.data=[],this.height="120px",this._chart=null,this._resizeObserver=null}render(){return ct`
`}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=Gw(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)}}bI.styles=k` +var Vc={},jc={};var qc,Wc=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 ds,o=n.renderer||"canvas";Vc[o]||(o=io(Vc)[0]),n.useDirtyRect=null!=n.useDirtyRect&&n.useDirtyRect;var a=new Vc[o](e,r,n,t),s=n.ssr||a.ssrOnly;this.storage=r,this.painter=a;var l,c=kr.node||kr.worker||s?null:new nc(a.getViewportRoot(),a.root),d=n.useCoarsePointer;(null==d||"auto"===d?kr.touchEventsSupported:!!d)&&(l=yo(n.pointerSize,44)),this.handler=new Za(r,a,c,a.root,l),this.animation=new Hl({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 il(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 Qc=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 Jc(t,e,n)};function Jc(t,e,n){return lo(t)?(i=t,i.replace(/^\s+|\s+$/g,"")).match(/%$/)?parseFloat(t)/100*e+(n||0):parseFloat(t):null==t?NaN:+t;var i}function td(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function ed(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 nd(t,e){var n=Math.max(ed(t),ed(e)),i=t+e;return n>20?i:td(i,n)}function id(t){var e=2*Math.PI;return(t%e+e)%e}function rd(t){return t>-1e-4&&t=10&&e++,e}function ld(t,e){var n=sd(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 cd(t){var e=parseFloat(t);return e==t&&(0!==e||!lo(t)||t.indexOf("x")<=0)?e:NaN}function dd(){return Math.round(9*Math.random())}function ud(t,e){return 0===e?t:ud(e,t%e)}function hd(t,e){return null==t?e:null==e?t:t*e/ud(t,e)}var pd="undefined"!=typeof console&&console.warn&&console.log;function fd(t,e){!function(t,e){pd&&console[t]("[ECharts] "+e)}("error",t)}function gd(t){throw new Error(t)}function md(t,e,n){return(e-t)*n+t}var vd="series\0";function _d(t){return t instanceof Array?t:null==t?[]:[t]}function yd(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&&Zr(r,s)<0)){var l=n.getShallow(s,e);null!=l&&(o[t[a][0]]=l)}}return o}}var Gd=Ud([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),Xd=function(){function t(){}return t.prototype.getAreaStyle=function(t,e){return Gd(this,t,e)},t}(),Yd=new Hs(50);function Zd(t){if("string"==typeof t){var e=Yd.get(t);return e&&e.image}return t}function Kd(t,e,n,i,r){if(t){if("string"==typeof t){if(e&&e.__zrImageSrc===t||!n)return e;var o=Yd.get(t),a={hostEl:n,cb:i,cbPayload:r};return o?!Jd(e=o.image)&&o.pending.push(a):((e=Dr.loadImage(t,Qd,Qd)).__zrImageSrc=t,Yd.put(t,e.__cachedImgObj={image:e,pending:[a]})),e}return t}return e}function Qd(){var t=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=s;c++)l-=s;var d=wc(a,n);return d>l&&(n="",d=0),l=t-d,r.ellipsis=n,r.ellipsisWidth=d,r.contentWidth=l,r.containerWidth=t,r}function iu(t,e,n){var i=n.containerWidth,r=n.contentWidth,o=n.fontMeasureInfo;if(!i)return t.textLine="",void(t.isTruncated=!1);var a=wc(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?ru(e,r,o):a>0?Math.floor(e.length*r/a):0;a=wc(o,e=e.substr(0,l))}""===e&&(e=n.placeholder),t.textLine=e,t.isTruncated=!0}function ru(t,e,n){for(var i=0,r=0,o=t.length;r0&&f+i.accumWidth>i.width&&(o=e.split("\n"),u=!0),i.accumWidth=f}else{var g=uu(e,d,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=_c(d),v=0;v=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}(t)||!!cu[t]}function uu(t,e,n,i,r){for(var o=[],a=[],s="",l="",c=0,d=0,u=_c(e),h=0;hn:r+d+f>n)?d?(s||l)&&(g?(s||(s=l,l="",d=c=0),o.push(s),a.push(d-c),l+=p,s="",d=c+=f):(l&&(s+=l,l="",c=0),o.push(s),a.push(d),s=p,d=f)):g?(o.push(l),a.push(c),l=p,c=f):(o.push(p),a.push(f)):(d+=f,g?(l+=p,c+=f):(l&&(s+=l,l="",c=0),s+=p))}else l&&(s+=l,d+=c),o.push(s),a.push(d),s="",l="",c=0,d=0}return l&&(s+=l),s&&(o.push(s),a.push(d)),1===o.length&&(d+=r),{accumWidth:d,lines:o,linesWidths:a}}function hu(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;Ha.set(pu,kc(n,a,r),Mc(i,s,o),a,s),Ha.intersect(e,pu,null,fu);var l=fu.outIntersectRect;t.outerWidth=l.width,t.outerHeight=l.height,t.baseX=kc(l.x,l.width,r,!0),t.baseY=Mc(l.y,l.height,o,!0)}}var pu=new Ha(0,0,0,0),fu={outIntersectRect:{},clamp:!0};function gu(t){return null!=t?t+="":t=""}function mu(t,e,n,i){var r=new Ha(kc(t.x||0,e,t.textAlign),Mc(t.y||0,n,t.textBaseline),e,n),o=null!=i?i:vu(t)?t.lineWidth:0;return o>0&&(r.x-=o/2,r.y-=o/2,r.width+=o,r.height+=o),r}function vu(t){var e=t.stroke;return null!=e&&"none"!==e&&t.lineWidth>0}var _u="__zr_style_"+Math.round(10*Math.random()),yu={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},bu={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};yu[_u]=!0;var xu=["z","z2","invisible"],wu=["invisible"],Su=function(t){function e(e){return t.call(this,e)||this}var n;return v(e,t),e.prototype._init=function(e){for(var n=io(e),i=0;i1e-4)return s[0]=t-n,s[1]=e-i,l[0]=t+n,void(l[1]=e+i);if(Du[0]=Iu(r)*n+t,Du[1]=Au(r)*i+e,Lu[0]=Iu(o)*n+t,Lu[1]=Au(o)*i+e,c(s,Du,Lu),d(l,Du,Lu),(r%=Pu)<0&&(r+=Pu),(o%=Pu)<0&&(o+=Pu),r>o&&!a?o+=Pu:rr&&(Eu[0]=Iu(p)*n+t,Eu[1]=Au(p)*i+e,c(s,Eu,s),d(l,Eu,l))}var Fu={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},Bu=[],Vu=[],ju=[],qu=[],Wu=[],Uu=[],Gu=Math.min,Xu=Math.max,Yu=Math.cos,Zu=Math.sin,Ku=Math.abs,Qu=Math.PI,Ju=2*Qu,th="undefined"!=typeof Float32Array,eh=[];function nh(t){return Math.round(t/Qu*1e8)/1e8%2*Qu}var ih=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=Ku(n/rc/t)||0,this._uy=Ku(n/rc/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(Fu.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=Ku(t-this._xi),i=Ku(e-this._yi),r=n>this._ux||i>this._uy;if(this.addData(Fu.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(Fu.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(Fu.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(),eh[0]=i,eh[1]=r,function(t,e){var n=nh(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-nh(n-r)):e&&n0&&o))for(var a=0;ac.length&&(this._expandData(),c=this.data);for(var d=0;d0&&(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(){ju[0]=ju[1]=Wu[0]=Wu[1]=Number.MAX_VALUE,qu[0]=qu[1]=Uu[0]=Uu[1]=-Number.MAX_VALUE;var t,e=this.data,n=0,i=0,r=0,o=0;for(t=0;tn||Ku(m)>i||u===e-1)&&(f=Math.sqrt(I*I+m*m),r=g,o=y);break;case Fu.C:var v=t[u++],_=t[u++],y=(g=t[u++],t[u++]),b=t[u++],x=t[u++];f=As(r,o,v,_,g,y,b,x,10),r=b,o=x;break;case Fu.Q:f=Es(r,o,v=t[u++],_=t[u++],g=t[u++],y=t[u++],10),r=g,o=y;break;case Fu.A:var w=t[u++],S=t[u++],C=t[u++],k=t[u++],M=t[u++],T=t[u++],A=T+M;u+=1,p&&(a=Yu(M)*C+w,s=Zu(M)*k+S),f=Xu(C,k)*Gu(Ju,Math.abs(T)),r=Yu(A)*C+w,o=Zu(A)*k+S;break;case Fu.R:a=r=t[u++],s=o=t[u++],f=2*t[u++]+2*t[u++];break;case Fu.Z:var I=a-r;m=s-o;f=Math.sqrt(I*I+m*m),r=a,o=s}f>=0&&(l[d++]=f,c+=f)}return this._pathLen=c,c},t.prototype.rebuildPath=function(t,e){var n,i,r,o,a,s,l,c,d,u,h=this.data,p=this._ux,f=this._uy,g=this._len,m=e<1,v=0,_=0,y=0;if(!m||(this._pathSegLen||this._calculateLength(),l=this._pathSegLen,c=e*this._pathLen))t:for(var b=0;b0&&(t.lineTo(d,u),y=0),x){case Fu.M:n=r=h[b++],i=o=h[b++],t.moveTo(r,o);break;case Fu.L:a=h[b++],s=h[b++];var S=Ku(a-r),C=Ku(s-o);if(S>p||C>f){if(m){if(v+(X=l[_++])>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,y=0}else{var M=S*S+C*C;M>y&&(d=a,u=s,y=M)}break;case Fu.C:var T=h[b++],A=h[b++],I=h[b++],P=h[b++],D=h[b++],L=h[b++];if(m){if(v+(X=l[_++])>c){Ts(r,T,I,D,k=(c-v)/X,Bu),Ts(o,A,P,L,k,Vu),t.bezierCurveTo(Bu[1],Vu[1],Bu[2],Vu[2],Bu[3],Vu[3]);break t}v+=X}t.bezierCurveTo(T,A,I,P,D,L),r=D,o=L;break;case Fu.Q:T=h[b++],A=h[b++],I=h[b++],P=h[b++];if(m){if(v+(X=l[_++])>c){Ls(r,T,I,k=(c-v)/X,Bu),Ls(o,A,P,k,Vu),t.quadraticCurveTo(Bu[1],Vu[1],Bu[2],Vu[2]);break t}v+=X}t.quadraticCurveTo(T,A,I,P),r=I,o=P;break;case Fu.A:var E=h[b++],R=h[b++],N=h[b++],O=h[b++],z=h[b++],$=h[b++],H=h[b++],F=!h[b++],B=N>O?N:O,V=Ku(N-O)>.001,j=z+$,q=!1;if(m)v+(X=l[_++])>c&&(j=z+$*(c-v)/X,q=!0),v+=X;if(V&&t.ellipse?t.ellipse(E,R,N,O,H,z,j,F):t.arc(E,R,B,z,j,F),q)break t;w&&(n=Yu(z)*N+E,i=Zu(z)*O+R),r=Yu(j)*N+E,o=Zu(j)*O+R;break;case Fu.R:n=r=h[b],i=o=h[b+1],a=h[b++],s=h[b++];var W=h[b++],U=h[b++];if(m){if(v+(X=l[_++])>c){var G=c-v;t.moveTo(a,s),t.lineTo(a+Gu(G,W),s),(G-=W)>0&&t.lineTo(a+W,s+Gu(G,U)),(G-=U)>0&&t.lineTo(a+Xu(W-G,0),s+U),(G-=W)>0&&t.lineTo(a,s+Xu(U-G,0));break t}v+=X}t.rect(a,s,W,U);break;case Fu.Z:if(m){var X;if(v+(X=l[_++])>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=Fu,t.initDefaultProps=((e=t.prototype)._saveData=!0,e._ux=0,e._uy=0,e._pendingPtDist=0,void(e._version=0)),t}();function rh(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+u&&d>i+u&&d>o+u&&d>s+u||dt+u&&c>n+u&&c>r+u&&c>a+u||c=0&&pe+c&&l>i+c&&l>o+c||lt+c&&s>n+c&&s>r+c||s=0&&gn||d+cr&&(r+=ch);var h=Math.atan2(l,s);return h<0&&(h+=ch),h>=i&&h<=r||h+ch>=i&&h+ch<=r}function uh(t,e,n,i,r,o){if(o>e&&o>i||or?s:0}var hh=ih.CMD,ph=2*Math.PI;var fh=[-1,-1,-1],gh=[-1,-1];function mh(){var t=gh[0];gh[0]=gh[1],gh[1]=t}function vh(t,e,n,i,r,o,a,s,l,c){if(c>e&&c>i&&c>o&&c>s||c1&&mh(),p=Ss(e,i,o,s,gh[0]),h>1&&(f=Ss(e,i,o,s,gh[1]))),2===h?me&&s>i&&s>o||s=0&&d<=1&&(r[l++]=d);else{var c=a*a-4*o*s;if(xs(c))(d=-a/(2*o))>=0&&d<=1&&(r[l++]=d);else if(c>0){var d,u=ps(c),h=(-a-u)/(2*o);(d=(-a+u)/(2*o))>=0&&d<=1&&(r[l++]=d),h>=0&&h<=1&&(r[l++]=h)}}return l}(e,i,o,s,fh);if(0===l)return 0;var c=Ds(e,i,o);if(c>=0&&c<=1){for(var d=0,u=Is(e,i,o,c),h=0;hn||s<-n)return 0;var l=Math.sqrt(n*n-s*s);fh[0]=-l,fh[1]=l;var c=Math.abs(i-r);if(c<1e-4)return 0;if(c>=ph-1e-4){i=0,r=ph;var d=o?1:-1;return a>=fh[0]+t&&a<=fh[1]+t?d:0}if(i>r){var u=i;i=r,r=u}i<0&&(i+=ph,r+=ph);for(var h=0,p=0;p<2;p++){var f=fh[p];if(f+t>a){var g=Math.atan2(s,f);d=o?1:-1;g<0&&(g=ph+g),(g>=i&&g<=r||g+ph>=i&&g+ph<=r)&&(g>Math.PI/2&&g<1.5*Math.PI&&(d=-d),h+=d)}}return h}function bh(t,e,n,i,r){for(var o,a,s=t.data,l=t.len(),c=0,d=0,u=0,h=0,p=0,f=0;f1&&(n||(c+=uh(d,u,h,p,i,r))),m&&(h=d=s[f],p=u=s[f+1]),g){case hh.M:d=h=s[f++],u=p=s[f++];break;case hh.L:if(n){if(rh(d,u,s[f],s[f+1],e,i,r))return!0}else c+=uh(d,u,s[f],s[f+1],i,r)||0;d=s[f++],u=s[f++];break;case hh.C:if(n){if(oh(d,u,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=vh(d,u,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],i,r)||0;d=s[f++],u=s[f++];break;case hh.Q:if(n){if(ah(d,u,s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=_h(d,u,s[f++],s[f++],s[f],s[f+1],i,r)||0;d=s[f++],u=s[f++];break;case hh.A:var v=s[f++],_=s[f++],y=s[f++],b=s[f++],x=s[f++],w=s[f++];f+=1;var S=!!(1-s[f++]);o=Math.cos(x)*y+v,a=Math.sin(x)*b+_,m?(h=o,p=a):c+=uh(d,u,o,a,i,r);var C=(i-v)*b/y+v;if(n){if(dh(v,_,b,x,x+w,S,e,C,r))return!0}else c+=yh(v,_,b,x,x+w,S,C,r);d=Math.cos(x+w)*y+v,u=Math.sin(x+w)*b+_;break;case hh.R:if(h=d=s[f++],p=u=s[f++],o=h+s[f++],a=p+s[f++],n){if(rh(h,p,o,p,e,i,r)||rh(o,p,o,a,e,i,r)||rh(o,a,h,a,e,i,r)||rh(h,a,h,p,e,i,r))return!0}else c+=uh(o,p,o,a,i,r),c+=uh(h,a,h,p,i,r);break;case hh.Z:if(n){if(rh(d,u,h,p,e,i,r))return!0}else c+=uh(d,u,h,p,i,r);d=h,u=p}}return n||function(t,e){return Math.abs(t-e)<1e-4}(u,p)||(c+=uh(d,u,h,p,i,r)||0),0!==c}var xh=Yr({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},yu),wh={style:Yr({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},bu.style)},Sh=mc.concat(["invisible","culling","z","z2","zlevel","parent"]),Ch=function(t){function e(e){return t.call(this,e)||this}var n;return v(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?oc:e>.2?"#eee":ac}if(t)return ac}return oc},e.prototype.getInsideTextStroke=function(t){var e=this.style.fill;if(lo(e)){var n=this.__zr;if(!(!n||!n.isDarkMode())===il(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 ih(!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 bh(t,e,!0,n,i)}(o,a/s,t,e)))return!0}if(this.hasFill())return function(t,e,n){return bh(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:Xr(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(4&this.__dirty)},e.prototype.createStyle=function(t){return Lo(xh,t)},e.prototype._innerSaveToNormal=function(e){t.prototype._innerSaveToNormal.call(this,e);var n=this._normalState;e.shape&&!n.shape&&(n.shape=Xr({},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=Xr({},i.shape),Xr(s,n.shape)):(s=Xr({},r?this.shape:i.shape),Xr(s,n.shape)):l&&(s=i.shape),s)if(o){this.shape=Xr({},this.shape);for(var c={},d=io(s),u=0;uc&&(n*=c/(a=n+i),i*=c/a),r+o>c&&(r*=c/(a=r+o),o*=c/a),i+r>d&&(i*=d/(a=i+r),r*=d/a),n+o>d&&(n*=d/(a=n+o),o*=d/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+d-r),0!==r&&t.arc(s+c-r,l+d-r,r,0,Math.PI/2),t.lineTo(s+o,l+d),0!==o&&t.arc(s+o,l+d-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}(Ch);Oh.prototype.type="rect";var zh={fill:"#000"},$h={},Hh={style:Yr({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},bu.style)},Fh=function(t){function e(e){var n=t.call(this)||this;return n.type="text",n._children=[],n._defaultStyle=zh,n.attr(e),n}return v(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 y=Math.floor(v/h);f=f||m.length>y,_=(m=m.slice(0,y)).length*h}if(r&&d&&null!=g)for(var b=nu(g,c,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),x={},w=0;w0,k=0;kg&&lu(o,a.substring(g,m),e,f),lu(o,h[2],e,f,h[1]),g=tu.lastIndex}gu){var R=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=y[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=y[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&&Qh(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 d=!!s.backgroundColor,u=t.textPadding;u&&(r=Zh(r,o,u),c-=t.height/2-u[0]-t.innerHeight/2);var h=this._getOrCreateChild(Mh),p=h.createStyle();h.useStyle(p);var f=this._defaultStyle,g=!1,m=0,v=!1,_=Yh("fill"in s?s.fill:"fill"in e?e.fill:(g=!0,f.fill)),y=Xh("stroke"in s?s.stroke:"stroke"in e?e.stroke:d||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||Tr,p.opacity=bo(s.opacity,e.opacity,1),Wh(p,s),y&&(p.lineWidth=bo(s.lineWidth,e.lineWidth,m),p.lineDash=yo(s.lineDash,e.lineDash),p.lineDashOffset=e.lineDashOffset||0,p.stroke=y),_&&(p.fill=_),h.setBoundingRect(mu(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,d=t.borderWidth,u=t.borderColor,h=c&&c.image,p=c&&!h,f=t.borderRadius,g=this;if(p||t.lineHeight||d&&u){(a=this._getOrCreateChild(Oh)).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=yo(t.fillOpacity,1);else if(h){(s=this._getOrCreateChild(Ih)).onload=function(){g.dirtyStyle()};var v=s.style;v.image=c.image,v.x=n,v.y=i,v.width=r,v.height=o}d&&u&&((l=a.style).lineWidth=d,l.stroke=u,l.strokeOpacity=yo(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 _=(a||s).style;_.shadowBlur=t.shadowBlur||0,_.shadowColor=t.shadowColor||"transparent",_.shadowOffsetX=t.shadowOffsetX||0,_.shadowOffsetY=t.shadowOffsetY||0,_.opacity=bo(t.opacity,e.opacity,1)},e.makeFont=function(t){var e="";return Uh(t)&&(e=[t.fontStyle,t.fontWeight,qh(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),e&&Co(e)||t.textFont||t.font},e}(Su),Bh={left:!0,right:1,center:1},Vh={top:1,bottom:1,middle:1},jh=["fontStyle","fontWeight","fontSize","fontFamily"];function qh(t){return"string"!=typeof t||-1===t.indexOf("px")&&-1===t.indexOf("rem")&&-1===t.indexOf("em")?isNaN(+t)?"12px":t+"px":t}function Wh(t,e){for(var n=0;n=0,o=!1;if(t instanceof Ch){var a=np(t),s=r&&a.selectFill||a.normalFill,l=r&&a.selectStroke||a.normalStroke;if(hp(s)||hp(l)){var c=(i=i||{}).style||{};"inherit"===c.fill?(o=!0,i=Xr({},i),(c=Xr({},c)).fill=s):!hp(c.fill)&&hp(s)?(o=!0,i=Xr({},i),(c=Xr({},c)).fill=ol(s)):!hp(c.stroke)&&hp(l)&&(o||(i=Xr({},i),c=Xr({},c)),c.stroke=ol(l)),i.style=c}}if(i&&null==i.z2){o||(i=Xr({},i));var d=t.z2EmphasisLift;i.z2=t.z2+(null!=d?d:10)}return i}(this,0,e,n);if("blur"===t)return function(t,e,n){var i=Zr(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 Hp(t,e,n){qp(t,!0),xp(t,Cp),function(t,e,n){var i=Jh(t);null!=e?(i.focus=e,i.blurScope=n):i.focus&&(i.focus=null)}(t,e,n)}function Fp(t,e,n,i){i?function(t){qp(t,!1)}(t):Hp(t,e,n)}var Bp=["emphasis","blur","select"],Vp={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function jp(t,e,n,i){n=n||"itemStyle";for(var r=0;r1&&(a*=Qp(f),s*=Qp(f));var g=(r===o?-1:1)*Qp((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,_=(t+n)/2+tf(u)*m-Jp(u)*v,y=(e+i)/2+Jp(u)*m+tf(u)*v,b=of([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=of(x,w);if(rf(x,w)<=-1&&(S=ef),rf(x,w)>=1&&(S=0),S<0){var C=Math.round(S/ef*1e6)/1e6;S=2*ef+C%2*ef}d.addData(c,_,y,a,s,b,S,u,o)}var sf=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,lf=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;var cf=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e.prototype.applyTransform=function(t){},e}(Ch);function df(t){return null!=t.setData}function uf(t,e){var n=function(t){var e=new ih;if(!t)return e;var n,i=0,r=0,o=i,a=r,s=ih.CMD,l=t.match(sf);if(!l)return e;for(var c=0;cP*P+D*D&&(C=M,k=T),{cx:C,cy:k,x0:-d,y0:-u,x1:C*(r/x-1),y1:k*(r/x-1)}}function Af(t,e){var n,i=Cf(e.r,0),r=Cf(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,d=e.cy,u=!!e.clockwise,h=wf(l-s),p=h>vf&&h%vf;if(p>Mf&&(h=p),i>Mf)if(h>vf-Mf)t.moveTo(c+i*yf(s),d+i*_f(s)),t.arc(c,d,i,s,l,!u),r>Mf&&(t.moveTo(c+r*yf(l),d+r*_f(l)),t.arc(c,d,r,l,s,u));else{var f=void 0,g=void 0,m=void 0,v=void 0,_=void 0,y=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,P=i*yf(s),D=i*_f(s),L=r*yf(l),E=r*_f(l),R=h>Mf;if(R){var N=e.cornerRadius;N&&(n=function(t){var e;if(ao(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}(N),f=n[0],g=n[1],m=n[2],v=n[3]);var O=wf(i-r)/2;if(_=kf(O,m),y=kf(O,v),b=kf(O,f),x=kf(O,g),C=w=Cf(_,y),k=S=Cf(b,x),(w>Mf||S>Mf)&&(M=i*yf(l),T=i*_f(l),A=r*yf(s),I=r*_f(s),hMf){var q=kf(m,C),W=kf(v,C),U=Tf(A,I,P,D,i,q,u),G=Tf(M,T,L,E,i,W,u);t.moveTo(c+U.cx+U.x0,d+U.cy+U.y0),C0&&t.arc(c+U.cx,d+U.cy,q,xf(U.y0,U.x0),xf(U.y1,U.x1),!u),t.arc(c,d,i,xf(U.cy+U.y1,U.cx+U.x1),xf(G.cy+G.y1,G.cx+G.x1),!u),W>0&&t.arc(c+G.cx,d+G.cy,W,xf(G.y1,G.x1),xf(G.y0,G.x0),!u))}else t.moveTo(c+P,d+D),t.arc(c,d,i,s,l,!u);else t.moveTo(c+P,d+D);if(r>Mf&&R)if(k>Mf){q=kf(f,k),U=Tf(L,E,M,T,r,-(W=kf(g,k)),u),G=Tf(P,D,A,I,r,-q,u);t.lineTo(c+U.cx+U.x0,d+U.cy+U.y0),k0&&t.arc(c+U.cx,d+U.cy,W,xf(U.y0,U.x0),xf(U.y1,U.x1),!u),t.arc(c,d,r,xf(U.cy+U.y1,U.cx+U.x1),xf(G.cy+G.y1,G.cx+G.x1),u),q>0&&t.arc(c+G.cx,d+G.cy,q,xf(G.y1,G.x1),xf(G.y0,G.x0),!u))}else t.lineTo(c+L,d+E),t.arc(c,d,r,l,s,u);else t.lineTo(c+L,d+E)}else t.moveTo(c,d);t.closePath()}}}var If=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},Pf=function(t){function e(e){return t.call(this,e)||this}return v(e,t),e.prototype.getDefaultShape=function(){return new If},e.prototype.buildPath=function(t,e){Af(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(Ch);Pf.prototype.type="sector";var Df=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},Lf=function(t){function e(e){return t.call(this,e)||this}return v(e,t),e.prototype.getDefaultShape=function(){return new Df},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}(Ch);function Ef(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=[],d=[],u=[];if(i){a=[1/0,1/0],s=[-1/0,-1/0];for(var h=0,p=t.length;heg[1]){if(r=!1,ng.negativeSize||n)return r;var s=Jf(eg[0]-tg[1]),l=Jf(tg[0]-eg[1]);Kf(s,l)>rg.len()&&(s=l||!ng.bidirectional)&&(ka.scale(ig,a,-l*i),ng.useDir&&ng.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 u={duration:d.duration,delay:d.delay||0,easing:d.easing,done:o,force:!!o||!!a,setToFinal:!c,scope:t,during:a};l?e.animateFrom(n,u):e.animateTo(n,u)}else e.stopAnimation(),!l&&e.attr(n),a&&a(1),o&&o()}function dg(t,e,n,i,r,o){cg("update",t,e,n,i,r,o)}function ug(t,e,n,i,r,o){cg("enter",t,e,n,i,r,o)}function hg(t){if(!t.__zr)return!0;for(var e=0;e=-1e-6)return!1;var f=t-r,g=e-o,m=Lg(f,g,c,d)/p;if(m<0||m>1)return!1;var v=Lg(f,g,u,h)/p;return!(v<0||v>1)}function Lg(t,e,n,i){return t*i-n*e}function Eg(t,e,n,i,r){return null==e||(uo(e)?Rg[0]=Rg[1]=Rg[2]=Rg[3]=e:(Rg[0]=e[0],Rg[1]=e[1],Rg[2]=e[2],Rg[3]=e[3]),i&&(Rg[0]=Yc(0,Rg[0]),Rg[1]=Yc(0,Rg[1]),Rg[2]=Yc(0,Rg[2]),Rg[3]=Yc(0,Rg[3])),n&&(Rg[0]=-Rg[0],Rg[1]=-Rg[1],Rg[2]=-Rg[2],Rg[3]=-Rg[3]),Ng(t,Rg,"x","width",3,1,r&&r[0]||0),Ng(t,Rg,"y","height",0,2,r&&r[1]||0)),t}var Rg=[0,0,0,0];function Ng(t,e,n,i,r,o,a){var s=e[o]+e[r],l=t[i];t[i]+=s,a=Yc(0,Xc(a,l)),t[i]=0?-e[r]:e[o]>=0?l+e[o]:Zc(s)>1e-8?(l-a)*e[r]/s:0):t[n]-=e[r]}function Og(t){var e=t.itemTooltipOption,n=t.componentModel,i=t.itemName,r=lo(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&&Jr(io(l),function(t){Eo(s,t)||(s[t]=l[t],s.$vars.push(t))});var c=Jh(t.el);c.componentMainType=o,c.componentIndex=a,c.tooltipConfig={name:i,option:Yr({content:i,encodeHTMLContent:!0,formatterParams:s},r)}}function zg(t,e){var n;t.isGroup&&(n=e(t)),n||t.traverse(e)}function $g(t,e){if(t)if(ao(t))for(var n=0;ne&&(e=i),ie&&(n=e=0),{min:n,max:e}},clipPointsByRect:function(t,e){return to(t,function(t){var n=t[0];n=Yc(n,e.x),n=Xc(n,e.x+e.width);var i=t[1];return i=Yc(i,e.y),[n,i=Xc(i,e.y+e.height)]})},clipRectByRect:function(t,e){var n=Yc(t.x,e.x),i=Xc(t.x+t.width,e.x+e.width),r=Yc(t.y,e.y),o=Xc(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:Pg,ensureCopyRect:Bg,ensureCopyTransform:Vg,expandOrShrinkRect:Eg,extendPath:function(t,e){return _g(t,e)},extendShape:function(t){return Ch.extend(t)},getShapeClass:function(t){if(gg.hasOwnProperty(t))return gg[t]},getTransform:function(t,e){for(var n=ya([]);t&&t!==e;)xa(n,t.getLocalTransform(),n),t=t.parent;return n},groupTransition:Ig,initProps:ug,isBoundingRectAxisAligned:Hg,isElementRemoved:hg,lineLineIntersect:Dg,linePolygonIntersect:function(t,e,n,i,r){for(var o=0,a=r[r.length-1];oZc(o[1])?o[0]>0?"right":"left":o[1]>0?"bottom":"top"},traverseElements:$g,traverseUpdateZ:qg,updateProps:dg}),Gg={};function Xg(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=so(t.defaultText)?t.defaultText(o,t,n):t.defaultText);for(var l={normal:i},c=0;c-1?bm:wm;function Mm(t,e){t=t.toUpperCase(),Cm[t]=new vm(e),Sm[t]=e}Mm(xm,{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:". "}}}}),Mm(bm,{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 Tm(){return null}var Am=1e3,Im=6e4,Pm=36e5,Dm=864e5,Lm=31536e6,Em={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})/},Rm={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}"},Nm="{yyyy}-{MM}-{dd}",Om={year:"{yyyy}",month:"{yyyy}-{MM}",day:Nm,hour:Nm+" "+Rm.hour,minute:Nm+" "+Rm.minute,second:Nm+" "+Rm.second,millisecond:"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}"},zm=["year","month","day","hour","minute","second","millisecond"],$m=["year","half-year","quarter","month","week","half-week","day","half-day","quarter-day","hour","minute","second","millisecond"];function Hm(t){return lo(t)||so(t)?t:function(t){t=t||{};var e={},n=!0;return Jr(zm,function(e){n&&(n=null==t[e])}),Jr(zm,function(i,r){var o=t[i];e[i]={};for(var a=null,s=r;s>=0;s--){var l=zm[s],c=ho(o)&&!ao(o)?o[l]:o,d=void 0;ao(c)?a=(d=c.slice())[0]||"":lo(c)?d=[a=c]:(null==a?a=Rm[i]:Em[l].test(a)||(a=e[l][l][0]+" "+a),d=[a],n&&(d[1]="{primary|"+a+"}")),e[i][l]=d}}),e}(t)}function Fm(t,e){return"0000".substr(0,e-(t+="").length)+t}function Bm(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 Vm(t){return t===Bm(t)}function jm(t,e,n,i){var r=ad(t),o=r[Um(n)](),a=r[Gm(n)]()+1,s=Math.floor((a-1)/3)+1,l=r[Xm(n)](),c=r["get"+(n?"UTC":"")+"Day"](),d=r[Ym(n)](),u=(d-1)%12+1,h=r[Zm(n)](),p=r[Km(n)](),f=r[Qm(n)](),g=d>=12?"pm":"am",m=g.toUpperCase(),v=i instanceof vm?i:function(t){return Cm[t]}(i||km)||Cm[wm],_=v.getModel("time"),y=_.get("month"),b=_.get("monthAbbr"),x=_.get("dayOfWeek"),w=_.get("dayOfWeekAbbr");return(e||"").replace(/{a}/g,g+"").replace(/{A}/g,m+"").replace(/{yyyy}/g,o+"").replace(/{yy}/g,Fm(o%100+"",2)).replace(/{Q}/g,s+"").replace(/{MMMM}/g,y[a-1]).replace(/{MMM}/g,b[a-1]).replace(/{MM}/g,Fm(a,2)).replace(/{M}/g,a+"").replace(/{dd}/g,Fm(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,x[c]).replace(/{ee}/g,w[c]).replace(/{e}/g,c+"").replace(/{HH}/g,Fm(d,2)).replace(/{H}/g,d+"").replace(/{hh}/g,Fm(u+"",2)).replace(/{h}/g,u+"").replace(/{mm}/g,Fm(h,2)).replace(/{m}/g,h+"").replace(/{ss}/g,Fm(p,2)).replace(/{s}/g,p+"").replace(/{SSS}/g,Fm(f,3)).replace(/{S}/g,f+"")}function qm(t,e){var n=ad(t),i=n[Gm(e)]()+1,r=n[Xm(e)](),o=n[Ym(e)](),a=n[Zm(e)](),s=n[Km(e)](),l=0===n[Qm(e)](),c=l&&0===s,d=c&&0===a,u=d&&0===o,h=u&&1===r;return h&&1===i?"year":h?"month":u?"day":d?"hour":c?"minute":l?"second":"millisecond"}function Wm(t,e,n){switch(e){case"year":t[tv(n)](0);case"month":t[ev(n)](1);case"day":t[nv(n)](0);case"hour":t[iv(n)](0);case"minute":t[rv(n)](0);case"second":t[ov(n)](0)}return t}function Um(t){return t?"getUTCFullYear":"getFullYear"}function Gm(t){return t?"getUTCMonth":"getMonth"}function Xm(t){return t?"getUTCDate":"getDate"}function Ym(t){return t?"getUTCHours":"getHours"}function Zm(t){return t?"getUTCMinutes":"getMinutes"}function Km(t){return t?"getUTCSeconds":"getSeconds"}function Qm(t){return t?"getUTCMilliseconds":"getMilliseconds"}function Jm(t){return t?"setUTCFullYear":"setFullYear"}function tv(t){return t?"setUTCMonth":"setMonth"}function ev(t){return t?"setUTCDate":"setDate"}function nv(t){return t?"setUTCHours":"setHours"}function iv(t){return t?"setUTCMinutes":"setMinutes"}function rv(t){return t?"setUTCSeconds":"setSeconds"}function ov(t){return t?"setUTCMilliseconds":"setMilliseconds"}function av(t){if(isNaN(cd(t)))return lo(t)?t:"-";var e=(t+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function sv(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 lv=wo;function cv(t,e,n){function i(t){return t&&Co(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?ad(t):t;if(!isNaN(+s))return jm(s,"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}",n);if(a)return"-"}if("ordinal"===e)return co(t)?i(t):uo(t)&&r(t)?t+"":"-";var l=cd(t);return r(l)?av(l):co(t)?i(t):"boolean"==typeof t?t+"":"-"}var dv=["a","b","c","d","e","f","g"],uv=function(t,e){return"{"+t+(null==e?"":e)+"}"};function hv(t,e,n){ao(e)||(e=[e]);var i=e.length;if(!i)return"";for(var r=e[0].$vars||[],o=0;oi||l.newline?(o=0,d=g,a+=s+n,s=h.height):s=Math.max(s,h.height)}else{var m=h.height+(f?-f.y+h.y:0);(u=a+m)>r||l.newline?(o+=s+n,a=0,u=m,s=h.width):s=Math.max(s,h.width)}l.newline||(l.x=o,l.y=a,l.markRedraw(),"horizontal"===t?o=d+n:a=u+n)})}function Av(t,e,n){n=lv(n||0);var i=e.width,r=e.height,o=Qc(t.left,i),a=Qc(t.top,r),s=Qc(t.right,i),l=Qc(t.bottom,r),c=Qc(t.width,i),d=Qc(t.height,r),u=n[2]+n[0],h=n[1]+n[3],p=t.aspect;switch(isNaN(c)&&(c=i-s-h-o),isNaN(d)&&(d=r-l-u-a),null!=p&&(isNaN(c)&&isNaN(d)&&(p>i/r?c=.8*i:d=.8*r),isNaN(c)&&(c=p*d),isNaN(d)&&(d=c/p)),isNaN(o)&&(o=i-s-c-h),isNaN(a)&&(a=r-l-d-u),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-d/2-n[0];break;case"bottom":a=r-d-u}o=o||0,a=a||0,isNaN(c)&&(c=i-h-o-(s||0)),isNaN(d)&&(d=r-u-a-(l||0));var f=new Ha((e.x||0)+o+n[3],(e.y||0)+a+n[0],c,d);return f.margin=n,f}oo(Tv,"vertical"),oo(Tv,"horizontal");var Iv=1;function Pv(t,e,n){var i,r,o,a,s=t.boxCoordinateSystem;if(s){var l=function(t){var e=t.getShallow("coord",!0),n=vv;if(null==e){var i=yv.get(t.type);i&&i.getCoord2&&(n=_v,e=i.getCoord2(t))}return{coord:e,from:n}}(t),c=l.coord,d=l.from;if(s.dataToLayout){o=Iv,a=d;var u=s.dataToLayout(c);i=u.contentRect||u.rect}}return null==o&&(o=Iv),o===Iv&&(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 Dv(t){var e=t.layoutMode||t.constructor.layoutMode;return ho(e)?e:e?{type:e}:null}function Lv(t,e,n){var i=n&&n.ignoreSize;!ao(i)&&(i=[i,i]);var r=a(Mv[0],0),o=a(Mv[1],1);function a(n,r){var o={},a=0,l={},c=0;if(Cv(n,function(e){l[e]=t[e]}),Cv(n,function(t){Eo(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 d=0;d=0;a--)o=Gr(o,n[a],!0);e.defaultOption=o}return e.defaultOption},e.prototype.getReferringComponents=function(t,e){var n=t+"Index",i=t+"Id";return Nd(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}(vm);Bd(Nv,vm),Wd(Nv),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){var i=Hd(t);e[i.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var o=Hd(n).main;t.hasSubTypes(n)&&e[o]&&(r=e[o](i))}return r}}(Nv),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 Jr(t,function(o){var a=n(i,o),s=function(t,e){var n=[];return Jr(t,function(t){Zr(e,t)>=0&&n.push(t)}),n}(a.originalDeps=e(o),t);a.entryCount=s.length,0===a.entryCount&&r.push(o),Jr(s,function(t){Zr(a.predecessor,t)<0&&a.predecessor.push(t);var e=n(i,t);Zr(e.successor,t)<0&&e.successor.push(o)})}),{graph:i,noEntryList:r}}(i),s=a.graph,l=a.noEntryList,c={};for(Jr(t,function(t){c[t]=!0});l.length;){var d=l.pop(),u=s[d],h=!!c[d];h&&(r.call(o,d,u.originalDeps.slice()),delete c[d]),Jr(u.successor,h?f:p)}Jr(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)}}}(Nv,function(t){var e=[];Jr(Nv.getClassesByMainType(t),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=to(e,function(t){return Hd(t).main}),"dataset"!==t&&Zr(e,"dataset")<=0&&e.unshift("dataset");return e});var Ov={color:{},darkColor:{},size:{}},zv=Ov.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 $v in Xr(zv,{primary:zv.neutral80,secondary:zv.neutral70,tertiary:zv.neutral60,quaternary:zv.neutral50,disabled:zv.neutral20,border:zv.neutral30,borderTint:zv.neutral20,borderShade:zv.neutral40,background:zv.neutral05,backgroundTint:"rgba(234,237,245,0.5)",backgroundTransparent:"rgba(255,255,255,0)",backgroundShade:zv.neutral10,shadow:"rgba(0,0,0,0.2)",shadowTint:"rgba(129,130,136,0.2)",axisLine:zv.neutral70,axisLineTint:zv.neutral40,axisTick:zv.neutral70,axisTickMinor:zv.neutral60,axisLabel:zv.neutral70,axisSplitLine:zv.neutral15,axisMinorSplitLine:zv.neutral05}),zv)if(zv.hasOwnProperty($v)){var Hv=zv[$v];"theme"===$v?Ov.darkColor.theme=zv.theme.slice():"highlight"===$v?Ov.darkColor.highlight="rgba(255,231,130,0.4)":0===$v.indexOf("accent")?Ov.darkColor[$v]=el(Hv,0,function(t){return.5*t},function(t){return Math.min(1,1.3-t)}):Ov.darkColor[$v]=el(Hv,0,function(t){return.9*t},function(t){return 1-Math.pow(t,1.5)})}Ov.size={xxs:2,xs:5,s:10,m:15,l:20,xl:30,xxl:40,xxxl:50};var Fv="";"undefined"!=typeof navigator&&(Fv=navigator.platform||"");var Bv="rgba(0, 0, 0, 0.2)",Vv=Ov.color.theme[0],jv=el(Vv,0,null,.9),qv={darkMode:"auto",colorBy:"series",color:Ov.color.theme,gradientColor:[jv,Vv],aria:{decal:{decals:[{color:Bv,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:Bv,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:Bv,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:Bv,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:Bv,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:Bv,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:Fv.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},Wv=Do(["tooltip","label","itemName","itemId","itemGroupId","itemChildGroupId","seriesName"]),Uv="original",Gv="arrayRows",Xv="objectRows",Yv="keyedColumns",Zv="typedArray",Kv="unknown",Qv="column",Jv="row",t_=1,e_=2,n_=3,i_=Pd();function r_(t,e,n){var i={},r=o_(e);if(!r||!t)return i;var o,a,s=[],l=[],c=e.ecModel,d=i_(c).datasetMap,u=r.uid+"_"+n.seriesLayoutBy;Jr(t=t.slice(),function(e,n){var r=ho(e)?e:t[n]={name:e};"ordinal"===r.type&&null==o&&(o=n,a=f(r)),i[r.name]=[]});var h=d.get(u)||d.set(u,{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(d=d||n,!d||!d.length)return;var u=d[l];r&&(c[r]=u);return s.paletteIdx=(l+1)%d.length,u}(this,l_,i,r,t,e,n)},t.prototype.clearColorPalette=function(){!function(t,e){e(t).paletteIdx=0,e(t).paletteNameMap={}}(this,l_)},t}();var p_="\0_ec_inner",f_=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e.prototype.init=function(t,e,n,i,r,o){i=i||{},this.option=null,this._theme=new vm(i),this._locale=new vm(r),this._optionManager=o},e.prototype.setOption=function(t,e,n){var i=v_(e);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,e){return this._resetOption(t,v_(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)):u_(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&&Jr(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=Do(),s=e&&e.replaceMergeMainTypeMap;i_(this).datasetMap=Do(),Jr(t,function(t,e){null!=t&&(Nv.hasClass(e)?e&&(o.push(e),a.set(e,!0)):n[e]=null==n[e]?Ur(t):Gr(n[e],t,!0))}),s&&s.each(function(t,e){Nv.hasClass(e)&&!a.get(e)&&(o.push(e),a.set(e,!0))}),Nv.topologicalTravel(o,Nv.getAllClassMainTypes(),function(e){var o=function(t,e,n){var i=s_.get(e);if(!i)return n;var r=i(t);return r?n.concat(r):n}(this,e,_d(t[e])),a=i.get(e),l=a?s&&s.get(e)?"replaceMerge":"normalMerge":"replaceAll",c=Sd(a,o,l);(function(t,e,n){Jr(t,function(t){var i=t.newOption;ho(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,Nv),n[e]=null,i.set(e,null),r.set(e,0);var d,u=[],h=[],p=0;Jr(c,function(t,n){var i=t.existing,r=t.newOption;if(r){var o="series"===e,a=Nv.getClass(e,t.keyInfo.subType,!o);if(!a)return;if("tooltip"===e){if(d)return;d=!0}if(i&&i.constructor===a)i.name=t.keyInfo.name,i.mergeOption(r,this),i.optionUpdated(r,!1);else{var s=Xr({componentIndex:n},t.keyInfo);Xr(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?(u.push(i.option),h.push(i),p++):(u.push(void 0),h.push(void 0))},this),n[e]=u,i.set(e,h),r.set(e,p),"series"===e&&c_(this)},this),this._seriesIndices||c_(this)},e.prototype.getOption=function(){var t=Ur(this.option);return Jr(t,function(e,n){if(Nv.hasClass(n)){for(var i=_d(e),r=i.length,o=!1,a=r-1;a>=0;a--)i[a]&&!Ad(i[a])?o=!0:(i[a]=null,!o&&r--);i.length=r,t[n]=i}}),delete t[p_],t},e.prototype.setTheme=function(t){this._theme=new vm(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 S_=Jr,C_=ho,k_=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function M_(t){var e=t&&t.itemStyle;if(e)for(var n=0,i=k_.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 gy(this.getData(e),t)},t.prototype.formatTooltip=function(t,e,n){},t}();function _y(t){var e,n;return ho(t)?t.type&&(n=t):e=t,{text:e,frag:n}}function yy(t){return new by(t)}var by=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=d(this._modBy),s=this._modDataCount||0,l=d(t&&t.modBy),c=t&&t.modDataCount||0;function d(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 u=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!=u?this._dueIndex+u: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}(),Cy=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 wy(t,e)},t}();function ky(t){if(!Dy(t.sourceFormat)){gd("")}return t.data}function My(t){var e=t.sourceFormat,n=t.data;if(!Dy(e)){gd("")}if(e===Gv){for(var i=[],r=0,o=n.length;r65535?Ry:Ny}function Fy(){return[1/0,-1/0]}function By(t){var e=t.constructor;return e===Array?t.slice():new e(t)}function Vy(t,e,n,i,r){var o=$y[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=to(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&&y<=d||isNaN(y))&&(a[s++]=p),p++}h=!0}else if(2===r){f=u[i[0]];var m=u[i[1]],v=t[i[1]][0],_=t[i[1]][1];for(g=0;g=c&&y<=d||isNaN(y))&&(b>=v&&b<=_||isNaN(b))&&(a[s++]=p),p++}h=!0}}if(!h)if(1===r)for(g=0;g=c&&y<=d||isNaN(y))&&(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),d=this.getRawIndex(0),u=new(Hy(this._rawCount))(Math.min(2*(Math.ceil(s/c)+2),s));u[l++]=d;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(d),_=this.getRawIndex(h);dc-p&&(s=c-p,a.length=s);for(var f=0;fd[1]&&(d[1]=m),u[h++]=v}return r._count=h,r._indices=u,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 wy(t[i],this._dimensions[i])}Ly={arrayRows:t,objectRows:function(t,e,n,i){return wy(t[e],this._dimensions[i])},keyedColumns:t,original:function(t,e,n,i){var r=t&&(null==t.value?t:t.value);return wy(r instanceof Array?r[i]:r,this._dimensions[i])},typedArray:function(t,e,n,i){return t[i]}}}(),t}(),qy=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(Wy(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=fo(a=o.get("data",!0))?Zv:Uv,e=[];var d=this._getSourceMetaRawOption()||{},u=l&&l.metaRawOption||{},h=yo(d.seriesLayoutBy,u.seriesLayoutBy)||null,p=yo(d.sourceHeader,u.sourceHeader),f=yo(d.dimensions,u.dimensions);t=h!==u.seriesLayoutBy||!!p!=!!u.sourceHeader||f?[K_(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=[K_(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&&Uy("")}var o,a=[],s=[];return Jr(t,function(t){t.prepareSource();var e=t.getSource(r||0);null==r||e||Uy(""),a.push(e),s.push(t._getVersionSign())}),i?e=function(t,e){var n=_d(t),i=n.length;i||gd("");for(var r=0,o=i;r1||n>0&&!t.noHeader;return Jr(t.blocks,function(t){var n=tb(t);n>=e&&(e=n+ +(i&&(!n||Qy(t)&&!t.noHeader)))}),e}return 0}function eb(t,e,n,i){var r,o=e.noHeader,a=(r=tb(e),{html:Yy[r],richText:Zy[r]}),s=[],l=e.blocks||[];So(!l||ao(l)),l=l||[];var c=t.orderMode;if(e.sortBlocks&&c){l=l.slice();var d={valueAsc:"asc",valueDesc:"desc"};if(Eo(d,c)){var u=new Sy(d[c],null);l.sort(function(t,e){return u.evaluate(t.sortParam,e.sortParam)})}else"seriesDesc"===c&&l.reverse()}Jr(l,function(n,r){var o=e.valueFormatter,l=Jy(n)(o?Xr(Xr({},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):rb(i,s.join(""),o?n:a.html);if(o)return h;var p=cv(e.header,"ordinal",t.useUTC),f=Xy(i,t.renderMode).nameStyle,g=Gy(i);return"richText"===t.renderMode?ob(t,p,f)+a.richText+h:rb(i,'
'+aa(p)+"
"+h,n)}function nb(t,e,n,i){var r=t.renderMode,o=e.noName,a=e.noValue,s=!e.markerType,l=e.name,c=t.useUTC,d=e.valueFormatter||t.valueFormatter||function(t){return to(t=ao(t)?t:[t],function(t,e){return cv(t,ao(p)?p[e]:p,c)})};if(!o||!a){var u=s?"":t.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||Ov.color.secondary,r),h=o?"":cv(l,"ordinal",c),p=e.valueType,f=a?[]:d(e.value,e.dataIndex),g=!s||!o,m=!s&&o,v=Xy(i,r),_=v.nameStyle,y=v.valueStyle;return"richText"===r?(s?"":u)+(o?"":ob(t,h,_))+(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(ao(e)?e.join(" "):e,o)}(t,f,g,m,y)):rb(i,(s?"":u)+(o?"":function(t,e,n){return''+aa(t)+""}(h,!s,_))+(a?"":function(t,e,n,i){var r=n?"10px":"20px",o=e?"float:right;margin-left:"+r:"";return t=ao(t)?t:[t],''+to(t,function(t){return aa(t)}).join("  ")+""}(f,g,m,y)),n)}}function ib(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 rb(t,e,n){return'
'+e+'
'}function ob(t,e,n){return t.markupStyleCreator.wrapRichTextStyle(e,n)}function ab(t,e){var n=t.get("padding");return null!=n?n:"richText"===e?[8,10]:10}var sb=function(){function t(){this.richTextStyles={},this._nextStyleNameId=dd()}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=lo(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 lo(r)?r:(this.richTextStyles[i]=r.style,r.content)},t.prototype.wrapRichTextStyle=function(t,e){var n={};ao(e)?Jr(e,function(t){return Xr(n,t)}):Xr(n,e);var i=this._generateStyleName();return this.richTextStyles[i]=n,"{"+i+"|"+t+"}"},t}();function lb(t){var e,n,i,r,o=t.series,a=t.dataIndex,s=t.multipleSeries,l=o.getData(),c=l.mapDimensionsAll("defaultedTooltip"),d=c.length,u=o.getRawValue(a),h=ao(u),p=function(t,e){return pv(t.getData().getItemVisual(e,"style")[t.visualDrawType])}(o,a);if(d>1||h&&!d){var f=function(t,e,n,i,r){var o=e.getData(),a=eo(t,function(t,e,n){var i=o.getDimensionInfo(n);return t||i&&!1!==i.tooltip&&null!=i.displayName},!1),s=[],l=[],c=[];function d(t,e){var n=o.getDimensionInfo(e);n&&!1!==n.otherDims.tooltip&&(a?c.push(Ky("nameValue",{markerType:"subItem",markerColor:r,name:n.displayName,value:t,valueType:n.type})):(s.push(t),l.push(n.type)))}return i.length?Jr(i,function(t){d(gy(o,n,t),t)}):Jr(t,d),{inlineValues:s,inlineValueTypes:l,blocks:c}}(u,o,a,c,p);e=f.inlineValues,n=f.inlineValueTypes,i=f.blocks,r=f.inlineValues[0]}else if(d){var g=l.getDimensionInfo(c[0]);r=e=gy(l,a,c[0]),n=g.type}else r=e=h?u[0]:u;var m=Td(o),v=m&&o.name||"",_=l.getName(a),y=s?v:_;return Ky("section",{header:v,noHeader:s||!m,sortParam:r,blocks:[Ky("nameValue",{markerType:"item",markerColor:p,name:y,noName:!Co(y),value:e,valueType:n,dataIndex:a})].concat(i||[])})}var cb=Pd();function db(t,e){return t.getName(e)||t.getId(e)}var ub=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._selectedDataIndicesMap={},e}var n;return v(e,t),e.prototype.init=function(t,e,n){this.seriesIndex=this.componentIndex,this.dataTask=yy({count:pb,reset:fb}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),(cb(this).sourceManager=new qy(this)).prepareSource();var i=this.getInitialData(t,n);mb(i,this),this.dataTask.context.data=i,cb(this).dataBeforeProcessed=i,hb(this),this._initSelectedMapFromData(i)},e.prototype.mergeDefaultAndTheme=function(t,e){var n=Dv(this),i=n?Ev(t):{},r=this.subType;Nv.hasClass(r)&&(r+="Series"),Gr(t,e.getTheme().get(this.subType)),Gr(t,this.getDefaultOption()),yd(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&Lv(t,i,n)},e.prototype.mergeOption=function(t,e){t=Gr(this.option,t,!0),this.fillDataTextStyle(t.data);var n=Dv(this);n&&Lv(this.option,t,n);var i=cb(this).sourceManager;i.dirty(),i.prepareSource();var r=this.getInitialData(t,e);mb(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,cb(this).dataBeforeProcessed=r,hb(this),this._initSelectedMapFromData(r)},e.prototype.fillDataTextStyle=function(t){if(t&&!fo(t))for(var e=["show"],n=0;n=0&&d<0)&&(c=o,d=r,u=0),r===d&&(l[u++]=e))}),l.length=u,l},e.prototype.formatTooltip=function(t,e,n){return lb({series:this,dataIndex:t,multipleSeries:e})},e.prototype.isAnimationEnabled=function(){var t=this.ecModel;if(kr.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=h_.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[db(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){ho(r.selectedMap)||(r.selectedMap={});for(var s=r.selectedMap,l=0;l0&&this._innerSelect(t,e)}},e.registerClass=function(t){return Nv.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}(Nv);function hb(t){var e=t.name;Td(t)||(t.name=function(t){var e=t.getRawData(),n=e.mapDimensionsAll("seriesName"),i=[];return Jr(n,function(t){var n=e.getDimensionInfo(t);n.displayName&&i.push(n.displayName)}),i.join(" ")}(t)||e)}function pb(t){return t.model.getRawData().count()}function fb(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),gb}function gb(t,e){e.outputData&&t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function mb(t,e){Jr(function(t,e){for(var n=new t.constructor(t.length+e.length),i=0;i=0?u():d=setTimeout(u,-r),l=i};return h.clear=function(){d&&(clearTimeout(d),d=null)},h.debounceNextCall=function(t){s=t},h}function Eb(t,e,n,i){var r=t[e];if(r){var o=r[Ib]||r,a=r[Db];if(r[Pb]!==n||a!==i){if(null==n||!i)return t[e]=o;(r=t[e]=Lb(o,n,"debounce"===i))[Ib]=o,r[Db]=i,r[Pb]=n}return r}}function Rb(t,e){var n=t[e];n&&n[Ib]&&(n.clear&&n.clear(),t[e]=n[Ib])}var Nb=Pd(),Ob={itemStyle:Ud(fm,!0),lineStyle:Ud(um,!0)},zb={lineStyle:"stroke",itemStyle:"fill"};function $b(t,e){var n=t.visualStyleMapper||Ob[e];return n||(console.warn("Unknown style type '"+e+"'."),Ob.itemStyle)}function Hb(t,e){var n=t.visualDrawType||zb[e];return n||(console.warn("Unknown style type '"+e+"'."),"fill")}var Fb={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=t.getModel(i),o=$b(t,i)(r),a=r.getShallow("decal");a&&(n.setVisual("decal",a),a.dirty=!0);var s=Hb(t,i),l=o[s],c=so(l)?l:null,d="auto"===o.fill||"auto"===o.stroke;if(!o[s]||c||d){var u=t.getColorFromPalette(t.name,null,e.getSeriesCount());o[s]||(o[s]=u,n.setVisual("colorFromPalette",!0)),o.fill="auto"===o.fill||so(o.fill)?u:o.fill,o.stroke="auto"===o.stroke||so(o.stroke)?u: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=Xr({},o);r[s]=c(i),e.setItemVisual(n,"style",r)}}}},Bb=new vm,Vb={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){if(!t.ignoreStyleOnData&&!e.isSeriesFiltered(t)){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=$b(t,i),o=n.getVisual("drawType");return{dataEach:n.hasItemOption?function(t,e){var n=t.getRawDataItem(e);if(n&&n[i]){Bb.option=n[i];var a=r(Bb);Xr(t.ensureUniqueItemVisual(e,"style"),a),Bb.option.decal&&(t.setItemVisual(e,"decal",Bb.option.decal),Bb.option.decal.dirty=!0),o in a&&t.setItemVisual(e,"colorFromPalette",!1)}}:null}}}},jb={performRawSeries:!0,overallReset:function(t){var e=Do();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)),Nb(t).scope=r}}),t.eachSeries(function(e){if(!e.isColorBySeries()&&!t.isSeriesFiltered(e)){var n=e.getRawData(),i={},r=e.getData(),o=Nb(e).scope,a=e.visualStyleAccessPath||"itemStyle",s=Hb(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+"",d=n.count();l[s]=e.getColorFromPalette(c,o,d)}})}})}},qb=Math.PI;var Wb=function(){function t(t,e,n,i){this._stageTaskMap=Do(),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=Do();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;Jr(this._allHandlers,function(i){var r=t.get(i.uid)||t.set(i.uid,{});So(!(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))}Jr(t,function(t,s){if(!i.visualType||i.visualType===t.visualType){var l=o._stageTaskMap.get(t.uid),c=l.seriesTaskMap,d=l.overallTask;if(d){var u,h=d.agentStubMap;h.each(function(t){a(i,t)&&(t.dirty(),u=!0)}),u&&d.dirty(),o.updatePayload(d,n);var p=o.getPerformArgs(d,i.block);h.each(function(t){t.perform(p)}),d.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=Do(),s=t.seriesType,l=t.getTargetSeries;function c(e){var s=e.uid,l=a.set(s,o&&o.get(s)||yy({plan:Zb,reset:Kb,count:tx}));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||yy({reset:Ub});o.context={ecModel:n,api:i,overallReset:t.overallReset,scheduler:r};var a=o.agentStubMap,s=o.agentStubMap=Do(),l=t.seriesType,c=t.getTargetSeries,d=!0,u=!1;function h(t){var e=t.uid,n=s.set(e,a&&a.get(e)||(u=!0,yy({reset:Gb,onDirty:Yb})));n.context={model:t,overallProgress:d},n.agent=o,n.__block=d,r._pipe(t,n)}So(!t.createOnAllSeries,""),l?n.eachRawSeriesByType(l,h):c?c(n,i).each(h):(d=!1,Jr(n.getSeries(),h)),u&&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 so(t)&&(t={overallReset:t,seriesType:ex(t)}),t.uid=ym("stageHandler"),e&&(t.visualType=e),t},t}();function Ub(t){t.overallReset(t.ecModel,t.api,t.payload)}function Gb(t){return t.overallProgress&&Xb}function Xb(){this.agent.dirty(),this.getDownstream().dirty()}function Yb(){this.agent&&this.agent.dirty()}function Zb(t){return t.plan?t.plan(t.model,t.ecModel,t.api,t.payload):null}function Kb(t){t.useClearVisual&&t.data.clearAllVisual();var e=t.resetDefines=_d(t.reset(t.model,t.ecModel,t.api,t.payload));return e.length>1?to(e,function(t,e){return Jb(e)}):Qb}var Qb=Jb(0);function Jb(t){return function(e,n){var i=n.data,r=n.resetDefines[t];if(r&&r.dataEach)for(var o=e.start;o0&&d===r.length-c.length){var u=r.slice(0,d);"data"!==u&&(e.mainType=u,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}(),px=["symbol","symbolSize","symbolRotate","symbolOffset"],fx=px.concat(["symbolKeepAspect"]),gx={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&&Ex(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=Ex(i)?i:0,r=Ex(r)?r:1,o=Ex(o)?o:0,a=Ex(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]:uo(e)?[e]:ao(e)?e:null:null),o=i.lineDashOffset;if(r){var a=i.strokeNoScale&&t.getLineScale?t.getLineScale():1;a&&1!==a&&(r=to(r,function(t){return t/a}),o/=a)}return[r,o]}var $x=new ih(!0);function Hx(t){var e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))}function Fx(t){return"string"==typeof t&&"none"!==t}function Bx(t){var e=t.fill;return null!=e&&"none"!==e}function Vx(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 jx(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 qx(t,e,n){var i=Kd(e.image,e.__image,n);if(Jd(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)*No),o.scaleSelf(e.scaleX||1,e.scaleY||1),r.setTransform(o)}return r}}var Wx=["shadowBlur","shadowOffsetX","shadowOffsetY"],Ux=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function Gx(t,e,n,i,r){var o=!1;if(!i&&e===(n=n||{}))return!1;if(i||e.opacity!==n.opacity){Zx(t,r),o=!0;var a=Math.max(Math.min(e.opacity,1),0);t.globalAlpha=isNaN(a)?yu.opacity:a}(i||e.blend!==n.blend)&&(o||(Zx(t,r),o=!0),t.globalCompositeOperation=e.blend||yu.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[uw])if(this._disposed)this.id;else{var i,r,o;if(ho(e)&&(n=e.lazyUpdate,i=e.silent,r=e.replaceMerge,o=e.transition,e=e.notMerge),this[uw]=!0,$w(this),!this._model||e){var a=new x_(this._api),s=this._theme,l=this._model=new f_;l.scheduler=this._scheduler,l.ssr=this._ssr,l.init(null,null,null,s,this._locale,a)}this._model.setOption(t,{replaceMerge:r},Xw);var c={seriesTransition:o,optionChanged:!0};if(n)this[pw]={silent:i,updateParams:c},this[uw]=!1,this.getZr().wakeUp();else{try{bw(this),Sw.update.call(this,null,c)}catch(t){throw this[pw]=null,this[uw]=!1,t}this._ssr||this._zr.flush(),this[pw]=null,this[uw]=!1,Tw.call(this,i),Aw.call(this,i)}}},e.prototype.setTheme=function(t,e){if(!this[uw])if(this._disposed)this.id;else{var n=this._model;if(n){var i=e&&e.silent,r=null;this[pw]&&(null==i&&(i=this[pw].silent),r=this[pw].updateParams,this[pw]=null),this[uw]=!0,$w(this);try{this._updateTheme(t),n.setTheme(this._theme),bw(this),Sw.update.call(this,{type:"setTheme"},r)}catch(t){throw this[uw]=!1,t}this[uw]=!1,Tw.call(this,i),Aw.call(this,i)}}},e.prototype._updateTheme=function(t){lo(t)&&(t=Zw[t]),t&&((t=Ur(t))&&V_(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||kr.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 Jr(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;Jr(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 Jr(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(Jw[n]){var a=o,s=o,l=-1/0,c=-1/0,d=[],u=t&&t.pixelRatio||this.getDevicePixelRatio();Jr(Qw,function(o,u){if(o.group===n){var h=e?o.getZr().painter.getSvgDom().innerHTML:o.renderToCanvas(Ur(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),d.push({dom:h,left:p.left,top:p.top})}});var h=(l*=u)-(a*=u),p=(c*=u)-(s*=u),f=Dr.createCanvas(),g=Uc(f,{renderer:e?"svg":"canvas"});if(g.resize({width:h,height:p}),e){var m="";return Jr(d,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 Oh({shape:{x:0,y:0,width:h,height:p},style:{fill:t.connectedBackgroundColor}})),Jr(d,function(t){var e=new Ih({style:{x:t.left*u-a,y:t.top*u-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 Cw(this,"convertToPixel",t,e,n)},e.prototype.convertToLayout=function(t,e,n){return Cw(this,"convertToLayout",t,e,n)},e.prototype.convertFromPixel=function(t,e,n){return Cw(this,"convertFromPixel",t,e,n)},e.prototype.containPixel=function(t,e){var n;if(!this._disposed)return Jr(Ld(this._model,t),function(t,i){i.indexOf("Models")>=0&&Jr(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=Ld(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;Jr(jw,function(e){var n=function(n){var i,r=t.getModel(),o=n.target;if("globalout"===e?i={}:o&&_x(o,function(t){var e=Jh(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=Xr({},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;Jr(Uw,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?(vx("map","selectchanged",e,i,t),vx("pie","selectchanged",e,i,t)):"select"===t.fromAction?(vx("map","selected",e,i,t),vx("pie","selected",e,i,t)):"unselect"===t.fromAction&&(vx("map","unselected",e,i,t),vx("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()&&Od(this.getDom(),eS,"");var t=this,e=t._api,n=t._model;Jr(t._componentsViews,function(t){t.dispose(n,e)}),Jr(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 Qw[t.id]}},e.prototype.resize=function(t){if(!this[uw])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[pw]&&(null==i&&(i=this[pw].silent),n=!0,this[pw]=null),this[uw]=!0,$w(this);try{n&&bw(this),Sw.update.call(this,{type:"resize",animation:Xr({duration:0},t&&t.animation)})}catch(t){throw this[uw]=!1,t}this[uw]=!1,Tw.call(this,i),Aw.call(this,i)}}},e.prototype.showLoading=function(t,e){if(this._disposed)this.id;else if(ho(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),Kw[t]){var n=Kw[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=Xr({},t);return e.type=Ww[t.type],e},e.prototype.dispatchAction=function(t,e){if(this._disposed)this.id;else if(ho(e)||(e={silent:!!e}),qw[t.type]&&this._model)if(this[uw])this._pendingActions.push(t);else{var n=e.silent;Mw.call(this,t,n);var i=e.flush;i?this._zr.flush():!1!==i&&kr.browser.weChat&&this._throttledZrFlush(),Tw.call(this,n),Aw.call(this,n)}},e.prototype.updateLabelLayout=function(){aw.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(hg(t))return;if(t instanceof Ch&&function(t){var e=np(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)}})}bw=function(t){var e=t._scheduler;e.restorePipelines(t._model),e.prepareStageTasks(),xw(t,!0),xw(t,!1),e.plan()},xw=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")&&!kr.node&&!kr.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),aw.trigger("series:afterupdate",e,o,s)},Ow=function(t){t[fw]=!0,t.getZr().wakeUp()},$w=function(t){t[hw]=(t[hw]+1)%1e3},zw=function(t){t[fw]&&(t.getZr().storage.traverse(function(t){hg(t)||e(t)}),t[fw]=!1)},Rw=function(t){return new(function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return v(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){Tp(e,n),Ow(t)},n.prototype.leaveEmphasis=function(e,n){Ap(e,n),Ow(t)},n.prototype.enterBlur=function(e){!function(t){xp(t,mp)}(e),Ow(t)},n.prototype.leaveBlur=function(e){Ip(e),Ow(t)},n.prototype.enterSelect=function(e){Pp(e),Ow(t)},n.prototype.leaveSelect=function(e){Dp(e),Ow(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[hw]},n}(y_))(t)},Nw=function(t){function e(t,e){for(var n=0;n=0)){cS.push(n);var o=Wb.wrapStageHandler(n,r);o.__prio=e,o.__raw=n,t.push(o)}}function uS(t,e){Kw[t]=e}var hS=function(t){var e=(t=Ur(t)).type;e||gd("");var n=e.split(":");2!==n.length&&gd("");var i=!1;"echarts"===n[0]&&(e=n[1],i=!0),t.__isBuiltIn=i,Iy.set(e,t)};function pS(t,e,n,i){return{eventContent:{selected:$p(n),isFromClick:e.isFromClick||!1}}}function fS(t){return null==t?0:t.length||1}function gS(t){return t}lS(lw,Fb),lS(cw,Vb),lS(cw,jb),lS(lw,gx),lS(cw,mx),lS(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=nw(n,e))});var r=i.getVisual("decal");if(r)i.getVisual("style").decal=nw(r,e)}})}),rS(V_),oS(900,function(t){var e=Do();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(),Jr(t,function(e,n){e.data.setCalculationInfo("stackedOnSeries",n>0?t[n-1].seriesModel:null)}),function(t){Jr(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,d){var u,h,p=a.get(e.stackedDimension,d);if(isNaN(p))return r;s?h=a.getRawIndex(d):u=a.get(e.stackedByDimension,d);for(var f=NaN,g=n-1;g>=0;g--){var m=t[g];if(s||(h=m.data.rawIndexOf(m.stackedByDimension,u)),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=nd(p,v),f=v;break}}}return i[0]=p,i[1]=f,i})})}(t))})}),uS("default",function(t,e){Yr(e=e||{},{text:"loading",textColor:Ov.color.primary,fontSize:12,fontWeight:"normal",fontStyle:"normal",fontFamily:"sans-serif",maskColor:"rgba(255,255,255,0.8)",showSpinner:!0,color:Ov.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new Bc,i=new Oh({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});n.add(i);var r,o=new Fh({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 Oh({style:{fill:"none"},textContent:o,textConfig:{position:"right",distance:10},zlevel:e.zlevel,z:10001});return n.add(a),e.showSpinner&&((r=new Uf({shape:{startAngle:-qb/2,endAngle:-qb/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*qb/2}).start("circularInOut"),r.animateShape(!0).when(1e3,{startAngle:3*qb/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}),sS({type:ap,event:ap,update:ap},Ro),sS({type:sp,event:sp,update:sp},Ro),sS({type:lp,event:up,update:lp,action:Ro,refineEvent:pS,publishNonRefinedEvent:!0}),sS({type:cp,event:up,update:cp,action:Ro,refineEvent:pS,publishNonRefinedEvent:!0}),sS({type:dp,event:up,update:dp,action:Ro,refineEvent:pS,publishNonRefinedEvent:!0}),iS("default",{}),iS("dark",ux);var mS=function(){function t(t,e,n,i,r,o){this._old=t,this._new=e,this._oldKeyGetter=n||gS,this._newKeyGetter=i||gS,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===u)this._updateManyToOne&&this._updateManyToOne(c,l),i[s]=null;else if(1===d&&u>1)this._updateOneToMany&&this._updateOneToMany(c,l),i[s]=null;else if(1===d&&1===u)this._update&&this._update(c,l),i[s]=null;else if(d>1&&u>1)this._updateManyToMany&&this._updateManyToMany(c,l),i[s]=null;else if(d>1)for(var h=0;h1)for(var a=0;a30}var TS,AS,IS,PS,DS,LS,ES,RS=ho,NS=to,OS="undefined"==typeof Int32Array?Array:Int32Array,zS=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],$S=["_approximateExtent"],HS=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;SS(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===Uv&&!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&&(ao(r=this.getVisual(e))?r=r.slice():RS(r)&&(r=Xr({},r)),i[e]=r),r},t.prototype.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{};this._itemVisuals[t]=i,RS(e)?Xr(i,e):i[e]=n},t.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},t.prototype.setLayout=function(t,e){RS(t)?Xr(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?Xr(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=Jh(i);r.dataIndex=n,r.dataType=e,r.seriesIndex=t,r.ssrType="chart","group"===i.type&&i.traverse(function(i){var r=Jh(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){Jr(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:NS(this.dimensions,this._getDimInfo,this),this.hostModel)),DS(e,this),e._store=this._store,e},t.prototype.wrapMethod=function(t,e){var n=this[t];so(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(t),this[t]=function(){var t=n.apply(this,arguments);return e.apply(this,[t].concat(xo(arguments)))})},t.internalField=(TS=function(t){var e=t._invertedIndicesMap;Jr(e,function(n,i){var r=t._dimInfos[i],o=r.ordinalMeta,a=t._store;if(o){n=e[i]=new OS(o.categories.length);for(var s=0;s1&&(s+="__ec__"+c),i[e]=s}})),t}();function FS(t,e){Z_(t)||(t=Q_(t));var n=(e=e||{}).coordDimensions||[],i=e.dimensionsDefine||t.dimensionsDefine||[],r=Do(),o=[],a=function(t,e,n,i){var r=Math.max(t.dimensionsDetectedCount||1,e.length,n.length,i||0);return Jr(e,function(t){var e;ho(t)&&(e=t.dimsDef)&&(r=Math.max(r,e.length))}),r}(t,n,i,e.dimensionsCount),s=e.canOmitUnusedDimensions&&MS(a),l=i===t.dimensionsDefine,c=l?kS(t):CS(i),d=e.encodeDefine;!d&&e.encodeDefaulter&&(d=e.encodeDefaulter(t,a));for(var u=Do(d),h=new Oy(a),p=0;p0&&(i.name=r+(o-1)),o++,e.set(r,o)}}(o),new wS({source:t,dimensions:o,fullDimensionCount:a,dimensionOmitted:s})}function BS(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 VS=function(t){this.coordSysDims=[],this.axisMap=Do(),this.categoryAxisMap=Do(),this.coordSysName=t};var jS={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis",Rd).models[0],o=t.getReferringComponents("yAxis",Rd).models[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",o),qS(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),qS(o)&&(i.set("y",o),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis",Rd).models[0];e.coordSysDims=["single"],n.set("single",r),qS(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar",Rd).models[0],o=r.findAxisModel("radiusAxis"),a=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",o),n.set("angle",a),qS(o)&&(i.set("radius",o),e.firstCategoryDimIndex=0),qS(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();Jr(o.parallelAxisIndex,function(t,o){var s=r.getComponent("parallelAxis",t),l=a[o];n.set(l,s),qS(s)&&(i.set(l,s),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=o))})},matrix:function(t,e,n,i){var r=t.getReferringComponents("matrix",Rd).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 qS(t){return"category"===t.get("type")}function WS(t,e,n){var i,r,o,a=(n=n||{}).byIndex,s=n.stackedCoordDimension;!function(t){return!SS(t.schema)}(e)?(r=e.schema,i=r.dimensions,o=e.store):i=e;var l,c,d,u,h=!(!t||!t.get("stack"));if(Jr(i,function(t,e){lo(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){d="__\0ecstackresult_"+t.id,u="__\0ecstackedover_"+t.id,l&&(l.createInvertedIndices=!0);var p=c.coordDim,f=c.type,g=0;Jr(i,function(t){t.coordDim===p&&g++});var m={name:d,coordDim:p,coordDimIndex:g,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length},v={name:u,coordDim:u,coordDimIndex:g+1,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length+1};r?(o&&(m.storeDimIndex=o.ensureCalculationDimension(u,f),v.storeDimIndex=o.ensureCalculationDimension(d,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:u,stackResultDimension:d}}function US(t,e){return!!e&&e===t.getCalculationInfo("stackedDimension")}function GS(t,e,n){n=n||{};var i,r,o=e.getSourceManager();r=(i=o.getSource()).sourceFormat===Uv;var a=function(t){var e=t.get("coordinateSystem"),n=new VS(e),i=jS[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}(e),s=function(t,e){var n,i=t.get("coordinateSystem"),r=mv.get(i);return e&&e.coordSysDims&&(n=to(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=so(l)?l:l?oo(r_,s,e):null,d=FS(i,{coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:e.getEncode(),encodeDefaulter:c,canOmitUnusedDimensions:!r}),u=function(t,e,n){var i,r;return n&&Jr(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}(d.dimensions,n.createInvertedIndices,a),h=r?null:o.getSharedDataStore(d),p=WS(e,{schema:d,store:h}),f=new HS(d,e);f.setCalculationInfo(p);var g=null!=u&&function(t){if(t.sourceFormat===Uv){var e=function(t){var e=0;for(;er&&(a=o.interval=r);var s=o.intervalPrecision=KS(a);return function(t,e){!isFinite(t[0])&&(t[0]=e[0]),!isFinite(t[1])&&(t[1]=e[1]),QS(t,0,e),QS(t,1,e),t[0]>t[1]&&(t[0]=t[1])}(o.niceTickExtent=[td(Math.ceil(t[0]/a)*a,s),td(Math.floor(t[1]/a)*a,s)],t),o}function ZS(t){var e=Math.pow(10,sd(t)),n=t/e;return n?2===n?n=3:3===n?n=5:n*=2:n=1,td(n*e)}function KS(t){return ed(t)+2}function QS(t,e,n){t[e]=Math.max(Math.min(t[e],n[1]),n[0])}function JS(t,e){return t>=e[0]&&t<=e[1]}var tC=function(){function t(){this.normalize=eC,this.scale=nC}return t.prototype.updateMethods=function(t){t.hasBreaks()?(this.normalize=ro(t.normalize,t),this.scale=ro(t.scale,t)):(this.normalize=eC,this.scale=nC)},t}();function eC(t,e){return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])}function nC(t,e){return t*(e[1]-e[0])+e[0]}function iC(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 rC=function(){function t(t){this._calculator=new tC,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}();Wd(rC);var oC=0,aC=function(){function t(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this.uid=++oC,this._onCollect=t.onCollect}return t.createByAxisModel=function(e){var n=e.option,i=n.data,r=i&&to(i,sC);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(!lo(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=Do(this.categories))},t}();function sC(t){return ho(t)&&null!=t.value?t.value:t+""}var lC=function(t){function e(e){var n=t.call(this,e)||this;n.type="ordinal";var i=n.getSetting("ordinalMeta");return i||(i=new aC({})),ao(i)&&(i=new aC({categories:to(i,function(t){return ho(t)?t.value:t})})),n._ordinalMeta=i,n._extent=n.getSetting("extent")||[0,i.categories.length-1],n}return v(e,t),e.prototype.parse=function(t){return null==t?NaN:lo(t)?this._ordinalMeta.getOrdinal(t):Math.round(t)},e.prototype.contain=function(t){return JS(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}(rC);rC.registerClass(lC);var cC=td,dC=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 v(e,t),e.prototype.parse=function(t){return null==t||""===t?NaN:Number(t)},e.prototype.contain=function(t){return JS(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=KS(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=cC(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:cC(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]&&u0&&(o=null===o?s:Math.min(o,s))}n[i]=o}}return n}(t),n=[];return Jr(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(),d=Math.abs(c[1]-c[0]);i=s?l/d*s:l}else{var u=t.getData();i=Math.abs(o[1]-o[0])/u.count()}var h=Qc(t.get("barWidth"),i),p=Qc(t.get("barMaxWidth"),i),f=Qc(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:gC(r),stackId:fC(t)})}),function(t){var e={};Jr(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 d=t.barMinWidth;d&&(a[s].minWidth=d);var u=t.barGap;null!=u&&(o.gap=u);var h=t.barCategoryGap;null!=h&&(o.categoryGap=h)});var n={};return Jr(e,function(t,e){n[e]={};var i=t.stacks,r=t.bandWidth,o=t.categoryGap;if(null==o){var a=io(i).length;o=Math.max(35-4*a,15)+"%"}var s=Qc(o,r),l=Qc(t.gap,1),c=t.remainedWidth,d=t.autoWidthCount,u=(c-s)/(d+(d-1)*l);u=Math.max(u,0),Jr(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,d--}else{var i=u;e&&ei&&(i=n),i!==u&&(t.width=i,c-=i+l*i,d--)}}),u=(c-s)/(d+(d-1)*l),u=Math.max(u,0);var h,p=0;Jr(i,function(t,e){t.width||(t.width=u),h=t,p+=t.width*(1+l)}),h&&(p-=h.width*l);var f=-p/2;Jr(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 vC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="time",n}return v(e,t),e.prototype.getLabel=function(t){var e=this.getSetting("useUTC");return jm(t.value,Om[function(t){switch(t){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}(Bm(this._minLevelUnit))]||Om.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(lo(n))o=n;else if(so(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 d=qm(t.value,r);o=n[d][d][0]}}return jm(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=qm(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=$m,l=0;function c(t,e,n,r,s,c,d){for(var u=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,u);f>0&&(p[s](p[r]()+f*t),h=p.getTime())}d.push({value:h,notAdd:!0})}function d(t,r,o){var a=[],s=!r.length;if(!function(t,e,n,i){return Wm(new Date(e),t,i).getTime()===Wm(new Date(n),t,i).getTime()}(Bm(t),i[0],i[1],n)){s&&(r=[{value:CC(i[0],t,n)},{value:i[1]}]);for(var l=0;l=i[0]&&d<=i[1]&&c(h,d,u,p,f,g,a),"year"===t&&o.length>1&&0===l&&o.unshift({value:o[0].value-h})}}for(l=0;l=i[0]&&y<=i[1]&&p++)}var b=r/e;if(p>1.5*b&&f>b/1.5)break;if(u.push(v),p>b||t===s[g])break}h=[]}}var x=no(to(u,function(t){return no(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=_C.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 bC(t){return(t/=2592e6)>6?6:t>3?3:t>2?2:1}function xC(t){return(t/=Pm)>12?12:t>6?6:t>3.5?4:t>2?2:1}function wC(t,e){return(t/=e?Im:Am)>30?30:t>20?20:t>15?15:t>10?10:t>5?5:t>2?2:1}function SC(t){return ld(t)}function CC(t,e,n){var i=Math.max(0,Zr(zm,e)-1);return Wm(new Date(t),zm[i],n).getTime()}rC.registerClass(vC);var kC=td,MC=Math.floor,TC=Math.ceil,AC=Math.pow,IC=Math.log,PC=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="log",e.base=10,e._originalScale=new dC,e}return v(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(),to(r,function(t){var e=t.value,r=null,a=AC(o,e);return e===n[0]&&this._fixMin?r=i[0]:e===n[1]&&this._fixMax&&(r=i[1]),null!=r&&(a=DC(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=iC(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]=AC(e,n[0]),n[1]=AC(e,n[1]);var i=this._originalScale.getExtent();return this._fixMin&&(n[0]=DC(n[0],i[0])),this._fixMax&&(n[1]=DC(n[1],i[1])),n},e.prototype.unionExtentFromData=function(t,e){this._originalScale.unionExtentFromData(t,e);var n=iC(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,sd(i)));for(t/n*r<=.5&&(r*=10);!isNaN(r)&&Math.abs(r)<1&&Math.abs(r)>0;)r*=10;var o=[kC(TC(e[0]/r)*r),kC(MC(e[1]/r)*r)];this._interval=r,this._intervalPrecision=KS(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=IC(e)/IC(this.base),t.prototype.contain.call(this,e)},e.prototype.normalize=function(e){return e=IC(e)/IC(this.base),t.prototype.normalize.call(this,e)},e.prototype.scale=function(e){return e=t.prototype.scale.call(this,e),AC(this.base,e)},e.prototype.setBreaksFromOption=function(t){},e.type="log",e}(dC);function DC(t,e){return kC(t,ed(e))}rC.registerClass(PC);var LC=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 u=this._determinedMin,h=this._determinedMax;return null!=u&&(a=u,l=!0),null!=h&&(s=h,c=!0),{min:a,max:s,minFixed:l,maxFixed:c,isBlank:d}},t.prototype.modifyDataMinMax=function(t,e){this[RC[t]]=e},t.prototype.setDeterminedMinMax=function(t,e){this[EC[t]]=e},t.prototype.freeze=function(){this.frozen=!0},t}(),EC={min:"_determinedMin",max:"_determinedMax"},RC={min:"_dataMin",max:"_dataMax"};function NC(t,e){return null==e?null:vo(e)?NaN:t.parse(e)}function OC(t,e){var n=t.type,i=function(t,e,n){var i=t.rawExtentInfo;return i||(i=new LC(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(Jr(s,function(t){l=l||t.getBaseAxis()===e.axis}),l){var c=mC(s),d=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[gC(e)]}(i,n.axis);if(void 0===a)return{min:t,max:e};var s=1/0;Jr(a,function(t){s=Math.min(t.offset,s)});var l=-1/0;Jr(a,function(t){l=Math.max(t.offset+t.width,l)}),s=Math.abs(s),l=Math.abs(l);var c=s+l,d=e-t,u=d/(1-(s+l)/o)-d;return e+=u*(l/c),t-=u*(s/c),{min:t,max:e}}(r,o,e,c);r=d.min,o=d.max}}return{extent:[r,o],fixMin:i.minFixed,fixMax:i.maxFixed}}function zC(t,e){var n=e,i=OC(t,n),r=i.extent,o=n.get("splitNumber");t instanceof PC&&(t.base=n.get("logBase"));var a=t.type,s=n.get("interval"),l="interval"===a||"time"===a;t.setBreaksFromOption(WC(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 $C(t){var e=t.getLabelModel().get("formatter");if("time"===t.type){var n=Hm(e);return function(e,i){return t.scale.getFormattedLabel(e,i,n)}}if(lo(e))return function(n){var i=t.scale.getLabel(n);return e.replace("{value}",null!=i?i:"")};if(so(e)){if("category"===t.type)return function(n,i){return e(HC(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(HC(t,n),r,o)}}return function(e){return t.scale.getLabel(e)}}function HC(t,e){return"category"===t.type?t.scale.getLabel(e):e.value}function FC(t){var e=t.get("interval");return null==e?"auto":e}function BC(t){return"category"===t.type&&0===FC(t.getLabelModel())}function VC(t,e){var n={};return Jr(t.mapDimensionsAll(e),function(e){n[function(t,e){return US(t,e)?t.getCalculationInfo("stackResultDimension"):e}(t,e)]=!0}),io(n)}function jC(t){return"middle"===t||"center"===t}function qC(t){return t.getShallow("show")}function WC(t){t.get("breaks",!0)}var UC=function(){function t(){}return t.prototype.getNeedCrossZero=function(){return!this.option.scale},t.prototype.getCoordSysModel=function(){},t}(),GC=[],XC={registerPreprocessor:rS,registerProcessor:oS,registerPostInit:function(t){aS("afterinit",t)},registerPostUpdate:function(t){aS("afterupdate",t)},registerUpdateLifecycle:aS,registerAction:sS,registerCoordinateSystem:function(t,e){mv.register(t,e)},registerLayout:function(t,e){dS(Yw,t,e,1e3,"layout")},registerVisual:lS,registerTransform:hS,registerLoading:uS,registerMap:function(t,e,n){var i=sw["registerMap"];i&&i(t,e,n)},registerImpl:function(t,e){sw[t]=e},PRIORITY:dw,ComponentModel:Nv,ComponentView:yb,SeriesModel:ub,ChartView:Sb,registerComponentModel:function(t){Nv.registerClass(t)},registerComponentView:function(t){yb.registerClass(t)},registerSeriesModel:function(t){ub.registerClass(t)},registerChartView:function(t){Sb.registerClass(t)},registerCustomSeries:function(t,e){},registerSubTypeDefaulter:function(t,e){Nv.registerSubTypeDefaulter(t,e)},registerPainter:function(t,e){var n;n=e,Vc[t]=n}};function YC(t){ao(t)?Jr(t,function(t){YC(t)}):Zr(GC,t)>=0||(GC.push(t),so(t)&&(t={install:t}),t.install(XC))}var ZC=Pd(),KC=Pd(),QC=1,JC=2;function tk(t){return{out:{noPxChangeTryDetermine:[]},kind:t}}function ek(t,e){var n=to(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 nk(t,e){var n=t.getLabelModel().get("customValues");if(n){var i=$C(t),r=t.scale.getExtent();return{labels:to(no(ek(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=rk(t,n,e);return!n.get("show")||t.scale.isBlank()?{labels:[]}:i}(t,e):function(t){var e=t.scale.getTicks(),n=$C(t);return{labels:to(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 ik(t,e,n){var i=t.getTickModel().get("customValues");if(i){var r=t.scale.getExtent();return{ticks:no(ek(t,i),function(t){return t>=r[0]&&t<=r[1]})}}return"category"===t.type?function(t,e){var n,i,r=ok(t),o=FC(e),a=lk(r,o);if(a)return a;e.get("show")&&!t.scale.isBlank()||(n=[]);if(so(o))n=pk(t,o,!0);else if("auto"===o){var s=rk(t,t.getLabelModel(),tk(JC));i=s.labelCategoryInterval,n=to(s.labels,function(t){return t.tickValue})}else n=hk(t,i=o,!0);return ck(r,o,{ticks:n,tickCategoryInterval:i})}(t,e):{ticks:to(t.scale.getTicks(n),function(t){return t.value})}}function rk(t,e,n){var i,r,o=ak(t),a=FC(e),s=n.kind===QC;if(!s){var l=lk(o,a);if(l)return l}so(a)?i=pk(t,a):(r="auto"===a?function(t,e){if(e.kind===QC){var n=t.calculateCategoryInterval(e);return e.out.noPxChangeTryDetermine.push(function(){return KC(t).autoInterval=n,!0}),n}var i=KC(t).autoInterval;return null!=i?i:KC(t).autoInterval=t.calculateCategoryInterval(e)}(t,n):a,i=hk(t,r));var c={labels:i,labelCategoryInterval:r};return s?n.out.noPxChangeTryDetermine.push(function(){return ck(o,a,c),!0}):ck(o,a,c),c}var ok=sk("axisTick"),ak=sk("axisLabel");function sk(t){return function(e){return KC(e)[t]||(KC(e)[t]={list:[]})}}function lk(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 hk(t,e,n){var i=$C(t),r=t.scale,o=r.getExtent(),a=t.getLabelModel(),s=[],l=Math.max((e||0)+1,1),c=o[0],d=r.count();0!==c&&l>1&&d/l>2&&(c=Math.round(Math.ceil(c/l)*l));var u=BC(t),h=a.get("showMinLabel")||u,p=a.get("showMaxLabel")||u;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 pk(t,e,n){var i=t.scale,r=$C(t),o=[];return Jr(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 fk=[0,1],gk=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(Zc(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&&mk(n=n.slice(),i.count()),Kc(t,fk,n,e)},t.prototype.coordToData=function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&mk(n=n.slice(),i.count());var r=Kc(t,n,fk,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=to(ik(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;Jr(e,function(t){t.coord-=c/2,t.onBand=!0});var d=t.scale.getExtent();a=1+d[1]-e[r-1].tickValue,o={coord:e[r-1].coord+c*a,tickValue:d[1]+1,onBand:!0},e.push(o)}var u=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=td(t),e=td(e),u?t>e:t0&&t<100||(t=5),to(this.scale.getMinorTicks(t),function(t){return to(t,function(t){return{coord:this.dataToCoord(t),tickValue:t}},this)},this)},t.prototype.getViewLabels=function(t){return nk(this,t=t||tk(JC)).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=$C(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 d=s[0],u=t.dataToCoord(d+1)-t.dataToCoord(d),h=Math.abs(u*Math.cos(o)),p=Math.abs(u*Math.sin(o)),f=0,g=0;d<=s[1];d+=c){var m,v,_=Cc(r({value:d}),i.font,"center","top");m=1.3*_.width,v=1.3*_.height,f=Math.max(f,m,7),g=Math.max(g,v,7)}var y=f/h,b=g/p;isNaN(y)&&(y=1/0),isNaN(b)&&(b=1/0);var x=Math.max(0,Math.floor(Math.min(y,b)));if(n===QC)return e.out.noPxChangeTryDetermine.push(ro(dk,null,t,x,l)),x;var w=uk(t,x,l);return null!=w?w:x}(this,t=t||tk(JC))},t}();function mk(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}var vk=["label","labelLine","layoutOption","priority","defaultAttr","marginForce","minMarginForce","marginDefault","suggestIgnore"];function _k(t,e,n){n=n||3,e?t.dirty|=n:t.dirty&=~n}function yk(t,e){return e=e||3,null==t.dirty||!!(t.dirty&e)}function bk(t){if(t)return yk(t)&&function(t,e,n){var i=e.getComputedTransform();t.transform=Vg(t.transform,i);var r=t.localRect=Bg(t.localRect,e.getBoundingRect()),o=e.style,a=o.margin,s=n&&n.marginForce,l=n&&n.minMarginForce,c=n&&n.marginDefault,d=o.__marginType;null==d&&c&&(a=c,d=am.textMargin);for(var u=0;u<4;u++)xk[u]=d===am.minMargin&&l&&null!=l[u]?l[u]:s&&null!=s[u]?s[u]:a?a[u]:0;d===am.textMargin&&Eg(r,xk,!1,!1);var h=t.rect=Bg(t.rect,r);i&&h.applyTransform(i);d===am.minMargin&&Eg(h,xk,!1,!1);t.axisAligned=Hg(i),(t.label=t.label||{}).ignore=e.ignore,_k(t,!1),_k(t,!0,2)}(t,t.label,t),t}var xk=[0,0,0,0];function wk(t,e){for(var n=0;n-1&&(s.style.stroke=s.style.fill,s.style.fill=Ov.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}(ub);function Mk(t,e){var n=t.mapDimensionsAll("defaultedLabel"),i=n.length;if(1===i){var r=gy(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),Fp(this,l,c,d)},e.prototype.setSymbolScale=function(t){this.scaleX=this.scaleY=t},e.prototype.fadeOut=function(t,e,n){var i=this.childAt(0),r=Jh(this).dataIndex,o=n&&n.animation;if(this.silent=i.silent=!0,n&&n.fadeLabel){var a=i.getTextContent();a&&pg(a,{style:{opacity:0}},e,{dataIndex:r,removeOpt:o,cb:function(){i.removeTextContent()}})}else i.removeTextContent();pg(i,{style:{opacity:0},scaleX:0,scaleY:0},e,{dataIndex:r,cb:t,removeOpt:o})},e.getSymbolSize=function(t,e){return ao(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}(Bc);function Ak(t,e){this.parent.drift(t,e)}function Ik(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 Pk(t){return null==t||ho(t)||(t={isIgnore:t}),t||{}}function Dk(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:Zg(e),cursorStyle:e.get("cursor")}}var Lk=function(){function t(t){this.group=new Bc,this._SymbolCtor=t||Tk}return t.prototype.updateData=function(t,e){this._progressiveEls=null,e=Pk(e);var n=this.group,i=t.hostModel,r=this._data,o=this._SymbolCtor,a=e.disableAnimation,s=Dk(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(Ik(t,r,i,e)){var a=new o(t,i,s,l);a.setPosition(r),t.setItemGraphicEl(i,a),n.add(a)}}).update(function(d,u){var h=r.getItemGraphicEl(u),p=c(d);if(Ik(t,p,d,e)){var f=t.getItemVisual(d,"symbol")||"circle",g=h&&h.getSymbolType&&h.getSymbolType();if(!h||g&&g!==f)n.remove(h),(h=new o(t,d,s,l)).setPosition(p);else{h.updateData(t,d,s,l);var m={x:p[0],y:p[1]};a?h.attr(m):dg(h,m,i)}n.add(h),t.setItemGraphicEl(d,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=Dk(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=Pk(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),d="x"===s||"radius"===s?1:0,u=to(t.dimensions,function(t){return e.mapDimension(t)}),h=!1,p=e.getCalculationInfo("stackResultDimension");return US(e,u[0])&&(h=!0,u[0]=p),US(e,u[1])&&(h=!0,u[1]=p),{dataDimsForPoint:u,valueStart:o,valueAxisDim:s,baseAxisDim:a,stacked:!!h,valueDim:l,baseDim:c,baseDataOffset:d,stackedOverDimension:e.getCalculationInfo("stackedOverDimension")}}function Rk(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 Nk=Math.min,Ok=Math.max;function zk(t,e){return isNaN(t)||isNaN(e)}function $k(t,e,n,i,r,o,a,s,l){for(var c,d,u,h,p,f,g=n,m=0;m=r||g<0)break;if(zk(v,_)){if(l){g+=o;continue}break}if(g===n)t[o>0?"moveTo":"lineTo"](v,_),u=v,h=_;else{var y=v-c,b=_-d;if(y*y+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===_&&m=i||zk(w,S))p=v,f=_;else{M=w-c,T=S-d;var P=v-c,D=w-v,L=_-d,E=S-_,R=void 0,N=void 0;if("x"===s){var O=M>0?1:-1;p=v-O*(R=Math.abs(P))*a,f=_,A=v+O*(N=Math.abs(D))*a,I=_}else if("y"===s){var z=T>0?1:-1;p=v,f=_-z*(R=Math.abs(L))*a,A=v,I=_+z*(N=Math.abs(E))*a}else R=Math.sqrt(P*P+L*L),p=v-M*a*(1-(k=(N=Math.sqrt(D*D+E*E))/(N+R))),f=_-T*a*(1-k),I=_+T*a*k,A=Nk(A=v+M*a*k,Ok(w,v)),I=Nk(I,Ok(S,_)),A=Ok(A,Nk(w,v)),f=_-(T=(I=Ok(I,Nk(S,_)))-_)*R/N,p=Nk(p=v-(M=A-v)*R/N,Ok(c,v)),f=Nk(f,Ok(d,_)),A=v+(M=v-(p=Ok(p,Nk(c,v))))*N/R,I=_+(T=_-(f=Ok(f,Nk(d,_))))*N/R}t.bezierCurveTo(u,h,p,f,v,_),u=A,h=I}else t.lineTo(v,_)}c=v,d=_,g+=o}return m}var Hk=function(){this.smooth=0,this.smoothConstraint=!0},Fk=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polyline",n}return v(e,t),e.prototype.getDefaultStyle=function(){return{stroke:Ov.color.neutral99,fill:null}},e.prototype.getDefaultShape=function(){return new Hk},e.prototype.buildPath=function(t,e){var n=e.points,i=0,r=n.length/2;if(e.connectNulls){for(;r>0&&zk(n[2*r-2],n[2*r-1]);r--);for(;i=0){var m=a?(d-i)*g+i:(c-n)*g+n;return a?[t,m]:[m,t]}n=c,i=d;break;case o.C:c=r[l++],d=r[l++],u=r[l++],h=r[l++],p=r[l++],f=r[l++];var v=a?ks(n,c,u,p,t,s):ks(i,d,h,f,t,s);if(v>0)for(var _=0;_=0){m=a?Ss(i,d,h,f,y):Ss(n,c,u,p,y);return a?[t,m]:[m,t]}}n=p,i=f}}},e}(Ch),Bk=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e}(Hk),Vk=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polygon",n}return v(e,t),e.prototype.getDefaultShape=function(){return new Bk},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&&zk(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=Qs(e[r]),s=Qs(e[o]),l=i-r,c=nl([Bs(Us(a[0],s[0],l)),Bs(Us(a[1],s[1],l)),Bs(Us(a[2],s[2],l)),Vs(Us(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 Yk(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 Jr(o.getViewLabels(),function(t){var e=o.scale.getRawOrdinalNumber(t.tickValue);s[e]=1}),function(t){return!s.hasOwnProperty(e.get(a,t))}}}}function Zk(t,e){return isNaN(t)||isNaN(e)}function Kk(t,e){return[t[2*e],t[2*e+1]]}function Qk(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=to(o.stops,function(t){return{coord:l.toGlobalCoord(l.dataToCoord(t.value)),color:t.color}}),d=c.length,u=o.outerColors.slice();d&&c[0].coord>c[d-1].coord&&(c.reverse(),u.reverse());var h=Xk(c,"x"===r?n.getWidth():n.getHeight()),p=h.length;if(!p&&d)return c[0].coord<0?u[1]?u[1]:c[d-1].color:u[0]?u[0]:c[0].color;var f=h[0].coord-10,g=h[p-1].coord+10,m=g-f;if(m<.001)return"transparent";Jr(h,function(t){t.offset=(t.coord-f)/m}),h.push({offset:p?h[p-1].offset:.5,color:u[1]||"transparent"}),h.unshift({offset:p?h[0].offset:.5,color:u[0]||"transparent"});var v=new Yf(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&&d.type===i.type&&k===this._step){m&&!p?p=this._newPolygon(l,y):p&&!m&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,pv(M));var T=f.getClipPath();if(T)ug(T,{shape:Jk(this,i,!1,t).shape},t);else f.setClipPath(Jk(this,i,!0,t));b&&u.updateData(o,{isIgnore:w,clipShape:C,disableAnimation:!0,getSymbolPoint:function(t){return[l[2*t],l[2*t+1]]}}),jk(this._stackedOnPoints,y)&&jk(this._points,l)||(g?this._doUpdateAnimation(o,y,i,n,k,v,x):(k&&(y&&(y=Gk(y,l,i,k,x)),l=Gk(l,null,i,k,x)),h.setShape({points:l}),p&&p.setShape({points:l,stackedOnPoints:y})))}else b&&u.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&&(y&&(y=Gk(y,l,i,k,x)),l=Gk(l,null,i,k,x)),h=this._newPolyline(l),m?p=this._newPolygon(l,y):p&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,pv(M)),f.setClipPath(Jk(this,i,!0,t));var A=t.getModel("emphasis"),I=A.get("focus"),P=A.get("blurScope"),D=A.get("disabled");(h.useStyle(Yr(a.getLineStyle(),{fill:"none",stroke:M,lineJoin:"bevel"})),jp(h,t,"lineStyle"),h.style.lineWidth>0&&"bolder"===t.get(["emphasis","lineStyle","width"]))&&(h.getState("emphasis").style.lineWidth=+h.style.lineWidth+1);Jh(h).seriesIndex=t.seriesIndex,Fp(h,I,P,D);var L=Uk(t.get("smooth")),E=t.get("smoothMonotone");if(h.setShape({smooth:L,smoothMonotone:E,connectNulls:x}),p){var R=o.getCalculationInfo("stackedOnSeries"),N=0;p.useStyle(Yr(s.getAreaStyle(),{fill:M,opacity:.7,lineJoin:"bevel",decal:o.getVisual("style").decal})),R&&(N=Uk(R.get("smooth"))),p.setShape({smooth:L,stackedOnSmooth:N,smoothMonotone:E,connectNulls:x}),jp(p,t,"areaStyle"),Jh(p).seriesIndex=t.seriesIndex,Fp(p,I,P,D)}var O=this._changePolyState;o.eachItemGraphicEl(function(t){t&&(t.onHoverStateChange=O)}),this._polyline.onHoverStateChange=O,this._data=o,this._coordSys=i,this._stackedOnPoints=y,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){Jh(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=Id(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 d=t.get("zlevel")||0,u=t.get("z")||0;(s=new Tk(r,o)).x=l,s.y=c,s.setZ(d,u);var h=s.getSymbolPath().getTextContent();h&&(h.zlevel=d,h.z=u,h.z2=this._polyline.z2+1),s.__temp=!0,r.setItemGraphicEl(o,s),s.stopSymbolAnimation(!0),this.group.add(s)}s.highlight()}else Sb.prototype.highlight.call(this,t,e,n,i)},e.prototype.downplay=function(t,e,n,i){var r=t.getData(),o=Id(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 Sb.prototype.downplay.call(this,t,e,n,i)},e.prototype._changePolyState=function(t){var e=this._polygon;wp(this._polyline,t),e&&wp(e,t)},e.prototype._newPolyline=function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new Fk({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 Vk({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");so(l)&&(l=l(null));var c=s.get("animationDelay")||0,d=so(c)?c(null):c;t.eachItemGraphicEl(function(t,o){var s=t;if(s){var u=[t.x,t.y],h=void 0,p=void 0,f=void 0;if(n)if(r){var g=n,m=e.pointToCoord(u);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 _=p===h?0:(f-h)/(p-h);a&&(_=1-_);var y=so(c)?c(o):l*_+d,b=s.getSymbolPath(),x=b.getTextContent();s.attr({scaleX:0,scaleY:0}),s.animateTo({scaleX:1,scaleY:1},{duration:200,setToFinal:!0,delay:y}),x&&x.animateFrom({style:{opacity:0}},{duration:300,delay:y}),b.disableLabelAnimation=!0}})},e.prototype._initOrUpdateEndLabel=function(t,e,n){var i=t.getModel("endLabel");if(Qk(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 Fh({z2:200})).ignoreClip=!0,o.setTextContent(this._endLabel),o.disableLabelAnimation=!0);var l=function(t){for(var e=t.length/2;e>0&&Zk(t[2*e-2],t[2*e-1]);e--);return e-1}(a);l>=0&&(Yg(o,Zg(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(!ao(e))return e+"";for(var i=[],r=0;r=0&&i.push(e[o])}return i.join(" ")}(r,n):Mk(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"),d=n.hostModel,u=d.get("connectNulls"),h=o.get("precision"),p=o.get("distance")||0,f=a.getBaseAxis(),g=f.isHorizontal(),m=f.inverse,v=e.shape,_=m?g?v.x:v.y+v.height:g?v.x+v.width:v.y,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,_,x),S=w.range,C=S[1]-S[0],k=void 0;if(C>=1){if(C>1&&!u){var M=Kk(c,S[0]);s.attr({x:M[0]+y,y:M[1]+b}),r&&(k=d.getRawValue(S[0]))}else{(M=l.getPointOn(_,x))&&s.attr({x:M[0]+y,y:M[1]+b});var T=d.getRawValue(S[0]),A=d.getRawValue(S[1]);r&&(k=function(t,e,n,i,r){var o=null==e||"auto"===e;if(null==i)return i;if(uo(i))return td(f=md(n||0,i,r),o?Math.max(ed(n||0),ed(i)):e);if(lo(i))return r<1?n:i;for(var a=[],s=n,l=i,c=Math.max(s?s.length:0,l.length),d=0;d0?S[0]:0;M=Kk(c,I);r&&(k=d.getRawValue(I)),s.attr({x:M[0]+y,y:M[1]+b})}if(r){var P=om(s);"function"==typeof P.setLabelText&&P.setLabelText(k)}}},e.prototype._doUpdateAnimation=function(t,e,n,i,r,o,a){var s=this._polyline,l=this._polygon,c=t.hostModel,d=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=[],d=[],u=[],h=[],p=[],f=[],g=Ek(r,e,a),m=t.getLayout("points")||[],v=e.getLayout("points")||[],_=0;_3e3||l&&Wk(h,f)>3e3)return s.stopAnimation(),s.setShape({points:p}),void(l&&(l.stopAnimation(),l.setShape({points:p,stackedOnPoints:f})));s.shape.__points=d.current,s.shape.points=u;var g={shape:{points:p}};d.current!==u&&(g.shape.__points=d.next),s.stopAnimation(),dg(s,g,c),l&&(l.setShape({points:u,stackedOnPoints:h}),l.stopAnimation(),dg(l,{shape:{stackedOnPoints:f}},c),s.shape.points!==l.shape.points&&(l.shape.points=s.shape.points));for(var m=[],v=d.status,_=0;_e&&(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}(gk),yM="expandAxisBreak",bM=Math.PI,xM=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],wM=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],SM=Pd(),CM=Pd(),kM=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 MM=[1,0,0,1,0,0],TM=new Ha(0,0,0,0),AM=function(t,e,n,i,r,o){if(jC(t.nameLocation)){var a=o.stOccupiedRect;a&&IM(function(t,e,n){return t.transform=Vg(t.transform,n),t.localRect=Bg(t.localRect,e),t.rect=Bg(t.rect,e),n&&t.rect.applyTransform(n),t.axisAligned=Hg(n),t.obb=void 0,(t.label=t.label||{}).ignore=!1,t}({},a,o.transGroup.transform),i,r)}else PM(o.labelInfoList,o.dirVec,i,r)};function IM(t,e,n){var i=new ka;Ck(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 PM(t,e,n,i){for(var r=ka.dot(i,e)>=0,o=0,a=t.length;o0?"top":"bottom",i="center"):rd(o-bM)?(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}(),LM=["axisLine","axisTickLabelEstimate","axisTickLabelDetermine","axisName"],EM={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,d=[l[0],0],u=[l[1],0],h=d[0]>u[0];c&&(Wo(d,d,c),Wo(u,u,c));var p=Xr({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 Ff(Xr({shape:{x1:d[0],y1:d[1],x2:u[0],y2:u[1]}},f));kg(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"]);lo(m)&&(m=[m,m]),(lo(v)||uo(v))&&(v=[v,v]);var _=Lx(i.get(["axisLine","symbolOffset"])||0,v),y=v[0],b=v[1];Jr([{rotate:t.rotation+Math.PI/2,offset:_[0],r:0},{rotate:t.rotation-Math.PI/2,offset:_[1],r:Math.sqrt((d[0]-u[0])*(d[0]-u[0])+(d[1]-u[1])*(d[1]-u[1]))}],function(e,n){if("none"!==m[n]&&null!=m[n]){var i=Dx(m[n],-y/2,-b/2,y,b,p.stroke,!0),o=e.r+e.offset,a=h?u:d;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){zM(e,r,s)&&RM(t,e,n,i,r,o,a,QC)},axisTickLabelDetermine:function(t,e,n,i,r,o,a,s){zM(e,r,s)&&RM(t,e,n,i,r,o,a,JC);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=OM(r.getTicksCoords(),n.transform,l,Yr(s.getLineStyle(),{stroke:i.get(["axisLine","lineStyle","color"])}),"ticks"),d=0;di[1],l="start"===e&&!s||"start"!==e&&s;rd(a-bM/2)?(o=l?"bottom":"top",r="center"):rd(a-1.5*bM)?(o=l?"top":"bottom",r="center"):(o="middle",r=a<1.5*bM&&a>bM/2?l?"left":"right":l?"right":"left");return{rotation:a,textAlign:r,textVerticalAlign:o}}(t.rotation,d,x||0,f),null!=(b=t.raw.axisNameAvailableWidth)&&(b=Math.abs(b/Math.sin(y.rotation)),!isFinite(b)&&(b=null)));var w=h.getFont(),S=i.get("nameTruncate",!0)||{},C=S.ellipsis,k=_o(t.raw.nameTruncateMaxWidth,S.maxWidth,b),M=s.nameMarginLevel||0,T=new Fh({x:m.x,y:m.y,rotation:y.rotation,silent:DM.isLabelSilent(i),style:Kg(h,{text:c,font:w,overflow:"truncate",width:k,ellipsis:C,fill:h.getTextColor()||i.get(["axisLine","lineStyle","color"]),align:h.get("align")||y.textAlign,verticalAlign:h.get("verticalAlign")||y.textVerticalAlign}),z2:1});if(Og({el:T,componentModel:i,itemName:c}),T.__fullText=c,T.anid="name",i.get("triggerEvent")){var A=DM.makeAxisEventDataBase(i);A.targetType="axisName",A.name=c,Jh(T).eventData=A}o.add(T),T.updateTransform(),e.nameEl=T;var I=l.nameLayout=bk({label:T,priority:T.z2,defaultAttr:{ignore:T.ignore},marginDefault:jC(d)?xM[M]:wM[M]});if(l.nameLocation=d,r.add(T),T.decomposeTransform(),t.shouldNameMoveOverlap&&I){var P=n.ensureRecord(i);n.resolveAxisNameOverlap(t,n,i,I,v,P)}}}};function RM(t,e,n,i,r,o,a,s){$M(e)||function(t,e,n,i,r,o){var a=r.axis,s=_o(t.raw.axisLabelShow,r.get(["axisLabel","show"])),l=new Bc;n.add(l);var c=tk(i);if(!s||a.scale.isBlank())return void HM(e,[],l,c);var d=r.getModel("axisLabel"),u=a.getViewLabels(c),h=(_o(t.raw.labelRotate,d.get("rotate"))||0)*bM/180,p=DM.innerTextLayout(t.rotation,h,t.labelDirection),f=r.getCategories&&r.getCategories(!0),g=[],m=r.get("triggerEvent"),v=1/0,_=-1/0;Jr(u,function(t,e){var n,i="ordinal"===a.scale.type?a.scale.getRawOrdinalNumber(t.tickValue):t.tickValue,s=t.formattedLabel,c=t.rawLabel,h=d;if(f&&f[i]){var y=f[i];ho(y)&&y.textStyle&&(h=new vm(y.textStyle,d,r.ecModel))}var b=h.getTextColor()||r.get(["axisLine","lineStyle","color"]),x=h.getShallow("align",!0)||p.textAlign,w=yo(h.getShallow("alignMinLabel",!0),x),S=yo(h.getShallow("alignMaxLabel",!0),x),C=h.getShallow("verticalAlign",!0)||h.getShallow("baseline",!0)||p.textVerticalAlign,k=yo(h.getShallow("verticalAlignMinLabel",!0),C),M=yo(h.getShallow("verticalAlignMaxLabel",!0),C),T=10+((null===(n=t.time)||void 0===n?void 0:n.level)||0);v=Math.min(v,T),_=Math.max(_,T);var A=new Fh({x:0,y:0,rotation:0,silent:DM.isLabelSilent(r),z2:T,style:Kg(h,{text:s,align:0===e?w:e===u.length-1?S:x,verticalAlign:0===e?k:e===u.length-1?M:C,fill:so(b)?b("category"===a.type?c:"value"===a.type?i+"":i,e):b})});A.anid="label_"+i;var I=SM(A);if(I.break=t.break,I.tickValue=i,I.layoutRotation=p.rotation,Og({el:A,componentModel:r,itemName:s,formatterParamsExtra:{isTruncated:function(){return A.isTruncated},value:c,tickIndex:e}}),m){var P=DM.makeAxisEventDataBase(r);P.targetType="axisLabel",P.value=c,P.tickIndex=e,t.break&&(P.break={start:t.break.parsedBreak.vmin,end:t.break.parsedBreak.vmax}),"category"===a.type&&(P.dataIndex=i),Jh(A).eventData=P,t.break&&function(t,e,n,i){n.on("click",function(n){var r={type:yM,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 y=to(g,function(t){return{label:t,priority:SM(t).break?t.z2+(_-v+1):t.z2,defaultAttr:{ignore:t.ignore}}});HM(e,y,l,c)}(t,e,r,s,i,a);var l=e.labelLayoutList;!function(t,e,n,i){var r=e.get(["axisLabel","margin"]);Jr(n,function(n,o){var a=bk(n);if(a){var s=a.label,l=SM(s);a.suggestIgnore=s.ignore,s.ignore=!1,vc(FM,BM),FM.x=e.axis.dataToCoord(l.tickValue),FM.y=t.labelOffset+t.labelDirection*r,FM.rotation=l.layoutRotation,i.add(FM),FM.updateTransform(),i.remove(FM),FM.decomposeTransform(),vc(s,FM),s.markRedraw(),_k(a,!0),bk(a)}})}(t,i,l,o),t.rotation;var c=t.optionHideOverlap;!function(t,e,n){if(BC(t.axis))return;function i(t,i,r){var o=bk(e[i]),a=bk(e[r]);if(o&&a)if(!1===t||o.suggestIgnore)NM(o.label);else if(a.suggestIgnore)NM(a.label);else{var s=.1;if(!n){var l=[0,0,0,0];o=wk({marginForce:l},o),a=wk({marginForce:l},a)}Ck(o,a,null,{touchThreshold:s})&&NM(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",d=a.transGroup[c];if(s.sort(function(t,e){return Math.abs(t.label[c]-d)-Math.abs(e.label[c]-d)}),l&&r){var u=o.getExtent(),h=Math.min(u[0],u[1]),p=Math.max(u[0],u[1])-h;r.union(new Ha(h,0,p,1))}a.stOccupiedRect=r,a.labelInfoList=s}(t,n,i,l)}function NM(t){t&&(t.ignore=!0)}function OM(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;XS(l)&&s.get("alignTicks")&&null==s.get("interval")?r.push(a):(zC(l,s),XS(l)&&(e=a))}r.length&&(e||zC((e=r.pop()).scale,e.model),Jr(r,function(t){!function(t,e,n){var i=dC.prototype,r=i.getTicks.call(n),o=i.getTicks.call(n,{expandToNicedExtent:!0}),a=r.length-1,s=i.getInterval.call(n),l=OC(t,e),c=l.extent,d=l.fixMin,u=l.fixMax;"log"===t.type&&(c=iC(t.base,c,!0)),t.setBreaksFromOption(WC(e)),t.setExtent(c[0],c[1]),t.calcNiceExtent({splitNumber:a,fixMin:d,fixMax:u});var h=i.getExtent.call(t);d&&(c[0]=h[0]),u&&(c[1]=h[1]);var p=i.getInterval.call(t),f=c[0],g=c[1];if(d&&u)p=(g-f)/a;else if(d)for(g=c[0]+p*a;gc[0]&&isFinite(f)&&isFinite(c[0]);)p=ZS(p),f=c[1]-p*a;else{t.getTicks().length-1>a&&(p=ZS(p));var m=p*a;(f=td((g=Math.ceil(c[1]/p)*p)-m))<0&&c[0]>=0?(f=0,g=td(m)):g>0&&c[1]<=0&&(g=0,f=-td(m))}var v=(r[0].value-o[0].value)/s,_=(r[a].value-o[a].value)/s;i.setExtent.call(t,f+p*v,g+p*_),i.setInterval.call(t,p),(v||_)&&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={};Jr(n.x,function(t){XM(n,"y",t,r)}),Jr(n.y,function(t){XM(n,"x",t,r)}),this.resize(this.model,e)},t.prototype.resize=function(t,e,n){var i=Pv(t,e),r=this._rect=Av(t.getBoxLayoutParams(),i.refContainer),o=this._axesMap,a=this._coordsList,s=t.get("containLabel");if(ZM(o,r),!n){var l=function(t,e,n,i,r){var o=new kM(tT);return Jr(n,function(n){return Jr(n,function(n){if(qC(n.model)){var a=!i;n.axisBuilder=function(t,e,n,i,r,o){for(var a=jM(t,n),s=!1,l=!1,c=0;c0&&i>0||n<0&&i<0)}(t)}function ZM(t,e){Jr(t.x,function(t){return KM(t,e.x,e.width)}),Jr(t.y,function(t){return KM(t,e.y,e.height)})}function KM(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 QM(t,e,n,i,r,o,a){JM(i,r,QC,e,!1,a);var s=[0,0,0,0];c(0),c(1),d(i,0,NaN),d(i,1,NaN);var l=null==function(t,e,n){if(t&&e)for(var i=0,r=t.length;i0});return Eg(i,s,!0,!0,n),ZM(r,i),l;function c(t){Jr(r[mg[t]],function(e){if(qC(e.model)){var n=o.ensureRecord(e.model),i=n.labelInfoList;if(i)for(var r=0;r0&&!vo(e)&&e>1e-4&&(t/=e),t}}function JM(t,e,n,i,r,o){var a=n===JC;Jr(e,function(e){return Jr(e,function(e){qC(e.model)&&(!function(t,e,n){var i=jM(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[mg[1-e]]=t[vg[e]]<=.5*o.refContainer[vg[e]]?0:1-e==1?2:1}l(0),l(1),Jr(e,function(t,e){return Jr(t,function(t){qC(t.model)&&(("all"===i||a)&&t.axisBuilder.build({axisName:!0},{nameMarginLevel:s[e]}),a&&t.axisBuilder.build({axisLine:!0}))})})}var tT=function(t,e,n,i,r,o){var a="x"===n.axis.dim?"y":"x";AM(t,0,0,i,r,o),jC(t.nameLocation)||Jr(e.recordMap[a],function(t){t&&t.labelInfoList&&t.dirVec&&PM(t.labelInfoList,t.dirVec,i,r)})};function eT(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=[];Jr(n.getCoordinateSystems(),function(n){if(n.axisPointerEnabled){var s=oT(n.model),l=t.coordSysAxesInfo[s]={};t.coordSysMap[s]=n;var c=n.model.getModel("tooltip",i);if(Jr(n.getAxes(),oo(p,!1,null)),n.getTooltipAxes&&i&&c.get("show")){var d="axis"===c.get("trigger"),u="cross"===c.get(["axisPointer","type"]),h=n.getTooltipAxes(c.get(["axisPointer","axis"]));(d||u)&&Jr(h.baseAxes,oo(p,!u||"cross",d)),u&&Jr(h.otherAxes,oo(p,"cross",!1))}}function p(i,s,d){var u=d.model.getModel("axisPointer",r),h=u.get("show");if(h&&("auto"!==h||i||rT(u))){null==s&&(s=u.get("triggerTooltip")),u=i?function(t,e,n,i,r,o){var a=e.getModel("axisPointer"),s={};Jr(["type","snap","lineStyle","shadowStyle","label","animation","animationDurationUpdate","animationEasingUpdate","z"],function(t){s[t]=Ur(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 d=s.lineStyle=a.get("crossStyle");d&&Yr(l,d.textStyle)}}return t.model.getModel("axisPointer",new vm(s,n,i))}(d,c,r,e,i,s):u;var p=u.get("snap"),f=u.get("triggerEmphasis"),g=oT(d.model),m=s||p||"category"===d.type,v=t.axesInfo[g]={key:g,axis:d,coordSys:n,axisPointerModel:u,triggerTooltip:s,triggerEmphasis:f,involveSeries:m,snap:p,useHandle:rT(u),seriesModels:[],linkGroup:null};l[g]=v,t.seriesInvolved=t.seriesInvolved||m;var _=function(t,e){for(var n=e.model,i=e.dim,r=0;r=0||t===e}function iT(t){var e=(t.ecModel.getComponent("axisPointer")||{}).coordSysAxesInfo;return e&&e.axesInfo[oT(t)]}function rT(t){return!!t.get(["handle","show"])}function oT(t){return t.type+"||"+t.id}var aT={},sT=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return v(e,t),e.prototype.render=function(e,n,i,r){this.axisPointerClass&&function(t){var e=iT(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=rT(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=iT(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=vT(t).pointerEl=new Ug[r.type](_T(e.pointer));t.add(o)}},t.prototype.createLabelEl=function(t,e,n,i){if(e.label){var r=vT(t).labelEl=new Fh(_T(e.label));t.add(r),ST(r,i)}},t.prototype.updatePointerEl=function(t,e,n){var i=vT(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=vT(t).labelEl;r&&(r.setStyle(e.label.style),n(r,{x:e.label.x,y:e.label.y}),ST(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=Pg(o.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(t){ga(t.event)},onmousedown:yT(this._onHandleDragMove,this,0,0),drift:yT(this._onHandleDragMove,this),ondragend:yT(this._onHandleDragEnd,this)}),i.add(r)),kT(r,n,!1),r.setStyle(o.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var s=o.get("size");ao(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,Eb(this,"_doDispatchAxisPointer",o.get("throttle")||0,"fixRate"),this._moveHandleToValue(t,e)}},t.prototype._moveHandleToValue=function(t,e){xT(this._axisPointerModel,!e&&this._moveAnimation,this._handle,CT(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(CT(n),[t,e],this._axisModel,this._axisPointerModel);this._payloadInfo=i,n.stopAnimation(),n.attr(CT(i)),vT(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),Rb(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 xT(t,e,n,i){wT(vT(n).lastProp,i)||(vT(n).lastProp=i,e?dg(n,i,t):(n.stopAnimation(),n.attr(i)))}function wT(t,e){if(ho(t)&&ho(e)){var n=!0;return Jr(e,function(e,i){n=n&&wT(t[i],e)}),!!n}return t===e}function ST(t,e){t[e.get(["label","show"])?"show":"hide"]()}function CT(t){return{x:t.x||0,y:t.y||0,rotation:t.rotation||0}}function kT(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 MT(t,e,n,i,r){var o=TT(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=lv(a.get("padding")||0),l=a.getFont(),c=Cc(o,l),d=r.position,u=c.width+s[1]+s[3],h=c.height+s[0]+s[2],p=r.align;"right"===p&&(d[0]-=u),"center"===p&&(d[0]-=u/2);var f=r.verticalAlign;"bottom"===f&&(d[1]-=h),"middle"===f&&(d[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)}(d,u,h,i);var g=a.get("backgroundColor");g&&"auto"!==g||(g=e.get(["axisLine","lineStyle","color"])),t.label={x:d[0],y:d[1],style:Kg(a,{text:o,font:l,fill:a.getTextColor(),padding:s,backgroundColor:g}),z2:10}}function TT(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:HC(e,{value:t}),axisDimension:e.dim,axisIndex:e.index,seriesData:[]};Jr(i,function(t){var e=n.getSeriesByIndex(t.seriesIndex),i=t.dataIndexInside,r=e&&e.getDataParams(i);r&&s.seriesData.push(r)}),lo(a)?o=a.replace("{value}",o):so(a)&&(o=a(s))}return o}function AT(t,e,n){var i=[1,0,0,1,0,0];return Sa(i,i,n.rotation),wa(i,i,n.position),Tg([t.dataToCoord(e),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],i)}var IT=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e.prototype.makeElOption=function(t,e,n,i,r){var o=n.axis,a=o.grid,s=i.get("type"),l=PT(a,o).getOtherAxis(o).getGlobalExtent(),c=o.toGlobalCoord(o.dataToCoord(e,!0));if(s&&"none"!==s){var d=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),u=DT[s](o,c,l);u.style=d,t.graphicKey=u.type,t.pointer=u}!function(t,e,n,i,r,o){var a=DM.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=r.get(["label","margin"]),MT(e,i,r,o,{position:AT(i.axis,t,n),align:a.textAlign,verticalAlign:a.textVerticalAlign})}(e,t,jM(a.getRect(),n),n,i,r)},e.prototype.getHandleTransform=function(t,e,n){var i=jM(e.axis.grid.getRect(),e,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var r=AT(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=PT(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 d=(s[1]+s[0])/2,u=[d,d];u[l]=c[l];return{x:c[0],y:c[1],rotation:t.rotation,cursorPoint:u,tooltipOption:[{verticalAlign:"middle"},{align:"center"}][l]}},e}(bT);function PT(t,e){var n={};return n[e.dim+"AxisIndex"]=e.index,t.getCartesian(n)}var DT={line:function(t,e,n){var i,r,o;return{type:"Line",subPixelOptimize:!0,shape:(i=[e,n[0]],r=[e,n[1]],o=LT(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=LT(t),{x:i[o=o||0],y:i[1-o],width:r[o],height:r[1-o]})}}};function LT(t){return"x"===t.dim?0:1}var ET=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return v(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:Ov.color.border,width:1,type:"dashed"},shadowStyle:{color:Ov.color.shadowTint},label:{show:!0,formatter:null,precision:"auto",margin:3,color:Ov.color.neutral00,padding:[5,7,5,7],backgroundColor:Ov.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:Ov.color.accent40,throttle:40}},e}(Nv),RT=Pd(),NT=Jr;function OT(t,e,n){if(!kr.node){var i=e.getZr();RT(i).records||(RT(i).records={}),function(t,e){if(RT(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);NT(RT(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)})}RT(t).initialized=!0,n("click",oo($T,"click")),n("mousemove",oo($T,"mousemove")),n("globalout",zT)}(i,e),(RT(i).records[t]||(RT(i).records[t]={})).handler=n}}function zT(t,e,n){t.handler("leave",null,n)}function $T(t,e,n,i){e.handler(t,n,i)}function HT(t,e){if(!kr.node){var n=e.getZr();(RT(n).records||{})[t]&&(RT(n).records[t]=null)}}var FT=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return v(e,t),e.prototype.render=function(t,e,n){var i=e.getComponent("tooltip"),r=t.get("triggerOn")||i&&i.get("triggerOn")||"mousemove|click";OT("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){HT("axisPointer",e)},e.prototype.dispose=function(t,e){HT("axisPointer",e)},e.type="axisPointer",e}(yb);function BT(t,e){var n,i=[],r=t.seriesIndex;if(null==r||!(n=e.getSeriesByIndex(r)))return{point:[]};var o=n.getData(),a=Id(o,t);if(null==a||a<0||ao(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(),d=l.getOtherAxis(c).dim,u=c.dim,h="x"===d||"radius"===d?1:0,p=o.mapDimension(u),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(to(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 VT=Pd();function jT(t,e,n){var i=t.currTrigger,r=[t.x,t.y],o=t,a=t.dispatchAction||ro(n.dispatchAction,n),s=e.getComponent("axisPointer").coordSysAxesInfo;if(s){XT(r)&&(r=BT({seriesIndex:o.seriesIndex,dataIndex:o.dataIndex},e).point);var l=XT(r),c=o.axesInfo,d=s.axesInfo,u="leave"===i||XT(r),h={},p={},f={list:[],map:{}},g={showPointer:oo(WT,p),showTooltip:oo(UT,f)};Jr(s.coordSysMap,function(t,e){var n=l||t.containPoint(r);Jr(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(!u&&n&&(!c||o)){var a=o&&o.value;null!=a||l||(a=i.pointToData(r)),null!=a&&qT(t,a,g,!1,h)}})});var m={};return Jr(d,function(t,e){var n=t.linkGroup;n&&!p[e]&&Jr(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,GT(e),GT(t)))),m[t.key]=o}})}),Jr(m,function(t,e){qT(d[e],t,g,!0,h)}),function(t,e,n){var i=n.axesInfo=[];Jr(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,d,h),function(t,e,n,i){if(XT(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=VT(i)[r]||{},a=VT(i)[r]={};Jr(t,function(t,e){var n=t.axisPointerModel.option;"show"===n.status&&t.triggerEmphasis&&Jr(n.seriesDataIndices,function(t){var e=t.seriesIndex+" | "+t.dataIndex;a[e]=t})});var s=[],l=[];Jr(o,function(t,e){!a[e]&&l.push(t)}),Jr(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})}(d,0,n),h}}function qT(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 Jr(e.seriesModels,function(e,l){var c,d,u=e.getData().mapDimensionsAll(i);if(e.getAxisTooltipData){var h=e.getAxisTooltipData(u,t,n);d=h.dataIndices,c=h.nestestValue}else{if(!(d=e.indicesOfNearest(i,u[0],t,"category"===n.type?.5:null)).length)return;c=e.getData().get(u[0],d[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),Jr(d,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&&Xr(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 WT(t,e,n,i){t[e.key]={value:n,payloadBatch:i}}function UT(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=oT(l),d=t.map[c];d||(d=t.map[c]={coordSysId:l.id,coordSysIndex:l.componentIndex,coordSysType:l.type,coordSysMainType:l.mainType,dataByAxis:[]},t.list.push(d)),d.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 GT(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 XT(t){return!t||null==t[0]||isNaN(t[0])||null==t[1]||isNaN(t[1])}function YT(t){sT.registerAxisPointerClass("CartesianAxisPointer",IT),t.registerComponentModel(ET),t.registerComponentView(FT),t.registerPreprocessor(function(t){if(t){(!t.axisPointer||0===t.axisPointer.length)&&(t.axisPointer={});var e=t.axisPointer.link;e&&!ao(e)&&(t.axisPointer.link=[e])}}),t.registerProcessor(t.PRIORITY.PROCESSOR.STATISTIC,function(t,e){t.getComponent("axisPointer").coordSysAxesInfo=eT(t,e)}),t.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},jT)}var ZT=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return v(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:Ov.color.neutral00,shadowBlur:10,shadowColor:"rgba(0, 0, 0, .2)",shadowOffsetX:1,shadowOffsetY:2,borderRadius:4,borderWidth:1,defaultBorderColor:Ov.color.border,padding:null,extraCssText:"",axisPointer:{type:"line",axis:"auto",animation:"auto",animationDurationUpdate:200,animationEasingUpdate:"exponentialOut",crossStyle:{color:Ov.color.borderShade,width:1,type:"dashed",textStyle:{}}},textStyle:{color:Ov.color.tertiary,fontSize:14}},e}(Nv);function KT(t){var e=t.get("confine");return null!=e?!!e:"richText"===t.get("renderMode")}function QT(t){if(kr.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?",":"")+(kr.transformSupported?""+nA+r:",left"+r+",top"+r)),eA+":"+o}(o,n,i)),a&&r.push("background-color:"+a),Jr(["width","color","radius"],function(e){var n="border-"+e,i=sv(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=yo(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),Jr(["decoration","align"],function(n){var i=t.get(n);i&&e.push("text-"+n+":"+i)}),e.join(";")}(u)),null!=h&&r.push("padding:"+lv(h).join("px ")+"px"),r.join(";")+";"}function aA(t,e,n,i,r){var o=e&&e.painter;if(n){var a=o&&o.getViewportRoot();a&&function(t,e,n,i,r){na(ea,e,i,r,!0)&&na(t,n,ea[0],ea[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 sA=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,kr.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&&(lo(r)?document.querySelector(r):go(r)?r:so(r)&&r(t.getDom()));aA(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;pa(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=iA+oA(t,!this._firstShow,this._longHide,this._enableDisplayTransition)+rA(r[0],r[1],!0)+"border-color:"+pv(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(lo(r)&&"item"===n.get("trigger")&&!KT(n)&&(a=function(t,e,n){if(!lo(n)||"inside"===n)return"";var i=t.get("backgroundColor"),r=t.get("borderWidth");e=pv(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="",d=nA+":";Zr(["left","right"],s)>-1?(c+="top:50%",d+="translateY(-50%) rotate("+(a="left"===s?-225:-45)+"deg)"):(c+="left:50%",d+="translateX(-50%) rotate("+(a="top"===s?225:45)+"deg)");var u=a*Math.PI/180,h=l+r,p=h*Math.abs(Math.cos(u))+h*Math.abs(Math.sin(u)),f=e+" solid "+r+"px;";return'
'}(n,i,r)),lo(t))o.innerHTML=t+a;else if(t){o.innerHTML="",ao(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&&!kr.node&&n.getDom()){var r=gA(i,n);this._ticket="";var o=i.dataByCoordSys,a=function(t,e,n){var i=Ed(t).queryOptionMap,r=i.keys()[0];if(!r||"series"===r)return;var o=Nd(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=Jh(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=hA;l.x=i.x,l.y=i.y,l.update(),Jh(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=BT(i,e),d=c.point[0],u=c.point[1];null!=d&&null!=u&&this._tryShow({offsetX:d,offsetY:u,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(gA(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"===fA([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"===Jh(n).ssrType)return;this._lastDataByCoordSys=null,_x(n,function(t){if(t.tooltipDisabled)return r=o=null,!0;r||o||(null!=Jh(t).dataIndex?r=t:null!=Jh(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=ro(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=fA([e.tooltipOption],i),a=this._renderMode,s=[],l=Ky("section",{blocks:[],noHeader:!0}),c=[],d=new sb;Jr(t,function(t){Jr(t.dataByAxis,function(t){var e=n.getComponent(t.axisDim+"Axis",t.axisIndex),r=t.value;if(e&&null!=r){var o=TT(r,e.axis,n,t.seriesDataIndices,t.valueLabelOpt),u=Ky("section",{header:o,noHeader:!Co(o),sortBlocks:!0,blocks:[]});l.blocks.push(u),Jr(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=HC(e.axis,{value:r}),f.axisValueLabel=o,f.marker=d.makeTooltipMarker("item",pv(f.color),a);var g=_y(h.formatTooltip(p,!0,null)),m=g.frag;if(m){var v=fA([h],i).get("valueFormatter");u.blocks.push(v?Xr({valueFormatter:v},m):m)}g.text&&c.push(g.text),s.push(f)}})}})}),l.blocks.reverse(),c.reverse();var u=e.position,h=o.get("order"),p=ib(l,d,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,u,r[0],r[1],this._tooltipContent,s):this._showTooltipContent(o,g,s,Math.random()+"",r[0],r[1],u,null,d)})},e.prototype._showSeriesItemTooltip=function(t,e,n){var i=this._ecModel,r=Jh(e),o=r.seriesIndex,a=i.getSeriesByIndex(o),s=r.dataModel||a,l=r.dataIndex,c=r.dataType,d=s.getData(c),u=this._renderMode,h=t.positionDefault,p=fA([d.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 sb;g.marker=m.makeTooltipMarker("item",pv(g.color),u);var v=_y(s.formatTooltip(l,!1,c)),_=p.get("order"),y=p.get("valueFormatter"),b=v.frag,x=b?ib(y?Xr({valueFormatter:y},b):b,m,u,_,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:d.getRawIndex(l),seriesIndex:o,from:this.uid})}},e.prototype._showComponentItemTooltip=function(t,e,n){var i="html"===this._renderMode,r=Jh(e),o=r.tooltipConfig.option||{},a=o.encodeHTMLContent;if(lo(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=Ur(o)).content=aa(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,d=fA(s,this._tooltipModel,c?{position:c}:null),u=d.get("content"),h=Math.random()+"",p=new sb;this._showOrMove(d,function(){var n=Ur(d.get("formatterParams")||{});this._showTooltipContent(d,u,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 d=t.get("formatter");a=a||t.get("position");var u=e,h=this._getNearestPoint([r,o],n,t.get("trigger"),t.get("borderColor"),t.get("defaultBorderColor",!0)).color;if(d)if(lo(d)){var p=t.ecModel.get("useUTC"),f=ao(n)?n[0]:n;u=d,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(u=jm(f.axisValue,u,p)),u=hv(u,n,!0)}else if(so(d)){var g=ro(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,u=d(n,i,g)}else u=d;c.setContent(u,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||ao(e)?{color:i||r}:ao(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(),d=t.get("align"),u=t.get("verticalAlign"),h=a&&a.getBoundingRect().clone();if(a&&h.applyTransform(a.transform),so(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),ao(e))n=Qc(e[0],s),i=Qc(e[1],l);else if(ho(e)){var p=e;p.width=c[0],p.height=c[1];var f=Av(p,{width:s,height:l});n=f.x,i=f.y,d=null,u=null}else if(lo(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,d=e.height;switch(t){case"inside":s=e.x+c/2-r/2,l=e.y+d/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+d+a;break;case"left":s=e.x-r-a,l=e.y+d/2-o/2;break;case"right":s=e.x+c+a,l=e.y+d/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,d?null:20,u?null:20);n=g[0],i=g[1]}if(d&&(n-=mA(d)?c[0]/2:"right"===d?c[0]:0),u&&(i-=mA(u)?c[1]/2:"bottom"===u?c[1]:0),KT(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&&Jr(n,function(n,o){var a=n.dataByAxis||[],s=(t[o]||{}).dataByAxis||[];(r=r&&a.length===s.length)&&Jr(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)&&Jr(a,function(t,e){var n=l[e];r=r&&t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex}),i&&Jr(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){!kr.node&&e.getDom()&&(Rb(this,"_updatePosition"),this._tooltipContent.dispose(),HT("itemTooltip",e))},e.type="tooltip",e}(yb);function fA(t,e,n){var i,r=e.ecModel;n?(i=new vm(n,r,r),i=new vm(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof vm&&(a=a.get("tooltip",!0)),lo(a)&&(a={formatter:a}),a&&(i=new vm(a,i,r)))}return i}function gA(t,e){return t.dispatchAction||ro(e.dispatchAction,e)}function mA(t){return"center"===t||"middle"===t}var vA=Math.sin,_A=Math.cos,yA=Math.PI,bA=2*Math.PI,xA=180/yA,wA=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,d=Math.abs(l),u=cl(d-bA)||(c?l>=bA:-l>=bA),h=l>0?l%bA:l%bA+bA,p=!1;p=!!u||!cl(d)&&h>=yA==!!c;var f=t+n*_A(o),g=e+i*vA(o);this._start&&this._add("M",f,g);var m=Math.round(r*xA);if(u){var v=1/this._p,_=(c?1:-1)*(bA-v);this._add("A",n,i,m,1,+c,t+n*_A(o+_),e+i*vA(o+_)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var y=t+n*_A(a),b=e+i*vA(a);this._add("A",n,i,m,+p,+c,y,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=[],d=this._p,u=1;u"}(r,o)+("style"!==r?aa(a):a||"")+(i?""+n+to(i,function(e){return t(e)}).join(n)+n:"")+("")}(t)}function RA(t){return{zrId:t,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function NA(t,e,n,i){return LA("svg","root",{width:t,height:e,xmlns:AA,"xmlns:xlink":IA,version:"1.1",baseProfile:"full",viewBox:!!i&&"0 0 "+t+" "+e},n)}var OA=0;function zA(){return OA++}var $A={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"},HA="transform-origin";function FA(t,e,n){var i=Xr({},t.shape);Xr(i,e),t.buildPath(n,i);var r=new wA;return r.reset(yl(t)),n.rebuildPath(r,1),r.generateStr(),r.getStr()}function BA(t,e){var n=e.originX,i=e.originY;(n||i)&&(t[HA]=n+"px "+i+"px")}var VA={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function jA(t,e){var n=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[n]=t,n}function qA(t){return lo(t)?$A[t]?"cubic-bezier("+$A[t]+")":Ns(t)?t:"":""}function WA(t,e,n,i){var r=t.animators,o=r.length,a=[];if(t instanceof Gf){var s=function(t,e,n){var i,r,o=t.shape.paths,a={};if(Jr(o,function(t){var e=RA(n.zrId);e.animation=!0,WA(t,{},e,!0);var o=e.cssAnims,s=e.cssNodes,l=io(o),c=l.length;if(c){var d=o[r=l[c-1]];for(var u in d){var h=d[u];a[u]=a[u]||{d:""},a[u].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=jA(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 jA(d,n)+" "+r[0]+" both"}for(var m in l){(s=g(l[m]))&&a.push(s)}if(a.length){var v=n.zrId+"-cls-"+zA();n.cssNodes["."+v]={animation:a.join(",")},e.class=v}}function UA(t,e,n,i){var r=JSON.stringify(t),o=n.cssStyleCache[r];o||(o=n.zrId+"-cls-"+zA(),n.cssStyleCache[r]=o,n.cssNodes["."+o+":hover"]=t),e.class=e.class?e.class+" "+o:o}var GA=Math.round;function XA(t){return t&&lo(t.src)}function YA(t){return t&&so(t.toDataURL)}function ZA(t,e,n,i){TA(function(r,o){var a="fill"===r||"stroke"===r;a&&vl(o)?sI(e,t,r,i):a&&fl(o)?lI(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 d=i.shadowOffsetX||0,u=i.shadowOffsetY||0,h=i.shadowBlur,p=sl(i.shadowColor),f=p.opacity,g=p.color,m=h/2/l+" "+h/2/c;a=n.zrId+"-s"+n.shadowIdx++,n.defs[a]=LA("filter",a,{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},[LA("feDropShadow","",{dx:d/l,dy:u/c,stdDeviation:m,"flood-color":g,"flood-opacity":f})]),o[r]=a}e.filter=_l(a)}}(n,t,i)}function KA(t,e){var n=function(t){if("function"==typeof qc)return qc(t)}(e);n&&(n.each(function(e,n){null!=e&&(t[(PA+n).toLowerCase()]=e+"")}),e.isSilent()&&(t[PA+"silent"]="true"))}function QA(t){return cl(t[0]-1)&&cl(t[1])&&cl(t[2])&&cl(t[3]-1)}function JA(t,e,n){if(e&&(!function(t){return cl(t[4])&&cl(t[5])}(e)||!QA(e))){var i=1e4;t.transform=QA(e)?"translate("+GA(e[4]*i)/i+" "+GA(e[5]*i)/i+")":function(t){return"matrix("+dl(t[0])+","+dl(t[1])+","+dl(t[2])+","+dl(t[3])+","+ul(t[4])+","+ul(t[5])+")"}(e)}}function tI(t,e,n){for(var i=t.points,r=[],o=0;o=0&&a||o;s&&(r=ol(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),UA(c,e,n)}}(t,o,e),LA(s,t.id+"",o)}function aI(t,e){return t instanceof Ch?oI(t,e):t instanceof Ih?function(t,e){var n=t.style,i=n.image;if(i&&!lo(i)&&(XA(i)?i=i.src:YA(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),JA(a,t.transform),ZA(a,n,t,e),KA(a,t),e.animation&&WA(t,a,e),LA("image",t.id+"",a)}}(t,e):t instanceof Mh?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||Tr,o=n.x||0,a=function(t,e,n){return"top"===n?t+=e/2:"bottom"===n&&(t-=e/2),t}(n.y||0,Tc(r),n.textBaseline),s={"dominant-baseline":"central","text-anchor":hl[n.textAlign]||n.textAlign};if(Uh(n)){var l="",c=n.fontStyle,d=qh(n.fontSize);if(!parseFloat(d))return;var u=n.fontFamily||Mr,h=n.fontWeight;l+="font-size:"+d+";font-family:"+u+";",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),JA(s,t.transform),ZA(s,n,t,e),KA(s,t),e.animation&&WA(t,s,e),LA("text",t.id+"",s,void 0,i)}}(t,e):void 0}function sI(t,e,n,i){var r,o=t[n],a={gradientUnits:o.global?"userSpaceOnUse":"objectBoundingBox"};if(gl(o))r="linearGradient",a.x1=o.x,a.y1=o.y,a.x2=o.x2,a.y2=o.y2;else{if(!ml(o))return;r="radialGradient",a.cx=yo(o.x,.5),a.cy=yo(o.y,.5),a.r=yo(o.r,.5)}for(var s=o.colorStops,l=[],c=0,d=s.length;cl?SI(t,null==n[u+1]?null:n[u+1].elm,n,s,u):CI(t,e,a,l))}(n,i,r):yI(r)?(yI(t.text)&&mI(n,""),SI(n,null,r,0,r.length-1)):yI(i)?CI(n,i,0,i.length-1):yI(t.text)&&mI(n,""):t.text!==e.text&&(yI(i)&&CI(n,i,0,i.length-1),mI(n,e.text)))}var TI=0,AI=function(){function t(t,e,n){if(this.type="svg",this.refreshHover=function(){},this.configLayer=function(){},this.storage=e,this._opts=n=Xr({},n),this.root=t,this._id="zr"+TI++,this._oldVNode=NA(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=DA("svg");kI(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(xI(t,e))MI(t,e);else{var n=t.elm,i=fI(n);wI(e),null!==i&&(uI(i,e.elm,gI(n)),CI(i,[t],0,0))}}(this._oldVNode,t),this._oldVNode=t}},t.prototype.renderOneToVNode=function(t){return aI(t,RA(this._id))},t.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),n=this._width,i=this._height,r=RA(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=LA("rect","bg",{width:t,height:e,x:"0",y:"0"}),vl(n))sI({fill:n},r.attrs,"fill",i);else if(fl(n))lI({style:{fill:n},dirty:Ro,getBoundingRect:function(){return{width:t,height:e}}},r.attrs,"fill",i);else{var o=sl(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=LA("g","main",{},[]);this._paintList(e,r,s?s.children:o),s&&o.push(s);var l=to(io(r.defs),function(t){return r.defs[t]});if(l.length&&o.push(LA("defs","defs",{},l)),t.animation){var c=function(t,e,n){var i=(n=n||{}).newline?"\n":"",r=" {"+i,o=i+"}",a=to(io(t),function(e){return e+r+to(io(t[e]),function(n){return n+":"+t[e][n]+";"}).join(i)+o}).join(i),s=to(io(e),function(t){return"@keyframes "+t+r+to(io(e[t]),function(n){return n+r+to(io(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 d=LA("style","stl",{},[],c);o.push(d)}}return NA(n,i,o,t.useViewBox)},t.prototype.renderToString=function(t){return t=t||{},EA(this.renderToVNode({animation:yo(t.cssAnimation,!0),emphasis:yo(t.cssEmphasis,!0),willUpdate:!1,compress:!0,useViewBox:yo(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&&(!u||!r||u[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(),d=n.getDevicePixelRatio(),u=Math.abs(c[1]-c[0])*(d||1),h=Math.round(a/u);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;lo(r)?p=eM[r]:so(r)&&(p=r),p&&t.setData(i.downSample(i.mapDimension(l.dim),1/h,p,nM))}}}}}("line"))},function(t){YC(mT),YC(YT)},function(t){YC(YT),t.registerComponentModel(ZT),t.registerComponentView(pA),t.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},Ro),t.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},Ro)},function(t){t.registerPainter("svg",AI)}]);class II extends At{constructor(){super(...arguments),this.options=null,this.data=[],this.height="120px",this._chart=null,this._resizeObserver=null}render(){return ct`
`}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=nS(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)}}II.styles=k` :host { display: block; width: 100%; @@ -282,16 +282,7 @@ var Ec={},Rc={};var Nc,Oc=function(){function t(t,e,n){var i=this;this._sleepAft width: 100%; height: 100%; } - `,_([Lt({attribute:!1})],bI.prototype,"options",void 0),_([Lt({attribute:!1})],bI.prototype,"data",void 0),_([Lt({type:String})],bI.prototype,"height",void 0);try{customElements.get("span-chart")||customElements.define("span-chart",bI)}catch{}function xI(t,e,n,i,o,a,s,l,c){const{options:d,series:u}=function(t,e,n,i,o,a=!1){n||(n=h[r]);const s=i?"140, 160, 220":"77, 217, 175",l=`rgb(${s})`,c=Date.now(),d=c-e,u=void 0!==n.fixedMin&&void 0!==n.fixedMax,p=(t??[]).filter(t=>t.time>=d).map(t=>[t.time,Math.abs(t.value)]),f=[{type:"line",data:p,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}}],g=p.length>0?function(t){let e=0;for(const n of t)n[1]>e&&(e=n[1]);return e}(p):0,m={type:"value",splitNumber:4,axisLabel:{fontSize:10,formatter:g<10?t=>0===t?"0":t.toFixed(1):t=>n.format(t)},splitLine:{lineStyle:{opacity:.15}}};if(u?(m.min=n.fixedMin,m.max=n.fixedMax):g<1&&(m.min=0,m.max=1),o&&"current"===n.entityRole){const t=o.ratingA*o.continuousPct/100,e=o.ratingA*o.spikePct/100;m.min=0,m.max=Math.ceil(1.25*Math.max(t,e,g)),f.push({type:"line",data:[[d,t],[c,t]],showSymbol:!1,lineStyle:{width:1,color:"rgba(255, 200, 40, 0.6)",type:"dashed"},itemStyle:{color:"transparent"},tooltip:{show:!1}}),f.push({type:"line",data:[[d,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 v={xAxis:{type:"time",min:d,max:c,axisLabel:{fontSize:10},splitLine:{show:!1}},yAxis:m,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:v,series:f}}(n,i,o,a,l,c),p=s??120;t.style.minHeight=p+"px";let f=t.querySelector("span-chart");f||(f=document.createElement("span-chart"),f.style.display="block",f.style.width="100%",t.innerHTML="",t.appendChild(f));const g=t.clientHeight;f.height=(g>0?g:p)+"px",f.options=d,f.data=u}function wI(t){return null===t?ki:function(t){return(Math.abs(t)/1e3).toFixed(1)}(t)}function SI(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):ki,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:Pn(o),partial:!1}),a&&(a.textContent=wI(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):ki,c&&(c.textContent="A")}else l.textContent=wI(Pn(i)),c&&(c.textContent="kW")}const d=t.querySelector(".stat-downstream .stat-value"),u=t.querySelector(".stat-downstream .stat-unit");if(d){const t=n.panel_entities?.feedthrough_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;d.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):ki,u&&(u.textContent="A")}else d.textContent=wI(Pn(i)),u&&(u.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):ki,p&&(p.textContent="A")}else h.textContent=wI(Pn(i)),p&&(p.textContent="kW")}const f=t.querySelector(".stat-battery .stat-value");if(f){const t=n.panel_entities?.battery_level,i=Pn(t?e.states[t]:void 0);f.textContent=null===i?ki:`${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:ki}}function CI(t,e,n,i,r,o,a){if(!t||!n||!e)return;const s=rr(i),l=we(n),c=[];for(const{circuit:t}of l){if(!t.entities?.power||Gn(t)||$n(t))continue;const n=Wn(t,e);c.push(null===n?null:Math.abs(n))}!function(t,e,n,i,r){const o=t.querySelector(".panel-stats");o&&SI(o,e,n,i,r)}(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 d={hass:e,topology:n,powerHistory:r,horizonMap:o,defaultDurationMs:s,chartMetric:Oi(i),monitoringStatus:a};for(const e of l)for(const n of ye(e)){const i=t.querySelector(`.circuit-slot[data-uuid="${Gi(n.uuid)}"]`);if(!i)continue;const r=n.uuid===e.uuid?e.circuit:xe(n.circuit,e);kI(i,n.uuid,r,d)}}function kI(t,e,n,i){const{hass:r,powerHistory:o,horizonMap:a,defaultDurationMs:s,chartMetric:l,monitoringStatus:c}=i,d=Wn(n,r),u=Xn(n,d),h=qn(n,r),p=t.querySelector(".power-value");p&&(p.innerHTML="current"===l.entityRole?Di(Un(n,r)):Pi(d)),Fi(t,h,ei(n,r),on(i.topology,e)),t.classList.toggle("circuit-off",!h),t.classList.toggle("circuit-producer",u),qi(t,ri(n,r));const f=t.querySelector(".chart-container");if(f){const i=o.get(e)||[],r=t.classList.contains("circuit-col-span")?200:100,d=a?.has(e)?or(a.get(e)):s,h=Gn(n),p=Oe(c,n),g=Ut(n,p);xI(f,0,i,d,l,u,r,g?{ratingA:g,...$e(p)}:void 0,h)}}class MI{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._settings=null,this._lastFetch=0,this._fetching=!1}async fetch(t,e){const i=Date.now();if(this._fetching)return this._settings;if(this._settings&&i-this._lastFetch<3e4)return this._settings;this._fetching=!0;try{const i={};e&&(i.config_entry_id=e);const r={type:"call_service",domain:s,service:"get_graph_settings",service_data:i,return_response:!0},o=this._retry?await this._retry.callWS(t,r,{errorId:"fetch:graph_settings",errorMessage:n("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:n("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 TI(t,e){if(!t)return o;const n=t.circuits?.[e];return n?.has_override?n.horizon:t.global_horizon??o}function AI(t,e){if(!t)return o;const n=t.sub_devices?.[e];return n?.has_override?n.horizon:t.global_horizon??o}function II(t,e,n){return{members:t?ye(t):[{uuid:e,circuit:n}],capacityA:t&&t.members.length>1?t.circuit.breaker_rating_a??null:null}}class PI{constructor(){this.powerHistory=new Map,this.horizonMap=new Map,this.subDeviceHorizonMap=new Map,this.monitoringCache=new Ee,this.monitoringMultiCache=new Re,this.graphSettingsCache=new MI,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,TI(t,e));if(t&&this._topology?.sub_devices)for(const e of Object.keys(this._topology.sub_devices))this.subDeviceHorizonMap.set(e,AI(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:n("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,TI(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,AI(i,r))}}async loadHistory(){await fr(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)??o;if(!a[i]?.useRealtime)continue;const r=zi(n,this._config);if(!r)continue;const s=Pn(this._hass.states[r]);if(null===s)continue;const l=or(i),c=ar(l),d=sr(l),u=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 pr(this._topology))i.has(e)&&r.add(t);const o=new Map;try{await fr(this._hass,this._topology,this._config,o,e,i);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:n("error.history_failed"),persistent:!1})}}updateDOM(t){this._hass&&this._topology&&this._config&&(CI(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=rr(i);for(const[i,s]of Object.entries(n.sub_devices)){const n=t.querySelector(`[data-subdev="${Gi(i)}"]`);if(!n)continue;const l=Dn(s);if(l.headlineEid){const t=n.querySelector(".sub-power-value");t&&(t.innerHTML=Ii(Rn(e,l.headlineEid)))}if(l.siteTotalEid){const t=Rn(e,l.siteTotalEid),i=n.querySelector(".sub-site-total-value");i&&(i.innerHTML=Ii(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=p.power;e.endsWith("_soc")?s=p.soc:e.endsWith("_soe")&&(s=p.soe);const l=!!t.closest(".bess-chart-col");xI(t,0,n,o?.has(i)?or(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="${Gi(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=Pn(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 Xi(n)){const n=t.querySelector(`.meter-tile[data-meter-uuid="${Gi(r)}"] .meter-readings`);n&&(n.innerHTML=Zi(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"!==ei(s,this._hass))return;const c=on(this._topology,a);if(!c.mayOperate)return void this._errorStore?.add({key:"service:relay",level:"warning",message:un(c),persistent:!1});const d=this._hass;pn(d,c).setRelay(l,"on"!==d.states[l]?.state).catch(t=>mn(d,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 a=i.dataset.uuid;if(a&&this._topology){const t=this._topology.circuits[a];if(t){const e=this._favRefs?.[a]??null,n=e&&"circuit"===e.kind?e.targetId:a,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=Oe(l,t),d=s?.global_horizon??o,u=s?.circuits?.[n],h=u?{...u,globalHorizon:d}:{horizon:d,has_override:!1,globalHorizon:d},p=e?.panelDeviceId??this._panelFavorites?.panelDeviceId,f=null!==e||(this._panelFavorites?.circuitUuids.has(n)??!1),g=this._sidePanelSlot(a,e),m=e?this._perPanelInfo.get(e.panelDeviceId)?.topology:this._topology,v={uuid:n,name:t.name,entities:t.entities,...II(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:on(this._topology,a)};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 a;e?a=await this._fetchGraphSettingsFresh(i):(await this.graphSettingsCache.fetch(this._hass,i),a=this.graphSettingsCache.settings);const l=a?.global_horizon??o,c=a?.sub_devices?.[n],d=c?{...c,globalHorizon:l}:{horizon:l,has_override:!1,globalHorizon:l},u=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:En(t).length>0,graphHorizonInfo:d,showFavorites:this.showFavorites,favoritePanelDeviceId:u,isFavorite:h,configEntryId:i})}}_sidePanelSlot(t,e){const n="circuit"===e?.kind?this._perPanelInfo.get(e.panelDeviceId)?.topology:void 0;return n&&e?be(we(n)).get(e.targetId):this._topology?be(we(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=be(we(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=Oe(l,a);r.refreshRating({...II(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(nn(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 i={type:"call_service",domain:s,service:"get_graph_settings",service_data:e,return_response:!0},r=this._errorStore?new De(this._errorStore):null,o=r?await r.callWS(this._hass,i,{errorId:"fetch:graph_settings",errorMessage:n("error.graph_settings_failed")}):await this._hass.callWS(i);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 i={type:"call_service",domain:s,service:"get_monitoring_status",service_data:e,return_response:!0},r=this._errorStore?new De(this._errorStore):null,o=r?await r.callWS(this._hass,i,{errorId:"fetch:monitoring",errorMessage:n("error.monitoring_failed")}):await this._hass.callWS(i);return Le(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 DI(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()}}const LI='\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';class EI{constructor(){this._ctrl=new PI,this._container=null,this._onGearClick=null,this._onToggleClick=null,this._onSidePanelClosed=null,this._onGraphSettingsChanged=null,this._foldUnobserve=null}get hass(){return this._ctrl.hass}set hass(t){this._ctrl.hass=t}set errorStore(t){this._ctrl.errorStore=t}setPanelFavorites(t){this._ctrl.setPanelFavorites(t)}async render(t,e,i,r,o){let a,s;this.stop(),this._ctrl.reset(),this._ctrl.showMonitoring=!0,this._container=t,this._ctrl.hass=e;try{const t=await wi(e,i);if(a=t.topology,s=Hn(a,t.panelSize),!s)throw new Error(n("card.topology_error"))}catch(e){return t.innerHTML=`

${Ft(Jt(e))}

`,null}this._ctrl.init(a,r,e,o??null),await this._ctrl.monitoringCache.fetch(e,o??null),await this._ctrl.fetchAndBuildHorizonMaps();const l=function(t){return Fn(t.last)-Fn(t.first)+1}(s),c=this._ctrl.monitoringCache.status,d=Ni(a,r),u=function(t){if(!t)return"";const e=Object.values(t.circuits??{}),i=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(),...i],a=o.flatMap(t=>null!=t.utilization_pct?[He(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 ✓ ${n("status.monitoring")} · ${e.length} ${n("status.circuits")} · ${i.length} ${n("status.mains")}\n \n ${s>0?`${s} ${n(s>1?"status.warnings":"status.warning")}`:""}\n ${l>0?`${l} ${n(l>1?"status.alerts":"status.alert")}`:""}\n ${c>0?`${c} ${n(c>1?"status.overrides":"status.override")}`:""}\n \n
\n `}(c),h=function(t,e,n,i,r){const o=new Map,a=new Set;for(const{uuid:e,circuit:n,members:i}of we(t)){if($n(n))continue;const t=n.tabs;if(!t||0===t.length)continue;const r=Math.min(...t),s=1===t.length?"single":Vn(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=Fn(Math.max(...n));0===Bn(t)?s.add(i):l.add(i)}function c(e){return{monInfo:Oe(r,e.circuit),sheddingPriority:ri(e.circuit,n),access:on(t,e.uuid)}}const d=t=>t>=e.first&&t<=e.last,u=Fn(e.first),h=Fn(e.last);let p="";for(let t=u;t<=h;t++){const e=t-u+1,r=2*t-1,h=2*t,f=o.get(r),g=o.get(h),m=d(r)?`
${r}
`:"",v=d(h)?`
${h}
`:"";if(p+=m,f&&"row-span"===f.layout){const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=Wi(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)&&d(r)&&(p+=Ui(e,"2"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=Wi(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)&&d(h)&&(p+=Ui(e,"4"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(g);p+=Wi(g.uuid,g.circuit,e,"4",g.layout,n,i,t,r,o,g.members)}p+=v}return p}(a,s,e,r,c),p=Qi(a,e,r,{showFavorites:this._ctrl.showFavorites}),f=Ki(a,e,r);t.innerHTML=`\n \n ${d}\n ${u}\n ${p?`
${p}
`:""}\n ${f}\n ${!1!==r.show_panel?`\n
\n ${h}\n
\n `:""}\n \n `,this._onGearClick=e=>{this._ctrl.onGearClick(e,t)},this._onToggleClick=e=>{this._ctrl.onToggleClick(e,t)},t.addEventListener("click",this._onGearClick),t.addEventListener("click",this._onToggleClick),this._onSidePanelClosed=()=>{this._ctrl.monitoringCache.invalidate(),this._ctrl.graphSettingsCache.invalidate()},t.addEventListener("side-panel-closed",this._onSidePanelClosed),this._onGraphSettingsChanged=()=>this._ctrl.onGraphSettingsChanged(t),t.addEventListener("graph-settings-changed",this._onGraphSettingsChanged);try{await this._ctrl.loadHistory()}catch{}this._ctrl.updateDOM(t);const g=t.querySelector(".slide-confirm");return g&&(this._ctrl.bindSlideConfirm(g,t),t.classList.add("switches-disabled")),this._ctrl.setupResizeObserver(t,t),this._ctrl.startIntervals(t),this._foldUnobserve&&this._foldUnobserve(),this._foldUnobserve=DI(t,{rowSelector:".circuit-slot",nameSelector:".circuit-name",foldClass:"is-folded"}),a}invalidateMonitoring(){this._ctrl.monitoringCache.invalidate()}async refreshSidePanel(t,e,n=null){this._container&&await this._ctrl.refreshCircuitSidePanel(this._container,t,e,n)}refreshSidePanelControlAccess(t,e){this._container&&this._ctrl.refreshCircuitControlAccess(this._container,t,e)}stop(){this._ctrl.stopIntervals(),this._foldUnobserve&&(this._foldUnobserve(),this._foldUnobserve=null),this._container&&(this._onGearClick&&(this._container.removeEventListener("click",this._onGearClick),this._onGearClick=null),this._onToggleClick&&(this._container.removeEventListener("click",this._onToggleClick),this._onToggleClick=null),this._onSidePanelClosed&&(this._container.removeEventListener("side-panel-closed",this._onSidePanelClosed),this._onSidePanelClosed=null),this._onGraphSettingsChanged&&(this._container.removeEventListener("graph-settings-changed",this._onGraphSettingsChanged),this._onGraphSettingsChanged=null))}}const RI="\n display:flex;align-items:center;gap:8px;margin-bottom:8px;\n",NI="var(--divider-color)",OI=`\n background:var(--secondary-background-color,#333);\n border:1px solid ${NI};\n color:var(--primary-text-color);\n border-radius:4px;padding:6px 10px;width:80px;font-size:0.85em;\n`,zI="\n min-width:130px;font-size:0.85em;color:var(--secondary-text-color);\n",$I="\n min-width:160px;font-size:0.85em;color:var(--secondary-text-color);\n",HI="\n background:var(--secondary-background-color,#333);\n border:1px solid var(--divider-color);\n color:var(--primary-text-color);\n border-radius:4px;padding:6px 10px;flex:1;font-size:0.85em;\n font-family:monospace;\n",FI=`\n background:var(--secondary-background-color,#333);\n border:1px solid ${NI};\n color:var(--primary-text-color);\n border-radius:3px;padding:3px 6px;width:50px;font-size:0.8em;\n text-align:center;\n`,BI="var(--error-color,#f44336)",VI="\n background:none;border:1px solid var(--divider-color);color:var(--primary-text-color);\n border-radius:4px;padding:3px 6px;cursor:pointer;font-size:0.75em;\n";let jI=0;function qI(t){return jI+=1,`span-monitoring-${t}-${jI}`}const WI=[["continuous_threshold_pct","#g-continuous"],["spike_threshold_pct","#g-spike"],["window_duration_m","#g-window"],["cooldown_duration_m","#g-cooldown"]];function UI(t){const e=document.createElement("div");e.id=qI("feedback"),e.setAttribute("aria-live","polite"),e.style.cssText="\n font-size:0.75em;color:var(--error-color,#f44336);\n max-width:10em;white-space:normal;line-height:1.3;\n";const n=t.getAttribute("aria-describedby");return t.setAttribute("aria-describedby",n?`${n} ${e.id}`:e.id),t.parentElement?.appendChild(e),n=>{e.textContent=n??"",t.style.borderColor=n?BI:NI}}const GI=["reset-btn","circuit-toggle","mains-toggle","rating-clear","rating-turn-off"],XI="other_breaker",YI=["[id]",".threshold-input",".rating-input",...GI.map(t=>`.${t}`)].join(", "),ZI={"reset-btn":t=>QI(t,"continuous_threshold_pct"),"rating-clear":t=>QI(t,XI),"rating-turn-off":t=>JI("circuit-toggle",t)};function KI(t){if(t.id)return`#${t.id}`;const{entity:e,field:n}=t.dataset;if(void 0===e)return null;if(t.classList.contains("threshold-input"))return void 0!==n?QI(e,n):null;if(t.classList.contains("rating-input"))return QI(e,XI);const i=tP(t);return i?JI(i,e):null}function QI(t,e){return`${t}\0${e}`}function JI(t,e){return`${t}\0${e}`}function tP(t){return GI.find(e=>t.classList.contains(e))}const eP=["one_space","two_spaces"],nP=["applies","pending","averaged_legs"];function iP(t,e){return null===t||e.some(e=>e===t)}function rP(t){const{package_ratings_form:e,package_ratings_state:n,...i}=t,r=i;return iP(e,eP)&&(r.package_ratings_form=e),iP(n,nP)&&(r.package_ratings_state=n),r}function oP(t){if(!t||"object"!=typeof t)return;const e={};for(const[n,i]of Object.entries(t))i&&"object"==typeof i&&(e[n]=rP(i));return e}const aP={continuous_threshold_pct:"monitoring.continuous",spike_threshold_pct:"monitoring.spike",window_duration_m:"monitoring.window",cooldown_duration_m:"monitoring.cooldown"};function sP(t,e,r,o,a,s){const{min:l,max:c}=he[r];return`\n ${a}\n `}function lP(t,e){const i=Yt(t);return`${Kt({...i,userSet:!e&&i.userSet})||`${Ft(n("monitoringRating.none"))}`}`}function cP(t,e){const{package_ratings_form:n,breaker_rating_a:i,point_id:r}=t;return e&&n&&null!=i&&"string"==typeof r?{circuitId:r,panelA:i,ratings:t.package_ratings_a??null}:null}function dP(t){return t.ratings?.[1]??null}function uP(t){return"averaged_legs"===t?n("monitoringRating.averaged_legs"):"own"===t?i("monitoringRating.table_threshold_warning",{reset:n("monitoring.reset")}):i("monitoringRating.table_threshold_warning_global",{settings:n("monitoring.global_settings")})}function hP(t,e){t.addEventListener("click",async()=>{"true"!==t.getAttribute("aria-disabled")&&(t.setAttribute("aria-disabled","true"),t.style.opacity="0.6",await e()||(t.removeAttribute("aria-disabled"),t.style.opacity=""))})}const pP="event_bus",fP=[{type:"device"},{type:"entity"}];function gP(t){return t.length?t.map(t=>t===pP?n("notification.event_bus_target"):t).join(", "):n("notification.none_selected")}function mP(t){return i("notification.targets_button",{targets:t})}function vP(t,e){t.textContent=`${n("error.prefix")} ${e}`,t.style.color="var(--error-color, #f44336)"}const _P="0.4";function yP(t,e,n){t.isConnected&&(e&&t.toggleAttribute("checked",n),t.checked=t.hasAttribute("checked"))}function bP(t,e,n){if(!t.isConnected)return;yP(t,e,n);const i=t.closest("tr");i&&(i.style.opacity=t.checked?"":_P)}function xP(t,e,n){return t.querySelector(`.${e}[data-entity="${Gi(n)}"]`)}function wP(t,e){const n=[...e.querySelectorAll(".circuit-toggle, .mains-toggle")],i=n.length>0&&n.every(t=>t.checked);t.toggleAttribute("checked",i),t.checked=i,t.indeterminate=!i&&n.some(t=>t.checked)}function SP(t,e,n,i){if(!e.isConnected)return;bP(e,n,i);const r=t.querySelector("#toggle-all-circuits");r&&wP(r,t)}class CP{static of(t){let e=CP._watches.get(t);return e||(e=new CP(t),CP._watches.set(t,e)),e}constructor(t){this._pressed=!1,this._waiting=[],t.addEventListener("pointerdown",()=>this._press(),!0)}settled(){return this._pressed?new Promise(t=>this._waiting.push(t)):Promise.resolve()}_press(){this._pressed=!0;const t=setTimeout(()=>e(),3e3),e=()=>{clearTimeout(t),window.removeEventListener("pointerup",e,!0),window.removeEventListener("pointercancel",e,!0),setTimeout(()=>this._release(),0)};window.addEventListener("pointerup",e,!0),window.addEventListener("pointercancel",e,!0)}_release(){this._pressed=!1;for(const t of this._waiting.splice(0))t()}}CP._watches=new WeakMap;class kP{constructor(){this._timer=null,this._send=null}schedule(t,e){this._clear(),this._send=t,this._timer=setTimeout(()=>{this.flush().catch(()=>{})},e)}flush(){const t=this._send;return this._clear(),t?t():Promise.resolve()}_clear(){this._timer&&clearTimeout(this._timer),this._timer=null,this._send=null}}const MP=Promise.resolve(new Map);function TP(t,e,n){return n.get(t)||e.name||t}class AP{constructor(){this.errorStore=null,this._pendingSaves=new Map,this._circuitLabels=MP,this._epoch=0,this._renderSeq=0,this._drawn=null,this._statusFailure=null,this._configEntryId=null,this._notifyCloseHandler=null,this._headerHTML=""}stop(){this._epoch+=1,this._statusFailure=null,this._notifyCloseHandler&&(document.removeEventListener("click",this._notifyCloseHandler),this._notifyCloseHandler=null),this._flushPendingSaves().catch(()=>{})}async render(t,e,r,o,a=""){const l=void 0===r||r===this._configEntryId;l||(this._statusFailure=null),void 0!==r&&(this._configEntryId=r),void 0!==o?this._circuitLabels=function(t){return Promise.resolve(t).then(ze,t=>(console.warn("SPAN Panel: no topology to label the Monitoring tab's circuits by:",Jt(t)),new Map))}(o):l||(this._circuitLabels=MP);const c=this._circuitLabels;this._headerHTML=a,this._notifyCloseHandler&&(document.removeEventListener("click",this._notifyCloseHandler),this._notifyCloseHandler=null);const d=this._epoch,u=++this._renderSeq;await this._flushPendingSaves().catch(()=>{});let h=null,p=!1;try{const t={};this._configEntryId&&(t.config_entry_id=this._configEntryId);const n=await e.callWS({type:"call_service",domain:s,service:"get_monitoring_status",service_data:t,return_response:!0});h=function(t){if(!t||"object"!=typeof t)return null;const e=t,n={};"boolean"==typeof e.enabled&&(n.enabled=e.enabled),"boolean"==typeof e.monitoring_rating_offered&&(n.monitoring_rating_offered=e.monitoring_rating_offered),e.global_settings&&"object"==typeof e.global_settings&&(n.global_settings=e.global_settings);const i=oP(e.circuits);i&&(n.circuits=i);const r=oP(e.mains);return r&&(n.mains=r),n}(n?.response)}catch(t){console.warn("SPAN Panel: monitoring status fetch failed",t),p=!0}const f=await c;if(d!==this._epoch||u!==this._renderSeq)return;if(await CP.of(t).settled(),d!==this._epoch||u!==this._renderSeq)return;if(p)return void this._showReadFailure(t,l);const g=h?.global_settings??{},m=!0===h?.enabled,v=h?.circuits??{},_=h?.mains??{},y=new Set;for(const t of Object.keys(e.states||{}))t.startsWith("notify.")&&y.add(t);const b=new Set(["notify","send_message"]);for(const t of Object.keys(e.services?.notify||{}))b.has(t)||y.add(`notify.${t}`);y.add(pP);const x=[...y].sort(),w=g.notify_targets??"",S=("string"==typeof w?w.split(","):w).map(t=>t.trim()).filter(Boolean),C=x.length>0&&x.every(t=>S.includes(t)),k=g.notification_title_template??"SPAN: {name} {alert_type}",M=g.notification_message_template??"{name} at {current_a}A ({utilization_pct}% of {breaker_rating_a}A rating)",T=g.notification_priority??"default",A=new Map(Object.entries(v).map(([t,e])=>[t,TP(t,e,f)])),I=t=>A.get(t)??t,P=Object.entries(v).sort(([t],[e])=>I(t).localeCompare(I(e))),D=Object.entries(_),L=[...P,...D],E=L.length>0&&L.every(([,t])=>Wt(t)),R=L.some(([,t])=>Wt(t)),N=!0===h?.monitoring_rating_offered,O=new Map;for(const[t,e]of P){const n=cP(e,N);n&&O.set(t,n)}const z=new Map,$=new Map,H=P.map(([t,e])=>{const r=I(t),o=Ft(r),a=Wt(e),s=!0===e.has_override,l=a?"":`opacity:${_P};`,c=Ft(t),d=O.get(t)??null,u=d?Xt(e,e):null,h=u?{warning:u,textId:qI("warning")}:null;u&&(z.set(t,u),$.set(t,r));const p="own"===h?.warning?` aria-describedby="${h.textId}"`:"";return`\n \n \n \n \n ${d?function(t,e,n,r,o){const a="applies"===n.package_ratings_state?qt(n):null,s=i("monitoringRating.panel_plus",{panel:String(r.panelA)}),l=qI("panel-rating"),c=i("monitoringRating.other_breaker_label",{circuit:e}),d=o?`${l} ${o}`:l,u=a?`${Ft(i("monitoringRating.judged_equals",{rating:String(a)}))}`:"",h=r.ratings?``:"";return`\n ${Ft(s)}\n \n ${u}\n ${h}\n `}(c,r,e,d,h?.textId??null):lP(e,!1)}\n ${sP(c,r,"continuous_threshold_pct",e.continuous_threshold_pct,"%","circuit")}\n ${sP(c,r,"spike_threshold_pct",e.spike_threshold_pct,"%","circuit")}\n ${sP(c,r,"window_duration_m",e.window_duration_m,"m","circuit")}\n ${sP(c,r,"cooldown_duration_m",e.cooldown_duration_m,"m","circuit")}\n \n ${s?``:""}\n \n \n ${h?function(t,e,r,o){const a=n("monitoringRating.turn_off_monitoring"),s="averaged_legs"===r?``:"";return`\n \n
${Ft(uP(r))}${s}
\n \n `}(c,r,h.warning,h.textId):""}\n `}).join(""),F=Object.entries(_).map(([t,e])=>{const r=e.name??t,o=Ft(r),a=Wt(e),s=!0===e.has_override,l=a?"":`opacity:${_P};`,c=Ft(t);return`\n \n \n \n \n ${lP(e,!0)}\n ${sP(c,r,"continuous_threshold_pct",e.continuous_threshold_pct,"%","mains")}\n ${sP(c,r,"spike_threshold_pct",e.spike_threshold_pct,"%","mains")}\n ${sP(c,r,"window_duration_m",e.window_duration_m,"m","mains")}\n ${sP(c,r,"cooldown_duration_m",e.cooldown_duration_m,"m","mains")}\n \n ${s?``:""}\n \n \n `}).join(""),B=l?function(t){const e=ce(t),n=e?KI(e):null;if(!e||null===n)return null;const i=e.dataset.entity,r=tP(e),o=void 0!==r&&void 0!==i?ZI[r]?.(i):void 0;return{keys:void 0!==o?[n,o]:[n],draft:e instanceof HTMLInputElement&&e.value!==e.defaultValue?e.value:null}}(t):null,{drawing:V,overTable:j}=this._drawingIn(t);V.content.innerHTML=`\n ${this._headerHTML}\n
\n

${n("monitoring.heading")}

\n\n
\n
\n

${n("monitoring.global_settings")}

\n \n
\n\n
\n
\n ${n("monitoring.continuous")}\n \n
\n
\n ${n("monitoring.spike")}\n \n
\n
\n ${n("monitoring.window")}\n \n
\n
\n ${n("monitoring.cooldown")}\n \n
\n\n
\n

${n("notification.heading")}

\n\n
\n ${n("notification.targets")}\n \n
\n \n
\n ${0===x.length?`
${n("notification.no_targets")}
`:x.map(t=>{const i=S.includes(t);return``}).join("")}\n
\n
\n
\n\n
\n ${n("notification.priority")}\n \n \n ${"critical"===T?n("notification.hint.critical"):"time-sensitive"===T?n("notification.hint.time_sensitive"):"passive"===T?n("notification.hint.passive"):"active"===T?n("notification.hint.active"):""}\n \n
\n\n
\n ${n("notification.title_template")}\n \n
\n\n
\n ${n("notification.message_template")}\n \n
\n\n
\n ${n("notification.placeholders")} {name} {entity_id} {alert_type}\n {current_a} {breaker_rating_a} {threshold_pct}\n {utilization_pct} {window_m} {local_time}\n
\n
\n ${n("notification.event_bus_help")} span_panel_current_alert\n ${n("notification.event_bus_payload")} alert_source alert_id\n alert_name alert_type current_a\n breaker_rating_a threshold_pct utilization_pct\n panel_serial window_duration_s local_time\n
\n\n
\n ${n("notification.test_label")}\n \n \n
\n
\n\n
\n
\n\n

${n("monitoring.monitored_points")}

\n ${N?function(){const t=t=>`

${t}

`,e=e=>t(Ft(e)),r=`${Ft(n("monitoringRating.note_guide"))}`,o=[n("monitoringRating.note_step_find"),i("monitoringRating.note_step_enter",{column:n("monitoring.rating")}),n("monitoringRating.note_step_single")].map(t=>`
  • ${Ft(t)}
  • `).join("");return`
    \n

    ${Ft(n("monitoringRating.note_title"))}

    \n ${e(n("monitoringRating.note_problem"))}\n ${e(n("monitoringRating.note_steps"))}\n
      ${o}
    \n ${e(n("monitoringRating.note_judged"))}\n ${e(i("monitoringRating.note_thresholds",{reset:n("monitoring.reset")}))}\n ${e(n("monitoringRating.note_two_spaces"))}\n ${t(r)}\n
    `}():""}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ${F}\n ${H}\n \n
    ${n("monitoring.col.name")}${n("monitoring.rating")}${n("monitoring.col.continuous")}${n("monitoring.col.spike")}${n("monitoring.col.window")}${n("monitoring.col.cooldown")}
    \n \n
    \n
    \n `;const q=V.content.querySelector(".monitoring-settings");q&&!Be(e)&&function(t){t.querySelector("h2")?.after(Ze()),Ye(t,".rating-user-set")}(q);const W=t.querySelector("#toggle-all-circuits");W&&!E&&R&&(W.indeterminate=!0);const U=t.querySelector("#notify-all-targets");if(U&&x.length>0){const t=S.length>0;!C&&t&&(U.indeterminate=!0)}this._bindGlobalControls(t,e),this._bindNotifyTargetSelect(t,e),this._bindNotificationSettings(t,e,T),this._bindToggleAll(t,e,v,_),this._bindCircuitToggles(t,e),this._bindMainsToggles(t,e),this._bindThresholdInputs(t,e),this._bindPackageRatings(t,e,O),this._bindTurnOffButtons(t,e),this._bindResetButtons(t,e),this._bindRatingMarks(t),function(t,e){if(!e)return;const n=[...t.querySelectorAll(YI)];for(const t of e.keys){const i=n.find(e=>KI(e)===t);if(i)return null!==e.draft&&i instanceof HTMLInputElement&&i.value!==e.draft&&(i.value=e.draft,i.dispatchEvent(new Event("input"))),void i.focus()}}(t,B),this._sayNewWarnings(V,j&&l,z,$),this._sayStatusFailure(t)}_showReadFailure(t,e){if(this.errorStore?.add({key:"fetch:monitoring",level:"warning",message:n("error.monitoring_failed"),persistent:!1}),e&&this._holdsDrawing(t))return void this._sayStatusFailure(t);const{drawing:i}=this._drawingIn(t);i.content.innerHTML=`\n ${this._headerHTML}\n
    \n

    ${n("monitoring.heading")}

    \n \n
    \n `,i.announcer.textContent="",this._drawn=null}_sayStatusFailure(t){const e=this._statusFailure,n=t.querySelector("#global-status");e&&e.entryId===this._configEntryId&&n&&(this._statusFailure=null,vP(n,e.message))}_holdsDrawing(t){const e=this._drawn;return e?.container===t&&2===t.childNodes.length&&t.firstChild===e.content&&t.lastChild===e.announcer}_drawingIn(t){const e=this._drawn;if(e&&this._holdsDrawing(t))return{drawing:e,overTable:!0};const n=document.createElement("div"),i=document.createElement("div");i.className="rating-announcer",i.setAttribute("aria-live","polite"),i.style.cssText="\n position:absolute;width:1px;height:1px;margin:-1px;padding:0;border:0;\n overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;\n",t.replaceChildren(n,i);const r={container:t,content:n,announcer:i,warnings:new Map};return this._drawn=r,{drawing:r,overTable:!1}}_sayNewWarnings(t,e,n,r){const o=t.warnings;t.warnings=n,e?function(t,e){return t.size===e.size&&[...t].every(([t,n])=>e.get(t)===n)}(o,n)||(t.announcer.textContent=function(t,e,n){return[...t].filter(([t,n])=>e.get(t)!==n).map(([t,e])=>i("monitoringRating.warning_announcement",{circuit:n.get(t)??t,warning:uP(e)})).join(" ")}(n,o,r)):t.announcer.textContent=""}async _redraw(t,e,n){n===this._epoch&&await this.render(t,e)}_serviceData(t){return this._configEntryId&&(t.config_entry_id=this._configEntryId),t}_callSetGlobal(t,e){return qe(t).setGlobalMonitoring(this._serviceData({...e}))}_saveOnPause(t,e,n){const i=this._serviceData({[e]:n});let r=this._pendingSaves.get(e);r||(r=new kP,this._pendingSaves.set(e,r)),r.schedule(async()=>{try{await qe(t).setGlobalMonitoring(i)}catch(t){throw Ue(this.errorStore,t,`${e} save`),t}},500)}async _flushPendingSaves(){await Promise.all([...this._pendingSaves.values()].map(t=>t.flush()))}_bindGlobalControls(t,e){const i=t.querySelector("#monitoring-enabled"),r=t.querySelector("#global-fields"),o=t.querySelector("#global-status"),a=(t,e,n)=>{t&&vP(t,null===e?n:Jt(e))},s=async i=>{const r=this._epoch;try{await this._callSetGlobal(e,i)}catch(t){return void a(o,t,n("error.failed_save"))}await this._redraw(t,e,r)},l=new Map;for(const[e,n]of WI){const i=t.querySelector(n);i&&l.set(e,me(i,e,{report:UI(i),save:t=>{s({[e]:t})}}))}const c=t=>{r&&(r.style.opacity=t?"":_P,r.style.pointerEvents=t?"":"none")};i&&i.addEventListener("change",async()=>{const r=this._epoch,s=this._configEntryId,d=i.checked;c(d);let u=!0;try{if(d){const t=(()=>{const t={};let e=!0;for(const[n]of WI){const i=l.get(n)?.check()??null;null===i?e=!1:t[n]=i}return e?t:null})();if(!t)return i.checked=!d,c(!d),void a(o,null,n("monitoring.enable_invalid"));await this._callSetGlobal(e,t)}else await this._callSetGlobal(e,{enabled:!1})}catch(t){u=!1,r===this._epoch&&(this._statusFailure={entryId:s,message:Jt(t)})}await this._redraw(t,e,r),yP(i,u,d),i.isConnected&&c(i.checked)})}_bindNotifyTargetSelect(t,e){const n=t.querySelector("#notify-target-btn"),i=t.querySelector("#notify-target-dropdown"),r=t.querySelector("#notify-target-label");if(!n||!i)return;n.addEventListener("click",t=>{t.stopPropagation();const e="none"!==i.style.display;i.style.display=e?"none":"block"});const o=e=>{const n=t.querySelector("#notify-target-select");n&&!n.contains(e.target)&&(i.style.display="none")};document.addEventListener("click",o),this._notifyCloseHandler=o;const a=()=>{const i=[...t.querySelectorAll(".notify-target-cb:checked")].map(t=>t.value),o=gP(i);r&&(r.textContent=o),n.setAttribute("aria-label",mP(o));const a=t.querySelector("#notify-all-targets");if(a){const e=[...t.querySelectorAll(".notify-target-cb")];a.checked=e.length>0&&e.every(t=>t.checked),a.indeterminate=!a.checked&&e.some(t=>t.checked)}this._saveOnPause(e,"notify_targets",i.join(", "))},s=t.querySelector("#notify-all-targets");s&&s.addEventListener("change",()=>{for(const e of t.querySelectorAll(".notify-target-cb"))e.checked=s.checked;const e=t.querySelector("#notify-target-btn");e&&(e.style.opacity=s.checked?"0.4":"",e.style.pointerEvents=s.checked?"none":""),s.checked&&(i.style.display="none"),a()});for(const e of t.querySelectorAll(".notify-target-cb"))e.addEventListener("change",()=>{a()})}_bindNotificationSettings(t,e,i){const r=t.querySelector("#g-priority"),o=t.querySelector("#g-title-template"),a=t.querySelector("#g-message-template");r&&r.addEventListener("change",async()=>{const n=this._epoch;try{await this._callSetGlobal(e,{notification_priority:r.value})}catch(t){return Ue(this.errorStore,t,"notification priority change"),void(r.value=i)}await this._redraw(t,e,n)}),o&&o.addEventListener("input",()=>{this._saveOnPause(e,"notification_title_template",o.value)}),a&&a.addEventListener("input",()=>{this._saveOnPause(e,"notification_message_template",a.value)});const s=t.querySelector("#test-notification-btn"),l=t.querySelector("#test-notification-status");s&&s.addEventListener("click",async()=>{s.disabled=!0,l&&(l.textContent=n("notification.test_sending"),l.style.color="var(--secondary-text-color)");try{const i=[...t.querySelectorAll(".notify-target-cb:checked")];this._saveOnPause(e,"notify_targets",i.map(t=>t.value).join(", ")),await this._flushPendingSaves(),await qe(e).testNotification(this._serviceData({})),l&&(l.textContent=n("notification.test_sent"),l.style.color="var(--success-color, #4caf50)")}catch(t){if(l){const e=Jt(t);l.textContent=`${n("error.prefix")} ${e}`,l.style.color="var(--error-color, #f44336)"}}finally{s.disabled=!1}})}_bindToggleAll(t,e,n,i){const r=t.querySelector("#toggle-all-circuits");r&&r.addEventListener("change",async()=>{const o=this._epoch,a=r.checked,s=qe(e),l=(t,e)=>t.then(()=>!0,t=>(Ue(this.errorStore,t,e),!1)),c=[...Object.keys(n).map(e=>({control:xP(t,"circuit-toggle",e),stored:l(s.setCircuitThreshold(this._serviceData({circuit_id:e,monitoring_enabled:a})),"circuit monitoring toggle")})),...Object.keys(i).map(e=>({control:xP(t,"mains-toggle",e),stored:l(s.setMainsThreshold(this._serviceData({leg:e,monitoring_enabled:a})),"mains monitoring toggle")}))],d=await Promise.all(c.map(async({control:t,stored:e})=>({control:t,stored:await e})));if(await this._redraw(t,e,o),r.isConnected){for(const{control:t,stored:e}of d)t&&bP(t,e,a);wP(r,t)}})}_bindMainsToggles(t,e){for(const n of t.querySelectorAll(".mains-toggle"))n.addEventListener("change",async()=>{const i=this._epoch,r=n.dataset.entity,o=n.checked;let a=!0;try{await qe(e).setMainsThreshold(this._serviceData({leg:r,monitoring_enabled:o}))}catch(t){Ue(this.errorStore,t,"mains threshold toggle"),a=!1}await this._redraw(t,e,i),SP(t,n,a,o)})}_bindCircuitToggles(t,e){for(const n of t.querySelectorAll(".circuit-toggle")){const i=n.dataset.entity;void 0!==i&&n.addEventListener("change",async()=>{const r=n.checked;SP(t,n,await this._setCircuitMonitoring(t,e,i,r),r)})}}_bindTurnOffButtons(t,e){for(const n of t.querySelectorAll(".rating-turn-off")){const i=n.dataset.entity;void 0!==i&&hP(n,async()=>{const r=await this._setCircuitMonitoring(t,e,i,!1);return r&&n.isConnected&&this._settleTurnedOff(t,n,i),r})}}_settleTurnedOff(t,e,n){const i=xP(t,"circuit-toggle",n);i&&SP(t,i,!0,!1);const r=e.closest(".rating-warning-row"),o=le(r);r?.remove(),o&&i?.focus();const a=this._drawn;if(a?.container===t&&a.warnings.has(n)){const t=new Map(a.warnings);t.delete(n),a.warnings=t}}async _setCircuitMonitoring(t,e,n,i){const r=this._epoch;let o=!0;try{await qe(e).setCircuitThreshold(this._serviceData({circuit_id:n,monitoring_enabled:i}))}catch(t){Ue(this.errorStore,t,"circuit threshold toggle"),o=!1}return await this._redraw(t,e,r),o}_bindThresholdInputs(t,e){for(const n of t.querySelectorAll(".threshold-input")){const i=n.dataset.field,r=n.dataset.entity;if(!fe(i)||void 0===r)continue;const o="mains"===n.dataset.type;me(n,i,{report:UI(n),save:a=>{this._saveThreshold(t,e,n,t=>o?t.setMainsThreshold(this._serviceData({leg:r,[i]:a})):t.setCircuitThreshold(this._serviceData({circuit_id:r,[i]:a})))}})}}async _saveThreshold(t,e,n,i){const r=this._epoch;try{await i(qe(e))}catch(t){return Ue(this.errorStore,t,"threshold input save"),void(n.style.borderColor=BI)}await this._redraw(t,e,r)}_bindPackageRatings(t,e,n){for(const i of t.querySelectorAll(".rating-input")){const r=i.dataset.entity,o=void 0!==r?n.get(r):void 0;if(!o)continue;const a=ve(i,{report:UI(i),stored:()=>dP(o),save:n=>{this._savePackageRatings(t,e,i,a,o,n)}}),s=i.closest("td")?.querySelector(".rating-clear");s&&hP(s,()=>(a.revert(),this._clearPackageRatings(t,e,o)))}}async _savePackageRatings(t,e,n,i,r,o){const a=this._epoch;try{await qe(e).setCircuitPackageRatings(this._serviceData({circuit_id:r.circuitId,package_ratings_a:[r.panelA,o]}))}catch(t){return _e(e,this.errorStore,t),void(i.answerRefusal(o)&&n.isConnected&&de()&&n.focus())}await this._redraw(t,e,a)}async _clearPackageRatings(t,e,n){const i=this._epoch;try{await qe(e).clearCircuitPackageRatings(this._serviceData({circuit_id:n.circuitId}))}catch(t){return _e(e,this.errorStore,t),!1}return await this._redraw(t,e,i),!0}_bindRatingMarks(t){for(const e of t.querySelectorAll(".rating-user-set"))e.addEventListener("click",()=>Qt(e))}_bindResetButtons(t,e){for(const i of t.querySelectorAll(".reset-btn")){const r=i.dataset.entity;if(!r)continue;const o="mains"===i.dataset.type;hP(i,async()=>{const i=this._epoch,a=qe(e);try{await(o?a.clearMainsThreshold(this._serviceData({leg:r})):a.clearCircuitThreshold(this._serviceData({circuit_id:r})))}catch(t){return console.warn("SPAN Panel: threshold reset failed",t),oe(e,t,s,n("error.threshold_failed")).then(t=>{this.errorStore?.add({key:"service:monitoring",level:"error",message:t,persistent:!1})}),!1}return await this._redraw(t,e,i),!0})}}}function IP(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function PP(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)=>PP(t,e[n]));if(!IP(t)||!IP(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=>PP(t[n],e[n]))}function DP(t,e){return null!==t&&t.toLowerCase().includes(e)}function LP(t,e){const n=t[e];return"string"==typeof n?n:""}function EP(t,e){return{enabled:null!==e&&null===e.disabledBy,name:null===e?"":e.name,deviceClass:t.curation.device_class??"",stateClass:t.curation.state_class??"",promote:"none"===t.curation.entity_category}}function RP(t,e){const n=Number(e);return{unit_of_measurement:t||null,display_precision:""!==e&&Number.isFinite(n)?n:null}}function NP(t,e,n){return""!==t&&e.includes(t)&&n.length>0}function OP(t){if(!t)return"";const e=t.replace(/_/g," ");return e.charAt(0).toUpperCase()+e.slice(1)}const zP=["0","1","2","3","4","5","6"],$P="var(--secondary-text-color,#999)",HP="var(--primary-color,#4dd9af)",FP="var(--warning-color,#ff9800)",BP="var(--card-background-color,#1c1c1c)",VP="var(--secondary-background-color,#232323)",jP="var(--divider-color,#333)",qP=`background:${VP};border:1px solid ${jP};color:var(--primary-text-color);border-radius:4px;padding:4px 8px;font-size:0.85em;`,WP=`${qP}min-width:0;`,UP="display:flex;align-items:center;gap:12px;flex-wrap:wrap;",GP=`font-size:0.85em;color:${$P};min-width:130px;`,XP=`color:${$P};font-size:0.75em;`,YP=`background:none;border:1px solid ${jP};color:var(--primary-text-color);border-radius:6px;padding:6px 12px;font-size:0.8em;cursor:pointer;`;function ZP(t,e){const n=e?HP:$P;return`${Ft(t)}`}function KP(t,e,n){const i=e.map(t=>``).join("");return``}function QP(t){return"total_increasing"===t?n("adopted.warn_total_increasing"):"statistics_removed"===t?n("adopted.warn_statistics_removed"):t}class JP{constructor(){this._container=null,this._hass=null,this._deviceId=null,this._groups=[],this._loadError=null,this._query="",this._expandedKey=null,this._editor=null,this._unitsCache=new Map,this._refreshTimer=null,this._onClick=t=>{this._handleClick(t)},this._onInput=t=>{this._handleInput(t)},this._onChange=t=>{this._handleChange(t)}}stop(){this._refreshTimer&&(clearTimeout(this._refreshTimer),this._refreshTimer=null),this._unbind()}async render(t,e,n){const i=void 0===n?this._deviceId:n||null;i!==this._deviceId&&(this._deviceId=i,this._expandedKey=null,this._editor=null,this._query=""),this._unbind(),this._container=t,this._hass=e,"stale"!==this._adoptList(await this._fetchList(e),!1)&&this._paint()}async refresh(){const t=this._hass;t&&this._container&&"changed"===this._adoptList(await this._fetchList(t),!0)&&this._paintGroups()}async _fetchList(t){const e=this._deviceId;if(!e)return{deviceId:e,groups:[],error:null};try{const n=await t.callWS({type:`${s}/adopted/list`,device_id:e});return{deviceId:e,groups:Array.isArray(n?.devices)?n.devices:[],error:null}}catch(t){return{deviceId:e,groups:[],error:Jt(t)}}}_adoptList(t,e){if(t.deviceId!==this._deviceId)return"stale";if(null!==t.error&&e)return"unchanged";const n=t.error!==this._loadError||!PP(t.groups,this._groups);return this._groups=t.groups,this._loadError=t.error,n?"changed":"unchanged"}async _fetchSeed(t,e){try{return function(t){if(!t||"object"!=typeof t)return null;const e=t;if("string"!=typeof e.entity_id)return null;const n=e.options&&"object"==typeof e.options?e.options:{},i=n.sensor&&"object"==typeof n.sensor?n.sensor:{},r=i.display_precision;return{disabledBy:"string"==typeof e.disabled_by?e.disabled_by:null,name:LP(e,"name"),unit:LP(i,"unit_of_measurement"),precision:"number"==typeof r?String(r):""}}(await t.callWS({type:"config/entity_registry/get",entity_id:e}))}catch{return null}}async _fetchUnits(t,e){if(!e)return[];const n=this._unitsCache.get(e);if(n)return n;try{const n=await t.callWS({type:"sensor/device_class_convertible_units",device_class:e}),i=Array.isArray(n?.units)?n.units.filter(t=>"string"==typeof t):[];return this._unitsCache.set(e,i),i}catch{return[]}}_findRow(t){for(const e of this._groups)for(const n of e.rows)if(n.key===t)return n;return null}_paint(){const t=this._container;t&&(t.innerHTML=`\n
    \n

    ${n("adopted.heading")}

    \n

    ${n("adopted.description")}

    \n\n
    \n \n \n
    \n\n
    ${this._groupsHTML()}
    \n
    \n `,this._bind())}_paintGroups(){const t=this._container?.querySelector("#adopted-groups");t&&(t.innerHTML=this._groupsHTML())}_groupsHTML(){if(null!==this._loadError)return`

    ${Ft(n("adopted.load_failed"))} — ${Ft(this._loadError)}

    `;if(0===this._groups.length)return`

    ${n("adopted.none")}

    `;const t=function(t,e){const n=e.trim().toLowerCase();if(!n)return t;const i=[];for(const e of t){if(DP(e.name,n)){i.push(e);continue}const t=e.rows.filter(t=>DP(t.name,n));t.length>0&&i.push({...e,rows:t})}return i}(this._groups,this._query);return 0===t.length?`

    ${n("adopted.no_results")}

    `:t.map(t=>this._groupHTML(t)).join("")}_groupHTML(t){const e=t.adopted_device?ZP(n("adopted.adopted_device"),!1):ZP(n("adopted.vendor_readings"),!0),r=i("adopted.count",{count:String(t.rows.length)}),o=t.adopted_device?`${n("adopted.via_panel")} · ${r}`:r;return`\n
    \n ${Ft(t.name??"")}\n ${e}\n ${Ft(o)}\n
    \n
    \n ${t.rows.map(t=>this._rowHTML(t)).join("")}\n
    \n `}_rowHTML(t){const e=this._expandedKey===t.key,i=e&&this._editor?this._editorHTML(t,this._editor):"",r=e?`display:flex;align-items:center;padding:12px 16px;gap:10px;background:${VP};border:1px solid ${jP};border-bottom-color:transparent;border-radius:8px 8px 0 0;cursor:pointer;`:`display:flex;align-items:center;padding:12px 16px;gap:10px;background:${BP};border:1px solid ${jP};border-radius:8px;cursor:pointer;`;return`\n
    \n
    \n ${Ft(t.name)}\n ${Ft(function(t){return t.unit?`${t.platform} · ${t.unit}`:t.platform}(t))}\n ${Object.keys(t.curation).length>0?ZP(n("adopted.curated"),!0):""}\n ${t.stale_fields.length>0?ZP(n("adopted.stale"),!1):""}\n ${function(t){return``}(e)}\n
    \n ${i}\n
    \n `}_editorHTML(t,e){const r=[];null!==e.seed?(r.push(this._enableHTML(e)),r.push(this._identityHTML(e))):r.push(`
    ${n("adopted.registry_unavailable")}
    `),t.allowed_device_classes.length>0&&r.push(this._deviceClassHTML(t,e)),t.allowed_state_classes.length>0&&r.push(this._stateClassHTML(t,e)),r.push(this._prominenceHTML(e)),null!==e.seed&&NP(e.form.deviceClass,t.allowed_device_classes,e.units)&&r.push(this._displayHTML(t,e)),t.stale_fields.length>0&&r.push(`
    ${Ft(i("adopted.stale_note",{fields:t.stale_fields.join(", ")}))}
    `),r.push(this._actionsHTML(e)),null!==e.confirm&&r.push(this._confirmHTML(t,e)),null!==e.error&&r.push(`
    ${Ft(e.error)}
    `);for(const t of e.notices)r.push(`
    ${Ft(t)}
    `);return r.push(`
    ${Ft(function(t){const e=[t.path,t.datatype];return t.unit&&e.push(t.unit),e.push(t.settable?n("adopted.settable"):n("adopted.read_only")),e.join(" · ")}(t))}
    `),`\n
    \n ${r.join("")}\n
    \n `}_enableHTML(t){const e=t.form.enabled,i=e?HP:$P;return`\n
    \n ${n("adopted.enable_entity")}\n \n ${n("adopted.enable_note")}\n
    \n `}_identityHTML(t){return`\n
    \n ${n("adopted.name")}\n \n
    \n `}_deviceClassHTML(t,e){const r=[{value:"",label:n("adopted.no_device_class")},...t.allowed_device_classes.map(t=>({value:t,label:OP(t)}))],o=t.unit?i("adopted.device_class_note",{unit:t.unit}):n("adopted.device_class_note_unitless");return`\n
    \n ${n("adopted.device_class")}\n ${KP("device_class",r,e.form.deviceClass)}\n ${Ft(o)}\n
    \n `}_stateClassHTML(t,e){const i=[{value:"",label:n("adopted.no_statistics")},...t.allowed_state_classes.map(t=>({value:t,label:OP(t)}))];return`\n
    \n ${n("adopted.statistics_class")}\n ${KP("state_class",i,e.form.stateClass)}\n ${n("adopted.statistics_note")}\n
    \n `}_prominenceHTML(t){const e=(t,e,n)=>``;return`\n
    \n ${n("adopted.prominence")}\n \n ${e("diagnostic",n("adopted.diagnostic"),!t.form.promote)}\n ${e("standard",n("adopted.standard"),t.form.promote)}\n \n
    \n `}_displayHTML(t,e){const i=[{value:"",label:t.unit?`${t.unit} — ${n("adopted.unit_as_published")}`:n("adopted.unit_as_published")},...e.units.map(t=>({value:t,label:t}))],r=[{value:"",label:n("adopted.precision_default")},...zP.map(t=>({value:t,label:t}))];return`\n
    \n ${n("adopted.display_unit")}\n ${KP("unit",i,e.unit)}\n ${n("adopted.precision")}\n ${KP("precision",r,e.precision)}\n
    \n `}_actionsHTML(t){const e=t.busy?" disabled":"";return`\n
    \n \n \n ${n("adopted.reload_note")}\n
    \n `}_confirmHTML(t,e){const r="clearing"===e.confirm,o=r?i("adopted.confirm_clearing_subject",{name:t.name}):i("adopted.confirm_setting",{name:t.name,value:OP(e.form.stateClass)}),a=n(r?"adopted.confirm_clearing":"adopted.confirm_total_increasing");return`\n
    \n
    \n \n ${n("adopted.confirm_heading")}\n
    \n

    ${Ft(o)}

    \n

    ${a}

    \n
    \n \n \n
    \n
    \n `}_bind(){const t=this._container;t&&(t.addEventListener("click",this._onClick),t.addEventListener("input",this._onInput),t.addEventListener("change",this._onChange))}_unbind(){const t=this._container;t&&(t.removeEventListener("click",this._onClick),t.removeEventListener("input",this._onInput),t.removeEventListener("change",this._onChange))}async _handleClick(t){const e=t.target;if(!e)return;const n=e.closest("[data-action]");if(n)return void await this._handleAction(n);const i=e.closest(".adopted-row-header"),r=i?.dataset.key;return r?this._expandedKey===r?(this._expandedKey=null,this._editor=null,void this._paintGroups()):void await this._openEditor(r):void 0}async _handleAction(t){const e=this._editor;if(e)switch(t.dataset.action){case"toggle-enable":return e.form={...e.form,enabled:!e.form.enabled},void this._paintGroups();case"prominence":return e.form={...e.form,promote:"standard"===t.dataset.value},void this._paintGroups();case"save":return void(e.busy||await this._save(!1));case"clear":return void(e.busy||await this._save(!0));case"confirm-cancel":return e.confirm=null,void this._paintGroups();case"confirm-save":{const t=e.confirmClears;return e.confirm=null,void await this._commit(t)}default:return}}_handleInput(t){const e=t.target;if(!e)return;if("adopted-filter"===e.id)return this._query=e.value,void this._paintGroups();const n=this._editor,i=e.dataset.field;if(!n||!i)return;const r=e.value;"name"===i&&(n.form={...n.form,name:r})}async _handleChange(t){const e=t.target,n=this._editor,i=e?.dataset.field;if(e&&n&&i)switch(i){case"device_class":return n.form={...n.form,deviceClass:e.value},n.units=this._hass?await this._fetchUnits(this._hass,e.value):[],void this._paintGroups();case"state_class":return void(n.form={...n.form,stateClass:e.value});case"unit":return void(n.unit=e.value);case"precision":return void(n.precision=e.value);default:return}}async _openEditor(t){const e=this._findRow(t),n=this._hass;if(!e||!n)return;this._expandedKey=t,this._editor={form:EP(e,null),seed:null,units:[],unit:"",precision:"",confirm:null,confirmClears:!1,busy:!0,error:null,notices:[]},this._paintGroups();const i=null===e.entity_id?null:await this._fetchSeed(n,e.entity_id);if(this._expandedKey!==t)return;const r=EP(e,i),o=await this._fetchUnits(n,r.deviceClass);this._expandedKey===t&&(this._editor={form:r,seed:i,units:o,unit:i?.unit??"",precision:i?.precision??"",confirm:null,confirmClears:!1,busy:!1,error:null,notices:[]},this._paintGroups())}async _save(t){const e=this._editor,n=null===this._expandedKey?null:this._findRow(this._expandedKey);if(!e||!n)return;const i=function(t,e){return"total_increasing"===e.stateClass?"total_increasing":t.curation.state_class&&""===e.stateClass?"clearing":null}(n,this._formFor(e,t));if(null!==i)return e.confirm=i,e.confirmClears=t,e.error=null,e.notices=[],void this._paintGroups();await this._commit(t)}_formFor(t,e){return e?{...t.form,deviceClass:"",stateClass:"",promote:!1}:t.form}async _commit(t){const e=this._editor,i=this._hass,r=null===this._expandedKey?null:this._findRow(this._expandedKey);if(!(e&&i&&r&&this._deviceId))return;const o=this._formFor(e,t),a=function(t,e){const n={};return e.deviceClass&&(n.device_class=e.deviceClass),e.stateClass&&(n.state_class=e.stateClass),e.promote&&(n.entity_category="none"),{registryUpdate:null===t.entity_id?null:{type:"config/entity_registry/update",entity_id:t.entity_id,name:e.name||null,disabled_by:e.enabled?null:"user"},curate:{key:t.key,record:n}}}(r,o);e.busy=!0,e.error=null,e.notices=[],this._paintGroups();let l=e.seed;try{const c=t||null===l?null:function(t,e,n){if(null===t.registryUpdate||null===e||!function(t,e){return null!==t&&(e.enabled!==(null===t.disabledBy)||e.name!==t.name)}(e,n))return null;const i={...t.registryUpdate};return function(t,e){return e.enabled===(null===t.disabledBy)}(e,n)&&delete i.disabled_by,i}(a,l,o);null!==c&&null!==l&&(await i.callWS(c),l=function(t,e){return{...t,disabledBy:e.enabled?null:t.disabledBy??"user",name:e.name}}(l,o),e.seed=l),!t&&null!==l&&null!==r.entity_id&&NP(o.deviceClass,r.allowed_device_classes,e.units)&&function(t,e,n){return null!==t&&(e!==t.unit||n!==t.precision)}(l,e.unit,e.precision)&&(await i.callWS({type:"config/entity_registry/update",entity_id:r.entity_id,options_domain:"sensor",options:RP(e.unit,e.precision)}),l={...l,unit:e.unit,precision:e.precision},e.seed=l);const d=await i.callWS({type:`${s}/adopted/curate`,device_id:this._deviceId,key:a.curate.key,record:a.curate.record});r.curation=d?.record??{},e.form=o,e.notices=[n("adopted.saved"),...Array.isArray(d?.warnings)?d.warnings.map(QP):[]]}catch(t){return e.error=Jt(t),e.busy=!1,void this._paintGroups()}e.busy=!1,this._paintGroups(),this._scheduleRefresh()}_scheduleRefresh(){this._refreshTimer&&clearTimeout(this._refreshTimer),this._refreshTimer=setTimeout(()=>{this._refreshTimer=null;const t=this._hass;t&&this._fetchList(t).then(t=>{"changed"===this._adoptList(t,!0)&&this._paintGroups()})},2e3)}}function tD(t=""){const e=t?` value="${Ft(t)}"`:"",i=t?"":"display:none;";return`\n
    \n \n \n
    \n `}function eD(t,e,i,r,o,a,s,l,c){const d=qn(e,i),u=ei(e,i),h=Ce([e]),p=Ft(e.name||n("grid.unknown")),f="current"===Oi(r).entityRole;let g;g=d?f?Di(Un(e,i)):Pi(Wn(e,i)):"";const m=ji(a||"unknown");let v="";const _=Yn(l,i,o);null!==_&&(v=`${Math.round(_)}%`);const y=``,b=$n(e)?"":"none"===u?`${d?"ON":"OFF"}`:Hi(d,u,c);return`\n
    \n ${h?`${h}`:""}\n ${v}\n ${p}\n ${m}\n ${b}\n \n ${g}\n \n ${y}\n \n
    \n `}function nD(t,e,n,i,r){const o=Xn(e,Wn(e,n)),a=jn(0,r,qn(e,n),o),s=Ft(t);return`\n
    \n
    \n
    \n
    \n
    \n `}function iD(t){return`
    ${Ft(t)}
    `}function rD(t,e,n){return{isOn:qn(t,e),value:"current"===(n.chart_metric||"power")?Un(t,e):Wn(t,e)}}function oD(t,e,n,i){const r=rD(t,n,i),o=rD(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 aD(t,e,n){return t.sort((t,i)=>oD(t[1],i[1],e,n))}class sD{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=aD(Object.entries(n.circuits),e,i),s=be(we(n));let l=o+tD(this._searchQuery);l+=`
    `;for(const[t,o]of a){const a=Oe(r,o),c=ri(o,e),d=this._expandedUuids.has(t);l+=`
    `,l+=eD(t,o,e,i,a,c,d,xe(o,s.get(t)),on(n,t)),d&&(l+=nD(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,i,r,o,a){this._unbindEvents(),this._hass=e,this._topology=i,this._config=r,this._monitoringStatus=o;const s=n("list.unassigned_area"),l=be(we(i)),c=new Map;for(const[t,e]of Object.entries(i.circuits)){const n=e.area??s,i=c.get(n);i?i.push([t,e]):c.set(n,[[t,e]])}const d=[...c.keys()].sort((t,e)=>t===s?1:e===s?-1:t.localeCompare(e));let u=a+tD(this._searchQuery);u+=`
    `;for(const t of d){const n=c.get(t);if(!n)continue;const a=aD(n,e,r);u+=iD(t);for(const[t,n]of a){const a=Oe(o,n),s=ri(n,e),c=this._expandedUuids.has(t);u+=`
    `,u+=eD(t,n,e,r,a,s,c,xe(n,l.get(t)),on(i,t)),c&&(u+=nD(t,n,e,0,a)),u+="
    "}}u+="
    ",u+="",t.innerHTML=u;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"===Oi(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}=rD(a,e,i),c=t.querySelector(".list-power-value");c&&(c.innerHTML=s?r?Di(l):Pi(l):""),Fi(t,s,ei(a,e),on(n,o)),qi(t,ri(a,e));const d=t.querySelector(".list-status-badge");d&&(d.textContent=s?"ON":"OFF",d.classList.toggle("list-status-on",s),d.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)=>oD(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=DI(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=Gi(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=Oe(this._monitoringStatus,e),o=nD(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 lD=["name","name_by_user"];function cD(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))}async function dD(t,e){const n={type:"config/device_registry/list"},i={type:"config_entries/get",domain:s},[r,o]=await Promise.all([e?e.callWS(t,n,{errorId:"fetch:devices"}):t.callWS(n),e?e.callWS(t,i,{errorId:"fetch:config_entries"}):t.callWS(i)]),a=new Set(o.map(t=>t.entry_id));return r.filter(t=>function(t,e){return void 0!==t.config_entry_id&&e.has(t.config_entry_id)&&!t.via_device_id&&!t.parent_device_id}(t,a))}function uD(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 hD(t,e,n){const i=t.connection;return i?i.subscribeEvents(t=>{(function(t){const e=uD(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=uD(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 pD(t){const e={...t};for(const t of Ke)delete e[t];return e}function fD(t){const e=Object.fromEntries(Object.entries(t.circuits).map(([t,e])=>[t,pD(e)]));return{...t,circuits:e}}function gD(t,e){return`${t}|${e}`}class mD{async build(t,e,n,i){const r=new Map;for(const t of n)r.set(t.id,t);const o=i?new De(i):null,a=[];for(const[n,i]of Object.entries(e)){if(!((i?.circuits?.length??0)>0||(i?.sub_devices?.length??0)>0))continue;const e=r.get(n);e&&a.push((async()=>{try{const i=await wi(t,n,o);return{panelDeviceId:n,panel:e,topology:i.topology}}catch(t){return console.warn("SPAN Panel: favorites topology fetch failed",n,t),{panelDeviceId:n,panel:e,topology:null}}})())}const s=(await Promise.all(a)).filter(t=>null!==t.topology),l=s.length>1,c={},d={},u={},h={},p=new Set,f=[];for(const{panelDeviceId:t,panel:n,topology:i}of s){if(!i)continue;const r=n.config_entry_id??null;r&&p.add(r);const o=n.name_by_user??n.name??i.device_name??"";f.push({panelDeviceId:t,panelName:o,topology:i});const a=e[t],s=a?.circuits??[],g=a?.sub_devices??[];for(const e of s){const n=i.circuits?.[e];if(!n)continue;const a=gD(t,e),s=l&&o?`${o} · ${n.name}`:n.name,u=n.shared_meter_group,p=u?gD(t,u):u,f=u?i.shared_meter_groups?.[u]:void 0;p&&f&&(d[p]={...f,members:f.members.map(e=>gD(t,e))}),c[a]={...n,name:s,shared_meter_group:p},h[a]={panelDeviceId:t,kind:"circuit",targetId:e,configEntryId:r,controlAccess:nn(i)}}for(const e of g){const n=i.sub_devices?.[e];if(!n)continue;const a=gD(t,e),s=l&&o&&n.name?`${o} · ${n.name}`:n.name??e;u[a]={...n,name:s},h[a]={panelDeviceId:t,kind:"sub_device",targetId:e,configEntryId:r}}}return{topology:{circuits:c,shared_meter_groups:d,sub_devices:u,panel_entities:{},device_name:"",_favoriteRefs:h},entryIds:Array.from(p),perPanelStats:f}}}const vD="span_panel_favorites_view_state";function _D(t){try{localStorage.setItem(vD,JSON.stringify(t))}catch{}}function yD(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 bD(t){let e=!1;return()=>{e||(e=!0,Promise.resolve().then(()=>{e=!1,t()}))}}var xD;const wD="favorites";function SD(t){return"dashboard"===t||"adopted"===t}let CD=xD=class extends At{constructor(){super(...arguments),this.narrow=!1,this._panels=[],this._selectedPanelId=null,this._activeTab="dashboard",this._discovered=!1,this._listColumns=Vt(),this._favorites={},this._favoritesViewState={expanded:{activity:[],area:[]}},this._favoritesPanelStats=[],this._dashboardTab=new EI,this._monitoringTab=new AP,this._adoptedTab=new JP,this._listDashCtrl=new PI,this._listCtrl=new sD(this._listDashCtrl),this._favCache=new xn,this._favCtrl=new mD,this._favoritesMonitoring=null,this._detaches=0,this._renderOnAttach=!1,this._errorStore=new $t,this._watchedPanelId=null,this._discovering=!1,this._refreshSeq=0,this._areaSub=null,this._areaTopology=null,this._reloadSub=null,this._ratingSubs=new Map,this._ratingRefreshes=new Map,this._ratingChangedIds=new Map,this._renderedTopologies=new Map,this._renderedView=null,this._favoritesWatchEntries=[],this._panelsRefresh=yD(()=>this._refreshPanels()),this._requestPanelsRefresh=bD(()=>{this._panelsRefresh()}),this._requestTabRender=bD(()=>{this._scheduleTabRender()}),this._onFavoritesChanged=null,this._deviceRegistryUnsub=null,this._renamedPanelIds=new Set,this._renameRefresh=yD(async()=>{const t=[...this._renamedPanelIds].filter(t=>this._renderedTopologies.has(t));this._renamedPanelIds.clear(),await Promise.all(t.map(t=>this._renderIfRestructured(t)))}),this._pendingTabRender=!1,this._persistFavoritesViewStateTimer=null,this._tabRenderScheduler=yD(async()=>this._renderTab()),this._beginRender=function(){let t=0;return()=>{t+=1;const e=t;return()=>t!==e}}()}get _root(){const t=this.shadowRoot;if(!t)throw new Error("span-panel: shadow root is not available");return t}connectedCallback(){super.connectedCallback(),this._dashboardTab.errorStore=this._errorStore,this._listDashCtrl.errorStore=this._errorStore,this._favCache.errorStore=this._errorStore,this._monitoringTab.errorStore=this._errorStore,this._onFavoritesChanged=()=>{this._refreshFavorites()},document.addEventListener(yn,this._onFavoritesChanged),this._subscribeDeviceRegistry(),this._subscribeEntryReloads(),this._syncRatingSubscriptions(),this._discovered&&(this._reapplyPanelStatusWatch(),"area"!==this._activeTab||this._isFavoritesView||this._subscribeAreaTab()),this._renderOnAttach&&(this._renderOnAttach=!1,this._requestTabRender())}disconnectedCallback(){this._dashboardTab.stop(),this._monitoringTab.stop(),this._adoptedTab.stop(),this._listCtrl.stop(),this._listDashCtrl.stopIntervals(),this._detaches+=1,this._stopFavoritesMonitoring(),this._unsubscribeAreaTab(),this._onFavoritesChanged&&(document.removeEventListener(yn,this._onFavoritesChanged),this._onFavoritesChanged=null),this._unsubscribeDeviceRegistry(),this._unsubscribeEntryReloads(),this._unsubscribeRatingChanges(),this._watchedPanelId=null,this._persistFavoritesViewStateTimer&&(clearTimeout(this._persistFavoritesViewStateTimer),this._persistFavoritesViewStateTimer=null),this._errorStore.dispose(),super.disconnectedCallback()}firstUpdated(){this.hass&&!this._discovered&&this._discoverPanels()}updated(t){if(t.has("hass")){const e=t.get("hass");this._dashboardTab.hass=this.hass,this._listDashCtrl.hass=this.hass,this._errorStore.updateHass(this.hass),this._discovered?this._root.getElementById("tab-content")?Be(e)!==Be(this.hass)&&this._monitoringAccessChanged():this._scheduleTabRender():this._discoverPanels(),!e&&this.hass&&(this._subscribeDeviceRegistry(),this._subscribeEntryReloads())}if((t.has("_panels")||t.has("hass"))&&this._syncRatingSubscriptions(),this._discovered&&(t.has("_discovered")||t.has("_activeTab")||t.has("_selectedPanelId")||t.has("_chartMetric")||t.has("_listColumns"))){if(this._isFavoritesView&&SD(this._activeTab))return void(this._activeTab="activity");this._scheduleTabRender()}if(t.has("_selectedPanelId")&&(this._selectedPanelId!==wD&&this._selectedPanelId?(this._updatePanelStatusWatch(),this._listDashCtrl.setFavoritesPerPanelInfo(null)):(this._errorStore.clearPanelStatusWatch(),this._watchedPanelId=null)),this._discovered&&(t.has("_panels")||t.has("_selectedPanelId"))){const t=this.shadowRoot?.getElementById("panel-select");t&&null!==this._selectedPanelId&&t.value!==this._selectedPanelId&&(t.value=this._selectedPanelId)}if(t.has("hass")&&this._discovered&&("activity"===this._activeTab||"area"===this._activeTab)){const t=this._root.getElementById("tab-content"),e=this._listDashCtrl.topology;if(t&&e){this._listCtrl.updateCollapsedRows(t,this.hass,e,this._buildDashboardConfig());const n=t.querySelector("span-side-panel");n&&(n.hass=this.hass,n.errorStore=this._errorStore)}}}_monitoringAccessChanged(){"monitoring"===this._activeTab&&this._scheduleTabRender();const t=this._root.getElementById("tab-content")?.querySelector("span-side-panel");t&&(t.hass=this.hass)}setConfig(t){}render(){var i,r,o;if(i=this.hass?.language,t=i&&e[i]?i:"en",!this.hass)return ct` -
    -
    -
    Span Panel
    -
    -
    -
    -
    ${n("card.connecting")}
    -
    - `;if(!this._discovered){const t=this._errorStore.hasPersistent("discovery-failed");return ct` + `,_([Lt({attribute:!1})],II.prototype,"options",void 0),_([Lt({attribute:!1})],II.prototype,"data",void 0),_([Lt({type:String})],II.prototype,"height",void 0);try{customElements.get("span-chart")||customElements.define("span-chart",II)}catch{}function PI(t,e,n,i,o,a,s,l,c){const{options:d,series:u}=function(t,e,n,i,o,a=!1){n||(n=h[r]);const s=i?"140, 160, 220":"77, 217, 175",l=`rgb(${s})`,c=Date.now(),d=c-e,u=void 0!==n.fixedMin&&void 0!==n.fixedMax,p=(t??[]).filter(t=>t.time>=d).map(t=>[t.time,Math.abs(t.value)]),f=[{type:"line",data:p,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}}],g=p.length>0?function(t){let e=0;for(const n of t)n[1]>e&&(e=n[1]);return e}(p):0,m={type:"value",splitNumber:4,axisLabel:{fontSize:10,formatter:g<10?t=>0===t?"0":t.toFixed(1):t=>n.format(t)},splitLine:{lineStyle:{opacity:.15}}};if(u?(m.min=n.fixedMin,m.max=n.fixedMax):g<1&&(m.min=0,m.max=1),o&&"current"===n.entityRole){const t=o.ratingA*o.continuousPct/100,e=o.ratingA*o.spikePct/100;m.min=0,m.max=Math.ceil(1.25*Math.max(t,e,g)),f.push({type:"line",data:[[d,t],[c,t]],showSymbol:!1,lineStyle:{width:1,color:"rgba(255, 200, 40, 0.6)",type:"dashed"},itemStyle:{color:"transparent"},tooltip:{show:!1}}),f.push({type:"line",data:[[d,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 v={xAxis:{type:"time",min:d,max:c,axisLabel:{fontSize:10},splitLine:{show:!1}},yAxis:m,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:v,series:f}}(n,i,o,a,l,c),p=s??120;t.style.minHeight=p+"px";let f=t.querySelector("span-chart");f||(f=document.createElement("span-chart"),f.style.display="block",f.style.width="100%",t.innerHTML="",t.appendChild(f));const g=t.clientHeight;f.height=(g>0?g:p)+"px",f.options=d,f.data=u}function DI(t){return null===t?Ri:function(t){return(Math.abs(t)/1e3).toFixed(1)}(t)}function LI(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):Ri,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:On(o),partial:!1}),a&&(a.textContent=DI(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):Ri,c&&(c.textContent="A")}else l.textContent=DI(On(i)),c&&(c.textContent="kW")}const d=t.querySelector(".stat-downstream .stat-value"),u=t.querySelector(".stat-downstream .stat-unit");if(d){const t=n.panel_entities?.feedthrough_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;d.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Ri,u&&(u.textContent="A")}else d.textContent=DI(On(i)),u&&(u.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):Ri,p&&(p.textContent="A")}else h.textContent=DI(On(i)),p&&(p.textContent="kW")}const f=t.querySelector(".stat-battery .stat-value");if(f){const t=n.panel_entities?.battery_level,i=On(t?e.states[t]:void 0);f.textContent=null===i?Ri:`${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:Ri}}function EI(t,e,n,i,r,o,a){if(!t||!n||!e)return;const s=pr(i),l=we(n),c=[];for(const{circuit:t}of l){if(!t.entities?.power||Jn(t)||qn(t))continue;const n=Kn(t,e);c.push(null===n?null:Math.abs(n))}!function(t,e,n,i,r){const o=t.querySelector(".panel-stats");o&&LI(o,e,n,i,r)}(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 d={hass:e,topology:n,powerHistory:r,horizonMap:o,defaultDurationMs:s,chartMetric:Wi(i),monitoringStatus:a};for(const e of l)for(const n of ye(e)){const i=t.querySelector(`.circuit-slot[data-uuid="${nr(n.uuid)}"]`);if(!i)continue;const r=n.uuid===e.uuid?e.circuit:xe(n.circuit,e);RI(i,n.uuid,r,d)}}function RI(t,e,n,i){const{hass:r,powerHistory:o,horizonMap:a,defaultDurationMs:s,chartMetric:l,monitoringStatus:c}=i,d=Kn(n,r),u=ti(n,d),h=Zn(n,r),p=t.querySelector(".power-value");p&&(p.innerHTML="current"===l.entityRole?Fi(Qn(n,r)):Hi(d)),Yi(t,h,si(n,r),un(i.topology,e)),t.classList.toggle("circuit-off",!h),t.classList.toggle("circuit-producer",u),Ji(t,di(n,r));const f=t.querySelector(".chart-container");if(f){const i=o.get(e)||[],r=t.classList.contains("circuit-col-span")?200:100,d=a?.has(e)?fr(a.get(e)):s,h=Jn(n),p=je(c,n),g=Ut(n,p);PI(f,0,i,d,l,u,r,g?{ratingA:g,...qe(p)}:void 0,h)}}class NI{constructor(t){this._settings=null,this._lastFetch=0,this._fetching=!1,this._retry=new $e(t)}async fetch(t,e){const i=Date.now();if(this._fetching)return this._settings;if(this._settings&&i-this._lastFetch<3e4)return this._settings;this._fetching=!0;try{const i={};e&&(i.config_entry_id=e);const r={type:"call_service",domain:s,service:"get_graph_settings",service_data:i,return_response:!0},o=await this._retry.callWS(t,r,{errorId:"fetch:graph_settings",errorMessage:n("error.graph_settings_failed")});this._settings=o?.response??null,this._lastFetch=Date.now()}catch(t){console.warn("SPAN Panel: graph settings fetch failed",t),this._settings=null}finally{this._fetching=!1}return this._settings}invalidate(){this._lastFetch=0}get settings(){return this._settings}clear(){this._settings=null,this._lastFetch=0}}function OI(t,e){if(!t)return o;const n=t.circuits?.[e];return n?.has_override?n.horizon:t.global_horizon??o}function zI(t,e){if(!t)return o;const n=t.sub_devices?.[e];return n?.has_override?n.horizon:t.global_horizon??o}function $I(t,e,n){return{members:t?ye(t):[{uuid:e,circuit:n}],capacityA:t&&t.members.length>1?t.circuit.breaker_rating_a??null:null}}class HI{constructor(t){this.errorStore=t,this.powerHistory=new Map,this.horizonMap=new Map,this.subDeviceHorizonMap=new Map,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,this.monitoringCache=new Fe(t),this.monitoringMultiCache=new Be(t),this.graphSettingsCache=new NI(t)}get hass(){return this._hass}set hass(t){this._hass=t}get _drawnHass(){const t=this._hass;if(!t)throw new Error("dashboard controller: acted on before it was given Home Assistant");return 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,OI(t,e));if(t&&this._topology?.sub_devices)for(const e of Object.keys(this._topology.sub_devices))this.subDeviceHorizonMap.set(e,zI(t,e))}async fetchAndBuildHorizonMaps(){this._favRefs?await this._buildFavoritesHorizonMaps():(await this.graphSettingsCache.fetch(this._hass,this._configEntryId),this.buildHorizonMaps(this.graphSettingsCache.settings))}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,OI(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,zI(i,r))}}async loadHistory(){await Sr(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)??o;if(!a[i]?.useRealtime)continue;const r=Ui(n,this._config);if(!r)continue;const s=On(this._hass.states[r]);if(null===s)continue;const l=fr(i),c=gr(l),d=mr(l),u=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 wr(this._topology))i.has(e)&&r.add(t);const o=new Map;try{await Sr(this._hass,this._topology,this._config,o,e,i);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:n("error.history_failed"),persistent:!1})}}updateDOM(t){this._hass&&this._topology&&this._config&&(EI(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=pr(i);for(const[i,s]of Object.entries(n.sub_devices)){const n=t.querySelector(`[data-subdev="${nr(i)}"]`);if(!n)continue;const l=zn(s);if(l.headlineEid){const t=n.querySelector(".sub-power-value");t&&(t.innerHTML=$i(Fn(e,l.headlineEid)))}if(l.siteTotalEid){const t=Fn(e,l.siteTotalEid),i=n.querySelector(".sub-site-total-value");i&&(i.innerHTML=$i(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=p.power;e.endsWith("_soc")?s=p.soc:e.endsWith("_soe")&&(s=p.soe);const l=!!t.closest(".bess-chart-col");PI(t,0,n,o?.has(i)?fr(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="${nr(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=On(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 ir(n)){const n=t.querySelector(`.meter-tile[data-meter-uuid="${nr(r)}"] .meter-readings`);n&&(n.innerHTML=or(o,e,i))}}(t,this._hass,this._topology,this._config))}async onGraphSettingsChanged(t){const e=this._drawnHass;this._favRefs?await this._buildFavoritesHorizonMaps():(this.graphSettingsCache.invalidate(),await this.graphSettingsCache.fetch(e,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"!==si(s,this._hass))return;const c=un(this._topology,a);if(!c.mayOperate)return void this.errorStore.add({key:"service:relay",level:"warning",message:vn(c),persistent:!1});const d=this._hass;yn(d,c).setRelay(l,"on"!==d.states[l]?.state).catch(t=>wn(d,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 a=i.dataset.uuid;if(a&&this._topology){const t=this._topology.circuits[a];if(t){const e=this._favRefs?.[a]??null,n=e&&"circuit"===e.kind?e.targetId:a,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=je(l,t),d=s?.global_horizon??o,u=s?.circuits?.[n],h=u?{...u,globalHorizon:d}:{horizon:d,has_override:!1,globalHorizon:d},p=e?.panelDeviceId??this._panelFavorites?.panelDeviceId,f=null!==e||(this._panelFavorites?.circuitUuids.has(n)??!1),g=this._sidePanelSlot(a,e),m=e?this._perPanelInfo.get(e.panelDeviceId)?.topology:this._topology,v={uuid:n,name:t.name,entities:t.entities,...$I(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:un(this._topology,a)};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 a;e?a=await this._fetchGraphSettingsFresh(i):(await this.graphSettingsCache.fetch(this._hass,i),a=this.graphSettingsCache.settings);const l=a?.global_horizon??o,c=a?.sub_devices?.[n],d=c?{...c,globalHorizon:l}:{horizon:l,has_override:!1,globalHorizon:l},u=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:Hn(t).length>0,graphHorizonInfo:d,showFavorites:this.showFavorites,favoritePanelDeviceId:u,isFavorite:h,configEntryId:i})}}_sidePanelSlot(t,e){const n="circuit"===e?.kind?this._perPanelInfo.get(e.panelDeviceId)?.topology:void 0;return n&&e?be(we(n)).get(e.targetId):this._topology?be(we(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=be(we(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=je(l,a);r.refreshRating({...$I(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(cn(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){const e=this._drawnHass;try{const i={};t&&(i.config_entry_id=t);const r={type:"call_service",domain:s,service:"get_graph_settings",service_data:i,return_response:!0},o=await new $e(this.errorStore).callWS(e,r,{errorId:"fetch:graph_settings",errorMessage:n("error.graph_settings_failed")});return o?.response??null}catch(t){return console.warn("SPAN Panel: fresh graph settings fetch failed",t),null}}async _fetchMonitoringStatusFresh(t){const e=this._drawnHass;try{const i={};t&&(i.config_entry_id=t);const r={type:"call_service",domain:s,service:"get_monitoring_status",service_data:i,return_response:!0},o=await new $e(this.errorStore,{passThrough:Le}).callWS(e,r,{errorId:"fetch:monitoring",errorMessage:n("error.monitoring_failed")});return He(o?.response)}catch(t){return Le(t)||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 FI(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()}}const BI='\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';class VI{get hass(){return this._ctrl.hass}set hass(t){this._ctrl.hass=t}constructor(t){this._container=null,this._onGearClick=null,this._onToggleClick=null,this._onSidePanelClosed=null,this._onGraphSettingsChanged=null,this._foldUnobserve=null,this._ctrl=new HI(t)}setPanelFavorites(t){this._ctrl.setPanelFavorites(t)}async render(t,e,i,r,o){let a,s;this.stop(),this._ctrl.reset(),this._ctrl.showMonitoring=!0,this._container=t,this._ctrl.hass=e;try{const t=await Di(e,i);if(a=t.topology,s=Wn(a,t.panelSize),!s)throw new Error(n("card.topology_error"))}catch(e){return Le(e)?Ee:(t.innerHTML=`

    ${Ft(Jt(e))}

    `,null)}if(this._ctrl.init(a,r,e,o??null),await this._ctrl.monitoringCache.fetch(e,o??null),this._ctrl.monitoringCache.awaitingLoad)return Ee;await this._ctrl.fetchAndBuildHorizonMaps();const l=function(t){return Un(t.last)-Un(t.first)+1}(s),c=this._ctrl.monitoringCache.status,d=qi(a,r),u=function(t){if(!t)return"";const e=Object.values(t.circuits??{}),i=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(),...i],a=o.flatMap(t=>null!=t.utilization_pct?[We(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 ✓ ${n("status.monitoring")} · ${e.length} ${n("status.circuits")} · ${i.length} ${n("status.mains")}\n \n ${s>0?`${s} ${n(s>1?"status.warnings":"status.warning")}`:""}\n ${l>0?`${l} ${n(l>1?"status.alerts":"status.alert")}`:""}\n ${c>0?`${c} ${n(c>1?"status.overrides":"status.override")}`:""}\n \n
    \n `}(c),h=function(t,e,n,i,r){const o=new Map,a=new Set;for(const{uuid:e,circuit:n,members:i}of we(t)){if(qn(n))continue;const t=n.tabs;if(!t||0===t.length)continue;const r=Math.min(...t),s=1===t.length?"single":Xn(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=Un(Math.max(...n));0===Gn(t)?s.add(i):l.add(i)}function c(e){return{monInfo:je(r,e.circuit),sheddingPriority:di(e.circuit,n),access:un(t,e.uuid)}}const d=t=>t>=e.first&&t<=e.last,u=Un(e.first),h=Un(e.last);let p="";for(let t=u;t<=h;t++){const e=t-u+1,r=2*t-1,h=2*t,f=o.get(r),g=o.get(h),m=d(r)?`
    ${r}
    `:"",v=d(h)?`
    ${h}
    `:"";if(p+=m,f&&"row-span"===f.layout){const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=tr(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)&&d(r)&&(p+=er(e,"2"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=tr(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)&&d(h)&&(p+=er(e,"4"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(g);p+=tr(g.uuid,g.circuit,e,"4",g.layout,n,i,t,r,o,g.members)}p+=v}return p}(a,s,e,r,c),p=sr(a,e,r,{showFavorites:this._ctrl.showFavorites}),f=ar(a,e,r);t.innerHTML=`\n \n ${d}\n ${u}\n ${p?`
    ${p}
    `:""}\n ${f}\n ${!1!==r.show_panel?`\n
    \n ${h}\n
    \n `:""}\n \n `,this._onGearClick=e=>{this._ctrl.onGearClick(e,t)},this._onToggleClick=e=>{this._ctrl.onToggleClick(e,t)},t.addEventListener("click",this._onGearClick),t.addEventListener("click",this._onToggleClick),this._onSidePanelClosed=()=>{this._ctrl.monitoringCache.invalidate(),this._ctrl.graphSettingsCache.invalidate()},t.addEventListener("side-panel-closed",this._onSidePanelClosed),this._onGraphSettingsChanged=()=>this._ctrl.onGraphSettingsChanged(t),t.addEventListener("graph-settings-changed",this._onGraphSettingsChanged);try{await this._ctrl.loadHistory()}catch{}this._ctrl.updateDOM(t);const g=t.querySelector(".slide-confirm");return g&&(this._ctrl.bindSlideConfirm(g,t),t.classList.add("switches-disabled")),this._ctrl.setupResizeObserver(t,t),this._ctrl.startIntervals(t),this._foldUnobserve&&this._foldUnobserve(),this._foldUnobserve=FI(t,{rowSelector:".circuit-slot",nameSelector:".circuit-name",foldClass:"is-folded"}),a}invalidateMonitoring(){this._ctrl.monitoringCache.invalidate()}async refreshSidePanel(t,e,n=null){this._container&&await this._ctrl.refreshCircuitSidePanel(this._container,t,e,n)}refreshSidePanelControlAccess(t,e){this._container&&this._ctrl.refreshCircuitControlAccess(this._container,t,e)}stop(){this._ctrl.stopIntervals(),this._foldUnobserve&&(this._foldUnobserve(),this._foldUnobserve=null),this._container&&(this._onGearClick&&(this._container.removeEventListener("click",this._onGearClick),this._onGearClick=null),this._onToggleClick&&(this._container.removeEventListener("click",this._onToggleClick),this._onToggleClick=null),this._onSidePanelClosed&&(this._container.removeEventListener("side-panel-closed",this._onSidePanelClosed),this._onSidePanelClosed=null),this._onGraphSettingsChanged&&(this._container.removeEventListener("graph-settings-changed",this._onGraphSettingsChanged),this._onGraphSettingsChanged=null))}}const jI="\n display:flex;align-items:center;gap:8px;margin-bottom:8px;\n",qI="var(--divider-color)",WI=`\n background:var(--secondary-background-color,#333);\n border:1px solid ${qI};\n color:var(--primary-text-color);\n border-radius:4px;padding:6px 10px;width:80px;font-size:0.85em;\n`,UI="\n min-width:130px;font-size:0.85em;color:var(--secondary-text-color);\n",GI="\n min-width:160px;font-size:0.85em;color:var(--secondary-text-color);\n",XI="\n background:var(--secondary-background-color,#333);\n border:1px solid var(--divider-color);\n color:var(--primary-text-color);\n border-radius:4px;padding:6px 10px;flex:1;font-size:0.85em;\n font-family:monospace;\n",YI=`\n background:var(--secondary-background-color,#333);\n border:1px solid ${qI};\n color:var(--primary-text-color);\n border-radius:3px;padding:3px 6px;width:50px;font-size:0.8em;\n text-align:center;\n`,ZI="var(--error-color,#f44336)",KI="\n background:none;border:1px solid var(--divider-color);color:var(--primary-text-color);\n border-radius:4px;padding:3px 6px;cursor:pointer;font-size:0.75em;\n";let QI=0;function JI(t){return QI+=1,`span-monitoring-${t}-${QI}`}const tP=[["continuous_threshold_pct","#g-continuous"],["spike_threshold_pct","#g-spike"],["window_duration_m","#g-window"],["cooldown_duration_m","#g-cooldown"]];function eP(t){const e=document.createElement("div");e.id=JI("feedback"),e.setAttribute("aria-live","polite"),e.style.cssText="\n font-size:0.75em;color:var(--error-color,#f44336);\n max-width:10em;white-space:normal;line-height:1.3;\n";const n=t.getAttribute("aria-describedby");return t.setAttribute("aria-describedby",n?`${n} ${e.id}`:e.id),t.parentElement?.appendChild(e),n=>{e.textContent=n??"",t.style.borderColor=n?ZI:qI}}const nP=["reset-btn","circuit-toggle","mains-toggle","rating-clear","rating-turn-off"],iP="other_breaker",rP=["[id]",".threshold-input",".rating-input",...nP.map(t=>`.${t}`)].join(", "),oP={"reset-btn":t=>sP(t,"continuous_threshold_pct"),"rating-clear":t=>sP(t,iP),"rating-turn-off":t=>lP("circuit-toggle",t)};function aP(t){if(t.id)return`#${t.id}`;const{entity:e,field:n}=t.dataset;if(void 0===e)return null;if(t.classList.contains("threshold-input"))return void 0!==n?sP(e,n):null;if(t.classList.contains("rating-input"))return sP(e,iP);const i=cP(t);return i?lP(i,e):null}function sP(t,e){return`${t}\0${e}`}function lP(t,e){return`${t}\0${e}`}function cP(t){return nP.find(e=>t.classList.contains(e))}const dP=["one_space","two_spaces"],uP=["applies","pending","averaged_legs"];function hP(t,e){return null===t||e.some(e=>e===t)}function pP(t){const{package_ratings_form:e,package_ratings_state:n,...i}=t,r=i;return hP(e,dP)&&(r.package_ratings_form=e),hP(n,uP)&&(r.package_ratings_state=n),r}function fP(t){if(!t||"object"!=typeof t)return;const e={};for(const[n,i]of Object.entries(t))i&&"object"==typeof i&&(e[n]=pP(i));return e}const gP={continuous_threshold_pct:"monitoring.continuous",spike_threshold_pct:"monitoring.spike",window_duration_m:"monitoring.window",cooldown_duration_m:"monitoring.cooldown"};function mP(t,e,r,o,a,s){const{min:l,max:c}=he[r];return`\n ${a}\n `}function vP(t,e){const i=Yt(t);return`${Kt({...i,userSet:!e&&i.userSet})||`${Ft(n("monitoringRating.none"))}`}`}function _P(t,e){const{package_ratings_form:n,breaker_rating_a:i,point_id:r}=t;return e&&n&&null!=i&&"string"==typeof r?{circuitId:r,panelA:i,ratings:t.package_ratings_a??null}:null}function yP(t){return t.ratings?.[1]??null}function bP(t){return"averaged_legs"===t?n("monitoringRating.averaged_legs"):"own"===t?i("monitoringRating.table_threshold_warning",{reset:n("monitoring.reset")}):i("monitoringRating.table_threshold_warning_global",{settings:n("monitoring.global_settings")})}function xP(t,e){t.addEventListener("click",async()=>{"true"!==t.getAttribute("aria-disabled")&&(t.setAttribute("aria-disabled","true"),t.style.opacity="0.6",await e()||(t.removeAttribute("aria-disabled"),t.style.opacity=""))})}const wP="event_bus",SP=[{type:"device"},{type:"entity"}];function CP(t){return t.length?t.map(t=>t===wP?n("notification.event_bus_target"):t).join(", "):n("notification.none_selected")}function kP(t){return i("notification.targets_button",{targets:t})}function MP(t,e){t.textContent=`${n("error.prefix")} ${e}`,t.style.color="var(--error-color, #f44336)"}const TP="0.4";function AP(t,e,n){t.isConnected&&(e&&t.toggleAttribute("checked",n),t.checked=t.hasAttribute("checked"))}function IP(t,e,n){if(!t.isConnected)return;AP(t,e,n);const i=t.closest("tr");i&&(i.style.opacity=t.checked?"":TP)}function PP(t,e,n){return t.querySelector(`.${e}[data-entity="${nr(n)}"]`)}function DP(t,e){const n=[...e.querySelectorAll(".circuit-toggle, .mains-toggle")],i=n.length>0&&n.every(t=>t.checked);t.toggleAttribute("checked",i),t.checked=i,t.indeterminate=!i&&n.some(t=>t.checked)}function LP(t,e,n,i){if(!e.isConnected)return;IP(e,n,i);const r=t.querySelector("#toggle-all-circuits");r&&DP(r,t)}class EP{static of(t){let e=EP._watches.get(t);return e||(e=new EP(t),EP._watches.set(t,e)),e}constructor(t){this._pressed=!1,this._waiting=[],t.addEventListener("pointerdown",()=>this._press(),!0)}settled(){return this._pressed?new Promise(t=>this._waiting.push(t)):Promise.resolve()}_press(){this._pressed=!0;const t=setTimeout(()=>e(),3e3),e=()=>{clearTimeout(t),window.removeEventListener("pointerup",e,!0),window.removeEventListener("pointercancel",e,!0),setTimeout(()=>this._release(),0)};window.addEventListener("pointerup",e,!0),window.addEventListener("pointercancel",e,!0)}_release(){this._pressed=!1;for(const t of this._waiting.splice(0))t()}}EP._watches=new WeakMap;class RP{constructor(){this._timer=null,this._send=null}schedule(t,e){this._clear(),this._send=t,this._timer=setTimeout(()=>{this.flush().catch(()=>{})},e)}flush(){const t=this._send;return this._clear(),t?t():Promise.resolve()}_clear(){this._timer&&clearTimeout(this._timer),this._timer=null,this._send=null}}const NP=new Map;function OP(t,e,n){return n.get(t)||e.name||t}class zP{constructor(t){this.errorStore=t,this._pendingSaves=new Map,this._circuitLabels=NP,this._awaitingLoad=!1,this._epoch=0,this._renderSeq=0,this._drawn=null,this._statusFailure=null,this._configEntryId=null,this._notifyCloseHandler=null}awaitsLoadOf(t){return this._awaitingLoad&&this._configEntryId===t}stop(){this._epoch+=1,this._statusFailure=null,this._awaitingLoad=!1,this._notifyCloseHandler&&(document.removeEventListener("click",this._notifyCloseHandler),this._notifyCloseHandler=null),this._flushPendingSaves().catch(()=>{})}async render(t,e,r,o){const a=void 0===r||r===this._configEntryId;a||(this._statusFailure=null),void 0!==r&&(this._configEntryId=r),void 0!==o?this._circuitLabels=function(t){const e=new Map;for(const n of Object.values(t?.circuits??{})){const t=Ve(n);t&&n.name&&e.set(t,n.name)}return e}(o):a||(this._circuitLabels=NP);const l=this._circuitLabels;this._notifyCloseHandler&&(document.removeEventListener("click",this._notifyCloseHandler),this._notifyCloseHandler=null);const c=this._epoch,d=++this._renderSeq;await this._flushPendingSaves().catch(()=>{});let u=null,h=!1,p=!1;try{const t={};this._configEntryId&&(t.config_entry_id=this._configEntryId);const n=await e.callWS({type:"call_service",domain:s,service:"get_monitoring_status",service_data:t,return_response:!0});u=function(t){if(!t||"object"!=typeof t)return null;const e=t,n={};"boolean"==typeof e.enabled&&(n.enabled=e.enabled),"boolean"==typeof e.monitoring_rating_offered&&(n.monitoring_rating_offered=e.monitoring_rating_offered),e.global_settings&&"object"==typeof e.global_settings&&(n.global_settings=e.global_settings);const i=fP(e.circuits);i&&(n.circuits=i);const r=fP(e.mains);return r&&(n.mains=r),n}(n?.response)}catch(t){p=Le(t),p||(console.warn("SPAN Panel: monitoring status fetch failed",t),h=!0)}if(c!==this._epoch||d!==this._renderSeq)return;if(await EP.of(t).settled(),c!==this._epoch||d!==this._renderSeq)return;if(this._awaitingLoad=p,p)return Ee;if(h)return void this._showReadFailure(t,a);const f=u?.global_settings??{},g=!0===u?.enabled,m=u?.circuits??{},v=u?.mains??{},_=new Set;for(const t of Object.keys(e.states||{}))t.startsWith("notify.")&&_.add(t);const y=new Set(["notify","send_message"]);for(const t of Object.keys(e.services?.notify||{}))y.has(t)||_.add(`notify.${t}`);_.add(wP);const b=[..._].sort(),x=f.notify_targets??"",w=("string"==typeof x?x.split(","):x).map(t=>t.trim()).filter(Boolean),S=b.length>0&&b.every(t=>w.includes(t)),C=f.notification_title_template??"SPAN: {name} {alert_type}",k=f.notification_message_template??"{name} at {current_a}A ({utilization_pct}% of {breaker_rating_a}A rating)",M=f.notification_priority??"default",T=new Map(Object.entries(m).map(([t,e])=>[t,OP(t,e,l)])),A=t=>T.get(t)??t,I=Object.entries(m).sort(([t],[e])=>A(t).localeCompare(A(e))),P=Object.entries(v),D=[...I,...P],L=D.length>0&&D.every(([,t])=>Wt(t)),E=D.some(([,t])=>Wt(t)),R=!0===u?.monitoring_rating_offered,N=new Map;for(const[t,e]of I){const n=_P(e,R);n&&N.set(t,n)}const O=new Map,z=new Map,$=I.map(([t,e])=>{const r=A(t),o=Ft(r),a=Wt(e),s=!0===e.has_override,l=a?"":`opacity:${TP};`,c=Ft(t),d=N.get(t)??null,u=d?Xt(e,e):null,h=u?{warning:u,textId:JI("warning")}:null;u&&(O.set(t,u),z.set(t,r));const p="own"===h?.warning?` aria-describedby="${h.textId}"`:"";return`\n \n \n \n \n ${d?function(t,e,n,r,o){const a="applies"===n.package_ratings_state?qt(n):null,s=i("monitoringRating.panel_plus",{panel:String(r.panelA)}),l=JI("panel-rating"),c=i("monitoringRating.other_breaker_label",{circuit:e}),d=o?`${l} ${o}`:l,u=a?`${Ft(i("monitoringRating.judged_equals",{rating:String(a)}))}`:"",h=r.ratings?``:"";return`\n ${Ft(s)}\n \n ${u}\n ${h}\n `}(c,r,e,d,h?.textId??null):vP(e,!1)}\n ${mP(c,r,"continuous_threshold_pct",e.continuous_threshold_pct,"%","circuit")}\n ${mP(c,r,"spike_threshold_pct",e.spike_threshold_pct,"%","circuit")}\n ${mP(c,r,"window_duration_m",e.window_duration_m,"m","circuit")}\n ${mP(c,r,"cooldown_duration_m",e.cooldown_duration_m,"m","circuit")}\n \n ${s?``:""}\n \n \n ${h?function(t,e,r,o){const a=n("monitoringRating.turn_off_monitoring"),s="averaged_legs"===r?``:"";return`\n \n
    ${Ft(bP(r))}${s}
    \n \n `}(c,r,h.warning,h.textId):""}\n `}).join(""),H=Object.entries(v).map(([t,e])=>{const r=e.name??t,o=Ft(r),a=Wt(e),s=!0===e.has_override,l=a?"":`opacity:${TP};`,c=Ft(t);return`\n \n \n \n \n ${vP(e,!0)}\n ${mP(c,r,"continuous_threshold_pct",e.continuous_threshold_pct,"%","mains")}\n ${mP(c,r,"spike_threshold_pct",e.spike_threshold_pct,"%","mains")}\n ${mP(c,r,"window_duration_m",e.window_duration_m,"m","mains")}\n ${mP(c,r,"cooldown_duration_m",e.cooldown_duration_m,"m","mains")}\n \n ${s?``:""}\n \n \n `}).join(""),F=a?function(t){const e=ce(t),n=e?aP(e):null;if(!e||null===n)return null;const i=e.dataset.entity,r=cP(e),o=void 0!==r&&void 0!==i?oP[r]?.(i):void 0;return{keys:void 0!==o?[n,o]:[n],draft:e instanceof HTMLInputElement&&e.value!==e.defaultValue?e.value:null}}(t):null,{drawing:B,overTable:V}=this._drawingIn(t);B.content.innerHTML=`\n
    \n

    ${n("monitoring.heading")}

    \n\n
    \n
    \n

    ${n("monitoring.global_settings")}

    \n \n
    \n\n
    \n
    \n ${n("monitoring.continuous")}\n \n
    \n
    \n ${n("monitoring.spike")}\n \n
    \n
    \n ${n("monitoring.window")}\n \n
    \n
    \n ${n("monitoring.cooldown")}\n \n
    \n\n
    \n

    ${n("notification.heading")}

    \n\n
    \n ${n("notification.targets")}\n \n
    \n \n
    \n ${0===b.length?`
    ${n("notification.no_targets")}
    `:b.map(t=>{const i=w.includes(t);return``}).join("")}\n
    \n
    \n
    \n\n
    \n ${n("notification.priority")}\n \n \n ${"critical"===M?n("notification.hint.critical"):"time-sensitive"===M?n("notification.hint.time_sensitive"):"passive"===M?n("notification.hint.passive"):"active"===M?n("notification.hint.active"):""}\n \n
    \n\n
    \n ${n("notification.title_template")}\n \n
    \n\n
    \n ${n("notification.message_template")}\n \n
    \n\n
    \n ${n("notification.placeholders")} {name} {entity_id} {alert_type}\n {current_a} {breaker_rating_a} {threshold_pct}\n {utilization_pct} {window_m} {local_time}\n
    \n
    \n ${n("notification.event_bus_help")} span_panel_current_alert\n ${n("notification.event_bus_payload")} alert_source alert_id\n alert_name alert_display_name alert_type current_a\n breaker_rating_a monitoring_rating_a monitoring_rating_user_set\n package_ratings_a package_ratings_state threshold_pct\n utilization_pct panel_serial local_time\n window_duration_s over_threshold_since\n
    \n\n
    \n ${n("notification.test_label")}\n \n \n
    \n
    \n\n
    \n
    \n\n

    ${n("monitoring.monitored_points")}

    \n ${R?function(){const t=t=>`

    ${t}

    `,e=e=>t(Ft(e)),r=`${Ft(n("monitoringRating.note_guide"))}`,o=[n("monitoringRating.note_step_find"),i("monitoringRating.note_step_enter",{column:n("monitoring.rating")}),n("monitoringRating.note_step_single")].map(t=>`
  • ${Ft(t)}
  • `).join("");return`
    \n

    ${Ft(n("monitoringRating.note_title"))}

    \n ${e(n("monitoringRating.note_problem"))}\n ${e(n("monitoringRating.note_steps"))}\n
      ${o}
    \n ${e(n("monitoringRating.note_judged"))}\n ${e(i("monitoringRating.note_thresholds",{reset:n("monitoring.reset")}))}\n ${e(n("monitoringRating.note_two_spaces"))}\n ${t(r)}\n
    `}():""}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ${H}\n ${$}\n \n
    ${n("monitoring.col.name")}${n("monitoring.rating")}${n("monitoring.col.continuous")}${n("monitoring.col.spike")}${n("monitoring.col.window")}${n("monitoring.col.cooldown")}
    \n \n
    \n
    \n `;const j=B.content.querySelector(".monitoring-settings");j&&!Ge(e)&&function(t){t.querySelector("h2")?.after(nn()),en(t,".rating-user-set")}(j);const q=t.querySelector("#toggle-all-circuits");q&&!L&&E&&(q.indeterminate=!0);const W=t.querySelector("#notify-all-targets");if(W&&b.length>0){const t=w.length>0;!S&&t&&(W.indeterminate=!0)}this._bindGlobalControls(t,e),this._bindNotifyTargetSelect(t,e),this._bindNotificationSettings(t,e,M),this._bindToggleAll(t,e,m,v),this._bindCircuitToggles(t,e),this._bindMainsToggles(t,e),this._bindThresholdInputs(t,e),this._bindPackageRatings(t,e,N),this._bindTurnOffButtons(t,e),this._bindResetButtons(t,e),this._bindRatingMarks(t),function(t,e){if(!e)return;const n=[...t.querySelectorAll(rP)];for(const t of e.keys){const i=n.find(e=>aP(e)===t);if(i)return null!==e.draft&&i instanceof HTMLInputElement&&i.value!==e.draft&&(i.value=e.draft,i.dispatchEvent(new Event("input"))),void i.focus()}}(t,F),this._sayNewWarnings(B,V&&a,O,z),this._sayStatusFailure(t)}_showReadFailure(t,e){if(this.errorStore.add({key:"fetch:monitoring",level:"warning",message:n("error.monitoring_failed"),persistent:!1}),e&&this._holdsDrawing(t))return void this._sayStatusFailure(t);const{drawing:i}=this._drawingIn(t);i.content.innerHTML=`\n
    \n

    ${n("monitoring.heading")}

    \n \n
    \n `,i.announcer.textContent="",this._drawn=null}_sayStatusFailure(t){const e=this._statusFailure,n=t.querySelector("#global-status");e&&e.entryId===this._configEntryId&&n&&(this._statusFailure=null,MP(n,e.message))}_holdsDrawing(t){const e=this._drawn;return e?.container===t&&2===t.childNodes.length&&t.firstChild===e.content&&t.lastChild===e.announcer}_drawingIn(t){const e=this._drawn;if(e&&this._holdsDrawing(t))return{drawing:e,overTable:!0};const n=document.createElement("div"),i=document.createElement("div");i.className="rating-announcer",i.setAttribute("aria-live","polite"),i.style.cssText="\n position:absolute;width:1px;height:1px;margin:-1px;padding:0;border:0;\n overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;\n",t.replaceChildren(n,i);const r={container:t,content:n,announcer:i,warnings:new Map};return this._drawn=r,{drawing:r,overTable:!1}}_sayNewWarnings(t,e,n,r){const o=t.warnings;t.warnings=n,e?function(t,e){return t.size===e.size&&[...t].every(([t,n])=>e.get(t)===n)}(o,n)||(t.announcer.textContent=function(t,e,n){return[...t].filter(([t,n])=>e.get(t)!==n).map(([t,e])=>i("monitoringRating.warning_announcement",{circuit:n.get(t)??t,warning:bP(e)})).join(" ")}(n,o,r)):t.announcer.textContent=""}async _redraw(t,e,n){n===this._epoch&&await this.render(t,e)}_serviceData(t){return this._configEntryId&&(t.config_entry_id=this._configEntryId),t}_callSetGlobal(t,e){return Ze(t).setGlobalMonitoring(this._serviceData({...e}))}_saveOnPause(t,e,n){const i=this._serviceData({[e]:n});let r=this._pendingSaves.get(e);r||(r=new RP,this._pendingSaves.set(e,r)),r.schedule(async()=>{try{await Ze(t).setGlobalMonitoring(i)}catch(t){throw Qe(this.errorStore,t,`${e} save`),t}},500)}async _flushPendingSaves(){await Promise.all([...this._pendingSaves.values()].map(t=>t.flush()))}_bindGlobalControls(t,e){const i=t.querySelector("#monitoring-enabled"),r=t.querySelector("#global-fields"),o=t.querySelector("#global-status"),a=(t,e,n)=>{t&&MP(t,null===e?n:Jt(e))},s=async i=>{const r=this._epoch;try{await this._callSetGlobal(e,i)}catch(t){return void a(o,t,n("error.failed_save"))}await this._redraw(t,e,r)},l=new Map;for(const[e,n]of tP){const i=t.querySelector(n);i&&l.set(e,me(i,e,{report:eP(i),save:t=>{s({[e]:t})}}))}const c=t=>{r&&(r.style.opacity=t?"":TP,r.style.pointerEvents=t?"":"none")};i&&i.addEventListener("change",async()=>{const r=this._epoch,s=this._configEntryId,d=i.checked;c(d);let u=!0;try{if(d){const t=(()=>{const t={};let e=!0;for(const[n]of tP){const i=l.get(n)?.check()??null;null===i?e=!1:t[n]=i}return e?t:null})();if(!t)return i.checked=!d,c(!d),void a(o,null,n("monitoring.enable_invalid"));await this._callSetGlobal(e,t)}else await this._callSetGlobal(e,{enabled:!1})}catch(t){u=!1,r===this._epoch&&(this._statusFailure={entryId:s,message:Jt(t)})}await this._redraw(t,e,r),AP(i,u,d),i.isConnected&&c(i.checked)})}_bindNotifyTargetSelect(t,e){const n=t.querySelector("#notify-target-btn"),i=t.querySelector("#notify-target-dropdown"),r=t.querySelector("#notify-target-label");if(!n||!i)return;n.addEventListener("click",t=>{t.stopPropagation();const e="none"!==i.style.display;i.style.display=e?"none":"block"});const o=e=>{const n=t.querySelector("#notify-target-select");n&&!n.contains(e.target)&&(i.style.display="none")};document.addEventListener("click",o),this._notifyCloseHandler=o;const a=()=>{const i=[...t.querySelectorAll(".notify-target-cb:checked")].map(t=>t.value),o=CP(i);r&&(r.textContent=o),n.setAttribute("aria-label",kP(o));const a=t.querySelector("#notify-all-targets");if(a){const e=[...t.querySelectorAll(".notify-target-cb")];a.checked=e.length>0&&e.every(t=>t.checked),a.indeterminate=!a.checked&&e.some(t=>t.checked)}this._saveOnPause(e,"notify_targets",i.join(", "))},s=t.querySelector("#notify-all-targets");s&&s.addEventListener("change",()=>{for(const e of t.querySelectorAll(".notify-target-cb"))e.checked=s.checked;const e=t.querySelector("#notify-target-btn");e&&(e.style.opacity=s.checked?"0.4":"",e.style.pointerEvents=s.checked?"none":""),s.checked&&(i.style.display="none"),a()});for(const e of t.querySelectorAll(".notify-target-cb"))e.addEventListener("change",()=>{a()})}_bindNotificationSettings(t,e,i){const r=t.querySelector("#g-priority"),o=t.querySelector("#g-title-template"),a=t.querySelector("#g-message-template");r&&r.addEventListener("change",async()=>{const n=this._epoch;try{await this._callSetGlobal(e,{notification_priority:r.value})}catch(t){return Qe(this.errorStore,t,"notification priority change"),void(r.value=i)}await this._redraw(t,e,n)}),o&&o.addEventListener("input",()=>{this._saveOnPause(e,"notification_title_template",o.value)}),a&&a.addEventListener("input",()=>{this._saveOnPause(e,"notification_message_template",a.value)});const s=t.querySelector("#test-notification-btn"),l=t.querySelector("#test-notification-status");s&&s.addEventListener("click",async()=>{s.disabled=!0,l&&(l.textContent=n("notification.test_sending"),l.style.color="var(--secondary-text-color)");try{const i=[...t.querySelectorAll(".notify-target-cb:checked")];this._saveOnPause(e,"notify_targets",i.map(t=>t.value).join(", ")),await this._flushPendingSaves(),await Ze(e).testNotification(this._serviceData({})),l&&(l.textContent=n("notification.test_sent"),l.style.color="var(--success-color, #4caf50)")}catch(t){if(l){const e=Jt(t);l.textContent=`${n("error.prefix")} ${e}`,l.style.color="var(--error-color, #f44336)"}}finally{s.disabled=!1}})}_bindToggleAll(t,e,n,i){const r=t.querySelector("#toggle-all-circuits");r&&r.addEventListener("change",async()=>{const o=this._epoch,a=r.checked,s=Ze(e),l=(t,e)=>t.then(()=>!0,t=>(Qe(this.errorStore,t,e),!1)),c=[...Object.keys(n).map(e=>({control:PP(t,"circuit-toggle",e),stored:l(s.setCircuitThreshold(this._serviceData({circuit_id:e,monitoring_enabled:a})),"circuit monitoring toggle")})),...Object.keys(i).map(e=>({control:PP(t,"mains-toggle",e),stored:l(s.setMainsThreshold(this._serviceData({leg:e,monitoring_enabled:a})),"mains monitoring toggle")}))],d=await Promise.all(c.map(async({control:t,stored:e})=>({control:t,stored:await e})));if(await this._redraw(t,e,o),r.isConnected){for(const{control:t,stored:e}of d)t&&IP(t,e,a);DP(r,t)}})}_bindMainsToggles(t,e){for(const n of t.querySelectorAll(".mains-toggle"))n.addEventListener("change",async()=>{const i=this._epoch,r=n.dataset.entity,o=n.checked;let a=!0;try{await Ze(e).setMainsThreshold(this._serviceData({leg:r,monitoring_enabled:o}))}catch(t){Qe(this.errorStore,t,"mains threshold toggle"),a=!1}await this._redraw(t,e,i),LP(t,n,a,o)})}_bindCircuitToggles(t,e){for(const n of t.querySelectorAll(".circuit-toggle")){const i=n.dataset.entity;void 0!==i&&n.addEventListener("change",async()=>{const r=n.checked;LP(t,n,await this._setCircuitMonitoring(t,e,i,r),r)})}}_bindTurnOffButtons(t,e){for(const n of t.querySelectorAll(".rating-turn-off")){const i=n.dataset.entity;void 0!==i&&xP(n,async()=>{const r=await this._setCircuitMonitoring(t,e,i,!1);return r&&n.isConnected&&this._settleTurnedOff(t,n,i),r})}}_settleTurnedOff(t,e,n){const i=PP(t,"circuit-toggle",n);i&&LP(t,i,!0,!1);const r=e.closest(".rating-warning-row"),o=le(r);r?.remove(),o&&i?.focus();const a=this._drawn;if(a?.container===t&&a.warnings.has(n)){const t=new Map(a.warnings);t.delete(n),a.warnings=t}}async _setCircuitMonitoring(t,e,n,i){const r=this._epoch;let o=!0;try{await Ze(e).setCircuitThreshold(this._serviceData({circuit_id:n,monitoring_enabled:i}))}catch(t){Qe(this.errorStore,t,"circuit threshold toggle"),o=!1}return await this._redraw(t,e,r),o}_bindThresholdInputs(t,e){for(const n of t.querySelectorAll(".threshold-input")){const i=n.dataset.field,r=n.dataset.entity;if(!fe(i)||void 0===r)continue;const o="mains"===n.dataset.type;me(n,i,{report:eP(n),save:a=>{this._saveThreshold(t,e,n,t=>o?t.setMainsThreshold(this._serviceData({leg:r,[i]:a})):t.setCircuitThreshold(this._serviceData({circuit_id:r,[i]:a})))}})}}async _saveThreshold(t,e,n,i){const r=this._epoch;try{await i(Ze(e))}catch(t){return Qe(this.errorStore,t,"threshold input save"),void(n.style.borderColor=ZI)}await this._redraw(t,e,r)}_bindPackageRatings(t,e,n){for(const i of t.querySelectorAll(".rating-input")){const r=i.dataset.entity,o=void 0!==r?n.get(r):void 0;if(!o)continue;const a=ve(i,{report:eP(i),stored:()=>yP(o),save:n=>{this._savePackageRatings(t,e,i,a,o,n)}}),s=i.closest("td")?.querySelector(".rating-clear");s&&xP(s,()=>(a.revert(),this._clearPackageRatings(t,e,o)))}}async _savePackageRatings(t,e,n,i,r,o){const a=this._epoch;try{await Ze(e).setCircuitPackageRatings(this._serviceData({circuit_id:r.circuitId,package_ratings_a:[r.panelA,o]}))}catch(t){return _e(e,this.errorStore,t),void(i.answerRefusal(o)&&n.isConnected&&de()&&n.focus())}await this._redraw(t,e,a)}async _clearPackageRatings(t,e,n){const i=this._epoch;try{await Ze(e).clearCircuitPackageRatings(this._serviceData({circuit_id:n.circuitId}))}catch(t){return _e(e,this.errorStore,t),!1}return await this._redraw(t,e,i),!0}_bindRatingMarks(t){for(const e of t.querySelectorAll(".rating-user-set"))e.addEventListener("click",()=>Qt(e))}_bindResetButtons(t,e){for(const i of t.querySelectorAll(".reset-btn")){const r=i.dataset.entity;if(!r)continue;const o="mains"===i.dataset.type;xP(i,async()=>{const i=this._epoch,a=Ze(e);try{await(o?a.clearMainsThreshold(this._serviceData({leg:r})):a.clearCircuitThreshold(this._serviceData({circuit_id:r})))}catch(t){return console.warn("SPAN Panel: threshold reset failed",t),oe(e,t,s,n("error.threshold_failed")).then(t=>{this.errorStore.add({key:"service:monitoring",level:"error",message:t,persistent:!1})}),!1}return await this._redraw(t,e,i),!0})}}}function $P(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function HP(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)=>HP(t,e[n]));if(!$P(t)||!$P(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=>HP(t[n],e[n]))}function FP(t,e){return null!==t&&t.toLowerCase().includes(e)}function BP(t,e){const n=t[e];return"string"==typeof n?n:""}function VP(t,e){return{enabled:null!==e&&null===e.disabledBy,name:null===e?"":e.name,deviceClass:t.curation.device_class??"",stateClass:t.curation.state_class??"",promote:"none"===t.curation.entity_category}}function jP(t,e){const n=Number(e);return{unit_of_measurement:t||null,display_precision:""!==e&&Number.isFinite(n)?n:null}}function qP(t,e,n){return""!==t&&e.includes(t)&&n.length>0}function WP(t){if(!t)return"";const e=t.replace(/_/g," ");return e.charAt(0).toUpperCase()+e.slice(1)}const UP=["0","1","2","3","4","5","6"],GP="var(--secondary-text-color,#999)",XP="var(--primary-color,#4dd9af)",YP="var(--warning-color,#ff9800)",ZP="var(--card-background-color,#1c1c1c)",KP="var(--secondary-background-color,#232323)",QP="var(--divider-color,#333)",JP=`background:${KP};border:1px solid ${QP};color:var(--primary-text-color);border-radius:4px;padding:4px 8px;font-size:0.85em;`,tD=`${JP}min-width:0;`,eD="display:flex;align-items:center;gap:12px;flex-wrap:wrap;",nD=`font-size:0.85em;color:${GP};min-width:130px;`,iD=`color:${GP};font-size:0.75em;`,rD=`background:none;border:1px solid ${QP};color:var(--primary-text-color);border-radius:6px;padding:6px 12px;font-size:0.8em;cursor:pointer;`;function oD(t,e){const n=e?XP:GP;return`${Ft(t)}`}function aD(t,e,n){const i=e.map(t=>``).join("");return``}function sD(t){return"total_increasing"===t?n("adopted.warn_total_increasing"):"statistics_removed"===t?n("adopted.warn_statistics_removed"):t}class lD{constructor(){this._view=null,this._groups=[],this._loadError=null,this._awaitingLoad=!1,this._epoch=0,this._query="",this._expandedKey=null,this._editor=null,this._unitsCache=new Map,this._refreshTimer=null,this._onClick=t=>{this._handleClick(t)},this._onInput=t=>{this._handleInput(t)},this._onChange=t=>{this._handleChange(t)}}stop(){this._epoch+=1,this._refreshTimer&&(clearTimeout(this._refreshTimer),this._refreshTimer=null),this._unbind()}async render(t,e,n){n!==this._view?.deviceId&&(this._expandedKey=null,this._editor=null,this._query=""),this._unbind(),this._view={container:t,hass:e,deviceId:n};const i=this._epoch,r=await this._fetchList(e,n);if(i===this._epoch){if(this._adoptList(r,!1),this._awaitingLoad)return Ee;this._paint()}}async refresh(){const t=this._view;if(!t)return;const e=this._awaitingLoad,n=this._epoch,i=await this._fetchList(t.hass,t.deviceId);n===this._epoch&&"changed"===this._adoptList(i,!e)&&(e?this._paint():this._paintGroups())}async _fetchList(t,e){try{return{groups:(await t.callWS({type:`${s}/adopted/list`,device_id:e})).devices,error:null,awaitingLoad:!1}}catch(t){return Le(t)?{groups:[],error:null,awaitingLoad:!0}:{groups:[],error:Jt(t),awaitingLoad:!1}}}_adoptList(t,e){if((null!==t.error||t.awaitingLoad)&&e)return"unchanged";const n=t.error!==this._loadError||t.awaitingLoad!==this._awaitingLoad||!HP(t.groups,this._groups);return this._groups=t.groups,this._loadError=t.error,this._awaitingLoad=t.awaitingLoad,n?"changed":"unchanged"}async _fetchSeed(t,e){try{return function(t){if(!t||"object"!=typeof t)return null;const e=t;if("string"!=typeof e.entity_id)return null;const n=e.options&&"object"==typeof e.options?e.options:{},i=n.sensor&&"object"==typeof n.sensor?n.sensor:{},r=i.display_precision;return{disabledBy:"string"==typeof e.disabled_by?e.disabled_by:null,name:BP(e,"name"),unit:BP(i,"unit_of_measurement"),precision:"number"==typeof r?String(r):""}}(await t.callWS({type:"config/entity_registry/get",entity_id:e}))}catch{return null}}async _fetchUnits(t,e){if(!e)return[];const n=this._unitsCache.get(e);if(n)return n;try{const n=await t.callWS({type:"sensor/device_class_convertible_units",device_class:e}),i=Array.isArray(n?.units)?n.units.filter(t=>"string"==typeof t):[];return this._unitsCache.set(e,i),i}catch{return[]}}_findRow(t){for(const e of this._groups)for(const n of e.rows)if(n.key===t)return n;return null}get _drawn(){const t=this._view;if(!t)throw new Error("adopted tab: acted on before its first draw");return t}_paint(){this._drawn.container.innerHTML=`\n
    \n

    ${n("adopted.heading")}

    \n

    ${n("adopted.description")}

    \n\n
    \n \n \n
    \n\n
    ${this._groupsHTML()}
    \n
    \n `,this._bind()}_paintGroups(){const t=this._drawn.container.querySelector("#adopted-groups");t&&(t.innerHTML=this._groupsHTML())}_groupsHTML(){if(null!==this._loadError)return`

    ${Ft(n("adopted.load_failed"))} — ${Ft(this._loadError)}

    `;if(0===this._groups.length)return`

    ${n("adopted.none")}

    `;const t=function(t,e){const n=e.trim().toLowerCase();if(!n)return t;const i=[];for(const e of t){if(FP(e.name,n)){i.push(e);continue}const t=e.rows.filter(t=>FP(t.name,n));t.length>0&&i.push({...e,rows:t})}return i}(this._groups,this._query);return 0===t.length?`

    ${n("adopted.no_results")}

    `:t.map(t=>this._groupHTML(t)).join("")}_groupHTML(t){const e=t.adopted_device?oD(n("adopted.adopted_device"),!1):oD(n("adopted.vendor_readings"),!0),r=i("adopted.count",{count:String(t.rows.length)}),o=t.adopted_device?`${n("adopted.via_panel")} · ${r}`:r;return`\n
    \n ${Ft(t.name??"")}\n ${e}\n ${Ft(o)}\n
    \n
    \n ${t.rows.map(t=>this._rowHTML(t)).join("")}\n
    \n `}_rowHTML(t){const e=this._expandedKey===t.key,i=e&&this._editor?this._editorHTML(t,this._editor):"",r=e?`display:flex;align-items:center;padding:12px 16px;gap:10px;background:${KP};border:1px solid ${QP};border-bottom-color:transparent;border-radius:8px 8px 0 0;cursor:pointer;`:`display:flex;align-items:center;padding:12px 16px;gap:10px;background:${ZP};border:1px solid ${QP};border-radius:8px;cursor:pointer;`;return`\n
    \n
    \n ${Ft(t.name)}\n ${Ft(function(t){return t.unit?`${t.platform} · ${t.unit}`:t.platform}(t))}\n ${Object.keys(t.curation).length>0?oD(n("adopted.curated"),!0):""}\n ${t.stale_fields.length>0?oD(n("adopted.stale"),!1):""}\n ${function(t){return``}(e)}\n
    \n ${i}\n
    \n `}_editorHTML(t,e){const r=[];null!==e.seed?(r.push(this._enableHTML(e)),r.push(this._identityHTML(e))):r.push(`
    ${n("adopted.registry_unavailable")}
    `),t.allowed_device_classes.length>0&&r.push(this._deviceClassHTML(t,e)),t.allowed_state_classes.length>0&&r.push(this._stateClassHTML(t,e)),r.push(this._prominenceHTML(e)),null!==e.seed&&qP(e.form.deviceClass,t.allowed_device_classes,e.units)&&r.push(this._displayHTML(t,e)),t.stale_fields.length>0&&r.push(`
    ${Ft(i("adopted.stale_note",{fields:t.stale_fields.join(", ")}))}
    `),r.push(this._actionsHTML(e)),null!==e.confirm&&r.push(this._confirmHTML(t,e)),null!==e.error&&r.push(`
    ${Ft(e.error)}
    `);for(const t of e.notices)r.push(`
    ${Ft(t)}
    `);return r.push(`
    ${Ft(function(t){const e=[t.path,t.datatype];return t.unit&&e.push(t.unit),e.push(t.settable?n("adopted.settable"):n("adopted.read_only")),e.join(" · ")}(t))}
    `),`\n
    \n ${r.join("")}\n
    \n `}_enableHTML(t){const e=t.form.enabled,i=e?XP:GP;return`\n
    \n ${n("adopted.enable_entity")}\n \n ${n("adopted.enable_note")}\n
    \n `}_identityHTML(t){return`\n
    \n ${n("adopted.name")}\n \n
    \n `}_deviceClassHTML(t,e){const r=[{value:"",label:n("adopted.no_device_class")},...t.allowed_device_classes.map(t=>({value:t,label:WP(t)}))],o=t.unit?i("adopted.device_class_note",{unit:t.unit}):n("adopted.device_class_note_unitless");return`\n
    \n ${n("adopted.device_class")}\n ${aD("device_class",r,e.form.deviceClass)}\n ${Ft(o)}\n
    \n `}_stateClassHTML(t,e){const i=[{value:"",label:n("adopted.no_statistics")},...t.allowed_state_classes.map(t=>({value:t,label:WP(t)}))];return`\n
    \n ${n("adopted.statistics_class")}\n ${aD("state_class",i,e.form.stateClass)}\n ${n("adopted.statistics_note")}\n
    \n `}_prominenceHTML(t){const e=(t,e,n)=>``;return`\n
    \n ${n("adopted.prominence")}\n \n ${e("diagnostic",n("adopted.diagnostic"),!t.form.promote)}\n ${e("standard",n("adopted.standard"),t.form.promote)}\n \n
    \n `}_displayHTML(t,e){const i=[{value:"",label:t.unit?`${t.unit} — ${n("adopted.unit_as_published")}`:n("adopted.unit_as_published")},...e.units.map(t=>({value:t,label:t}))],r=[{value:"",label:n("adopted.precision_default")},...UP.map(t=>({value:t,label:t}))];return`\n
    \n ${n("adopted.display_unit")}\n ${aD("unit",i,e.unit)}\n ${n("adopted.precision")}\n ${aD("precision",r,e.precision)}\n
    \n `}_actionsHTML(t){const e=t.busy?" disabled":"";return`\n
    \n \n \n ${n("adopted.reload_note")}\n
    \n `}_confirmHTML(t,e){const r="clearing"===e.confirm,o=r?i("adopted.confirm_clearing_subject",{name:t.name}):i("adopted.confirm_setting",{name:t.name,value:WP(e.form.stateClass)}),a=n(r?"adopted.confirm_clearing":"adopted.confirm_total_increasing");return`\n
    \n
    \n \n ${n("adopted.confirm_heading")}\n
    \n

    ${Ft(o)}

    \n

    ${a}

    \n
    \n \n \n
    \n
    \n `}_bind(){const{container:t}=this._drawn;t.addEventListener("click",this._onClick),t.addEventListener("input",this._onInput),t.addEventListener("change",this._onChange)}_unbind(){const t=this._view?.container;t&&(t.removeEventListener("click",this._onClick),t.removeEventListener("input",this._onInput),t.removeEventListener("change",this._onChange))}async _handleClick(t){const e=t.target;if(!e)return;const n=e.closest("[data-action]");if(n)return void await this._handleAction(n);const i=e.closest(".adopted-row-header"),r=i?.dataset.key;return r?this._expandedKey===r?(this._expandedKey=null,this._editor=null,void this._paintGroups()):void await this._openEditor(r):void 0}async _handleAction(t){const e=this._editor;if(e)switch(t.dataset.action){case"toggle-enable":return e.form={...e.form,enabled:!e.form.enabled},void this._paintGroups();case"prominence":return e.form={...e.form,promote:"standard"===t.dataset.value},void this._paintGroups();case"save":return void(e.busy||await this._save(e,!1));case"clear":return void(e.busy||await this._save(e,!0));case"confirm-cancel":return e.confirm=null,void this._paintGroups();case"confirm-save":{const t=e.confirmClears;return e.confirm=null,void await this._commit(e,this._expandedRow(),t)}default:return}}_handleInput(t){const e=t.target;if(!e)return;if("adopted-filter"===e.id)return this._query=e.value,void this._paintGroups();const n=this._editor,i=e.dataset.field;if(!n||!i)return;const r=e.value;"name"===i&&(n.form={...n.form,name:r})}async _handleChange(t){const e=t.target,n=this._editor,i=e?.dataset.field;if(e&&n&&i)switch(i){case"device_class":return n.form={...n.form,deviceClass:e.value},n.units=await this._fetchUnits(this._drawn.hass,e.value),void this._paintGroups();case"state_class":return void(n.form={...n.form,stateClass:e.value});case"unit":return void(n.unit=e.value);case"precision":return void(n.precision=e.value);default:return}}_expandedRow(){const t=this._expandedKey,e=null===t?null:this._findRow(t);if(!e)throw new Error("adopted tab: an editor is open on no row the tab holds");return e}async _openEditor(t){const e=this._findRow(t);if(!e)throw new Error(`adopted tab: no row ${t} behind its header`);const{hass:n}=this._drawn;this._expandedKey=t,this._editor={form:VP(e,null),seed:null,units:[],unit:"",precision:"",confirm:null,confirmClears:!1,busy:!0,error:null,notices:[]},this._paintGroups();const i=null===e.entity_id?null:await this._fetchSeed(n,e.entity_id);if(this._expandedKey!==t)return;const r=VP(e,i),o=await this._fetchUnits(n,r.deviceClass);this._expandedKey===t&&(this._editor={form:r,seed:i,units:o,unit:i?.unit??"",precision:i?.precision??"",confirm:null,confirmClears:!1,busy:!1,error:null,notices:[]},this._paintGroups())}async _save(t,e){const n=this._expandedRow(),i=function(t,e){return"total_increasing"===e.stateClass?"total_increasing":t.curation.state_class&&""===e.stateClass?"clearing":null}(n,this._formFor(t,e));if(null!==i)return t.confirm=i,t.confirmClears=e,t.error=null,t.notices=[],void this._paintGroups();await this._commit(t,n,e)}_formFor(t,e){return e?{...t.form,deviceClass:"",stateClass:"",promote:!1}:t.form}async _commit(t,e,i){const{hass:r,deviceId:o}=this._drawn,a=this._formFor(t,i),l=function(t,e){const n={};return e.deviceClass&&(n.device_class=e.deviceClass),e.stateClass&&(n.state_class=e.stateClass),e.promote&&(n.entity_category="none"),{registryUpdate:null===t.entity_id?null:{type:"config/entity_registry/update",entity_id:t.entity_id,name:e.name||null,disabled_by:e.enabled?null:"user"},curate:{key:t.key,record:n}}}(e,a);t.busy=!0,t.error=null,t.notices=[],this._paintGroups();let c=t.seed;try{const d=i||null===c?null:function(t,e,n){if(null===t.registryUpdate||null===e||!function(t,e){return null!==t&&(e.enabled!==(null===t.disabledBy)||e.name!==t.name)}(e,n))return null;const i={...t.registryUpdate};return function(t,e){return e.enabled===(null===t.disabledBy)}(e,n)&&delete i.disabled_by,i}(l,c,a);null!==d&&null!==c&&(await r.callWS(d),c=function(t,e){return{...t,disabledBy:e.enabled?null:t.disabledBy??"user",name:e.name}}(c,a),t.seed=c),!i&&null!==c&&null!==e.entity_id&&qP(a.deviceClass,e.allowed_device_classes,t.units)&&function(t,e,n){return null!==t&&(e!==t.unit||n!==t.precision)}(c,t.unit,t.precision)&&(await r.callWS({type:"config/entity_registry/update",entity_id:e.entity_id,options_domain:"sensor",options:jP(t.unit,t.precision)}),c={...c,unit:t.unit,precision:t.precision},t.seed=c);const u=await r.callWS({type:`${s}/adopted/curate`,device_id:o,key:l.curate.key,record:l.curate.record});e.curation=u?.record??{},t.form=a,t.notices=[n("adopted.saved"),...Array.isArray(u?.warnings)?u.warnings.map(sD):[]]}catch(e){return t.error=Jt(e),t.busy=!1,void this._paintGroups()}t.busy=!1,this._paintGroups(),this._scheduleRefresh(r,o)}_scheduleRefresh(t,e){this._refreshTimer&&clearTimeout(this._refreshTimer),this._refreshTimer=setTimeout(()=>{this._refreshTimer=null;const n=this._epoch;this._fetchList(t,e).then(t=>{n===this._epoch&&"changed"===this._adoptList(t,!0)&&this._paintGroups()})},2e3)}}function cD(t=""){const e=t?` value="${Ft(t)}"`:"",i=t?"":"display:none;";return`\n
    \n \n \n
    \n `}function dD(t,e,i,r,o,a,s,l,c){const d=Zn(e,i),u=si(e,i),h=Ce([e]),p=Ft(e.name||n("grid.unknown")),f="current"===Wi(r).entityRole;let g;g=d?f?Fi(Qn(e,i)):Hi(Kn(e,i)):"";const m=Qi(a||"unknown");let v="";const _=ei(l,i,o);null!==_&&(v=`${Math.round(_)}%`);const y=``,b=qn(e)?"":"none"===u?`${d?"ON":"OFF"}`:Xi(d,u,c);return`\n
    \n ${h?`${h}`:""}\n ${v}\n ${p}\n ${m}\n ${b}\n \n ${g}\n \n ${y}\n \n
    \n `}function uD(t,e,n,i,r){const o=ti(e,Kn(e,n)),a=Yn(0,r,Zn(e,n),o),s=Ft(t);return`\n
    \n
    \n
    \n
    \n
    \n `}function hD(t){return`
    ${Ft(t)}
    `}function pD(t,e,n){return{isOn:Zn(t,e),value:"current"===(n.chart_metric||"power")?Qn(t,e):Kn(t,e)}}function fD(t,e,n,i){const r=pD(t,n,i),o=pD(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 gD(t,e,n){return t.sort((t,i)=>fD(t[1],i[1],e,n))}class mD{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=gD(Object.entries(n.circuits),e,i),s=be(we(n));let l=o+cD(this._searchQuery);l+=`
    `;for(const[t,o]of a){const a=je(r,o),c=di(o,e),d=this._expandedUuids.has(t);l+=`
    `,l+=dD(t,o,e,i,a,c,d,xe(o,s.get(t)),un(n,t)),d&&(l+=uD(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,i,r,o,a){this._unbindEvents(),this._hass=e,this._topology=i,this._config=r,this._monitoringStatus=o;const s=n("list.unassigned_area"),l=be(we(i)),c=new Map;for(const[t,e]of Object.entries(i.circuits)){const n=e.area??s,i=c.get(n);i?i.push([t,e]):c.set(n,[[t,e]])}const d=[...c.keys()].sort((t,e)=>t===s?1:e===s?-1:t.localeCompare(e));let u=a+cD(this._searchQuery);u+=`
    `;for(const t of d){const n=c.get(t);if(!n)continue;const a=gD(n,e,r);u+=hD(t);for(const[t,n]of a){const a=je(o,n),s=di(n,e),c=this._expandedUuids.has(t);u+=`
    `,u+=dD(t,n,e,r,a,s,c,xe(n,l.get(t)),un(i,t)),c&&(u+=uD(t,n,e,0,a)),u+="
    "}}u+="
    ",u+="",t.innerHTML=u;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"===Wi(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}=pD(a,e,i),c=t.querySelector(".list-power-value");c&&(c.innerHTML=s?r?Fi(l):Hi(l):""),Yi(t,s,si(a,e),un(n,o)),Ji(t,di(a,e));const d=t.querySelector(".list-status-badge");d&&(d.textContent=s?"ON":"OFF",d.classList.toggle("list-status-on",s),d.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)=>fD(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=FI(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=nr(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=je(this._monitoringStatus,e),o=uD(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 vD=["name","name_by_user"];function _D(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))}function yD(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 bD(t,e,n){return t.connection.subscribeEvents(t=>{(function(t){const e=yD(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=yD(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 xD(t){const e={...t};for(const t of rn)delete e[t];return e}function wD(t){const e=Object.fromEntries(Object.entries(t.circuits).map(([t,e])=>[t,xD(e)]));return{...t,circuits:e}}function SD(t,e){return`${t}|${e}`}class CD{async build(t,e,n,i){const r=new Map;for(const t of n)r.set(t.id,t);const o=new $e(i,{passThrough:Le}),a=[];for(const[n,i]of Object.entries(e)){if(!((i?.circuits?.length??0)>0||(i?.sub_devices?.length??0)>0))continue;const e=r.get(n);e&&a.push((async()=>{try{const i=await Di(t,n,o);return{panelDeviceId:n,panel:e,topology:i.topology,pending:!1}}catch(t){return Le(t)?{panelDeviceId:n,panel:e,topology:null,pending:!0}:(console.warn("SPAN Panel: favorites topology fetch failed",n,t),{panelDeviceId:n,panel:e,topology:null,pending:!1})}})())}const s=await Promise.all(a),l=s.filter(t=>null!==t.topology),c=l.length>1,d={},u={},h={},p={},f=new Set,g=[];for(const{panelDeviceId:t,panel:n,topology:i}of l){if(!i)continue;const r=n.config_entry_id??null;r&&f.add(r);const o=n.name_by_user??n.name??i.device_name??"";g.push({panelDeviceId:t,panelName:o,topology:i});const a=e[t],s=a?.circuits??[],l=a?.sub_devices??[];for(const e of s){const n=i.circuits?.[e];if(!n)continue;const a=SD(t,e),s=c&&o?`${o} · ${n.name}`:n.name,l=n.shared_meter_group,h=l?SD(t,l):l,f=l?i.shared_meter_groups?.[l]:void 0;h&&f&&(u[h]={...f,members:f.members.map(e=>SD(t,e))}),d[a]={...n,name:s,shared_meter_group:h},p[a]={panelDeviceId:t,kind:"circuit",targetId:e,configEntryId:r,controlAccess:cn(i)}}for(const e of l){const n=i.sub_devices?.[e];if(!n)continue;const a=SD(t,e),s=c&&o&&n.name?`${o} · ${n.name}`:n.name??e;h[a]={...n,name:s},p[a]={panelDeviceId:t,kind:"sub_device",targetId:e,configEntryId:r}}}return{topology:{circuits:d,shared_meter_groups:u,sub_devices:h,panel_entities:{},device_name:"",_favoriteRefs:p},entryIds:Array.from(f),perPanelStats:g,awaitingPanelIds:s.filter(t=>t.pending).map(t=>t.panelDeviceId)}}}const kD="span_panel_favorites_view_state";function MD(t){try{localStorage.setItem(kD,JSON.stringify(t))}catch{}}function TD(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 AD(t){let e=!1;return()=>{e||(e=!0,Promise.resolve().then(()=>{e=!1,t()}))}}var ID;const PD="favorites";function DD(t){return"dashboard"===t||"adopted"===t}let LD=ID=class extends At{constructor(){super(...arguments),this.narrow=!1,this._panels=[],this._selectedPanelId=null,this._activeTab="dashboard",this._discovered=!1,this._awaitingConnection=!1,this._listColumns=Vt(),this._favorites={},this._favoritesViewState={expanded:{activity:[],area:[]}},this._favoritesPanelStats=[],this._errorStore=new $t,this._dashboardTab=new VI(this._errorStore),this._monitoringTab=new zP(this._errorStore),this._adoptedTab=new lD,this._listDashCtrl=new HI(this._errorStore),this._listCtrl=new mD(this._listDashCtrl),this._favCache=new Tn(this._errorStore),this._favCtrl=new CD,this._favoritesMonitoring=null,this._watchedPanelId=null,this._discovering=!1,this._refreshSeq=0,this._areaSub=null,this._areaTopology=null,this._attachment=null,this._entryLoads=new Map,this._waitEntries=new Set,this._ratingSubs=new Map,this._ratingRefreshes=new Map,this._ratingChangedIds=new Map,this._renderedTopologies=new Map,this._renderedView=null,this._panelsRefresh=TD(()=>this._refreshPanels()),this._requestPanelsRefresh=AD(()=>{this._panelsRefresh()}),this._requestTabRender=AD(()=>{this._scheduleTabRender()}),this._renamedPanelIds=new Set,this._renameRefresh=TD(async()=>{const t=[...this._renamedPanelIds].filter(t=>this._renderedTopologies.has(t));this._renamedPanelIds.clear(),await Promise.all(t.map(t=>this._renderIfRestructured(t)))}),this._pendingTabRender=!1,this._persistFavoritesViewStateTimer=null,this._tabRenderScheduler=TD(async()=>{await this._renderTab(),this.isConnected||this._stopViews()})}get _root(){const t=this.shadowRoot;if(!t)throw new Error("span-panel: shadow root is not available");return t}connectedCallback(){super.connectedCallback();const t=()=>{this._refreshFavorites()};document.addEventListener(kn,t),this._attachment={deviceRegistry:this._subscribeDeviceRegistry(),entryReloads:this._subscribeEntryReloads(),onFavoritesChanged:t}}disconnectedCallback(){const t=this._attachment;if(!t)throw new Error("span-panel: detached before it was attached");this._stopViews(),this._unsubscribeAreaTab(),document.removeEventListener(kn,t.onFavoritesChanged),t.deviceRegistry.then(t=>t()),t.entryReloads.then(t=>t()),this._unsubscribeRatingChanges(),this._persistFavoritesViewStateTimer&&(clearTimeout(this._persistFavoritesViewStateTimer),this._persistFavoritesViewStateTimer=null,MD(this._favoritesViewState)),this._errorStore.dispose(),super.disconnectedCallback()}updated(t){if(t.has("hass")){const e=t.get("hass");this._dashboardTab.hass=this.hass,this._listDashCtrl.hass=this.hass,this._errorStore.updateHass(this.hass),this._discovered?this._root.getElementById("tab-content")?Ge(e)!==Ge(this.hass)&&this._monitoringAccessChanged():this._scheduleTabRender():e&&!this._awaitingConnection||this._discoverPanels(),this._discovered&&this._awaitingConnection&&this._panelsRefresh()}if((t.has("_panels")||t.has("hass"))&&this._syncRatingSubscriptions(),this._discovered&&(t.has("_discovered")||t.has("_activeTab")||t.has("_selectedPanelId")||t.has("_chartMetric")||t.has("_listColumns"))){if(this._isFavoritesView&&DD(this._activeTab))return void(this._activeTab="activity");this._scheduleTabRender()}if(t.has("_selectedPanelId")&&(this._selectedPanelId!==PD&&this._selectedPanelId?(this._errorStore.clearPanelStatusWatch(),this._updatePanelStatusWatch(this._selectedPanelId),this._listDashCtrl.setFavoritesPerPanelInfo(null)):(this._errorStore.clearPanelStatusWatch(),this._watchedPanelId=null)),this._discovered&&(t.has("_panels")||t.has("_selectedPanelId"))){const t=this.shadowRoot?.getElementById("panel-select");t&&null!==this._selectedPanelId&&t.value!==this._selectedPanelId&&(t.value=this._selectedPanelId)}if(t.has("hass")&&this._discovered&&("activity"===this._activeTab||"area"===this._activeTab)){const t=this._root.getElementById("tab-content"),e=this._listDashCtrl.topology;if(t&&e){this._listCtrl.updateCollapsedRows(t,this.hass,e,this._buildDashboardConfig());const n=t.querySelector("span-side-panel");n&&(n.hass=this.hass,n.errorStore=this._errorStore)}}}_monitoringAccessChanged(){"monitoring"===this._activeTab&&this._scheduleTabRender();const t=this._root.getElementById("tab-content")?.querySelector("span-side-panel");t&&(t.hass=this.hass)}setConfig(t){}render(){var i,r,o;if(i=this.hass.language,t=i&&e[i]?i:"en",!this._discovered){const t=this._awaitingConnection?Oe("waiting").text:n("card.connecting");return ct`
    @@ -300,7 +291,7 @@ var Ec={},Rc={};var Nc,Oc=function(){function t(t,e,n){var i=this;this._sleepAft
    - ${t?ht:ct`
    ${n("card.connecting")}
    `} +
    ${t}
    `}return ct`
    @@ -333,7 +324,7 @@ var Ec={},Rc={};var Nc,Oc=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: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` + `}_onPanelChange(t){const e=t.target;this._selectedPanelId=e.value,localStorage.setItem("span_panel_selected",e.value),this._isFavoritesView&&DD(this._activeTab)&&(this._activeTab="activity"),this._unsubscribeAreaTab(),this._areaTopology=null}get _isFavoritesView(){return this._selectedPanelId===PD}_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&&!DD(n)&&(this._favoritesViewState.activeTab=n,MD(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,MD(n)},250)}_subscribeDeviceRegistry(){return this.hass.connection.subscribeEvents(t=>this._onDeviceRegistryUpdated(t),"device_registry_updated")}_onDeviceRegistryUpdated(t){this._requestPanelsRefresh();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:vD.some(t=>t in n)?e.device_id:null}(t);if(e){for(const[t,n]of this._renderedTopologies)_D(n,e)&&this._renamedPanelIds.add(t);this._renamedPanelIds.size>0&&this._renameRefresh()}}_subscribeEntryReloads(){return Ti(this.hass,t=>t.domain===s,t=>this._onEntryLoaded(t),{initialIsReseed:!1,onStatus:(t,e)=>this._onEntryStatus(t,e)})}_onEntryStatus(t,e){null===e?this._entryLoads.delete(t):this._entryLoads.set(t,e),"loaded"!==e&&this._waitEntries.has(t)&&this._requestTabRender()}_showPanelWait(t,e){const[n,...i]=e;var r;!function(t,e){const{text:n,role:i,color:r}=Oe(e),o=document.createElement("div");o.setAttribute("role",i),o.style.padding="24px",o.style.color=r,o.textContent=n,t.replaceChildren(o)}(t,(r=[this._waitFor(n),...i.map(t=>this._waitFor(t))],r.includes("waiting")?"waiting":r.includes("setup_failed")?"setup_failed":r.includes("restart_needed")?"restart_needed":"disabled"))}_showViewWait(t,e){this._isShown(e)&&this._showPanelWait(t,[e.panelId])}_isShown(t){return t.tab===this._activeTab&&t.panelId===this._selectedPanelId}_waitFor(t){const e=this._panels.find(e=>e.id===t)?.config_entry_id;if(void 0===e)throw new Error(`span-panel: a view waits for panel ${t}, which the dashboard does not list`);return this._waitEntries.add(e),void 0===(n=this._entryLoads.get(e))||"loading"===n||"loaded"===n?"waiting":n;var n}_syncRatingSubscriptions(){const t=this.hass;if(!this.isConnected)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!==PD&&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,bD(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!==PD&&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=TD(()=>{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._waitEntries.delete(t)||this._monitoringAwaitsLoad(t),n=this._panels.find(e=>e.id!==PD&&e.config_entry_id===t);this._isFavoritesView||n&&n.id===this._selectedPanelId?n?(this._isFavoritesView||this._updatePanelStatusWatch(n.id),(!this._isFavoritesView||this._renderedTopologies.has(n.id)||In(this._favorites,n.id))&&(this._isFavoritesView||"adopted"!==this._activeTab?e?this._requestTabRender():this._renderIfRestructured(n.id,e=>this._refreshOpenSidePanel(t,e,null)):this._adoptedTab.refresh())):this._requestTabRender():this._requestPanelsRefresh()}_monitoringAwaitsLoad(t){if("monitoring"===this._activeTab){const e=this._isFavoritesView?this._favoritesMonitoring?.blocks.get(t)?.tab:this._monitoringTab;return!0===e?.awaitsLoadOf(t)}return this._isFavoritesView&&this._listDashCtrl.monitoringMultiCache.awaitingLoad(t)}async _renderIfRestructured(t,e){const n=this._renderedTopologies.get(t);if(!n)return void this._requestTabRender();let i;try{({topology:i}=await Di(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)&&HP(wD(r),wD(o))||this._requestTabRender()))}async _fetchBaselineTopology(t){try{return(await Di(this.hass,t,null)).topology}catch(t){return Le(t)?Ee:(console.warn("SPAN Panel: no topology baseline for this view:",Jt(t)),null)}}_recordRenderedTopology(t,e){e&&this._isShown(t)&&this._renderedTopologies.set(t.panelId,e)}_subscribeAreaTab(){this._areaSub||(this._areaSub=async function(t,e,i,r){const o=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 ki(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})}},a=await Promise.all(Ci.map(e=>t.connection.subscribeEvents(o,e)));return()=>{for(const t of a)t()}}(this.hass,()=>this._areaTopology,()=>{"area"===this._activeTab&&this._scheduleTabRender()},this._errorStore))}_unsubscribeAreaTab(){const t=this._areaSub;this._areaSub=null,t?.then(t=>t())}async _refreshPanels(){if(!this._discovered)return;let t;try{t=await Pi(this.hass)}catch(t){if(!Pe(t))throw t;return void(this._awaitingConnection=!0)}this._awaitingConnection=!1;const e=this._panels.filter(t=>t.id!==PD),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))){const e=t[0]?.id??(An(this._favorites)?PD:null);this._selectedPanelId=e,null!==e&&localStorage.setItem("span_panel_selected",e)}}async _updatePanelStatusWatch(t){if(this._watchedPanelId===t)return;const e=t;this._watchedPanelId=e;try{const t=new $e(this._errorStore,{passThrough:Le}),n=await Di(this.hass,e,t);if(this._selectedPanelId!==e)return;const i=n.topology.panel_entities?.panel_status;i&&(this._errorStore.watchPanelStatus(i),this._errorStore.updateHass(this.hass))}catch(t){Le(t)||console.warn("SPAN Panel: unable to fetch topology for panel status watching",t),this._watchedPanelId===e&&(this._watchedPanelId=null)}}async _discoverPanels(){if(!this._discovering){this._discovering=!0;try{let t;try{t=await Pi(this.hass)}catch(t){if(!Pe(t))throw t;return void(this._awaitingConnection=!0)}this._awaitingConnection=!1,this._favorites=await this._loadFavorites(),this._panels=this._buildPanelList(t,this._favorites),this._favoritesViewState=function(){try{const t=localStorage.getItem(kD);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===PD){const t=this._favoritesViewState.activeTab;"activity"===t||"area"===t||"monitoring"===t?this._activeTab=t:DD(this._activeTab)&&(this._activeTab="activity")}this._chartMetric=localStorage.getItem("span_panel_metric")||"power"}finally{this._discovering=!1}}}_buildPanelList(t,e){if(!An(e))return t;return[{id:PD,name:n("panel.favorites"),model:"__favorites__"},...t]}async _loadFavorites(){return 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===PD;this._favorites=e;const i=this._panels.filter(t=>t.id!==PD);if(this._panels=this._buildPanelList(i,e),n&&!An(e)){!function(){try{localStorage.removeItem(kD)}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 ${Bi(e,{note:!1})}\n
    \n ${Vi()}\n
    \n \n \n
    \n
    \n
    \n `}("current"===(this._chartMetric||"power"),hn(t))}_buildFavoritesPanelStatsGridHTML(t,e,n){if(0===t.length)return"";const i=gn(e,fn);return`
    ${t.map(t=>`\n
    \n
    ${Ft(t.panelName||t.topology.device_name||"")}
    \n ${(t=>{const e=i.get(t);return e?Cn(e):""})(t.panelDeviceId)}\n ${ji(t.topology,n,t.panelDeviceId)}\n
    \n `).join("")}
    `}_updateFavoritesPanelStats(t,e){for(const n of this._favoritesPanelStats){const i=t.querySelector(`.panel-stats[data-stats-panel-id="${nr(n.panelDeviceId)}"]`);i&&LI(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}}_stopViews(){this._dashboardTab.stop(),this._monitoringTab.stop(),this._adoptedTab.stop(),this._listCtrl.stop(),this._listDashCtrl.stopIntervals(),this._dropFavoritesMonitoring()}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._root.getElementById("tab-content"),e=this._renderedView,n={tab:this._activeTab,panelId:this._selectedPanelId},i=null!==t&&null!==e&&e.tab===n.tab&&e.panelId===n.panelId;if(this._dashboardTab.stop(),i||(this._monitoringTab.stop(),this._dropFavoritesMonitoring()),this._adoptedTab.stop(),this._listCtrl.stop(),this._listDashCtrl.stopIntervals(),this._favoritesPanelStats=[],this._renderedTopologies.clear(),this._waitEntries.clear(),!t)return;if(this._renderedView=n,this._isFavoritesView)return void await this._renderFavoritesTab(t,i);this._listDashCtrl.clearFavoriteRefs(),this._listCtrl.setViewName(null),this._applyPanelFavorites();const r=n.panelId;if(null===r)return void this._showNoPanel(t);const o={tab:n.tab,panelId:r};switch(this._activeTab){case"dashboard":{t.innerHTML="";const e=this._buildDashboardConfig(),n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null,a=await this._dashboardTab.render(t,this.hass,r,e,i);a===Ee?this._showViewWait(t,o):this._recordRenderedTopology(o,a);break}case"activity":{t.innerHTML="";const e=this._panels.find(t=>t.id===this._selectedPanelId),n=e?.config_entry_id??null;try{const e=new $e(this._errorStore,{passThrough:Le}),i=await Di(this.hass,r,e),a=this._buildDashboardConfig();if(this._listDashCtrl.init(i.topology,a,this.hass,n),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,n),this._listDashCtrl.monitoringCache.awaitingLoad){this._showViewWait(t,o);break}await this._listDashCtrl.fetchAndBuildHorizonMaps();const s=qi(i.topology,a);this._listCtrl.setColumns(this._listColumns),this._listCtrl.renderActivityView(t,this.hass,i.topology,a,this._listDashCtrl.monitoringCache.status,s),await this._listDashCtrl.loadHistory(),this._listDashCtrl.updateDOM(t),this._listDashCtrl.startIntervals(t),this._recordRenderedTopology(o,i.topology)}catch(e){this._showListViewFailure(t,o,e)}break}case"area":{t.innerHTML="";const e=this._panels.find(t=>t.id===this._selectedPanelId),n=e?.config_entry_id??null;try{const e=new $e(this._errorStore,{passThrough:Le}),i=await Di(this.hass,r,e),a=this._buildDashboardConfig();if(this._listDashCtrl.init(i.topology,a,this.hass,n),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,n),this._listDashCtrl.monitoringCache.awaitingLoad){this._showViewWait(t,o);break}await this._listDashCtrl.fetchAndBuildHorizonMaps();const s=qi(i.topology,a);this._listCtrl.setColumns(this._listColumns),this._listCtrl.renderAreaView(t,this.hass,i.topology,a,this._listDashCtrl.monitoringCache.status,s),await this._listDashCtrl.loadHistory(),this._listDashCtrl.updateDOM(t),this._listDashCtrl.startIntervals(t),this._recordRenderedTopology(o,i.topology),this._areaTopology=i.topology,this.isConnected&&this._subscribeAreaTab()}catch(e){this._showListViewFailure(t,o,e)}break}case"monitoring":{i||(t.innerHTML="");const e=this._panels.find(t=>t.id===this._selectedPanelId),n=e?.config_entry_id??null,a=await this._fetchBaselineTopology(r);if(a===Ee||await this._monitoringTab.render(t,this.hass,n??void 0,a)===Ee){this._monitoringTab.stop(),this._showViewWait(t,o);break}this._recordRenderedTopology(o,a);break}case"adopted":t.innerHTML="";await this._adoptedTab.render(t,this.hass,r)===Ee&&this._showViewWait(t,o);break}}_showNoPanel(t){const e=document.createElement("p");e.style.padding="24px",e.style.color="var(--secondary-text-color)",e.textContent=n("panel.no_panels"),t.replaceChildren(e)}_showListViewFailure(t,e,n){if(Le(n))return void this._showViewWait(t,e);const i=document.createElement("p");i.style.color="var(--error-color)",i.textContent=Jt(n),t.appendChild(i)}async _renderFavoritesTab(t,e){const i=e?this._shownFavoritesMonitoring(t):null;i||(this._dropFavoritesMonitoring(),t.innerHTML="");const r=this._panels.filter(t=>t.id!==PD),o=await this._favCtrl.build(this.hass,this._favorites,r,this._errorStore);for(const t of o.perPanelStats)this._renderedTopologies.set(t.panelDeviceId,t.topology);const a=o.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._errorStore.watchPanelStatuses(a),this._errorStore.updateHass(this.hass);const s=new Map;for(const t of o.perPanelStats){const e=r.find(e=>e.id===t.panelDeviceId);s.set(t.panelDeviceId,{panelName:t.panelName,topology:t.topology,configEntryId:e?.config_entry_id??null})}this._listDashCtrl.setFavoritesPerPanelInfo(s);const l=o.topology,c=o.entryIds[0]??null,d=Object.keys(l.circuits).length>0,u=Object.keys(l.sub_devices??{}).length>0;if(!d&&!u){this._dropFavoritesMonitoring();const[e,...i]=o.awaitingPanelIds.filter(t=>this._panels.some(e=>e.id===t));if(void 0!==e)return void this._showPanelWait(t,[e,...i]);t.innerHTML="";const r=document.createElement("p");return r.style.color="var(--secondary-text-color)",r.style.padding="24px",r.textContent=n("list.no_results"),void t.appendChild(r)}if(this._listDashCtrl.setFavoriteRefs(l._favoriteRefs),this._listDashCtrl.setPanelFavorites(null),"monitoring"===this._activeTab){this._listCtrl.setViewName(null);const e=new Map;for(const t of s.values())t.configEntryId&&e.set(t.configEntryId,t.topology);return void await this._renderFavoritesMonitoring(t,o.entryIds,r,i,e)}const h=this._activeTab,p=new Set(Object.keys(l.circuits)),f=this._favoritesViewState.expanded[h].filter(t=>p.has(t));this._listCtrl.setViewName(h),this._listCtrl.setInitialExpansion(f),this._listCtrl.setInitialSearchQuery(this._favoritesViewState.searchQuery??""),this._listCtrl.setColumns(this._listColumns);const g=this._buildDashboardConfig();this._listDashCtrl.init(l,g,this.hass,c),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.fetchAndBuildHorizonMaps();const m=await this._listDashCtrl.fetchMergedMonitoringStatus(o.entryIds);this._favoritesPanelStats=o.perPanelStats;try{await this._listDashCtrl.loadHistory();const e=this._buildFavoritesSummaryHTML(l),n=this._buildFavoritesPanelStatsGridHTML(o.perPanelStats,l,g),i=e+n+(u?`
    \n
    ${sr(l,this.hass,g,{showFavorites:this._listDashCtrl.showFavorites})}
    \n
    `:"");"activity"===h?this._listCtrl.renderActivityView(t,this.hass,l,g,m,i):this._listCtrl.renderAreaView(t,this.hass,l,g,m,i),this._updateFavoritesPanelStats(t,g),this._listDashCtrl.setupResizeObserver(t,t),this._listDashCtrl.startIntervals(t,()=>{this._updateFavoritesPanelStats(t,g)})}catch(e){const n=document.createElement("p");n.style.color="var(--error-color)",n.textContent=Jt(e),t.appendChild(n)}}async _renderFavoritesMonitoring(t,e,n,i,r){const o=this.hass,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));for(const[t,n]of e.entries()){if(!this.isConnected)return;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)===Ee&&this._showBlockWait(l,e)}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)}}}_showBlockWait(t,e){t.tab.stop(),e&&this._panels.some(t=>t.id===e.id)?this._showPanelWait(t.body,[e.id]):t.body.replaceChildren()}_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");return t.appendChild(n),{tab:new zP(this._errorStore),block:t,heading:e,body:n}}_shownFavoritesMonitoring(t){const e=this._favoritesMonitoring;return null!==e&&e.wrapper.parentElement===t?e:null}_dropFavoritesMonitoring(){for(const{tab:t}of this._favoritesMonitoring?.blocks.values()??[])t.stop();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)}};LD._shellStyles=k` :host { color: var(--primary-text-color); } @@ -430,4 +421,4 @@ var Ec={},Rc={};var Nc,Oc=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(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;"); + `,LD.styles=[ID._shellStyles,C(BI)],_([Lt({attribute:!1})],LD.prototype,"hass",void 0),_([Lt({type:Boolean,reflect:!0})],LD.prototype,"narrow",void 0),_([Et()],LD.prototype,"_panels",void 0),_([Et()],LD.prototype,"_selectedPanelId",void 0),_([Et()],LD.prototype,"_activeTab",void 0),_([Et()],LD.prototype,"_discovered",void 0),_([Et()],LD.prototype,"_awaitingConnection",void 0),_([Et()],LD.prototype,"_chartMetric",void 0),_([Et()],LD.prototype,"_listColumns",void 0),_([Et()],LD.prototype,"_favorites",void 0),LD=ID=_([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})("span-panel")],LD),console.warn("%c SPAN-PANEL %c v0.12.1-beta.3 ","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;");