From b4b5bf1efaa328edbcf795650465117d6d7a4d62 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:29:27 -0800 Subject: [PATCH 01/15] refactor(controls): say once who the control mode lets operate the panel ControlPolicy.refusal_for answers why the mode refuses a caller, judged by whether the caller is an administrator, or None for a caller with no logged-in user, whom only Nobody refuses. The gate asks it once per command and acts on the answer in its own order: Nobody first, then the lock, then contextless control, then Administrators only. Every refusal and its message is unchanged. --- custom_components/span_panel/control_gate.py | 70 +++++++++++++++++--- tests/test_control_gate.py | 19 ++++++ 2 files changed, 81 insertions(+), 8 deletions(-) diff --git a/custom_components/span_panel/control_gate.py b/custom_components/span_panel/control_gate.py index b2e7bb26..5b5506b6 100644 --- a/custom_components/span_panel/control_gate.py +++ b/custom_components/span_panel/control_gate.py @@ -96,6 +96,22 @@ class ControlMode(StrEnum): """ +class ControlAccessRefusal(StrEnum): + """Why the control mode refuses a caller, judged by who the caller is. + + The values are wire values: `span_panel/panel_topology` reports them to the + card as `control_access.reason`. They are not the gate's translation keys, + which name the refusal a service caller is shown and are free to be worded + for that reader. + """ + + CONTROL_DISABLED = "control_disabled" + """The mode is `disabled`, so no one may operate the panel.""" + + ADMIN_ONLY = "admin_only" + """The mode is `admin_only` and the caller is not an administrator.""" + + @dataclass(frozen=True, slots=True) class ControlCaller: """Who issued the command currently being published, if anyone. @@ -171,6 +187,30 @@ def lock_enabled(self) -> bool: """ return self.lock_timeout_minutes is not None and self.mode is not ControlMode.DISABLED + def refusal_for(self, *, is_admin: bool | None) -> ControlAccessRefusal | None: + """Why the control mode refuses this caller, or None where it does not. + + The one statement of who the mode lets operate the panel. The gate + enforces it on every command, and `span_panel/panel_topology` reports it + for whoever is viewing the card, so the controls the card offers and the + commands the gate lets through cannot come to disagree. + + `is_admin` is None for a caller with no logged-in user. `disabled` + refuses that caller as it refuses everyone. `admin_only` does not judge + it, there being no user to judge: whether a command with no user is let + through is `allow_contextless`'s question, which the gate asks on its + own. + + Nothing here is about the moment. Whether the control lock is armed + changes while a page is open, and the relay debounce is about one + circuit's last command; the gate asks both itself. + """ + if self.mode is ControlMode.DISABLED: + return ControlAccessRefusal.CONTROL_DISABLED + if self.mode is ControlMode.ADMIN_ONLY and is_admin is False: + return ControlAccessRefusal.ADMIN_ONLY + return None + @classmethod def default(cls) -> ControlPolicy: """Return the policy an entry with no control options configured has. @@ -386,13 +426,18 @@ async def before_publish(self, command: ControlCommand) -> None: context = caller.context if caller is not None else None user_id = context.user_id if context is not None else None + # Judged once, by the rule the topology reports to the card, and acted + # on below in this method's own order: `disabled` before everything, + # `admin_only` last. + refusal = self._policy.refusal_for(is_admin=await self._caller_is_admin(user_id)) + # First, because it is the entry-wide answer and the most useful thing # to be told. Not creating the entities is what a user sees, but it is # not a choke point: a command arriving by any other route -- a service # this integration grows later, a code path that forgets the helper -- # would otherwise be published by an entry whose owner switched control # off. That is the promise this module opens with. - if self._policy.mode is ControlMode.DISABLED: + if refusal is ControlAccessRefusal.CONTROL_DISABLED: self._refuse( "control_disabled", "Control of this SPAN panel is switched off in its options. " @@ -413,13 +458,11 @@ async def before_publish(self, command: ControlCommand) -> None: parent_id=context.parent_id if context is not None else None, ) - if self._policy.mode is ControlMode.ADMIN_ONLY and user_id is not None: - user = await self._hass.auth.async_get_user(user_id) - if user is None or not user.is_admin: - self._refuse( - "admin_only_control", - "Only a Home Assistant administrator may operate this SPAN panel.", - ) + if refusal is ControlAccessRefusal.ADMIN_ONLY: + self._refuse( + "admin_only_control", + "Only a Home Assistant administrator may operate this SPAN panel.", + ) if command.property_id == RELAY_PROPERTY: self._refuse_a_debounced_relay(command) @@ -461,6 +504,17 @@ async def after_publish(self, command: ControlCommand, outcome: PublishOutcome) # -- internals ---------------------------------------------------------- + async def _caller_is_admin(self, user_id: str | None) -> bool | None: + """Whether the caller is an administrator, or None when there is no logged-in user. + + A user id that no longer resolves -- a user deleted since the call was + made -- is not an administrator. + """ + if user_id is None: + return None + user = await self._hass.auth.async_get_user(user_id) + return user is not None and user.is_admin + def _refuse_a_debounced_relay(self, command: ControlCommand) -> None: """Refuse a relay command that follows too closely on the last one. diff --git a/tests/test_control_gate.py b/tests/test_control_gate.py index 309e3174..7fdbab2c 100644 --- a/tests/test_control_gate.py +++ b/tests/test_control_gate.py @@ -8,6 +8,7 @@ from __future__ import annotations +from dataclasses import replace from datetime import timedelta from unittest.mock import AsyncMock, MagicMock, patch @@ -21,6 +22,7 @@ from custom_components.span_panel.const import DOMAIN, EVENT_CONTROL_COMMAND from custom_components.span_panel.control_gate import ( CONTROL_CALLER, + ControlAccessRefusal, ControlGate, ControlLock, ControlMode, @@ -683,6 +685,23 @@ def test_an_entry_with_no_control_options_gets_the_defaults() -> None: assert policy.relay_debounce_seconds == 2.0 +@pytest.mark.parametrize( + ("mode", "refusal"), + [ + (ControlMode.ALL_USERS, None), + (ControlMode.ADMIN_ONLY, None), + (ControlMode.DISABLED, ControlAccessRefusal.CONTROL_DISABLED), + ], +) +def test_the_mode_judges_a_caller_with_no_user_only_by_refusing_everyone( + mode: ControlMode, refusal: ControlAccessRefusal | None +) -> None: + """`admin_only` has no user to judge; whether such a command goes through is `allow_contextless`'s question.""" + policy = replace(ControlPolicy.default(), mode=mode) + + assert policy.refusal_for(is_admin=None) is refusal + + def test_an_unrecognised_mode_falls_back_to_the_permissive_one() -> None: """A typo in `.storage` must not lock a household out of its own panel.""" policy = ControlPolicy.from_options({"control_mode": "nonsense"}) From f9997bbecaa388b8078c8b9779bdd3c5f2c64168 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:32:13 -0800 Subject: [PATCH 02/15] feat(websocket): tell the topology's asker whether they may operate the panel span_panel/panel_topology answers control_access, {may_operate, reason}, for the user the connection is authenticated as. The reason is what ControlPolicy.refusal_for, the rule the gate refuses a command by, answers for that user under the entry's policy: null, admin_only or control_disabled. The card can then disable the relay and priority controls of a user the gate would refuse. The control lock is not part of it, and contextless control never applies to a WebSocket caller. A test runs the topology and the gate for every mode and every kind of user and holds them to one answer. The capture topologies gain the key, and the test that an open command answers a non-admin as it answers an administrator now sets aside what the answer says about its asker. --- custom_components/span_panel/websocket.py | 31 ++- tests/fixtures/topology/main32_r202633.json | 4 + .../main32_r202639-battery-unvalued.json | 4 + .../topology/main32_r202639-no-battery.json | 4 + .../main32_r202639-unpublished-readings.json | 4 + tests/fixtures/topology/main32_r202639.json | 4 + tests/fixtures/topology/r202639-a.json | 4 + tests/fixtures/topology/r202639-b.json | 4 + tests/fixtures/topology/r202639-c.json | 4 + tests/fixtures/topology/r202639-d.json | 4 + tests/fixtures/topology/r202639-e.json | 4 + tests/test_topology_control_access.py | 197 ++++++++++++++++++ tests/test_websocket_admin_rule.py | 36 +++- 13 files changed, 300 insertions(+), 4 deletions(-) create mode 100644 tests/test_topology_control_access.py diff --git a/custom_components/span_panel/websocket.py b/custom_components/span_panel/websocket.py index 01eac0a0..b37bdb63 100644 --- a/custom_components/span_panel/websocket.py +++ b/custom_components/span_panel/websocket.py @@ -13,7 +13,7 @@ from span_panel_api import shared_meter_groups from .const import DOMAIN -from .control_gate import ControlMode +from .control_gate import ControlAccessRefusal, ControlMode, ControlPolicy from .current_monitor import MonitoredCircuit, monitored_circuits from .energy_orientation import circuit_is_generation from .entity_resolver import entity_id_in_entry @@ -38,6 +38,7 @@ from .websocket_panel import resolve_panel_device if TYPE_CHECKING: + from homeassistant.auth.models import User from span_panel_api import SpanCircuitSnapshot, SpanPanelSnapshot # Mapping from unique_id suffixes to semantic role names for circuit sensors. @@ -110,7 +111,9 @@ async def handle_panel_topology( each circuit and device, the ratings current monitoring judges each circuit against, and the registry IDs that tie them together; no host, credential or certificate is in it. Whether a control it names may be operated is - decided by the control policy when the control is used, not here. + decided by the control policy when the control is used, not here; what + `control_access` carries is that policy's answer for the user asking, so + the card can offer no control the gate would refuse them. The caller passes the HA device registry ID for the **main SPAN panel** device only (not a sub-device or a circuit's device). Returns panel @@ -325,6 +328,10 @@ async def handle_panel_topology( # circuit's `package_ratings_form` says whether it takes a copy, and in # which form. "monitoring_rating_offered": not describes_breakers, + # Whether the user asking may operate the panel, by the policy the + # gate holds. It is the same object: setup hands one policy to the + # gate and to the runtime data, and an options change reloads both. + "control_access": _control_access_record(runtime_data.control_policy, connection.user), "circuits": circuits, # Each shared meter by the key its members carry in `shared_meter_group`. "shared_meter_groups": meter_groups, @@ -359,6 +366,26 @@ def _meter_group_record(point: MonitoredCircuit) -> MeterGroupRecord: ) +class ControlAccessRecord(TypedDict): + """Whether the user asking may operate the panel, and if not, why. + + `reason` is `ControlPolicy.refusal_for`'s answer for that user, the answer + the gate refuses a command by, and `may_operate` is true exactly where it is + null. Neither says whether the control lock is armed, which changes while + the card is open and which the card reads from the lock's own switch. A + WebSocket connection always has a logged-in user, so whether control + without one is allowed never comes into it. + """ + + may_operate: bool + reason: ControlAccessRefusal | None + + +def _control_access_record(policy: ControlPolicy, user: User) -> ControlAccessRecord: + refusal = policy.refusal_for(is_admin=user.is_admin) + return ControlAccessRecord(may_operate=refusal is None, reason=refusal) + + def _group_of(groups: Mapping[str, tuple[str, ...]]) -> dict[str, str]: """Map every member of every group to its group's key.""" return {member: key for key, members in groups.items() for member in members} diff --git a/tests/fixtures/topology/main32_r202633.json b/tests/fixtures/topology/main32_r202633.json index 882f9062..1c236fcb 100644 --- a/tests/fixtures/topology/main32_r202633.json +++ b/tests/fixtures/topology/main32_r202633.json @@ -687,6 +687,10 @@ } }, "config_entry_id": "entry-main32_r202633", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "nt-0000-panel", "device_name": "Span Panel", "firmware": "spanos3/r202633/02", diff --git a/tests/fixtures/topology/main32_r202639-battery-unvalued.json b/tests/fixtures/topology/main32_r202639-battery-unvalued.json index eb465977..e57cf43f 100644 --- a/tests/fixtures/topology/main32_r202639-battery-unvalued.json +++ b/tests/fixtures/topology/main32_r202639-battery-unvalued.json @@ -589,6 +589,10 @@ } }, "config_entry_id": "entry-main32_r202639-battery-unvalued", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "nt-9874-s7rxt", "device_name": "Span Panel", "firmware": "spanos3/r202639/03", diff --git a/tests/fixtures/topology/main32_r202639-no-battery.json b/tests/fixtures/topology/main32_r202639-no-battery.json index 26c46d22..faf256bb 100644 --- a/tests/fixtures/topology/main32_r202639-no-battery.json +++ b/tests/fixtures/topology/main32_r202639-no-battery.json @@ -589,6 +589,10 @@ } }, "config_entry_id": "entry-main32_r202639-no-battery", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "nt-9874-s7rxt", "device_name": "Span Panel", "firmware": "spanos3/r202639/03", diff --git a/tests/fixtures/topology/main32_r202639-unpublished-readings.json b/tests/fixtures/topology/main32_r202639-unpublished-readings.json index b07f0e97..4bcf02b3 100644 --- a/tests/fixtures/topology/main32_r202639-unpublished-readings.json +++ b/tests/fixtures/topology/main32_r202639-unpublished-readings.json @@ -589,6 +589,10 @@ } }, "config_entry_id": "entry-main32_r202639-unpublished-readings", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "nt-9874-s7rxt", "device_name": "Span Panel", "firmware": "spanos3/r202639/03", diff --git a/tests/fixtures/topology/main32_r202639.json b/tests/fixtures/topology/main32_r202639.json index c6120988..06464ab8 100644 --- a/tests/fixtures/topology/main32_r202639.json +++ b/tests/fixtures/topology/main32_r202639.json @@ -589,6 +589,10 @@ } }, "config_entry_id": "entry-main32_r202639", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "nt-9874-s7rxt", "device_name": "Span Panel", "firmware": "spanos3/r202639/03", diff --git a/tests/fixtures/topology/r202639-a.json b/tests/fixtures/topology/r202639-a.json index e6581ef8..caecbb59 100644 --- a/tests/fixtures/topology/r202639-a.json +++ b/tests/fixtures/topology/r202639-a.json @@ -105,6 +105,10 @@ } }, "config_entry_id": "entry-r202639-a", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "xg-3940-9ooto", "device_name": "Span Panel", "firmware": "spanos3/r202639/03", diff --git a/tests/fixtures/topology/r202639-b.json b/tests/fixtures/topology/r202639-b.json index fb373d16..7994cac0 100644 --- a/tests/fixtures/topology/r202639-b.json +++ b/tests/fixtures/topology/r202639-b.json @@ -609,6 +609,10 @@ } }, "config_entry_id": "entry-r202639-b", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "xg-1155-18fkf", "device_name": "Span Panel", "firmware": "spanos3/r202639/03", diff --git a/tests/fixtures/topology/r202639-c.json b/tests/fixtures/topology/r202639-c.json index 4d28f4e9..07831b6b 100644 --- a/tests/fixtures/topology/r202639-c.json +++ b/tests/fixtures/topology/r202639-c.json @@ -181,6 +181,10 @@ } }, "config_entry_id": "entry-r202639-c", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "xg-7814-15i6h", "device_name": "Span Panel", "firmware": "spanos3/r202639/03", diff --git a/tests/fixtures/topology/r202639-d.json b/tests/fixtures/topology/r202639-d.json index 4d67083b..e77e7f51 100644 --- a/tests/fixtures/topology/r202639-d.json +++ b/tests/fixtures/topology/r202639-d.json @@ -254,6 +254,10 @@ } }, "config_entry_id": "entry-r202639-d", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "xg-1334-066e8", "device_name": "Span Panel", "firmware": "spanos3/r202639/03", diff --git a/tests/fixtures/topology/r202639-e.json b/tests/fixtures/topology/r202639-e.json index d2eb7340..a7ec7161 100644 --- a/tests/fixtures/topology/r202639-e.json +++ b/tests/fixtures/topology/r202639-e.json @@ -1661,6 +1661,10 @@ } }, "config_entry_id": "entry-r202639-e", + "control_access": { + "may_operate": true, + "reason": null + }, "device_id": "xg-6159-74dlx", "device_name": "Span Panel", "firmware": "spanos3/r202639/03", diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py new file mode 100644 index 00000000..5d985056 --- /dev/null +++ b/tests/test_topology_control_access.py @@ -0,0 +1,197 @@ +"""`span_panel/panel_topology` tells the card whether the user asking may operate the panel. + +`control_access` is the control mode's answer for the WebSocket connection's +user, by `ControlPolicy.refusal_for` -- the rule the gate refuses a command by. +The card disables the panel's controls for a user it says may not operate them, +so what it says and what the gate does must not come apart: the last test runs +both, for every mode and every kind of user, and holds them to one answer. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import replace +from typing import Final +from unittest.mock import AsyncMock, MagicMock + +from homeassistant.auth.const import GROUP_ID_ADMIN, GROUP_ID_READ_ONLY, GROUP_ID_USER +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import Context, HomeAssistant +from homeassistant.exceptions import ServiceValidationError +import pytest +from pytest_homeassistant.common import CLIENT_ID, MockConfigEntry, MockUser +from pytest_homeassistant.typing import WebSocketGenerator +from span_panel_api import ControlCommand, FieldMetadata + +from custom_components.span_panel.const import DOMAIN +from custom_components.span_panel.control_gate import ( + CONTROL_CALLER, + ControlGate, + ControlLock, + ControlMode, + ControlPolicy, + async_bind_caller, +) +from custom_components.span_panel.curation import CurationOverlay +from custom_components.span_panel.package_rating_manager import PackageRatingManager +from custom_components.span_panel.runtime import SpanPanelRuntimeData +from custom_components.span_panel.websocket import async_register_commands + +from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory, pv_binding_for +from .helpers import register_panel_device + +_SERIAL: Final = "sp3-synthetic-access-001" +_CIRCUIT_ID: Final = "circuit-3" +_DECLARED: Final = {"panel.main_breaker_rating_a": FieldMetadata(unit="A", datatype="integer")} + +_PRIORITY: Final = ControlCommand( + device_id=_SERIAL, + node_id=_CIRCUIT_ID, + property_id="priority", + value="OFF_GRID", + topic=f"ebus/5/{_CIRCUIT_ID}/load-shed/priority/set", +) +"""A command the relay debounce never touches, so a refusal is only ever about who asked.""" + +EXPECTED_REASON: Final[Mapping[tuple[ControlMode, bool], str | None]] = { + (ControlMode.ALL_USERS, True): None, + (ControlMode.ALL_USERS, False): None, + (ControlMode.ADMIN_ONLY, True): None, + (ControlMode.ADMIN_ONLY, False): "admin_only", + (ControlMode.DISABLED, True): "control_disabled", + (ControlMode.DISABLED, False): "control_disabled", +} +"""`control_access.reason` by control mode and whether the asker is an administrator. + +Written as the wire values the card reads, so renaming one fails here. +""" + +GATE_REFUSAL: Final[Mapping[str | None, str | None]] = { + None: None, + "admin_only": "admin_only_control", + "control_disabled": "control_disabled", +} +"""The refusal the gate gives a command, by the `control_access.reason` the topology reports. + +None is no refusal on either side: the topology says the user may operate the +panel, and the gate lets the command through. +""" + +_GROUPS: Final = { + "administrator": GROUP_ID_ADMIN, + "ordinary user": GROUP_ID_USER, + "read-only user": GROUP_ID_READ_ONLY, +} + + +@pytest.fixture(params=list(_GROUPS.values()), ids=list(_GROUPS)) +async def asker(hass: HomeAssistant, request: pytest.FixtureRequest) -> MockUser: + """Return a logged-in user from each group a Home Assistant user can be in.""" + group = await hass.auth.async_get_group(request.param) + assert group is not None + user = MockUser(groups=[group]).add_to_hass(hass) + assert user.is_admin is (request.param == GROUP_ID_ADMIN) + return user + + +async def _load_panel(hass: HomeAssistant, mode: ControlMode) -> tuple[MockConfigEntry, str]: + """Load a one-circuit panel whose control mode is `mode`, and return its entry and device's registry ID.""" + snapshot = SpanPanelSnapshotFactory.create( + serial_number=_SERIAL, + circuits={ + _CIRCUIT_ID: SpanCircuitSnapshotFactory.create( + circuit_id=_CIRCUIT_ID, name="Synthetic Circuit", tabs=[3], breaker_rating_a=20.0 + ) + }, + main_breaker_rating_a=100, + ) + entry = MockConfigEntry(domain=DOMAIN, data={}, unique_id=_SERIAL) + entry.add_to_hass(hass) + manager = PackageRatingManager(hass, entry) + await manager.async_load() + manager.begin(snapshot, _DECLARED) + coordinator = MagicMock() + coordinator.data = snapshot + coordinator.package_rating_manager = manager + # Home Assistant unloads the loaded entry as the test ends, which shuts the + # coordinator down. + coordinator.async_shutdown = AsyncMock() + device_id = register_panel_device(hass, entry, _SERIAL) + entry.runtime_data = SpanPanelRuntimeData( + coordinator=coordinator, + panel_device_id=device_id, + curation=CurationOverlay.empty(), + pv_binding=pv_binding_for(snapshot), + setup_snapshot=snapshot, + control_policy=replace(ControlPolicy.default(), mode=mode), + ) + entry.mock_state(hass, ConfigEntryState.LOADED) + async_register_commands(hass) + return entry, device_id + + +async def _control_access( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, user: MockUser, device_id: str +) -> dict[str, object]: + """Ask for the topology as `user` and return its `control_access`.""" + refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID) + client = await hass_ws_client(hass, hass.auth.async_create_access_token(refresh_token)) + await client.send_json_auto_id({"type": "span_panel/panel_topology", "device_id": device_id}) + reply = await client.receive_json() + assert reply["success"] is True, reply + control_access = reply["result"]["control_access"] + assert isinstance(control_access, dict) + return control_access + + +async def _gate_refusal(hass: HomeAssistant, entry: MockConfigEntry, user: MockUser) -> str | None: + """Return the refusal the entry's gate gives `user`'s command, or None where it lets it through. + + The gate is built as setup builds it, from the policy the runtime data + holds, with the lock open so the only refusal left is about who asked. + """ + gate = ControlGate(hass, entry, entry.runtime_data.control_policy, ControlLock(armed=False)) + token = async_bind_caller(Context(user_id=user.id), "select.span_panel_synthetic_circuit") + try: + await gate.before_publish(_PRIORITY) + except ServiceValidationError as refused: + return refused.translation_key + finally: + CONTROL_CALLER.reset(token) + return None + + +def test_every_mode_has_an_expected_answer_for_both_kinds_of_user() -> None: + """A mode added later has to be given its answers here before the card can rely on them.""" + assert set(EXPECTED_REASON) == { + (mode, is_admin) for mode in ControlMode for is_admin in (True, False) + } + + +@pytest.mark.parametrize("mode", list(ControlMode)) +async def test_the_topology_says_whether_the_asker_may_operate_the_panel( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mode: ControlMode, asker: MockUser +) -> None: + """`may_operate` is true exactly where `reason` is null, and `reason` is the mode's answer for the asker.""" + _, device_id = await _load_panel(hass, mode) + + control_access = await _control_access(hass, hass_ws_client, asker, device_id) + + reason = EXPECTED_REASON[(mode, asker.is_admin)] + assert control_access == {"may_operate": reason is None, "reason": reason} + + +@pytest.mark.parametrize("mode", list(ControlMode)) +async def test_the_topology_and_the_gate_give_the_asker_the_same_answer( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mode: ControlMode, asker: MockUser +) -> None: + """The gate refuses the asker's command exactly where the topology says they may not operate the panel, and for the reason it gives.""" + entry, device_id = await _load_panel(hass, mode) + + control_access = await _control_access(hass, hass_ws_client, asker, device_id) + refusal = await _gate_refusal(hass, entry, asker) + + assert control_access["may_operate"] is (refusal is None) + reason = control_access["reason"] + assert reason is None or isinstance(reason, str) + assert GATE_REFUSAL[reason] == refusal diff --git a/tests/test_websocket_admin_rule.py b/tests/test_websocket_admin_rule.py index 1fd40220..2765cbe2 100644 --- a/tests/test_websocket_admin_rule.py +++ b/tests/test_websocket_admin_rule.py @@ -75,6 +75,16 @@ } """The commands every logged-in user may send.""" +ABOUT_THE_ASKER: Final[Mapping[str, frozenset[str]]] = { + "span_panel/panel_topology": frozenset({"control_access"}), +} +"""The keys of an open command's answer that describe the user asking, and so differ by user. + +`control_access` is the control policy's answer for that user; see +`test_topology_control_access.py`. Everything else an open command answers is +the same for every user. +""" + async def _non_admin(hass: HomeAssistant, group_id: str) -> MockUser: """Add a logged-in user in `group_id`, one of the groups a user who is not an administrator is in.""" @@ -108,6 +118,11 @@ async def _send( return reply +def _apart_from(result: Mapping[str, object], keys: frozenset[str]) -> dict[str, object]: + """Return a command's answer without `keys`.""" + return {key: value for key, value in result.items() if key not in keys} + + def _error_code(reply: Mapping[str, object]) -> object: """Return the code of a refused command's error.""" error = reply["error"] @@ -189,6 +204,11 @@ def test_the_classifications_do_not_overlap() -> None: assert not set(ADMINISTRATOR_ONLY) & set(OPEN_TO_EVERY_USER) +def test_only_an_open_command_answers_about_the_asker() -> None: + """A key set aside as describing the asker belongs to a command every user may send.""" + assert set(ABOUT_THE_ASKER) <= set(OPEN_TO_EVERY_USER) + + def _registered_commands(hass: HomeAssistant) -> set[str]: """Return the type of every WebSocket command registered on `hass`, whoever registered it.""" handlers = hass.data.get(websocket_api.DOMAIN, {}) @@ -254,7 +274,12 @@ async def test_an_open_command_answers_a_non_admin_as_it_answers_an_administrato command: str, fields: CommandFields, ) -> None: - """The answer does not depend on who asks: a non-admin gets exactly what an administrator gets.""" + """A non-admin gets exactly what an administrator gets, apart from what the answer says about the asker. + + The keys that describe the asker are set aside only once both answers are + seen to carry them, so naming one that the command does not answer fails + here rather than excusing nothing. + """ as_admin = await _send(await hass_ws_client(hass), command, fields(panel_device_id)) as_non_admin = await _send( await _client_for(hass, hass_ws_client, non_admin_user), command, fields(panel_device_id) @@ -262,7 +287,14 @@ async def test_an_open_command_answers_a_non_admin_as_it_answers_an_administrato assert as_admin["success"] is True assert as_non_admin["success"] is True - assert as_non_admin["result"] == as_admin["result"] + admin_result, non_admin_result = as_admin["result"], as_non_admin["result"] + assert isinstance(admin_result, dict) + assert isinstance(non_admin_result, dict) + about_the_asker = ABOUT_THE_ASKER.get(command, frozenset()) + assert about_the_asker <= set(admin_result) & set(non_admin_result) + assert _apart_from(non_admin_result, about_the_asker) == _apart_from( + admin_result, about_the_asker + ) async def test_a_non_admin_reads_the_panels_topology( From 804410eef3878552be236f3cedb6113e2e692801 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:34:42 -0800 Subject: [PATCH 03/15] docs(websocket-api): document the topology's control_access Says what may_operate and reason answer, for whom, and what they leave out: the control lock, the relay debounce and contextless control. Prettier rewraps the paragraph on the package-ratings event, which was committed unwrapped. --- websocket-api.md | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/websocket-api.md b/websocket-api.md index b783bb7c..541c5146 100644 --- a/websocket-api.md +++ b/websocket-api.md @@ -17,7 +17,8 @@ provides all of these relationships explicitly, keyed by circuit UUID, so the ca Any logged-in user may call it, administrator or not, so the sidebar dashboard and the card work for whoever is viewing them. It carries the panel's layout, what the panel publishes about each circuit and device, the ratings current monitoring judges each circuit against, and the registry IDs that tie them together; no host, credential or certificate is in it. Whether a switch or select it names can be operated is decided when it is used, by -[Who may operate the panel](README.md#restricting-who-can-operate-the-panel). +[Who may operate the panel](README.md#restricting-who-can-operate-the-panel). `control_access` reports that option's answer for the user asking, so a card can +disable the controls that user would be refused. ### Request @@ -49,6 +50,10 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID. "config_entry_id": "e5f6a7b8c9d0", "device_name": "SPAN Panel", "monitoring_rating_offered": true, + "control_access": { + "may_operate": true, + "reason": null + }, "circuits": { "a1b2c3d4e5f6": { "device_id": "c7d8e9f0a1b2", @@ -209,10 +214,24 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID. | `config_entry_id` | string | The config entry that owns the panel | | `device_name` | string | HA device display name | | `monitoring_rating_offered` | bool | Whether `set_circuit_package_ratings` takes ratings on this panel: false where the panel publishes each circuit of a multi-load breaker with its own rating | +| `control_access` | object | Whether the user asking may operate the panel, and if not, why (see below) | | `circuits` | object | Circuit UUID keyed map (see below) | | `shared_meter_groups` | object | Each group of circuits that share a meter, keyed by the group key its members carry in `shared_meter_group` (see below); empty where no meter is shared | | `sub_devices` | object | HA device ID keyed map of BESS/MID/EVSE/PV (see below) | +#### Control Access Object + +| Field | Type | Description | +| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `may_operate` | bool | Whether **Who may operate the panel** lets the user asking operate the panel's controls | +| `reason` | string/null | Why not: `control_disabled` where the option is `Nobody`, `admin_only` where it is `Administrators only` and the user is not an administrator; null where `may_operate` is true | + +The answer is for the user the WebSocket connection is authenticated as, so two users asking about the same panel can be told different things. It comes from +the rule the integration refuses a control command by, so a card that disables its relay and priority controls where `may_operate` is false offers no control +that rule would refuse. It says nothing about the control lock, which can be armed or disarmed while a page is open and which its switch reports, nor about the +relay debounce. **Allow control without a logged-in user** never applies, because a WebSocket connection always has a logged-in user. Changing **Who may operate +the panel** reloads the entry, and the topology then answers by the new setting. + #### Circuit Object | Field | Type | Description | @@ -387,8 +406,8 @@ snapshot removes one or changes its `package_ratings_state`. A consumer showing | `circuit_ids` | array[string] | The circuits whose package ratings, or what they are judged as, changed | Subscribing to this event over the WebSocket API (`subscribe_events`) requires an administrator: Home Assistant lets any other user subscribe only to the events -on its own allowlist, and this integration's event is not on it. Any other user reads the same ratings from `span_panel/panel_topology`, and sees a change the next -time it fetches the topology. +on its own allowlist, and this integration's event is not on it. Any other user reads the same ratings from `span_panel/panel_topology`, and sees a change the +next time it fetches the topology. ## `span_panel/adopted/list` From a95484fbc40bbc4086e3a9d65f37c1acd9cdac6d Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:49:24 -0800 Subject: [PATCH 04/15] feat(websocket): report a user whose permissions allow no control as read_only control_access.reason may also be read_only. Home Assistant refuses a user who is not an administrator control of any entity their permissions do not allow, before the gate is asked, so the card would otherwise offer a read-only user controls that fail. The new control_access module asks the control mode first and the user's permissions second, over the relay switches and priority selects the topology offers, and reports read_only only where the user may control none of them. Administrators are not checked, as Core does not check them, and a panel offering no circuit control reports no permission refusal. The gate is unchanged. Tests hold the topology to Core's own refusal of a switch.turn_on and to the gate's refusals, for every mode and every kind of user. --- .../span_panel/control_access.py | 96 ++++++ custom_components/span_panel/control_gate.py | 7 +- custom_components/span_panel/websocket.py | 60 ++-- tests/test_topology_control_access.py | 293 ++++++++++++++---- tests/test_websocket_admin_rule.py | 2 +- 5 files changed, 366 insertions(+), 92 deletions(-) create mode 100644 custom_components/span_panel/control_access.py diff --git a/custom_components/span_panel/control_access.py b/custom_components/span_panel/control_access.py new file mode 100644 index 00000000..b41a555d --- /dev/null +++ b/custom_components/span_panel/control_access.py @@ -0,0 +1,96 @@ +"""Whether the user asking may operate the panel, as `span_panel/panel_topology` reports it. + +The card disables a panel's relay and priority controls for a user this says may +not operate them, so it answers from the two rules that would refuse that user +and restates neither: + +- **The control mode**, `ControlPolicy.refusal_for`, which the gate enforces on + every command. It comes first, because it is the integration's own answer + and holds for every control the entry has. +- **The user's Home Assistant permissions.** Core refuses an entity service + call from a user who is not an administrator, with `Unauthorized`, for each + entity that `user.permissions.check_entity(entity_id, POLICY_CONTROL)` does + not allow, and administrators are not checked at all (`helpers/service.py`). + That happens before any entity, and so before the gate, is asked, which is + why the gate never answers it and this module has to. + +`control_access` asks the mode, then the permissions, and reports the first +refusal. +""" + +from __future__ import annotations + +from collections.abc import Collection +from enum import StrEnum +from typing import TYPE_CHECKING, TypedDict + +from homeassistant.auth.permissions.const import POLICY_CONTROL + +from .control_gate import ControlAccessRefusal, ControlPolicy + +if TYPE_CHECKING: + from homeassistant.auth.models import User + + +class PermissionRefusal(StrEnum): + """Why the user's own Home Assistant permissions keep them from operating the panel. + + A wire value beside `ControlAccessRefusal`'s, in the same + `control_access.reason` field. Separate because Core decides it, not the + control mode, and the gate never refuses for it. + """ + + READ_ONLY = "read_only" + """The user may control none of the panel's circuit controls, as a Read Only user may control nothing.""" + + +class ControlAccessRecord(TypedDict): + """Whether the user asking may operate the panel, and if not, why. + + `may_operate` is true exactly where `reason` is null. Neither says whether + the control lock is armed, which changes while the card is open and which + the card reads from the lock's own switch. A WebSocket connection always + has a logged-in user, so whether control without one is allowed never comes + into it. + """ + + may_operate: bool + reason: ControlAccessRefusal | PermissionRefusal | None + + +def control_access( + policy: ControlPolicy, user: User, circuit_controls: Collection[str] +) -> ControlAccessRecord: + """Return whether `user` may operate the panel whose policy is `policy`. + + `circuit_controls` is the entity id of every relay switch and priority + select the topology offers for the panel's circuits. The permissions are + checked against those, and only those, because they are what the card + disables on this answer: a user able to control only the control lock's + switch, or an EVSE's, could still operate none of them. + + `read_only` is reported where there is at least one such control and the + user may control none of them. Where they may control some, the card keeps + its controls and Core refuses the rest, one at a time, as it would anywhere + else -- the answer is one flag for the whole panel, and a user who can + operate something is not told they can operate nothing. Where the panel + offers no circuit control there is nothing to disable and nothing for Core + to refuse, so the permissions are not reported. + """ + reason: ControlAccessRefusal | PermissionRefusal | None = policy.refusal_for( + is_admin=user.is_admin + ) + if reason is None: + reason = _permission_refusal(user, circuit_controls) + return ControlAccessRecord(may_operate=reason is None, reason=reason) + + +def _permission_refusal(user: User, circuit_controls: Collection[str]) -> PermissionRefusal | None: + """Core's answer for `user` over `circuit_controls`, by the check its entity services make.""" + if user.is_admin or not circuit_controls: + return None + if any( + user.permissions.check_entity(entity_id, POLICY_CONTROL) for entity_id in circuit_controls + ): + return None + return PermissionRefusal.READ_ONLY diff --git a/custom_components/span_panel/control_gate.py b/custom_components/span_panel/control_gate.py index 5b5506b6..02b2536b 100644 --- a/custom_components/span_panel/control_gate.py +++ b/custom_components/span_panel/control_gate.py @@ -100,9 +100,10 @@ class ControlAccessRefusal(StrEnum): """Why the control mode refuses a caller, judged by who the caller is. The values are wire values: `span_panel/panel_topology` reports them to the - card as `control_access.reason`. They are not the gate's translation keys, - which name the refusal a service caller is shown and are free to be worded - for that reader. + card as `control_access.reason`, beside the one Home Assistant's own + permissions give, which `control_access` adds. They are not the gate's + translation keys, which name the refusal a service caller is shown and are + free to be worded for that reader. """ CONTROL_DISABLED = "control_disabled" diff --git a/custom_components/span_panel/websocket.py b/custom_components/span_panel/websocket.py index b37bdb63..a5de01f8 100644 --- a/custom_components/span_panel/websocket.py +++ b/custom_components/span_panel/websocket.py @@ -3,7 +3,7 @@ from __future__ import annotations from collections.abc import Collection, Mapping -from typing import TYPE_CHECKING, Any, TypedDict +from typing import TYPE_CHECKING, Any, Final, TypedDict from homeassistant.components import websocket_api from homeassistant.config_entries import ConfigEntryState @@ -13,7 +13,8 @@ from span_panel_api import shared_meter_groups from .const import DOMAIN -from .control_gate import ControlAccessRefusal, ControlMode, ControlPolicy +from .control_access import control_access +from .control_gate import ControlMode from .current_monitor import MonitoredCircuit, monitored_circuits from .energy_orientation import circuit_is_generation from .entity_resolver import entity_id_in_entry @@ -38,7 +39,6 @@ from .websocket_panel import resolve_panel_device if TYPE_CHECKING: - from homeassistant.auth.models import User from span_panel_api import SpanCircuitSnapshot, SpanPanelSnapshot # Mapping from unique_id suffixes to semantic role names for circuit sensors. @@ -111,9 +111,10 @@ async def handle_panel_topology( each circuit and device, the ratings current monitoring judges each circuit against, and the registry IDs that tie them together; no host, credential or certificate is in it. Whether a control it names may be operated is - decided by the control policy when the control is used, not here; what - `control_access` carries is that policy's answer for the user asking, so - the card can offer no control the gate would refuse them. + decided by the control policy and by Home Assistant's permissions when the + control is used, not here; `control_access` carries their answer for the + user asking, so the card can disable the controls that user would be + refused. See `control_access`. The caller passes the HA device registry ID for the **main SPAN panel** device only (not a sub-device or a circuit's device). Returns panel @@ -194,6 +195,9 @@ async def handle_panel_topology( # Build circuits section. circuits: dict[str, dict[str, Any]] = {} + # Every relay switch and priority select offered below, which + # `control_access` checks the user's permissions against. + circuit_controls: list[str] = [] for circuit_id, circuit in snapshot.circuits.items(): if circuit_id not in circuit_ids: continue @@ -203,6 +207,10 @@ async def handle_panel_topology( own_device = circuit_device( device_registry, snapshot.serial_number, circuit_id, config_entry_id=config_entry_id ) + offered = _offered_roles( + entity_map.get(circuit_id, {}), circuit, runtime_data.control_policy.mode + ) + circuit_controls.extend(offered[role] for role in _CONTROL_ROLES if role in offered) circuits[circuit_id] = { # The circuit's own device, a child of the panel's, by its registry # id; null where the circuit has none. A consumer reads the name and @@ -260,9 +268,7 @@ async def handle_panel_topology( # circuit, because a consumer rendering from this record has no # other way to tell a pinned priority from an absent one. "is_never_backup": None if circuit.measures_outside_panel else circuit.is_never_backup, - "entities": _offered_roles( - entity_map.get(circuit_id, {}), circuit, runtime_data.control_policy.mode - ), + "entities": offered, } # Build sub-devices section from devices linked via via_device_id. @@ -328,10 +334,14 @@ async def handle_panel_topology( # circuit's `package_ratings_form` says whether it takes a copy, and in # which form. "monitoring_rating_offered": not describes_breakers, - # Whether the user asking may operate the panel, by the policy the - # gate holds. It is the same object: setup hands one policy to the - # gate and to the runtime data, and an options change reloads both. - "control_access": _control_access_record(runtime_data.control_policy, connection.user), + # Whether the user asking may operate the panel: by the policy the + # gate holds, then by their own permissions over the controls offered + # above. The policy is the gate's own object: setup hands one policy + # to the gate and to the runtime data, and an options change reloads + # both. + "control_access": control_access( + runtime_data.control_policy, connection.user, circuit_controls + ), "circuits": circuits, # Each shared meter by the key its members carry in `shared_meter_group`. "shared_meter_groups": meter_groups, @@ -366,26 +376,6 @@ def _meter_group_record(point: MonitoredCircuit) -> MeterGroupRecord: ) -class ControlAccessRecord(TypedDict): - """Whether the user asking may operate the panel, and if not, why. - - `reason` is `ControlPolicy.refusal_for`'s answer for that user, the answer - the gate refuses a command by, and `may_operate` is true exactly where it is - null. Neither says whether the control lock is armed, which changes while - the card is open and which the card reads from the lock's own switch. A - WebSocket connection always has a logged-in user, so whether control - without one is allowed never comes into it. - """ - - may_operate: bool - reason: ControlAccessRefusal | None - - -def _control_access_record(policy: ControlPolicy, user: User) -> ControlAccessRecord: - refusal = policy.refusal_for(is_admin=user.is_admin) - return ControlAccessRecord(may_operate=refusal is None, reason=refusal) - - def _group_of(groups: Mapping[str, tuple[str, ...]]) -> dict[str, str]: """Map every member of every group to its group's key.""" return {member: key for key, members in groups.items() for member in members} @@ -440,6 +430,10 @@ def _solar_block( return None +_CONTROL_ROLES: Final = ("switch", "select") +"""The roles that name a circuit control: its relay switch and its priority select.""" + + def _offered_roles( roles: Mapping[str, str], circuit: SpanCircuitSnapshot, mode: ControlMode ) -> dict[str, str]: diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py index 5d985056..f0d4e6b4 100644 --- a/tests/test_topology_control_access.py +++ b/tests/test_topology_control_access.py @@ -1,10 +1,13 @@ """`span_panel/panel_topology` tells the card whether the user asking may operate the panel. -`control_access` is the control mode's answer for the WebSocket connection's -user, by `ControlPolicy.refusal_for` -- the rule the gate refuses a command by. -The card disables the panel's controls for a user it says may not operate them, -so what it says and what the gate does must not come apart: the last test runs -both, for every mode and every kind of user, and holds them to one answer. +`control_access` answers from two rules and restates neither: the control mode, +by `ControlPolicy.refusal_for`, which the gate refuses a command by, and then the +user's own Home Assistant permissions over the circuit controls, which Core +refuses an entity service call by before the gate is asked. The card disables +the panel's controls for a user it says may not operate them, so what it says +must not come apart from what either rule does: two tests here run the rule +itself -- the gate, and a service call through Core -- beside the topology and +hold them to one answer. """ from __future__ import annotations @@ -17,15 +20,19 @@ from homeassistant.auth.const import GROUP_ID_ADMIN, GROUP_ID_READ_ONLY, GROUP_ID_USER from homeassistant.config_entries import ConfigEntryState from homeassistant.core import Context, HomeAssistant -from homeassistant.exceptions import ServiceValidationError +from homeassistant.exceptions import ServiceValidationError, Unauthorized +from homeassistant.helpers import entity_registry as er +from homeassistant.setup import async_setup_component import pytest from pytest_homeassistant.common import CLIENT_ID, MockConfigEntry, MockUser from pytest_homeassistant.typing import WebSocketGenerator from span_panel_api import ControlCommand, FieldMetadata from custom_components.span_panel.const import DOMAIN +from custom_components.span_panel.control_access import PermissionRefusal, control_access from custom_components.span_panel.control_gate import ( CONTROL_CALLER, + ControlAccessRefusal, ControlGate, ControlLock, ControlMode, @@ -33,6 +40,7 @@ async_bind_caller, ) from custom_components.span_panel.curation import CurationOverlay +from custom_components.span_panel.id_builder import build_select_unique_id, build_switch_unique_id from custom_components.span_panel.package_rating_manager import PackageRatingManager from custom_components.span_panel.runtime import SpanPanelRuntimeData from custom_components.span_panel.websocket import async_register_commands @@ -53,15 +61,31 @@ ) """A command the relay debounce never touches, so a refusal is only ever about who asked.""" -EXPECTED_REASON: Final[Mapping[tuple[ControlMode, bool], str | None]] = { - (ControlMode.ALL_USERS, True): None, - (ControlMode.ALL_USERS, False): None, - (ControlMode.ADMIN_ONLY, True): None, - (ControlMode.ADMIN_ONLY, False): "admin_only", - (ControlMode.DISABLED, True): "control_disabled", - (ControlMode.DISABLED, False): "control_disabled", +_ADMINISTRATOR: Final = "administrator" +_ORDINARY: Final = "ordinary user" +_READ_ONLY: Final = "read-only user" + +_GROUPS: Final = { + _ADMINISTRATOR: GROUP_ID_ADMIN, + _ORDINARY: GROUP_ID_USER, + _READ_ONLY: GROUP_ID_READ_ONLY, } -"""`control_access.reason` by control mode and whether the asker is an administrator. +"""Each group a Home Assistant user can be in, by the name its tests carry.""" + +EXPECTED_REASON: Final[Mapping[tuple[ControlMode, str], str | None]] = { + (ControlMode.ALL_USERS, _ADMINISTRATOR): None, + (ControlMode.ALL_USERS, _ORDINARY): None, + (ControlMode.ALL_USERS, _READ_ONLY): "read_only", + (ControlMode.ADMIN_ONLY, _ADMINISTRATOR): None, + (ControlMode.ADMIN_ONLY, _ORDINARY): "admin_only", + # The mode's answer comes first, so a read-only user is told it rather than + # their own permissions'. + (ControlMode.ADMIN_ONLY, _READ_ONLY): "admin_only", + (ControlMode.DISABLED, _ADMINISTRATOR): "control_disabled", + (ControlMode.DISABLED, _ORDINARY): "control_disabled", + (ControlMode.DISABLED, _READ_ONLY): "control_disabled", +} +"""`control_access.reason` by control mode and the group the asker is in, on a panel with circuit controls. Written as the wire values the card reads, so renaming one fails here. """ @@ -70,37 +94,46 @@ None: None, "admin_only": "admin_only_control", "control_disabled": "control_disabled", + # Core's reason, reported only where the mode has none, so the gate lets + # the command through: Core refuses it before the gate is asked. + "read_only": None, } """The refusal the gate gives a command, by the `control_access.reason` the topology reports. -None is no refusal on either side: the topology says the user may operate the -panel, and the gate lets the command through. +None is no refusal by the gate. """ -_GROUPS: Final = { - "administrator": GROUP_ID_ADMIN, - "ordinary user": GROUP_ID_USER, - "read-only user": GROUP_ID_READ_ONLY, -} - -@pytest.fixture(params=list(_GROUPS.values()), ids=list(_GROUPS)) -async def asker(hass: HomeAssistant, request: pytest.FixtureRequest) -> MockUser: - """Return a logged-in user from each group a Home Assistant user can be in.""" - group = await hass.auth.async_get_group(request.param) +@pytest.fixture(params=list(_GROUPS), ids=list(_GROUPS)) +async def asker(hass: HomeAssistant, request: pytest.FixtureRequest) -> tuple[str, MockUser]: + """Return a logged-in user from each group, with the group's name.""" + name: str = request.param + group = await hass.auth.async_get_group(_GROUPS[name]) assert group is not None user = MockUser(groups=[group]).add_to_hass(hass) - assert user.is_admin is (request.param == GROUP_ID_ADMIN) - return user + assert user.is_admin is (name == _ADMINISTRATOR) + return name, user -async def _load_panel(hass: HomeAssistant, mode: ControlMode) -> tuple[MockConfigEntry, str]: - """Load a one-circuit panel whose control mode is `mode`, and return its entry and device's registry ID.""" +async def _load_panel( + hass: HomeAssistant, mode: ControlMode, *, with_controls: bool = True +) -> tuple[MockConfigEntry, str, list[str]]: + """Load a one-circuit panel whose control mode is `mode`. + + Returns its entry, its device's registry ID, and the entity ids of the + circuit's relay switch and priority select, which are registered only + `with_controls`. + """ snapshot = SpanPanelSnapshotFactory.create( serial_number=_SERIAL, circuits={ _CIRCUIT_ID: SpanCircuitSnapshotFactory.create( - circuit_id=_CIRCUIT_ID, name="Synthetic Circuit", tabs=[3], breaker_rating_a=20.0 + circuit_id=_CIRCUIT_ID, + name="Synthetic Circuit", + tabs=[3], + breaker_rating_a=20.0, + is_user_controllable=True, + is_never_backup=False, ) }, main_breaker_rating_a=100, @@ -126,22 +159,46 @@ async def _load_panel(hass: HomeAssistant, mode: ControlMode) -> tuple[MockConfi control_policy=replace(ControlPolicy.default(), mode=mode), ) entry.mock_state(hass, ConfigEntryState.LOADED) + + controls: list[str] = [] + if with_controls: + entities = er.async_get(hass) + for domain, unique_id in ( + ("switch", build_switch_unique_id(_SERIAL, _CIRCUIT_ID)), + ("select", build_select_unique_id(_SERIAL, _CIRCUIT_ID)), + ): + registered = entities.async_get_or_create( + domain, DOMAIN, unique_id, config_entry=entry, device_id=device_id + ) + controls.append(registered.entity_id) + async_register_commands(hass) - return entry, device_id + return entry, device_id, controls -async def _control_access( +async def _topology( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, user: MockUser, device_id: str ) -> dict[str, object]: - """Ask for the topology as `user` and return its `control_access`.""" + """Ask for the topology as `user` and return it.""" refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID) client = await hass_ws_client(hass, hass.auth.async_create_access_token(refresh_token)) await client.send_json_auto_id({"type": "span_panel/panel_topology", "device_id": device_id}) reply = await client.receive_json() assert reply["success"] is True, reply - control_access = reply["result"]["control_access"] - assert isinstance(control_access, dict) - return control_access + topology = reply["result"] + assert isinstance(topology, dict) + return topology + + +async def _control_access( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, user: MockUser, device_id: str +) -> dict[str, object]: + """Ask for the topology as `user` and return its `control_access`.""" + control_access_record = (await _topology(hass, hass_ws_client, user, device_id))[ + "control_access" + ] + assert isinstance(control_access_record, dict) + return control_access_record async def _gate_refusal(hass: HomeAssistant, entry: MockConfigEntry, user: MockUser) -> str | None: @@ -161,37 +218,163 @@ async def _gate_refusal(hass: HomeAssistant, entry: MockConfigEntry, user: MockU return None -def test_every_mode_has_an_expected_answer_for_both_kinds_of_user() -> None: - """A mode added later has to be given its answers here before the card can rely on them.""" - assert set(EXPECTED_REASON) == { - (mode, is_admin) for mode in ControlMode for is_admin in (True, False) - } +async def _core_refuses_control(hass: HomeAssistant, user: MockUser, entity_id: str) -> bool: + """Whether Core refuses `user` a `switch.turn_on` of `entity_id` for want of control permission. + + The switch is only registered, never added, so a call Core lets through + reaches no entity and does nothing: what is asked is Core's permission + check, which comes first. + """ + try: + await hass.services.async_call( + "switch", + "turn_on", + {"entity_id": entity_id}, + blocking=True, + context=Context(user_id=user.id), + ) + except Unauthorized: + return True + return False + + +# --------------------------------------------------------------------------- +# What the topology answers +# --------------------------------------------------------------------------- + + +def test_every_mode_has_an_expected_answer_for_every_group() -> None: + """A mode or group added later has to be given its answers here before the card can rely on them.""" + assert set(EXPECTED_REASON) == {(mode, group) for mode in ControlMode for group in _GROUPS} @pytest.mark.parametrize("mode", list(ControlMode)) async def test_the_topology_says_whether_the_asker_may_operate_the_panel( - hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mode: ControlMode, asker: MockUser + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + mode: ControlMode, + asker: tuple[str, MockUser], ) -> None: - """`may_operate` is true exactly where `reason` is null, and `reason` is the mode's answer for the asker.""" - _, device_id = await _load_panel(hass, mode) + """`may_operate` is true exactly where `reason` is null, and `reason` is the first refusal that applies.""" + group, user = asker + _, device_id, _ = await _load_panel(hass, mode) + + reason = EXPECTED_REASON[(mode, group)] + assert await _control_access(hass, hass_ws_client, user, device_id) == { + "may_operate": reason is None, + "reason": reason, + } - control_access = await _control_access(hass, hass_ws_client, asker, device_id) - reason = EXPECTED_REASON[(mode, asker.is_admin)] - assert control_access == {"may_operate": reason is None, "reason": reason} +async def test_a_panel_offering_no_circuit_control_reports_no_permission_refusal( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator +) -> None: + """With no relay switch or priority select there is nothing to disable, and nothing for Core to refuse.""" + group = await hass.auth.async_get_group(GROUP_ID_READ_ONLY) + assert group is not None + user = MockUser(groups=[group]).add_to_hass(hass) + _, device_id, _ = await _load_panel(hass, ControlMode.ALL_USERS, with_controls=False) + + assert await _control_access(hass, hass_ws_client, user, device_id) == { + "may_operate": True, + "reason": None, + } + + +# --------------------------------------------------------------------------- +# The topology and the rules it reports +# --------------------------------------------------------------------------- @pytest.mark.parametrize("mode", list(ControlMode)) async def test_the_topology_and_the_gate_give_the_asker_the_same_answer( - hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mode: ControlMode, asker: MockUser + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + mode: ControlMode, + asker: tuple[str, MockUser], ) -> None: - """The gate refuses the asker's command exactly where the topology says they may not operate the panel, and for the reason it gives.""" - entry, device_id = await _load_panel(hass, mode) + """The gate refuses the asker's command exactly where the topology reports one of its reasons, and for that reason.""" + _, user = asker + entry, device_id, _ = await _load_panel(hass, mode) - control_access = await _control_access(hass, hass_ws_client, asker, device_id) - refusal = await _gate_refusal(hass, entry, asker) + control_access_record = await _control_access(hass, hass_ws_client, user, device_id) + refusal = await _gate_refusal(hass, entry, user) - assert control_access["may_operate"] is (refusal is None) - reason = control_access["reason"] + reason = control_access_record["reason"] assert reason is None or isinstance(reason, str) assert GATE_REFUSAL[reason] == refusal + + +async def test_the_topology_reports_read_only_exactly_where_core_refuses_control( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator, asker: tuple[str, MockUser] +) -> None: + """Core refuses the asker the panel's relay switch exactly where the topology says `read_only`. + + Under All users, where the mode refuses no one, so the permissions are the + whole answer. + """ + _, user = asker + assert await async_setup_component(hass, "switch", {}) + _, device_id, controls = await _load_panel(hass, ControlMode.ALL_USERS) + topology = await _topology(hass, hass_ws_client, user, device_id) + circuit = topology["circuits"] + assert isinstance(circuit, dict) + switch = circuit[_CIRCUIT_ID]["entities"]["switch"] + assert switch in controls + + control_access_record = topology["control_access"] + assert isinstance(control_access_record, dict) + assert (control_access_record["reason"] == "read_only") is await _core_refuses_control( + hass, user, switch + ) + + +# --------------------------------------------------------------------------- +# The rule, directly +# --------------------------------------------------------------------------- + + +_ALL_USERS: Final = replace(ControlPolicy.default(), mode=ControlMode.ALL_USERS) +_SWITCH: Final = "switch.synthetic_circuit_breaker" +_SELECT: Final = "select.synthetic_circuit_priority" + + +def test_a_user_who_may_control_some_circuit_controls_may_operate_the_panel() -> None: + """One flag for the whole panel: a user who can operate something is not told they can operate nothing.""" + user = MockUser() + user.mock_policy({"entities": {"entity_ids": {_SWITCH: True}}}) + + assert control_access(_ALL_USERS, user, [_SWITCH, _SELECT]) == { + "may_operate": True, + "reason": None, + } + + +def test_a_user_who_may_read_but_not_control_them_is_read_only() -> None: + """Reading a control is not operating it.""" + user = MockUser() + user.mock_policy({"entities": {"entity_ids": {_SWITCH: {"read": True}}}}) + + assert control_access(_ALL_USERS, user, [_SWITCH, _SELECT]) == { + "may_operate": False, + "reason": PermissionRefusal.READ_ONLY, + } + + +@pytest.mark.parametrize("mode", list(ControlMode)) +def test_an_administrator_is_never_read_only(mode: ControlMode) -> None: + """Core does not check an administrator's permissions at all, so neither does this. + + The administrator here holds a policy that would refuse anyone else, which + is what shows the check is skipped rather than passed. + """ + user = MockUser(is_owner=True) + user.mock_policy({"entities": {"entity_ids": {_SWITCH: {"read": True}}}}) + policy = replace(ControlPolicy.default(), mode=mode) + + reason = control_access(policy, user, [_SWITCH, _SELECT])["reason"] + + assert reason is not PermissionRefusal.READ_ONLY + assert reason is ( + ControlAccessRefusal.CONTROL_DISABLED if mode is ControlMode.DISABLED else None + ) diff --git a/tests/test_websocket_admin_rule.py b/tests/test_websocket_admin_rule.py index 2765cbe2..ce34a932 100644 --- a/tests/test_websocket_admin_rule.py +++ b/tests/test_websocket_admin_rule.py @@ -80,7 +80,7 @@ } """The keys of an open command's answer that describe the user asking, and so differ by user. -`control_access` is the control policy's answer for that user; see +`control_access` says whether that user may operate the panel; see `test_topology_control_access.py`. Everything else an open command answers is the same for every user. """ From 65ebb3dbc5b3ebbd017e0555b2831aa633c7c4ce Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:52:02 -0800 Subject: [PATCH 05/15] docs(websocket-api): document read_only and the panel's breaker position range control_access gains its third reason, with the order the reasons are reported in and what read_only is checked against. first_position and last_position, which the topology already sends, are named in the example and the top-level table, with what they cover. --- websocket-api.md | 42 +++++++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/websocket-api.md b/websocket-api.md index 541c5146..0a53ca07 100644 --- a/websocket-api.md +++ b/websocket-api.md @@ -17,8 +17,8 @@ provides all of these relationships explicitly, keyed by circuit UUID, so the ca Any logged-in user may call it, administrator or not, so the sidebar dashboard and the card work for whoever is viewing them. It carries the panel's layout, what the panel publishes about each circuit and device, the ratings current monitoring judges each circuit against, and the registry IDs that tie them together; no host, credential or certificate is in it. Whether a switch or select it names can be operated is decided when it is used, by -[Who may operate the panel](README.md#restricting-who-can-operate-the-panel). `control_access` reports that option's answer for the user asking, so a card can -disable the controls that user would be refused. +[Who may operate the panel](README.md#restricting-who-can-operate-the-panel) and by the user's own Home Assistant permissions. `control_access` reports their +answer for the user asking, so a card can disable the controls that user would be refused. ### Request @@ -45,6 +45,8 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID. "serial": "sim-main32-0001", "firmware": "spanos3/r202639/03", "panel_size": 32, + "first_position": 1, + "last_position": 32, "device_id": "abc123def456", "panel_device_id": "abc123def456", "config_entry_id": "e5f6a7b8c9d0", @@ -209,6 +211,8 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID. | `serial` | string | Panel serial number | | `firmware` | string | Panel firmware version | | `panel_size` | int or null | Total breaker spaces (e.g., 32, 40) | +| `first_position` | int or null | The panel's first breaker position (see below) | +| `last_position` | int or null | The panel's last breaker position (see below) | | `device_id` | string | HA device registry ID (echoed from request) | | `panel_device_id` | string | The panel's current HA device registry ID | | `config_entry_id` | string | The config entry that owns the panel | @@ -219,18 +223,34 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID. | `shared_meter_groups` | object | Each group of circuits that share a meter, keyed by the group key its members carry in `shared_meter_group` (see below); empty where no meter is shared | | `sub_devices` | object | HA device ID keyed map of BESS/MID/EVSE/PV (see below) | +`first_position` and `last_position` say which breaker positions the panel has, occupied or not: the reported model's range where the integration knows the +model, otherwise the lowest and highest occupied spaces, and null where neither is known. `circuits` lists only the circuits that are there, so a position in +the range with no circuit is an empty space. + #### Control Access Object -| Field | Type | Description | -| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `may_operate` | bool | Whether **Who may operate the panel** lets the user asking operate the panel's controls | -| `reason` | string/null | Why not: `control_disabled` where the option is `Nobody`, `admin_only` where it is `Administrators only` and the user is not an administrator; null where `may_operate` is true | +| Field | Type | Description | +| ------------- | ----------- | ------------------------------------------------------------------------------------------------------ | +| `may_operate` | bool | Whether the user asking may operate the panel's relay and priority controls | +| `reason` | string/null | Why not: `control_disabled`, `admin_only` or `read_only` (see below); null where `may_operate` is true | + +`reason` is the first of these that applies: + +| Reason | Meaning | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `control_disabled` | **Who may operate the panel** is `Nobody`, so no one may | +| `admin_only` | **Who may operate the panel** is `Administrators only` and the user is not an administrator | +| `read_only` | The user's Home Assistant permissions let them control none of the relay switches and priority selects named in `circuits`, as for a read-only user | + +The answer is for the user the WebSocket connection is authenticated as, so two users asking about the same panel can be told different things. The first two +come from the rule the integration refuses a control command by. `read_only` comes from Home Assistant, which refuses a user without control permission before +the integration is asked; it is never reported for an administrator, whose permissions Home Assistant does not check, nor for a panel whose circuits name no +relay switch or priority select. A user who may control some of those controls but not others may operate the panel, and is refused the others one at a time. -The answer is for the user the WebSocket connection is authenticated as, so two users asking about the same panel can be told different things. It comes from -the rule the integration refuses a control command by, so a card that disables its relay and priority controls where `may_operate` is false offers no control -that rule would refuse. It says nothing about the control lock, which can be armed or disarmed while a page is open and which its switch reports, nor about the -relay debounce. **Allow control without a logged-in user** never applies, because a WebSocket connection always has a logged-in user. Changing **Who may operate -the panel** reloads the entry, and the topology then answers by the new setting. +A card that disables its relay and priority controls where `may_operate` is false therefore offers them only to a user who may operate at least one of them. The +answer says nothing about the control lock, which can be armed or disarmed while a page is open and which its switch reports, nor about the relay debounce. +**Allow control without a logged-in user** never applies, because a WebSocket connection always has a logged-in user. Changing **Who may operate the panel** +reloads the entry, and the topology then answers by the new setting. #### Circuit Object From 5c7b76a5504309782b0192f2f580aef203a60921 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:54:08 -0800 Subject: [PATCH 06/15] docs: say that the card disables controls for a user who may not operate the panel Beside the existing Nobody wording: under Administrators only for anyone but an administrator, and for an account whose Home Assistant permissions do not allow control. --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8989a1c5..8c577b41 100644 --- a/README.md +++ b/README.md @@ -714,7 +714,9 @@ see [Recommended deployment](#recommended-deployment), where network topology an **Choosing `Nobody` is reversible.** The control entities stop being created and read as unavailable, but their registry entries, names, areas and customizations are kept, so turning the option back on restores exactly the entities you had. The control lock comes back armed or disarmed as you left it, with any auto-relock still due at the same moment, and armed if Home Assistant no longer holds its last state. The shipped SPAN Panel card and dashboard offer no -breaker switch or priority while `Nobody` is chosen, and other dashboards show those entities unavailable. +breaker switch or priority while `Nobody` is chosen, and other dashboards show those entities unavailable. For a user who may not operate the panel — anyone but +an administrator while `Administrators only` is chosen, or an account whose Home Assistant permissions do not allow control — the card and dashboard show the +relay and priority controls disabled. ### The record of what was commanded From b9c3013c72b11cf30a08841da372c0ea9511bf1b Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:13:12 -0800 Subject: [PATCH 07/15] docs(websocket-api): document the topology's panel_entities The map is in the response and was named nowhere. It is now in the example and the top-level table, with a table of its roles, when a role is present, and which one stays available while the panel is offline. --- websocket-api.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/websocket-api.md b/websocket-api.md index 0a53ca07..e226f0c9 100644 --- a/websocket-api.md +++ b/websocket-api.md @@ -51,6 +51,17 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID. "panel_device_id": "abc123def456", "config_entry_id": "e5f6a7b8c9d0", "device_name": "SPAN Panel", + "panel_entities": { + "current_power": "sensor.span_panel_current_power", + "site_power": "sensor.span_panel_site_power", + "grid_power": "sensor.span_panel_grid_power", + "pv_power": "sensor.span_panel_solar_pv_power", + "battery_power": "sensor.span_panel_battery_battery_power", + "battery_level": "sensor.span_panel_battery_battery_level", + "l1_voltage": "sensor.span_panel_l1_voltage", + "l2_voltage": "sensor.span_panel_l2_voltage", + "panel_status": "binary_sensor.span_panel_panel_status" + }, "monitoring_rating_offered": true, "control_access": { "may_operate": true, @@ -217,6 +228,7 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID. | `panel_device_id` | string | The panel's current HA device registry ID | | `config_entry_id` | string | The config entry that owns the panel | | `device_name` | string | HA device display name | +| `panel_entities` | object | Role-keyed map of the entity IDs of the panel's own readings and its status (see below) | | `monitoring_rating_offered` | bool | Whether `set_circuit_package_ratings` takes ratings on this panel: false where the panel publishes each circuit of a multi-load breaker with its own rating | | `control_access` | object | Whether the user asking may operate the panel, and if not, why (see below) | | `circuits` | object | Circuit UUID keyed map (see below) | @@ -227,6 +239,31 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID. model, otherwise the lowest and highest occupied spaces, and null where neither is known. `circuits` lists only the circuits that are there, so a position in the range with no circuit is an empty space. +#### Panel Entity Roles + +| Role | Domain | Entity | +| ----------------------- | ------------- | --------------------- | +| `current_power` | sensor | Current Power | +| `site_power` | sensor | Site Power | +| `grid_power` | sensor | Grid Power | +| `feedthrough_power` | sensor | Feed Through Power | +| `pv_power` | sensor | PV Power | +| `battery_power` | sensor | Battery Power | +| `battery_level` | sensor | Battery Level | +| `dsm_state` | sensor | DSM Grid State | +| `main_breaker_rating` | sensor | Main Breaker Rating | +| `upstream_l1_current` | sensor | Upstream L1 Current | +| `upstream_l2_current` | sensor | Upstream L2 Current | +| `downstream_l1_current` | sensor | Downstream L1 Current | +| `downstream_l2_current` | sensor | Downstream L2 Current | +| `l1_voltage` | sensor | L1 Voltage | +| `l2_voltage` | sensor | L2 Voltage | +| `panel_status` | binary_sensor | Panel Status | + +A role is present while its entity is registered for this panel, enabled or not, and omitted otherwise: a panel without a battery has no `battery_power` or +`battery_level`. Each value is the entity's current ID, so a renamed entity is still found. `panel_status` stays available while the panel is offline, so a +consumer can watch it for whether the panel is online. + #### Control Access Object | Field | Type | Description | From 91bbfa410a10aa205a6960efa38b001b12193d3b Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:29:13 -0800 Subject: [PATCH 08/15] refactor(controls): name the mode's refusals ControlModeRefusal, and the reason both rules give ControlAccessReason ControlAccessRefusal held only the control mode's two reasons, while read_only, Core's, is PermissionRefusal. The mode's enum is renamed for what it holds, and ControlAccessReason names the union that control_access.reason carries. A docs test holds the two enums' values disjoint and, together, equal to the reason table in websocket-api.md. --- .../span_panel/control_access.py | 14 ++++---- custom_components/span_panel/control_gate.py | 12 +++---- tests/test_control_gate.py | 6 ++-- tests/test_docs_agree_with_code.py | 34 +++++++++++++++++++ tests/test_topology_control_access.py | 6 ++-- 5 files changed, 53 insertions(+), 19 deletions(-) diff --git a/custom_components/span_panel/control_access.py b/custom_components/span_panel/control_access.py index b41a555d..20929309 100644 --- a/custom_components/span_panel/control_access.py +++ b/custom_components/span_panel/control_access.py @@ -26,7 +26,7 @@ from homeassistant.auth.permissions.const import POLICY_CONTROL -from .control_gate import ControlAccessRefusal, ControlPolicy +from .control_gate import ControlModeRefusal, ControlPolicy if TYPE_CHECKING: from homeassistant.auth.models import User @@ -35,7 +35,7 @@ class PermissionRefusal(StrEnum): """Why the user's own Home Assistant permissions keep them from operating the panel. - A wire value beside `ControlAccessRefusal`'s, in the same + A wire value beside `ControlModeRefusal`'s, in the same `control_access.reason` field. Separate because Core decides it, not the control mode, and the gate never refuses for it. """ @@ -44,6 +44,10 @@ class PermissionRefusal(StrEnum): """The user may control none of the panel's circuit controls, as a Read Only user may control nothing.""" +type ControlAccessReason = ControlModeRefusal | PermissionRefusal +"""Every reason `control_access` can give: the control mode's, then Core's permissions'.""" + + class ControlAccessRecord(TypedDict): """Whether the user asking may operate the panel, and if not, why. @@ -55,7 +59,7 @@ class ControlAccessRecord(TypedDict): """ may_operate: bool - reason: ControlAccessRefusal | PermissionRefusal | None + reason: ControlAccessReason | None def control_access( @@ -77,9 +81,7 @@ def control_access( offers no circuit control there is nothing to disable and nothing for Core to refuse, so the permissions are not reported. """ - reason: ControlAccessRefusal | PermissionRefusal | None = policy.refusal_for( - is_admin=user.is_admin - ) + reason: ControlAccessReason | None = policy.refusal_for(is_admin=user.is_admin) if reason is None: reason = _permission_refusal(user, circuit_controls) return ControlAccessRecord(may_operate=reason is None, reason=reason) diff --git a/custom_components/span_panel/control_gate.py b/custom_components/span_panel/control_gate.py index 02b2536b..f0cf0af2 100644 --- a/custom_components/span_panel/control_gate.py +++ b/custom_components/span_panel/control_gate.py @@ -96,7 +96,7 @@ class ControlMode(StrEnum): """ -class ControlAccessRefusal(StrEnum): +class ControlModeRefusal(StrEnum): """Why the control mode refuses a caller, judged by who the caller is. The values are wire values: `span_panel/panel_topology` reports them to the @@ -188,7 +188,7 @@ def lock_enabled(self) -> bool: """ return self.lock_timeout_minutes is not None and self.mode is not ControlMode.DISABLED - def refusal_for(self, *, is_admin: bool | None) -> ControlAccessRefusal | None: + def refusal_for(self, *, is_admin: bool | None) -> ControlModeRefusal | None: """Why the control mode refuses this caller, or None where it does not. The one statement of who the mode lets operate the panel. The gate @@ -207,9 +207,9 @@ def refusal_for(self, *, is_admin: bool | None) -> ControlAccessRefusal | None: circuit's last command; the gate asks both itself. """ if self.mode is ControlMode.DISABLED: - return ControlAccessRefusal.CONTROL_DISABLED + return ControlModeRefusal.CONTROL_DISABLED if self.mode is ControlMode.ADMIN_ONLY and is_admin is False: - return ControlAccessRefusal.ADMIN_ONLY + return ControlModeRefusal.ADMIN_ONLY return None @classmethod @@ -438,7 +438,7 @@ async def before_publish(self, command: ControlCommand) -> None: # this integration grows later, a code path that forgets the helper -- # would otherwise be published by an entry whose owner switched control # off. That is the promise this module opens with. - if refusal is ControlAccessRefusal.CONTROL_DISABLED: + if refusal is ControlModeRefusal.CONTROL_DISABLED: self._refuse( "control_disabled", "Control of this SPAN panel is switched off in its options. " @@ -459,7 +459,7 @@ async def before_publish(self, command: ControlCommand) -> None: parent_id=context.parent_id if context is not None else None, ) - if refusal is ControlAccessRefusal.ADMIN_ONLY: + if refusal is ControlModeRefusal.ADMIN_ONLY: self._refuse( "admin_only_control", "Only a Home Assistant administrator may operate this SPAN panel.", diff --git a/tests/test_control_gate.py b/tests/test_control_gate.py index 7fdbab2c..67edda2b 100644 --- a/tests/test_control_gate.py +++ b/tests/test_control_gate.py @@ -22,10 +22,10 @@ from custom_components.span_panel.const import DOMAIN, EVENT_CONTROL_COMMAND from custom_components.span_panel.control_gate import ( CONTROL_CALLER, - ControlAccessRefusal, ControlGate, ControlLock, ControlMode, + ControlModeRefusal, ControlPolicy, async_bind_caller, outcome_is_failure, @@ -690,11 +690,11 @@ def test_an_entry_with_no_control_options_gets_the_defaults() -> None: [ (ControlMode.ALL_USERS, None), (ControlMode.ADMIN_ONLY, None), - (ControlMode.DISABLED, ControlAccessRefusal.CONTROL_DISABLED), + (ControlMode.DISABLED, ControlModeRefusal.CONTROL_DISABLED), ], ) def test_the_mode_judges_a_caller_with_no_user_only_by_refusing_everyone( - mode: ControlMode, refusal: ControlAccessRefusal | None + mode: ControlMode, refusal: ControlModeRefusal | None ) -> None: """`admin_only` has no user to judge; whether such a command goes through is `allow_contextless`'s question.""" policy = replace(ControlPolicy.default(), mode=mode) diff --git a/tests/test_docs_agree_with_code.py b/tests/test_docs_agree_with_code.py index 61dba0cc..67238744 100644 --- a/tests/test_docs_agree_with_code.py +++ b/tests/test_docs_agree_with_code.py @@ -11,6 +11,7 @@ downgrade is refused across, and states the oldest Home Assistant the release installs on, which `hacs.json` enforces; - `AGENTS.md` names the schema library a service is validated with; +- `websocket-api.md` lists each reason the topology's `control_access` can give; - the card the integration bundles links to a section of the tandem guide (`tandems.md`) by the anchor GitHub gives that section's heading. """ @@ -22,12 +23,14 @@ import json from pathlib import Path, PurePosixPath import re +from typing import get_args from urllib.parse import urlsplit import pytest import custom_components.span_panel as span_panel from custom_components.span_panel.const import ENTITY_NAMING_PATTERN +from custom_components.span_panel.control_access import ControlAccessReason REPO = Path(__file__).resolve().parent.parent PACKAGE = Path(span_panel.__file__).resolve().parent @@ -37,6 +40,7 @@ AGENTS = REPO / "AGENTS.md" HACS = REPO / "hacs.json" TANDEM_GUIDE = REPO / "tandems.md" +WEBSOCKET_API = REPO / "websocket-api.md" BUNDLED_PANEL = PACKAGE / "frontend" / "dist" / "span-panel.js" CITED_MODULES = ( @@ -306,6 +310,36 @@ def test_agents_names_the_schema_library_services_import() -> None: assert f"`{libraries[0]}`" in requirements +def _documented_control_access_reasons() -> list[str]: + """Return the reasons the WebSocket API's reason table lists, in its order.""" + section = _section(_read(WEBSOCKET_API), "#### Control Access Object") + lines = section.splitlines() + header = next(index for index, line in enumerate(lines) if line.startswith("| Reason ")) + reasons: list[str] = [] + for line in lines[header + 2 :]: + if not line.startswith("|"): + break + cell = line.split("|")[1].strip() + assert cell.startswith("`") and cell.endswith("`"), line + reasons.append(cell.strip("`")) + return reasons + + +def test_the_websocket_api_lists_each_reason_control_access_can_give() -> None: + """The reason table names every value `ControlAccessReason` holds, and nothing else. + + The reason is one field fed by two enums, one per rule. Their values must + not overlap, or the card could not tell which rule refused, and the table is + what the card is written against. + """ + members = [member.value for enum in get_args(ControlAccessReason.__value__) for member in enum] + documented = _documented_control_access_reasons() + assert documented, "the reason table lists nothing, so this test reads nothing" + + assert len(members) == len(set(members)), members + assert sorted(documented) == sorted(members) + + TANDEM_GUIDE_URL = "https://github.com/SpanPanel/span/blob/main/tandems.md#main-32" """Where the card's MAIN 32 tandem note links: the tandem guide's MAIN 32 section, on `main`.""" diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py index f0d4e6b4..405874d4 100644 --- a/tests/test_topology_control_access.py +++ b/tests/test_topology_control_access.py @@ -32,10 +32,10 @@ from custom_components.span_panel.control_access import PermissionRefusal, control_access from custom_components.span_panel.control_gate import ( CONTROL_CALLER, - ControlAccessRefusal, ControlGate, ControlLock, ControlMode, + ControlModeRefusal, ControlPolicy, async_bind_caller, ) @@ -375,6 +375,4 @@ def test_an_administrator_is_never_read_only(mode: ControlMode) -> None: reason = control_access(policy, user, [_SWITCH, _SELECT])["reason"] assert reason is not PermissionRefusal.READ_ONLY - assert reason is ( - ControlAccessRefusal.CONTROL_DISABLED if mode is ControlMode.DISABLED else None - ) + assert reason is (ControlModeRefusal.CONTROL_DISABLED if mode is ControlMode.DISABLED else None) From 441156c38bfaf0385437d1c1a34975551d96ee99 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:33:01 -0800 Subject: [PATCH 09/15] test(controls): pin the order the gate refuses in A table of every mode, lock state, contextless option and kind of caller, with the refusal the gate gives a priority command or none. Written out, so moving one check past another changes a row: admin_only ahead of the lock, or disabled behind the lock and contextless checks, each passed the suite before this. --- tests/test_control_gate.py | 115 +++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) diff --git a/tests/test_control_gate.py b/tests/test_control_gate.py index 67edda2b..ceb0a0e1 100644 --- a/tests/test_control_gate.py +++ b/tests/test_control_gate.py @@ -8,8 +8,10 @@ from __future__ import annotations +from collections.abc import Mapping from dataclasses import replace from datetime import timedelta +from typing import Final from unittest.mock import AsyncMock, MagicMock, patch from homeassistant.core import Context, Event, HomeAssistant @@ -546,6 +548,119 @@ async def test_a_disabled_entry_refuses_an_administrator_too(hass: HomeAssistant assert err.value.translation_key == "control_disabled" +# ---------- the order the gate refuses in ---------- + +_NO_USER: Final = "no user" +_ADMIN: Final = "administrator" +_NON_ADMIN: Final = "non-admin" + +_CONTROL_DISABLED: Final = "control_disabled" +_LOCKED: Final = "control_locked" +_CONTEXTLESS: Final = "contextless_control_refused" +_ADMIN_ONLY: Final = "admin_only_control" + +_ALL, _ADMINS, _NOBODY = ControlMode.ALL_USERS, ControlMode.ADMIN_ONLY, ControlMode.DISABLED +_ARMED, _OPEN = True, False +_CONTEXTLESS_ALLOWED, _CONTEXTLESS_REFUSED = True, False + +GATE_ORDER: Final[Mapping[tuple[ControlMode, bool, bool, str], str | None]] = { + # `disabled` comes first, so it is the answer whatever else holds. + (_NOBODY, _ARMED, _CONTEXTLESS_ALLOWED, _NO_USER): _CONTROL_DISABLED, + (_NOBODY, _ARMED, _CONTEXTLESS_ALLOWED, _ADMIN): _CONTROL_DISABLED, + (_NOBODY, _ARMED, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _CONTROL_DISABLED, + (_NOBODY, _ARMED, _CONTEXTLESS_REFUSED, _NO_USER): _CONTROL_DISABLED, + (_NOBODY, _ARMED, _CONTEXTLESS_REFUSED, _ADMIN): _CONTROL_DISABLED, + (_NOBODY, _ARMED, _CONTEXTLESS_REFUSED, _NON_ADMIN): _CONTROL_DISABLED, + (_NOBODY, _OPEN, _CONTEXTLESS_ALLOWED, _NO_USER): _CONTROL_DISABLED, + (_NOBODY, _OPEN, _CONTEXTLESS_ALLOWED, _ADMIN): _CONTROL_DISABLED, + (_NOBODY, _OPEN, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _CONTROL_DISABLED, + (_NOBODY, _OPEN, _CONTEXTLESS_REFUSED, _NO_USER): _CONTROL_DISABLED, + (_NOBODY, _OPEN, _CONTEXTLESS_REFUSED, _ADMIN): _CONTROL_DISABLED, + (_NOBODY, _OPEN, _CONTEXTLESS_REFUSED, _NON_ADMIN): _CONTROL_DISABLED, + # Then the lock, which refuses everyone while armed, administrators too. + (_ALL, _ARMED, _CONTEXTLESS_ALLOWED, _NO_USER): _LOCKED, + (_ALL, _ARMED, _CONTEXTLESS_ALLOWED, _ADMIN): _LOCKED, + (_ALL, _ARMED, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _LOCKED, + (_ALL, _ARMED, _CONTEXTLESS_REFUSED, _NO_USER): _LOCKED, + (_ALL, _ARMED, _CONTEXTLESS_REFUSED, _ADMIN): _LOCKED, + (_ALL, _ARMED, _CONTEXTLESS_REFUSED, _NON_ADMIN): _LOCKED, + (_ADMINS, _ARMED, _CONTEXTLESS_ALLOWED, _NO_USER): _LOCKED, + (_ADMINS, _ARMED, _CONTEXTLESS_ALLOWED, _ADMIN): _LOCKED, + (_ADMINS, _ARMED, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _LOCKED, + (_ADMINS, _ARMED, _CONTEXTLESS_REFUSED, _NO_USER): _LOCKED, + (_ADMINS, _ARMED, _CONTEXTLESS_REFUSED, _ADMIN): _LOCKED, + (_ADMINS, _ARMED, _CONTEXTLESS_REFUSED, _NON_ADMIN): _LOCKED, + # Then a command with no user, where the option refuses one. + (_ALL, _OPEN, _CONTEXTLESS_ALLOWED, _NO_USER): None, + (_ALL, _OPEN, _CONTEXTLESS_ALLOWED, _ADMIN): None, + (_ALL, _OPEN, _CONTEXTLESS_ALLOWED, _NON_ADMIN): None, + (_ALL, _OPEN, _CONTEXTLESS_REFUSED, _NO_USER): _CONTEXTLESS, + (_ALL, _OPEN, _CONTEXTLESS_REFUSED, _ADMIN): None, + (_ALL, _OPEN, _CONTEXTLESS_REFUSED, _NON_ADMIN): None, + # Then `admin_only`, which judges only a caller who has a user. + (_ADMINS, _OPEN, _CONTEXTLESS_ALLOWED, _NO_USER): None, + (_ADMINS, _OPEN, _CONTEXTLESS_ALLOWED, _ADMIN): None, + (_ADMINS, _OPEN, _CONTEXTLESS_ALLOWED, _NON_ADMIN): _ADMIN_ONLY, + (_ADMINS, _OPEN, _CONTEXTLESS_REFUSED, _NO_USER): _CONTEXTLESS, + (_ADMINS, _OPEN, _CONTEXTLESS_REFUSED, _ADMIN): None, + (_ADMINS, _OPEN, _CONTEXTLESS_REFUSED, _NON_ADMIN): _ADMIN_ONLY, +} +"""What the gate answers a priority command, by mode, lock, contextless option and caller. + +The translation key it refuses with, or None where it lets the command +through. A priority command, so the relay debounce never comes into it. +Written out rather than derived, so it states the order the gate checks in -- +`disabled`, the lock, contextless control, `admin_only` -- and moving one +check past another changes a row. +""" + + +def _order_id(case: tuple[ControlMode, bool, bool, str]) -> str: + mode, armed, allow_contextless, caller = case + lock = "armed" if armed else "open" + contextless = "contextless allowed" if allow_contextless else "contextless refused" + return f"{mode}-{lock}-{contextless}-{caller}" + + +def test_the_order_table_covers_every_case() -> None: + """Every mode, lock state, contextless option and kind of caller has a row.""" + assert set(GATE_ORDER) == { + (mode, armed, allow_contextless, caller) + for mode in ControlMode + for armed in (_ARMED, _OPEN) + for allow_contextless in (_CONTEXTLESS_ALLOWED, _CONTEXTLESS_REFUSED) + for caller in (_NO_USER, _ADMIN, _NON_ADMIN) + } + + +@pytest.mark.parametrize("case", list(GATE_ORDER), ids=[_order_id(case) for case in GATE_ORDER]) +@pytest.mark.asyncio +async def test_the_gate_refuses_in_its_order( + hass: HomeAssistant, case: tuple[ControlMode, bool, bool, str] +) -> None: + """The first check that applies is the refusal, whichever others would also apply.""" + mode, armed, allow_contextless, caller = case + gate = _gate( + hass, mode=mode, allow_contextless=allow_contextless, lock=ControlLock(armed=armed) + ) + context = ( + Context() + if caller == _NO_USER + else Context(user_id=MockUser(is_owner=caller == _ADMIN).add_to_hass(hass).id) + ) + + refused: str | None = None + token = async_bind_caller(context, "select.span_panel_kitchen_priority") + try: + await gate.before_publish(PRIORITY) + except ServiceValidationError as err: + refused = err.translation_key + finally: + CONTROL_CALLER.reset(token) + + assert refused == GATE_ORDER[case] + + # ---------- the audit ---------- From 12abfcdbf60052132d2d7cc3d58ebade56a086ee Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:39:21 -0800 Subject: [PATCH 10/15] test(controls): hold the topology and the gate to the policy setup gives them Every other topology test hands the topology and the gate one policy object by construction, so a setup that gave runtime data all_users while the gate enforced admin_only passed the whole suite. That divergence is the bug control_access exists to prevent. The new test runs the entry's real setup under admin_only, asks the topology as a non-admin and turns a real relay switch on: the topology says admin_only and the gate refuses with admin_only_control. After switching to all_users through the options and the reload it causes, both let the user through. The lock tests' real-setup harness moves to switch_platform_setup and both use it. Its stand-in client now puts relay commands to the interceptor setup installed, its coordinator holds the real hass and a connected panel, and its rating manager answers as one holding no copy. --- tests/switch_platform_setup.py | 198 ++++++++++++++++++++++++++ tests/test_control_lock_state.py | 125 +++------------- tests/test_topology_control_access.py | 76 +++++++++- 3 files changed, 294 insertions(+), 105 deletions(-) create mode 100644 tests/switch_platform_setup.py diff --git a/tests/switch_platform_setup.py b/tests/switch_platform_setup.py new file mode 100644 index 00000000..09135aef --- /dev/null +++ b/tests/switch_platform_setup.py @@ -0,0 +1,198 @@ +"""A v2 entry set up for real, with only the switch platform forwarded. + +For tests whose subject is what the entry's own setup builds: the control policy +it resolves from the options, the gate it installs on the transport, the runtime +data it hands the platforms and the WebSocket commands, the switch platform it +forwards, and the reload an options change asks for. Those are all the real +ones. The transport and the coordinator are stand-ins, because none of that +reads the panel. + +A command a relay switch sends goes through the interceptor setup installed, as +the library's publish does, so a test can operate a switch through Home +Assistant and see the real gate decide. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator, Mapping +import contextlib +from unittest.mock import AsyncMock, MagicMock, patch + +from homeassistant.const import CONF_HOST, Platform +from homeassistant.core import HomeAssistant +from pytest_homeassistant.common import MockConfigEntry +from span_panel_api import ( + ControlCommand, + ControlInterceptor, + PublishOutcome, + PublishState, + SpanCircuitSnapshot, + SpanPanelSnapshot, +) + +from custom_components.span_panel.const import ( + CONF_API_VERSION, + CONF_EBUS_BROKER_HOST, + CONF_EBUS_BROKER_PASSWORD, + CONF_EBUS_BROKER_PORT, + CONF_EBUS_BROKER_USERNAME, + CONF_HTTP_PORT, + DOMAIN, +) +from custom_components.span_panel.control_gate import ControlMode +from custom_components.span_panel.migrations import ( + CURRENT_CONFIG_MINOR_VERSION, + CURRENT_CONFIG_VERSION, +) +from custom_components.span_panel.options import CONTROL_MODE +from custom_components.span_panel.package_ratings import MonitoringRating + +from .factories import SpanPanelSnapshotFactory +from .helpers import ensure_device_registered_stand_in + + +def v2_entry(*, serial: str, entry_id: str, options: Mapping[str, object]) -> MockConfigEntry: + """Build a v2 entry for the panel `serial`, at the current config version, with `options`.""" + return MockConfigEntry( + domain=DOMAIN, + data={ + CONF_API_VERSION: "v2", + CONF_HOST: "192.168.1.50", + CONF_EBUS_BROKER_HOST: "span-panel.local", + CONF_EBUS_BROKER_USERNAME: "mqtt-user", + CONF_EBUS_BROKER_PASSWORD: "hunter2-synthetic", + CONF_EBUS_BROKER_PORT: 8883, + CONF_HTTP_PORT: 80, + }, + options=dict(options), + entry_id=entry_id, + title="SPAN Panel", + unique_id=serial, + version=CURRENT_CONFIG_VERSION, + minor_version=CURRENT_CONFIG_MINOR_VERSION, + ) + + +class GatedControls: + """The coordinator's client, as far as a relay switch uses it. + + Each command is put to the interceptor setup installed on the transport and + recorded in `published` once the interceptor lets it through, which is the + part of the library's publish a gate test needs. The library also reports + every outcome back to the interceptor; nothing here does, so no audit event + fires and no relay debounce window opens. + """ + + def __init__(self, serial: str) -> None: + """Start with no interceptor, as the transport does before setup installs one.""" + self._serial = serial + self.interceptor: ControlInterceptor | None = None + self.published: list[ControlCommand] = [] + + def install(self, interceptor: ControlInterceptor | None) -> None: + """Replace the interceptor, as `set_control_interceptor` on the transport does.""" + self.interceptor = interceptor + + async def set_circuit_relay(self, circuit_id: str, state: str) -> PublishOutcome: + """Put a relay command to the interceptor, and publish it if it is let through.""" + return await self._publish( + ControlCommand( + device_id=self._serial, + node_id=circuit_id, + property_id="relay", + value=state, + topic=f"ebus/5/{self._serial}/{circuit_id}/switch/relay/set", + ) + ) + + async def _publish(self, command: ControlCommand) -> PublishOutcome: + assert self.interceptor is not None, "setup installed no interceptor" + await self.interceptor.before_publish(command) + self.published.append(command) + return PublishOutcome( + state=PublishState.CONFIRMED, topic=command.topic, value=command.value + ) + + +def _no_copied_rating(circuit_id: str, snapshot: SpanPanelSnapshot) -> MonitoringRating: + """Answer as a package-rating manager holding no copy does: with the panel's own rating.""" + circuit = snapshot.circuits.get(circuit_id) + rating = circuit.breaker_rating_a if circuit is not None else None + return MonitoringRating(rating, rating, False, None, None) + + +@contextlib.asynccontextmanager +async def switch_platform_setup( + hass: HomeAssistant, + entry: MockConfigEntry, + *, + circuits: Mapping[str, SpanCircuitSnapshot] | None = None, +) -> AsyncIterator[MockConfigEntry]: + """Add `entry`, set it up for real with only the switch platform forwarded, and unload it after. + + The panel publishes `circuits`, none by default. The stand-in coordinator's + client is a `GatedControls` (see `gated_controls`), and its package-rating + manager answers as one holding no copied rating, so the topology can be + asked of the entry. The WebSocket commands are not registered by setup; a + test that sends one registers them itself. + """ + entry.add_to_hass(hass) + serial = str(entry.unique_id) + + snapshot = SpanPanelSnapshotFactory.create(serial_number=serial, circuits=dict(circuits or {})) + controls = GatedControls(serial) + client = MagicMock() + client.connect = AsyncMock() + client.close = AsyncMock() + client.set_control_interceptor = MagicMock(side_effect=controls.install) + coordinator = MagicMock() + # As the real coordinator is: the panel's device info is built from its + # entry, and a circuit entity's id from the registries its `hass` holds. + coordinator.hass = hass + coordinator.config_entry = entry + coordinator.data = snapshot + coordinator.client = controls + # A connected panel, so its relay switches are available: Core skips an + # unavailable entity without an error, and the command would never be sent. + coordinator.panel_offline = False + coordinator.transport_dead = False + coordinator.current_monitor = None + coordinator.async_config_entry_first_refresh = AsyncMock() + coordinator.package_rating_manager.async_load = AsyncMock() + coordinator.package_rating_manager.resolve = MagicMock(side_effect=_no_copied_rating) + coordinator.async_setup_streaming = AsyncMock() + coordinator.async_shutdown = AsyncMock() + + with ( + patch("custom_components.span_panel.async_register_commands"), + patch("custom_components.span_panel.SpanMqttClient", return_value=client), + patch("custom_components.span_panel.SpanPanelCoordinator", return_value=coordinator), + patch( + "custom_components.span_panel.ensure_device_registered", + AsyncMock(side_effect=ensure_device_registered_stand_in), + ), + patch("custom_components.span_panel.PLATFORMS", [Platform.SWITCH]), + ): + assert await hass.config_entries.async_setup(entry.entry_id) is True + await hass.async_block_till_done() + try: + yield entry + finally: + await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + + +def gated_controls(entry: MockConfigEntry) -> GatedControls: + """Return the stand-in client the loaded `entry`'s relay switches publish through.""" + controls = entry.runtime_data.coordinator.client + assert isinstance(controls, GatedControls) + return controls + + +async def set_control_mode(hass: HomeAssistant, entry: MockConfigEntry, mode: ControlMode) -> None: + """Change the control mode as an options save does, and let the reload it asks for run.""" + hass.config_entries.async_update_entry( + entry, options={**entry.options, CONTROL_MODE: mode.value} + ) + await hass.async_block_till_done() + assert entry.runtime_data.control_policy.mode is mode diff --git a/tests/test_control_lock_state.py b/tests/test_control_lock_state.py index e3d33ed2..df341748 100644 --- a/tests/test_control_lock_state.py +++ b/tests/test_control_lock_state.py @@ -10,18 +10,15 @@ from __future__ import annotations -from collections.abc import AsyncIterator, Awaitable, Callable +from collections.abc import Awaitable, Callable import contextlib from datetime import timedelta -from unittest.mock import AsyncMock, MagicMock, patch from homeassistant.const import ( ATTR_RESTORED, - CONF_HOST, STATE_OFF, STATE_ON, STATE_UNAVAILABLE, - Platform, ) from homeassistant.core import Context, HomeAssistant, State from homeassistant.helpers import area_registry as ar, entity_registry as er @@ -34,108 +31,39 @@ mock_restore_cache_with_extra_data, ) -from custom_components.span_panel.const import ( - CONF_API_VERSION, - CONF_EBUS_BROKER_HOST, - CONF_EBUS_BROKER_PASSWORD, - CONF_EBUS_BROKER_PORT, - CONF_EBUS_BROKER_USERNAME, - CONF_HTTP_PORT, - DOMAIN, -) +from custom_components.span_panel.const import DOMAIN from custom_components.span_panel.control_gate import ControlLock, ControlMode -from custom_components.span_panel.migrations import ( - CURRENT_CONFIG_MINOR_VERSION, - CURRENT_CONFIG_VERSION, -) from custom_components.span_panel.options import CONTROL_LOCK_TIMEOUT, CONTROL_MODE from custom_components.span_panel.switch import SpanPanelControlLockSwitch from .common import async_fire_time_changed -from .factories import SpanPanelSnapshotFactory -from .helpers import ensure_device_registered_stand_in, watch_add_and_remove +from .helpers import watch_add_and_remove +from .switch_platform_setup import set_control_mode, switch_platform_setup, v2_entry LOCK_ENTITY = "switch.span_panel_control_lock" EDITED_LOCK_ENTITY = "switch.panel_control_lock" SERIAL = "sp3-lock-001" -def _entry(timeout: float, mode: ControlMode | None) -> MockConfigEntry: - """Build a v2 entry with the control-lock feature configured to `timeout`. - - `mode` None leaves the control mode unset, as most entries have it. +def _panel( + hass: HomeAssistant, *, timeout: float, mode: ControlMode | None = None +) -> contextlib.AbstractAsyncContextManager[MockConfigEntry]: + """Set up, for real, an entry with the control-lock feature configured to `timeout`. + + `mode` None leaves the control mode unset, as most entries have it. The + transport and the coordinator are stubs -- neither has anything to do with + the lock -- but the entry setup, the platform forward, the entity registry + and the unload path are all the real ones, because a reload is exactly + those four things. See `switch_platform_setup`. """ options: dict[str, object] = {CONTROL_LOCK_TIMEOUT: timeout} if mode is not None: options[CONTROL_MODE] = mode.value - return MockConfigEntry( - domain=DOMAIN, - data={ - CONF_API_VERSION: "v2", - CONF_HOST: "192.168.1.50", - CONF_EBUS_BROKER_HOST: "span-panel.local", - CONF_EBUS_BROKER_USERNAME: "mqtt-user", - CONF_EBUS_BROKER_PASSWORD: "hunter2-synthetic", - CONF_EBUS_BROKER_PORT: 8883, - CONF_HTTP_PORT: 80, - }, - options=options, - entry_id="entry-control-lock", - title="SPAN Panel", - unique_id=SERIAL, - version=CURRENT_CONFIG_VERSION, - minor_version=CURRENT_CONFIG_MINOR_VERSION, + return switch_platform_setup( + hass, v2_entry(serial=SERIAL, entry_id="entry-control-lock", options=options) ) -@contextlib.asynccontextmanager -async def _panel( - hass: HomeAssistant, *, timeout: float, mode: ControlMode | None = None -) -> AsyncIterator[MockConfigEntry]: - """Set the entry up for real, with only the switch platform forwarded. - - The transport and the coordinator are stubs -- neither has anything to do - with the lock -- but the entry setup, the platform forward, the entity - registry and the unload path are all the real ones, because a reload is - exactly those four things. - """ - entry = _entry(timeout, mode) - entry.add_to_hass(hass) - - snapshot = SpanPanelSnapshotFactory.create(serial_number=SERIAL, circuits={}) - client = MagicMock() - client.connect = AsyncMock() - client.close = AsyncMock() - coordinator = MagicMock() - # As the real coordinator is: the panel's device info is built from it. - coordinator.config_entry = entry - coordinator.data = snapshot - coordinator.transport_dead = False - coordinator.current_monitor = None - coordinator.async_config_entry_first_refresh = AsyncMock() - coordinator.package_rating_manager.async_load = AsyncMock() - coordinator.async_setup_streaming = AsyncMock() - coordinator.async_shutdown = AsyncMock() - - with ( - patch("custom_components.span_panel.async_register_commands"), - patch("custom_components.span_panel.SpanMqttClient", return_value=client), - patch("custom_components.span_panel.SpanPanelCoordinator", return_value=coordinator), - patch( - "custom_components.span_panel.ensure_device_registered", - AsyncMock(side_effect=ensure_device_registered_stand_in), - ), - patch("custom_components.span_panel.PLATFORMS", [Platform.SWITCH]), - ): - assert await hass.config_entries.async_setup(entry.entry_id) is True - await hass.async_block_till_done() - try: - yield entry - finally: - await hass.config_entries.async_unload(entry.entry_id) - await hass.async_block_till_done() - - def _lock(entry: MockConfigEntry) -> ControlLock: """Return the live lock object this entry's gate consults.""" lock = entry.runtime_data.control_lock @@ -158,9 +86,7 @@ async def _reload(hass: HomeAssistant, entry: MockConfigEntry) -> None: async def _arm(hass: HomeAssistant) -> None: """Arm through the service, so the entity writes its own state.""" - await hass.services.async_call( - "switch", "turn_on", {"entity_id": LOCK_ENTITY}, blocking=True - ) + await hass.services.async_call("switch", "turn_on", {"entity_id": LOCK_ENTITY}, blocking=True) async def _disarm(hass: HomeAssistant) -> None: @@ -446,15 +372,6 @@ async def test_the_lock_stays_operable_when_the_transport_dies(hass: HomeAssista # ---------- while control is disabled ---------- -async def _set_mode(hass: HomeAssistant, entry: MockConfigEntry, mode: ControlMode) -> None: - """Change the control mode as an options save does, and let the reload it asks for run.""" - hass.config_entries.async_update_entry( - entry, options={**entry.options, CONTROL_MODE: mode.value} - ) - await hass.async_block_till_done() - assert entry.runtime_data.control_policy.mode is mode - - def _registry_row(hass: HomeAssistant) -> er.RegistryEntry: row = er.async_get(hass).async_get(LOCK_ENTITY) assert row is not None @@ -475,7 +392,7 @@ async def test_disabling_control_stops_creating_the_lock_switch_and_keeps_its_re async with _panel(hass, timeout=0, mode=ControlMode.ALL_USERS) as entry: before = _registry_row(hass) - await _set_mode(hass, entry, ControlMode.DISABLED) + await set_control_mode(hass, entry, ControlMode.DISABLED) after = _registry_row(hass) assert (after.id, after.entity_id, after.unique_id) == ( @@ -520,8 +437,8 @@ async def test_turning_control_back_on_brings_the_same_lock_switch_back_as_it_wa er.async_get(hass).async_update_entity(LOCK_ENTITY, name="Breaker lock", area_id=garage.id) before = _registry_row(hass) - await _set_mode(hass, entry, ControlMode.DISABLED) - await _set_mode(hass, entry, ControlMode.ALL_USERS) + await set_control_mode(hass, entry, ControlMode.DISABLED) + await set_control_mode(hass, entry, ControlMode.ALL_USERS) after = _registry_row(hass) assert (after.id, after.entity_id, after.unique_id, after.name, after.area_id) == ( @@ -583,7 +500,7 @@ async def test_a_restart_while_control_is_disabled_keeps_the_lock_state_for_late async with _panel(hass, timeout=0, mode=ControlMode.DISABLED) as entry: assert _lock(entry).armed is False - await _set_mode(hass, entry, ControlMode.ALL_USERS) + await set_control_mode(hass, entry, ControlMode.ALL_USERS) assert _lock(entry).armed is False restored = hass.states.get(LOCK_ENTITY) diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py index 405874d4..7556b9b6 100644 --- a/tests/test_topology_control_access.py +++ b/tests/test_topology_control_access.py @@ -7,7 +7,8 @@ the panel's controls for a user it says may not operate them, so what it says must not come apart from what either rule does: two tests here run the rule itself -- the gate, and a service call through Core -- beside the topology and -hold them to one answer. +hold them to one answer. A third runs the entry's own setup, so a setup that +handed the topology one policy and the gate another would fail it. """ from __future__ import annotations @@ -41,12 +42,19 @@ ) from custom_components.span_panel.curation import CurationOverlay from custom_components.span_panel.id_builder import build_select_unique_id, build_switch_unique_id +from custom_components.span_panel.options import CONTROL_MODE from custom_components.span_panel.package_rating_manager import PackageRatingManager from custom_components.span_panel.runtime import SpanPanelRuntimeData from custom_components.span_panel.websocket import async_register_commands from .factories import SpanCircuitSnapshotFactory, SpanPanelSnapshotFactory, pv_binding_for from .helpers import register_panel_device +from .switch_platform_setup import ( + gated_controls, + set_control_mode, + switch_platform_setup, + v2_entry, +) _SERIAL: Final = "sp3-synthetic-access-001" _CIRCUIT_ID: Final = "circuit-3" @@ -329,6 +337,72 @@ async def test_the_topology_reports_read_only_exactly_where_core_refuses_control ) +# --------------------------------------------------------------------------- +# Through the entry's own setup +# --------------------------------------------------------------------------- + +_SETUP_SERIAL: Final = "sp3-synthetic-access-002" + + +async def _turn_on(hass: HomeAssistant, user: MockUser, entity_id: str) -> None: + """Turn `entity_id` on as `user`, through Home Assistant's service call.""" + await hass.services.async_call( + "switch", + "turn_on", + {"entity_id": entity_id}, + blocking=True, + context=Context(user_id=user.id), + ) + + +async def test_setup_gives_the_topology_the_policy_its_gate_enforces( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator +) -> None: + """A non-admin is told what the gate then does to their relay command, before and after an options change. + + Everything else here hands the topology and the gate one policy object by + construction, so it cannot see setup give them different ones -- which is + the bug the topology exists to prevent: the card offering a toggle the gate + refuses. This runs the entry's real setup, a real `switch.turn_on` on a relay + switch the real platform created, the real gate, and the reload an options + change causes. + """ + group = await hass.auth.async_get_group(GROUP_ID_USER) + assert group is not None + user = MockUser(groups=[group]).add_to_hass(hass) + entry = v2_entry( + serial=_SETUP_SERIAL, + entry_id="entry-control-access", + options={CONTROL_MODE: ControlMode.ADMIN_ONLY.value}, + ) + circuit = SpanCircuitSnapshotFactory.create( + circuit_id=_CIRCUIT_ID, name="Synthetic Circuit", tabs=[3], is_user_controllable=True + ) + + async with switch_platform_setup(hass, entry, circuits={_CIRCUIT_ID: circuit}): + async_register_commands(hass) + device_id = entry.runtime_data.panel_device_id + topology = await _topology(hass, hass_ws_client, user, device_id) + circuits = topology["circuits"] + assert isinstance(circuits, dict) + relay = circuits[_CIRCUIT_ID]["entities"]["switch"] + + assert topology["control_access"] == {"may_operate": False, "reason": "admin_only"} + with pytest.raises(ServiceValidationError) as refused: + await _turn_on(hass, user, relay) + assert refused.value.translation_key == "admin_only_control" + assert gated_controls(entry).published == [] + + await set_control_mode(hass, entry, ControlMode.ALL_USERS) + + assert await _control_access(hass, hass_ws_client, user, device_id) == { + "may_operate": True, + "reason": None, + } + await _turn_on(hass, user, relay) + assert [command.node_id for command in gated_controls(entry).published] == [_CIRCUIT_ID] + + # --------------------------------------------------------------------------- # The rule, directly # --------------------------------------------------------------------------- From 301d1827387a072f2c56ba14b64a2e59f941f8e9 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:42:14 -0800 Subject: [PATCH 11/15] test(websocket): hold read_only to Core's refusal of the priority select too, and of a custom policy The Core-agreement test asked only switch.turn_on of the relay switch. It now asks select.select_option of the priority select as well. A group whose policy allows control of the relay alone may operate the panel, and Core refuses that group the priority select. --- tests/test_topology_control_access.py | 60 +++++++++++++++++++++------ 1 file changed, 48 insertions(+), 12 deletions(-) diff --git a/tests/test_topology_control_access.py b/tests/test_topology_control_access.py index 7556b9b6..22911170 100644 --- a/tests/test_topology_control_access.py +++ b/tests/test_topology_control_access.py @@ -19,6 +19,7 @@ from unittest.mock import AsyncMock, MagicMock from homeassistant.auth.const import GROUP_ID_ADMIN, GROUP_ID_READ_ONLY, GROUP_ID_USER +from homeassistant.auth.models import Group from homeassistant.config_entries import ConfigEntryState from homeassistant.core import Context, HomeAssistant from homeassistant.exceptions import ServiceValidationError, Unauthorized @@ -227,17 +228,22 @@ async def _gate_refusal(hass: HomeAssistant, entry: MockConfigEntry, user: MockU async def _core_refuses_control(hass: HomeAssistant, user: MockUser, entity_id: str) -> bool: - """Whether Core refuses `user` a `switch.turn_on` of `entity_id` for want of control permission. + """Whether Core refuses `user` control of `entity_id` for want of control permission. - The switch is only registered, never added, so a call Core lets through - reaches no entity and does nothing: what is asked is Core's permission - check, which comes first. + A relay switch is asked `switch.turn_on` and a priority select + `select.select_option`, the calls the card makes. The entity is only + registered, never added, so a call Core lets through reaches no entity and + does nothing: what is asked is Core's permission check, which comes first. """ + domain = entity_id.split(".", 1)[0] + service, data = ( + ("select_option", {"option": "OFF_GRID"}) if domain == "select" else ("turn_on", {}) + ) try: await hass.services.async_call( - "switch", - "turn_on", - {"entity_id": entity_id}, + domain, + service, + {"entity_id": entity_id, **data}, blocking=True, context=Context(user_id=user.id), ) @@ -316,25 +322,55 @@ async def test_the_topology_and_the_gate_give_the_asker_the_same_answer( async def test_the_topology_reports_read_only_exactly_where_core_refuses_control( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, asker: tuple[str, MockUser] ) -> None: - """Core refuses the asker the panel's relay switch exactly where the topology says `read_only`. + """Core refuses the asker the panel's relay switch and priority select exactly where the topology says `read_only`. Under All users, where the mode refuses no one, so the permissions are the whole answer. """ _, user = asker assert await async_setup_component(hass, "switch", {}) + assert await async_setup_component(hass, "select", {}) _, device_id, controls = await _load_panel(hass, ControlMode.ALL_USERS) topology = await _topology(hass, hass_ws_client, user, device_id) circuit = topology["circuits"] assert isinstance(circuit, dict) - switch = circuit[_CIRCUIT_ID]["entities"]["switch"] - assert switch in controls + entities = circuit[_CIRCUIT_ID]["entities"] + offered = [entities["switch"], entities["select"]] + assert offered == controls control_access_record = topology["control_access"] assert isinstance(control_access_record, dict) - assert (control_access_record["reason"] == "read_only") is await _core_refuses_control( - hass, user, switch + read_only = control_access_record["reason"] == "read_only" + assert [await _core_refuses_control(hass, user, entity_id) for entity_id in offered] == [ + read_only, + read_only, + ] + + +async def test_a_policy_that_allows_one_relay_may_operate_and_is_refused_the_rest( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator +) -> None: + """A group whose policy allows control of the relay switch alone: the panel may be operated, the priority select may not. + + The answer is one flag for the panel, so it is true for a user who can + control any of its controls, and Core refuses the others one at a time. + """ + assert await async_setup_component(hass, "switch", {}) + assert await async_setup_component(hass, "select", {}) + _, device_id, controls = await _load_panel(hass, ControlMode.ALL_USERS) + relay, priority = controls + relay_only = Group( + name="Synthetic relay only", policy={"entities": {"entity_ids": {relay: True}}} ) + user = MockUser(groups=[relay_only]).add_to_hass(hass) + assert not user.is_admin + + assert await _control_access(hass, hass_ws_client, user, device_id) == { + "may_operate": True, + "reason": None, + } + assert await _core_refuses_control(hass, user, relay) is False + assert await _core_refuses_control(hass, user, priority) is True # --------------------------------------------------------------------------- From 754cef02fd2e9bc8bf98621fc74b0c569162f453 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:44:51 -0800 Subject: [PATCH 12/15] docs(controls): say what keeps the gate and the topology agreeing, and where Core refuses refusal_for no longer claims the two cannot disagree; it says they are decided by one rule and which tests hold them to one answer. The gate's ordering comment places admin_only before the relay debounce rather than last, and control_access says Core raises Unauthorized at the first entity a call names that the user may not control. --- custom_components/span_panel/control_access.py | 11 ++++++----- custom_components/span_panel/control_gate.py | 9 ++++++--- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/custom_components/span_panel/control_access.py b/custom_components/span_panel/control_access.py index 20929309..6d5a9fea 100644 --- a/custom_components/span_panel/control_access.py +++ b/custom_components/span_panel/control_access.py @@ -8,11 +8,12 @@ every command. It comes first, because it is the integration's own answer and holds for every control the entry has. - **The user's Home Assistant permissions.** Core refuses an entity service - call from a user who is not an administrator, with `Unauthorized`, for each - entity that `user.permissions.check_entity(entity_id, POLICY_CONTROL)` does - not allow, and administrators are not checked at all (`helpers/service.py`). - That happens before any entity, and so before the gate, is asked, which is - why the gate never answers it and this module has to. + call from a user who is not an administrator, raising `Unauthorized` at the + first entity it names that `user.permissions.check_entity(entity_id, + POLICY_CONTROL)` does not allow, and administrators are not checked at all + (`helpers/service.py`). That happens before any entity, and so before the + gate, is asked, which is why the gate never answers it and this module has + to. `control_access` asks the mode, then the permissions, and reports the first refusal. diff --git a/custom_components/span_panel/control_gate.py b/custom_components/span_panel/control_gate.py index f0cf0af2..19e11141 100644 --- a/custom_components/span_panel/control_gate.py +++ b/custom_components/span_panel/control_gate.py @@ -194,7 +194,9 @@ def refusal_for(self, *, is_admin: bool | None) -> ControlModeRefusal | None: The one statement of who the mode lets operate the panel. The gate enforces it on every command, and `span_panel/panel_topology` reports it for whoever is viewing the card, so the controls the card offers and the - commands the gate lets through cannot come to disagree. + commands the gate lets through are decided by one rule rather than two + copies of it. `test_topology_control_access.py` runs both, the gate + through a real setup too, and holds them to the same answer. `is_admin` is None for a caller with no logged-in user. `disabled` refuses that caller as it refuses everyone. `admin_only` does not judge @@ -428,8 +430,9 @@ async def before_publish(self, command: ControlCommand) -> None: user_id = context.user_id if context is not None else None # Judged once, by the rule the topology reports to the card, and acted - # on below in this method's own order: `disabled` before everything, - # `admin_only` last. + # on below in this method's own order: `disabled` before everything + # else, `admin_only` after the lock and contextless checks and before + # the relay debounce. refusal = self._policy.refusal_for(is_admin=await self._caller_is_admin(user_id)) # First, because it is the entry-wide answer and the most useful thing From 2d3dada5a369f302c10c214fd682823cfc539c15 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:47:46 -0800 Subject: [PATCH 13/15] docs: state the topology's empty spaces, panel roles and the README's permission case precisely An empty space is a position in the range that no circuit's tabs include. The panel roles are read from the entity registry, and the battery example says a panel set up without one, which is what was checked. The README's account is one whose permissions allow control of none of the relay and priority controls. --- README.md | 4 ++-- websocket-api.md | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8c577b41..98d8c6e4 100644 --- a/README.md +++ b/README.md @@ -715,8 +715,8 @@ see [Recommended deployment](#recommended-deployment), where network topology an customizations are kept, so turning the option back on restores exactly the entities you had. The control lock comes back armed or disarmed as you left it, with any auto-relock still due at the same moment, and armed if Home Assistant no longer holds its last state. The shipped SPAN Panel card and dashboard offer no breaker switch or priority while `Nobody` is chosen, and other dashboards show those entities unavailable. For a user who may not operate the panel — anyone but -an administrator while `Administrators only` is chosen, or an account whose Home Assistant permissions do not allow control — the card and dashboard show the -relay and priority controls disabled. +an administrator while `Administrators only` is chosen, or an account whose Home Assistant permissions allow control of none of its relay and priority controls +— the card and dashboard show those controls disabled. ### The record of what was commanded diff --git a/websocket-api.md b/websocket-api.md index e226f0c9..75d93553 100644 --- a/websocket-api.md +++ b/websocket-api.md @@ -237,7 +237,7 @@ Home Assistant's device list, which no longer holds a pre-2026.8 ID. `first_position` and `last_position` say which breaker positions the panel has, occupied or not: the reported model's range where the integration knows the model, otherwise the lowest and highest occupied spaces, and null where neither is known. `circuits` lists only the circuits that are there, so a position in -the range with no circuit is an empty space. +the range that no circuit's `tabs` include is an empty space. #### Panel Entity Roles @@ -260,9 +260,9 @@ the range with no circuit is an empty space. | `l2_voltage` | sensor | L2 Voltage | | `panel_status` | binary_sensor | Panel Status | -A role is present while its entity is registered for this panel, enabled or not, and omitted otherwise: a panel without a battery has no `battery_power` or -`battery_level`. Each value is the entity's current ID, so a renamed entity is still found. `panel_status` stays available while the panel is offline, so a -consumer can watch it for whether the panel is online. +The roles are read from the entity registry: a role is present while its entity is registered for this panel, enabled or not, and omitted otherwise. A panel set +up without a battery, for example, has no `battery_power` or `battery_level`. Each value is the entity's current ID, so a renamed entity is still found. +`panel_status` stays available while the panel is offline, so a consumer can watch it for whether the panel is online. #### Control Access Object From 11c775ab05bc6cb7640ba6c46c9de42858aa9d06 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:56:14 -0800 Subject: [PATCH 14/15] docs(websocket-api): say which controls each control_access reason covers control_disabled and admin_only hold for every control the integration sends the panel through the gate: circuit relays and priorities, the GFE override, EVSE charge limits and locks, and adopted controls. read_only is judged over the relay switches and priority selects alone, which a consumer other than the card needs to know. Also renames the gate test for a caller with no user to say plainly what it shows: such a caller is refused only when control is disabled. --- tests/test_control_gate.py | 2 +- websocket-api.md | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/test_control_gate.py b/tests/test_control_gate.py index ceb0a0e1..494da374 100644 --- a/tests/test_control_gate.py +++ b/tests/test_control_gate.py @@ -808,7 +808,7 @@ def test_an_entry_with_no_control_options_gets_the_defaults() -> None: (ControlMode.DISABLED, ControlModeRefusal.CONTROL_DISABLED), ], ) -def test_the_mode_judges_a_caller_with_no_user_only_by_refusing_everyone( +def test_a_caller_with_no_user_is_refused_only_when_control_is_disabled( mode: ControlMode, refusal: ControlModeRefusal | None ) -> None: """`admin_only` has no user to judge; whether such a command goes through is `allow_contextless`'s question.""" diff --git a/websocket-api.md b/websocket-api.md index 75d93553..437a0cc4 100644 --- a/websocket-api.md +++ b/websocket-api.md @@ -280,7 +280,9 @@ up without a battery, for example, has no `battery_power` or `battery_level`. Ea | `read_only` | The user's Home Assistant permissions let them control none of the relay switches and priority selects named in `circuits`, as for a read-only user | The answer is for the user the WebSocket connection is authenticated as, so two users asking about the same panel can be told different things. The first two -come from the rule the integration refuses a control command by. `read_only` comes from Home Assistant, which refuses a user without control permission before +come from the rule the integration refuses a control command by, and hold for every control it sends the panel: circuit relays and priorities, the GFE override, +EVSE charge limits and locks, and adopted controls. `read_only` is judged over the relay switches and priority selects alone, so for any other control +`may_operate` true does not say the user's permissions allow it. `read_only` comes from Home Assistant, which refuses a user without control permission before the integration is asked; it is never reported for an administrator, whose permissions Home Assistant does not check, nor for a panel whose circuits name no relay switch or priority select. A user who may control some of those controls but not others may operate the panel, and is refused the others one at a time. From d2e634dae4adc44500677386a46bf91918428f4d Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:01:03 -0800 Subject: [PATCH 15/15] build: bundle the card that disables the controls a user may not operate Built from span-card main 8c95a56 (SpanPanel/span-card#44), which reads the topology's control_access. --- .../frontend/dist/span-panel-card.js | 129 ++++++++++++------ .../span_panel/frontend/dist/span-panel.js | 117 +++++++++++----- 2 files changed, 172 insertions(+), 74 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 422bed1d..4cb6f4c0 100644 --- a/custom_components/span_panel/frontend/dist/span-panel-card.js +++ b/custom_components/span_panel/frontend/dist/span-panel-card.js @@ -1,42 +1,42 @@ -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}","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.failed":"Failed","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","settings.heading":"Settings","settings.description":"General integration settings (entity naming, device prefix, circuit numbers) are managed through the integration's options flow.","settings.open_link":"Open SPAN Panel Integration Settings","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Panel monitoring settings","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.device_not_found":"Panel device not found. Check device_id in card config.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","card.panel_size_error":"Could not determine panel_size. No circuits found and no panel_size attribute. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.panel":"Panel","tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.settings":"Configuración","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.failed":"Falló","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","settings.heading":"Configuración","settings.description":"La configuración general de la integración (nombres de entidades, prefijo de dispositivo, números de circuito) se administra a través del flujo de opciones de la integración.","settings.open_link":"Abrir Configuración de Integración SPAN Panel","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configuración de monitoreo del panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.device_not_found":"Dispositivo de panel no encontrado. Verifique device_id en la configuración de la tarjeta.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","card.panel_size_error":"No se pudo determinar panel_size. No se encontraron circuitos ni atributo panel_size. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.panel":"Panneau","tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.settings":"Paramètres","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.failed":"Échoué","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","settings.heading":"Paramètres","settings.description":"Les paramètres généraux de l'intégration (noms d'entités, préfixe de l'appareil, numéros de circuit) sont gérés via le flux d'options de l'intégration.","settings.open_link":"Ouvrir les Paramètres d'Intégration SPAN Panel","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Paramètres de surveillance du panneau","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.device_not_found":"Appareil de panneau introuvable. Vérifiez device_id dans la configuration de la carte.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","card.panel_size_error":"Impossible de déterminer panel_size. Aucun circuit trouvé et aucun attribut panel_size. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.panel":"パネル","tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.settings":"設定","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.failed":"失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","settings.heading":"設定","settings.description":"統合の一般設定(エンティティ名、デバイスプレフィックス、回路番号)は統合のオプションフローで管理されます。","settings.open_link":"SPAN Panel統合設定を開く","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"パネルモニタリング設定","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.device_not_found":"パネルデバイスが見つかりません。カード設定のdevice_idを確認してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","card.panel_size_error":"panel_sizeを判定できません。回路がpanel_size属性が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.panel":"Painel","tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.settings":"Configurações","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.failed":"Falhou","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","settings.heading":"Configurações","settings.description":"As configurações gerais da integração (nomes de entidades, prefixo do dispositivo, números de circuito) são gerenciadas através do fluxo de opções da integração.","settings.open_link":"Abrir Configurações de Integração SPAN Panel","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configurações de monitoramento do painel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.device_not_found":"Dispositivo do painel não encontrado. Verifique device_id na configuração do cartão.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","card.panel_size_error":"Não foi possível determinar panel_size. Nenhum circuito encontrado e nenhum atributo panel_size. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){t=n&&e[n]?n:"en"}function i(n){return e[t]?.[n]??e.en?.[n]??n}function r(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const o="power",a="5m",s={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},l="span_panel",c="bess",u="evse",d="pv",h="sub_",p={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)}},f={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:p.power},g={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")}},m=Object.keys(g).filter(t=>"unknown"!==t&&"always_on"!==t);var v=function(t,e){return v=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])},v(t,e)};function y(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}v(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function _(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; +let t="en";const e={en:{"tab.panel":"Panel","tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","tab.settings":"Settings","tab.adopted":"Adopted","list.search_placeholder":"Search circuits...","list.unassigned_area":"Unassigned","list.no_results":"No circuits found","monitoring.heading":"Monitoring","monitoring.global_settings":"Global Settings","monitoring.enabled":"Enabled","monitoring.continuous":"Continuous (%)","monitoring.spike":"Spike (%)","monitoring.window":"Window (min)","monitoring.cooldown":"Cooldown (min)","monitoring.monitored_points":"Monitored Points","monitoring.col.name":"Name","monitoring.col.continuous":"Continuous","monitoring.col.spike":"Spike","monitoring.col.window":"Window","monitoring.col.cooldown":"Cooldown","monitoring.rating":"Rating","monitoring.all_none":"All / None","monitoring.reset":"Reset","monitoring.limit_invalid":"Enter a whole number from {min} to {max}.","monitoring.enable_invalid":"Monitoring was not turned on: correct the fields marked.","monitoring.point_field":"{field} for {name}","monitoring.reset_point":"Reset {name}","monitoring.admin_only":"Only an administrator can change monitoring.","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.failed":"Failed","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","settings.heading":"Settings","settings.description":"General integration settings (entity naming, device prefix, circuit numbers) are managed through the integration's options flow.","settings.open_link":"Open SPAN Panel Integration Settings","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Panel monitoring settings","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","controls.admin_only":"Only an administrator can operate this panel's controls.","controls.disabled":"Control of this panel is switched off in its options.","controls.read_only":"Your Home Assistant account can't operate this panel's controls.","controls.entity_unauthorized":"Your Home Assistant account can't operate this control.","controls.not_operable":"You can't operate this panel's controls.","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.device_not_found":"Panel device not found. Check device_id in card config.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","card.panel_size_error":"Could not determine panel_size. No circuits found and no panel_size attribute. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.panel":"Panel","tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.settings":"Configuración","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","monitoring.admin_only":"Solo un administrador puede cambiar el monitoreo.","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.failed":"Falló","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","settings.heading":"Configuración","settings.description":"La configuración general de la integración (nombres de entidades, prefijo de dispositivo, números de circuito) se administra a través del flujo de opciones de la integración.","settings.open_link":"Abrir Configuración de Integración SPAN Panel","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configuración de monitoreo del panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","controls.admin_only":"Solo un administrador puede operar los controles de este panel.","controls.disabled":"El control de este panel está desactivado en sus opciones.","controls.read_only":"Su cuenta de Home Assistant no puede operar los controles de este panel.","controls.entity_unauthorized":"Su cuenta de Home Assistant no puede operar este control.","controls.not_operable":"No puede operar los controles de este panel.","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.device_not_found":"Dispositivo de panel no encontrado. Verifique device_id en la configuración de la tarjeta.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","card.panel_size_error":"No se pudo determinar panel_size. No se encontraron circuitos ni atributo panel_size. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.panel":"Panneau","tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.settings":"Paramètres","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","monitoring.admin_only":"Seul un administrateur peut modifier la surveillance.","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.failed":"Échoué","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","settings.heading":"Paramètres","settings.description":"Les paramètres généraux de l'intégration (noms d'entités, préfixe de l'appareil, numéros de circuit) sont gérés via le flux d'options de l'intégration.","settings.open_link":"Ouvrir les Paramètres d'Intégration SPAN Panel","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Paramètres de surveillance du panneau","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","controls.admin_only":"Seul un administrateur peut utiliser les commandes de ce panneau.","controls.disabled":"La commande de ce panneau est désactivée dans ses options.","controls.read_only":"Votre compte Home Assistant ne peut pas utiliser les commandes de ce panneau.","controls.entity_unauthorized":"Votre compte Home Assistant ne peut pas utiliser cette commande.","controls.not_operable":"Vous ne pouvez pas utiliser les commandes de ce panneau.","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.device_not_found":"Appareil de panneau introuvable. Vérifiez device_id dans la configuration de la carte.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","card.panel_size_error":"Impossible de déterminer panel_size. Aucun circuit trouvé et aucun attribut panel_size. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.panel":"パネル","tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.settings":"設定","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","monitoring.admin_only":"モニタリングを変更できるのは管理者のみです。","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.failed":"失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","settings.heading":"設定","settings.description":"統合の一般設定(エンティティ名、デバイスプレフィックス、回路番号)は統合のオプションフローで管理されます。","settings.open_link":"SPAN Panel統合設定を開く","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"パネルモニタリング設定","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","controls.admin_only":"このパネルのコントロールを操作できるのは管理者のみです。","controls.disabled":"このパネルのコントロールはオプションで無効になっています。","controls.read_only":"お使いのHome Assistantアカウントでは、このパネルのコントロールを操作できません。","controls.entity_unauthorized":"お使いのHome Assistantアカウントでは、このコントロールを操作できません。","controls.not_operable":"このパネルのコントロールは操作できません。","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.device_not_found":"パネルデバイスが見つかりません。カード設定のdevice_idを確認してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","card.panel_size_error":"panel_sizeを判定できません。回路がpanel_size属性が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.panel":"Painel","tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.settings":"Configurações","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","monitoring.admin_only":"Somente um administrador pode alterar o monitoramento.","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.failed":"Falhou","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","settings.heading":"Configurações","settings.description":"As configurações gerais da integração (nomes de entidades, prefixo do dispositivo, números de circuito) são gerenciadas através do fluxo de opções da integração.","settings.open_link":"Abrir Configurações de Integração SPAN Panel","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configurações de monitoramento do painel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","controls.admin_only":"Somente um administrador pode operar os controles deste painel.","controls.disabled":"O controle deste painel está desativado nas suas opções.","controls.read_only":"Sua conta do Home Assistant não pode operar os controles deste painel.","controls.entity_unauthorized":"Sua conta do Home Assistant não pode operar este controle.","controls.not_operable":"Você não pode operar os controles deste painel.","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.device_not_found":"Dispositivo do painel não encontrado. Verifique device_id na configuração do cartão.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","card.panel_size_error":"Não foi possível determinar panel_size. Nenhum circuito encontrado e nenhum atributo panel_size. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){t=n&&e[n]?n:"en"}function i(n){return e[t]?.[n]??e.en?.[n]??n}function r(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const o="power",a="5m",s={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},l="span_panel",c="span-panel-card",u=`custom:${c}`,d="span-panel",h=`custom:${d}`,p=`ll-strategy-section-${d}`,f="bess",g="evse",m="pv",v="sub_",y={power:{entityRole:"power",label:()=>i("metric.power"),unit:t=>Math.abs(t)>=1e3?"kW":"W",format:t=>{const e=Math.abs(t);return e>=1e3?(e/1e3).toFixed(1):e<10&&e>0?e.toFixed(1):String(Math.round(e))}},current:{entityRole:"current",label:()=>i("metric.current"),unit:()=>"A",format:t=>Math.abs(t).toFixed(1)}},_={soc:{entityRole:"soc",label:()=>i("metric.soc"),unit:()=>"%",format:t=>String(Math.round(t)),fixedMin:0,fixedMax:100},soe:{entityRole:"soe",label:()=>i("metric.soe"),unit:()=>"kWh",format:t=>t.toFixed(1)},power:y.power},b={always_on:{icon:"mdi:battery",icon2:"mdi:router-wireless",color:"#4caf50",label:()=>i("shedding.always_on")},never:{icon:"mdi:battery",color:"#4caf50",label:()=>i("shedding.never")},soc_threshold:{icon:"mdi:battery-alert-variant-outline",color:"#9c27b0",label:()=>i("shedding.soc_threshold"),textLabel:"SoC"},off_grid:{icon:"mdi:transmission-tower",color:"#ff9800",label:()=>i("shedding.off_grid")},unknown:{icon:"mdi:help-circle-outline",color:"#888",label:()=>i("shedding.unknown")}},x=Object.keys(b).filter(t=>"unknown"!==t&&"always_on"!==t);var w=function(t,e){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},w(t,e)};function S(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}w(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function C(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ -const b=globalThis,x=b.ShadowRoot&&(void 0===b.ShadyCSS||b.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,w=Symbol(),S=new WeakMap;let C=class{constructor(t,e,n){if(this._$cssResult$=!0,n!==w)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(x&&void 0===t){const n=void 0!==e&&1===e.length;n&&(t=S.get(e)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&S.set(e,t))}return t}toString(){return this.cssText}};const k=t=>new C("string"==typeof t?t:t+"",void 0,w),M=(t,...e)=>{const n=1===t.length?t[0]:e.reduce((e,n,i)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+t[i+1],t[0]);return new C(n,t,w)},T=x?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return k(e)})(t):t,{is:A,defineProperty:I,getOwnPropertyDescriptor:D,getOwnPropertyNames:P,getOwnPropertySymbols:L,getPrototypeOf:E}=Object,N=globalThis,R=N.trustedTypes,O=R?R.emptyScript:"",z=N.reactiveElementPolyfillSupport,H=(t,e)=>t,B={toAttribute(t,e){switch(e){case Boolean:t=t?O:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=null!==t;break;case Number:n=null===t?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch(t){n=null}}return n}},$=(t,e)=>!A(t,e),F={attribute:!0,type:String,converter:B,reflect:!1,useDefault:!1,hasChanged:$}; +const k=globalThis,M=k.ShadowRoot&&(void 0===k.ShadyCSS||k.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,T=Symbol(),A=new WeakMap;let I=class{constructor(t,e,n){if(this._$cssResult$=!0,n!==T)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(M&&void 0===t){const n=void 0!==e&&1===e.length;n&&(t=A.get(e)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),n&&A.set(e,t))}return t}toString(){return this.cssText}};const D=t=>new I("string"==typeof t?t:t+"",void 0,T),P=(t,...e)=>{const n=1===t.length?t[0]:e.reduce((e,n,i)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if("number"==typeof t)return t;throw Error("Value passed to 'css' function must be a 'css' function result: "+t+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+t[i+1],t[0]);return new I(n,t,T)},L=M?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e="";for(const n of t.cssRules)e+=n.cssText;return D(e)})(t):t,{is:E,defineProperty:N,getOwnPropertyDescriptor:R,getOwnPropertyNames:O,getOwnPropertySymbols:z,getPrototypeOf:H}=Object,B=globalThis,$=B.trustedTypes,F=$?$.emptyScript:"",V=B.reactiveElementPolyfillSupport,W=(t,e)=>t,j={toAttribute(t,e){switch(e){case Boolean:t=t?F:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,e){let n=t;switch(e){case Boolean:n=null!==t;break;case Number:n=null===t?null:Number(t);break;case Object:case Array:try{n=JSON.parse(t)}catch(t){n=null}}return n}},q=(t,e)=>!E(t,e),U={attribute:!0,type:String,converter:j,reflect:!1,useDefault:!1,hasChanged:q}; /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */Symbol.metadata??=Symbol("metadata"),N.litPropertyMetadata??=new WeakMap;let V=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=F){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(t,n,e);void 0!==i&&I(this.prototype,t,i)}}static getPropertyDescriptor(t,e,n){const{get:i,set:r}=D(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:i,set(e){const o=i?.call(this);r?.call(this,e),this.requestUpdate(t,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??F}static _$Ei(){if(this.hasOwnProperty(H("elementProperties")))return;const t=E(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(H("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(H("properties"))){const t=this.properties,e=[...P(t),...L(t)];for(const n of e)this.createProperty(n,t[n])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,n]of e)this.elementProperties.set(t,n)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const n=this._$Eu(t,e);void 0!==n&&this._$Eh.set(n,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const n=new Set(t.flat(1/0).reverse());for(const t of n)e.unshift(T(t))}else void 0!==t&&e.push(T(t));return e}static _$Eu(t,e){const n=e.attribute;return!1===n?void 0:"string"==typeof n?n:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const n of e.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((t,e)=>{if(x)t.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const n of e){const e=document.createElement("style"),i=b.litNonce;void 0!==i&&e.setAttribute("nonce",i),e.textContent=n.cssText,t.appendChild(e)}})(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,n){this._$AK(t,n)}_$ET(t,e){const n=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,n);if(void 0!==i&&!0===n.reflect){const r=(void 0!==n.converter?.toAttribute?n.converter:B).toAttribute(e,n.type);this._$Em=t,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(t,e){const n=this.constructor,i=n._$Eh.get(t);if(void 0!==i&&this._$Em!==i){const t=n.getPropertyOptions(i),r="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:B;this._$Em=i;const o=r.fromAttribute(e,t.type);this[i]=o??this._$Ej?.get(i)??o,this._$Em=null}}requestUpdate(t,e,n,i=!1,r){if(void 0!==t){const o=this.constructor;if(!1===i&&(r=this[t]),n??=o.getPropertyOptions(t),!((n.hasChanged??$)(r,e)||n.useDefault&&n.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,n))))return;this.C(t,e,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:n,reflect:i,wrapped:r},o){n&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==r||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||n||(e=void 0),this._$AL.set(t,e)),!0===i&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,n]of t){const{wrapped:t}=n,i=this[e];!0!==t||this._$AL.has(e)||void 0===i||this.C(e,void 0,n,i)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};V.elementStyles=[],V.shadowRootOptions={mode:"open"},V[H("elementProperties")]=new Map,V[H("finalized")]=new Map,z?.({ReactiveElement:V}),(N.reactiveElementVersions??=[]).push("2.1.2"); + */Symbol.metadata??=Symbol("metadata"),B.litPropertyMetadata??=new WeakMap;let G=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=U){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const n=Symbol(),i=this.getPropertyDescriptor(t,n,e);void 0!==i&&N(this.prototype,t,i)}}static getPropertyDescriptor(t,e,n){const{get:i,set:r}=R(this.prototype,t)??{get(){return this[e]},set(t){this[e]=t}};return{get:i,set(e){const o=i?.call(this);r?.call(this,e),this.requestUpdate(t,o,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??U}static _$Ei(){if(this.hasOwnProperty(W("elementProperties")))return;const t=H(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(W("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(W("properties"))){const t=this.properties,e=[...O(t),...z(t)];for(const n of e)this.createProperty(n,t[n])}const t=this[Symbol.metadata];if(null!==t){const e=litPropertyMetadata.get(t);if(void 0!==e)for(const[t,n]of e)this.elementProperties.set(t,n)}this._$Eh=new Map;for(const[t,e]of this.elementProperties){const n=this._$Eu(t,e);void 0!==n&&this._$Eh.set(n,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const n=new Set(t.flat(1/0).reverse());for(const t of n)e.unshift(L(t))}else void 0!==t&&e.push(L(t));return e}static _$Eu(t,e){const n=e.attribute;return!1===n?void 0:"string"==typeof n?n:"string"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const n of e.keys())this.hasOwnProperty(n)&&(t.set(n,this[n]),delete this[n]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((t,e)=>{if(M)t.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const n of e){const e=document.createElement("style"),i=k.litNonce;void 0!==i&&e.setAttribute("nonce",i),e.textContent=n.cssText,t.appendChild(e)}})(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,n){this._$AK(t,n)}_$ET(t,e){const n=this.constructor.elementProperties.get(t),i=this.constructor._$Eu(t,n);if(void 0!==i&&!0===n.reflect){const r=(void 0!==n.converter?.toAttribute?n.converter:j).toAttribute(e,n.type);this._$Em=t,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(t,e){const n=this.constructor,i=n._$Eh.get(t);if(void 0!==i&&this._$Em!==i){const t=n.getPropertyOptions(i),r="function"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:j;this._$Em=i;const o=r.fromAttribute(e,t.type);this[i]=o??this._$Ej?.get(i)??o,this._$Em=null}}requestUpdate(t,e,n,i=!1,r){if(void 0!==t){const o=this.constructor;if(!1===i&&(r=this[t]),n??=o.getPropertyOptions(t),!((n.hasChanged??q)(r,e)||n.useDefault&&n.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,n))))return;this.C(t,e,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,e,{useDefault:n,reflect:i,wrapped:r},o){n&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,o??e??this[t]),!0!==r||void 0!==o)||(this._$AL.has(t)||(this.hasUpdated||n||(e=void 0),this._$AL.set(t,e)),!0===i&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,e]of this._$Ep)this[t]=e;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[e,n]of t){const{wrapped:t}=n,i=this[e];!0!==t||this._$AL.has(e)||void 0===i||this.C(e,void 0,n,i)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(e)):this._$EM()}catch(e){throw t=!1,this._$EM(),e}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}};G.elementStyles=[],G.shadowRootOptions={mode:"open"},G[W("elementProperties")]=new Map,G[W("finalized")]=new Map,V?.({ReactiveElement:G}),(B.reactiveElementVersions??=[]).push("2.1.2"); /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ -const W=globalThis,j=t=>t,q=W.trustedTypes,U=q?q.createPolicy("lit-html",{createHTML:t=>t}):void 0,G="$lit$",X=`lit$${Math.random().toFixed(9).slice(2)}$`,Y="?"+X,Z=`<${Y}>`,K=document,Q=()=>K.createComment(""),J=t=>null===t||"object"!=typeof t&&"function"!=typeof t,tt=Array.isArray,et="[ \t\n\f\r]",nt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,it=/-->/g,rt=/>/g,ot=RegExp(`>|${et}(?:([^\\s"'>=/]+)(${et}*=${et}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),at=/'/g,st=/"/g,lt=/^(?:script|style|textarea|title)$/i,ct=t=>(e,...n)=>({_$litType$:t,strings:e,values:n}),ut=ct(1),dt=ct(2),ht=Symbol.for("lit-noChange"),pt=Symbol.for("lit-nothing"),ft=new WeakMap,gt=K.createTreeWalker(K,129);function mt(t,e){if(!tt(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==U?U.createHTML(e):e}const vt=(t,e)=>{const n=t.length-1,i=[];let r,o=2===e?"":3===e?"":"",a=nt;for(let e=0;e"===l[0]?(a=r??nt,c=-1):void 0===l[1]?c=-2:(c=a.lastIndex-l[2].length,s=l[1],a=void 0===l[3]?ot:'"'===l[3]?st:at):a===st||a===at?a=ot:a===it||a===rt?a=nt:(a=ot,r=void 0);const d=a===ot&&t[e+1].startsWith("/>")?" ":"";o+=a===nt?n+Z:c>=0?(i.push(s),n.slice(0,c)+G+n.slice(c)+X+d):n+X+(-2===c?e:d)}return[mt(t,o+(t[n]||"")+(2===e?"":3===e?"":"")),i]};class yt{constructor({strings:t,_$litType$:e},n){let i;this.parts=[];let r=0,o=0;const a=t.length-1,s=this.parts,[l,c]=vt(t,e);if(this.el=yt.createElement(l,n),gt.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(i=gt.nextNode())&&s.length0){i.textContent=q?q.emptyScript:"";for(let n=0;ntt(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==pt&&J(this._$AH)?this._$AA.nextSibling.data=t:this.T(K.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:n}=t,i="number"==typeof n?this._$AC(t):(void 0===n.el&&(n.el=yt.createElement(mt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===i)this._$AH.p(e);else{const t=new bt(i,this),n=t.u(this.options);t.p(e),this.T(n),this._$AH=t}}_$AC(t){let e=ft.get(t.strings);return void 0===e&&ft.set(t.strings,e=new yt(t)),e}k(t){tt(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let n,i=0;for(const r of t)i===e.length?e.push(n=new xt(this.O(Q()),this.O(Q()),this,this.options)):n=e[i],n._$AI(r),i++;i2||""!==n[0]||""!==n[1]?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=pt}_$AI(t,e=this,n,i){const r=this.strings;let o=!1;if(void 0===r)t=_t(this,t,e,0),o=!J(t)||t!==this._$AH&&t!==ht,o&&(this._$AH=t);else{const i=t;let a,s;for(t=r[0],a=0;at,Z=X.trustedTypes,K=Z?Z.createPolicy("lit-html",{createHTML:t=>t}):void 0,Q="$lit$",J=`lit$${Math.random().toFixed(9).slice(2)}$`,tt="?"+J,et=`<${tt}>`,nt=document,it=()=>nt.createComment(""),rt=t=>null===t||"object"!=typeof t&&"function"!=typeof t,ot=Array.isArray,at="[ \t\n\f\r]",st=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,lt=/-->/g,ct=/>/g,ut=RegExp(`>|${at}(?:([^\\s"'>=/]+)(${at}*=${at}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),dt=/'/g,ht=/"/g,pt=/^(?:script|style|textarea|title)$/i,ft=t=>(e,...n)=>({_$litType$:t,strings:e,values:n}),gt=ft(1),mt=ft(2),vt=Symbol.for("lit-noChange"),yt=Symbol.for("lit-nothing"),_t=new WeakMap,bt=nt.createTreeWalker(nt,129);function xt(t,e){if(!ot(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==K?K.createHTML(e):e}const wt=(t,e)=>{const n=t.length-1,i=[];let r,o=2===e?"":3===e?"":"",a=st;for(let e=0;e"===l[0]?(a=r??st,c=-1):void 0===l[1]?c=-2:(c=a.lastIndex-l[2].length,s=l[1],a=void 0===l[3]?ut:'"'===l[3]?ht:dt):a===ht||a===dt?a=ut:a===lt||a===ct?a=st:(a=ut,r=void 0);const d=a===ut&&t[e+1].startsWith("/>")?" ":"";o+=a===st?n+et:c>=0?(i.push(s),n.slice(0,c)+Q+n.slice(c)+J+d):n+J+(-2===c?e:d)}return[xt(t,o+(t[n]||"")+(2===e?"":3===e?"":"")),i]};class St{constructor({strings:t,_$litType$:e},n){let i;this.parts=[];let r=0,o=0;const a=t.length-1,s=this.parts,[l,c]=wt(t,e);if(this.el=St.createElement(l,n),bt.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(i=bt.nextNode())&&s.length0){i.textContent=Z?Z.emptyScript:"";for(let n=0;not(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==yt&&rt(this._$AH)?this._$AA.nextSibling.data=t:this.T(nt.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:n}=t,i="number"==typeof n?this._$AC(t):(void 0===n.el&&(n.el=St.createElement(xt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===i)this._$AH.p(e);else{const t=new kt(i,this),n=t.u(this.options);t.p(e),this.T(n),this._$AH=t}}_$AC(t){let e=_t.get(t.strings);return void 0===e&&_t.set(t.strings,e=new St(t)),e}k(t){ot(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let n,i=0;for(const r of t)i===e.length?e.push(n=new Mt(this.O(it()),this.O(it()),this,this.options)):n=e[i],n._$AI(r),i++;i2||""!==n[0]||""!==n[1]?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=yt}_$AI(t,e=this,n,i){const r=this.strings;let o=!1;if(void 0===r)t=Ct(this,t,e,0),o=!rt(t)||t!==this._$AH&&t!==vt,o&&(this._$AH=t);else{const i=t;let a,s;for(t=r[0],a=0;a{const i=n?.renderBefore??e;let r=i._$litPart$;if(void 0===r){const t=n?.renderBefore??null;i._$litPart$=r=new xt(e.insertBefore(Q(),t),t,void 0,n??{})}return r._$AI(t),r})(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return ht}}It._$litElement$=!0,It.finalized=!0,At.litElementHydrateSupport?.({LitElement:It});const Dt=At.litElementPolyfillSupport;Dt?.({LitElement:It}),(At.litElementVersions??=[]).push("4.2.2"); + */class Nt extends G{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=((t,e,n)=>{const i=n?.renderBefore??e;let r=i._$litPart$;if(void 0===r){const t=n?.renderBefore??null;i._$litPart$=r=new Mt(e.insertBefore(it(),t),t,void 0,n??{})}return r._$AI(t),r})(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return vt}}Nt._$litElement$=!0,Nt.finalized=!0,Et.litElementHydrateSupport?.({LitElement:Nt});const Rt=Et.litElementPolyfillSupport;Rt?.({LitElement:Nt}),(Et.litElementVersions??=[]).push("4.2.2"); /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ -const Pt={attribute:!0,type:String,converter:B,reflect:!1,hasChanged:$},Lt=(t=Pt,e,n)=>{const{kind:i,metadata:r}=n;let o=globalThis.litPropertyMetadata.get(r);if(void 0===o&&globalThis.litPropertyMetadata.set(r,o=new Map),"setter"===i&&((t=Object.create(t)).wrapped=!0),o.set(n.name,t),"accessor"===i){const{name:i}=n;return{set(n){const r=e.get.call(this);e.set.call(this,n),this.requestUpdate(i,r,t,!0,n)},init(e){return void 0!==e&&this.C(i,void 0,t,e),e}}}if("setter"===i){const{name:i}=n;return function(n){const r=this[i];e.call(this,n),this.requestUpdate(i,r,t,!0,n)}}throw Error("Unsupported decorator location: "+i)}; +const Ot={attribute:!0,type:String,converter:j,reflect:!1,hasChanged:q},zt=(t=Ot,e,n)=>{const{kind:i,metadata:r}=n;let o=globalThis.litPropertyMetadata.get(r);if(void 0===o&&globalThis.litPropertyMetadata.set(r,o=new Map),"setter"===i&&((t=Object.create(t)).wrapped=!0),o.set(n.name,t),"accessor"===i){const{name:i}=n;return{set(n){const r=e.get.call(this);e.set.call(this,n),this.requestUpdate(i,r,t,!0,n)},init(e){return void 0!==e&&this.C(i,void 0,t,e),e}}}if("setter"===i){const{name:i}=n;return function(n){const r=this[i];e.call(this,n),this.requestUpdate(i,r,t,!0,n)}}throw Error("Unsupported decorator location: "+i)}; /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */function Et(t){return(e,n)=>"object"==typeof n?Lt(t,e,n):((t,e,n)=>{const i=e.hasOwnProperty(n);return e.constructor.createProperty(n,t),i?Object.getOwnPropertyDescriptor(e,n):void 0})(t,e,n)} + */function Ht(t){return(e,n)=>"object"==typeof n?zt(t,e,n):((t,e,n)=>{const i=e.hasOwnProperty(n);return e.constructor.createProperty(n,t),i?Object.getOwnPropertyDescriptor(e,n):void 0})(t,e,n)} /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause - */function Nt(t){return Et({...t,state:!0,attribute:!1})}const Rt={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ot(t){return String(t).replace(/[&<>"']/g,t=>Rt[t]??t)}const zt="span_panel_list_columns";function Ht(){try{const t=localStorage.getItem(zt);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function Bt(t){try{localStorage.setItem(zt,String(t))}catch{}}function $t(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}const Ft=p.power,Vt=p.current,Wt="--",jt=`${Wt}`;function qt(t){return Ft.unit(t)}function Ut(t){return(t<0?"-":"")+Ft.format(t)}function Gt(t){return null===t?jt:`${Ut(t)} ${qt(t)}`}function Xt(t){return null===t?jt:`${Ut(t)}${qt(t)}`}function Yt(t){return null===t?jt:`${Vt.format(t)}A`}function Zt(t,e,n={}){const r=Ot(t.device_name||i("header.default_name")),o=Ot(t.serial||""),a=Ot(t.firmware||""),s="current"===(e.chart_metric||"power"),l=!1!==n.showSwitches;return`\n
\n
\n
\n

${r}

\n ${o}\n \n ${l?`
\n ${Ot(i("header.enable_switches"))}\n
\n \n
\n
`:""}\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 ${Wt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${o?`\n
\n ${i("header.grid")}\n
\n ${Wt}\n
\n
`:""}\n ${a?`\n
\n ${i("header.upstream")}\n
\n ${Wt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${s?`\n
\n ${i("header.downstream")}\n
\n ${Wt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${l?`\n
\n ${i("header.solar")}\n
\n ${Wt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${c?`\n
\n ${i("header.battery")}\n
\n ${Wt}\n %\n
\n
`:""}\n
\n `}(t,e)}\n
\n
\n
\n ${a}\n
\n \n \n
\n
\n
\n ${Object.entries(g).filter(([t])=>"unknown"!==t).map(([,t])=>{const e=Ot(t.icon),n=Ot(t.color),i=Ot(t.label());let r;return r=t.icon2?``:t.textLabel?`${Ot(t.textLabel)}`:``,`
${r}${i}
`}).join("")}\n
\n
\n
\n `}function Kt(t){return"number"==typeof t&&Number.isInteger(t)&&t>0}function Qt(t){return!0===t.outside_panel}function Jt(t,e){if(!t)return null;let n=null,i=null;const{first_position:r,last_position:o}=t;Kt(r)&&Kt(o)&&r<=o?(n=r,i=o):Kt(e)&&(n=1,i=e);for(const e of Object.values(t.circuits))if(e&&!Qt(e))for(const t of e.tabs??[])Kt(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 te(t){return ee(t.last)-ee(t.first)+1}function ee(t){return Math.ceil(t/2)}function ne(t){return t%2==0?1:0}function ie(t){if(2!==t.length)return null;const[e,n]=[Math.min(...t),Math.max(...t)];return ee(e)===ee(n)?"row-span":ne(e)===ne(n)?"col-span":"row-span"}function re(t){const e=t.chart_metric??o;return p[e]??p[o]}function oe(t,e){const n=function(t){return re(t).entityRole}(e);return t.entities?.[n]??t.entities?.power??null}function ae(t){return t.members.map((e,n)=>({uuid:t.memberIds[n],circuit:e}))}function se(t){return new Map(t.flatMap(t=>t.memberIds.map(e=>[e,t])))}function le(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 ce(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:ue(o),breaker_rating_a:s?s.breaker_rating_a:he(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 ue(t){return[...new Set(t.flatMap(t=>t.tabs))].sort((t,e)=>t-e)}function de(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 he(t){let e=0;for(const n of t){if(!n.breaker_rating_a)return null;e+=n.breaker_rating_a}return e}function pe(t){if(1===t.length){const e=t[0].breaker_rating_a;return e?`${e}A`:""}return de(t)}function fe(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:String(t)}const ge="Validation error: ",me={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 ve(t,e){return"object"==typeof t&&null!==t?me[e](t):void 0}async function ye(t,e,n,i){const r=ve(e,"translation_key");if(t&&"string"==typeof r&&ve(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=ve(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=fe(e),a=o.startsWith(ge)?o.slice(18):o;return a&&"[object Object]"!==a?a:i}function _e(t){return new Promise(e=>setTimeout(e,t))}class be{constructor(t){this._store=t}async callWS(t,e,n){const i=n?.retries??3,r=n?.errorId??`ws:${String(e.type??"unknown")}`;return this._withRetry(()=>t.callWS(e),i,r,n?.errorMessage)}async callService(t,e,n,i,r,o){const a=o?.retries??3,s=o?.errorId??`svc:${e}.${n}`;return this._withRetry(()=>t.callService(e,n,i,r),a,s,o?.errorMessage)}async _withRetry(t,e,n,r){if(this._store.hasAnyPanelOffline())try{const e=await t();return this._store.remove(n),e}catch(t){const e=t instanceof Error?t:new Error(fe(t));throw this._store.add({key:n,level:"error",message:r??i("error.panel_offline"),persistent:!1}),e}let o;for(let i=0;i<=e;i++)try{const e=await t();return this._store.remove(n),e}catch(t){if(o=t instanceof Error?t:new Error(fe(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=xe(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 Se{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 we,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 Ce(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 Me(t,e){const{continuousPct:n,spikePct:i}=ke(e);return t>=i?"alert":t>=n?"warning":"normal"}function Te(t,e){return`utilization-${Me(t,e)}`}function Ae(t){return(void 0===t.monitoring_rating_a?t.breaker_rating_a:t.monitoring_rating_a)??null}function Ie(t){return null!=t&&!1!==t.monitoring_enabled}function De(t,e){return Ie(e)?Ae(t):t.breaker_rating_a??null}const Pe=["continuous_threshold_pct","spike_threshold_pct"];function Le(t,e){return Ie(e)?function(t,e){return"averaged_legs"===t?.package_ratings_state&&Ie(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)&&Pe.some(t=>(e[t]??0)>100)?!0===e.has_override?"own":"global":null}(t,e):null}function Ee(t){return t.packageRatings?.length&&t.panelAmps?r("monitoringRating.copied",{package:t.packageRatings.join("-"),panel:String(t.panelAmps)}):i("monitoringRating.copied_unnamed")}function Ne(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 Re(t,e){return Qt(t)||qe(t,e)}function Oe(t,e){const n=t.entities?.power;return $t(n?e.states[n]:void 0)}function ze(t,e){const n=t.entities?.current;return $t(n?e.states[n]:void 0)}function He(t){return t.is_generation??"pv"===t.device_type}function Be(t,e){return He(t)||null!==e&&e<0}function $e(t,e,n){const i=ze(t,e);if(t.entities?.current&&null===i)return null;const r=n?.utilization_pct??null,o=De(t,n);return null===r&&null!==i&&o?Math.round(Math.abs(i)/o*1e3)/10:r}const Fe=new Set(m),Ve={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function We(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function je(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 qe(t,e){const n=We(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(je(t,e,"relay_state")??t.relay_state)}function Ue(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=We(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function Ge(t){return void 0===t?void 0:Ve[t]}function Xe(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function Ye(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=Xe(t,e);return void 0!==n&&Fe.has(n)?n:Ge(je(t,e,"shed_priority"))??Ge(t.priority)??"unknown"}function Ze(t,e,n=!1){if("none"===e)return"";const r=["toggle-pill",t?"toggle-on":"toggle-off"];"inert"===e&&r.push("toggle-unavailable"),n&&r.push("toggle-shared");const o=n?` title="${Ot(i("grid.shared_switch"))}"`:"";return`
\n ${i(t?"grid.on":"grid.off")}\n \n
`}function Ke(t,e,n){const r=t.querySelector(".toggle-pill");if(!r)return;r.classList.toggle("toggle-on",e),r.classList.toggle("toggle-off",!e),r.classList.toggle("toggle-unavailable","operable"!==n);const o=r.querySelector(".toggle-label");o&&(o.textContent=i(e?"grid.on":"grid.off"))}function Qe(t){return"unknown"===t?void 0:g[t]}const Je="display:none;";function tn(t){const e=Qe(t),n=e?Ot(e.color):"",i=e?` title="${Ot(e.label())}"`:"",r=e?Ot(e.icon):"",o=e?.icon2?Ot(e.icon2):"",a=e?.textLabel?Ot(e.textLabel):"";return`\n \n \n ${a}\n `}function en(t,e){const n=t.querySelector(".shedding-composite");if(!n)return;const i=Qe(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 nn(t,e,n,r,o,a,s,l,c,u=[e],d=!1){const h=Oe(e,a),p=Be(e,h),f=qe(e,a),g=Ue(e,a),m=u.length>1,v=de(u),y=Ot(u.map(t=>t.name||i("grid.unknown")).join(" · ")),_="current"===re(s).entityRole?Yt(ze(e,a)):Xt(h),b=tn(c||"unknown"),x=``;let w="";const S=$e(e,a,l);null!==S&&(w=`${Math.round(S)}%`);return`\n
\n
\n
\n ${v?`${v}`:""}\n ${w}\n ${y}\n
\n
\n \n ${_}\n \n ${Ze(f,g,m&&function(t){const e=t[0]?.shared_relay_group;return!!e&&t.every(t=>t.shared_relay_group===e)}(u))}\n
\n
\n
\n ${b}\n ${x}\n
\n
\n
\n `}function rn(t,e){return`\n
\n —\n
\n `}function on(t){return"function"==typeof globalThis.CSS?.escape?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function an(t){return Object.entries(t.circuits).filter(([,t])=>Qt(t))}function sn(t,e){return!1!==e.show_panel&&an(t).length>0}function ln(t,e,n){return`${Ot(function(t){const e=$t(t);if(null===e)return Wt;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))} ${Ot(n)}`}function cn(t,e,n){const r=Oe(t,e),o=null===r||0===r?"":i(r>0?"meters.importing":"meters.exporting");return`\n ${"current"===re(n).entityRole?Yt(ze(t,e)):Xt(r)}\n ${Ot(o)}\n ${ln(e,t.entities?.consumed_energy,i("meters.imported"))}\n ${ln(e,t.entities?.produced_energy,i("meters.exported"))}\n `}const un={names:["power","battery power"],suffixes:["_power"]},dn={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},hn={names:["state of energy"],suffixes:["_soe_kwh"]};function pn(t,e){if(!t.entities)return null;for(const[n,i]of Object.entries(t.entities)){if("sensor"!==i.domain)continue;const t=(i.original_name??"").toLowerCase();if(e.names.some(e=>t===e))return n;if(i.unique_id&&e.suffixes.some(t=>i.unique_id.endsWith(t)))return n}return null}function fn(t){return pn(t,dn)}function gn(t){return pn(t,hn)}function mn(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,pn(n,un)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function vn(t){const{headlineEid:e,siteTotalEid:n}=mn(t),i=[e,n];return t.type===c&&i.push(fn(t),gn(t)),new Set(i.filter(t=>null!==t))}function yn(t){const e=[{role:"power",entityId:mn(t).headlineEid}];return t.type===c&&e.push({role:"soc",entityId:fn(t)},{role:"soe",entityId:gn(t)}),e.filter(t=>null!==t.entityId)}function _n(t,e){return $t(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 xn(t,e){return yn(t).length>0||e&&null!==bn(t.entities)}function wn(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}function Sn(t){return(t.identifiers??[]).some(t=>t[0]===l)&&!t.via_device_id&&!t.parent_device_id}function Cn(t){return(t.name_by_user||t.name||"").trim()}function kn(t){return(t.name??t.original_name??"").trim()}function Mn(t){return t.type===d?"inverter"===t.solar?.role?i("subdevice.solar_inverter"):i("subdevice.solar"):t.type===u?i("subdevice.ev_charger"):t.type===c?i("subdevice.battery"):i("subdevice.fallback")}function Tn(t,e,n){let r="";const o="role"===t.identity?"":[t.vendor,t.model].filter(t=>!!t).join(" · ");if(o&&(r+=`
${Ot(o)}
`),e.siteTotalEid){const t=_n(n,e.siteTotalEid);r+=`\n
\n ${Ot(i("subdevice.site_total"))}:\n ${Gt(t)}\n
`}return"inverter"!==t.role||e.headlineEid||(r+=`
${Ot(i("subdevice.in_site_total"))}
`),r}function An(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&&Cn(r)||e}function In(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||An(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=$t(s);null!==t&&(u=(t/1e3).toFixed(1)+" kWh")}o+=`\n
\n ${Ot(l)}:\n ${Ot(u)}\n
\n `}return o}function Dn(t,e,n,r,o,a){if(n){const e=[{key:`${h}${t}_soc`,title:i("subdevice.soc"),available:!!o},{key:`${h}${t}_soe`,title:i("subdevice.soe"),available:!!a},{key:`${h}${t}_power`,title:i("subdevice.power"),available:!!r}].filter(t=>t.available);return`\n
\n ${e.map(t=>`\n
\n
${Ot(t.title)}
\n
\n
\n `).join("")}\n
\n `}return r?`
`:""}function Pn(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 Ln(t){const e=s[t];return e?e.ms:s[a].ms}function En(t){const e=t/1e3;return e<=600?Math.ceil(e):Math.min(5e3,Math.ceil(e/5))}function Nn(t){return Math.max(500,Math.floor(t/5e3))}function Rn(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 On(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 zn(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 Hn(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 Bn(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=En(i),l=Nn(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,On(n,s,l))}}}function $n(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 yn(i))e.push({entityId:r,key:`${h}${n}_${t}`,devId:n});return e}async function Fn(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)?Ln(r.get(t)):Pn(n),zn(a,o,e,t)}for(const{entityId:t,key:i,devId:r}of $n(e)){let e;e=o&&o.has(r)?Ln(o.get(r)):Pn(n),zn(a,e,t,i)}const s=[];for(const[e,n]of a){if(0===n.entityIds.length)continue;e>2592e5?s.push(Hn(t,n.entityIds,n.keysByEntity,e,i)):s.push(Bn(t,n.entityIds,n.keysByEntity,e,i))}await Promise.all(s)}var Vn=function(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1},Wn=new function(){this.browser=new Vn,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?(Wn.wxa=!0,Wn.touchEventsSupported=!0):"undefined"==typeof document&&"undefined"!=typeof self?Wn.worker=!0:!Wn.hasGlobalWindow||"Deno"in window||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Node.js")>-1?(Wn.node=!0,Wn.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,Wn);var jn="sans-serif",qn="12px "+jn;var Un,Gn,Xn=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(){vi(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?mr(s,a):mr(a,s))}(a,o,r);if(s)return s(t,n,i),!0}return!1}function br(t){return"CANVAS"===t.nodeName.toUpperCase()}var xr=/([&<>"'])/g,wr={"&":"&","<":"<",">":">",'"':""","'":"'"};function Sr(t){return null==t?"":(t+"").replace(xr,function(t,e){return wr[e]})}var Cr=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,kr=[],Mr=Wn.browser.firefox&&+Wn.browser.version.split(".")[0]<39;function Tr(t,e,n,i){return n=n||{},i?Ar(t,e,n):Mr&&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):Ar(t,e,n),n}function Ar(t,e,n){if(Wn.domSupported&&t.getBoundingClientRect){var i=e.clientX,r=e.clientY;if(br(t)){var o=t.getBoundingClientRect();return n.zrX=i-o.left,void(n.zrY=r-o.top)}if(_r(kr,t,i,r))return n.zrX=kr[0],void(n.zrY=kr[1])}n.zrX=n.zrY=0}function Ir(t){return t||window.event}function Dr(t,e,n){if(null!=(e=Ir(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&&Tr(t,r,e,n)}else{Tr(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&&Cr.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function Pr(t,e,n,i){t.removeEventListener(e,n,i)}var Lr=function(t){t.preventDefault(),t.stopPropagation(),t.cancelBubble=!0},Er=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=Nr(r)/Nr(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 Or(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function zr(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 Hr(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 Br(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 $r(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 Fr(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 Vr=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}(),Wr=Math.min,jr=Math.max,qr=Math.abs,Ur=["x","y"],Gr=["width","height"],Xr=new Vr,Yr=new Vr,Zr=new Vr,Kr=new Vr,Qr=ao(),Jr=Qr.minTv,to=Qr.maxTv,eo=[0,0],no=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=Wr(t.x,this.x),n=Wr(t.y,this.y);isFinite(this.x)&&isFinite(this.width)?this.width=jr(t.x+t.width,this.x+this.width)-e:this.width=t.width,isFinite(this.y)&&isFinite(this.height)?this.height=jr(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 Br(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]),Br(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&&Vr.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(io,e.x,e.y,e.width,e.height)),n instanceof t||(n=t.set(ro,n.x,n.y,n.width,n.height));var s=!!i;Qr.reset(r,s);var l=Qr.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))}Xr.x=Zr.x=n.x,Xr.y=Kr.y=n.y,Yr.x=Kr.x=n.x+n.width,Yr.y=Zr.y=n.y+n.height,Xr.transform(i),Kr.transform(i),Yr.transform(i),Zr.transform(i),e.x=Wr(Xr.x,Yr.x,Zr.x,Kr.x),e.y=Wr(Xr.y,Yr.y,Zr.y,Kr.y);var l=jr(Xr.x,Yr.x,Zr.x,Kr.x),c=jr(Xr.y,Yr.y,Zr.y,Kr.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),io=new no(0,0,0,0),ro=new no(0,0,0,0);function oo(t,e,n,i,r,o,a,s){var l=qr(e-n),c=qr(i-t),u=Wr(l,c),d=Ur[r],h=Ur[1-r],p=Gr[r];e=c||!Qr.bidirectional)&&(Jr[d]=-c,Jr[h]=0,Qr.useDir&&Qr.calcDirMTV())))}function ao(){var t=0,e=new Vr,n=new Vr,i={minTv:new Vr,maxTv:new Vr,useDir:!1,dirMinTv:new Vr,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(r,o){i.touchThreshold=0,r&&null!=r.touchThreshold&&(i.touchThreshold=jr(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||(po.copy(u.getBoundingRect()),u.transform&&po.applyTransform(u.transform),po.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!==so)){e.target=a;break}}}function vo(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}vi(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){fo.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=vo(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||ar(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function yo(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 _o(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 bo(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 wo(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=bo(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-bo(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=yo(t,n,i,e))s&&(l=s),_o(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 Co=!1;function ko(){Co||(Co=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function Mo(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var To,Ao=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=Mo}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}();To=Wn.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){return setTimeout(t,16)};var Io={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-Io.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*Io.bounceIn(2*t):.5*Io.bounceOut(2*t-1)+.5}},Do=Math.pow,Po=Math.sqrt,Lo=1e-8,Eo=1e-4,No=Po(3),Ro=1/3,Oo=Ji(),zo=Ji(),Ho=Ji();function Bo(t){return t>-1e-8&&tLo||t<-1e-8}function Fo(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 Vo(t,e,n,i,r){var o=1-r;return 3*(((e-t)*o+2*(n-e)*r)*o+(i-n)*r*r)}function Wo(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(Bo(u)&&Bo(d)){if(Bo(s))o[0]=0;else(C=-l/s)>=0&&C<=1&&(o[p++]=C)}else{var f=d*d-4*u*h;if(Bo(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=Po(f),y=u*s+1.5*a*(-d+v),_=u*s+1.5*a*(-d-v);(C=(-s-((y=y<0?-Do(-y,Ro):Do(y,Ro))+(_=_<0?-Do(-_,Ro):Do(_,Ro))))/(3*a))>=0&&C<=1&&(o[p++]=C)}else{var b=(2*u*s-3*a*d)/(2*Po(u*u*u)),x=Math.acos(b)/3,w=Po(u),S=Math.cos(x),C=(-s-2*w*S)/(3*a),k=(m=(-s+w*(S+No*Math.sin(x)))/(3*a),(-s+w*(S-No*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 jo(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(Bo(a)){if($o(o))(u=-s/o)>=0&&u<=1&&(r[l++]=u)}else{var c=o*o-4*a*s;if(Bo(c))r[0]=-o/(2*a);else if(c>0){var u,d=Po(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 qo(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 Uo(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=Fo(t,n,r,a,f),m=Fo(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 Go(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function Xo(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function Yo(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function Zo(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 Ko(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=Go(t,n,r,h),f=Go(e,i,o,h),g=p-s,m=f-l;c+=Math.sqrt(g*g+m*m),s=p,l=f}return c}var Qo=/cubic-bezier\(([0-9,\.e ]+)\)/;function Jo(t){var e=t&&Qo.exec(t);if(e){var n=e[1].split(","),i=+Fi(n[0]),r=+Fi(n[1]),o=+Fi(n[2]),a=+Fi(n[3]);if(isNaN(i+r+o+a))return;var s=[];return function(t){return t<=0?0:t>=1?1:Wo(0,i,o,1,t,s)&&Fo(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||Ki,this.ondestroy=t.ondestroy||Ki,this.onrestart=t.onrestart||Ki,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=ki(t)?t:Io[t]||Jo(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}(),ia=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}(),ra={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 oa(t){return(t=Math.round(t))<0?0:t>255?255:t}function aa(t){return t<0?0:t>1?1:t}function sa(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?oa(parseFloat(e)/100*255):oa(parseInt(e,10))}function la(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?aa(parseFloat(e)/100):aa(parseFloat(e))}function ca(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 ua(t,e,n){return t+(e-t)*n}function da(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function ha(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}var pa=new ia(20),fa=null;function ga(t,e){fa&&ha(fa,e),fa=pa.put(t,fa||e.slice())}function ma(t,e){if(t){e=e||[];var n=pa.get(t);if(n)return ha(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in ra)return ha(e,ra[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?(da(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 da(e,0,0,0,1):7===o||9===o?(r=parseInt(i.slice(1,7),16))>=0&&r<=16777215?(da(e,(16711680&r)>>16,(65280&r)>>8,255&r,9===o?parseInt(i.slice(7),16)/255:1),ga(t,e),e):void da(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?da(e,+c[0],+c[1],+c[2],1):da(e,0,0,0,1);u=la(c.pop());case"rgb":return c.length>=3?(da(e,sa(c[0]),sa(c[1]),sa(c[2]),3===c.length?u:la(c[3])),ga(t,e),e):void da(e,0,0,0,1);case"hsla":return 4!==c.length?void da(e,0,0,0,1):(c[3]=la(c[3]),va(c,e),ga(t,e),e);case"hsl":return 3!==c.length?void da(e,0,0,0,1):(va(c,e),ga(t,e),e);default:return}}da(e,0,0,0,1)}}function va(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=la(t[1]),r=la(t[2]),o=r<=.5?r*(i+1):r+i-r*i,a=2*r-o;return da(e=e||[],oa(255*ca(a,o,n+1/3)),oa(255*ca(a,o,n)),oa(255*ca(a,o,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function ya(t,e){var n=ma(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 ba(n,4===n.length?"rgba":"rgb")}}function _a(t,e,n,i){var r=ma(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]=la(ki(n)?n(r[1]):n)),null!=i&&(r[2]=la(ki(i)?i(r[2]):i)),ba(va(r),"rgba")}function ba(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=ma(t);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*e:0}var wa=new ia(100);function Sa(t){if(Mi(t)){var e=wa.get(t);return e||(e=ya(t,-.1),wa.put(t,e)),e}if(Ei(t)){var n=hi({},t);return n.colorStops=yi(t.colorStops,function(t){return{offset:t.offset,color:ya(t.color,-.1)}}),n}return t}var Ca=Math.round;function ka(t){var e;if(t&&"transparent"!==t){if("string"==typeof t&&t.indexOf("rgba")>-1){var n=ma(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 Ma=1e-4;function Ta(t){return t-1e-4}function Aa(t){return Ca(1e3*t)/1e3}function Ia(t){return Ca(1e4*t)/1e4}var Da={left:"start",right:"end",center:"middle",middle:"middle"};function Pa(t){return t&&!!t.image}function La(t){return Pa(t)||function(t){return t&&!!t.svgElement}(t)}function Ea(t){return"linear"===t.type}function Na(t){return"radial"===t.type}function Ra(t){return t&&("linear"===t.type||"radial"===t.type)}function Oa(t){return"url(#"+t+")"}function za(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 Ha(t){var e=t.x||0,n=t.y||0,i=(t.rotation||0)*Qi,r=Oi(t.scaleX,1),o=Oi(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("+Ca(a*Qi)+"deg, "+Ca(s*Qi)+"deg)"),l.join(" ")}var Ba=Wn.hasGlobalWindow&&ki(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},$a=Array.prototype.slice;function Fa(t,e,n){return(e-t)*n+t}function Va(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(mi(e)){var l=function(t){return mi(t&&t[0])?2:1}(e);a=l,(1===l&&!Ai(e[0])||2===l&&!Ai(e[0][0]))&&(o=!0)}else if(Ai(e)&&!Ni(e))a=0;else if(Mi(e))if(isNaN(+e)){var c=ma(e);c&&(s=c,a=3)}else a=0;else if(Ei(e)){var u=hi({},s);u.colorStops=yi(e.colorStops,function(t){return{offset:t.offset,color:ma(t.color)}}),Ea(e)?a=4:Na(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=ki(n)?n:Io[n]||Jo(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=Za(i),l=Ya(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?Ka:t[u];if(!Za(s)&&!d||m||(m=this._additiveValue=[]),this.discrete)t[u]=g<1?i.rawValue:r.rawValue;else if(Za(s))1===s?Va(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,Ga(l),i),this._trackKeys.push(a)}s.addKeyframe(t,Ga(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 es,ns,is=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 y(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,To(function e(){t._running&&(To(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 Ja(t,e.loop);return this.addAnimator(n),n},e}(pr),rs=Wn.domSupported,os=(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:yi(es,function(t){var e=t.replace("mouse","pointer");return ns.hasOwnProperty(e)?e:t})}),as=["mousemove","mouseup"],ss=["pointermove","pointerup"],ls=!1;function cs(t){var e=t.pointerType;return"pen"===e||"touch"===e}function us(t){t&&(t.zrByTouch=!0)}function ds(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 hs=function(t,e){this.stopPropagation=Ki,this.stopImmediatePropagation=Ki,this.preventDefault=Ki,this.type=e.type,this.target=this.currentTarget=t.dom,this.pointerType=e.pointerType,this.clientX=e.clientX,this.clientY=e.clientY},ps={mousedown:function(t){t=Dr(this.dom,t),this.__mayPointerCapture=[t.zrX,t.zrY],this.trigger("mousedown",t)},mousemove:function(t){t=Dr(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=Dr(this.dom,t),this.__togglePointerCapture(!1),this.trigger("mouseup",t)},mouseout:function(t){ds(this,(t=Dr(this.dom,t)).toElement||t.relatedTarget)||(this.__pointerCapturing&&(t.zrEventControl="no_globalout"),this.trigger("mouseout",t))},wheel:function(t){ls=!0,t=Dr(this.dom,t),this.trigger("mousewheel",t)},mousewheel:function(t){ls||(t=Dr(this.dom,t),this.trigger("mousewheel",t))},touchstart:function(t){us(t=Dr(this.dom,t)),this.__lastTouchMoment=new Date,this.handler.processGesture(t,"start"),ps.mousemove.call(this,t),ps.mousedown.call(this,t)},touchmove:function(t){us(t=Dr(this.dom,t)),this.handler.processGesture(t,"change"),ps.mousemove.call(this,t)},touchend:function(t){us(t=Dr(this.dom,t)),this.handler.processGesture(t,"end"),ps.mouseup.call(this,t),+new Date-+this.__lastTouchMoment<300&&ps.click.call(this,t)},pointerdown:function(t){ps.mousedown.call(this,t)},pointermove:function(t){cs(t)||ps.mousemove.call(this,t)},pointerup:function(t){ps.mouseup.call(this,t)},pointerout:function(t){cs(t)||ps.mouseout.call(this,t)}};vi(["click","dblclick","contextmenu"],function(t){ps[t]=function(e){e=Dr(this.dom,e),this.trigger(t,e)}});var fs={pointermove:function(t){cs(t)||fs.mousemove.call(this,t)},pointerup:function(t){fs.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;Wn.pointerEventsSupported?vi(os.pointer,function(i){vs(e,i,function(e){n[i].call(t,e)})}):(Wn.touchEventsSupported&&vi(os.touch,function(i){vs(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)})}),vi(os.mouse,function(i){vs(e,i,function(r){r=Ir(r),e.touching||n[i].call(t,r)})}))}function ms(t,e){function n(n){vs(e,n,function(i){i=Ir(i),ds(t,i.target)||(i=function(t,e){return Dr(t.dom,new hs(t,e),!0)}(t,i),e.domHandlers[n].call(t,i))},{capture:!0})}Wn.pointerEventsSupported?vi(ss,n):Wn.touchEventsSupported||vi(as,n)}function vs(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 ys(t){var e=t.mounted;for(var n in e)e.hasOwnProperty(n)&&Pr(t.domTarget,n,e[n],t.listenerOpts[n]);t.mounted={}}var _s=function(t,e){this.mounted={},this.listenerOpts={},this.touching=!1,this.domTarget=t,this.domHandlers=e},bs=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 _s(e,ps),rs&&(i._globalHandlerScope=new _s(document,fs)),gs(i,i._localHandlerScope),i}return y(e,t),e.prototype.dispose=function(){ys(this._localHandlerScope),rs&&ys(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,rs&&+this.__pointerCapturing^+t){this.__pointerCapturing=t;var e=this._globalHandlerScope;t?ms(this,e):ys(e)}},e}(pr),xs=1;Wn.hasGlobalWindow&&(xs=Math.max(window.devicePixelRatio||window.screen&&window.screen.deviceXDPI/window.screen.logicalXDPI||1,1));var ws=xs,Ss="#333",Cs="#ccc",ks=Or,Ms=5e-5;function Ts(t){return t>Ms||t<-5e-5}var As,Is=[],Ds=[],Ps=[1,0,0,1,0,0],Ls=Math.abs,Es=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 Ts(this.rotation)||Ts(this.x)||Ts(this.y)||Ts(this.scaleX-1)||Ts(this.scaleY-1)||Ts(this.skewX)||Ts(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):ks(n),t&&(e?Hr(n,t,n):zr(n,t)),this.transform=n,this._resolveGlobalScaleRatio(n)):n&&(ks(n),this.invTransform=null)},t.prototype._resolveGlobalScaleRatio=function(t){var e=this.globalScaleRatio;if(null!=e&&1!==e){this.getGlobalScale(Is);var n=Is[0]<0?-1:1,i=Is[1]<0?-1:1,r=((Is[0]-n)*e+n)/Is[0]||0,o=((Is[1]-i)*e+i)/Is[1]||0;t[0]*=r,t[1]*=r,t[2]*=o,t[3]*=o}this.invTransform=this.invTransform||[1,0,0,1,0,0],Fr(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],Hr(Ds,t.invTransform,e),e=Ds);var n=this.originX,i=this.originY;(n||i)&&(Ps[4]=n,Ps[5]=i,Hr(Ds,e,Ps),Ds[4]-=n,Ds[5]-=i,e=Ds),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&&lr(n,n,i),n},t.prototype.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&lr(n,n,i),n},t.prototype.getLineScale=function(){var t=this.transform;return t&&Ls(t[0]-1)>1e-10&&Ls(t[3]-1)>1e-10?Math.sqrt(Ls(t[0]*t[3]-t[2]*t[1])):1},t.prototype.copyTransform=function(t){Rs(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&&$r(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}(),Ns=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function Rs(t,e){for(var n=0;n=Hs)){t=t||qn;for(var e=[],n=+new Date,i=0;i<=127;i++)e[i]=Yn.measureText(String.fromCharCode(i),t).width;var r=+new Date-n;return r>16?zs=Hs:r>2&&zs++,e}}(t.font),t.asciiWidthMapTried=!0),0<=e&&e<=127?null!=t.asciiWidthMap?t.asciiWidthMap[e]:t.asciiCharWidth:t.stWideCharWidth}function $s(t,e){var n=t.strWidthCache,i=n.get(e);return null==i&&(i=Yn.measureText(e,t.font).width,n.put(e,i)),i}function Fs(t,e,n,i){var r=$s(Os(e),t),o=qs(e),a=Ws(0,r,n),s=js(0,o,i);return new no(a,s,r,o)}function Vs(t,e,n,i){var r=((t||"")+"").split("\n");if(1===r.length)return Fs(r[0],e,n,i);for(var o=new no(0,0,0,0),a=0;a=0?parseFloat(t)/100*e:parseFloat(t):t}function Gs(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+=Us(i[0],n.width),c+=Us(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 Xs="__zr_normal__",Ys=Ns.concat(["ignore"]),Zs=_i(Ns,function(t,e){return t[e]=!0,t},{ignore:!1}),Ks={},Qs=new no(0,0,0,0),Js=[],tl=function(){function t(t){this.id=li(),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=Qs,n.layoutRect?d.copy(n.layoutRect):d.copy(this.getBoundingRect()),i||d.applyTransform(this.transform)),c){this.calculateTextPosition?this.calculateTextPosition(Ks,n,d):Gs(Ks,n,d),r.x=Ks.x,r.y=Ks.y,o=Ks.align,a=Ks.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=Us(h[0],d.width),f=Us(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 no(0,0,0,0);r.getLocalTransform(Js),Fr(Js,Js),no.copy(v,d),v.applyTransform(Js)}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()?Cs:Ss},t.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),n="string"==typeof e&&ma(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,ba(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||{},hi(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(Ii(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(Xs,!1,t)},t.prototype.useState=function(t,e,n,i){var r=t===Xs;if(this.hasState()||!r){var o=this.currentStates,a=this.stateTransition;if(!(fi(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}ci("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=fi(i,t),o=fi(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]]=Ga(n[v]),il(n,i,v)}}(w=new Ja(n,!1,!1,d?bi(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(tl,pr),gi(tl,Es);var ol=function(t){function e(e){var n=t.call(this)||this;return n.isGroup=!0,n._children=[],n.attr(e),n}return y(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=fi(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=fi(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 Ft(t){return String(t).replace(/[&<>"']/g,t=>$t[t]??t)}const Vt="span_panel_list_columns";function Wt(){try{const t=localStorage.getItem(Vt);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function jt(t){try{localStorage.setItem(Vt,String(t))}catch{}}function qt(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}const Ut=y.power,Gt=y.current,Xt="--",Yt=`${Xt}`;function Zt(t){return Ut.unit(t)}function Kt(t){return(t<0?"-":"")+Ut.format(t)}function Qt(t){return null===t?Yt:`${Kt(t)} ${Zt(t)}`}function Jt(t){return null===t?Yt:`${Kt(t)}${Zt(t)}`}function te(t){return null===t?Yt:`${Gt.format(t)}A`}function ee(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:String(t)}const ne=new Set(["Unauthorized","UnknownUser"]);function ie(t){if("object"!=typeof t||null===t)return!1;const e="code"in t?t.code:void 0;return"unauthorized"===e||"home_assistant_error"===e&&"message"in t&&ne.has(t.message)}const re="Validation error: ",oe={translation_domain:t=>"translation_domain"in t?t.translation_domain:void 0,translation_key:t=>"translation_key"in t?t.translation_key:void 0,translation_placeholders:t=>"translation_placeholders"in t?t.translation_placeholders:void 0};function ae(t,e){return"object"==typeof t&&null!==t?oe[e](t):void 0}async function se(t,e,n,i){const r=ae(e,"translation_key");if(t&&"string"==typeof r&&ae(e,"translation_domain")===n){const i=`component.${n}.exceptions.${r}.message`;try{const r=t.loadBackendTranslation?await t.loadBackendTranslation("exceptions",n):t.localize,o=r?.(i,function(t){const e=ae(t,"translation_placeholders");if("object"!=typeof e||null===e)return{};const n={};for(const[t,i]of Object.entries(e))"string"!=typeof i&&"number"!=typeof i||(n[t]=i);return n}(e));if(o)return o}catch{}}const o=ee(e),a=o.startsWith(re)?o.slice(18):o;return a&&"[object Object]"!==a?a:i}const le=["relay_state","relay_state_target","priority","priority_target"];function ce(t){return"_favoriteRefs"in t}const ue=Object.freeze({mayOperate:!0,reason:null}),de=Object.freeze({mayOperate:!1,reason:null}),he=["control_disabled","admin_only","read_only"];function pe(t){const e=t?.control_access;return"object"==typeof e&&null!==e&&"may_operate"in e&&"boolean"==typeof e.may_operate?e.may_operate?ue:{mayOperate:!1,reason:"reason"in e&&(n=e.reason,he.some(t=>t===n))?e.reason:null}:ue;var n}function fe(t){return"circuit"===t?.kind}function ge(t,e){if(!t||!ce(t))return pe(t);const n=t._favoriteRefs[e];return fe(n)?n.controlAccess:de}function me(t){return!!t?.entities?.switch&&!1!==t.is_user_controllable}function ve(t,e){const n=new Map;for(const[i,r]of Object.entries(t._favoriteRefs))fe(r)&&e(t.circuits[i])&&n.set(r.panelDeviceId,r.controlAccess);return n}const ye={control_disabled:()=>i("controls.disabled"),admin_only:()=>i("controls.admin_only"),read_only:()=>i("controls.read_only")};function _e(t){return t.mayOperate?"":t.reason?ye[t.reason]():i("controls.not_operable")}class be extends Error{constructor(t){super(t),this.name="ControlChangeRefused"}}function xe(t,e){return{setRelay:(n,i)=>we(t,e,"switch",i?"turn_on":"turn_off",n,{}),setPriority:(n,i)=>we(t,e,"select","select_option",n,{option:i})}}async function we(t,e,n,r,o,a){if(!e.mayOperate)throw new be(_e(e));try{await t.callWS({type:"call_service",domain:n,service:r,service_data:a,target:{entity_id:o}})}catch(t){throw ie(t)?new be(i("controls.entity_unauthorized")):t}}const Se={relay:{key:"service:relay",fallback:()=>i("error.relay_failed")},priority:{key:"service:shedding",fallback:()=>i("error.shedding_failed")}};function Ce(t,e,n,i){console.warn(`SPAN Panel: ${i} change failed`,n);const{key:r,fallback:o}=Se[i];se(t,n,l,o()).then(t=>{e?.add({key:r,level:"error",message:t,persistent:!1})})}function ke(t,e){const n=_e(e);n?t.title=n:t.removeAttribute("title")}function Me(t){const e=_e(t);return e?`

${Ft(e)}

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

${r}

\n ${o}\n \n ${l?function(t,e={}){const n=!t.mayOperate;return`
\n ${Ft(i("header.enable_switches"))}\n
\n \n
\n
${!1===e.note?"":Me(t)}`}(function(t){if(!t||!ce(t))return pe(t);const e=[...ve(t,me).values()],[n]=e;return!n||e.some(t=>t.mayOperate)?ue:n}(t)):""}\n
\n ${function(t,e){const n="current"===(e.chart_metric||"power"),r=!!t.panel_entities?.site_power,o=!!t.panel_entities?.dsm_state,a=!!t.panel_entities?.current_power,s=!!t.panel_entities?.feedthrough_power,l=!!t.panel_entities?.pv_power,c=!!t.panel_entities?.battery_level;return`\n
\n ${r?`\n
\n ${i("header.site")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${o?`\n
\n ${i("header.grid")}\n
\n ${Xt}\n
\n
`:""}\n ${a?`\n
\n ${i("header.upstream")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${s?`\n
\n ${i("header.downstream")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${l?`\n
\n ${i("header.solar")}\n
\n ${Xt}\n ${n?"A":"kW"}\n
\n
`:""}\n ${c?`\n
\n ${i("header.battery")}\n
\n ${Xt}\n %\n
\n
`:""}\n
\n `}(t,e)}\n
\n
\n
\n ${a}\n
\n \n \n
\n
\n
\n ${Object.entries(b).filter(([t])=>"unknown"!==t).map(([,t])=>{const e=Ft(t.icon),n=Ft(t.color),i=Ft(t.label());let r;return r=t.icon2?``:t.textLabel?`${Ft(t.textLabel)}`:``,`
${r}${i}
`}).join("")}\n
\n
\n
\n `}function Ae(t){return"number"==typeof t&&Number.isInteger(t)&&t>0}function Ie(t){return!0===t.outside_panel}function De(t,e){if(!t)return null;let n=null,i=null;const{first_position:r,last_position:o}=t;Ae(r)&&Ae(o)&&r<=o?(n=r,i=o):Ae(e)&&(n=1,i=e);for(const e of Object.values(t.circuits))if(e&&!Ie(e))for(const t of e.tabs??[])Ae(t)&&(n=null===n?t:Math.min(n,t),i=null===i?t:Math.max(i,t));return null===n||null===i?null:{first:n,last:i}}function Pe(t){return Le(t.last)-Le(t.first)+1}function Le(t){return Math.ceil(t/2)}function Ee(t){return t%2==0?1:0}function Ne(t){if(2!==t.length)return null;const[e,n]=[Math.min(...t),Math.max(...t)];return Le(e)===Le(n)?"row-span":Ee(e)===Ee(n)?"col-span":"row-span"}function Re(t){const e=t.chart_metric??o;return y[e]??y[o]}function Oe(t,e){const n=function(t){return Re(t).entityRole}(e);return t.entities?.[n]??t.entities?.power??null}function ze(t){return t.members.map((e,n)=>({uuid:t.memberIds[n],circuit:e}))}function He(t){return new Map(t.flatMap(t=>t.memberIds.map(e=>[e,t])))}function Be(t,e){if(!e)return t;const{breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}=e.circuit;return{...t,breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}}function $e(t){const e=t.circuits,n=new Map;for(const[t,i]of Object.entries(e)){const e=i.shared_meter_group;e&&n.set(e,[...n.get(e)??[],[t,i]])}const i=[];for(const[r,o]of Object.entries(e)){const e=o.shared_meter_group,a=e?n.get(e):void 0;if(e&&a){if(a[0][0]===r){const[n,r]=a.find(([t])=>t===e)??a[0],o=a.map(([,t])=>t),s=t.shared_meter_groups?.[e];i.push({uuid:n,circuit:{...r,tabs:Fe(o),breaker_rating_a:s?s.breaker_rating_a:We(o),monitoring_rating_a:s?.monitoring_rating_a,monitoring_rating_user_set:!0===s?.monitoring_rating_user_set},members:o,memberIds:a.map(([t])=>t)})}}else i.push({uuid:r,circuit:o,members:[o],memberIds:[r]})}return i}function Fe(t){return[...new Set(t.flatMap(t=>t.tabs))].sort((t,e)=>t-e)}function Ve(t){const e=function(t){return t.some(t=>!t.breaker_rating_a)?"":t.map(t=>Math.round(t.breaker_rating_a)).join("·")}(t);return e?1===t.length?`${e}A`:`${e} A`:""}function We(t){let e=0;for(const n of t){if(!n.breaker_rating_a)return null;e+=n.breaker_rating_a}return e}function je(t){if(1===t.length){const e=t[0].breaker_rating_a;return e?`${e}A`:""}return Ve(t)}function qe(t){return new Promise(e=>setTimeout(e,t))}class Ue{constructor(t){this._store=t}async callWS(t,e,n){const i=n?.retries??3,r=n?.errorId??`ws:${String(e.type??"unknown")}`;return this._withRetry(()=>t.callWS(e),i,r,n?.errorMessage)}async _withRetry(t,e,n,r){if(this._store.hasAnyPanelOffline())try{const e=await t();return this._store.remove(n),e}catch(t){const e=t instanceof Error?t:new Error(ee(t));throw this._store.add({key:n,level:"error",message:r??i("error.panel_offline"),persistent:!1}),e}let o;for(let i=0;i<=e;i++)try{const e=await t();return this._store.remove(n),e}catch(t){if(o=t instanceof Error?t:new Error(ee(t)),i{try{const n={};e&&(n.config_entry_id=e);const o={type:"call_service",domain:l,service:"get_monitoring_status",service_data:n,return_response:!0},a=this._retry?await this._retry.callWS(t,o,{errorId:"fetch:monitoring",errorMessage:i("error.monitoring_failed")}):await t.callWS(o),s=Ge(a?.response);return r===this._generation&&(this._status=s,this._lastFetch=Date.now()),s}catch(t){return console.warn("SPAN Panel: monitoring status fetch failed",t),r===this._generation&&(this._status=null),this._retry||this._errorStore?.add({key:"fetch:monitoring",level:"warning",message:i("error.monitoring_failed"),persistent:!1}),null}finally{this._inflight?.gen===r&&(this._inflight=null)}})();return this._inflight={gen:r,promise:o},o}invalidate(){this._lastFetch=0,this._generation++}get status(){return this._status}clear(){this._status=null,this._lastFetch=0,this._generation++}}class Ye{constructor(){this._caches=new Map,this._errorStore=null}get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t;for(const e of this._caches.values())e.errorStore=t}async fetchOne(t,e){let n=this._caches.get(e);return n||(n=new Xe,n.errorStore=this._errorStore,this._caches.set(e,n)),n.fetch(t,e)}invalidate(){for(const t of this._caches.values())t.invalidate()}clear(){this._caches.clear()}}function Ze(t,e){return function(t,e){return t?.circuits?t.circuits[e]??null:null}(t,function(t){return t.entities?.current??t.entities?.power??""}(e))}function Ke(t){return{continuousPct:t?.continuous_threshold_pct??80,spikePct:t?.spike_threshold_pct??100}}function Qe(t,e){const{continuousPct:n,spikePct:i}=Ke(e);return t>=i?"alert":t>=n?"warning":"normal"}function Je(t,e){return`utilization-${Qe(t,e)}`}function tn(t){return(void 0===t.monitoring_rating_a?t.breaker_rating_a:t.monitoring_rating_a)??null}function en(t){return null!=t&&!1!==t.monitoring_enabled}function nn(t,e){return en(e)?tn(t):t.breaker_rating_a??null}const rn=["continuous_threshold_pct","spike_threshold_pct"];function on(t,e){return en(e)?function(t,e){return"averaged_legs"===t?.package_ratings_state&&en(e)}(t,e)?"averaged_legs":function(t,e){return t&&e&&function(t){const e=t.package_ratings_state;return"applies"===e||"pending"===e&&"one_space"===t.package_ratings_form}(t)&&rn.some(t=>(e[t]??0)>100)?!0===e.has_override?"own":"global":null}(t,e):null}function an(t){return t.packageRatings?.length&&t.panelAmps?r("monitoringRating.copied",{package:t.packageRatings.join("-"),panel:String(t.panelAmps)}):i("monitoringRating.copied_unnamed")}function sn(t,e,n,i){const r=[];return n||r.push("circuit-off"),i&&r.push("circuit-producer"),function(t){return!!t&&null!=t.over_threshold_since}(e)&&r.push("circuit-alert"),r.join(" ")}function ln(t,e){return Ie(t)||yn(t,e)}function cn(t,e){const n=t.entities?.power;return qt(n?e.states[n]:void 0)}function un(t,e){const n=t.entities?.current;return qt(n?e.states[n]:void 0)}function dn(t){return t.is_generation??"pv"===t.device_type}function hn(t,e){return dn(t)||null!==e&&e<0}function pn(t,e,n){const i=un(t,e);if(t.entities?.current&&null===i)return null;const r=n?.utilization_pct??null,o=nn(t,n);return null===r&&null!==i&&o?Math.round(Math.abs(i)/o*1e3)/10:r}const fn=new Set(x),gn={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function mn(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function vn(t,e,n){const i=t.entities?.power,r=i?e.states[i]?.attributes?.[n]:void 0;return"string"==typeof r&&r?r:void 0}function yn(t,e){const n=mn(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(vn(t,e,"relay_state")??t.relay_state)}function _n(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=mn(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function bn(t){return void 0===t?void 0:gn[t]}function xn(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function wn(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=xn(t,e);return void 0!==n&&fn.has(n)?n:bn(vn(t,e,"shed_priority"))??bn(t.priority)??"unknown"}function Sn(t,e){return _e(t)||(e?i("grid.shared_switch"):"")}function Cn(t,e,n,r=!1){if("none"===e)return"";const o=["toggle-pill",t?"toggle-on":"toggle-off"];"inert"===e&&o.push("toggle-unavailable"),r&&o.push("toggle-shared"),n.mayOperate||o.push("toggle-forbidden");const a=Sn(n,r);return`
\n ${i(t?"grid.on":"grid.off")}\n \n
`}function kn(t,e,n,r){const o=t.querySelector(".toggle-pill");if(!o)return;o.classList.toggle("toggle-on",e),o.classList.toggle("toggle-off",!e),o.classList.toggle("toggle-unavailable","operable"!==n),o.classList.toggle("toggle-forbidden",!r.mayOperate);const a=Sn(r,o.classList.contains("toggle-shared"));a?o.title=a:o.removeAttribute("title");const s=o.querySelector(".toggle-label");s&&(s.textContent=i(e?"grid.on":"grid.off"))}function Mn(t){return"unknown"===t?void 0:b[t]}const Tn="display:none;";function An(t){const e=Mn(t),n=e?Ft(e.color):"",i=e?` title="${Ft(e.label())}"`:"",r=e?Ft(e.icon):"",o=e?.icon2?Ft(e.icon2):"",a=e?.textLabel?Ft(e.textLabel):"";return`\n \n \n ${a}\n `}function In(t,e){const n=t.querySelector(".shedding-composite");if(!n)return;const i=Mn(e);n.style.display=i?"":"none",n.title=i?i.label():"";const r=i?.color??"",o=n.querySelector(".shedding-icon");o&&(o.setAttribute("icon",i?.icon??""),o.style.color=r);const a=n.querySelector(".shedding-icon-secondary");a&&(a.setAttribute("icon",i?.icon2??""),a.style.color=r,a.style.display=i?.icon2?"":"none");const s=n.querySelector(".shedding-label");s&&(s.textContent=i?.textLabel??"",s.style.color=r,s.style.display=i?.textLabel?"":"none")}function Dn(t,e,n,r,o,a,s,l,c,u,d=[e],h=!1){const p=cn(e,a),f=hn(e,p),g=yn(e,a),m=_n(e,a),v=d.length>1,y=Ve(d),_=Ft(d.map(t=>t.name||i("grid.unknown")).join(" · ")),b="current"===Re(s).entityRole?te(un(e,a)):Jt(p),x=An(c||"unknown"),w=``;let S="";const C=pn(e,a,l);null!==C&&(S=`${Math.round(C)}%`);return`\n
\n
\n
\n ${y?`${y}`:""}\n ${S}\n ${_}\n
\n
\n \n ${b}\n \n ${Cn(g,m,u,v&&function(t){const e=t[0]?.shared_relay_group;return!!e&&t.every(t=>t.shared_relay_group===e)}(d))}\n
\n
\n
\n ${x}\n ${w}\n
\n
\n
\n `}function Pn(t,e){return`\n
\n —\n
\n `}function Ln(t){return"function"==typeof globalThis.CSS?.escape?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function En(t){return Object.entries(t.circuits).filter(([,t])=>Ie(t))}function Nn(t,e){return!1!==e.show_panel&&En(t).length>0}function Rn(t,e,n){return`${Ft(function(t){const e=qt(t);if(null===e)return Xt;const n=t?.attributes.unit_of_measurement;return"Wh"===n?`${(e/1e3).toFixed(1)} kWh`:"kWh"===n?`${e.toFixed(1)} kWh`:"string"==typeof n&&n?`${e} ${n}`:String(e)}(e?t.states[e]:void 0))} ${Ft(n)}`}function On(t,e,n){const r=cn(t,e),o=null===r||0===r?"":i(r>0?"meters.importing":"meters.exporting");return`\n ${"current"===Re(n).entityRole?te(un(t,e)):Jt(r)}\n ${Ft(o)}\n ${Rn(e,t.entities?.consumed_energy,i("meters.imported"))}\n ${Rn(e,t.entities?.produced_energy,i("meters.exported"))}\n `}const zn={names:["power","battery power"],suffixes:["_power"]},Hn={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},Bn={names:["state of energy"],suffixes:["_soe_kwh"]};function $n(t,e){if(!t.entities)return null;for(const[n,i]of Object.entries(t.entities)){if("sensor"!==i.domain)continue;const t=(i.original_name??"").toLowerCase();if(e.names.some(e=>t===e))return n;if(i.unique_id&&e.suffixes.some(t=>i.unique_id.endsWith(t)))return n}return null}function Fn(t){return $n(t,Hn)}function Vn(t){return $n(t,Bn)}function Wn(t){const e=t.solar;return e?"inverter"===e.role?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:null}:e.power_entity_id?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:e.site_power_entity_id}:{headlineEid:e.site_power_entity_id,headlineIsSiteTotal:null!==e.site_power_entity_id,siteTotalEid:null}:{headlineEid:(n=t,$n(n,zn)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function jn(t){const{headlineEid:e,siteTotalEid:n}=Wn(t),i=[e,n];return t.type===f&&i.push(Fn(t),Vn(t)),new Set(i.filter(t=>null!==t))}function qn(t){const e=[{role:"power",entityId:Wn(t).headlineEid}];return t.type===f&&e.push({role:"soc",entityId:Fn(t)},{role:"soe",entityId:Vn(t)}),e.filter(t=>null!==t.entityId)}function Un(t,e){return qt(t.states[e])}function Gn(t){if(!t)return null;let e=null;for(const[n,i]of Object.entries(t)){if("sensor"===i.domain)return n;e||(e=n)}return e}function Xn(t,e){return qn(t).length>0||e&&null!==Gn(t.entities)}function Yn(t,e=()=>""){const n=t=>"site"===t.solar?.role?0:1,i=new Map;for(const n of t){if(n[1].type!==m)continue;const t=e(n[0]),r=i.get(t);r?r.push(n):i.set(t,[n])}for(const t of i.values())t.sort(([,t],[,e])=>n(t)-n(e)||(t.name??"").localeCompare(e.name??""));const r=[],o=new Set;for(const n of t){if(n[1].type!==m){r.push(n);continue}const t=e(n[0]);o.has(t)||(o.add(t),r.push(...i.get(t)??[]))}return r}function Zn(t,e){return void 0!==t.config_entry_id&&e.has(t.config_entry_id)&&!t.via_device_id&&!t.parent_device_id}function Kn(t,e){return void 0!==t.config_entry_id&&t.config_entry_id===e.config_entry_id}function Qn(t){return(t.name_by_user||t.name||"").trim()}function Jn(t){return(t.name??t.original_name??"").trim()}function ti(t,e,n,r){const o=!1!==n.show_battery,a=!1!==n.show_evse,s=!1!==n.show_solar;if(!t.sub_devices)return"";const l=Yn(Object.entries(t.sub_devices).filter(([,t])=>!(t.type===f&&!o)&&(!(t.type===g&&!a)&&!(t.type===m&&!s))),function(t){if(!ce(t))return()=>"";const e=t._favoriteRefs;return t=>e[t]?.panelDeviceId??""}(t));if(0===l.length)return"";const c=[];for(const[t,i]of l){const r=Wn(i),o=i.type===f,a=o?Fn(i):null,s=o?Vn(i):null,l=ri(i,e,n,jn(i)),u=oi(t,i,o,r.headlineEid,a,s),d=i.solar?ni(i.solar,r,e):"";(r.headlineEid||u||l||d)&&c.push({devId:t,sub:i,power:r,chartsHTML:u,entHTML:l,solarHTML:d})}if(0===c.length)return"";const u=c.filter(t=>t.sub.type===g).length;let d=0,h="";for(const{devId:t,sub:n,power:o,chartsHTML:a,entHTML:s,solarHTML:l}of c){const c=ei(n),p=o.headlineIsSiteTotal?`${Ft(i("subdevice.site_total"))}`:"",m=o.headlineEid?`${p}${Qt(Un(e,o.headlineEid))}`:"",v=Xn(n,r.showFavorites)?``:"",y=n.type===f,_=n.type===g;let b="";y?b="sub-device-bess":_&&(d++,d===u&&u%2==1&&(b="sub-device-full")),h+=`\n
\n
\n ${Ft(c)}\n ${Ft(n.name||"")}\n ${m}\n ${v}\n
\n ${a}\n ${l}\n ${s}\n
\n `}return h}function ei(t){return t.type===m?"inverter"===t.solar?.role?i("subdevice.solar_inverter"):i("subdevice.solar"):t.type===g?i("subdevice.ev_charger"):t.type===f?i("subdevice.battery"):i("subdevice.fallback")}function ni(t,e,n){let r="";const o="role"===t.identity?"":[t.vendor,t.model].filter(t=>!!t).join(" · ");if(o&&(r+=`
${Ft(o)}
`),e.siteTotalEid){const t=Un(n,e.siteTotalEid);r+=`\n
\n ${Ft(i("subdevice.site_total"))}:\n ${Qt(t)}\n
`}return"inverter"!==t.role||e.headlineEid||(r+=`
${Ft(i("subdevice.in_site_total"))}
`),r}function ii(t,e){const n=t.entities?.[e],i=n?.name?.trim();if(i)return i;const r=n?.device_id?t.devices?.[n.device_id]:void 0;return r&&Qn(r)||e}function ri(t,e,n,i){const r=n.visible_sub_entities||{};let o="";if(!t.entities)return o;for(const[n,a]of Object.entries(t.entities)){if(i.has(n))continue;if(!0!==r[n])continue;const s=e.states[n];if(!s)continue;let l=a.original_name||ii(e,n);const c=t.name||"";let u;if(l.startsWith(c+" ")&&(l=l.slice(c.length+1)),e.formatEntityState)u=e.formatEntityState(s);else{u=s.state;const t=s.attributes.unit_of_measurement||"";t&&(u+=" "+t)}if("Wh"===(s.attributes.unit_of_measurement||"")){const t=qt(s);null!==t&&(u=(t/1e3).toFixed(1)+" kWh")}o+=`\n
\n ${Ft(l)}:\n ${Ft(u)}\n
\n `}return o}function oi(t,e,n,r,o,a){if(n){const e=[{key:`${v}${t}_soc`,title:i("subdevice.soc"),available:!!o},{key:`${v}${t}_soe`,title:i("subdevice.soe"),available:!!a},{key:`${v}${t}_power`,title:i("subdevice.power"),available:!!r}].filter(t=>t.available);return`\n
\n ${e.map(t=>`\n
\n
${Ft(t.title)}
\n
\n
\n `).join("")}\n
\n `}return r?`
`:""}function ai(t){const e=void 0!==t.history_days||void 0!==t.history_hours||void 0!==t.history_minutes,n=60*(60*(24*(e&&parseInt(String(t.history_days))||0)+(e&&parseInt(String(t.history_hours))||0))+(e?parseInt(String(t.history_minutes))||0:5))*1e3;return Math.max(n,6e4)}function si(t){const e=s[t];return e?e.ms:s[a].ms}function li(t){const e=t/1e3;return e<=600?Math.ceil(e):Math.min(5e3,Math.ceil(e/5))}function ci(t){return Math.max(500,Math.floor(t/5e3))}function ui(t,e,n,i,r,o){t.has(e)||t.set(e,[]);const a=t.get(e);a.push({time:i,value:n});const s=a.findIndex(t=>t.time>=r);s>0?a.splice(0,s):-1===s&&(a.length=0),a.length>o&&a.splice(0,a.length-o)}function di(t,e,n=500){if(0===t.length)return t;t.sort((t,e)=>t.time-e.time);const i=[t[0]];for(let e=1;e=n&&i.push(t[e]);return i.length>e&&i.splice(0,i.length-e),i}function hi(t,e,n,i){let r=t.get(e);r||(r={entityIds:[],keysByEntity:new Map},t.set(e,r));const o=r.keysByEntity.get(n);o?o.push(i):(r.entityIds.push(n),r.keysByEntity.set(n,[i]))}async function pi(t,e,n,i,r){const o=new Date(Date.now()-i).toISOString(),a=i/36e5>72?"hour":"5minute",s=await t.callWS({type:"recorder/statistics_during_period",start_time:o,statistic_ids:e,period:a,types:["mean"]});for(const[t,e]of Object.entries(s)){const i=n.get(t);if(!i||!e)continue;const o=[];for(const t of e){const e=t.mean;if(null==e||!Number.isFinite(e))continue;const n=t.start;n>0&&o.push({time:n,value:e})}if(0!==o.length)for(const t of i){const e=r.get(t)||[],n=[...o,...e];n.sort((t,e)=>t.time-e.time),r.set(t,n)}}}async function fi(t,e,n,i,r){const o=new Date(Date.now()-i).toISOString(),a=await t.callWS({type:"history/history_during_period",start_time:o,entity_ids:e,minimal_response:!0,significant_changes_only:!0,no_attributes:!0}),s=li(i),l=ci(i);for(const[t,e]of Object.entries(a)){const i=n.get(t);if(!i||!e)continue;const o=[];for(const t of e){const e=parseFloat(t.s);if(!Number.isFinite(e))continue;const n=1e3*(t.lu||t.lc||0);n>0&&o.push({time:n,value:e})}if(0!==o.length)for(const t of i){const e=r.get(t)||[],n=[...o,...e];r.set(t,di(n,s,l))}}}function gi(t){if(!t.sub_devices)return[];const e=[];for(const[n,i]of Object.entries(t.sub_devices))for(const{role:t,entityId:r}of qn(i))e.push({entityId:r,key:`${v}${n}_${t}`,devId:n});return e}async function mi(t,e,n,i,r,o){if(!e||!t)return;const a=new Map;for(const[t,i]of Object.entries(e.circuits)){const e=Oe(i,n);if(!e)continue;let o;o=r&&r.has(t)?si(r.get(t)):ai(n),hi(a,o,e,t)}for(const{entityId:t,key:i,devId:r}of gi(e)){let e;e=o&&o.has(r)?si(o.get(r)):ai(n),hi(a,e,t,i)}const s=[];for(const[e,n]of a){if(0===n.entityIds.length)continue;e>2592e5?s.push(pi(t,n.entityIds,n.keysByEntity,e,i)):s.push(fi(t,n.entityIds,n.keysByEntity,e,i))}await Promise.all(s)}var vi=function(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1},yi=new function(){this.browser=new vi,this.node=!1,this.wxa=!1,this.worker=!1,this.svgSupported=!1,this.touchEventsSupported=!1,this.pointerEventsSupported=!1,this.domSupported=!1,this.transformSupported=!1,this.transform3dSupported=!1,this.hasGlobalWindow="undefined"!=typeof window};"object"==typeof wx&&"function"==typeof wx.getSystemInfoSync?(yi.wxa=!0,yi.touchEventsSupported=!0):"undefined"==typeof document&&"undefined"!=typeof self?yi.worker=!0:!yi.hasGlobalWindow||"Deno"in window||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Node.js")>-1?(yi.node=!0,yi.svgSupported=!0):function(t,e){var n=e.browser,i=t.match(/Firefox\/([\d.]+)/),r=t.match(/MSIE\s([\d.]+)/)||t.match(/Trident\/.+?rv:(([\d.]+))/),o=t.match(/Edge?\/([\d.]+)/),a=/micromessenger/i.test(t);i&&(n.firefox=!0,n.version=i[1]);r&&(n.ie=!0,n.version=r[1]);o&&(n.edge=!0,n.version=o[1],n.newEdge=+o[1].split(".")[0]>18);a&&(n.weChat=!0);e.svgSupported="undefined"!=typeof SVGRect,e.touchEventsSupported="ontouchstart"in window&&!n.ie&&!n.edge,e.pointerEventsSupported="onpointerdown"in window&&(n.edge||n.ie&&+n.version>=11);var s=e.domSupported="undefined"!=typeof document;if(s){var l=document.documentElement.style;e.transform3dSupported=(n.ie&&"transition"in l||n.edge||"WebKitCSSMatrix"in window&&"m11"in new WebKitCSSMatrix||"MozPerspective"in l)&&!("OTransition"in l),e.transformSupported=e.transform3dSupported||n.ie&&+n.version>=9}}(navigator.userAgent,yi);var _i="sans-serif",bi="12px "+_i;var xi,wi,Si=function(t){var e={};if("undefined"==typeof JSON)return e;for(var n=0;n=0)o=r*t.length;else for(var a=0;a>1)%2;a.style.cssText=["position: absolute","visibility: hidden","padding: 0","margin: 0","border-width: 0","user-select: none","width:0","height:0",i[s]+":0",r[l]+":0",i[1-s]+":auto",r[1-l]+":auto",""].join("!important;"),t.appendChild(a),n.push(a)}return e.clearMarkers=function(){Ui(n,function(t){t.parentNode&&t.parentNode.removeChild(t)})},n}(e,o),s=function(t,e,n){for(var i=n?"invTrans":"trans",r=e[i],o=e.srcCoords,a=[],s=[],l=!0,c=0;c<4;c++){var u=t[c].getBoundingClientRect(),d=2*c,h=u.left,p=u.top;a.push(h,p),l=l&&o&&h===o[d]&&p===o[d+1],s.push(t[c].offsetLeft,t[c].offsetTop)}return l&&r?r:(e.srcCoords=a,e[i]=n?qr(s,a):qr(a,s))}(a,o,r);if(s)return s(t,n,i),!0}return!1}function Yr(t){return"CANVAS"===t.nodeName.toUpperCase()}var Zr=/([&<>"'])/g,Kr={"&":"&","<":"<",">":">",'"':""","'":"'"};function Qr(t){return null==t?"":(t+"").replace(Zr,function(t,e){return Kr[e]})}var Jr=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,to=[],eo=yi.browser.firefox&&+yi.browser.version.split(".")[0]<39;function no(t,e,n,i){return n=n||{},i?io(t,e,n):eo&&null!=e.layerX&&e.layerX!==e.offsetX?(n.zrX=e.layerX,n.zrY=e.layerY):null!=e.offsetX?(n.zrX=e.offsetX,n.zrY=e.offsetY):io(t,e,n),n}function io(t,e,n){if(yi.domSupported&&t.getBoundingClientRect){var i=e.clientX,r=e.clientY;if(Yr(t)){var o=t.getBoundingClientRect();return n.zrX=i-o.left,void(n.zrY=r-o.top)}if(Xr(to,t,i,r))return n.zrX=to[0],void(n.zrY=to[1])}n.zrX=n.zrY=0}function ro(t){return t||window.event}function oo(t,e,n){if(null!=(e=ro(e)).zrX)return e;var i=e.type;if(i&&i.indexOf("touch")>=0){var r="touchend"!==i?e.targetTouches[0]:e.changedTouches[0];r&&no(t,r,e,n)}else{no(t,e,e,n);var o=function(t){var e=t.wheelDelta;if(e)return e;var n=t.deltaX,i=t.deltaY;if(null==n||null==i)return e;return 3*(0!==i?Math.abs(i):Math.abs(n))*(i>0?-1:i<0?1:n>0?-1:1)}(e);e.zrDelta=o?o/120:-(e.detail||0)/3}var a=e.button;return null==e.which&&void 0!==a&&Jr.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function ao(t,e,n,i){t.removeEventListener(e,n,i)}var so=function(t){t.preventDefault(),t.stopPropagation(),t.cancelBubble=!0},lo=function(){function t(){this._track=[]}return t.prototype.recognize=function(t,e,n){return this._doTrack(t,e,n),this._recognize(t)},t.prototype.clear=function(){return this._track.length=0,this},t.prototype._doTrack=function(t,e,n){var i=t.touches;if(i){for(var r={points:[],touches:[],target:e,event:t},o=0,a=i.length;o1&&r&&r.length>1){var a=co(r)/co(o);!isFinite(a)&&(a=1),e.pinchScale=a;var s=[((i=r)[0][0]+i[1][0])/2,(i[0][1]+i[1][1])/2];return e.pinchX=s[0],e.pinchY=s[1],{type:"pinch",target:t[0].target,event:e}}}}};function ho(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function po(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t}function fo(t,e,n){var i=e[0]*n[0]+e[2]*n[1],r=e[1]*n[0]+e[3]*n[1],o=e[0]*n[2]+e[2]*n[3],a=e[1]*n[2]+e[3]*n[3],s=e[0]*n[4]+e[2]*n[5]+e[4],l=e[1]*n[4]+e[3]*n[5]+e[5];return t[0]=i,t[1]=r,t[2]=o,t[3]=a,t[4]=s,t[5]=l,t}function go(t,e,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4]+n[0],t[5]=e[5]+n[1],t}function mo(t,e,n,i){void 0===i&&(i=[0,0]);var r=e[0],o=e[2],a=e[4],s=e[1],l=e[3],c=e[5],u=Math.sin(n),d=Math.cos(n);return t[0]=r*d+s*u,t[1]=-r*u+s*d,t[2]=o*d+l*u,t[3]=-o*u+d*l,t[4]=d*(a-i[0])+u*(c-i[1])+i[0],t[5]=d*(c-i[1])-u*(a-i[0])+i[1],t}function vo(t,e){var n=e[0],i=e[2],r=e[4],o=e[1],a=e[3],s=e[5],l=n*a-o*i;return l?(l=1/l,t[0]=a*l,t[1]=-o*l,t[2]=-i*l,t[3]=n*l,t[4]=(i*s-a*r)*l,t[5]=(o*r-n*s)*l,t):null}var yo=function(){function t(t,e){this.x=t||0,this.y=e||0}return t.prototype.copy=function(t){return this.x=t.x,this.y=t.y,this},t.prototype.clone=function(){return new t(this.x,this.y)},t.prototype.set=function(t,e){return this.x=t,this.y=e,this},t.prototype.equal=function(t){return t.x===this.x&&t.y===this.y},t.prototype.add=function(t){return this.x+=t.x,this.y+=t.y,this},t.prototype.scale=function(t){this.x*=t,this.y*=t},t.prototype.scaleAndAdd=function(t,e){this.x+=t.x*e,this.y+=t.y*e},t.prototype.sub=function(t){return this.x-=t.x,this.y-=t.y,this},t.prototype.dot=function(t){return this.x*t.x+this.y*t.y},t.prototype.len=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},t.prototype.lenSquare=function(){return this.x*this.x+this.y*this.y},t.prototype.normalize=function(){var t=this.len();return this.x/=t,this.y/=t,this},t.prototype.distance=function(t){var e=this.x-t.x,n=this.y-t.y;return Math.sqrt(e*e+n*n)},t.prototype.distanceSquare=function(t){var e=this.x-t.x,n=this.y-t.y;return e*e+n*n},t.prototype.negate=function(){return this.x=-this.x,this.y=-this.y,this},t.prototype.transform=function(t){if(t){var e=this.x,n=this.y;return this.x=t[0]*e+t[2]*n+t[4],this.y=t[1]*e+t[3]*n+t[5],this}},t.prototype.toArray=function(t){return t[0]=this.x,t[1]=this.y,t},t.prototype.fromArray=function(t){this.x=t[0],this.y=t[1]},t.set=function(t,e,n){t.x=e,t.y=n},t.copy=function(t,e){t.x=e.x,t.y=e.y},t.len=function(t){return Math.sqrt(t.x*t.x+t.y*t.y)},t.lenSquare=function(t){return t.x*t.x+t.y*t.y},t.dot=function(t,e){return t.x*e.x+t.y*e.y},t.add=function(t,e,n){t.x=e.x+n.x,t.y=e.y+n.y},t.sub=function(t,e,n){t.x=e.x-n.x,t.y=e.y-n.y},t.scale=function(t,e,n){t.x=e.x*n,t.y=e.y*n},t.scaleAndAdd=function(t,e,n,i){t.x=e.x+n.x*i,t.y=e.y+n.y*i},t.lerp=function(t,e,n,i){var r=1-i;t.x=r*e.x+i*n.x,t.y=r*e.y+i*n.y},t}(),_o=Math.min,bo=Math.max,xo=Math.abs,wo=["x","y"],So=["width","height"],Co=new yo,ko=new yo,Mo=new yo,To=new yo,Ao=Oo(),Io=Ao.minTv,Do=Ao.maxTv,Po=[0,0],Lo=function(){function t(e,n,i,r){t.set(this,e,n,i,r)}return t.set=function(t,e,n,i,r){return i<0&&(e+=i,i=-i),r<0&&(n+=r,r=-r),t.x=e,t.y=n,t.width=i,t.height=r,t},t.prototype.union=function(t){var e=_o(t.x,this.x),n=_o(t.y,this.y);isFinite(this.x)&&isFinite(this.width)?this.width=bo(t.x+t.width,this.x+this.width)-e:this.width=t.width,isFinite(this.y)&&isFinite(this.height)?this.height=bo(t.y+t.height,this.y+this.height)-n:this.height=t.height,this.x=e,this.y=n},t.prototype.applyTransform=function(e){t.applyTransform(this,this,e)},t.prototype.calculateTransform=function(t){var e=this,n=t.width/e.width,i=t.height/e.height,r=[1,0,0,1,0,0];return go(r,r,[-e.x,-e.y]),function(t,e,n){var i=n[0],r=n[1];t[0]=e[0]*i,t[1]=e[1]*r,t[2]=e[2]*i,t[3]=e[3]*r,t[4]=e[4]*i,t[5]=e[5]*r}(r,r,[n,i]),go(r,r,[t.x,t.y]),r},t.prototype.intersect=function(e,n,i){return t.intersect(this,e,n,i)},t.intersect=function(e,n,i,r){i&&yo.set(i,0,0);var o=r&&r.outIntersectRect||null,a=r&&r.clamp;if(o&&(o.x=o.y=o.width=o.height=NaN),!e||!n)return!1;e instanceof t||(e=t.set(Eo,e.x,e.y,e.width,e.height)),n instanceof t||(n=t.set(No,n.x,n.y,n.width,n.height));var s=!!i;Ao.reset(r,s);var l=Ao.touchThreshold,c=e.x+l,u=e.x+e.width-l,d=e.y+l,h=e.y+e.height-l,p=n.x+l,f=n.x+n.width-l,g=n.y+l,m=n.y+n.height-l;if(c>u||d>h||p>f||g>m)return!1;var v=!(u=t.x&&e<=t.x+t.width&&n>=t.y&&n<=t.y+t.height},t.prototype.contain=function(e,n){return t.contain(this,e,n)},t.prototype.clone=function(){return new t(this.x,this.y,this.width,this.height)},t.prototype.copy=function(e){t.copy(this,e)},t.prototype.plain=function(){return{x:this.x,y:this.y,width:this.width,height:this.height}},t.prototype.isFinite=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)},t.prototype.isZero=function(){return 0===this.width||0===this.height},t.create=function(e){return new t(e.x,e.y,e.width,e.height)},t.copy=function(t,e){return t.x=e.x,t.y=e.y,t.width=e.width,t.height=e.height,t},t.applyTransform=function(e,n,i){if(i){if(i[1]<1e-5&&i[1]>-1e-5&&i[2]<1e-5&&i[2]>-1e-5){var r=i[0],o=i[3],a=i[4],s=i[5];return e.x=n.x*r+a,e.y=n.y*o+s,e.width=n.width*r,e.height=n.height*o,e.width<0&&(e.x+=e.width,e.width=-e.width),void(e.height<0&&(e.y+=e.height,e.height=-e.height))}Co.x=Mo.x=n.x,Co.y=To.y=n.y,ko.x=To.x=n.x+n.width,ko.y=Mo.y=n.y+n.height,Co.transform(i),To.transform(i),ko.transform(i),Mo.transform(i),e.x=_o(Co.x,ko.x,Mo.x,To.x),e.y=_o(Co.y,ko.y,Mo.y,To.y);var l=bo(Co.x,ko.x,Mo.x,To.x),c=bo(Co.y,ko.y,Mo.y,To.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Eo=new Lo(0,0,0,0),No=new Lo(0,0,0,0);function Ro(t,e,n,i,r,o,a,s){var l=xo(e-n),c=xo(i-t),u=_o(l,c),d=wo[r],h=wo[1-r],p=So[r];e=c||!Ao.bidirectional)&&(Io[d]=-c,Io[h]=0,Ao.useDir&&Ao.calcDirMTV())))}function Oo(){var t=0,e=new yo,n=new yo,i={minTv:new yo,maxTv:new yo,useDir:!1,dirMinTv:new yo,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(r,o){i.touchThreshold=0,r&&null!=r.touchThreshold&&(i.touchThreshold=bo(0,r.touchThreshold)),i.negativeSize=!1,o&&(i.minTv.set(1/0,1/0),i.maxTv.set(0,0),i.useDir=!1,r&&null!=r.direction&&(i.useDir=!0,i.dirMinTv.copy(i.minTv),n.copy(i.minTv),t=r.direction,i.bidirectional=null==r.bidirectional||!!r.bidirectional,i.bidirectional||e.set(Math.cos(t),Math.sin(t))))},calcDirMTV:function(){var o=i.minTv,a=i.dirMinTv,s=o.y*o.y+o.x*o.x,l=Math.sin(t),c=Math.cos(t),u=l*o.y+c*o.x;r(u)?r(o.x)&&r(o.y)&&a.set(0,0):(n.x=s*c/u,n.y=s*l/u,r(n.x)&&r(n.y)?a.set(0,0):(i.bidirectional||e.dot(n)>0)&&n.len()=0;c--){var u=i[c];u===n||u.ignore||u.ignoreCoarsePointer||u.parent&&u.parent.ignoreCoarsePointer||(Vo.copy(u.getBoundingRect()),u.transform&&Vo.applyTransform(u.transform),Vo.intersect(l)&&o.push(u))}if(o.length)for(var d=Math.PI/12,h=2*Math.PI,p=0;p=0;o--){var a=t[o],s=void 0;if(a!==r&&!a.ignore&&(s=jo(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==zo)){e.target=a;break}}}function Uo(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}Ui(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){Wo.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=Uo(this,r,o);if("mouseup"===t&&a||(i=(n=this.findHover(r,o)).target),"mousedown"===t)this._downEl=i,this._downPoint=[e.zrX,e.zrY],this._upEl=i;else if("mouseup"===t)this._upEl=i;else if("click"===t){if(this._downEl!==this._upEl||!this._downPoint||Rr(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function Go(t,e,n,i){var r=e+1;if(r===n)return 1;if(i(t[r++],t[e])<0){for(;r=0;)r++;return r-e}function Xo(t,e,n,i,r){for(i===e&&i++;i>>1])<0?l=o:s=o+1;var c=i-s;switch(c){case 3:t[s+3]=t[s+2];case 2:t[s+2]=t[s+1];case 1:t[s+1]=t[s];break;default:for(;c>0;)t[s+c]=t[s+c-1],c--}t[s]=a}}function Yo(t,e,n,i,r,o){var a=0,s=0,l=1;if(o(t,e[n+r])>0){for(s=i-r;l0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}else{for(s=r+1;ls&&(l=s);var c=a;a=r-l,l=r-c}for(a++;a>>1);o(t,e[n+u])>0?a=u+1:l=u}return l}function Zo(t,e,n,i,r,o){var a=0,s=0,l=1;if(o(t,e[n+r])<0){for(s=r+1;ls&&(l=s);var c=a;a=r-l,l=r-c}else{for(s=i-r;l=0;)a=l,(l=1+(l<<1))<=0&&(l=s);l>s&&(l=s),a+=r,l+=r}for(a++;a>>1);o(t,e[n+u])<0?l=u:a=u+1}return l}function Ko(t,e){var n,i,r=7,o=0,a=[];function s(s){var l=n[s],c=i[s],u=n[s+1],d=i[s+1];i[s]=c+d,s===o-3&&(n[s+1]=n[s+2],i[s+1]=i[s+2]),o--;var h=Zo(t[u],t,l,c,0,e);l+=h,0!==(c-=h)&&0!==(d=Yo(t[l+c-1],t,u,d,d-1,e))&&(c<=d?function(n,i,o,s){var l=0;for(l=0;l=7||p>=7);if(f)break;g<0&&(g=0),g+=2}if((r=g)<1&&(r=1),1===i){for(l=0;l=0;l--)t[p+l]=t[h+l];return void(t[d]=a[u])}var f=r;for(;;){var g=0,m=0,v=!1;do{if(e(a[u],t[c])<0){if(t[d--]=t[c--],g++,m=0,0===--i){v=!0;break}}else if(t[d--]=a[u--],m++,g=0,1===--s){v=!0;break}}while((g|m)=0;l--)t[p+l]=t[h+l];if(0===i){v=!0;break}}if(t[d--]=a[u--],1===--s){v=!0;break}if(0!==(m=s-Yo(t[c],a,0,s,s-1,e))){for(s-=m,p=(d-=m)+1,h=(u-=m)+1,l=0;l=7||m>=7);if(v)break;f<0&&(f=0),f+=2}(r=f)<1&&(r=1);if(1===s){for(p=(d-=i)+1,h=(c-=i)+1,l=i-1;l>=0;l--)t[p+l]=t[h+l];t[d]=a[u]}else{if(0===s)throw new Error;for(h=d-(s-1),l=0;l1;){var t=o-2;if(t>=1&&i[t-1]<=i[t]+i[t+1]||t>=2&&i[t-2]<=i[t]+i[t-1])i[t-1]i[t+1])break;s(t)}},forceMergeRuns:function(){for(;o>1;){var t=o-2;t>0&&i[t-1]=32;)e|=1&t,t>>=1;return t+e}(r);do{if((o=Go(t,n,i,e))s&&(l=s),Xo(t,n,n+l,n+o,e),o=l}a.pushRun(n,o),a.mergeRuns(),r-=o,n+=o}while(0!==r);a.forceMergeRuns()}}}var Jo=!1;function ta(){Jo||(Jo=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function ea(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var na,ia=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=ea}return t.prototype.traverse=function(t,e){for(var n=0;n=0&&this._roots.splice(i,1)}},t.prototype.delAllRoots=function(){this._roots=[],this._displayList=[],this._displayListLen=0},t.prototype.getRoots=function(){return this._roots},t.prototype.dispose=function(){this._displayList=null,this._roots=null},t}();na=yi.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){return setTimeout(t,16)};var ra={linear:function(t){return t},quadraticIn:function(t){return t*t},quadraticOut:function(t){return t*(2-t)},quadraticInOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)},cubicIn:function(t){return t*t*t},cubicOut:function(t){return--t*t*t+1},cubicInOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},quarticIn:function(t){return t*t*t*t},quarticOut:function(t){return 1- --t*t*t*t},quarticInOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)},quinticIn:function(t){return t*t*t*t*t},quinticOut:function(t){return--t*t*t*t*t+1},quinticInOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},sinusoidalIn:function(t){return 1-Math.cos(t*Math.PI/2)},sinusoidalOut:function(t){return Math.sin(t*Math.PI/2)},sinusoidalInOut:function(t){return.5*(1-Math.cos(Math.PI*t))},exponentialIn:function(t){return 0===t?0:Math.pow(1024,t-1)},exponentialOut:function(t){return 1===t?1:1-Math.pow(2,-10*t)},exponentialInOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))},circularIn:function(t){return 1-Math.sqrt(1-t*t)},circularOut:function(t){return Math.sqrt(1- --t*t)},circularInOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},elasticIn:function(t){var e,n=.1;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=.4*Math.asin(1/n)/(2*Math.PI),-n*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},elasticOut:function(t){var e,n=.1;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=.4*Math.asin(1/n)/(2*Math.PI),n*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},elasticInOut:function(t){var e,n=.1,i=.4;return 0===t?0:1===t?1:(!n||n<1?(n=1,e=.1):e=i*Math.asin(1/n)/(2*Math.PI),(t*=2)<1?n*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/i)*-.5:n*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/i)*.5+1)},backIn:function(t){var e=1.70158;return t*t*((e+1)*t-e)},backOut:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},backInOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)},bounceIn:function(t){return 1-ra.bounceOut(1-t)},bounceOut:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},bounceInOut:function(t){return t<.5?.5*ra.bounceIn(2*t):.5*ra.bounceOut(2*t-1)+.5}},oa=Math.pow,aa=Math.sqrt,sa=1e-8,la=1e-4,ca=aa(3),ua=1/3,da=Ar(),ha=Ar(),pa=Ar();function fa(t){return t>-1e-8&&tsa||t<-1e-8}function ma(t,e,n,i,r){var o=1-r;return o*o*(o*t+3*r*e)+r*r*(r*i+3*o*n)}function va(t,e,n,i,r){var o=1-r;return 3*(((e-t)*o+2*(n-e)*r)*o+(i-n)*r*r)}function ya(t,e,n,i,r,o){var a=i+3*(e-n)-t,s=3*(n-2*e+t),l=3*(e-t),c=t-r,u=s*s-3*a*l,d=s*l-9*a*c,h=l*l-3*s*c,p=0;if(fa(u)&&fa(d)){if(fa(s))o[0]=0;else(C=-l/s)>=0&&C<=1&&(o[p++]=C)}else{var f=d*d-4*u*h;if(fa(f)){var g=d/u,m=-g/2;(C=-s/a+g)>=0&&C<=1&&(o[p++]=C),m>=0&&m<=1&&(o[p++]=m)}else if(f>0){var v=aa(f),y=u*s+1.5*a*(-d+v),_=u*s+1.5*a*(-d-v);(C=(-s-((y=y<0?-oa(-y,ua):oa(y,ua))+(_=_<0?-oa(-_,ua):oa(_,ua))))/(3*a))>=0&&C<=1&&(o[p++]=C)}else{var b=(2*u*s-3*a*d)/(2*aa(u*u*u)),x=Math.acos(b)/3,w=aa(u),S=Math.cos(x),C=(-s-2*w*S)/(3*a),k=(m=(-s+w*(S+ca*Math.sin(x)))/(3*a),(-s+w*(S-ca*Math.sin(x)))/(3*a));C>=0&&C<=1&&(o[p++]=C),m>=0&&m<=1&&(o[p++]=m),k>=0&&k<=1&&(o[p++]=k)}}return p}function _a(t,e,n,i,r){var o=6*n-12*e+6*t,a=9*e+3*i-3*t-9*n,s=3*e-3*t,l=0;if(fa(a)){if(ga(o))(u=-s/o)>=0&&u<=1&&(r[l++]=u)}else{var c=o*o-4*a*s;if(fa(c))r[0]=-o/(2*a);else if(c>0){var u,d=aa(c),h=(-o-d)/(2*a);(u=(-o+d)/(2*a))>=0&&u<=1&&(r[l++]=u),h>=0&&h<=1&&(r[l++]=h)}}return l}function ba(t,e,n,i,r,o){var a=(e-t)*r+t,s=(n-e)*r+e,l=(i-n)*r+n,c=(s-a)*r+a,u=(l-s)*r+s,d=(u-c)*r+c;o[0]=t,o[1]=a,o[2]=c,o[3]=d,o[4]=d,o[5]=u,o[6]=l,o[7]=i}function xa(t,e,n,i,r,o,a,s,l){for(var c=t,u=e,d=0,h=1/l,p=1;p<=l;p++){var f=p*h,g=ma(t,n,r,a,f),m=ma(e,i,o,s,f),v=g-c,y=m-u;d+=Math.sqrt(v*v+y*y),c=g,u=m}return d}function wa(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function Sa(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function Ca(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function ka(t,e,n,i,r){var o=(e-t)*i+t,a=(n-e)*i+e,s=(a-o)*i+o;r[0]=t,r[1]=o,r[2]=s,r[3]=s,r[4]=a,r[5]=n}function Ma(t,e,n,i,r,o,a){for(var s=t,l=e,c=0,u=1/a,d=1;d<=a;d++){var h=d*u,p=wa(t,n,r,h),f=wa(e,i,o,h),g=p-s,m=f-l;c+=Math.sqrt(g*g+m*m),s=p,l=f}return c}var Ta=/cubic-bezier\(([0-9,\.e ]+)\)/;function Aa(t){var e=t&&Ta.exec(t);if(e){var n=e[1].split(","),i=+mr(n[0]),r=+mr(n[1]),o=+mr(n[2]),a=+mr(n[3]);if(isNaN(i+r+o+a))return;var s=[];return function(t){return t<=0?0:t>=1?1:ya(0,i,o,1,t,s)&&ma(0,r,a,1,s[0])}}}var Ia=function(){function t(t){this._inited=!1,this._startTime=0,this._pausedTime=0,this._paused=!1,this._life=t.life||1e3,this._delay=t.delay||0,this.loop=t.loop||!1,this.onframe=t.onframe||Mr,this.ondestroy=t.ondestroy||Mr,this.onrestart=t.onrestart||Mr,t.easing&&this.setEasing(t.easing)}return t.prototype.step=function(t,e){if(this._inited||(this._startTime=t+this._delay,this._inited=!0),!this._paused){var n=this._life,i=t-this._startTime-this._pausedTime,r=i/n;r<0&&(r=0),r=Math.min(r,1);var o=this.easingFunc,a=o?o(r):r;if(this.onframe(a),1===r){if(!this.loop)return!0;var s=i%n;this._startTime=t-s,this._pausedTime=0,this.onrestart()}return!1}this._pausedTime+=e},t.prototype.pause=function(){this._paused=!0},t.prototype.resume=function(){this._paused=!1},t.prototype.setEasing=function(t){this.easing=t,this.easingFunc=tr(t)?t:ra[t]||Aa(t)},t}(),Da=function(t){this.value=t},Pa=function(){function t(){this._len=0}return t.prototype.insert=function(t){var e=new Da(t);return this.insertEntry(e),e},t.prototype.insertEntry=function(t){this.head?(this.tail.next=t,t.prev=this.tail,t.next=null,this.tail=t):this.head=this.tail=t,this._len++},t.prototype.remove=function(t){var e=t.prev,n=t.next;e?e.next=n:this.head=n,n?n.prev=e:this.tail=e,t.next=t.prev=null,this._len--},t.prototype.len=function(){return this._len},t.prototype.clear=function(){this.head=this.tail=null,this._len=0},t}(),La=function(){function t(t){this._list=new Pa,this._maxSize=10,this._map={},this._maxSize=t}return t.prototype.put=function(t,e){var n=this._list,i=this._map,r=null;if(null==i[t]){var o=n.len(),a=this._lastRemovedEntry;if(o>=this._maxSize&&o>0){var s=n.head;n.remove(s),delete i[s.key],r=s.value,this._lastRemovedEntry=s}a?a.value=e:a=new Da(e),a.key=t,n.insertEntry(a),i[t]=a}return r},t.prototype.get=function(t){var e=this._map[t],n=this._list;if(null!=e)return e!==n.tail&&(n.remove(e),n.insertEntry(e)),e.value},t.prototype.clear=function(){this._list.clear(),this._map={}},t.prototype.len=function(){return this._list.len()},t}(),Ea={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function Na(t){return(t=Math.round(t))<0?0:t>255?255:t}function Ra(t){return t<0?0:t>1?1:t}function Oa(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Na(parseFloat(e)/100*255):Na(parseInt(e,10))}function za(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Ra(parseFloat(e)/100):Ra(parseFloat(e))}function Ha(t,e,n){return n<0?n+=1:n>1&&(n-=1),6*n<1?t+(e-t)*n*6:2*n<1?e:3*n<2?t+(e-t)*(2/3-n)*6:t}function Ba(t,e,n){return t+(e-t)*n}function $a(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function Fa(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}var Va=new La(20),Wa=null;function ja(t,e){Wa&&Fa(Wa,e),Wa=Va.put(t,Wa||e.slice())}function qa(t,e){if(t){e=e||[];var n=Va.get(t);if(n)return Fa(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in Ea)return Fa(e,Ea[i]),ja(t,e),e;var r,o=i.length;if("#"===i.charAt(0))return 4===o||5===o?(r=parseInt(i.slice(1,4),16))>=0&&r<=4095?($a(e,(3840&r)>>4|(3840&r)>>8,240&r|(240&r)>>4,15&r|(15&r)<<4,5===o?parseInt(i.slice(4),16)/15:1),ja(t,e),e):void $a(e,0,0,0,1):7===o||9===o?(r=parseInt(i.slice(1,7),16))>=0&&r<=16777215?($a(e,(16711680&r)>>16,(65280&r)>>8,255&r,9===o?parseInt(i.slice(7),16)/255:1),ja(t,e),e):void $a(e,0,0,0,1):void 0;var a=i.indexOf("("),s=i.indexOf(")");if(-1!==a&&s+1===o){var l=i.substr(0,a),c=i.substr(a+1,s-(a+1)).split(","),u=1;switch(l){case"rgba":if(4!==c.length)return 3===c.length?$a(e,+c[0],+c[1],+c[2],1):$a(e,0,0,0,1);u=za(c.pop());case"rgb":return c.length>=3?($a(e,Oa(c[0]),Oa(c[1]),Oa(c[2]),3===c.length?u:za(c[3])),ja(t,e),e):void $a(e,0,0,0,1);case"hsla":return 4!==c.length?void $a(e,0,0,0,1):(c[3]=za(c[3]),Ua(c,e),ja(t,e),e);case"hsl":return 3!==c.length?void $a(e,0,0,0,1):(Ua(c,e),ja(t,e),e);default:return}}$a(e,0,0,0,1)}}function Ua(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=za(t[1]),r=za(t[2]),o=r<=.5?r*(i+1):r+i-r*i,a=2*r-o;return $a(e=e||[],Na(255*Ha(a,o,n+1/3)),Na(255*Ha(a,o,n)),Na(255*Ha(a,o,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function Ga(t,e){var n=qa(t);if(n){for(var i=0;i<3;i++)n[i]=n[i]*(1-e)|0,n[i]>255?n[i]=255:n[i]<0&&(n[i]=0);return Ya(n,4===n.length?"rgba":"rgb")}}function Xa(t,e,n,i){var r=qa(t);if(t)return r=function(t){if(t){var e,n,i=t[0]/255,r=t[1]/255,o=t[2]/255,a=Math.min(i,r,o),s=Math.max(i,r,o),l=s-a,c=(s+a)/2;if(0===l)e=0,n=0;else{n=c<.5?l/(s+a):l/(2-s-a);var u=((s-i)/6+l/2)/l,d=((s-r)/6+l/2)/l,h=((s-o)/6+l/2)/l;i===s?e=h-d:r===s?e=1/3+u-h:o===s&&(e=2/3+d-u),e<0&&(e+=1),e>1&&(e-=1)}var p=[360*e,n,c];return null!=t[3]&&p.push(t[3]),p}}(r),null!=n&&(r[1]=za(tr(n)?n(r[1]):n)),null!=i&&(r[2]=za(tr(i)?i(r[2]):i)),Ya(Ua(r),"rgba")}function Ya(t,e){if(t&&t.length){var n=t[0]+","+t[1]+","+t[2];return"rgba"!==e&&"hsva"!==e&&"hsla"!==e||(n+=","+t[3]),e+"("+n+")"}}function Za(t,e){var n=qa(t);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*e:0}var Ka=new La(100);function Qa(t){if(er(t)){var e=Ka.get(t);return e||(e=Ga(t,-.1),Ka.put(t,e)),e}if(lr(t)){var n=Fi({},t);return n.colorStops=Gi(t.colorStops,function(t){return{offset:t.offset,color:Ga(t.color,-.1)}}),n}return t}var Ja=Math.round;function ts(t){var e;if(t&&"transparent"!==t){if("string"==typeof t&&t.indexOf("rgba")>-1){var n=qa(t);n&&(t="rgb("+n[0]+","+n[1]+","+n[2]+")",e=n[3])}}else t="none";return{color:t,opacity:null==e?1:e}}var es=1e-4;function ns(t){return t-1e-4}function is(t){return Ja(1e3*t)/1e3}function rs(t){return Ja(1e4*t)/1e4}var os={left:"start",right:"end",center:"middle",middle:"middle"};function as(t){return t&&!!t.image}function ss(t){return as(t)||function(t){return t&&!!t.svgElement}(t)}function ls(t){return"linear"===t.type}function cs(t){return"radial"===t.type}function us(t){return t&&("linear"===t.type||"radial"===t.type)}function ds(t){return"url(#"+t+")"}function hs(t){var e=t.getGlobalScale(),n=Math.max(e[0],e[1]);return Math.max(Math.ceil(Math.log(n)/Math.log(10)),1)}function ps(t){var e=t.x||0,n=t.y||0,i=(t.rotation||0)*Tr,r=dr(t.scaleX,1),o=dr(t.scaleY,1),a=t.skewX||0,s=t.skewY||0,l=[];return(e||n)&&l.push("translate("+e+"px,"+n+"px)"),i&&l.push("rotate("+i+")"),1===r&&1===o||l.push("scale("+r+","+o+")"),(a||s)&&l.push("skew("+Ja(a*Tr)+"deg, "+Ja(s*Tr)+"deg)"),l.join(" ")}var fs=yi.hasGlobalWindow&&tr(window.btoa)?function(t){return window.btoa(unescape(encodeURIComponent(t)))}:"undefined"!=typeof Buffer?function(t){return Buffer.from(t).toString("base64")}:function(t){return null},gs=Array.prototype.slice;function ms(t,e,n){return(e-t)*n+t}function vs(t,e,n,i){for(var r=e.length,o=0;oi?e:t,o=Math.min(n,i),a=r[o-1]||{color:[0,0,0,0],offset:0},s=o;sa)i.length=a;else for(var s=o;s=1},t.prototype.getAdditiveTrack=function(){return this._additiveTrack},t.prototype.addKeyframe=function(t,e,n){this._needsSort=!0;var i=this.keyframes,r=i.length,o=!1,a=6,s=e;if(qi(e)){var l=function(t){return qi(t&&t[0])?2:1}(e);a=l,(1===l&&!ir(e[0])||2===l&&!ir(e[0][0]))&&(o=!0)}else if(ir(e)&&!cr(e))a=0;else if(er(e))if(isNaN(+e)){var c=qa(e);c&&(s=c,a=3)}else a=0;else if(lr(e)){var u=Fi({},s);u.colorStops=Gi(e.colorStops,function(t){return{offset:t.offset,color:qa(t.color)}}),ls(e)?a=4:cs(e)&&(a=5),s=u}0===r?this.valType=a:a===this.valType&&6!==a||(o=!0),this.discrete=this.discrete||o;var d={time:t,value:s,rawValue:e,percent:0};return n&&(d.easing=n,d.easingFunc=tr(n)?n:ra[n]||Aa(n)),i.push(d),d},t.prototype.prepare=function(t,e){var n=this.keyframes;this._needsSort&&n.sort(function(t,e){return t.time-e.time});for(var i=this.valType,r=n.length,o=n[r-1],a=this.discrete,s=ks(i),l=Cs(i),c=0;c=0&&!(l[n].percent<=e);n--);n=p(n,c-2)}else{for(n=h;ne);n++);n=p(n-1,c-2)}r=l[n+1],i=l[n]}if(i&&r){this._lastFr=n,this._lastFrP=e;var f=r.percent-i.percent,g=0===f?1:p((e-i.percent)/f,1);r.easingFunc&&(g=r.easingFunc(g));var m=o?this._additiveValue:d?Ms:t[u];if(!ks(s)&&!d||m||(m=this._additiveValue=[]),this.discrete)t[u]=g<1?i.rawValue:r.rawValue;else if(ks(s))1===s?vs(m,i[a],r[a],g):function(t,e,n,i){for(var r=e.length,o=r&&e[0].length,a=0;a0&&s.addKeyframe(0,ws(l),i),this._trackKeys.push(a)}s.addKeyframe(t,ws(e[a]),i)}return this._maxTime=Math.max(this._maxTime,t),this},t.prototype.pause=function(){this._clip.pause(),this._paused=!0},t.prototype.resume=function(){this._clip.resume(),this._paused=!1},t.prototype.isPaused=function(){return!!this._paused},t.prototype.duration=function(t){return this._maxTime=t,this._force=!0,this},t.prototype._doneCallback=function(){this._setTracksFinished(),this._clip=null;var t=this._doneCbs;if(t)for(var e=t.length,n=0;n0)){this._started=1;for(var e=this,n=[],i=this._maxTime||0,r=0;r1){var a=o.pop();r.addKeyframe(a.time,t[i]),r.prepare(this._maxTime,r.getAdditiveTrack())}}}},t}();function Is(){return(new Date).getTime()}var Ds,Ps,Ls=function(t){function e(e){var n=t.call(this)||this;return n._running=!1,n._time=0,n._pausedTime=0,n._pauseStart=0,n._paused=!1,e=e||{},n.stage=e.stage||{},n}return S(e,t),e.prototype.addClip=function(t){t.animation&&this.removeClip(t),this._head?(this._tail.next=t,t.prev=this._tail,t.next=null,this._tail=t):this._head=this._tail=t,t.animation=this},e.prototype.addAnimator=function(t){t.animation=this;var e=t.getClip();e&&this.addClip(e)},e.prototype.removeClip=function(t){if(t.animation){var e=t.prev,n=t.next;e?e.next=n:this._head=n,n?n.prev=e:this._tail=e,t.next=t.prev=t.animation=null}},e.prototype.removeAnimator=function(t){var e=t.getClip();e&&this.removeClip(e),t.animation=null},e.prototype.update=function(t){for(var e=Is()-this._pausedTime,n=e-this._time,i=this._head;i;){var r=i.next;i.step(e,n)?(i.ondestroy(),this.removeClip(i),i=r):i=r}this._time=e,t||(this.trigger("frame",n),this.stage.update&&this.stage.update())},e.prototype._startLoop=function(){var t=this;this._running=!0,na(function e(){t._running&&(na(e),!t._paused&&t.update())})},e.prototype.start=function(){this._running||(this._time=Is(),this._pausedTime=0,this._startLoop())},e.prototype.stop=function(){this._running=!1},e.prototype.pause=function(){this._paused||(this._pauseStart=Is(),this._paused=!0)},e.prototype.resume=function(){this._paused&&(this._pausedTime+=Is()-this._pauseStart,this._paused=!1)},e.prototype.clear=function(){for(var t=this._head;t;){var e=t.next;t.prev=t.next=t.animation=null,t=e}this._head=this._tail=null},e.prototype.isFinished=function(){return null==this._head},e.prototype.animate=function(t,e){e=e||{},this.start();var n=new As(t,e.loop);return this.addAnimator(n),n},e}(Vr),Es=yi.domSupported,Ns=(Ps={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},{mouse:Ds=["click","dblclick","mousewheel","wheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],touch:["touchstart","touchend","touchmove"],pointer:Gi(Ds,function(t){var e=t.replace("mouse","pointer");return Ps.hasOwnProperty(e)?e:t})}),Rs=["mousemove","mouseup"],Os=["pointermove","pointerup"],zs=!1;function Hs(t){var e=t.pointerType;return"pen"===e||"touch"===e}function Bs(t){t&&(t.zrByTouch=!0)}function $s(t,e){for(var n=e,i=!1;n&&9!==n.nodeType&&!(i=n.domBelongToZr||n!==e&&n===t.painterRoot);)n=n.parentNode;return i}var Fs=function(t,e){this.stopPropagation=Mr,this.stopImmediatePropagation=Mr,this.preventDefault=Mr,this.type=e.type,this.target=this.currentTarget=t.dom,this.pointerType=e.pointerType,this.clientX=e.clientX,this.clientY=e.clientY},Vs={mousedown:function(t){t=oo(this.dom,t),this.__mayPointerCapture=[t.zrX,t.zrY],this.trigger("mousedown",t)},mousemove:function(t){t=oo(this.dom,t);var e=this.__mayPointerCapture;!e||t.zrX===e[0]&&t.zrY===e[1]||this.__togglePointerCapture(!0),this.trigger("mousemove",t)},mouseup:function(t){t=oo(this.dom,t),this.__togglePointerCapture(!1),this.trigger("mouseup",t)},mouseout:function(t){$s(this,(t=oo(this.dom,t)).toElement||t.relatedTarget)||(this.__pointerCapturing&&(t.zrEventControl="no_globalout"),this.trigger("mouseout",t))},wheel:function(t){zs=!0,t=oo(this.dom,t),this.trigger("mousewheel",t)},mousewheel:function(t){zs||(t=oo(this.dom,t),this.trigger("mousewheel",t))},touchstart:function(t){Bs(t=oo(this.dom,t)),this.__lastTouchMoment=new Date,this.handler.processGesture(t,"start"),Vs.mousemove.call(this,t),Vs.mousedown.call(this,t)},touchmove:function(t){Bs(t=oo(this.dom,t)),this.handler.processGesture(t,"change"),Vs.mousemove.call(this,t)},touchend:function(t){Bs(t=oo(this.dom,t)),this.handler.processGesture(t,"end"),Vs.mouseup.call(this,t),+new Date-+this.__lastTouchMoment<300&&Vs.click.call(this,t)},pointerdown:function(t){Vs.mousedown.call(this,t)},pointermove:function(t){Hs(t)||Vs.mousemove.call(this,t)},pointerup:function(t){Vs.mouseup.call(this,t)},pointerout:function(t){Hs(t)||Vs.mouseout.call(this,t)}};Ui(["click","dblclick","contextmenu"],function(t){Vs[t]=function(e){e=oo(this.dom,e),this.trigger(t,e)}});var Ws={pointermove:function(t){Hs(t)||Ws.mousemove.call(this,t)},pointerup:function(t){Ws.mouseup.call(this,t)},mousemove:function(t){this.trigger("mousemove",t)},mouseup:function(t){var e=this.__pointerCapturing;this.__togglePointerCapture(!1),this.trigger("mouseup",t),e&&(t.zrEventControl="only_globalout",this.trigger("mouseout",t))}};function js(t,e){var n=e.domHandlers;yi.pointerEventsSupported?Ui(Ns.pointer,function(i){Us(e,i,function(e){n[i].call(t,e)})}):(yi.touchEventsSupported&&Ui(Ns.touch,function(i){Us(e,i,function(r){n[i].call(t,r),function(t){t.touching=!0,null!=t.touchTimer&&(clearTimeout(t.touchTimer),t.touchTimer=null),t.touchTimer=setTimeout(function(){t.touching=!1,t.touchTimer=null},700)}(e)})}),Ui(Ns.mouse,function(i){Us(e,i,function(r){r=ro(r),e.touching||n[i].call(t,r)})}))}function qs(t,e){function n(n){Us(e,n,function(i){i=ro(i),$s(t,i.target)||(i=function(t,e){return oo(t.dom,new Fs(t,e),!0)}(t,i),e.domHandlers[n].call(t,i))},{capture:!0})}yi.pointerEventsSupported?Ui(Os,n):yi.touchEventsSupported||Ui(Rs,n)}function Us(t,e,n,i){t.mounted[e]=n,t.listenerOpts[e]=i,function(t,e,n,i){t.addEventListener(e,n,i)}(t.domTarget,e,n,i)}function Gs(t){var e=t.mounted;for(var n in e)e.hasOwnProperty(n)&&ao(t.domTarget,n,e[n],t.listenerOpts[n]);t.mounted={}}var Xs=function(t,e){this.mounted={},this.listenerOpts={},this.touching=!1,this.domTarget=t,this.domHandlers=e},Ys=function(t){function e(e,n){var i=t.call(this)||this;return i.__pointerCapturing=!1,i.dom=e,i.painterRoot=n,i._localHandlerScope=new Xs(e,Vs),Es&&(i._globalHandlerScope=new Xs(document,Ws)),js(i,i._localHandlerScope),i}return S(e,t),e.prototype.dispose=function(){Gs(this._localHandlerScope),Es&&Gs(this._globalHandlerScope)},e.prototype.setCursor=function(t){this.dom.style&&(this.dom.style.cursor=t||"default")},e.prototype.__togglePointerCapture=function(t){if(this.__mayPointerCapture=null,Es&&+this.__pointerCapturing^+t){this.__pointerCapturing=t;var e=this._globalHandlerScope;t?qs(this,e):Gs(e)}},e}(Vr),Zs=1;yi.hasGlobalWindow&&(Zs=Math.max(window.devicePixelRatio||window.screen&&window.screen.deviceXDPI/window.screen.logicalXDPI||1,1));var Ks=Zs,Qs="#333",Js="#ccc",tl=ho,el=5e-5;function nl(t){return t>el||t<-5e-5}var il,rl=[],ol=[],al=[1,0,0,1,0,0],sl=Math.abs,ll=function(){function t(){}var e;return t.prototype.getLocalTransform=function(e){return t.getLocalTransform(this,e)},t.prototype.setPosition=function(t){this.x=t[0],this.y=t[1]},t.prototype.setScale=function(t){this.scaleX=t[0],this.scaleY=t[1]},t.prototype.setSkew=function(t){this.skewX=t[0],this.skewY=t[1]},t.prototype.setOrigin=function(t){this.originX=t[0],this.originY=t[1]},t.prototype.needLocalTransform=function(){return nl(this.rotation)||nl(this.x)||nl(this.y)||nl(this.scaleX-1)||nl(this.scaleY-1)||nl(this.skewX)||nl(this.skewY)},t.prototype.updateTransform=function(){var t=this.parent&&this.parent.transform,e=this.needLocalTransform(),n=this.transform;e||t?(n=n||[1,0,0,1,0,0],e?this.getLocalTransform(n):tl(n),t&&(e?fo(n,t,n):po(n,t)),this.transform=n,this._resolveGlobalScaleRatio(n)):n&&(tl(n),this.invTransform=null)},t.prototype._resolveGlobalScaleRatio=function(t){var e=this.globalScaleRatio;if(null!=e&&1!==e){this.getGlobalScale(rl);var n=rl[0]<0?-1:1,i=rl[1]<0?-1:1,r=((rl[0]-n)*e+n)/rl[0]||0,o=((rl[1]-i)*e+i)/rl[1]||0;t[0]*=r,t[1]*=r,t[2]*=o,t[3]*=o}this.invTransform=this.invTransform||[1,0,0,1,0,0],vo(this.invTransform,t)},t.prototype.getComputedTransform=function(){for(var t=this,e=[];t;)e.push(t),t=t.parent;for(;t=e.pop();)t.updateTransform();return this.transform},t.prototype.setLocalTransform=function(t){if(t){var e=t[0]*t[0]+t[1]*t[1],n=t[2]*t[2]+t[3]*t[3],i=Math.atan2(t[1],t[0]),r=Math.PI/2+i-Math.atan2(t[3],t[2]);n=Math.sqrt(n)*Math.cos(r),e=Math.sqrt(e),this.skewX=r,this.skewY=0,this.rotation=-i,this.x=+t[4],this.y=+t[5],this.scaleX=e,this.scaleY=n,this.originX=0,this.originY=0}},t.prototype.decomposeTransform=function(){if(this.transform){var t=this.parent,e=this.transform;t&&t.transform&&(t.invTransform=t.invTransform||[1,0,0,1,0,0],fo(ol,t.invTransform,e),e=ol);var n=this.originX,i=this.originY;(n||i)&&(al[4]=n,al[5]=i,fo(ol,e,al),ol[4]-=n,ol[5]-=i,e=ol),this.setLocalTransform(e)}},t.prototype.getGlobalScale=function(t){var e=this.transform;return t=t||[],e?(t[0]=Math.sqrt(e[0]*e[0]+e[1]*e[1]),t[1]=Math.sqrt(e[2]*e[2]+e[3]*e[3]),e[0]<0&&(t[0]=-t[0]),e[3]<0&&(t[1]=-t[1]),t):(t[0]=1,t[1]=1,t)},t.prototype.transformCoordToLocal=function(t,e){var n=[t,e],i=this.invTransform;return i&&zr(n,n,i),n},t.prototype.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&zr(n,n,i),n},t.prototype.getLineScale=function(){var t=this.transform;return t&&sl(t[0]-1)>1e-10&&sl(t[3]-1)>1e-10?Math.sqrt(sl(t[0]*t[3]-t[2]*t[1])):1},t.prototype.copyTransform=function(t){ul(this,t)},t.getLocalTransform=function(t,e){e=e||[];var n=t.originX||0,i=t.originY||0,r=t.scaleX,o=t.scaleY,a=t.anchorX,s=t.anchorY,l=t.rotation||0,c=t.x,u=t.y,d=t.skewX?Math.tan(t.skewX):0,h=t.skewY?Math.tan(-t.skewY):0;if(n||i||a||s){var p=n+a,f=i+s;e[4]=-p*r-d*f*o,e[5]=-f*o-h*p*r}else e[4]=e[5]=0;return e[0]=r,e[3]=o,e[1]=h*r,e[2]=d*o,l&&mo(e,e,l),e[4]+=n+c,e[5]+=i+u,e},t.initDefaultProps=((e=t.prototype).scaleX=e.scaleY=e.globalScaleRatio=1,void(e.x=e.y=e.originX=e.originY=e.skewX=e.skewY=e.rotation=e.anchorX=e.anchorY=0)),t}(),cl=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function ul(t,e){for(var n=0;n=pl)){t=t||bi;for(var e=[],n=+new Date,i=0;i<=127;i++)e[i]=Ci.measureText(String.fromCharCode(i),t).width;var r=+new Date-n;return r>16?hl=pl:r>2&&hl++,e}}(t.font),t.asciiWidthMapTried=!0),0<=e&&e<=127?null!=t.asciiWidthMap?t.asciiWidthMap[e]:t.asciiCharWidth:t.stWideCharWidth}function gl(t,e){var n=t.strWidthCache,i=n.get(e);return null==i&&(i=Ci.measureText(e,t.font).width,n.put(e,i)),i}function ml(t,e,n,i){var r=gl(dl(e),t),o=bl(e),a=yl(0,r,n),s=_l(0,o,i);return new Lo(a,s,r,o)}function vl(t,e,n,i){var r=((t||"")+"").split("\n");if(1===r.length)return ml(r[0],e,n,i);for(var o=new Lo(0,0,0,0),a=0;a=0?parseFloat(t)/100*e:parseFloat(t):t}function wl(t,e,n){var i=e.position||"inside",r=null!=e.distance?e.distance:5,o=n.height,a=n.width,s=o/2,l=n.x,c=n.y,u="left",d="top";if(i instanceof Array)l+=xl(i[0],n.width),c+=xl(i[1],n.height),u=null,d=null;else switch(i){case"left":l-=r,c+=s,u="right",d="middle";break;case"right":l+=r+a,c+=s,d="middle";break;case"top":l+=a/2,c-=r,u="center",d="bottom";break;case"bottom":l+=a/2,c+=o+r,u="center";break;case"inside":l+=a/2,c+=s,u="center",d="middle";break;case"insideLeft":l+=r,c+=s,d="middle";break;case"insideRight":l+=a-r,c+=s,u="right",d="middle";break;case"insideTop":l+=a/2,c+=r,u="center";break;case"insideBottom":l+=a/2,c+=o-r,u="center",d="bottom";break;case"insideTopLeft":l+=r,c+=r;break;case"insideTopRight":l+=a-r,c+=r,u="right";break;case"insideBottomLeft":l+=r,c+=o-r,d="bottom";break;case"insideBottomRight":l+=a-r,c+=o-r,u="right",d="bottom"}return(t=t||{}).x=l,t.y=c,t.align=u,t.verticalAlign=d,t}var Sl="__zr_normal__",Cl=cl.concat(["ignore"]),kl=Xi(cl,function(t,e){return t[e]=!0,t},{ignore:!1}),Ml={},Tl=new Lo(0,0,0,0),Al=[],Il=function(){function t(t){this.id=zi(),this.animators=[],this.currentStates=[],this.states={},this._init(t)}return t.prototype._init=function(t){this.attr(t)},t.prototype.drift=function(t,e,n){switch(this.draggable){case"horizontal":e=0;break;case"vertical":t=0}var i=this.transform;i||(i=this.transform=[1,0,0,1,0,0]),i[4]+=t,i[5]+=e,this.decomposeTransform(),this.markRedraw()},t.prototype.beforeUpdate=function(){},t.prototype.afterUpdate=function(){},t.prototype.update=function(){this.updateTransform(),this.__dirty&&this.updateInnerText()},t.prototype.updateInnerText=function(t){var e=this._textContent;if(e&&(!e.ignore||t)){this.textConfig||(this.textConfig={});var n=this.textConfig,i=n.local,r=e.innerTransformable,o=void 0,a=void 0,s=!1;r.parent=i?this:null;var l=!1;r.copyTransform(e);var c=null!=n.position,u=n.autoOverflowArea,d=void 0;if((u||c)&&(d=Tl,n.layoutRect?d.copy(n.layoutRect):d.copy(this.getBoundingRect()),i||d.applyTransform(this.transform)),c){this.calculateTextPosition?this.calculateTextPosition(Ml,n,d):wl(Ml,n,d),r.x=Ml.x,r.y=Ml.y,o=Ml.align,a=Ml.verticalAlign;var h=n.origin;if(h&&null!=n.rotation){var p=void 0,f=void 0;"center"===h?(p=.5*d.width,f=.5*d.height):(p=xl(h[0],d.width),f=xl(h[1],d.height)),l=!0,r.originX=-r.x+p+(i?0:d.x),r.originY=-r.y+f+(i?0:d.y)}}null!=n.rotation&&(r.rotation=n.rotation);var g=n.offset;g&&(r.x+=g[0],r.y+=g[1],l||(r.originX=-g[0],r.originY=-g[1]));var m=this._innerTextDefaultStyle||(this._innerTextDefaultStyle={});if(u){var v=m.overflowRect=m.overflowRect||new Lo(0,0,0,0);r.getLocalTransform(Al),vo(Al,Al),Lo.copy(v,d),v.applyTransform(Al)}else m.overflowRect=null;var y=void 0,_=void 0,b=void 0;(null==n.inside?"string"==typeof n.position&&n.position.indexOf("inside")>=0:n.inside)&&this.canBeInsideText()?(y=n.insideFill,_=n.insideStroke,null!=y&&"auto"!==y||(y=this.getInsideTextFill()),null!=_&&"auto"!==_||(_=this.getInsideTextStroke(y),b=!0)):(y=n.outsideFill,_=n.outsideStroke,null!=y&&"auto"!==y||(y=this.getOutsideFill()),null!=_&&"auto"!==_||(_=this.getOutsideStroke(y),b=!0)),(y=y||"#000")===m.fill&&_===m.stroke&&b===m.autoStroke&&o===m.align&&a===m.verticalAlign||(s=!0,m.fill=y,m.stroke=_,m.autoStroke=b,m.align=o,m.verticalAlign=a,e.setDefaultTextStyle(m)),e.__dirty|=1,s&&e.dirtyStyle(!0)}},t.prototype.canBeInsideText=function(){return!0},t.prototype.getInsideTextFill=function(){return"#fff"},t.prototype.getInsideTextStroke=function(t){return"#000"},t.prototype.getOutsideFill=function(){return this.__zr&&this.__zr.isDarkMode()?Js:Qs},t.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),n="string"==typeof e&&qa(e);n||(n=[255,255,255,1]);for(var i=n[3],r=this.__zr.isDarkMode(),o=0;o<3;o++)n[o]=n[o]*i+(r?0:255)*(1-i);return n[3]=1,Ya(n,"rgba")},t.prototype.traverse=function(t,e){},t.prototype.attrKV=function(t,e){"textConfig"===t?this.setTextConfig(e):"textContent"===t?this.setTextContent(e):"clipPath"===t?this.setClipPath(e):"extra"===t?(this.extra=this.extra||{},Fi(this.extra,e)):this[t]=e},t.prototype.hide=function(){this.ignore=!0,this.markRedraw()},t.prototype.show=function(){this.ignore=!1,this.markRedraw()},t.prototype.attr=function(t,e){if("string"==typeof t)this.attrKV(t,e);else if(rr(t))for(var n=Zi(t),i=0;i0},t.prototype.getState=function(t){return this.states[t]},t.prototype.ensureState=function(t){var e=this.states;return e[t]||(e[t]={}),e[t]},t.prototype.clearStates=function(t){this.useState(Sl,!1,t)},t.prototype.useState=function(t,e,n,i){var r=t===Sl;if(this.hasState()||!r){var o=this.currentStates,a=this.stateTransition;if(!(Wi(o,t)>=0)||!e&&1!==o.length){var s;if(this.stateProxy&&!r&&(s=this.stateProxy(t)),s||(s=this.states&&this.states[t]),s||r){r||this.saveCurrentToNormalState(s);var l=!!(s&&s.hoverLayer||i);l&&this._toggleHoverLayerFlag(!0),this._applyStateObj(t,s,this._normalState,e,!n&&!this.__inHover&&a&&a.duration>0,a);var c=this._textContent,u=this._textGuide;return c&&c.useState(t,e,n,l),u&&u.useState(t,e,n,l),r?(this.currentStates=[],this._normalState={}):e?this.currentStates.push(t):this.currentStates=[t],this._updateAnimationTargets(),this.markRedraw(),!l&&this.__inHover&&(this._toggleHoverLayerFlag(!1),this.__dirty&=-2),s}Hi("State "+t+" not exists.")}}},t.prototype.useStates=function(t,e,n){if(t.length){var i=[],r=this.currentStates,o=t.length,a=o===r.length;if(a)for(var s=0;s0,p);var f=this._textContent,g=this._textGuide;f&&f.useStates(t,e,d),g&&g.useStates(t,e,d),this._updateAnimationTargets(),this.currentStates=t.slice(),this.markRedraw(),!d&&this.__inHover&&(this._toggleHoverLayerFlag(!1),this.__dirty&=-2)}else this.clearStates()},t.prototype.isSilent=function(){for(var t=this;t;){if(t.silent)return!0;var e=t.__hostTarget;t=e?t.ignoreHostSilent?null:e:t.parent}return!1},t.prototype._updateAnimationTargets=function(){for(var t=0;t=0){var n=this.currentStates.slice();n.splice(e,1),this.useStates(n)}},t.prototype.replaceState=function(t,e,n){var i=this.currentStates.slice(),r=Wi(i,t),o=Wi(i,e)>=0;r>=0?o?i.splice(r,1):i[r]=e:n&&!o&&i.push(e),this.useStates(i)},t.prototype.toggleState=function(t,e){e?this.useState(t,!0):this.removeState(t)},t.prototype._mergeStates=function(t){for(var e,n={},i=0;i=0&&e.splice(n,1)}),this.animators.push(t),n&&n.animation.addAnimator(t),n&&n.wakeUp()},t.prototype.updateDuringAnimation=function(t){this.markRedraw()},t.prototype.stopAnimation=function(t,e){for(var n=this.animators,i=n.length,r=[],o=0;o0&&n.during&&o[0].during(function(t,e){n.during(e)});for(var h=0;h0||r.force&&!a.length){var w,S=void 0,C=void 0,k=void 0;if(s){C={},h&&(S={});for(b=0;b<_;b++){C[v=g[b]]=n[v],h?S[v]=i[v]:n[v]=i[v]}}else if(h){k={};for(b=0;b<_;b++){k[v=g[b]]=ws(n[v]),Ll(n,i,v)}}(w=new As(n,!1,!1,d?Yi(f,function(t){return t.targetName===e}):null)).targetName=e,r.scope&&(w.scope=r.scope),h&&S&&w.whenWithKeys(0,S,g),k&&w.whenWithKeys(0,k,g),w.whenWithKeys(null==c?500:c,s?C:i,g).delay(u||0),t.addAnimator(w,e),a.push(w)}}ji(Il,Vr),ji(Il,ll);var Nl=function(t){function e(e){var n=t.call(this)||this;return n.isGroup=!0,n._children=[],n.attr(e),n}return S(e,t),e.prototype.childrenRef=function(){return this._children},e.prototype.children=function(){return this._children.slice()},e.prototype.childAt=function(t){return this._children[t]},e.prototype.childOfName=function(t){for(var e=this._children,n=0;n=0&&(n.splice(i,0,t),this._doAdd(t))}return this},e.prototype.replace=function(t,e){var n=Wi(this._children,t);return n>=0&&this.replaceAt(e,n),this},e.prototype.replaceAt=function(t,e){var n=this._children,i=n[e];if(t&&t!==this&&t.parent!==this&&t!==i){n[e]=t,i.parent=null;var r=this.__zr;r&&i.removeSelfFromZr(r),this._doAdd(t)}return this},e.prototype._doAdd=function(t){t.parent&&t.parent.remove(t),t.parent=this;var e=this.__zr;e&&e!==t.__zr&&t.addSelfToZr(e),e&&e.refresh()},e.prototype.remove=function(t){var e=this.__zr,n=this._children,i=Wi(n,t);return i<0||(n.splice(i,1),t.parent=null,e&&t.removeSelfFromZr(e),e&&e.refresh()),this},e.prototype.removeAll=function(){for(var t=this._children,e=this.__zr,n=0;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 ml=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 vl(t,e,n)};function vl(t,e,n){return Mi(t)?(i=t,i.replace(/^\s+|\s+$/g,"")).match(/%$/)?parseFloat(t)/100*e+(n||0):parseFloat(t):null==t?NaN:+t;var i}function yl(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function _l(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 bl(t,e){var n=Math.max(_l(t),_l(e)),i=t+e;return n>20?i:yl(i,n)}function xl(t){var e=2*Math.PI;return(t%e+e)%e}function wl(t){return t>-1e-4&&t=10&&e++,e}function Ml(t,e){var n=kl(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 Tl(t){var e=parseFloat(t);return e==t&&(0!==e||!Mi(t)||t.indexOf("x")<=0)?e:NaN}function Al(){return Math.round(9*Math.random())}function Il(t,e){return 0===e?t:Il(e,t%e)}function Dl(t,e){return null==t?e:null==e?t:t*e/Il(t,e)}var Pl="undefined"!=typeof console&&console.warn&&console.log;function Ll(t,e){!function(t,e){Pl&&console[t]("[ECharts] "+e)}("error",t)}function El(t){throw new Error(t)}function Nl(t,e,n){return(e-t)*n+t}var Rl="series\0";function Ol(t){return t instanceof Array?t:null==t?[]:[t]}function zl(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&&fi(r,s)<0)){var l=n.getShallow(s,e);null!=l&&(o[t[a][0]]=l)}}return o}}var dc=uc([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),hc=function(){function t(){}return t.prototype.getAreaStyle=function(t,e){return dc(this,t,e)},t}(),pc=new ia(50);function fc(t){if("string"==typeof t){var e=pc.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=pc.get(t),a={hostEl:n,cb:i,cbPayload:r};return o?!vc(e=o.image)&&o.pending.push(a):((e=Yn.loadImage(t,mc,mc)).__zrImageSrc=t,pc.put(t,e.__cachedImgObj={image:e,pending:[a]})),e}return t}return e}function mc(){var t=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=s;c++)l-=s;var u=$s(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=$s(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?wc(e,r,o):a>0?Math.floor(e.length*r/a):0;a=$s(o,e=e.substr(0,l))}""===e&&(e=n.placeholder),t.textLine=e,t.isTruncated=!0}function wc(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=Ic(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=Os(u),v=0;v=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}(t)||!!Tc[t]}function Ic(t,e,n,i,r){for(var o=[],a=[],s="",l="",c=0,u=0,d=Os(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 Dc(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;no.set(Pc,Ws(n,a,r),js(i,s,o),a,s),no.intersect(e,Pc,null,Lc);var l=Lc.outIntersectRect;t.outerWidth=l.width,t.outerHeight=l.height,t.baseX=Ws(l.x,l.width,r,!0),t.baseY=js(l.y,l.height,o,!0)}}var Pc=new no(0,0,0,0),Lc={outIntersectRect:{},clamp:!0};function Ec(t){return null!=t?t+="":t=""}function Nc(t,e,n,i){var r=new no(Ws(t.x||0,e,t.textAlign),js(t.y||0,n,t.textBaseline),e,n),o=null!=i?i:Rc(t)?t.lineWidth:0;return o>0&&(r.x-=o/2,r.y-=o/2,r.width+=o,r.height+=o),r}function Rc(t){var e=t.stroke;return null!=e&&"none"!==e&&t.lineWidth>0}var Oc="__zr_style_"+Math.round(10*Math.random()),zc={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},Hc={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};zc[Oc]=!0;var Bc=["z","z2","invisible"],$c=["invisible"],Fc=function(t){function e(e){return t.call(this,e)||this}var n;return y(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(Yc[0]=Gc(r)*n+t,Yc[1]=Uc(r)*i+e,Zc[0]=Gc(o)*n+t,Zc[1]=Uc(o)*i+e,c(s,Yc,Zc),u(l,Yc,Zc),(r%=Xc)<0&&(r+=Xc),(o%=Xc)<0&&(o+=Xc),r>o&&!a?o+=Xc:rr&&(Kc[0]=Gc(p)*n+t,Kc[1]=Uc(p)*i+e,c(s,Kc,s),u(l,Kc,l))}var ru={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},ou=[],au=[],su=[],lu=[],cu=[],uu=[],du=Math.min,hu=Math.max,pu=Math.cos,fu=Math.sin,gu=Math.abs,mu=Math.PI,vu=2*mu,yu="undefined"!=typeof Float32Array,_u=[];function bu(t){return Math.round(t/mu*1e8)/1e8%2*mu}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=gu(n/ws/t)||0,this._uy=gu(n/ws/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(ru.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(ru.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(ru.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(ru.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(),_u[0]=i,_u[1]=r,function(t,e){var n=bu(t[0]);n<0&&(n+=vu);var i=n-t[0],r=t[1];r+=i,!e&&r-n>=vu?r=n+vu:e&&n-r>=vu?r=n-vu:!e&&n>r?r=n+(vu-bu(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(){su[0]=su[1]=cu[0]=cu[1]=Number.MAX_VALUE,lu[0]=lu[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||gu(m)>i||d===e-1)&&(f=Math.sqrt(I*I+m*m),r=g,o=_);break;case ru.C:var v=t[d++],y=t[d++],_=(g=t[d++],t[d++]),b=t[d++],x=t[d++];f=Uo(r,o,v,y,g,_,b,x,10),r=b,o=x;break;case ru.Q:f=Ko(r,o,v=t[d++],y=t[d++],g=t[d++],_=t[d++],10),r=g,o=_;break;case ru.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=pu(M)*C+w,s=fu(M)*k+S),f=hu(C,k)*du(vu,Math.abs(T)),r=pu(A)*C+w,o=fu(A)*k+S;break;case ru.R:a=r=t[d++],s=o=t[d++],f=2*t[d++]+2*t[d++];break;case ru.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 ru.M:n=r=h[b++],i=o=h[b++],t.moveTo(r,o);break;case ru.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 ru.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){qo(r,T,I,P,k=(c-v)/X,ou),qo(o,A,D,L,k,au),t.bezierCurveTo(ou[1],au[1],ou[2],au[2],ou[3],au[3]);break t}v+=X}t.bezierCurveTo(T,A,I,D,P,L),r=P,o=L;break;case ru.Q:T=h[b++],A=h[b++],I=h[b++],D=h[b++];if(m){if(v+(X=l[y++])>c){Zo(r,T,I,k=(c-v)/X,ou),Zo(o,A,D,k,au),t.quadraticCurveTo(ou[1],au[1],ou[2],au[2]);break t}v+=X}t.quadraticCurveTo(T,A,I,D),r=I,o=D;break;case ru.A:var E=h[b++],N=h[b++],R=h[b++],O=h[b++],z=h[b++],H=h[b++],B=h[b++],$=!h[b++],F=R>O?R:O,V=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,$):t.arc(E,N,F,z,W,$),j)break t;w&&(n=pu(z)*R+E,i=fu(z)*O+N),r=pu(W)*R+E,o=fu(W)*O+N;break;case ru.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+du(G,q),s),(G-=q)>0&&t.lineTo(a+q,s+du(G,U)),(G-=U)>0&&t.lineTo(a+hu(q-G,0),s+U),(G-=q)>0&&t.lineTo(a,s+hu(U-G,0));break t}v+=X}t.rect(a,s,q,U);break;case ru.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=ru,t.initDefaultProps=((e=t.prototype)._saveData=!0,e._ux=0,e._uy=0,e._pendingPtDist=0,void(e._version=0)),t}();function wu(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+=Tu);var h=Math.atan2(l,s);return h<0&&(h+=Tu),h>=i&&h<=r||h+Tu>=i&&h+Tu<=r}function Iu(t,e,n,i,r,o){if(o>e&&o>i||or?s:0}var Du=xu.CMD,Pu=2*Math.PI;var Lu=[-1,-1,-1],Eu=[-1,-1];function Nu(){var t=Eu[0];Eu[0]=Eu[1],Eu[1]=t}function Ru(t,e,n,i,r,o,a,s,l,c){if(c>e&&c>i&&c>o&&c>s||c1&&Nu(),p=Fo(e,i,o,s,Eu[0]),h>1&&(f=Fo(e,i,o,s,Eu[1]))),2===h?me&&s>i&&s>o||s=0&&u<=1&&(r[l++]=u);else{var c=a*a-4*o*s;if(Bo(c))(u=-a/(2*o))>=0&&u<=1&&(r[l++]=u);else if(c>0){var u,d=Po(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,Lu);if(0===l)return 0;var c=Yo(e,i,o);if(c>=0&&c<=1){for(var u=0,d=Go(e,i,o,c),h=0;hn||s<-n)return 0;var l=Math.sqrt(n*n-s*s);Lu[0]=-l,Lu[1]=l;var c=Math.abs(i-r);if(c<1e-4)return 0;if(c>=Pu-1e-4){i=0,r=Pu;var u=o?1:-1;return a>=Lu[0]+t&&a<=Lu[1]+t?u:0}if(i>r){var d=i;i=r,r=d}i<0&&(i+=Pu,r+=Pu);for(var h=0,p=0;p<2;p++){var f=Lu[p];if(f+t>a){var g=Math.atan2(s,f);u=o?1:-1;g<0&&(g=Pu+g),(g>=i&&g<=r||g+Pu>=i&&g+Pu<=r)&&(g>Math.PI/2&&g<1.5*Math.PI&&(u=-u),h+=u)}}return h}function Hu(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+=Iu(u,d,h,p,i,r))),m&&(h=u=s[f],p=d=s[f+1]),g){case Du.M:u=h=s[f++],d=p=s[f++];break;case Du.L:if(n){if(wu(u,d,s[f],s[f+1],e,i,r))return!0}else c+=Iu(u,d,s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case Du.C:if(n){if(Su(u,d,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=Ru(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 Du.Q:if(n){if(Cu(u,d,s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=Ou(u,d,s[f++],s[f++],s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case Du.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+=Iu(u,d,o,a,i,r);var C=(i-v)*b/_+v;if(n){if(Au(v,y,b,x,x+w,S,e,C,r))return!0}else c+=zu(v,y,b,x,x+w,S,C,r);u=Math.cos(x+w)*_+v,d=Math.sin(x+w)*b+y;break;case Du.R:if(h=u=s[f++],p=d=s[f++],o=h+s[f++],a=p+s[f++],n){if(wu(h,p,o,p,e,i,r)||wu(o,p,o,a,e,i,r)||wu(o,a,h,a,e,i,r)||wu(h,a,h,p,e,i,r))return!0}else c+=Iu(o,p,o,a,i,r),c+=Iu(h,a,h,p,i,r);break;case Du.Z:if(n){if(wu(u,d,h,p,e,i,r))return!0}else c+=Iu(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+=Iu(u,d,h,p,i,r)||0),0!==c}var Bu=pi({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},zc),$u={style:pi({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},Hc.style)},Fu=Ns.concat(["invisible","culling","z","z2","zlevel","parent"]),Vu=function(t){function e(e){return t.call(this,e)||this}var n;return y(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?Ss:e>.2?"#eee":Cs}if(t)return Cs}return Ss},e.prototype.getInsideTextStroke=function(t){var e=this.style.fill;if(Mi(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 Hu(t,e,!0,n,i)}(o,a/s,t,e)))return!0}if(this.hasFill())return function(t,e,n){return Hu(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:hi(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(4&this.__dirty)},e.prototype.createStyle=function(t){return Yi(Bu,t)},e.prototype._innerSaveToNormal=function(e){t.prototype._innerSaveToNormal.call(this,e);var n=this._normalState;e.shape&&!n.shape&&(n.shape=hi({},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=hi({},i.shape),hi(s,n.shape)):(s=hi({},r?this.shape:i.shape),hi(s,n.shape)):l&&(s=i.shape),s)if(o){this.shape=hi({},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}(Vu);td.prototype.type="rect";var ed={fill:"#000"},nd={},id={style:pi({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},Hc.style)},rd=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 y(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=bc(g,c,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),x={},w=0;w0,k=0;kg&&Mc(o,a.substring(g,m),e,f),Mc(o,h[2],e,f,h[1]),g=yc.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&&md(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=fd(r,o,d),c-=t.height/2-d[0]-t.innerHeight/2);var h=this._getOrCreateChild(ju),p=h.createStyle();h.useStyle(p);var f=this._defaultStyle,g=!1,m=0,v=!1,y=pd("fill"in s?s.fill:"fill"in e?e.fill:(g=!0,f.fill)),_=hd("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||qn,p.opacity=zi(s.opacity,e.opacity,1),cd(p,s),_&&(p.lineWidth=zi(s.lineWidth,e.lineWidth,m),p.lineDash=Oi(s.lineDash,e.lineDash),p.lineDashOffset=e.lineDashOffset||0,p.stroke=_),y&&(p.fill=y),h.setBoundingRect(Nc(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=Oi(t.fillOpacity,1);else if(h){(s=this._getOrCreateChild(Gu)).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=Oi(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=zi(t.opacity,e.opacity,1)},e.makeFont=function(t){var e="";return ud(t)&&(e=[t.fontStyle,t.fontWeight,ld(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),e&&Fi(e)||t.textFont||t.font},e}(Fc),od={left:!0,right:1,center:1},ad={top:1,bottom:1,middle:1},sd=["fontStyle","fontWeight","fontSize","fontFamily"];function ld(t){return"string"!=typeof t||-1===t.indexOf("px")&&-1===t.indexOf("rem")&&-1===t.indexOf("em")?isNaN(+t)?"12px":t+"px":t}function cd(t,e){for(var n=0;n=0,o=!1;if(t instanceof Vu){var a=bd(t),s=r&&a.selectFill||a.normalFill,l=r&&a.selectStroke||a.normalStroke;if(Dd(s)||Dd(l)){var c=(i=i||{}).style||{};"inherit"===c.fill?(o=!0,i=hi({},i),(c=hi({},c)).fill=s):!Dd(c.fill)&&Dd(s)?(o=!0,i=hi({},i),(c=hi({},c)).fill=Sa(s)):!Dd(c.stroke)&&Dd(l)&&(o||(i=hi({},i),c=hi({},c)),c.stroke=Sa(l)),i.style=c}}if(i&&null==i.z2){o||(i=hi({},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=fi(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 ih(t,e,n){lh(t,!0),Bd(t,Vd),function(t,e,n){var i=vd(t);null!=e?(i.focus=e,i.blurScope=n):i.focus&&(i.focus=null)}(t,e,n)}function rh(t,e,n,i){i?function(t){lh(t,!1)}(t):ih(t,e,n)}var oh=["emphasis","blur","select"],ah={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function sh(t,e,n,i){n=n||"itemStyle";for(var r=0;r1&&(a*=mh(f),s*=mh(f));var g=(r===o?-1:1)*mh((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+yh(d)*m-vh(d)*v,_=(e+i)/2+vh(d)*m+yh(d)*v,b=wh([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=wh(x,w);if(xh(x,w)<=-1&&(S=_h),xh(x,w)>=1&&(S=0),S<0){var C=Math.round(S/_h*1e6)/1e6;S=2*_h+C%2*_h}u.addData(c,y,_,a,s,b,S,d,o)}var Ch=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,kh=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;var Mh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return y(e,t),e.prototype.applyTransform=function(t){},e}(Vu);function Th(t){return null!=t.setData}function Ah(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(Ch);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 qh(t,e){var n,i=Fh(e.r,0),r=Fh(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=Bh(l-s),p=h>Nh&&h%Nh;if(p>Wh&&(h=p),i>Wh)if(h>Nh-Wh)t.moveTo(c+i*Oh(s),u+i*Rh(s)),t.arc(c,u,i,s,l,!d),r>Wh&&(t.moveTo(c+r*Oh(l),u+r*Rh(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*Oh(s),P=i*Rh(s),L=r*Oh(l),E=r*Rh(l),N=h>Wh;if(N){var R=e.cornerRadius;R&&(n=function(t){var e;if(Ci(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=Bh(i-r)/2;if(y=Vh(O,m),_=Vh(O,v),b=Vh(O,f),x=Vh(O,g),C=w=Fh(y,_),k=S=Fh(b,x),(w>Wh||S>Wh)&&(M=i*Oh(l),T=i*Rh(l),A=r*Oh(s),I=r*Rh(s),hWh){var j=Vh(m,C),q=Vh(v,C),U=jh(A,I,D,P,i,j,d),G=jh(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,Hh(U.y0,U.x0),Hh(U.y1,U.x1),!d),t.arc(c,u,i,Hh(U.cy+U.y1,U.cx+U.x1),Hh(G.cy+G.y1,G.cx+G.x1),!d),q>0&&t.arc(c+G.cx,u+G.cy,q,Hh(G.y1,G.x1),Hh(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>Wh&&N)if(k>Wh){j=Vh(f,k),U=jh(L,E,M,T,r,-(q=Vh(g,k)),d),G=jh(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,Hh(U.y0,U.x0),Hh(U.y1,U.x1),!d),t.arc(c,u,r,Hh(U.cy+U.y1,U.cx+U.x1),Hh(G.cy+G.y1,G.cx+G.x1),d),j>0&&t.arc(c+G.cx,u+G.cy,j,Hh(G.y1,G.x1),Hh(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 Uh=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},Gh=function(t){function e(e){return t.call(this,e)||this}return y(e,t),e.prototype.getDefaultShape=function(){return new Uh},e.prototype.buildPath=function(t,e){qh(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(Vu);Gh.prototype.type="sector";var Xh=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},Yh=function(t){function e(e){return t.call(this,e)||this}return y(e,t),e.prototype.getDefaultShape=function(){return new Xh},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}(Vu);function Zh(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;hyp[1]){if(r=!1,_p.negativeSize||n)return r;var s=mp(yp[0]-vp[1]),l=mp(vp[0]-yp[1]);fp(s,l)>xp.len()&&(s=l||!_p.bidirectional)&&(Vr.scale(bp,a,-l*i),_p.useDir&&_p.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 Tp(t,e,n,i,r,o){Mp("update",t,e,n,i,r,o)}function Ap(t,e,n,i,r,o){Mp("enter",t,e,n,i,r,o)}function Ip(t){if(!t.__zr)return!0;for(var e=0;e=-1e-6)return!1;var f=t-r,g=e-o,m=Yp(f,g,c,u)/p;if(m<0||m>1)return!1;var v=Yp(f,g,d,h)/p;return!(v<0||v>1)}function Yp(t,e,n,i){return t*i-n*e}function Zp(t,e,n,i,r){return null==e||(Ai(e)?Kp[0]=Kp[1]=Kp[2]=Kp[3]=e:(Kp[0]=e[0],Kp[1]=e[1],Kp[2]=e[2],Kp[3]=e[3]),i&&(Kp[0]=pl(0,Kp[0]),Kp[1]=pl(0,Kp[1]),Kp[2]=pl(0,Kp[2]),Kp[3]=pl(0,Kp[3])),n&&(Kp[0]=-Kp[0],Kp[1]=-Kp[1],Kp[2]=-Kp[2],Kp[3]=-Kp[3]),Qp(t,Kp,"x","width",3,1,r&&r[0]||0),Qp(t,Kp,"y","height",0,2,r&&r[1]||0)),t}var Kp=[0,0,0,0];function Qp(t,e,n,i,r,o,a){var s=e[o]+e[r],l=t[i];t[i]+=s,a=pl(0,hl(a,l)),t[i]=0?-e[r]:e[o]>=0?l+e[o]:fl(s)>1e-8?(l-a)*e[r]/s:0):t[n]-=e[r]}function Jp(t){var e=t.itemTooltipOption,n=t.componentModel,i=t.itemName,r=Mi(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&&vi(xi(l),function(t){Zi(s,t)||(s[t]=l[t],s.$vars.push(t))});var c=vd(t.el);c.componentMainType=o,c.componentIndex=a,c.tooltipConfig={name:i,option:pi({content:i,encodeHTMLContent:!0,formatterParams:s},r)}}function tf(t,e){var n;t.isGroup&&(n=e(t)),n||t.traverse(e)}function ef(t,e){if(t)if(Ci(t))for(var n=0;ne&&(e=i),ie&&(n=e=0),{min:n,max:e}},clipPointsByRect:function(t,e){return yi(t,function(t){var n=t[0];n=pl(n,e.x),n=hl(n,e.x+e.width);var i=t[1];return i=pl(i,e.y),[n,i=hl(i,e.y+e.height)]})},clipRectByRect:function(t,e){var n=pl(t.x,e.x),i=hl(t.x+t.width,e.x+e.width),r=pl(t.y,e.y),o=hl(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:Gp,ensureCopyRect:of,ensureCopyTransform:af,expandOrShrinkRect:Zp,extendPath:function(t,e){return Rp(t,e)},extendShape:function(t){return Vu.extend(t)},getShapeClass:function(t){if(Lp.hasOwnProperty(t))return Lp[t]},getTransform:function(t,e){for(var n=Or([]);t&&t!==e;)Hr(n,t.getLocalTransform(),n),t=t.parent;return n},groupTransition:Up,initProps:Ap,isBoundingRectAxisAligned:nf,isElementRemoved:Ip,lineLineIntersect:Xp,linePolygonIntersect:function(t,e,n,i,r){for(var o=0,a=r[r.length-1];ofl(o[1])?o[0]>0?"right":"left":o[1]>0?"bottom":"top"},traverseElements:ef,traverseUpdateZ:lf,updateProps:Tp}),df={};function hf(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=ki(t.defaultText)?t.defaultText(o,t,n):t.defaultText);for(var l={normal:i},c=0;c-1?Hf:$f;function jf(t,e){t=t.toUpperCase(),Vf[t]=new Rf(e),Ff[t]=e}jf(Bf,{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:". "}}}}),jf(Hf,{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 qf(){return null}var Uf=1e3,Gf=6e4,Xf=36e5,Yf=864e5,Zf=31536e6,Kf={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})/},Qf={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}"},Jf="{yyyy}-{MM}-{dd}",tg={year:"{yyyy}",month:"{yyyy}-{MM}",day:Jf,hour:Jf+" "+Qf.hour,minute:Jf+" "+Qf.minute,second:Jf+" "+Qf.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 ig(t){return Mi(t)||ki(t)?t:function(t){t=t||{};var e={},n=!0;return vi(eg,function(e){n&&(n=null==t[e])}),vi(eg,function(i,r){var o=t[i];e[i]={};for(var a=null,s=r;s>=0;s--){var l=eg[s],c=Ii(o)&&!Ci(o)?o[l]:o,u=void 0;Ci(c)?a=(u=c.slice())[0]||"":Mi(c)?u=[a=c]:(null==a?a=Qf[i]:Kf[l].test(a)||(a=e[l][l][0]+" "+a),u=[a],n&&(u[1]="{primary|"+a+"}")),e[i][l]=u}}),e}(t)}function rg(t,e){return"0000".substr(0,e-(t+="").length)+t}function og(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 ag(t){return t===og(t)}function sg(t,e,n,i){var r=Cl(t),o=r[ug(n)](),a=r[dg(n)]()+1,s=Math.floor((a-1)/3)+1,l=r[hg(n)](),c=r["get"+(n?"UTC":"")+"Day"](),u=r[pg(n)](),d=(u-1)%12+1,h=r[fg(n)](),p=r[gg(n)](),f=r[mg(n)](),g=u>=12?"pm":"am",m=g.toUpperCase(),v=i instanceof Rf?i:function(t){return Vf[t]}(i||Wf)||Vf[$f],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,rg(o%100+"",2)).replace(/{Q}/g,s+"").replace(/{MMMM}/g,_[a-1]).replace(/{MMM}/g,b[a-1]).replace(/{MM}/g,rg(a,2)).replace(/{M}/g,a+"").replace(/{dd}/g,rg(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,x[c]).replace(/{ee}/g,w[c]).replace(/{e}/g,c+"").replace(/{HH}/g,rg(u,2)).replace(/{H}/g,u+"").replace(/{hh}/g,rg(d+"",2)).replace(/{h}/g,d+"").replace(/{mm}/g,rg(h,2)).replace(/{m}/g,h+"").replace(/{ss}/g,rg(p,2)).replace(/{s}/g,p+"").replace(/{SSS}/g,rg(f,3)).replace(/{S}/g,f+"")}function lg(t,e){var n=Cl(t),i=n[dg(e)]()+1,r=n[hg(e)](),o=n[pg(e)](),a=n[fg(e)](),s=n[gg(e)](),l=0===n[mg(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 cg(t,e,n){switch(e){case"year":t[yg(n)](0);case"month":t[_g(n)](1);case"day":t[bg(n)](0);case"hour":t[xg(n)](0);case"minute":t[wg(n)](0);case"second":t[Sg(n)](0)}return t}function ug(t){return t?"getUTCFullYear":"getFullYear"}function dg(t){return t?"getUTCMonth":"getMonth"}function hg(t){return t?"getUTCDate":"getDate"}function pg(t){return t?"getUTCHours":"getHours"}function fg(t){return t?"getUTCMinutes":"getMinutes"}function gg(t){return t?"getUTCSeconds":"getSeconds"}function mg(t){return t?"getUTCMilliseconds":"getMilliseconds"}function vg(t){return t?"setUTCFullYear":"setFullYear"}function yg(t){return t?"setUTCMonth":"setMonth"}function _g(t){return t?"setUTCDate":"setDate"}function bg(t){return t?"setUTCHours":"setHours"}function xg(t){return t?"setUTCMinutes":"setMinutes"}function wg(t){return t?"setUTCSeconds":"setSeconds"}function Sg(t){return t?"setUTCMilliseconds":"setMilliseconds"}function Cg(t){if(isNaN(Tl(t)))return Mi(t)?t:"-";var e=(t+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function kg(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 Mg=Bi;function Tg(t,e,n){function i(t){return t&&Fi(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?Cl(t):t;if(!isNaN(+s))return sg(s,"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}",n);if(a)return"-"}if("ordinal"===e)return Ti(t)?i(t):Ai(t)&&r(t)?t+"":"-";var l=Tl(t);return r(l)?Cg(l):Ti(t)?i(t):"boolean"==typeof t?t+"":"-"}var Ag=["a","b","c","d","e","f","g"],Ig=function(t,e){return"{"+t+(null==e?"":e)+"}"};function Dg(t,e,n){Ci(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 Ug(t,e,n){n=Mg(n||0);var i=e.width,r=e.height,o=ml(t.left,i),a=ml(t.top,r),s=ml(t.right,i),l=ml(t.bottom,r),c=ml(t.width,i),u=ml(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 no((e.x||0)+o+n[3],(e.y||0)+a+n[0],c,u);return f.margin=n,f}Si(qg,"vertical"),Si(qg,"horizontal");var Gg=1;function Xg(t,e,n){var i,r,o,a,s=t.boxCoordinateSystem;if(s){var l=function(t){var e=t.getShallow("coord",!0),n=Rg;if(null==e){var i=zg.get(t.type);i&&i.getCoord2&&(n=Og,e=i.getCoord2(t))}return{coord:e,from:n}}(t),c=l.coord,u=l.from;if(s.dataToLayout){o=Gg,a=u;var d=s.dataToLayout(c);i=d.contentRect||d.rect}}return null==o&&(o=Gg),o===Gg&&(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 Yg(t){var e=t.layoutMode||t.constructor.layoutMode;return Ii(e)?e:e?{type:e}:null}function Zg(t,e,n){var i=n&&n.ignoreSize;!Ci(i)&&(i=[i,i]);var r=a(jg[0],0),o=a(jg[1],1);function a(n,r){var o={},a=0,l={},c=0;if(Vg(n,function(e){l[e]=t[e]}),Vg(n,function(t){Zi(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=di(o,n[a],!0);e.defaultOption=o}return e.defaultOption},e.prototype.getReferringComponents=function(t,e){var n=t+"Index",i=t+"Id";return Jl(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}(Rf);oc(Jg,Rf),cc(Jg),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){var i=ic(t);e[i.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var o=ic(n).main;t.hasSubTypes(n)&&e[o]&&(r=e[o](i))}return r}}(Jg),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 vi(t,function(o){var a=n(i,o),s=function(t,e){var n=[];return vi(t,function(t){fi(e,t)>=0&&n.push(t)}),n}(a.originalDeps=e(o),t);a.entryCount=s.length,0===a.entryCount&&r.push(o),vi(s,function(t){fi(a.predecessor,t)<0&&a.predecessor.push(t);var e=n(i,t);fi(e.successor,t)<0&&e.successor.push(o)})}),{graph:i,noEntryList:r}}(i),s=a.graph,l=a.noEntryList,c={};for(vi(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]),vi(d.successor,h?f:p)}vi(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)}}}(Jg,function(t){var e=[];vi(Jg.getClassesByMainType(t),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=yi(e,function(t){return ic(t).main}),"dataset"!==t&&fi(e,"dataset")<=0&&e.unshift("dataset");return e});var tm={color:{},darkColor:{},size:{}},em=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 nm in hi(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 im=em[nm];"theme"===nm?tm.darkColor.theme=em.theme.slice():"highlight"===nm?tm.darkColor.highlight="rgba(255,231,130,0.4)":0===nm.indexOf("accent")?tm.darkColor[nm]=_a(im,0,function(t){return.5*t},function(t){return Math.min(1,1.3-t)}):tm.darkColor[nm]=_a(im,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 rm="";"undefined"!=typeof navigator&&(rm=navigator.platform||"");var om="rgba(0, 0, 0, 0.2)",am=tm.color.theme[0],sm=_a(am,0,null,.9),lm={darkMode:"auto",colorBy:"series",color:tm.color.theme,gradientColor:[sm,am],aria:{decal:{decals:[{color:om,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:om,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:om,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:om,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:om,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:om,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:rm.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},cm=Xi(["tooltip","label","itemName","itemId","itemGroupId","itemChildGroupId","seriesName"]),um="original",dm="arrayRows",hm="objectRows",pm="keyedColumns",fm="typedArray",gm="unknown",mm="column",vm="row",ym=1,_m=2,bm=3,xm=Xl();function wm(t,e,n){var i={},r=Sm(e);if(!r||!t)return i;var o,a,s=[],l=[],c=e.ecModel,u=xm(c).datasetMap,d=r.uid+"_"+n.seriesLayoutBy;vi(t=t.slice(),function(e,n){var r=Ii(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,Mm,i,r,t,e,n)},t.prototype.clearColorPalette=function(){!function(t,e){e(t).paletteIdx=0,e(t).paletteNameMap={}}(this,Mm)},t}();var Pm="\0_ec_inner",Lm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return y(e,t),e.prototype.init=function(t,e,n,i,r,o){i=i||{},this.option=null,this._theme=new Rf(i),this._locale=new Rf(r),this._optionManager=o},e.prototype.setOption=function(t,e,n){var i=Rm(e);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,e){return this._resetOption(t,Rm(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)):Im(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&&vi(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=Xi(),s=e&&e.replaceMergeMainTypeMap;xm(this).datasetMap=Xi(),vi(t,function(t,e){null!=t&&(Jg.hasClass(e)?e&&(o.push(e),a.set(e,!0)):n[e]=null==n[e]?ui(t):di(n[e],t,!0))}),s&&s.each(function(t,e){Jg.hasClass(e)&&!a.get(e)&&(o.push(e),a.set(e,!0))}),Jg.topologicalTravel(o,Jg.getAllClassMainTypes(),function(e){var o=function(t,e,n){var i=km.get(e);if(!i)return n;var r=i(t);return r?n.concat(r):n}(this,e,Ol(t[e])),a=i.get(e),l=a?s&&s.get(e)?"replaceMerge":"normalMerge":"replaceAll",c=Fl(a,o,l);(function(t,e,n){vi(t,function(t){var i=t.newOption;Ii(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,Jg),n[e]=null,i.set(e,null),r.set(e,0);var u,d=[],h=[],p=0;vi(c,function(t,n){var i=t.existing,r=t.newOption;if(r){var o="series"===e,a=Jg.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=hi({componentIndex:n},t.keyInfo);hi(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&&Tm(this)},this),this._seriesIndices||Tm(this)},e.prototype.getOption=function(){var t=ui(this.option);return vi(t,function(e,n){if(Jg.hasClass(n)){for(var i=Ol(e),r=i.length,o=!1,a=r-1;a>=0;a--)i[a]&&!Ul(i[a])?o=!0:(i[a]=null,!o&&r--);i.length=r,t[n]=i}}),delete t[Pm],t},e.prototype.setTheme=function(t){this._theme=new Rf(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 Fm=vi,Vm=Ii,Wm=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function jm(t){var e=t&&t.itemStyle;if(e)for(var n=0,i=Wm.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 Ev(this.getData(e),t)},t.prototype.formatTooltip=function(t,e,n){},t}();function Ov(t){var e,n;return Ii(t)?t.type&&(n=t):e=t,{text:e,frag:n}}function zv(t){return new Hv(t)}var Hv=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}(),Vv=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 $v(t,e)},t}();function Wv(t){if(!Yv(t.sourceFormat)){El("")}return t.data}function jv(t){var e=t.sourceFormat,n=t.data;if(!Yv(e)){El("")}if(e===dm){for(var i=[],r=0,o=n.length;r65535?Qv:Jv}function ry(){return[1/0,-1/0]}function oy(t){var e=t.constructor;return e===Array?t.slice():new e(t)}function ay(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=yi(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(iy(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 $v(t[i],this._dimensions[i])}Zv={arrayRows:t,objectRows:function(t,e,n,i){return $v(t[e],this._dimensions[i])},keyedColumns:t,original:function(t,e,n,i){var r=t&&(null==t.value?t:t.value);return $v(r instanceof Array?r[i]:r,this._dimensions[i])},typedArray:function(t,e,n,i){return t[i]}}}(),t}(),ly=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(cy(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=Pi(a=o.get("data",!0))?fm:um,e=[];var u=this._getSourceMetaRawOption()||{},d=l&&l.metaRawOption||{},h=Oi(u.seriesLayoutBy,d.seriesLayoutBy)||null,p=Oi(u.sourceHeader,d.sourceHeader),f=Oi(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&&uy("")}var o,a=[],s=[];return vi(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=Ol(t),i=n.length;i||El("");for(var r=0,o=i;r1||n>0&&!t.noHeader;return vi(t.blocks,function(t){var n=yy(t);n>=e&&(e=n+ +(i&&(!n||my(t)&&!t.noHeader)))}),e}return 0}function _y(t,e,n,i){var r,o=e.noHeader,a=(r=yy(e),{html:py[r],richText:fy[r]}),s=[],l=e.blocks||[];$i(!l||Ci(l)),l=l||[];var c=t.orderMode;if(e.sortBlocks&&c){l=l.slice();var u={valueAsc:"asc",valueDesc:"desc"};if(Zi(u,c)){var d=new Fv(u[c],null);l.sort(function(t,e){return d.evaluate(t.sortParam,e.sortParam)})}else"seriesDesc"===c&&l.reverse()}vi(l,function(n,r){var o=e.valueFormatter,l=vy(n)(o?hi(hi({},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):wy(i,s.join(""),o?n:a.html);if(o)return h;var p=Tg(e.header,"ordinal",t.useUTC),f=hy(i,t.renderMode).nameStyle,g=dy(i);return"richText"===t.renderMode?Sy(t,p,f)+a.richText+h:wy(i,'
'+Sr(p)+"
"+h,n)}function by(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 yi(t=Ci(t)?t:[t],function(t,e){return Tg(t,Ci(p)?p[e]:p,c)})};if(!o||!a){var d=s?"":t.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||tm.color.secondary,r),h=o?"":Tg(l,"ordinal",c),p=e.valueType,f=a?[]:u(e.value,e.dataIndex),g=!s||!o,m=!s&&o,v=hy(i,r),y=v.nameStyle,_=v.valueStyle;return"richText"===r?(s?"":d)+(o?"":Sy(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(Ci(e)?e.join(" "):e,o)}(t,f,g,m,_)):wy(i,(s?"":d)+(o?"":function(t,e,n){return''+Sr(t)+""}(h,!s,y))+(a?"":function(t,e,n,i){var r=n?"10px":"20px",o=e?"float:right;margin-left:"+r:"";return t=Ci(t)?t:[t],''+yi(t,function(t){return Sr(t)}).join("  ")+""}(f,g,m,_)),n)}}function xy(t,e,n,i,r,o){if(t)return vy(t)({useUTC:r,renderMode:n,orderMode:i,markupStyleCreator:e,valueFormatter:t.valueFormatter},t,0,o)}function wy(t,e,n){return'
'+e+'
'}function Sy(t,e,n){return t.markupStyleCreator.wrapRichTextStyle(e,n)}function Cy(t,e){var n=t.get("padding");return null!=n?n:"richText"===e?[8,10]:10}var ky=function(){function t(){this.richTextStyles={},this._nextStyleNameId=Al()}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=Mi(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 Mi(r)?r:(this.richTextStyles[i]=r.style,r.content)},t.prototype.wrapRichTextStyle=function(t,e){var n={};Ci(e)?vi(e,function(t){return hi(n,t)}):hi(n,e);var i=this._generateStyleName();return this.richTextStyles[i]=n,"{"+i+"|"+t+"}"},t}();function My(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=Ci(d),p=function(t,e){return Pg(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=_i(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?vi(i,function(t){u(Ev(o,n,t),t)}):vi(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=Ev(l,a,c[0]),n=g.type}else r=e=h?d[0]:d;var m=ql(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:!Fi(_),value:e,valueType:n,dataIndex:a})].concat(i||[])})}var Ty=Xl();function Ay(t,e){return t.getName(e)||t.getId(e)}var Iy=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._selectedDataIndicesMap={},e}var n;return y(e,t),e.prototype.init=function(t,e,n){this.seriesIndex=this.componentIndex,this.dataTask=zv({count:Py,reset:Ly}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),(Ty(this).sourceManager=new ly(this)).prepareSource();var i=this.getInitialData(t,n);Ny(i,this),this.dataTask.context.data=i,Ty(this).dataBeforeProcessed=i,Dy(this),this._initSelectedMapFromData(i)},e.prototype.mergeDefaultAndTheme=function(t,e){var n=Yg(this),i=n?Kg(t):{},r=this.subType;Jg.hasClass(r)&&(r+="Series"),di(t,e.getTheme().get(this.subType)),di(t,this.getDefaultOption()),zl(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&Zg(t,i,n)},e.prototype.mergeOption=function(t,e){t=di(this.option,t,!0),this.fillDataTextStyle(t.data);var n=Yg(this);n&&Zg(this.option,t,n);var i=Ty(this).sourceManager;i.dirty(),i.prepareSource();var r=this.getInitialData(t,e);Ny(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,Ty(this).dataBeforeProcessed=r,Dy(this),this._initSelectedMapFromData(r)},e.prototype.fillDataTextStyle=function(t){if(t&&!Pi(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 My({series:this,dataIndex:t,multipleSeries:e})},e.prototype.isAnimationEnabled=function(){var t=this.ecModel;if(Wn.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=Dm.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[Ay(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){Ii(r.selectedMap)||(r.selectedMap={});for(var s=r.selectedMap,l=0;l0&&this._innerSelect(t,e)}},e.registerClass=function(t){return Jg.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}(Jg);function Dy(t){var e=t.name;ql(t)||(t.name=function(t){var e=t.getRawData(),n=e.mapDimensionsAll("seriesName"),i=[];return vi(n,function(t){var n=e.getDimensionInfo(t);n.displayName&&i.push(n.displayName)}),i.join(" ")}(t)||e)}function Py(t){return t.model.getRawData().count()}function Ly(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),Ey}function Ey(t,e){e.outputData&&t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function Ny(t,e){vi(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 Ky(t,e,n,i){var r=t[e];if(r){var o=r[Gy]||r,a=r[Yy];if(r[Xy]!==n||a!==i){if(null==n||!i)return t[e]=o;(r=t[e]=Zy(o,n,"debounce"===i))[Gy]=o,r[Yy]=i,r[Xy]=n}return r}}function Qy(t,e){var n=t[e];n&&n[Gy]&&(n.clear&&n.clear(),t[e]=n[Gy])}var Jy=Xl(),t_={itemStyle:uc(Lf,!0),lineStyle:uc(If,!0)},e_={lineStyle:"stroke",itemStyle:"fill"};function n_(t,e){var n=t.visualStyleMapper||t_[e];return n||(console.warn("Unknown style type '"+e+"'."),t_.itemStyle)}function i_(t,e){var n=t.visualDrawType||e_[e];return n||(console.warn("Unknown style type '"+e+"'."),"fill")}var r_={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=i_(t,i),l=o[s],c=ki(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||ki(o.fill)?d:o.fill,o.stroke="auto"===o.stroke||ki(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=hi({},o);r[s]=c(i),e.setItemVisual(n,"style",r)}}}},o_=new Rf,a_={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]){o_.option=n[i];var a=r(o_);hi(t.ensureUniqueItemVisual(e,"style"),a),o_.option.decal&&(t.setItemVisual(e,"decal",o_.option.decal),o_.option.decal.dirty=!0),o in a&&t.setItemVisual(e,"colorFromPalette",!1)}}:null}}}},s_={performRawSeries:!0,overallReset:function(t){var e=Xi();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)),Jy(t).scope=r}}),t.eachSeries(function(e){if(!e.isColorBySeries()&&!t.isSeriesFiltered(e)){var n=e.getRawData(),i={},r=e.getData(),o=Jy(e).scope,a=e.visualStyleAccessPath||"itemStyle",s=i_(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)}})}})}},l_=Math.PI;var c_=function(){function t(t,e,n,i){this._stageTaskMap=Xi(),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=Xi();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;vi(this._allHandlers,function(i){var r=t.get(i.uid)||t.set(i.uid,{});$i(!(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))}vi(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=Xi(),s=t.seriesType,l=t.getTargetSeries;function c(e){var s=e.uid,l=a.set(s,o&&o.get(s)||zv({plan:f_,reset:g_,count:y_}));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||zv({reset:u_});o.context={ecModel:n,api:i,overallReset:t.overallReset,scheduler:r};var a=o.agentStubMap,s=o.agentStubMap=Xi(),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,zv({reset:d_,onDirty:p_})));n.context={model:t,overallProgress:u},n.agent=o,n.__block=u,r._pipe(t,n)}$i(!t.createOnAllSeries,""),l?n.eachRawSeriesByType(l,h):c?c(n,i).each(h):(u=!1,vi(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 ki(t)&&(t={overallReset:t,seriesType:__(t)}),t.uid=zf("stageHandler"),e&&(t.visualType=e),t},t}();function u_(t){t.overallReset(t.ecModel,t.api,t.payload)}function d_(t){return t.overallProgress&&h_}function h_(){this.agent.dirty(),this.getDownstream().dirty()}function p_(){this.agent&&this.agent.dirty()}function f_(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=Ol(t.reset(t.model,t.ecModel,t.api,t.payload));return e.length>1?yi(e,function(t,e){return v_(e)}):m_}var m_=v_(0);function v_(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}(),P_=["symbol","symbolSize","symbolRotate","symbolOffset"],L_=P_.concat(["symbolKeepAspect"]),E_={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&&Z_(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=Z_(i)?i:0,r=Z_(r)?r:1,o=Z_(o)?o:0,a=Z_(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]:Ai(e)?[e]:Ci(e)?e:null:null),o=i.lineDashOffset;if(r){var a=i.strokeNoScale&&t.getLineScale?t.getLineScale():1;a&&1!==a&&(r=yi(r,function(t){return t/a}),o/=a)}return[r,o]}var eb=new xu(!0);function nb(t){var e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))}function ib(t){return"string"==typeof t&&"none"!==t}function rb(t){var e=t.fill;return null!=e&&"none"!==e}function ob(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 ab(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 sb(t,e,n){var i=gc(e.image,e.__image,n);if(vc(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)*Qi),o.scaleSelf(e.scaleX||1,e.scaleY||1),r.setTransform(o)}return r}}var lb=["shadowBlur","shadowOffsetX","shadowOffsetY"],cb=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function ub(t,e,n,i,r){var o=!1;if(!i&&e===(n=n||{}))return!1;if(i||e.opacity!==n.opacity){pb(t,r),o=!0;var a=Math.max(Math.min(e.opacity,1),0);t.globalAlpha=isNaN(a)?zc.opacity:a}(i||e.blend!==n.blend)&&(o||(pb(t,r),o=!0),t.globalCompositeOperation=e.blend||zc.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[Ab])if(this._disposed)this.id;else{var i,r,o;if(Ii(e)&&(n=e.lazyUpdate,i=e.silent,r=e.replaceMerge,o=e.transition,e=e.notMerge),this[Ab]=!0,ex(this),!this._model||e){var a=new Bm(this._api),s=this._theme,l=this._model=new Lm;l.scheduler=this._scheduler,l.ssr=this._ssr,l.init(null,null,null,s,this._locale,a)}this._model.setOption(t,{replaceMerge:r},dx);var c={seriesTransition:o,optionChanged:!0};if(n)this[Db]={silent:i,updateParams:c},this[Ab]=!1,this.getZr().wakeUp();else{try{zb(this),$b.update.call(this,null,c)}catch(t){throw this[Db]=null,this[Ab]=!1,t}this._ssr||this._zr.flush(),this[Db]=null,this[Ab]=!1,jb.call(this,i),qb.call(this,i)}}},e.prototype.setTheme=function(t,e){if(!this[Ab])if(this._disposed)this.id;else{var n=this._model;if(n){var i=e&&e.silent,r=null;this[Db]&&(null==i&&(i=this[Db].silent),r=this[Db].updateParams,this[Db]=null),this[Ab]=!0,ex(this);try{this._updateTheme(t),n.setTheme(this._theme),zb(this),$b.update.call(this,{type:"setTheme"},r)}catch(t){throw this[Ab]=!1,t}this[Ab]=!1,jb.call(this,i),qb.call(this,i)}}},e.prototype._updateTheme=function(t){Mi(t)&&(t=px[t]),t&&((t=ui(t))&&av(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||Wn.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 vi(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;vi(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 vi(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(mx[n]){var a=o,s=o,l=-1/0,c=-1/0,u=[],d=t&&t.pixelRatio||this.getDevicePixelRatio();vi(gx,function(o,d){if(o.group===n){var h=e?o.getZr().painter.getSvgDom().innerHTML:o.renderToCanvas(ui(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=Yn.createCanvas(),g=ul(f,{renderer:e?"svg":"canvas"});if(g.resize({width:h,height:p}),e){var m="";return vi(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}})),vi(u,function(t){var e=new Gu({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 Fb(this,"convertToPixel",t,e,n)},e.prototype.convertToLayout=function(t,e,n){return Fb(this,"convertToLayout",t,e,n)},e.prototype.convertFromPixel=function(t,e,n){return Fb(this,"convertFromPixel",t,e,n)},e.prototype.containPixel=function(t,e){var n;if(!this._disposed)return vi(Zl(this._model,t),function(t,i){i.indexOf("Models")>=0&&vi(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=Zl(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;vi(ax,function(e){var n=function(n){var i,r=t.getModel(),o=n.target;if("globalout"===e?i={}:o&&O_(o,function(t){var e=vd(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=hi({},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;vi(cx,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?(R_("map","selectchanged",e,i,t),R_("pie","selectchanged",e,i,t)):"select"===t.fromAction?(R_("map","selected",e,i,t),R_("pie","selected",e,i,t)):"unselect"===t.fromAction&&(R_("map","unselected",e,i,t),R_("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(),yx,"");var t=this,e=t._api,n=t._model;vi(t._componentsViews,function(t){t.dispose(n,e)}),vi(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 gx[t.id]}},e.prototype.resize=function(t){if(!this[Ab])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[Db]&&(null==i&&(i=this[Db].silent),n=!0,this[Db]=null),this[Ab]=!0,ex(this);try{n&&zb(this),$b.update.call(this,{type:"resize",animation:hi({duration:0},t&&t.animation)})}catch(t){throw this[Ab]=!1,t}this[Ab]=!1,jb.call(this,i),qb.call(this,i)}}},e.prototype.showLoading=function(t,e){if(this._disposed)this.id;else if(Ii(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),fx[t]){var n=fx[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=hi({},t);return e.type=lx[t.type],e},e.prototype.dispatchAction=function(t,e){if(this._disposed)this.id;else if(Ii(e)||(e={silent:!!e}),sx[t.type]&&this._model)if(this[Ab])this._pendingActions.push(t);else{var n=e.silent;Wb.call(this,t,n);var i=e.flush;i?this._zr.flush():!1!==i&&Wn.browser.weChat&&this._throttledZrFlush(),jb.call(this,n),qb.call(this,n)}},e.prototype.updateLabelLayout=function(){Sb.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(Ip(t))return;if(t instanceof Vu&&function(t){var e=bd(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)}})}zb=function(t){var e=t._scheduler;e.restorePipelines(t._model),e.prepareStageTasks(),Hb(t,!0),Hb(t,!1),e.plan()},Hb=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")&&!Wn.node&&!Wn.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),Sb.trigger("series:afterupdate",e,o,s)},Jb=function(t){t[Pb]=!0,t.getZr().wakeUp()},ex=function(t){t[Ib]=(t[Ib]+1)%1e3},tx=function(t){t[Pb]&&(t.getZr().storage.traverse(function(t){Ip(t)||e(t)}),t[Pb]=!1)},Kb=function(t){return new(function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return y(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){qd(e,n),Jb(t)},n.prototype.leaveEmphasis=function(e,n){Ud(e,n),Jb(t)},n.prototype.enterBlur=function(e){!function(t){Bd(t,Nd)}(e),Jb(t)},n.prototype.leaveBlur=function(e){Gd(e),Jb(t)},n.prototype.enterSelect=function(e){Xd(e),Jb(t)},n.prototype.leaveSelect=function(e){Yd(e),Jb(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[Ib]},n}(zm))(t)},Qb=function(t){function e(t,e){for(var n=0;n=0)){Tx.push(n);var o=c_.wrapStageHandler(n,r);o.__prio=e,o.__raw=n,t.push(o)}}function Ix(t,e){fx[t]=e}var Dx=function(t){var e=(t=ui(t)).type;e||El("");var n=e.split(":");2!==n.length&&El("");var i=!1;"echarts"===n[0]&&(e=n[1],i=!0),t.__isBuiltIn=i,Gv.set(e,t)};function Px(t,e,n,i){return{eventContent:{selected:nh(n),isFromClick:e.isFromClick||!1}}}function Lx(t){return null==t?0:t.length||1}function Ex(t){return t}Mx(kb,r_),Mx(Mb,a_),Mx(Mb,s_),Mx(kb,E_),Mx(Mb,N_),Mx(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=_b(n,e))});var r=i.getVisual("decal");if(r)i.getVisual("style").decal=_b(r,e)}})}),xx(av),Sx(900,function(t){var e=Xi();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(),vi(t,function(e,n){e.data.setCalculationInfo("stackedOnSeries",n>0?t[n-1].seriesModel:null)}),function(t){vi(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=bl(p,v),f=v;break}}}return i[0]=p,i[1]=f,i})})}(t))})}),Ix("default",function(t,e){pi(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 ol,i=new td({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});n.add(i);var r,o=new rd({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 cp({shape:{startAngle:-l_/2,endAngle:-l_/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*l_/2}).start("circularInOut"),r.animateShape(!0).when(1e3,{startAngle:3*l_/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}),kx({type:Cd,event:Cd,update:Cd},Ki),kx({type:kd,event:kd,update:kd},Ki),kx({type:Md,event:Id,update:Md,action:Ki,refineEvent:Px,publishNonRefinedEvent:!0}),kx({type:Td,event:Id,update:Td,action:Ki,refineEvent:Px,publishNonRefinedEvent:!0}),kx({type:Ad,event:Id,update:Ad,action:Ki,refineEvent:Px,publishNonRefinedEvent:!0}),bx("default",{}),bx("dark",I_);var Nx=function(){function t(t,e,n,i,r,o){this._old=t,this._new=e,this._oldKeyGetter=n||Ex,this._newKeyGetter=i||Ex,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 qx,Ux,Gx,Xx,Yx,Zx,Kx,Qx=Ii,Jx=yi,tw="undefined"==typeof Int32Array?Array:Int32Array,ew=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],nw=["_approximateExtent"],iw=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;Fx(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===um&&!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&&(Ci(r=this.getVisual(e))?r=r.slice():Qx(r)&&(r=hi({},r)),i[e]=r),r},t.prototype.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{};this._itemVisuals[t]=i,Qx(e)?hi(i,e):i[e]=n},t.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},t.prototype.setLayout=function(t,e){Qx(t)?hi(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?hi(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=vd(i);r.dataIndex=n,r.dataType=e,r.seriesIndex=t,r.ssrType="chart","group"===i.type&&i.traverse(function(i){var r=vd(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){vi(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:Jx(this.dimensions,this._getDimInfo,this),this.hostModel)),Yx(e,this),e._store=this._store,e},t.prototype.wrapMethod=function(t,e){var n=this[t];ki(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(t),this[t]=function(){var t=n.apply(this,arguments);return e.apply(this,[t].concat(Hi(arguments)))})},t.internalField=(qx=function(t){var e=t._invertedIndicesMap;vi(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 rw(t,e){fv(t)||(t=mv(t));var n=(e=e||{}).coordDimensions||[],i=e.dimensionsDefine||t.dimensionsDefine||[],r=Xi(),o=[],a=function(t,e,n,i){var r=Math.max(t.dimensionsDetectedCount||1,e.length,n.length,i||0);return vi(e,function(t){var e;Ii(t)&&(e=t.dimsDef)&&(r=Math.max(r,e.length))}),r}(t,n,i,e.dimensionsCount),s=e.canOmitUnusedDimensions&&jx(a),l=i===t.dimensionsDefine,c=l?Wx(t):Vx(i),u=e.encodeDefine;!u&&e.encodeDefaulter&&(u=e.encodeDefaulter(t,a));for(var d=Xi(u),h=new ty(a),p=0;p0&&(i.name=r+(o-1)),o++,e.set(r,o)}}(o),new $x({source:t,dimensions:o,fullDimensionCount:a,dimensionOmitted:s})}function ow(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 aw=function(t){this.coordSysDims=[],this.axisMap=Xi(),this.categoryAxisMap=Xi(),this.coordSysName=t};var sw={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis",Ql).models[0],o=t.getReferringComponents("yAxis",Ql).models[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",o),lw(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),lw(o)&&(i.set("y",o),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis",Ql).models[0];e.coordSysDims=["single"],n.set("single",r),lw(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar",Ql).models[0],o=r.findAxisModel("radiusAxis"),a=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",o),n.set("angle",a),lw(o)&&(i.set("radius",o),e.firstCategoryDimIndex=0),lw(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();vi(o.parallelAxisIndex,function(t,o){var s=r.getComponent("parallelAxis",t),l=a[o];n.set(l,s),lw(s)&&(i.set(l,s),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=o))})},matrix:function(t,e,n,i){var r=t.getReferringComponents("matrix",Ql).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 lw(t){return"category"===t.get("type")}function cw(t,e,n){var i,r,o,a=(n=n||{}).byIndex,s=n.stackedCoordDimension;!function(t){return!Fx(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(vi(i,function(t,e){Mi(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;vi(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 uw(t,e){return!!e&&e===t.getCalculationInfo("stackedDimension")}function dw(t,e,n){n=n||{};var i,r,o=e.getSourceManager();r=(i=o.getSource()).sourceFormat===um;var a=function(t){var e=t.get("coordinateSystem"),n=new aw(e),i=sw[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}(e),s=function(t,e){var n,i=t.get("coordinateSystem"),r=Ng.get(i);return e&&e.coordSysDims&&(n=yi(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=ki(l)?l:l?Si(wm,s,e):null,u=rw(i,{coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:e.getEncode(),encodeDefaulter:c,canOmitUnusedDimensions:!r}),d=function(t,e,n){var i,r;return n&&vi(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=cw(e,{schema:u,store:h}),f=new iw(u,e);f.setCalculationInfo(p);var g=null!=d&&function(t){if(t.sourceFormat===um){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]),mw(t,0,e),mw(t,1,e),t[0]>t[1]&&(t[0]=t[1])}(o.niceTickExtent=[yl(Math.ceil(t[0]/a)*a,s),yl(Math.floor(t[1]/a)*a,s)],t),o}function fw(t){var e=Math.pow(10,kl(t)),n=t/e;return n?2===n?n=3:3===n?n=5:n*=2:n=1,yl(n*e)}function gw(t){return _l(t)+2}function mw(t,e,n){t[e]=Math.max(Math.min(t[e],n[1]),n[0])}function vw(t,e){return t>=e[0]&&t<=e[1]}var yw=function(){function t(){this.normalize=_w,this.scale=bw}return t.prototype.updateMethods=function(t){t.hasBreaks()?(this.normalize=wi(t.normalize,t),this.scale=wi(t.scale,t)):(this.normalize=_w,this.scale=bw)},t}();function _w(t,e){return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])}function bw(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 ww=function(){function t(t){this._calculator=new yw,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}();cc(ww);var Sw=0,Cw=function(){function t(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this.uid=++Sw,this._onCollect=t.onCollect}return t.createByAxisModel=function(e){var n=e.option,i=n.data,r=i&&yi(i,kw);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(!Mi(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=Xi(this.categories))},t}();function kw(t){return Ii(t)&&null!=t.value?t.value:t+""}var Mw=function(t){function e(e){var n=t.call(this,e)||this;n.type="ordinal";var i=n.getSetting("ordinalMeta");return i||(i=new Cw({})),Ci(i)&&(i=new Cw({categories:yi(i,function(t){return Ii(t)?t.value:t})})),n._ordinalMeta=i,n._extent=n.getSetting("extent")||[0,i.categories.length-1],n}return y(e,t),e.prototype.parse=function(t){return null==t?NaN:Mi(t)?this._ordinalMeta.getOrdinal(t):Math.round(t)},e.prototype.contain=function(t){return vw(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}(ww);ww.registerClass(Mw);var Tw=yl,Aw=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 y(e,t),e.prototype.parse=function(t){return null==t||""===t?NaN:Number(t)},e.prototype.contain=function(t){return vw(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=Tw(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:Tw(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 vi(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=ml(t.get("barWidth"),i),p=ml(t.get("barMaxWidth"),i),f=ml(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:Ew(r),stackId:Lw(t)})}),function(t){var e={};vi(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 vi(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=ml(o,r),l=ml(t.gap,1),c=t.remainedWidth,u=t.autoWidthCount,d=(c-s)/(u+(u-1)*l);d=Math.max(d,0),vi(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;vi(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;vi(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 Rw=function(t){function e(e){var n=t.call(this,e)||this;return n.type="time",n}return y(e,t),e.prototype.getLabel=function(t){var e=this.getSetting("useUTC");return sg(t.value,tg[function(t){switch(t){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}(og(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(Mi(n))o=n;else if(ki(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=lg(t.value,r);o=n[u][u][0]}}return sg(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=lg(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 cg(new Date(e),t,i).getTime()===cg(new Date(n),t,i).getTime()}(og(t),i[0],i[1],n)){s&&(r=[{value:Vw(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=bi(yi(d,function(t){return bi(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=Ow.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 Hw(t){return(t/=2592e6)>6?6:t>3?3:t>2?2:1}function Bw(t){return(t/=Xf)>12?12:t>6?6:t>3.5?4:t>2?2:1}function $w(t,e){return(t/=e?Gf:Uf)>30?30:t>20?20:t>15?15:t>10?10:t>5?5:t>2?2:1}function Fw(t){return Ml(t)}function Vw(t,e,n){var i=Math.max(0,fi(eg,e)-1);return cg(new Date(t),eg[i],n).getTime()}ww.registerClass(Rw);var Ww=yl,jw=Math.floor,qw=Math.ceil,Uw=Math.pow,Gw=Math.log,Xw=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="log",e.base=10,e._originalScale=new Aw,e}return y(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(),yi(r,function(t){var e=t.value,r=null,a=Uw(o,e);return e===n[0]&&this._fixMin?r=i[0]:e===n[1]&&this._fixMax&&(r=i[1]),null!=r&&(a=Yw(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]=Uw(e,n[0]),n[1]=Uw(e,n[1]);var i=this._originalScale.getExtent();return this._fixMin&&(n[0]=Yw(n[0],i[0])),this._fixMax&&(n[1]=Yw(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,kl(i)));for(t/n*r<=.5&&(r*=10);!isNaN(r)&&Math.abs(r)<1&&Math.abs(r)>0;)r*=10;var o=[Ww(qw(e[0]/r)*r),Ww(jw(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=Gw(e)/Gw(this.base),t.prototype.contain.call(this,e)},e.prototype.normalize=function(e){return e=Gw(e)/Gw(this.base),t.prototype.normalize.call(this,e)},e.prototype.scale=function(e){return e=t.prototype.scale.call(this,e),Uw(this.base,e)},e.prototype.setBreaksFromOption=function(t){},e.type="log",e}(Aw);function Yw(t,e){return Ww(t,_l(e))}ww.registerClass(Xw);var Zw=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[Qw[t]]=e},t.prototype.setDeterminedMinMax=function(t,e){this[Kw[t]]=e},t.prototype.freeze=function(){this.frozen=!0},t}(),Kw={min:"_determinedMin",max:"_determinedMax"},Qw={min:"_dataMin",max:"_dataMax"};function Jw(t,e){return null==e?null:Ni(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 Zw(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(vi(s,function(t){l=l||t.getBaseAxis()===e.axis}),l){var c=Nw(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[Ew(e)]}(i,n.axis);if(void 0===a)return{min:t,max:e};var s=1/0;vi(a,function(t){s=Math.min(t.offset,s)});var l=-1/0;vi(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=tS(t,n),r=i.extent,o=n.get("splitNumber");t instanceof Xw&&(t.base=n.get("logBase"));var a=t.type,s=n.get("interval"),l="interval"===a||"time"===a;t.setBreaksFromOption(cS(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=ig(e);return function(e,i){return t.scale.getFormattedLabel(e,i,n)}}if(Mi(e))return function(n){var i=t.scale.getLabel(n);return e.replace("{value}",null!=i?i:"")};if(ki(e)){if("category"===t.type)return function(n,i){return e(iS(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(iS(t,n),r,o)}}return function(e){return t.scale.getLabel(e)}}function iS(t,e){return"category"===t.type?t.scale.getLabel(e):e.value}function rS(t){var e=t.get("interval");return null==e?"auto":e}function oS(t){return"category"===t.type&&0===rS(t.getLabelModel())}function aS(t,e){var n={};return vi(t.mapDimensionsAll(e),function(e){n[function(t,e){return uw(t,e)?t.getCalculationInfo("stackResultDimension"):e}(t,e)]=!0}),xi(n)}function sS(t){return"middle"===t||"center"===t}function lS(t){return t.getShallow("show")}function cS(t){t.get("breaks",!0)}var uS=function(){function t(){}return t.prototype.getNeedCrossZero=function(){return!this.option.scale},t.prototype.getCoordSysModel=function(){},t}(),dS=[],hS={registerPreprocessor:xx,registerProcessor:Sx,registerPostInit:function(t){Cx("afterinit",t)},registerPostUpdate:function(t){Cx("afterupdate",t)},registerUpdateLifecycle:Cx,registerAction:kx,registerCoordinateSystem:function(t,e){Ng.register(t,e)},registerLayout:function(t,e){Ax(hx,t,e,1e3,"layout")},registerVisual:Mx,registerTransform:Dx,registerLoading:Ix,registerMap:function(t,e,n){var i=Cb["registerMap"];i&&i(t,e,n)},registerImpl:function(t,e){Cb[t]=e},PRIORITY:Tb,ComponentModel:Jg,ComponentView:zy,SeriesModel:Iy,ChartView:Fy,registerComponentModel:function(t){Jg.registerClass(t)},registerComponentView:function(t){zy.registerClass(t)},registerSeriesModel:function(t){Iy.registerClass(t)},registerChartView:function(t){Fy.registerClass(t)},registerCustomSeries:function(t,e){},registerSubTypeDefaulter:function(t,e){Jg.registerSubTypeDefaulter(t,e)},registerPainter:function(t,e){var n;n=e,al[t]=n}};function pS(t){Ci(t)?vi(t,function(t){pS(t)}):fi(dS,t)>=0||(dS.push(t),ki(t)&&(t={install:t}),t.install(hS))}var fS=Xl(),gS=Xl(),mS=1,vS=2;function yS(t){return{out:{noPxChangeTryDetermine:[]},kind:t}}function _S(t,e){var n=yi(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 bS(t,e){var n=t.getLabelModel().get("customValues");if(n){var i=nS(t),r=t.scale.getExtent();return{labels:yi(bi(_S(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=wS(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:yi(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:bi(_S(t,i),function(t){return t>=r[0]&&t<=r[1]})}}return"category"===t.type?function(t,e){var n,i,r=SS(t),o=rS(e),a=MS(r,o);if(a)return a;e.get("show")&&!t.scale.isBlank()||(n=[]);if(ki(o))n=PS(t,o,!0);else if("auto"===o){var s=wS(t,t.getLabelModel(),yS(vS));i=s.labelCategoryInterval,n=yi(s.labels,function(t){return t.tickValue})}else n=DS(t,i=o,!0);return TS(r,o,{ticks:n,tickCategoryInterval:i})}(t,e):{ticks:yi(t.scale.getTicks(n),function(t){return t.value})}}function wS(t,e,n){var i,r,o=CS(t),a=rS(e),s=n.kind===mS;if(!s){var l=MS(o,a);if(l)return l}ki(a)?i=PS(t,a):(r="auto"===a?function(t,e){if(e.kind===mS){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=DS(t,r));var c={labels:i,labelCategoryInterval:r};return s?n.out.noPxChangeTryDetermine.push(function(){return TS(o,a,c),!0}):TS(o,a,c),c}var SS=kS("axisTick"),CS=kS("axisLabel");function kS(t){return function(e){return gS(e)[t]||(gS(e)[t]={list:[]})}}function MS(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 DS(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=oS(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 PS(t,e,n){var i=t.scale,r=nS(t),o=[];return vi(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 LS=[0,1],ES=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(fl(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&&NS(n=n.slice(),i.count()),gl(t,LS,n,e)},t.prototype.coordToData=function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&NS(n=n.slice(),i.count());var r=gl(t,n,LS,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=yi(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;vi(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=yl(t),e=yl(e),d?t>e:t0&&t<100||(t=5),yi(this.scale.getMinorTicks(t),function(t){return yi(t,function(t){return{coord:this.dataToCoord(t),tickValue:t}},this)},this)},t.prototype.getViewLabels=function(t){return bS(this,t=t||yS(vS)).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=Vs(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===mS)return e.out.noPxChangeTryDetermine.push(wi(AS,null,t,x,l)),x;var w=IS(t,x,l);return null!=w?w:x}(this,t=t||yS(vS))},t}();function NS(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}var RS=["label","labelLine","layoutOption","priority","defaultAttr","marginForce","minMarginForce","marginDefault","suggestIgnore"];function OS(t,e,n){n=n||3,e?t.dirty|=n:t.dirty&=~n}function zS(t,e){return e=e||3,null==t.dirty||!!(t.dirty&e)}function HS(t){if(t)return zS(t)&&function(t,e,n){var i=e.getComputedTransform();t.transform=af(t.transform,i);var r=t.localRect=of(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=Cf.textMargin);for(var d=0;d<4;d++)BS[d]=u===Cf.minMargin&&l&&null!=l[d]?l[d]:s&&null!=s[d]?s[d]:a?a[d]:0;u===Cf.textMargin&&Zp(r,BS,!1,!1);var h=t.rect=of(t.rect,r);i&&h.applyTransform(i);u===Cf.minMargin&&Zp(h,BS,!1,!1);t.axisAligned=nf(i),(t.label=t.label||{}).ignore=e.ignore,OS(t,!1),OS(t,!0,2)}(t,t.label,t),t}var BS=[0,0,0,0];function $S(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}(Iy);function jS(t,e){var n=t.mapDimensionsAll("defaultedLabel"),i=n.length;if(1===i){var r=Ev(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),rh(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=vd(this).dataIndex,o=n&&n.animation;if(this.silent=i.silent=!0,n&&n.fadeLabel){var a=i.getTextContent();a&&Dp(a,{style:{opacity:0}},e,{dataIndex:r,removeOpt:o,cb:function(){i.removeTextContent()}})}else i.removeTextContent();Dp(i,{style:{opacity:0},scaleX:0,scaleY:0},e,{dataIndex:r,cb:t,removeOpt:o})},e.getSymbolSize=function(t,e){return Ci(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}(ol);function US(t,e){this.parent.drift(t,e)}function GS(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 XS(t){return null==t||Ii(t)||(t={isIgnore:t}),t||{}}function YS(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:ff(e),cursorStyle:e.get("cursor")}}var ZS=function(){function t(t){this.group=new ol,this._SymbolCtor=t||qS}return t.prototype.updateData=function(t,e){this._progressiveEls=null,e=XS(e);var n=this.group,i=t.hostModel,r=this._data,o=this._SymbolCtor,a=e.disableAnimation,s=YS(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(GS(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(GS(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):Tp(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=YS(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=XS(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=yi(t.dimensions,function(t){return e.mapDimension(t)}),h=!1,p=e.getCalculationInfo("stackResultDimension");return uw(e,d[0])&&(h=!0,d[0]=p),uw(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 QS(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 JS=Math.min,tC=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=JS(A=v+M*a*k,tC(w,v)),I=JS(I,tC(S,y)),A=tC(A,JS(w,v)),f=y-(T=(I=tC(I,JS(S,y)))-y)*N/R,p=JS(p=v-(M=A-v)*N/R,tC(c,v)),f=JS(f,tC(u,y)),A=v+(M=v-(p=tC(p,JS(c,v))))*R/N,I=y+(T=y-(f=tC(f,JS(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 iC=function(){this.smooth=0,this.smoothConstraint=!0},rC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polyline",n}return y(e,t),e.prototype.getDefaultStyle=function(){return{stroke:tm.color.neutral99,fill:null}},e.prototype.getDefaultShape=function(){return new iC},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?Wo(n,c,d,p,t,s):Wo(i,u,h,f,t,s);if(v>0)for(var y=0;y=0){m=a?Fo(i,u,h,f,_):Fo(n,c,d,p,_);return a?[t,m]:[m,t]}}n=p,i=f}}},e}(Vu),oC=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return y(e,t),e}(iC),aC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polygon",n}return y(e,t),e.prototype.getDefaultShape=function(){return new oC},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=ma(e[r]),s=ma(e[o]),l=i-r,c=ba([oa(ua(a[0],s[0],l)),oa(ua(a[1],s[1],l)),oa(ua(a[2],s[2],l)),aa(ua(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 pC(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 vi(o.getViewLabels(),function(t){var e=o.scale.getRawOrdinalNumber(t.tickValue);s[e]=1}),function(t){return!s.hasOwnProperty(e.get(a,t))}}}}function fC(t,e){return isNaN(t)||isNaN(e)}function gC(t,e){return[t[2*e],t[2*e+1]]}function mC(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=yi(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=hC(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";vi(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 hp(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,Pg(M));var T=f.getClipPath();if(T)Ap(T,{shape:vC(this,i,!1,t).shape},t);else f.setClipPath(vC(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]]}}),sC(this._stackedOnPoints,_)&&sC(this._points,l)||(g?this._doUpdateAnimation(o,_,i,n,k,v,x):(k&&(_&&(_=dC(_,l,i,k,x)),l=dC(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&&(_&&(_=dC(_,l,i,k,x)),l=dC(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,Pg(M)),f.setClipPath(vC(this,i,!0,t));var A=t.getModel("emphasis"),I=A.get("focus"),D=A.get("blurScope"),P=A.get("disabled");(h.useStyle(pi(a.getLineStyle(),{fill:"none",stroke:M,lineJoin:"bevel"})),sh(h,t,"lineStyle"),h.style.lineWidth>0&&"bolder"===t.get(["emphasis","lineStyle","width"]))&&(h.getState("emphasis").style.lineWidth=+h.style.lineWidth+1);vd(h).seriesIndex=t.seriesIndex,rh(h,I,D,P);var L=uC(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(pi(s.getAreaStyle(),{fill:M,opacity:.7,lineJoin:"bevel",decal:o.getVisual("style").decal})),N&&(R=uC(N.get("smooth"))),p.setShape({smooth:L,stackedOnSmooth:R,smoothMonotone:E,connectNulls:x}),sh(p,t,"areaStyle"),vd(p).seriesIndex=t.seriesIndex,rh(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){vd(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=Gl(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 qS(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 Fy.prototype.highlight.call(this,t,e,n,i)},e.prototype.downplay=function(t,e,n,i){var r=t.getData(),o=Gl(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 Fy.prototype.downplay.call(this,t,e,n,i)},e.prototype._changePolyState=function(t){var e=this._polygon;$d(this._polyline,t),e&&$d(e,t)},e.prototype._newPolyline=function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new rC({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 aC({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");ki(l)&&(l=l(null));var c=s.get("animationDelay")||0,u=ki(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 _=ki(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(mC(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 rd({z2:200})).ignoreClip=!0,o.setTextContent(this._endLabel),o.disableLabelAnimation=!0);var l=function(t){for(var e=t.length/2;e>0&&fC(t[2*e-2],t[2*e-1]);e--);return e-1}(a);l>=0&&(pf(o,ff(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(!Ci(e))return e+"";for(var i=[],r=0;r=0&&i.push(e[o])}return i.join(" ")}(r,n):jS(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(Ai(i))return yl(f=Nl(n||0,i,r),o?Math.max(_l(n||0),_l(i)):e);if(Mi(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=Sf(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=KS(r,e,a),m=t.getLayout("points")||[],v=e.getLayout("points")||[],y=0;y3e3||l&&cC(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(),Tp(s,g,c),l&&(l.setShape({points:d,stackedOnPoints:h}),l.stopAnimation(),Tp(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}(ES),zC="expandAxisBreak",HC=Math.PI,BC=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],$C=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],FC=Xl(),VC=Xl(),WC=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 jC=[1,0,0,1,0,0],qC=new no(0,0,0,0),UC=function(t,e,n,i,r,o){if(sS(t.nameLocation)){var a=o.stOccupiedRect;a&&GC(function(t,e,n){return t.transform=af(t.transform,n),t.localRect=of(t.localRect,e),t.rect=of(t.rect,e),n&&t.rect.applyTransform(n),t.axisAligned=nf(n),t.obb=void 0,(t.label=t.label||{}).ignore=!1,t}({},a,o.transGroup.transform),i,r)}else XC(o.labelInfoList,o.dirVec,i,r)};function GC(t,e,n){var i=new Vr;VS(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 XC(t,e,n,i){for(var r=Vr.dot(i,e)>=0,o=0,a=t.length;o0?"top":"bottom",i="center"):wl(o-HC)?(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}(),ZC=["axisLine","axisTickLabelEstimate","axisTickLabelDetermine","axisName"],KC={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&&(lr(u,u,c),lr(d,d,c));var p=hi({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 ip(hi({shape:{x1:u[0],y1:u[1],x2:d[0],y2:d[1]}},f));Vp(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"]);Mi(m)&&(m=[m,m]),(Mi(v)||Ai(v))&&(v=[v,v]);var y=Y_(i.get(["axisLine","symbolOffset"])||0,v),_=v[0],b=v[1];vi([{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=X_(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)&&QC(t,e,n,i,r,o,a,mS)},axisTickLabelDetermine:function(t,e,n,i,r,o,a,s){ek(e,r,s)&&QC(t,e,n,i,r,o,a,vS);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,pi(s.getLineStyle(),{stroke:i.get(["axisLine","lineStyle","color"])}),"ticks"),u=0;ui[1],l="start"===e&&!s||"start"!==e&&s;wl(a-HC/2)?(o=l?"bottom":"top",r="center"):wl(a-1.5*HC)?(o=l?"top":"bottom",r="center"):(o="middle",r=a<1.5*HC&&a>HC/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=Ri(t.raw.nameTruncateMaxWidth,S.maxWidth,b),M=s.nameMarginLevel||0,T=new rd({x:m.x,y:m.y,rotation:_.rotation,silent:YC.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(Jp({el:T,componentModel:i,itemName:c}),T.__fullText=c,T.anid="name",i.get("triggerEvent")){var A=YC.makeAxisEventDataBase(i);A.targetType="axisName",A.name=c,vd(T).eventData=A}o.add(T),T.updateTransform(),e.nameEl=T;var I=l.nameLayout=HS({label:T,priority:T.z2,defaultAttr:{ignore:T.ignore},marginDefault:sS(u)?BC[M]:$C[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 QC(t,e,n,i,r,o,a,s){nk(e)||function(t,e,n,i,r,o){var a=r.axis,s=Ri(t.raw.axisLabelShow,r.get(["axisLabel","show"])),l=new ol;n.add(l);var c=yS(i);if(!s||a.scale.isBlank())return void ik(e,[],l,c);var u=r.getModel("axisLabel"),d=a.getViewLabels(c),h=(Ri(t.raw.labelRotate,u.get("rotate"))||0)*HC/180,p=YC.innerTextLayout(t.rotation,h,t.labelDirection),f=r.getCategories&&r.getCategories(!0),g=[],m=r.get("triggerEvent"),v=1/0,y=-1/0;vi(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];Ii(_)&&_.textStyle&&(h=new Rf(_.textStyle,u,r.ecModel))}var b=h.getTextColor()||r.get(["axisLine","lineStyle","color"]),x=h.getShallow("align",!0)||p.textAlign,w=Oi(h.getShallow("alignMinLabel",!0),x),S=Oi(h.getShallow("alignMaxLabel",!0),x),C=h.getShallow("verticalAlign",!0)||h.getShallow("baseline",!0)||p.textVerticalAlign,k=Oi(h.getShallow("verticalAlignMinLabel",!0),C),M=Oi(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 rd({x:0,y:0,rotation:0,silent:YC.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:ki(b)?b("category"===a.type?c:"value"===a.type?i+"":i,e):b})});A.anid="label_"+i;var I=FC(A);if(I.break=t.break,I.tickValue=i,I.layoutRotation=p.rotation,Jp({el:A,componentModel:r,itemName:s,formatterParamsExtra:{isTruncated:function(){return A.isTruncated},value:c,tickIndex:e}}),m){var D=YC.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),vd(A).eventData=D,t.break&&function(t,e,n,i){n.on("click",function(n){var r={type:zC,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 _=yi(g,function(t){return{label:t,priority:FC(t).break?t.z2+(y-v+1):t.z2,defaultAttr:{ignore:t.ignore}}});ik(e,_,l,c)}(t,e,r,s,i,a);var l=e.labelLayoutList;!function(t,e,n,i){var r=e.get(["axisLabel","margin"]);vi(n,function(n,o){var a=HS(n);if(a){var s=a.label,l=FC(s);a.suggestIgnore=s.ignore,s.ignore=!1,Rs(rk,ok),rk.x=e.axis.dataToCoord(l.tickValue),rk.y=t.labelOffset+t.labelDirection*r,rk.rotation=l.layoutRotation,i.add(rk),rk.updateTransform(),i.remove(rk),rk.decomposeTransform(),Rs(s,rk),s.markRedraw(),OS(a,!0),HS(a)}})}(t,i,l,o),t.rotation;var c=t.optionHideOverlap;!function(t,e,n){if(oS(t.axis))return;function i(t,i,r){var o=HS(e[i]),a=HS(e[r]);if(o&&a)if(!1===t||o.suggestIgnore)JC(o.label);else if(a.suggestIgnore)JC(a.label);else{var s=.1;if(!n){var l=[0,0,0,0];o=$S({marginForce:l},o),a=$S({marginForce:l},a)}VS(o,a,null,{touchThreshold:s})&&JC(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 no(h,0,p,1))}a.stOccupiedRect=r,a.labelInfoList=s}(t,n,i,l)}function JC(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;hw(l)&&s.get("alignTicks")&&null==s.get("interval")?r.push(a):(eS(l,s),hw(l)&&(e=a))}r.length&&(e||eS((e=r.pop()).scale,e.model),vi(r,function(t){!function(t,e,n){var i=Aw.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(cS(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=fw(p),f=c[1]-p*a;else{t.getTicks().length-1>a&&(p=fw(p));var m=p*a;(f=yl((g=Math.ceil(c[1]/p)*p)-m))<0&&c[0]>=0?(f=0,g=yl(m)):g>0&&c[1]<=0&&(g=0,f=-yl(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={};vi(n.x,function(t){hk(n,"y",t,r)}),vi(n.y,function(t){hk(n,"x",t,r)}),this.resize(this.model,e)},t.prototype.resize=function(t,e,n){var i=Xg(t,e),r=this._rect=Ug(t.getBoxLayoutParams(),i.refContainer),o=this._axesMap,a=this._coordsList,s=t.get("containLabel");if(fk(o,r),!n){var l=function(t,e,n,i,r){var o=new WC(yk);return vi(n,function(n){return vi(n,function(n){if(lS(n.model)){var a=!i;n.axisBuilder=function(t,e,n,i,r,o){for(var a=sk(t,n),s=!1,l=!1,c=0;c0&&i>0||n<0&&i<0)}(t)}function fk(t,e){vi(t.x,function(t){return gk(t,e.x,e.width)}),vi(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 mk(t,e,n,i,r,o,a){vk(i,r,mS,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 Zp(i,s,!0,!0,n),fk(r,i),l;function c(t){vi(r[Ep[t]],function(e){if(lS(e.model)){var n=o.ensureRecord(e.model),i=n.labelInfoList;if(i)for(var r=0;r0&&!Ni(e)&&e>1e-4&&(t/=e),t}}function vk(t,e,n,i,r,o){var a=n===vS;vi(e,function(e){return vi(e,function(e){lS(e.model)&&(!function(t,e,n){var i=sk(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[Ep[1-e]]=t[Np[e]]<=.5*o.refContainer[Np[e]]?0:1-e==1?2:1}l(0),l(1),vi(e,function(t,e){return vi(t,function(t){lS(t.model)&&(("all"===i||a)&&t.axisBuilder.build({axisName:!0},{nameMarginLevel:s[e]}),a&&t.axisBuilder.build({axisLine:!0}))})})}var yk=function(t,e,n,i,r,o){var a="x"===n.axis.dim?"y":"x";UC(t,0,0,i,r,o),sS(t.nameLocation)||vi(e.recordMap[a],function(t){t&&t.labelInfoList&&t.dirVec&&XC(t.labelInfoList,t.dirVec,i,r)})};function _k(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=[];vi(n.getCoordinateSystems(),function(n){if(n.axisPointerEnabled){var s=Sk(n.model),l=t.coordSysAxesInfo[s]={};t.coordSysMap[s]=n;var c=n.model.getModel("tooltip",i);if(vi(n.getAxes(),Si(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)&&vi(h.baseAxes,Si(p,!d||"cross",u)),d&&vi(h.otherAxes,Si(p,"cross",!1))}}function p(i,s,u){var d=u.model.getModel("axisPointer",r),h=d.get("show");if(h&&("auto"!==h||i||wk(d))){null==s&&(s=d.get("triggerTooltip")),d=i?function(t,e,n,i,r,o){var a=e.getModel("axisPointer"),s={};vi(["type","snap","lineStyle","shadowStyle","label","animation","animationDurationUpdate","animationEasingUpdate","z"],function(t){s[t]=ui(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&&pi(l,u.textStyle)}}return t.model.getModel("axisPointer",new Rf(s,n,i))}(u,c,r,e,i,s):d;var p=d.get("snap"),f=d.get("triggerEmphasis"),g=Sk(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:wk(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[Sk(t)]}function wk(t){return!!t.get(["handle","show"])}function Sk(t){return t.type+"||"+t.id}var Ck={},kk=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return y(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=wk(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=Rk(t).pointerEl=new uf[r.type](Ok(e.pointer));t.add(o)}},t.prototype.createLabelEl=function(t,e,n,i){if(e.label){var r=Rk(t).labelEl=new rd(Ok(e.label));t.add(r),Fk(r,i)}},t.prototype.updatePointerEl=function(t,e,n){var i=Rk(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=Rk(t).labelEl;r&&(r.setStyle(e.label.style),n(r,{x:e.label.x,y:e.label.y}),Fk(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=Gp(o.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(t){Lr(t.event)},onmousedown:zk(this._onHandleDragMove,this,0,0),drift:zk(this._onHandleDragMove,this),ondragend:zk(this._onHandleDragEnd,this)}),i.add(r)),Wk(r,n,!1),r.setStyle(o.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var s=o.get("size");Ci(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,Ky(this,"_doDispatchAxisPointer",o.get("throttle")||0,"fixRate"),this._moveHandleToValue(t,e)}},t.prototype._moveHandleToValue=function(t,e){Bk(this._axisPointerModel,!e&&this._moveAnimation,this._handle,Vk(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(Vk(n),[t,e],this._axisModel,this._axisPointerModel);this._payloadInfo=i,n.stopAnimation(),n.attr(Vk(i)),Rk(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),Qy(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 Bk(t,e,n,i){$k(Rk(n).lastProp,i)||(Rk(n).lastProp=i,e?Tp(n,i,t):(n.stopAnimation(),n.attr(i)))}function $k(t,e){if(Ii(t)&&Ii(e)){var n=!0;return vi(e,function(e,i){n=n&&$k(t[i],e)}),!!n}return t===e}function Fk(t,e){t[e.get(["label","show"])?"show":"hide"]()}function Vk(t){return{x:t.x||0,y:t.y||0,rotation:t.rotation||0}}function Wk(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 jk(t,e,n,i,r){var o=qk(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=Mg(a.get("padding")||0),l=a.getFont(),c=Vs(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 qk(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:iS(e,{value:t}),axisDimension:e.dim,axisIndex:e.index,seriesData:[]};vi(i,function(t){var e=n.getSeriesByIndex(t.seriesIndex),i=t.dataIndexInside,r=e&&e.getDataParams(i);r&&s.seriesData.push(r)}),Mi(a)?o=a.replace("{value}",o):ki(a)&&(o=a(s))}return o}function Uk(t,e,n){var i=[1,0,0,1,0,0];return $r(i,i,n.rotation),Br(i,i,n.position),jp([t.dataToCoord(e),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],i)}var Gk=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return y(e,t),e.prototype.makeElOption=function(t,e,n,i,r){var o=n.axis,a=o.grid,s=i.get("type"),l=Xk(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=Yk[s](o,c,l);d.style=u,t.graphicKey=d.type,t.pointer=d}!function(t,e,n,i,r,o){var a=YC.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=r.get(["label","margin"]),jk(e,i,r,o,{position:Uk(i.axis,t,n),align:a.textAlign,verticalAlign:a.textVerticalAlign})}(e,t,sk(a.getRect(),n),n,i,r)},e.prototype.getHandleTransform=function(t,e,n){var i=sk(e.axis.grid.getRect(),e,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var r=Uk(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=Xk(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}(Hk);function Xk(t,e){var n={};return n[e.dim+"AxisIndex"]=e.index,t.getCartesian(n)}var Yk={line:function(t,e,n){var i,r,o;return{type:"Line",subPixelOptimize:!0,shape:(i=[e,n[0]],r=[e,n[1]],o=Zk(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=Zk(t),{x:i[o=o||0],y:i[1-o],width:r[o],height:r[1-o]})}}};function Zk(t){return"x"===t.dim?0:1}var Kk=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return y(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}(Jg),Qk=Xl(),Jk=vi;function tM(t,e,n){if(!Wn.node){var i=e.getZr();Qk(i).records||(Qk(i).records={}),function(t,e){if(Qk(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);Jk(Qk(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)})}Qk(t).initialized=!0,n("click",Si(nM,"click")),n("mousemove",Si(nM,"mousemove")),n("globalout",eM)}(i,e),(Qk(i).records[t]||(Qk(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 iM(t,e){if(!Wn.node){var n=e.getZr();(Qk(n).records||{})[t]&&(Qk(n).records[t]=null)}}var rM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return y(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){iM("axisPointer",e)},e.prototype.dispose=function(t,e){iM("axisPointer",e)},e.type="axisPointer",e}(zy);function oM(t,e){var n,i=[],r=t.seriesIndex;if(null==r||!(n=e.getSeriesByIndex(r)))return{point:[]};var o=n.getData(),a=Gl(o,t);if(null==a||a<0||Ci(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(yi(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 aM=Xl();function sM(t,e,n){var i=t.currTrigger,r=[t.x,t.y],o=t,a=t.dispatchAction||wi(n.dispatchAction,n),s=e.getComponent("axisPointer").coordSysAxesInfo;if(s){hM(r)&&(r=oM({seriesIndex:o.seriesIndex,dataIndex:o.dataIndex},e).point);var l=hM(r),c=o.axesInfo,u=s.axesInfo,d="leave"===i||hM(r),h={},p={},f={list:[],map:{}},g={showPointer:Si(cM,p),showTooltip:Si(uM,f)};vi(s.coordSysMap,function(t,e){var n=l||t.containPoint(r);vi(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&&lM(t,a,g,!1,h)}})});var m={};return vi(u,function(t,e){var n=t.linkGroup;n&&!p[e]&&vi(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,dM(e),dM(t)))),m[t.key]=o}})}),vi(m,function(t,e){lM(u[e],t,g,!0,h)}),function(t,e,n){var i=n.axesInfo=[];vi(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(hM(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=aM(i)[r]||{},a=aM(i)[r]={};vi(t,function(t,e){var n=t.axisPointerModel.option;"show"===n.status&&t.triggerEmphasis&&vi(n.seriesDataIndices,function(t){var e=t.seriesIndex+" | "+t.dataIndex;a[e]=t})});var s=[],l=[];vi(o,function(t,e){!a[e]&&l.push(t)}),vi(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 lM(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 vi(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),vi(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&&hi(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 cM(t,e,n,i){t[e.key]={value:n,payloadBatch:i}}function uM(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=Sk(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 dM(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 hM(t){return!t||null==t[0]||isNaN(t[0])||null==t[1]||isNaN(t[1])}function pM(t){kk.registerAxisPointerClass("CartesianAxisPointer",Gk),t.registerComponentModel(Kk),t.registerComponentView(rM),t.registerPreprocessor(function(t){if(t){(!t.axisPointer||0===t.axisPointer.length)&&(t.axisPointer={});var e=t.axisPointer.link;e&&!Ci(e)&&(t.axisPointer.link=[e])}}),t.registerProcessor(t.PRIORITY.PROCESSOR.STATISTIC,function(t,e){t.getComponent("axisPointer").coordSysAxesInfo=_k(t,e)}),t.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},sM)}var fM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return y(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}(Jg);function gM(t){var e=t.get("confine");return null!=e?!!e:"richText"===t.get("renderMode")}function mM(t){if(Wn.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?",":"")+(Wn.transformSupported?""+bM+r:",left"+r+",top"+r)),_M+":"+o}(o,n,i)),a&&r.push("background-color:"+a),vi(["width","color","radius"],function(e){var n="border-"+e,i=kg(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=Oi(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),vi(["decoration","align"],function(n){var i=t.get(n);i&&e.push("text-"+n+":"+i)}),e.join(";")}(d)),null!=h&&r.push("padding:"+Mg(h).join("px ")+"px"),r.join(";")+";"}function CM(t,e,n,i,r){var o=e&&e.painter;if(n){var a=o&&o.getViewportRoot();a&&function(t,e,n,i,r){_r(yr,e,i,r,!0)&&_r(t,n,yr[0],yr[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 kM=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,Wn.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&&(Mi(r)?document.querySelector(r):Li(r)?r:ki(r)&&r(t.getDom()));CM(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;Dr(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+SM(t,!this._firstShow,this._longHide,this._enableDisplayTransition)+wM(r[0],r[1],!0)+"border-color:"+Pg(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(Mi(r)&&"item"===n.get("trigger")&&!gM(n)&&(a=function(t,e,n){if(!Mi(n)||"inside"===n)return"";var i=t.get("backgroundColor"),r=t.get("borderWidth");e=Pg(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=bM+":";fi(["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)),Mi(t))o.innerHTML=t+a;else if(t){o.innerHTML="",Ci(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&&!Wn.node&&n.getDom()){var r=EM(i,n);this._ticket="";var o=i.dataByCoordSys,a=function(t,e,n){var i=Kl(t).queryOptionMap,r=i.keys()[0];if(!r||"series"===r)return;var o=Jl(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=vd(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=DM;l.x=i.x,l.y=i.y,l.update(),vd(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=oM(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(EM(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"===LM([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"===vd(n).ssrType)return;this._lastDataByCoordSys=null,O_(n,function(t){if(t.tooltipDisabled)return r=o=null,!0;r||o||(null!=vd(t).dataIndex?r=t:null!=vd(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=wi(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=LM([e.tooltipOption],i),a=this._renderMode,s=[],l=gy("section",{blocks:[],noHeader:!0}),c=[],u=new ky;vi(t,function(t){vi(t.dataByAxis,function(t){var e=n.getComponent(t.axisDim+"Axis",t.axisIndex),r=t.value;if(e&&null!=r){var o=qk(r,e.axis,n,t.seriesDataIndices,t.valueLabelOpt),d=gy("section",{header:o,noHeader:!Fi(o),sortBlocks:!0,blocks:[]});l.blocks.push(d),vi(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=iS(e.axis,{value:r}),f.axisValueLabel=o,f.marker=u.makeTooltipMarker("item",Pg(f.color),a);var g=Ov(h.formatTooltip(p,!0,null)),m=g.frag;if(m){var v=LM([h],i).get("valueFormatter");d.blocks.push(v?hi({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=vd(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=LM([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 ky;g.marker=m.makeTooltipMarker("item",Pg(g.color),d);var v=Ov(s.formatTooltip(l,!1,c)),y=p.get("order"),_=p.get("valueFormatter"),b=v.frag,x=b?xy(_?hi({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=vd(e),o=r.tooltipConfig.option||{},a=o.encodeHTMLContent;if(Mi(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=ui(o)).content=Sr(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=LM(s,this._tooltipModel,c?{position:c}:null),d=u.get("content"),h=Math.random()+"",p=new ky;this._showOrMove(u,function(){var n=ui(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(Mi(u)){var p=t.ecModel.get("useUTC"),f=Ci(n)?n[0]:n;d=u,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(d=sg(f.axisValue,d,p)),d=Dg(d,n,!0)}else if(ki(u)){var g=wi(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||Ci(e)?{color:i||r}:Ci(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),ki(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),Ci(e))n=ml(e[0],s),i=ml(e[1],l);else if(Ii(e)){var p=e;p.width=c[0],p.height=c[1];var f=Ug(p,{width:s,height:l});n=f.x,i=f.y,u=null,d=null}else if(Mi(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-=NM(u)?c[0]/2:"right"===u?c[0]:0),d&&(i-=NM(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&&vi(n,function(n,o){var a=n.dataByAxis||[],s=(t[o]||{}).dataByAxis||[];(r=r&&a.length===s.length)&&vi(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)&&vi(a,function(t,e){var n=l[e];r=r&&t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex}),i&&vi(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){!Wn.node&&e.getDom()&&(Qy(this,"_updatePosition"),this._tooltipContent.dispose(),iM("itemTooltip",e))},e.type="tooltip",e}(zy);function LM(t,e,n){var i,r=e.ecModel;n?(i=new Rf(n,r,r),i=new Rf(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof Rf&&(a=a.get("tooltip",!0)),Mi(a)&&(a={formatter:a}),a&&(i=new Rf(a,i,r)))}return i}function EM(t,e){return t.dispatchAction||wi(e.dispatchAction,e)}function NM(t){return"center"===t||"middle"===t}var RM=Math.sin,OM=Math.cos,zM=Math.PI,HM=2*Math.PI,BM=180/zM,$M=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=Ta(u-HM)||(c?l>=HM:-l>=HM),h=l>0?l%HM:l%HM+HM,p=!1;p=!!d||!Ta(u)&&h>=zM==!!c;var f=t+n*OM(o),g=e+i*RM(o);this._start&&this._add("M",f,g);var m=Math.round(r*BM);if(d){var v=1/this._p,y=(c?1:-1)*(HM-v);this._add("A",n,i,m,1,+c,t+n*OM(o+y),e+i*RM(o+y)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var _=t+n*OM(a),b=e+i*RM(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?Sr(a):a||"")+(i?""+n+yi(i,function(e){return t(e)}).join(n)+n:"")+("")}(t)}function QM(t){return{zrId:t,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function JM(t,e,n,i){return ZM("svg","root",{width:t,height:e,xmlns:UM,"xmlns:xlink":GM,version:"1.1",baseProfile:"full",viewBox:!!i&&"0 0 "+t+" "+e},n)}var tT=0;function eT(){return tT++}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"},iT="transform-origin";function rT(t,e,n){var i=hi({},t.shape);hi(i,e),t.buildPath(n,i);var r=new $M;return r.reset(za(t)),n.rebuildPath(r,1),r.generateStr(),r.getStr()}function oT(t,e){var n=e.originX,i=e.originY;(n||i)&&(t[iT]=n+"px "+i+"px")}var aT={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function sT(t,e){var n=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[n]=t,n}function lT(t){return Mi(t)?nT[t]?"cubic-bezier("+nT[t]+")":Jo(t)?t:"":""}function cT(t,e,n,i){var r=t.animators,o=r.length,a=[];if(t instanceof up){var s=function(t,e,n){var i,r,o=t.shape.paths,a={};if(vi(o,function(t){var e=QM(n.zrId);e.animation=!0,cT(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=sT(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 sT(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 uT(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 dT=Math.round;function hT(t){return t&&Mi(t.src)}function pT(t){return t&&ki(t.toDataURL)}function fT(t,e,n,i){qM(function(r,o){var a="fill"===r||"stroke"===r;a&&Ra(o)?kT(e,t,r,i):a&&La(o)?MT(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=ka(i.shadowColor),f=p.opacity,g=p.color,m=h/2/l+" "+h/2/c;a=n.zrId+"-s"+n.shadowIdx++,n.defs[a]=ZM("filter",a,{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},[ZM("feDropShadow","",{dx:u/l,dy:d/c,stdDeviation:m,"flood-color":g,"flood-opacity":f})]),o[r]=a}e.filter=Oa(a)}}(n,t,i)}function gT(t,e){var n=function(t){if("function"==typeof ll)return ll(t)}(e);n&&(n.each(function(e,n){null!=e&&(t[(XM+n).toLowerCase()]=e+"")}),e.isSilent()&&(t[XM+"silent"]="true"))}function mT(t){return Ta(t[0]-1)&&Ta(t[1])&&Ta(t[2])&&Ta(t[3]-1)}function vT(t,e,n){if(e&&(!function(t){return Ta(t[4])&&Ta(t[5])}(e)||!mT(e))){var i=1e4;t.transform=mT(e)?"translate("+dT(e[4]*i)/i+" "+dT(e[5]*i)/i+")":function(t){return"matrix("+Aa(t[0])+","+Aa(t[1])+","+Aa(t[2])+","+Aa(t[3])+","+Ia(t[4])+","+Ia(t[5])+")"}(e)}}function yT(t,e,n){for(var i=t.points,r=[],o=0;o=0&&a||o;s&&(r=Sa(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),uT(c,e,n)}}(t,o,e),ZM(s,t.id+"",o)}function CT(t,e){return t instanceof Vu?ST(t,e):t instanceof Gu?function(t,e){var n=t.style,i=n.image;if(i&&!Mi(i)&&(hT(i)?i=i.src:pT(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),vT(a,t.transform),fT(a,n,t,e),gT(a,t),e.animation&&cT(t,a,e),ZM("image",t.id+"",a)}}(t,e):t instanceof ju?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||qn,o=n.x||0,a=function(t,e,n){return"top"===n?t+=e/2:"bottom"===n&&(t-=e/2),t}(n.y||0,qs(r),n.textBaseline),s={"dominant-baseline":"central","text-anchor":Da[n.textAlign]||n.textAlign};if(ud(n)){var l="",c=n.fontStyle,u=ld(n.fontSize);if(!parseFloat(u))return;var d=n.fontFamily||jn,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),vT(s,t.transform),fT(s,n,t,e),gT(s,t),e.animation&&cT(t,s,e),ZM("text",t.id+"",s,void 0,i)}}(t,e):void 0}function kT(t,e,n,i){var r,o=t[n],a={gradientUnits:o.global?"userSpaceOnUse":"objectBoundingBox"};if(Ea(o))r="linearGradient",a.x1=o.x,a.y1=o.y,a.x2=o.x2,a.y2=o.y2;else{if(!Na(o))return;r="radialGradient",a.cx=Oi(o.x,.5),a.cy=Oi(o.y,.5),a.r=Oi(o.r,.5)}for(var s=o.colorStops,l=[],c=0,u=s.length;cl?FT(t,null==n[d+1]?null:n[d+1].elm,n,s,d):VT(t,e,a,l))}(n,i,r):zT(r)?(zT(t.text)&&NT(n,""),FT(n,null,r,0,r.length-1)):zT(i)?VT(n,i,0,i.length-1):zT(t.text)&&NT(n,""):t.text!==e.text&&(zT(i)&&VT(n,i,0,i.length-1),NT(n,e.text)))}var qT=0,UT=function(){function t(t,e,n){if(this.type="svg",this.refreshHover=function(){},this.configLayer=function(){},this.storage=e,this._opts=n=hi({},n),this.root=t,this._id="zr"+qT++,this._oldVNode=JM(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=YM("svg");WT(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(BT(t,e))jT(t,e);else{var n=t.elm,i=LT(n);$T(e),null!==i&&(IT(i,e.elm,ET(n)),VT(i,[t],0,0))}}(this._oldVNode,t),this._oldVNode=t}},t.prototype.renderOneToVNode=function(t){return CT(t,QM(this._id))},t.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),n=this._width,i=this._height,r=QM(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=ZM("rect","bg",{width:t,height:e,x:"0",y:"0"}),Ra(n))kT({fill:n},r.attrs,"fill",i);else if(La(n))MT({style:{fill:n},dirty:Ki,getBoundingRect:function(){return{width:t,height:e}}},r.attrs,"fill",i);else{var o=ka(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=ZM("g","main",{},[]);this._paintList(e,r,s?s.children:o),s&&o.push(s);var l=yi(xi(r.defs),function(t){return r.defs[t]});if(l.length&&o.push(ZM("defs","defs",{},l)),t.animation){var c=function(t,e,n){var i=(n=n||{}).newline?"\n":"",r=" {"+i,o=i+"}",a=yi(xi(t),function(e){return e+r+yi(xi(t[e]),function(n){return n+":"+t[e][n]+";"}).join(i)+o}).join(i),s=yi(xi(e),function(t){return"@keyframes "+t+r+yi(xi(e[t]),function(n){return n+r+yi(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=ZM("style","stl",{},[],c);o.push(u)}}return JM(n,i,o,t.useViewBox)},t.prototype.renderToString=function(t){return t=t||{},KM(this.renderToVNode({animation:Oi(t.cssAnimation,!0),emphasis:Oi(t.cssEmphasis,!0),willUpdate:!1,compress:!0,useViewBox:Oi(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;Mi(r)?p=_C[r]:ki(r)&&(p=r),p&&t.setData(i.downSample(i.mapDimension(l.dim),1/h,p,bC))}}}}}("line"))},function(t){pS(Nk),pS(pM)},function(t){pS(pM),t.registerComponentModel(fM),t.registerComponentView(PM),t.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},Ki),t.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},Ki)},function(t){t.registerPainter("svg",UT)}]);class GT extends It{constructor(){super(...arguments),this.options=null,this.data=[],this.height="120px",this._chart=null,this._resizeObserver=null}render(){return ut`
`}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=_x(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)}}GT.styles=M` +var Rl={},Ol={};var zl,Hl=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 ia,o=n.renderer||"canvas";Rl[o]||(o=Zi(Rl)[0]),n.useDirtyRect=null!=n.useDirtyRect&&n.useDirtyRect;var a=new Rl[o](e,r,n,t),s=n.ssr||a.ssrOnly;this.storage=r,this.painter=a;var l,c=yi.node||yi.worker||s?null:new Ys(a.getViewportRoot(),a.root),u=n.useCoarsePointer;(null==u||"auto"===u?yi.touchEventsSupported:!!u)&&(l=dr(n.pointerSize,44)),this.handler=new Wo(r,a,c,a.root,l),this.animation=new Ls({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 Za(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 ql=function(t,e,n){switch(t){case"center":case"middle":t="50%";break;case"left":case"top":t="0%";break;case"right":case"bottom":t="100%"}return Ul(t,e,n)};function Ul(t,e,n){return er(t)?(i=t,i.replace(/^\s+|\s+$/g,"")).match(/%$/)?parseFloat(t)/100*e+(n||0):parseFloat(t):null==t?NaN:+t;var i}function Gl(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function Xl(t){if(t=+t,isNaN(t))return 0;if(t>1e-14)for(var e=1,n=0;n<15;n++,e*=10)if(Math.round(t*e)/e===t)return n;return function(t){var e=t.toString().toLowerCase(),n=e.indexOf("e"),i=n>0?+e.slice(n+1):0,r=n>0?n:e.length,o=e.indexOf("."),a=o<0?0:r-1-o;return Math.max(0,a-i)}(t)}function Yl(t,e){var n=Math.max(Xl(t),Xl(e)),i=t+e;return n>20?i:Gl(i,n)}function Zl(t){var e=2*Math.PI;return(t%e+e)%e}function Kl(t){return t>-1e-4&&t<$l}var Ql=/^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d{1,2})(?::(\d{1,2})(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/;function Jl(t){if(t instanceof Date)return t;if(er(t)){var e=Ql.exec(t);if(!e)return new Date(NaN);if(e[8]){var n=+e[4]||0;return"Z"!==e[8].toUpperCase()&&(n-=+e[8].slice(0,3)),new Date(Date.UTC(+e[1],+(e[2]||1)-1,+e[3]||1,n,+(e[5]||0),+e[6]||0,e[7]?+e[7].substring(0,3):0))}return new Date(+e[1],+(e[2]||1)-1,+e[3]||1,+e[4]||0,+(e[5]||0),+e[6]||0,e[7]?+e[7].substring(0,3):0)}return null==t?new Date(NaN):new Date(Math.round(t))}function tc(t){if(0===t)return 0;var e=Math.floor(Math.log(t)/Math.LN10);return t/Math.pow(10,e)>=10&&e++,e}function ec(t,e){var n=tc(t),i=Math.pow(10,n),r=t/i;return t=(r<1.5?1:r<2.5?2:r<4?3:r<7?5:10)*i,n>=-20?+t.toFixed(n<0?-n:0):t}function nc(t){var e=parseFloat(t);return e==t&&(0!==e||!er(t)||t.indexOf("x")<=0)?e:NaN}function ic(){return Math.round(9*Math.random())}function rc(t,e){return 0===e?t:rc(e,t%e)}function oc(t,e){return null==t?e:null==e?t:t*e/rc(t,e)}var ac="undefined"!=typeof console&&console.warn&&console.log;function sc(t,e){!function(t,e){ac&&console[t]("[ECharts] "+e)}("error",t)}function lc(t){throw new Error(t)}function cc(t,e,n){return(e-t)*n+t}var uc="series\0";function dc(t){return t instanceof Array?t:null==t?[]:[t]}function hc(t,e,n){if(t){t[e]=t[e]||{},t.emphasis=t.emphasis||{},t.emphasis[e]=t.emphasis[e]||{};for(var i=0,r=n.length;i=0||r&&Wi(r,s)<0)){var l=n.getShallow(s,e);null!=l&&(o[t[a][0]]=l)}}return o}}var $c=Bc([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),Fc=function(){function t(){}return t.prototype.getAreaStyle=function(t,e){return $c(this,t,e)},t}(),Vc=new La(50);function Wc(t){if("string"==typeof t){var e=Vc.get(t);return e&&e.image}return t}function jc(t,e,n,i,r){if(t){if("string"==typeof t){if(e&&e.__zrImageSrc===t||!n)return e;var o=Vc.get(t),a={hostEl:n,cb:i,cbPayload:r};return o?!Uc(e=o.image)&&o.pending.push(a):((e=Ci.loadImage(t,qc,qc)).__zrImageSrc=t,Vc.put(t,e.__cachedImgObj={image:e,pending:[a]})),e}return t}return e}function qc(){var t=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=s;c++)l-=s;var u=gl(a,n);return u>l&&(n="",u=0),l=t-u,r.ellipsis=n,r.ellipsisWidth=u,r.contentWidth=l,r.containerWidth=t,r}function Zc(t,e,n){var i=n.containerWidth,r=n.contentWidth,o=n.fontMeasureInfo;if(!i)return t.textLine="",void(t.isTruncated=!1);var a=gl(o,e);if(a<=i)return t.textLine=e,void(t.isTruncated=!1);for(var s=0;;s++){if(a<=r||s>=n.maxIterations){e+=n.ellipsis;break}var l=0===s?Kc(e,r,o):a>0?Math.floor(e.length*r/a):0;a=gl(o,e=e.substr(0,l))}""===e&&(e=n.placeholder),t.textLine=e,t.isTruncated=!0}function Kc(t,e,n){for(var i=0,r=0,o=t.length;r0&&f+i.accumWidth>i.width&&(o=e.split("\n"),d=!0),i.accumWidth=f}else{var g=ru(e,u,i.width,i.breakAll,i.accumWidth);i.accumWidth=g.accumWidth+p,a=g.linesWidths,o=g.lines}}o||(o=e.split("\n"));for(var m=dl(u),v=0;v=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}(t)||!!nu[t]}function ru(t,e,n,i,r){for(var o=[],a=[],s="",l="",c=0,u=0,d=dl(e),h=0;hn:r+u+f>n)?u?(s||l)&&(g?(s||(s=l,l="",u=c=0),o.push(s),a.push(u-c),l+=p,s="",u=c+=f):(l&&(s+=l,l="",c=0),o.push(s),a.push(u),s=p,u=f)):g?(o.push(l),a.push(c),l=p,c=f):(o.push(p),a.push(f)):(u+=f,g?(l+=p,c+=f):(l&&(s+=l,l="",c=0),s+=p))}else l&&(s+=l,u+=c),o.push(s),a.push(u),s="",l="",c=0,u=0}return l&&(s+=l),s&&(o.push(s),a.push(u)),1===o.length&&(u+=r),{accumWidth:u,lines:o,linesWidths:a}}function ou(t,e,n,i,r,o){if(t.baseX=n,t.baseY=i,t.outerWidth=t.outerHeight=null,e){var a=2*e.width,s=2*e.height;Lo.set(au,yl(n,a,r),_l(i,s,o),a,s),Lo.intersect(e,au,null,su);var l=su.outIntersectRect;t.outerWidth=l.width,t.outerHeight=l.height,t.baseX=yl(l.x,l.width,r,!0),t.baseY=_l(l.y,l.height,o,!0)}}var au=new Lo(0,0,0,0),su={outIntersectRect:{},clamp:!0};function lu(t){return null!=t?t+="":t=""}function cu(t,e,n,i){var r=new Lo(yl(t.x||0,e,t.textAlign),_l(t.y||0,n,t.textBaseline),e,n),o=null!=i?i:uu(t)?t.lineWidth:0;return o>0&&(r.x-=o/2,r.y-=o/2,r.width+=o,r.height+=o),r}function uu(t){var e=t.stroke;return null!=e&&"none"!==e&&t.lineWidth>0}var du="__zr_style_"+Math.round(10*Math.random()),hu={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},pu={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};hu[du]=!0;var fu=["z","z2","invisible"],gu=["invisible"],mu=function(t){function e(e){return t.call(this,e)||this}var n;return S(e,t),e.prototype._init=function(e){for(var n=Zi(e),i=0;i1e-4)return s[0]=t-n,s[1]=e-i,l[0]=t+n,void(l[1]=e+i);if(Cu[0]=wu(r)*n+t,Cu[1]=xu(r)*i+e,ku[0]=wu(o)*n+t,ku[1]=xu(o)*i+e,c(s,Cu,ku),u(l,Cu,ku),(r%=Su)<0&&(r+=Su),(o%=Su)<0&&(o+=Su),r>o&&!a?o+=Su:rr&&(Mu[0]=wu(p)*n+t,Mu[1]=xu(p)*i+e,c(s,Mu,s),u(l,Mu,l))}var Eu={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},Nu=[],Ru=[],Ou=[],zu=[],Hu=[],Bu=[],$u=Math.min,Fu=Math.max,Vu=Math.cos,Wu=Math.sin,ju=Math.abs,qu=Math.PI,Uu=2*qu,Gu="undefined"!=typeof Float32Array,Xu=[];function Yu(t){return Math.round(t/qu*1e8)/1e8%2*qu}var Zu=function(){function t(t){this.dpr=1,this._xi=0,this._yi=0,this._x0=0,this._y0=0,this._len=0,t&&(this._saveData=!1),this._saveData&&(this.data=[])}var e;return t.prototype.increaseVersion=function(){this._version++},t.prototype.getVersion=function(){return this._version},t.prototype.setScale=function(t,e,n){(n=n||0)>0&&(this._ux=ju(n/Ks/t)||0,this._uy=ju(n/Ks/e)||0)},t.prototype.setDPR=function(t){this.dpr=t},t.prototype.setContext=function(t){this._ctx=t},t.prototype.getContext=function(){return this._ctx},t.prototype.beginPath=function(){return this._ctx&&this._ctx.beginPath(),this.reset(),this},t.prototype.reset=function(){this._saveData&&(this._len=0),this._pathSegLen&&(this._pathSegLen=null,this._pathLen=0),this._version++},t.prototype.moveTo=function(t,e){return this._drawPendingPt(),this.addData(Eu.M,t,e),this._ctx&&this._ctx.moveTo(t,e),this._x0=t,this._y0=e,this._xi=t,this._yi=e,this},t.prototype.lineTo=function(t,e){var n=ju(t-this._xi),i=ju(e-this._yi),r=n>this._ux||i>this._uy;if(this.addData(Eu.L,t,e),this._ctx&&r&&this._ctx.lineTo(t,e),r)this._xi=t,this._yi=e,this._pendingPtDist=0;else{var o=n*n+i*i;o>this._pendingPtDist&&(this._pendingPtX=t,this._pendingPtY=e,this._pendingPtDist=o)}return this},t.prototype.bezierCurveTo=function(t,e,n,i,r,o){return this._drawPendingPt(),this.addData(Eu.C,t,e,n,i,r,o),this._ctx&&this._ctx.bezierCurveTo(t,e,n,i,r,o),this._xi=r,this._yi=o,this},t.prototype.quadraticCurveTo=function(t,e,n,i){return this._drawPendingPt(),this.addData(Eu.Q,t,e,n,i),this._ctx&&this._ctx.quadraticCurveTo(t,e,n,i),this._xi=n,this._yi=i,this},t.prototype.arc=function(t,e,n,i,r,o){this._drawPendingPt(),Xu[0]=i,Xu[1]=r,function(t,e){var n=Yu(t[0]);n<0&&(n+=Uu);var i=n-t[0],r=t[1];r+=i,!e&&r-n>=Uu?r=n+Uu:e&&n-r>=Uu?r=n-Uu:!e&&n>r?r=n+(Uu-Yu(n-r)):e&&n0&&o))for(var a=0;ac.length&&(this._expandData(),c=this.data);for(var u=0;u0&&(this._ctx&&this._ctx.lineTo(this._pendingPtX,this._pendingPtY),this._pendingPtDist=0)},t.prototype._expandData=function(){if(!(this.data instanceof Array)){for(var t=[],e=0;e11&&(this.data=new Float32Array(t)))}},t.prototype.getBoundingRect=function(){Ou[0]=Ou[1]=Hu[0]=Hu[1]=Number.MAX_VALUE,zu[0]=zu[1]=Bu[0]=Bu[1]=-Number.MAX_VALUE;var t,e=this.data,n=0,i=0,r=0,o=0;for(t=0;tn||ju(m)>i||d===e-1)&&(f=Math.sqrt(I*I+m*m),r=g,o=_);break;case Eu.C:var v=t[d++],y=t[d++],_=(g=t[d++],t[d++]),b=t[d++],x=t[d++];f=xa(r,o,v,y,g,_,b,x,10),r=b,o=x;break;case Eu.Q:f=Ma(r,o,v=t[d++],y=t[d++],g=t[d++],_=t[d++],10),r=g,o=_;break;case Eu.A:var w=t[d++],S=t[d++],C=t[d++],k=t[d++],M=t[d++],T=t[d++],A=T+M;d+=1,p&&(a=Vu(M)*C+w,s=Wu(M)*k+S),f=Fu(C,k)*$u(Uu,Math.abs(T)),r=Vu(A)*C+w,o=Wu(A)*k+S;break;case Eu.R:a=r=t[d++],s=o=t[d++],f=2*t[d++]+2*t[d++];break;case Eu.Z:var I=a-r;m=s-o;f=Math.sqrt(I*I+m*m),r=a,o=s}f>=0&&(l[u++]=f,c+=f)}return this._pathLen=c,c},t.prototype.rebuildPath=function(t,e){var n,i,r,o,a,s,l,c,u,d,h=this.data,p=this._ux,f=this._uy,g=this._len,m=e<1,v=0,y=0,_=0;if(!m||(this._pathSegLen||this._calculateLength(),l=this._pathSegLen,c=e*this._pathLen))t:for(var b=0;b0&&(t.lineTo(u,d),_=0),x){case Eu.M:n=r=h[b++],i=o=h[b++],t.moveTo(r,o);break;case Eu.L:a=h[b++],s=h[b++];var S=ju(a-r),C=ju(s-o);if(S>p||C>f){if(m){if(v+(X=l[y++])>c){var k=(c-v)/X;t.lineTo(r*(1-k)+a*k,o*(1-k)+s*k);break t}v+=X}t.lineTo(a,s),r=a,o=s,_=0}else{var M=S*S+C*C;M>_&&(u=a,d=s,_=M)}break;case Eu.C:var T=h[b++],A=h[b++],I=h[b++],D=h[b++],P=h[b++],L=h[b++];if(m){if(v+(X=l[y++])>c){ba(r,T,I,P,k=(c-v)/X,Nu),ba(o,A,D,L,k,Ru),t.bezierCurveTo(Nu[1],Ru[1],Nu[2],Ru[2],Nu[3],Ru[3]);break t}v+=X}t.bezierCurveTo(T,A,I,D,P,L),r=P,o=L;break;case Eu.Q:T=h[b++],A=h[b++],I=h[b++],D=h[b++];if(m){if(v+(X=l[y++])>c){ka(r,T,I,k=(c-v)/X,Nu),ka(o,A,D,k,Ru),t.quadraticCurveTo(Nu[1],Ru[1],Nu[2],Ru[2]);break t}v+=X}t.quadraticCurveTo(T,A,I,D),r=I,o=D;break;case Eu.A:var E=h[b++],N=h[b++],R=h[b++],O=h[b++],z=h[b++],H=h[b++],B=h[b++],$=!h[b++],F=R>O?R:O,V=ju(R-O)>.001,W=z+H,j=!1;if(m)v+(X=l[y++])>c&&(W=z+H*(c-v)/X,j=!0),v+=X;if(V&&t.ellipse?t.ellipse(E,N,R,O,B,z,W,$):t.arc(E,N,F,z,W,$),j)break t;w&&(n=Vu(z)*R+E,i=Wu(z)*O+N),r=Vu(W)*R+E,o=Wu(W)*O+N;break;case Eu.R:n=r=h[b],i=o=h[b+1],a=h[b++],s=h[b++];var q=h[b++],U=h[b++];if(m){if(v+(X=l[y++])>c){var G=c-v;t.moveTo(a,s),t.lineTo(a+$u(G,q),s),(G-=q)>0&&t.lineTo(a+q,s+$u(G,U)),(G-=U)>0&&t.lineTo(a+Fu(q-G,0),s+U),(G-=q)>0&&t.lineTo(a,s+Fu(U-G,0));break t}v+=X}t.rect(a,s,q,U);break;case Eu.Z:if(m){var X;if(v+(X=l[y++])>c){k=(c-v)/X;t.lineTo(r*(1-k)+n*k,o*(1-k)+i*k);break t}v+=X}t.closePath(),r=n,o=i}}},t.prototype.clone=function(){var e=new t,n=this.data;return e.data=n.slice?n.slice():Array.prototype.slice.call(n),e._len=this._len,e},t.prototype.canSave=function(){return!!this._saveData},t.CMD=Eu,t.initDefaultProps=((e=t.prototype)._saveData=!0,e._ux=0,e._uy=0,e._pendingPtDist=0,void(e._version=0)),t}();function Ku(t,e,n,i,r,o,a){if(0===r)return!1;var s=r,l=0;if(a>e+s&&a>i+s||at+s&&o>n+s||oe+d&&u>i+d&&u>o+d&&u>s+d||ut+d&&c>n+d&&c>r+d&&c>a+d||c=0&&pe+c&&l>i+c&&l>o+c||lt+c&&s>n+c&&s>r+c||s=0&&gn||u+cr&&(r+=nd);var h=Math.atan2(l,s);return h<0&&(h+=nd),h>=i&&h<=r||h+nd>=i&&h+nd<=r}function rd(t,e,n,i,r,o){if(o>e&&o>i||or?s:0}var od=Zu.CMD,ad=2*Math.PI;var sd=[-1,-1,-1],ld=[-1,-1];function cd(){var t=ld[0];ld[0]=ld[1],ld[1]=t}function ud(t,e,n,i,r,o,a,s,l,c){if(c>e&&c>i&&c>o&&c>s||c1&&cd(),p=ma(e,i,o,s,ld[0]),h>1&&(f=ma(e,i,o,s,ld[1]))),2===h?me&&s>i&&s>o||s=0&&u<=1&&(r[l++]=u);else{var c=a*a-4*o*s;if(fa(c))(u=-a/(2*o))>=0&&u<=1&&(r[l++]=u);else if(c>0){var u,d=aa(c),h=(-a-d)/(2*o);(u=(-a+d)/(2*o))>=0&&u<=1&&(r[l++]=u),h>=0&&h<=1&&(r[l++]=h)}}return l}(e,i,o,s,sd);if(0===l)return 0;var c=Ca(e,i,o);if(c>=0&&c<=1){for(var u=0,d=wa(e,i,o,c),h=0;hn||s<-n)return 0;var l=Math.sqrt(n*n-s*s);sd[0]=-l,sd[1]=l;var c=Math.abs(i-r);if(c<1e-4)return 0;if(c>=ad-1e-4){i=0,r=ad;var u=o?1:-1;return a>=sd[0]+t&&a<=sd[1]+t?u:0}if(i>r){var d=i;i=r,r=d}i<0&&(i+=ad,r+=ad);for(var h=0,p=0;p<2;p++){var f=sd[p];if(f+t>a){var g=Math.atan2(s,f);u=o?1:-1;g<0&&(g=ad+g),(g>=i&&g<=r||g+ad>=i&&g+ad<=r)&&(g>Math.PI/2&&g<1.5*Math.PI&&(u=-u),h+=u)}}return h}function pd(t,e,n,i,r){for(var o,a,s=t.data,l=t.len(),c=0,u=0,d=0,h=0,p=0,f=0;f1&&(n||(c+=rd(u,d,h,p,i,r))),m&&(h=u=s[f],p=d=s[f+1]),g){case od.M:u=h=s[f++],d=p=s[f++];break;case od.L:if(n){if(Ku(u,d,s[f],s[f+1],e,i,r))return!0}else c+=rd(u,d,s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case od.C:if(n){if(Qu(u,d,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=ud(u,d,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case od.Q:if(n){if(Ju(u,d,s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=dd(u,d,s[f++],s[f++],s[f],s[f+1],i,r)||0;u=s[f++],d=s[f++];break;case od.A:var v=s[f++],y=s[f++],_=s[f++],b=s[f++],x=s[f++],w=s[f++];f+=1;var S=!!(1-s[f++]);o=Math.cos(x)*_+v,a=Math.sin(x)*b+y,m?(h=o,p=a):c+=rd(u,d,o,a,i,r);var C=(i-v)*b/_+v;if(n){if(id(v,y,b,x,x+w,S,e,C,r))return!0}else c+=hd(v,y,b,x,x+w,S,C,r);u=Math.cos(x+w)*_+v,d=Math.sin(x+w)*b+y;break;case od.R:if(h=u=s[f++],p=d=s[f++],o=h+s[f++],a=p+s[f++],n){if(Ku(h,p,o,p,e,i,r)||Ku(o,p,o,a,e,i,r)||Ku(o,a,h,a,e,i,r)||Ku(h,a,h,p,e,i,r))return!0}else c+=rd(o,p,o,a,i,r),c+=rd(h,a,h,p,i,r);break;case od.Z:if(n){if(Ku(u,d,h,p,e,i,r))return!0}else c+=rd(u,d,h,p,i,r);u=h,d=p}}return n||function(t,e){return Math.abs(t-e)<1e-4}(d,p)||(c+=rd(u,d,h,p,i,r)||0),0!==c}var fd=Vi({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},hu),gd={style:Vi({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},pu.style)},md=cl.concat(["invisible","culling","z","z2","zlevel","parent"]),vd=function(t){function e(e){return t.call(this,e)||this}var n;return S(e,t),e.prototype.update=function(){var n=this;t.prototype.update.call(this);var i=this.style;if(i.decal){var r=this._decalEl=this._decalEl||new e;r.buildPath===e.prototype.buildPath&&(r.buildPath=function(t){n.buildPath(t,n.shape)}),r.silent=!0;var o=r.style;for(var a in i)o[a]!==i[a]&&(o[a]=i[a]);o.fill=i.fill?i.decal:null,o.decal=null,o.shadowColor=null,i.strokeFirst&&(o.stroke=null);for(var s=0;s.5?Qs:e>.2?"#eee":Js}if(t)return Js}return Qs},e.prototype.getInsideTextStroke=function(t){var e=this.style.fill;if(er(e)){var n=this.__zr;if(!(!n||!n.isDarkMode())===Za(t,0)<.4)return e}},e.prototype.buildPath=function(t,e,n){},e.prototype.pathUpdated=function(){this.__dirty&=-5},e.prototype.getUpdatedPathProxy=function(t){return!this.path&&this.createPathProxy(),this.path.beginPath(),this.buildPath(this.path,this.shape,t),this.path},e.prototype.createPathProxy=function(){this.path=new Zu(!1)},e.prototype.hasStroke=function(){var t=this.style,e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))},e.prototype.hasFill=function(){var t=this.style.fill;return null!=t&&"none"!==t},e.prototype.getBoundingRect=function(){var t=this._rect,e=this.style,n=!t;if(n){var i=!1;this.path||(i=!0,this.createPathProxy());var r=this.path;(i||4&this.__dirty)&&(r.beginPath(),this.buildPath(r,this.shape,!1),this.pathUpdated()),t=r.getBoundingRect()}if(this._rect=t,this.hasStroke()&&this.path&&this.path.len()>0){var o=this._rectStroke||(this._rectStroke=t.clone());if(this.__dirty||n){o.copy(t);var a=e.strokeNoScale?this.getLineScale():1,s=e.lineWidth;if(!this.hasFill()){var l=this.strokeContainThreshold;s=Math.max(s,null==l?4:l)}a>1e-10&&(o.width+=s/a,o.height+=s/a,o.x-=s/a/2,o.y-=s/a/2)}return o}return t},e.prototype.contain=function(t,e){var n=this.transformCoordToLocal(t,e),i=this.getBoundingRect(),r=this.style;if(t=n[0],e=n[1],i.contain(t,e)){var o=this.path;if(this.hasStroke()){var a=r.lineWidth,s=r.strokeNoScale?this.getLineScale():1;if(s>1e-10&&(this.hasFill()||(a=Math.max(a,this.strokeContainThreshold)),function(t,e,n,i){return pd(t,e,!0,n,i)}(o,a/s,t,e)))return!0}if(this.hasFill())return function(t,e,n){return pd(t,0,!1,e,n)}(o,t,e)}return!1},e.prototype.dirtyShape=function(){this.__dirty|=4,this._rect&&(this._rect=null),this._decalEl&&this._decalEl.dirtyShape(),this.markRedraw()},e.prototype.dirty=function(){this.dirtyStyle(),this.dirtyShape()},e.prototype.animateShape=function(t){return this.animate("shape",t)},e.prototype.updateDuringAnimation=function(t){"style"===t?this.dirtyStyle():"shape"===t?this.dirtyShape():this.markRedraw()},e.prototype.attrKV=function(e,n){"shape"===e?this.setShape(n):t.prototype.attrKV.call(this,e,n)},e.prototype.setShape=function(t,e){var n=this.shape;return n||(n=this.shape={}),"string"==typeof t?n[t]=e:Fi(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(4&this.__dirty)},e.prototype.createStyle=function(t){return Cr(fd,t)},e.prototype._innerSaveToNormal=function(e){t.prototype._innerSaveToNormal.call(this,e);var n=this._normalState;e.shape&&!n.shape&&(n.shape=Fi({},this.shape))},e.prototype._applyStateObj=function(e,n,i,r,o,a){t.prototype._applyStateObj.call(this,e,n,i,r,o,a);var s,l=!(n&&r);if(n&&n.shape?o?r?s=n.shape:(s=Fi({},i.shape),Fi(s,n.shape)):(s=Fi({},r?this.shape:i.shape),Fi(s,n.shape)):l&&(s=i.shape),s)if(o){this.shape=Fi({},this.shape);for(var c={},u=Zi(s),d=0;dc&&(n*=c/(a=n+i),i*=c/a),r+o>c&&(r*=c/(a=r+o),o*=c/a),i+r>u&&(i*=u/(a=i+r),r*=u/a),n+o>u&&(n*=u/(a=n+o),o*=u/a),t.moveTo(s+n,l),t.lineTo(s+c-i,l),0!==i&&t.arc(s+c-i,l+i,i,-Math.PI/2,0),t.lineTo(s+c,l+u-r),0!==r&&t.arc(s+c-r,l+u-r,r,0,Math.PI/2),t.lineTo(s+o,l+u),0!==o&&t.arc(s+o,l+u-o,o,Math.PI/2,Math.PI),t.lineTo(s,l+n),0!==n&&t.arc(s+n,l+n,n,Math.PI,1.5*Math.PI)}(t,e):t.rect(n,i,r,o)},e.prototype.isZeroArea=function(){return!this.shape.width||!this.shape.height},e}(vd);Id.prototype.type="rect";var Dd={fill:"#000"},Pd={},Ld={style:Vi({fill:!0,stroke:!0,fillOpacity:!0,strokeOpacity:!0,lineWidth:!0,fontSize:!0,lineHeight:!0,width:!0,height:!0,textShadowColor:!0,textShadowBlur:!0,textShadowOffsetX:!0,textShadowOffsetY:!0,backgroundColor:!0,padding:!0,borderColor:!0,borderWidth:!0,borderRadius:!0},pu.style)},Ed=function(t){function e(e){var n=t.call(this)||this;return n.type="text",n._children=[],n._defaultStyle=Dd,n.attr(e),n}return S(e,t),e.prototype.childrenRef=function(){return this._children},e.prototype.update=function(){t.prototype.update.call(this),this.styleChanged()&&this._updateSubTexts();for(var e=0;ev&&p){var _=Math.floor(v/h);f=f||m.length>_,y=(m=m.slice(0,_)).length*h}if(r&&u&&null!=g)for(var b=Yc(g,c,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),x={},w=0;w0,k=0;kg&&eu(o,a.substring(g,m),e,f),eu(o,h[2],e,f,h[1]),g=Gc.lastIndex}gd){var N=o.lines.length;A>0?(k.tokens=k.tokens.slice(0,A),S(k,T,M),o.lines=o.lines.slice(0,C+1)):o.lines=o.lines.slice(0,C),o.isTruncated=o.isTruncated||o.lines.length=0&&"right"===(T=_[M]).align;)this._placeToken(T,t,x,f,k,"right",m),w-=T.width,k-=T.width,M--;for(C+=(s-(C-p)-(g-k)-w)/2;S<=M;)T=_[S],this._placeToken(T,t,x,f,C+T.width/2,"center",m),C+=T.width,S++;f+=x}},e.prototype._placeToken=function(t,e,n,i,r,o,a){var s=e.rich[t.styleName]||{};s.text=t.text;var l=t.verticalAlign,c=i+n/2;"top"===l?c=i+t.height/2:"bottom"===l&&(c=i+n-t.height/2),!t.isLineHolder&&qd(s)&&this._renderBackground(s,e,"right"===o?r-t.width:"center"===o?r-t.width/2:r,c-t.height/2,t.width,t.height);var u=!!s.backgroundColor,d=t.textPadding;d&&(r=Wd(r,o,d),c-=t.height/2-d[0]-t.innerHeight/2);var h=this._getOrCreateChild(_d),p=h.createStyle();h.useStyle(p);var f=this._defaultStyle,g=!1,m=0,v=!1,y=Vd("fill"in s?s.fill:"fill"in e?e.fill:(g=!0,f.fill)),_=Fd("stroke"in s?s.stroke:"stroke"in e?e.stroke:u||a||f.autoStroke&&!g?null:(m=2,v=!0,f.stroke)),b=s.textShadowBlur>0||e.textShadowBlur>0;p.text=t.text,p.x=r,p.y=c,b&&(p.shadowBlur=s.textShadowBlur||e.textShadowBlur||0,p.shadowColor=s.textShadowColor||e.textShadowColor||"transparent",p.shadowOffsetX=s.textShadowOffsetX||e.textShadowOffsetX||0,p.shadowOffsetY=s.textShadowOffsetY||e.textShadowOffsetY||0),p.textAlign=o,p.textBaseline="middle",p.font=t.font||bi,p.opacity=hr(s.opacity,e.opacity,1),Hd(p,s),_&&(p.lineWidth=hr(s.lineWidth,e.lineWidth,m),p.lineDash=dr(s.lineDash,e.lineDash),p.lineDashOffset=e.lineDashOffset||0,p.stroke=_),y&&(p.fill=y),h.setBoundingRect(cu(p,t.contentWidth,t.contentHeight,v?0:null))},e.prototype._renderBackground=function(t,e,n,i,r,o){var a,s,l,c=t.backgroundColor,u=t.borderWidth,d=t.borderColor,h=c&&c.image,p=c&&!h,f=t.borderRadius,g=this;if(p||t.lineHeight||u&&d){(a=this._getOrCreateChild(Id)).useStyle(a.createStyle()),a.style.fill=null;var m=a.shape;m.x=n,m.y=i,m.width=r,m.height=o,m.r=f,a.dirtyShape()}if(p)(l=a.style).fill=c||null,l.fillOpacity=dr(t.fillOpacity,1);else if(h){(s=this._getOrCreateChild(wd)).onload=function(){g.dirtyStyle()};var v=s.style;v.image=c.image,v.x=n,v.y=i,v.width=r,v.height=o}u&&d&&((l=a.style).lineWidth=u,l.stroke=d,l.strokeOpacity=dr(t.strokeOpacity,1),l.lineDash=t.borderDash,l.lineDashOffset=t.borderDashOffset||0,a.strokeContainThreshold=0,a.hasFill()&&a.hasStroke()&&(l.strokeFirst=!0,l.lineWidth*=2));var y=(a||s).style;y.shadowBlur=t.shadowBlur||0,y.shadowColor=t.shadowColor||"transparent",y.shadowOffsetX=t.shadowOffsetX||0,y.shadowOffsetY=t.shadowOffsetY||0,y.opacity=hr(t.opacity,e.opacity,1)},e.makeFont=function(t){var e="";return Bd(t)&&(e=[t.fontStyle,t.fontWeight,zd(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),e&&mr(e)||t.textFont||t.font},e}(mu),Nd={left:!0,right:1,center:1},Rd={top:1,bottom:1,middle:1},Od=["fontStyle","fontWeight","fontSize","fontFamily"];function zd(t){return"string"!=typeof t||-1===t.indexOf("px")&&-1===t.indexOf("rem")&&-1===t.indexOf("em")?isNaN(+t)?"12px":t+"px":t}function Hd(t,e){for(var n=0;n=0,o=!1;if(t instanceof vd){var a=Yd(t),s=r&&a.selectFill||a.normalFill,l=r&&a.selectStroke||a.normalStroke;if(oh(s)||oh(l)){var c=(i=i||{}).style||{};"inherit"===c.fill?(o=!0,i=Fi({},i),(c=Fi({},c)).fill=s):!oh(c.fill)&&oh(s)?(o=!0,i=Fi({},i),(c=Fi({},c)).fill=Qa(s)):!oh(c.stroke)&&oh(l)&&(o||(i=Fi({},i),c=Fi({},c)),c.stroke=Qa(l)),i.style=c}}if(i&&null==i.z2){o||(i=Fi({},i));var u=t.z2EmphasisLift;i.z2=t.z2+(null!=u?u:10)}return i}(this,0,e,n);if("blur"===t)return function(t,e,n){var i=Wi(t.currentStates,e)>=0,r=t.style.opacity,o=i?null:function(t,e,n,i){for(var r=t.style,o={},a=0;a0){var o={dataIndex:r,seriesIndex:t.seriesIndex};null!=i&&(o.dataType=i),e.push(o)}})}),e}function Lh(t,e,n){zh(t,!0),fh(t,vh),function(t,e,n){var i=Ud(t);null!=e?(i.focus=e,i.blurScope=n):i.focus&&(i.focus=null)}(t,e,n)}function Eh(t,e,n,i){i?function(t){zh(t,!1)}(t):Lh(t,e,n)}var Nh=["emphasis","blur","select"],Rh={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function Oh(t,e,n,i){n=n||"itemStyle";for(var r=0;r1&&(a*=qh(f),s*=qh(f));var g=(r===o?-1:1)*qh((a*a*(s*s)-a*a*(p*p)-s*s*(h*h))/(a*a*(p*p)+s*s*(h*h)))||0,m=g*a*p/s,v=g*-s*h/a,y=(t+n)/2+Gh(d)*m-Uh(d)*v,_=(e+i)/2+Uh(d)*m+Gh(d)*v,b=Kh([1,0],[(h-m)/a,(p-v)/s]),x=[(h-m)/a,(p-v)/s],w=[(-1*h-m)/a,(-1*p-v)/s],S=Kh(x,w);if(Zh(x,w)<=-1&&(S=Xh),Zh(x,w)>=1&&(S=0),S<0){var C=Math.round(S/Xh*1e6)/1e6;S=2*Xh+C%2*Xh}u.addData(c,y,_,a,s,b,S,d,o)}var Jh=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,tp=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;var ep=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.applyTransform=function(t){},e}(vd);function np(t){return null!=t.setData}function ip(t,e){var n=function(t){var e=new Zu;if(!t)return e;var n,i=0,r=0,o=i,a=r,s=Zu.CMD,l=t.match(Jh);if(!l)return e;for(var c=0;cD*D+P*P&&(C=M,k=T),{cx:C,cy:k,x0:-u,y0:-d,x1:C*(r/x-1),y1:k*(r/x-1)}}function bp(t,e){var n,i=mp(e.r,0),r=mp(e.r0||0,0),o=i>0;if(o||r>0){if(o||(i=r,r=0),r>i){var a=i;i=r,r=a}var s=e.startAngle,l=e.endAngle;if(!isNaN(s)&&!isNaN(l)){var c=e.cx,u=e.cy,d=!!e.clockwise,h=fp(l-s),p=h>cp&&h%cp;if(p>yp&&(h=p),i>yp)if(h>cp-yp)t.moveTo(c+i*dp(s),u+i*up(s)),t.arc(c,u,i,s,l,!d),r>yp&&(t.moveTo(c+r*dp(l),u+r*up(l)),t.arc(c,u,r,l,s,d));else{var f=void 0,g=void 0,m=void 0,v=void 0,y=void 0,_=void 0,b=void 0,x=void 0,w=void 0,S=void 0,C=void 0,k=void 0,M=void 0,T=void 0,A=void 0,I=void 0,D=i*dp(s),P=i*up(s),L=r*dp(l),E=r*up(l),N=h>yp;if(N){var R=e.cornerRadius;R&&(n=function(t){var e;if(Ji(t)){var n=t.length;if(!n)return t;e=1===n?[t[0],t[0],0,0]:2===n?[t[0],t[0],t[1],t[1]]:3===n?t.concat(t[2]):t}else e=[t,t,t,t];return e}(R),f=n[0],g=n[1],m=n[2],v=n[3]);var O=fp(i-r)/2;if(y=vp(O,m),_=vp(O,v),b=vp(O,f),x=vp(O,g),C=w=mp(y,_),k=S=mp(b,x),(w>yp||S>yp)&&(M=i*dp(l),T=i*up(l),A=r*dp(s),I=r*up(s),hyp){var j=vp(m,C),q=vp(v,C),U=_p(A,I,D,P,i,j,d),G=_p(M,T,L,E,i,q,d);t.moveTo(c+U.cx+U.x0,u+U.cy+U.y0),C0&&t.arc(c+U.cx,u+U.cy,j,pp(U.y0,U.x0),pp(U.y1,U.x1),!d),t.arc(c,u,i,pp(U.cy+U.y1,U.cx+U.x1),pp(G.cy+G.y1,G.cx+G.x1),!d),q>0&&t.arc(c+G.cx,u+G.cy,q,pp(G.y1,G.x1),pp(G.y0,G.x0),!d))}else t.moveTo(c+D,u+P),t.arc(c,u,i,s,l,!d);else t.moveTo(c+D,u+P);if(r>yp&&N)if(k>yp){j=vp(f,k),U=_p(L,E,M,T,r,-(q=vp(g,k)),d),G=_p(D,P,A,I,r,-j,d);t.lineTo(c+U.cx+U.x0,u+U.cy+U.y0),k0&&t.arc(c+U.cx,u+U.cy,q,pp(U.y0,U.x0),pp(U.y1,U.x1),!d),t.arc(c,u,r,pp(U.cy+U.y1,U.cx+U.x1),pp(G.cy+G.y1,G.cx+G.x1),d),j>0&&t.arc(c+G.cx,u+G.cy,j,pp(G.y1,G.x1),pp(G.y0,G.x0),!d))}else t.lineTo(c+L,u+E),t.arc(c,u,r,l,s,d);else t.lineTo(c+L,u+E)}else t.moveTo(c,u);t.closePath()}}}var xp=function(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=2*Math.PI,this.clockwise=!0,this.cornerRadius=0},wp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new xp},e.prototype.buildPath=function(t,e){bp(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(vd);wp.prototype.type="sector";var Sp=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},Cp=function(t){function e(e){return t.call(this,e)||this}return S(e,t),e.prototype.getDefaultShape=function(){return new Sp},e.prototype.buildPath=function(t,e){var n=e.cx,i=e.cy,r=2*Math.PI;t.moveTo(n+e.r,i),t.arc(n,i,e.r,0,r,!1),t.moveTo(n+e.r0,i),t.arc(n,i,e.r0,0,r,!0)},e}(vd);function kp(t,e,n){var i=e.smooth,r=e.points;if(r&&r.length>=2){if(i){var o=function(t,e,n,i){var r,o,a,s,l=[],c=[],u=[],d=[];if(i){a=[1/0,1/0],s=[-1/0,-1/0];for(var h=0,p=t.length;hGp[1]){if(r=!1,Xp.negativeSize||n)return r;var s=qp(Gp[0]-Up[1]),l=qp(Up[0]-Gp[1]);Wp(s,l)>Zp.len()&&(s=l||!Xp.bidirectional)&&(yo.scale(Yp,a,-l*i),Xp.useDir&&Xp.calcDirMTV()))}}return r},t.prototype._getProjMinMaxOnAxis=function(t,e,n){for(var i=this._axes[t],r=this._origin,o=e[0].dot(i)+r[t],a=o,s=o,l=1;l0){var d={duration:u.duration,delay:u.delay||0,easing:u.easing,done:o,force:!!o||!!a,setToFinal:!c,scope:t,during:a};l?e.animateFrom(n,d):e.animateTo(n,d)}else e.stopAnimation(),!l&&e.attr(n),a&&a(1),o&&o()}function nf(t,e,n,i,r,o){ef("update",t,e,n,i,r,o)}function rf(t,e,n,i,r,o){ef("enter",t,e,n,i,r,o)}function of(t){if(!t.__zr)return!0;for(var e=0;e=-1e-6)return!1;var f=t-r,g=e-o,m=kf(f,g,c,u)/p;if(m<0||m>1)return!1;var v=kf(f,g,d,h)/p;return!(v<0||v>1)}function kf(t,e,n,i){return t*i-n*e}function Mf(t,e,n,i,r){return null==e||(ir(e)?Tf[0]=Tf[1]=Tf[2]=Tf[3]=e:(Tf[0]=e[0],Tf[1]=e[1],Tf[2]=e[2],Tf[3]=e[3]),i&&(Tf[0]=Vl(0,Tf[0]),Tf[1]=Vl(0,Tf[1]),Tf[2]=Vl(0,Tf[2]),Tf[3]=Vl(0,Tf[3])),n&&(Tf[0]=-Tf[0],Tf[1]=-Tf[1],Tf[2]=-Tf[2],Tf[3]=-Tf[3]),Af(t,Tf,"x","width",3,1,r&&r[0]||0),Af(t,Tf,"y","height",0,2,r&&r[1]||0)),t}var Tf=[0,0,0,0];function Af(t,e,n,i,r,o,a){var s=e[o]+e[r],l=t[i];t[i]+=s,a=Vl(0,Fl(a,l)),t[i]=0?-e[r]:e[o]>=0?l+e[o]:Wl(s)>1e-8?(l-a)*e[r]/s:0):t[n]-=e[r]}function If(t){var e=t.itemTooltipOption,n=t.componentModel,i=t.itemName,r=er(e)?{formatter:e}:e,o=n.mainType,a=n.componentIndex,s={componentType:o,name:i,$vars:["name"]};s[o+"Index"]=a;var l=t.formatterParamsExtra;l&&Ui(Zi(l),function(t){kr(s,t)||(s[t]=l[t],s.$vars.push(t))});var c=Ud(t.el);c.componentMainType=o,c.componentIndex=a,c.tooltipConfig={name:i,option:Vi({content:i,encodeHTMLContent:!0,formatterParams:s},r)}}function Df(t,e){var n;t.isGroup&&(n=e(t)),n||t.traverse(e)}function Pf(t,e){if(t)if(Ji(t))for(var n=0;ne&&(e=i),ie&&(n=e=0),{min:n,max:e}},clipPointsByRect:function(t,e){return Gi(t,function(t){var n=t[0];n=Vl(n,e.x),n=Fl(n,e.x+e.width);var i=t[1];return i=Vl(i,e.y),[n,i=Fl(i,e.y+e.height)]})},clipRectByRect:function(t,e){var n=Vl(t.x,e.x),i=Fl(t.x+t.width,e.x+e.width),r=Vl(t.y,e.y),o=Fl(t.y+t.height,e.y+e.height);if(i>=n&&o>=r)return{x:n,y:r,width:i-n,height:o-r}},createIcon:Sf,ensureCopyRect:Nf,ensureCopyTransform:Rf,expandOrShrinkRect:Mf,extendPath:function(t,e){return df(t,e)},extendShape:function(t){return vd.extend(t)},getShapeClass:function(t){if(lf.hasOwnProperty(t))return lf[t]},getTransform:function(t,e){for(var n=ho([]);t&&t!==e;)fo(n,t.getLocalTransform(),n),t=t.parent;return n},groupTransition:wf,initProps:rf,isBoundingRectAxisAligned:Lf,isElementRemoved:of,lineLineIntersect:Cf,linePolygonIntersect:function(t,e,n,i,r){for(var o=0,a=r[r.length-1];oWl(o[1])?o[0]>0?"right":"left":o[1]>0?"bottom":"top"},traverseElements:Pf,traverseUpdateZ:zf,updateProps:nf}),$f={};function Ff(t,e,n){var i,r=t.labelFetcher,o=t.labelDataIndex,a=t.labelDimIndex,s=e.normal;r&&(i=r.getFormattedLabel(o,"normal",null,a,s&&s.get("formatter"),null!=n?{interpolatedValue:n}:null)),null==i&&(i=tr(t.defaultText)?t.defaultText(o,t,n):t.defaultText);for(var l={normal:i},c=0;c-1?pg:gg;function _g(t,e){t=t.toUpperCase(),vg[t]=new ug(e),mg[t]=e}_g(fg,{time:{month:["January","February","March","April","May","June","July","August","September","October","November","December"],monthAbbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayOfWeekAbbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},legend:{selector:{all:"All",inverse:"Inv"}},toolbox:{brush:{title:{rect:"Box Select",polygon:"Lasso Select",lineX:"Horizontally Select",lineY:"Vertically Select",keep:"Keep Selections",clear:"Clear Selections"}},dataView:{title:"Data View",lang:["Data View","Close","Refresh"]},dataZoom:{title:{zoom:"Zoom",back:"Zoom Reset"}},magicType:{title:{line:"Switch to Line Chart",bar:"Switch to Bar Chart",stack:"Stack",tiled:"Tile"}},restore:{title:"Restore"},saveAsImage:{title:"Save as Image",lang:["Right Click to Save Image"]}},series:{typeNames:{pie:"Pie chart",bar:"Bar chart",line:"Line chart",scatter:"Scatter plot",effectScatter:"Ripple scatter plot",radar:"Radar chart",tree:"Tree",treemap:"Treemap",boxplot:"Boxplot",candlestick:"Candlestick",k:"K line chart",heatmap:"Heat map",map:"Map",parallel:"Parallel coordinate map",lines:"Line graph",graph:"Relationship graph",sankey:"Sankey diagram",funnel:"Funnel chart",gauge:"Gauge",pictorialBar:"Pictorial bar",themeRiver:"Theme River Map",sunburst:"Sunburst",custom:"Custom chart",chart:"Chart"}},aria:{general:{withTitle:'This is a chart about "{title}"',withoutTitle:"This is a chart"},series:{single:{prefix:"",withName:" with type {seriesType} named {seriesName}.",withoutName:" with type {seriesType}."},multiple:{prefix:". It consists of {seriesCount} series count.",withName:" The {seriesId} series is a {seriesType} representing {seriesName}.",withoutName:" The {seriesId} series is a {seriesType}.",separator:{middle:"",end:""}}},data:{allData:"The data is as follows: ",partialData:"The first {displayCnt} items are: ",withName:"the data for {name} is {value}",withoutName:"{value}",separator:{middle:", ",end:". "}}}}),_g(pg,{time:{month:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],monthAbbr:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayOfWeek:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],dayOfWeekAbbr:["日","一","二","三","四","五","六"]},legend:{selector:{all:"全选",inverse:"反选"}},toolbox:{brush:{title:{rect:"矩形选择",polygon:"圈选",lineX:"横向选择",lineY:"纵向选择",keep:"保持选择",clear:"清除选择"}},dataView:{title:"数据视图",lang:["数据视图","关闭","刷新"]},dataZoom:{title:{zoom:"区域缩放",back:"区域缩放还原"}},magicType:{title:{line:"切换为折线图",bar:"切换为柱状图",stack:"切换为堆叠",tiled:"切换为平铺"}},restore:{title:"还原"},saveAsImage:{title:"保存为图片",lang:["右键另存为图片"]}},series:{typeNames:{pie:"饼图",bar:"柱状图",line:"折线图",scatter:"散点图",effectScatter:"涟漪散点图",radar:"雷达图",tree:"树图",treemap:"矩形树图",boxplot:"箱型图",candlestick:"K线图",k:"K线图",heatmap:"热力图",map:"地图",parallel:"平行坐标图",lines:"线图",graph:"关系图",sankey:"桑基图",funnel:"漏斗图",gauge:"仪表盘图",pictorialBar:"象形柱图",themeRiver:"主题河流图",sunburst:"旭日图",custom:"自定义图表",chart:"图表"}},aria:{general:{withTitle:"这是一个关于“{title}”的图表。",withoutTitle:"这是一个图表,"},series:{single:{prefix:"",withName:"图表类型是{seriesType},表示{seriesName}。",withoutName:"图表类型是{seriesType}。"},multiple:{prefix:"它由{seriesCount}个图表系列组成。",withName:"第{seriesId}个系列是一个表示{seriesName}的{seriesType},",withoutName:"第{seriesId}个系列是一个{seriesType},",separator:{middle:";",end:"。"}}},data:{allData:"其数据是——",partialData:"其中,前{displayCnt}项是——",withName:"{name}的数据是{value}",withoutName:"{value}",separator:{middle:",",end:""}}}});function bg(){return null}var xg=1e3,wg=6e4,Sg=36e5,Cg=864e5,kg=31536e6,Mg={year:/({yyyy}|{yy})/,month:/({MMMM}|{MMM}|{MM}|{M})/,day:/({dd}|{d})/,hour:/({HH}|{H}|{hh}|{h})/,minute:/({mm}|{m})/,second:/({ss}|{s})/,millisecond:/({SSS}|{S})/},Tg={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}"},Ag="{yyyy}-{MM}-{dd}",Ig={year:"{yyyy}",month:"{yyyy}-{MM}",day:Ag,hour:Ag+" "+Tg.hour,minute:Ag+" "+Tg.minute,second:Ag+" "+Tg.second,millisecond:"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}"},Dg=["year","month","day","hour","minute","second","millisecond"],Pg=["year","half-year","quarter","month","week","half-week","day","half-day","quarter-day","hour","minute","second","millisecond"];function Lg(t){return er(t)||tr(t)?t:function(t){t=t||{};var e={},n=!0;return Ui(Dg,function(e){n&&(n=null==t[e])}),Ui(Dg,function(i,r){var o=t[i];e[i]={};for(var a=null,s=r;s>=0;s--){var l=Dg[s],c=rr(o)&&!Ji(o)?o[l]:o,u=void 0;Ji(c)?a=(u=c.slice())[0]||"":er(c)?u=[a=c]:(null==a?a=Tg[i]:Mg[l].test(a)||(a=e[l][l][0]+" "+a),u=[a],n&&(u[1]="{primary|"+a+"}")),e[i][l]=u}}),e}(t)}function Eg(t,e){return"0000".substr(0,e-(t+="").length)+t}function Ng(t){switch(t){case"half-year":case"quarter":return"month";case"week":case"half-week":return"day";case"half-day":case"quarter-day":return"hour";default:return t}}function Rg(t){return t===Ng(t)}function Og(t,e,n,i){var r=Jl(t),o=r[Bg(n)](),a=r[$g(n)]()+1,s=Math.floor((a-1)/3)+1,l=r[Fg(n)](),c=r["get"+(n?"UTC":"")+"Day"](),u=r[Vg(n)](),d=(u-1)%12+1,h=r[Wg(n)](),p=r[jg(n)](),f=r[qg(n)](),g=u>=12?"pm":"am",m=g.toUpperCase(),v=i instanceof ug?i:function(t){return vg[t]}(i||yg)||vg[gg],y=v.getModel("time"),_=y.get("month"),b=y.get("monthAbbr"),x=y.get("dayOfWeek"),w=y.get("dayOfWeekAbbr");return(e||"").replace(/{a}/g,g+"").replace(/{A}/g,m+"").replace(/{yyyy}/g,o+"").replace(/{yy}/g,Eg(o%100+"",2)).replace(/{Q}/g,s+"").replace(/{MMMM}/g,_[a-1]).replace(/{MMM}/g,b[a-1]).replace(/{MM}/g,Eg(a,2)).replace(/{M}/g,a+"").replace(/{dd}/g,Eg(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,x[c]).replace(/{ee}/g,w[c]).replace(/{e}/g,c+"").replace(/{HH}/g,Eg(u,2)).replace(/{H}/g,u+"").replace(/{hh}/g,Eg(d+"",2)).replace(/{h}/g,d+"").replace(/{mm}/g,Eg(h,2)).replace(/{m}/g,h+"").replace(/{ss}/g,Eg(p,2)).replace(/{s}/g,p+"").replace(/{SSS}/g,Eg(f,3)).replace(/{S}/g,f+"")}function zg(t,e){var n=Jl(t),i=n[$g(e)]()+1,r=n[Fg(e)](),o=n[Vg(e)](),a=n[Wg(e)](),s=n[jg(e)](),l=0===n[qg(e)](),c=l&&0===s,u=c&&0===a,d=u&&0===o,h=d&&1===r;return h&&1===i?"year":h?"month":d?"day":u?"hour":c?"minute":l?"second":"millisecond"}function Hg(t,e,n){switch(e){case"year":t[Gg(n)](0);case"month":t[Xg(n)](1);case"day":t[Yg(n)](0);case"hour":t[Zg(n)](0);case"minute":t[Kg(n)](0);case"second":t[Qg(n)](0)}return t}function Bg(t){return t?"getUTCFullYear":"getFullYear"}function $g(t){return t?"getUTCMonth":"getMonth"}function Fg(t){return t?"getUTCDate":"getDate"}function Vg(t){return t?"getUTCHours":"getHours"}function Wg(t){return t?"getUTCMinutes":"getMinutes"}function jg(t){return t?"getUTCSeconds":"getSeconds"}function qg(t){return t?"getUTCMilliseconds":"getMilliseconds"}function Ug(t){return t?"setUTCFullYear":"setFullYear"}function Gg(t){return t?"setUTCMonth":"setMonth"}function Xg(t){return t?"setUTCDate":"setDate"}function Yg(t){return t?"setUTCHours":"setHours"}function Zg(t){return t?"setUTCMinutes":"setMinutes"}function Kg(t){return t?"setUTCSeconds":"setSeconds"}function Qg(t){return t?"setUTCMilliseconds":"setMilliseconds"}function Jg(t){if(isNaN(nc(t)))return er(t)?t:"-";var e=(t+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function tm(t,e){return t=(t||"").toLowerCase().replace(/-(.)/g,function(t,e){return e.toUpperCase()}),e&&t&&(t=t.charAt(0).toUpperCase()+t.slice(1)),t}var em=fr;function nm(t,e,n){function i(t){return t&&mr(t)?t:"-"}function r(t){return!(null==t||isNaN(t)||!isFinite(t))}var o="time"===e,a=t instanceof Date;if(o||a){var s=o?Jl(t):t;if(!isNaN(+s))return Og(s,"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}",n);if(a)return"-"}if("ordinal"===e)return nr(t)?i(t):ir(t)&&r(t)?t+"":"-";var l=nc(t);return r(l)?Jg(l):nr(t)?i(t):"boolean"==typeof t?t+"":"-"}var im=["a","b","c","d","e","f","g"],rm=function(t,e){return"{"+t+(null==e?"":e)+"}"};function om(t,e,n){Ji(e)||(e=[e]);var i=e.length;if(!i)return"";for(var r=e[0].$vars||[],o=0;oi||l.newline?(o=0,u=g,a+=s+n,s=h.height):s=Math.max(s,h.height)}else{var m=h.height+(f?-f.y+h.y:0);(d=a+m)>r||l.newline?(o+=s+n,a=0,d=m,s=h.width):s=Math.max(s,h.width)}l.newline||(l.x=o,l.y=a,l.markRedraw(),"horizontal"===t?o=u+n:a=d+n)})}function xm(t,e,n){n=em(n||0);var i=e.width,r=e.height,o=ql(t.left,i),a=ql(t.top,r),s=ql(t.right,i),l=ql(t.bottom,r),c=ql(t.width,i),u=ql(t.height,r),d=n[2]+n[0],h=n[1]+n[3],p=t.aspect;switch(isNaN(c)&&(c=i-s-h-o),isNaN(u)&&(u=r-l-d-a),null!=p&&(isNaN(c)&&isNaN(u)&&(p>i/r?c=.8*i:u=.8*r),isNaN(c)&&(c=p*u),isNaN(u)&&(u=c/p)),isNaN(o)&&(o=i-s-c-h),isNaN(a)&&(a=r-l-u-d),t.left||t.right){case"center":o=i/2-c/2-n[3];break;case"right":o=i-c-h}switch(t.top||t.bottom){case"middle":case"center":a=r/2-u/2-n[0];break;case"bottom":a=r-u-d}o=o||0,a=a||0,isNaN(c)&&(c=i-h-o-(s||0)),isNaN(u)&&(u=r-d-a-(l||0));var f=new Lo((e.x||0)+o+n[3],(e.y||0)+a+n[0],c,u);return f.margin=n,f}Qi(bm,"vertical"),Qi(bm,"horizontal");var wm=1;function Sm(t,e,n){var i,r,o,a,s=t.boxCoordinateSystem;if(s){var l=function(t){var e=t.getShallow("coord",!0),n=um;if(null==e){var i=hm.get(t.type);i&&i.getCoord2&&(n=dm,e=i.getCoord2(t))}return{coord:e,from:n}}(t),c=l.coord,u=l.from;if(s.dataToLayout){o=wm,a=u;var d=s.dataToLayout(c);i=d.contentRect||d.rect}}return null==o&&(o=wm),o===wm&&(i||(i={x:0,y:0,width:e.getWidth(),height:e.getHeight()}),r=[i.x+i.width/2,i.y+i.height/2]),{type:o,refContainer:i,refPoint:r,boxCoordFrom:a}}function Cm(t){var e=t.layoutMode||t.constructor.layoutMode;return rr(e)?e:e?{type:e}:null}function km(t,e,n){var i=n&&n.ignoreSize;!Ji(i)&&(i=[i,i]);var r=a(_m[0],0),o=a(_m[1],1);function a(n,r){var o={},a=0,l={},c=0;if(vm(n,function(e){l[e]=t[e]}),vm(n,function(t){kr(e,t)&&(o[t]=l[t]=e[t]),s(o,t)&&a++,s(l,t)&&c++}),i[r])return s(e,n[1])?l[n[2]]=null:s(e,n[2])&&(l[n[1]]=null),l;if(2!==c&&a){if(a>=2)return o;for(var u=0;u=0;a--)o=$i(o,n[a],!0);e.defaultOption=o}return e.defaultOption},e.prototype.getReferringComponents=function(t,e){var n=t+"Index",i=t+"Id";return Ac(this.ecModel,t,{index:this.get(n,!0),id:this.get(i,!0)},e)},e.prototype.getBoxLayoutParams=function(){return e=!1,{left:(t=this).getShallow("left",e),top:t.getShallow("top",e),right:t.getShallow("right",e),bottom:t.getShallow("bottom",e),width:t.getShallow("width",e),height:t.getShallow("height",e)};var t,e},e.prototype.getZLevelKey=function(){return""},e.prototype.setZLevel=function(t){this.option.zlevel=t},e.protoInitialize=((n=e.prototype).type="component",n.id="",n.name="",n.mainType="",n.subType="",void(n.componentIndex=0)),e}(ug);Nc(Am,ug),Hc(Am),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){var i=Lc(t);e[i.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var o=Lc(n).main;t.hasSubTypes(n)&&e[o]&&(r=e[o](i))}return r}}(Am),function(t,e){function n(t,e){return t[e]||(t[e]={predecessor:[],successor:[]}),t[e]}t.topologicalTravel=function(t,i,r,o){if(t.length){var a=function(t){var i={},r=[];return Ui(t,function(o){var a=n(i,o),s=function(t,e){var n=[];return Ui(t,function(t){Wi(e,t)>=0&&n.push(t)}),n}(a.originalDeps=e(o),t);a.entryCount=s.length,0===a.entryCount&&r.push(o),Ui(s,function(t){Wi(a.predecessor,t)<0&&a.predecessor.push(t);var e=n(i,t);Wi(e.successor,t)<0&&e.successor.push(o)})}),{graph:i,noEntryList:r}}(i),s=a.graph,l=a.noEntryList,c={};for(Ui(t,function(t){c[t]=!0});l.length;){var u=l.pop(),d=s[u],h=!!c[u];h&&(r.call(o,u,d.originalDeps.slice()),delete c[u]),Ui(d.successor,h?f:p)}Ui(c,function(){throw new Error("")})}function p(t){s[t].entryCount--,0===s[t].entryCount&&l.push(t)}function f(t){c[t]=!0,p(t)}}}(Am,function(t){var e=[];Ui(Am.getClassesByMainType(t),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=Gi(e,function(t){return Lc(t).main}),"dataset"!==t&&Wi(e,"dataset")<=0&&e.unshift("dataset");return e});var Im={color:{},darkColor:{},size:{}},Dm=Im.color={theme:["#5070dd","#b6d634","#505372","#ff994d","#0ca8df","#ffd10a","#fb628b","#785db0","#3fbe95"],neutral00:"#fff",neutral05:"#f4f7fd",neutral10:"#e8ebf0",neutral15:"#dbdee4",neutral20:"#cfd2d7",neutral25:"#c3c5cb",neutral30:"#b7b9be",neutral35:"#aaacb2",neutral40:"#9ea0a5",neutral45:"#929399",neutral50:"#86878c",neutral55:"#797b7f",neutral60:"#6d6e73",neutral65:"#616266",neutral70:"#54555a",neutral75:"#48494d",neutral80:"#3c3c41",neutral85:"#303034",neutral90:"#232328",neutral95:"#17171b",neutral99:"#000",accent05:"#eff1f9",accent10:"#e0e4f2",accent15:"#d0d6ec",accent20:"#c0c9e6",accent25:"#b1bbdf",accent30:"#a1aed9",accent35:"#91a0d3",accent40:"#8292cc",accent45:"#7285c6",accent50:"#6578ba",accent55:"#5c6da9",accent60:"#536298",accent65:"#4a5787",accent70:"#404c76",accent75:"#374165",accent80:"#2e3654",accent85:"#252b43",accent90:"#1b2032",accent95:"#121521",transparent:"rgba(0,0,0,0)",highlight:"rgba(255,231,130,0.8)"};for(var Pm in Fi(Dm,{primary:Dm.neutral80,secondary:Dm.neutral70,tertiary:Dm.neutral60,quaternary:Dm.neutral50,disabled:Dm.neutral20,border:Dm.neutral30,borderTint:Dm.neutral20,borderShade:Dm.neutral40,background:Dm.neutral05,backgroundTint:"rgba(234,237,245,0.5)",backgroundTransparent:"rgba(255,255,255,0)",backgroundShade:Dm.neutral10,shadow:"rgba(0,0,0,0.2)",shadowTint:"rgba(129,130,136,0.2)",axisLine:Dm.neutral70,axisLineTint:Dm.neutral40,axisTick:Dm.neutral70,axisTickMinor:Dm.neutral60,axisLabel:Dm.neutral70,axisSplitLine:Dm.neutral15,axisMinorSplitLine:Dm.neutral05}),Dm)if(Dm.hasOwnProperty(Pm)){var Lm=Dm[Pm];"theme"===Pm?Im.darkColor.theme=Dm.theme.slice():"highlight"===Pm?Im.darkColor.highlight="rgba(255,231,130,0.4)":0===Pm.indexOf("accent")?Im.darkColor[Pm]=Xa(Lm,0,function(t){return.5*t},function(t){return Math.min(1,1.3-t)}):Im.darkColor[Pm]=Xa(Lm,0,function(t){return.9*t},function(t){return 1-Math.pow(t,1.5)})}Im.size={xxs:2,xs:5,s:10,m:15,l:20,xl:30,xxl:40,xxxl:50};var Em="";"undefined"!=typeof navigator&&(Em=navigator.platform||"");var Nm="rgba(0, 0, 0, 0.2)",Rm=Im.color.theme[0],Om=Xa(Rm,0,null,.9),zm={darkMode:"auto",colorBy:"series",color:Im.color.theme,gradientColor:[Om,Rm],aria:{decal:{decals:[{color:Nm,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:Nm,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:Nm,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:Nm,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:Nm,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:Nm,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:Em.match(/^Win/)?"Microsoft YaHei":"sans-serif",fontSize:12,fontStyle:"normal",fontWeight:"normal"},blendMode:null,stateAnimation:{duration:300,easing:"cubicOut"},animation:"auto",animationDuration:1e3,animationDurationUpdate:500,animationEasing:"cubicInOut",animationEasingUpdate:"cubicInOut",animationThreshold:2e3,progressiveThreshold:3e3,progressive:400,hoverLayerThreshold:3e3,useUTC:!1},Hm=Sr(["tooltip","label","itemName","itemId","itemGroupId","itemChildGroupId","seriesName"]),Bm="original",$m="arrayRows",Fm="objectRows",Vm="keyedColumns",Wm="typedArray",jm="unknown",qm="column",Um="row",Gm=1,Xm=2,Ym=3,Zm=Sc();function Km(t,e,n){var i={},r=Qm(e);if(!r||!t)return i;var o,a,s=[],l=[],c=e.ecModel,u=Zm(c).datasetMap,d=r.uid+"_"+n.seriesLayoutBy;Ui(t=t.slice(),function(e,n){var r=rr(e)?e:t[n]={name:e};"ordinal"===r.type&&null==o&&(o=n,a=f(r)),i[r.name]=[]});var h=u.get(d)||u.set(d,{categoryWayDim:a,valueWayDim:0});function p(t,e,n){for(var i=0;ie)return t[i];return t[n-1]}(i,a):n;if(u=u||n,!u||!u.length)return;var d=u[l];r&&(c[r]=d);return s.paletteIdx=(l+1)%u.length,d}(this,ev,i,r,t,e,n)},t.prototype.clearColorPalette=function(){!function(t,e){e(t).paletteIdx=0,e(t).paletteNameMap={}}(this,ev)},t}();var av="\0_ec_inner",sv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.init=function(t,e,n,i,r,o){i=i||{},this.option=null,this._theme=new ug(i),this._locale=new ug(r),this._optionManager=o},e.prototype.setOption=function(t,e,n){var i=uv(e);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,e){return this._resetOption(t,uv(e))},e.prototype._resetOption=function(t,e){var n=!1,i=this._optionManager;if(!t||"recreate"===t){var r=i.mountOption("recreate"===t);this.option&&"recreate"!==t?(this.restoreData(),this._mergeOption(r,e)):rv(this,r),n=!0}if("timeline"!==t&&"media"!==t||this.restoreData(),!t||"recreate"===t||"timeline"===t){var o=i.getTimelineOption(this);o&&(n=!0,this._mergeOption(o,e))}if(!t||"recreate"===t||"media"===t){var a=i.getMediaOption(this);a.length&&Ui(a,function(t){n=!0,this._mergeOption(t,e)},this)}return n},e.prototype.mergeOption=function(t){this._mergeOption(t,null)},e.prototype._mergeOption=function(t,e){var n=this.option,i=this._componentsMap,r=this._componentsCount,o=[],a=Sr(),s=e&&e.replaceMergeMainTypeMap;Zm(this).datasetMap=Sr(),Ui(t,function(t,e){null!=t&&(Am.hasClass(e)?e&&(o.push(e),a.set(e,!0)):n[e]=null==n[e]?Bi(t):$i(n[e],t,!0))}),s&&s.each(function(t,e){Am.hasClass(e)&&!a.get(e)&&(o.push(e),a.set(e,!0))}),Am.topologicalTravel(o,Am.getAllClassMainTypes(),function(e){var o=function(t,e,n){var i=tv.get(e);if(!i)return n;var r=i(t);return r?n.concat(r):n}(this,e,dc(t[e])),a=i.get(e),l=a?s&&s.get(e)?"replaceMerge":"normalMerge":"replaceAll",c=mc(a,o,l);(function(t,e,n){Ui(t,function(t){var i=t.newOption;rr(i)&&(t.keyInfo.mainType=e,t.keyInfo.subType=function(t,e,n,i){return e.type?e.type:n?n.subType:i.determineSubType(t,e)}(e,i,t.existing,n))})})(c,e,Am),n[e]=null,i.set(e,null),r.set(e,0);var u,d=[],h=[],p=0;Ui(c,function(t,n){var i=t.existing,r=t.newOption;if(r){var o="series"===e,a=Am.getClass(e,t.keyInfo.subType,!o);if(!a)return;if("tooltip"===e){if(u)return;u=!0}if(i&&i.constructor===a)i.name=t.keyInfo.name,i.mergeOption(r,this),i.optionUpdated(r,!1);else{var s=Fi({componentIndex:n},t.keyInfo);Fi(i=new a(r,this,this,s),s),t.brandNew&&(i.__requireNewView=!0),i.init(r,this,this),i.optionUpdated(null,!0)}}else i&&(i.mergeOption({},this),i.optionUpdated({},!1));i?(d.push(i.option),h.push(i),p++):(d.push(void 0),h.push(void 0))},this),n[e]=d,i.set(e,h),r.set(e,p),"series"===e&&nv(this)},this),this._seriesIndices||nv(this)},e.prototype.getOption=function(){var t=Bi(this.option);return Ui(t,function(e,n){if(Am.hasClass(n)){for(var i=dc(e),r=i.length,o=!1,a=r-1;a>=0;a--)i[a]&&!xc(i[a])?o=!0:(i[a]=null,!o&&r--);i.length=r,t[n]=i}}),delete t[av],t},e.prototype.setTheme=function(t){this._theme=new ug(t),this._resetOption("recreate",null)},e.prototype.getTheme=function(){return this._theme},e.prototype.getLocaleModel=function(){return this._locale},e.prototype.setUpdatePayload=function(t){this._payload=t},e.prototype.getUpdatePayload=function(){return this._payload},e.prototype.getComponent=function(t,e){var n=this._componentsMap.get(t);if(n){var i=n[e||0];if(i)return i;if(null==e)for(var r=0;r=e:"max"===n?t<=e:t===e})(i[a],t,o)||(r=!1)}}),r}var mv=Ui,vv=rr,yv=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function _v(t){var e=t&&t.itemStyle;if(e)for(var n=0,i=yv.length;nc&&(c=p)}s[0]=l,s[1]=c}},i=function(){return this._data?this._data.length/this._dimSize:0};function r(t){for(var e=0;e=0&&(s=o.interpolatedValue[l])}return null!=s?s+"":""}):void 0},t.prototype.getRawValue=function(t,e){return ly(this.getData(e),t)},t.prototype.formatTooltip=function(t,e,n){},t}();function dy(t){var e,n;return rr(t)?t.type&&(n=t):e=t,{text:e,frag:n}}function hy(t){return new py(t)}var py=function(){function t(t){t=t||{},this._reset=t.reset,this._plan=t.plan,this._count=t.count,this._onDirty=t.onDirty,this._dirty=!0}return t.prototype.perform=function(t){var e,n=this._upstream,i=t&&t.skip;if(this._dirty&&n){var r=this.context;r.data=r.outputData=n.context.outputData}this.__pipeline&&(this.__pipeline.currentTask=this),this._plan&&!i&&(e=this._plan(this.context));var o,a=u(this._modBy),s=this._modDataCount||0,l=u(t&&t.modBy),c=t&&t.modDataCount||0;function u(t){return!(t>=1)&&(t=1),t}a===l&&s===c||(e="reset"),(this._dirty||"reset"===e)&&(this._dirty=!1,o=this._doReset(i)),this._modBy=l,this._modDataCount=c;var d=t&&t.step;if(this._dueEnd=n?n._outputDueEnd:this._count?this._count(this.context):1/0,this._progress){var h=this._dueIndex,p=Math.min(null!=d?this._dueIndex+d:1/0,this._dueEnd);if(!i&&(o||h1&&i>0?s:a}};return o;function a(){return e=t?null:oi?-this._resultLT:0},t}(),vy=function(){function t(){}return t.prototype.getRawData=function(){throw new Error("not supported")},t.prototype.getRawDataItem=function(t){throw new Error("not supported")},t.prototype.cloneRawData=function(){},t.prototype.getDimensionInfo=function(t){},t.prototype.cloneAllDimensionInfo=function(){},t.prototype.count=function(){},t.prototype.retrieveValue=function(t,e){},t.prototype.retrieveValueFromItem=function(t,e){},t.prototype.convertValue=function(t,e){return gy(t,e)},t}();function yy(t){if(!Cy(t.sourceFormat)){lc("")}return t.data}function _y(t){var e=t.sourceFormat,n=t.data;if(!Cy(e)){lc("")}if(e===$m){for(var i=[],r=0,o=n.length;r65535?Ty:Ay}function Ey(){return[1/0,-1/0]}function Ny(t){var e=t.constructor;return e===Array?t.slice():new e(t)}function Ry(t,e,n,i,r){var o=Py[n||"float"];if(r){var a=t[e],s=a&&a.length;if(s!==i){for(var l=new o(i),c=0;cg[1]&&(g[1]=f)}return this._rawCount=this._count=s,{start:a,end:s}},t.prototype._initDataFromProvider=function(t,e,n){for(var i=this._provider,r=this._chunks,o=this._dimensions,a=o.length,s=this._rawExtent,l=Gi(o,function(t){return t.property}),c=0;cm[1]&&(m[1]=g)}}!i.persistent&&i.clean&&i.clean(),this._rawCount=this._count=e,this._extent=[]},t.prototype.count=function(){return this._count},t.prototype.get=function(t,e){if(!(e>=0&&e=0&&e=this._rawCount||t<0)return-1;if(!this._indices)return t;var e=this._indices,n=e[t];if(null!=n&&nt))return o;r=o-1}}return-1},t.prototype.getIndices=function(){var t,e=this._indices;if(e){var n=e.constructor,i=this._count;if(n===Array){t=new n(i);for(var r=0;r=c&&_<=u||isNaN(_))&&(a[s++]=p),p++}h=!0}else if(2===r){f=d[i[0]];var m=d[i[1]],v=t[i[1]][0],y=t[i[1]][1];for(g=0;g=c&&_<=u||isNaN(_))&&(b>=v&&b<=y||isNaN(b))&&(a[s++]=p),p++}h=!0}}if(!h)if(1===r)for(g=0;g=c&&_<=u||isNaN(_))&&(a[s++]=x)}else for(g=0;gt[C][1])&&(w=!1)}w&&(a[s++]=e.getRawIndex(g))}return sm[1]&&(m[1]=g)}}}},t.prototype.lttbDownSample=function(t,e){var n,i,r,o=this.clone([t],!0),a=o._chunks[t],s=this.count(),l=0,c=Math.floor(1/e),u=this.getRawIndex(0),d=new(Ly(this._rawCount))(Math.min(2*(Math.ceil(s/c)+2),s));d[l++]=u;for(var h=1;hn&&(n=i,r=k)}C>0&&Ca&&(f=a-c);for(var g=0;gp&&(p=m,h=c+g)}var v=this.getRawIndex(u),y=this.getRawIndex(h);uc-p&&(s=c-p,a.length=s);for(var f=0;fu[1]&&(u[1]=m),d[h++]=v}return r._count=h,r._indices=d,r._updateGetRawIdx(),r},t.prototype.each=function(t,e){if(this._count)for(var n=t.length,i=this._chunks,r=0,o=this.count();ra&&(a=l)}return i=[o,a],this._extent[t]=i,i},t.prototype.getRawDataItem=function(t){var e=this.getRawIndex(t);if(this._provider.persistent)return this._provider.getItem(e);for(var n=[],i=this._chunks,r=0;r=0?this._indices[t]:-1},t.prototype._updateGetRawIdx=function(){this.getRawIndex=this._indices?this._getRawIdx:this._getRawIdxIdentity},t.internalField=function(){function t(t,e,n,i){return gy(t[i],this._dimensions[i])}ky={arrayRows:t,objectRows:function(t,e,n,i){return gy(t[e],this._dimensions[i])},keyedColumns:t,original:function(t,e,n,i){var r=t&&(null==t.value?t:t.value);return gy(r instanceof Array?r[i]:r,this._dimensions[i])},typedArray:function(t,e,n,i){return t[i]}}}(),t}(),zy=function(){function t(t){this._sourceList=[],this._storeList=[],this._upstreamSignList=[],this._versionSignBase=0,this._dirty=!0,this._sourceHost=t}return t.prototype.dirty=function(){this._setLocalSource([],[]),this._storeList=[],this._dirty=!0},t.prototype._setLocalSource=function(t,e){this._sourceList=t,this._upstreamSignList=e,this._versionSignBase++,this._versionSignBase>9e10&&(this._versionSignBase=0)},t.prototype._getVersionSign=function(){return this._sourceHost.uid+"_"+this._versionSignBase},t.prototype.prepareSource=function(){this._isDirty()&&(this._createSource(),this._dirty=!1)},t.prototype._createSource=function(){this._setLocalSource([],[]);var t,e,n=this._sourceHost,i=this._getUpstreamSourceManagers(),r=!!i.length;if(Hy(n)){var o=n,a=void 0,s=void 0,l=void 0;if(r){var c=i[0];c.prepareSource(),a=(l=c.getSource()).data,s=l.sourceFormat,e=[c._getVersionSign()]}else s=ar(a=o.get("data",!0))?Wm:Bm,e=[];var u=this._getSourceMetaRawOption()||{},d=l&&l.metaRawOption||{},h=dr(u.seriesLayoutBy,d.seriesLayoutBy)||null,p=dr(u.sourceHeader,d.sourceHeader),f=dr(u.dimensions,d.dimensions);t=h!==d.seriesLayoutBy||!!p!=!!d.sourceHeader||f?[jv(a,{seriesLayoutBy:h,sourceHeader:p,dimensions:f},s)]:[]}else{var g=n;if(r){var m=this._applyTransform(i);t=m.sourceList,e=m.upstreamSignList}else{t=[jv(g.get("source",!0),this._getSourceMetaRawOption(),null)],e=[]}}this._setLocalSource(t,e)},t.prototype._applyTransform=function(t){var e,n=this._sourceHost,i=n.get("transform",!0),r=n.get("fromTransformResult",!0);if(null!=r){1!==t.length&&By("")}var o,a=[],s=[];return Ui(t,function(t){t.prepareSource();var e=t.getSource(r||0);null==r||e||By(""),a.push(e),s.push(t._getVersionSign())}),i?e=function(t,e){var n=dc(t),i=n.length;i||lc("");for(var r=0,o=i;r1||n>0&&!t.noHeader;return Ui(t.blocks,function(t){var n=Gy(t);n>=e&&(e=n+ +(i&&(!n||qy(t)&&!t.noHeader)))}),e}return 0}function Xy(t,e,n,i){var r,o=e.noHeader,a=(r=Gy(e),{html:Vy[r],richText:Wy[r]}),s=[],l=e.blocks||[];gr(!l||Ji(l)),l=l||[];var c=t.orderMode;if(e.sortBlocks&&c){l=l.slice();var u={valueAsc:"asc",valueDesc:"desc"};if(kr(u,c)){var d=new my(u[c],null);l.sort(function(t,e){return d.evaluate(t.sortParam,e.sortParam)})}else"seriesDesc"===c&&l.reverse()}Ui(l,function(n,r){var o=e.valueFormatter,l=Uy(n)(o?Fi(Fi({},t),{valueFormatter:o}):t,n,r>0?a.html:0,i);null!=l&&s.push(l)});var h="richText"===t.renderMode?s.join(a.richText):Ky(i,s.join(""),o?n:a.html);if(o)return h;var p=nm(e.header,"ordinal",t.useUTC),f=Fy(i,t.renderMode).nameStyle,g=$y(i);return"richText"===t.renderMode?Qy(t,p,f)+a.richText+h:Ky(i,'
'+Qr(p)+"
"+h,n)}function Yy(t,e,n,i){var r=t.renderMode,o=e.noName,a=e.noValue,s=!e.markerType,l=e.name,c=t.useUTC,u=e.valueFormatter||t.valueFormatter||function(t){return Gi(t=Ji(t)?t:[t],function(t,e){return nm(t,Ji(p)?p[e]:p,c)})};if(!o||!a){var d=s?"":t.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||Im.color.secondary,r),h=o?"":nm(l,"ordinal",c),p=e.valueType,f=a?[]:u(e.value,e.dataIndex),g=!s||!o,m=!s&&o,v=Fy(i,r),y=v.nameStyle,_=v.valueStyle;return"richText"===r?(s?"":d)+(o?"":Qy(t,h,y))+(a?"":function(t,e,n,i,r){var o=[r],a=i?10:20;return n&&o.push({padding:[0,0,0,a],align:"right"}),t.markupStyleCreator.wrapRichTextStyle(Ji(e)?e.join(" "):e,o)}(t,f,g,m,_)):Ky(i,(s?"":d)+(o?"":function(t,e,n){return''+Qr(t)+""}(h,!s,y))+(a?"":function(t,e,n,i){var r=n?"10px":"20px",o=e?"float:right;margin-left:"+r:"";return t=Ji(t)?t:[t],''+Gi(t,function(t){return Qr(t)}).join("  ")+""}(f,g,m,_)),n)}}function Zy(t,e,n,i,r,o){if(t)return Uy(t)({useUTC:r,renderMode:n,orderMode:i,markupStyleCreator:e,valueFormatter:t.valueFormatter},t,0,o)}function Ky(t,e,n){return'
'+e+'
'}function Qy(t,e,n){return t.markupStyleCreator.wrapRichTextStyle(e,n)}function Jy(t,e){var n=t.get("padding");return null!=n?n:"richText"===e?[8,10]:10}var t_=function(){function t(){this.richTextStyles={},this._nextStyleNameId=ic()}return t.prototype._generateStyleName=function(){return"__EC_aUTo_"+this._nextStyleNameId++},t.prototype.makeTooltipMarker=function(t,e,n){var i="richText"===n?this._generateStyleName():null,r=function(t,e){var n=er(t)?{color:t,extraCssText:e}:t||{},i=n.color,r=n.type;e=n.extraCssText;var o=n.renderMode||"html";return i?"html"===o?"subItem"===r?'':'':{renderMode:o,content:"{"+(n.markerId||"markerX")+"|} ",style:"subItem"===r?{width:4,height:4,borderRadius:2,backgroundColor:i}:{width:10,height:10,borderRadius:5,backgroundColor:i}}:""}({color:e,type:t,renderMode:n,markerId:i});return er(r)?r:(this.richTextStyles[i]=r.style,r.content)},t.prototype.wrapRichTextStyle=function(t,e){var n={};Ji(e)?Ui(e,function(t){return Fi(n,t)}):Fi(n,e);var i=this._generateStyleName();return this.richTextStyles[i]=n,"{"+i+"|"+t+"}"},t}();function e_(t){var e,n,i,r,o=t.series,a=t.dataIndex,s=t.multipleSeries,l=o.getData(),c=l.mapDimensionsAll("defaultedTooltip"),u=c.length,d=o.getRawValue(a),h=Ji(d),p=function(t,e){return am(t.getData().getItemVisual(e,"style")[t.visualDrawType])}(o,a);if(u>1||h&&!u){var f=function(t,e,n,i,r){var o=e.getData(),a=Xi(t,function(t,e,n){var i=o.getDimensionInfo(n);return t||i&&!1!==i.tooltip&&null!=i.displayName},!1),s=[],l=[],c=[];function u(t,e){var n=o.getDimensionInfo(e);n&&!1!==n.otherDims.tooltip&&(a?c.push(jy("nameValue",{markerType:"subItem",markerColor:r,name:n.displayName,value:t,valueType:n.type})):(s.push(t),l.push(n.type)))}return i.length?Ui(i,function(t){u(ly(o,n,t),t)}):Ui(t,u),{inlineValues:s,inlineValueTypes:l,blocks:c}}(d,o,a,c,p);e=f.inlineValues,n=f.inlineValueTypes,i=f.blocks,r=f.inlineValues[0]}else if(u){var g=l.getDimensionInfo(c[0]);r=e=ly(l,a,c[0]),n=g.type}else r=e=h?d[0]:d;var m=bc(o),v=m&&o.name||"",y=l.getName(a),_=s?v:y;return jy("section",{header:v,noHeader:s||!m,sortParam:r,blocks:[jy("nameValue",{markerType:"item",markerColor:p,name:_,noName:!mr(_),value:e,valueType:n,dataIndex:a})].concat(i||[])})}var n_=Sc();function i_(t,e){return t.getName(e)||t.getId(e)}var r_=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e._selectedDataIndicesMap={},e}var n;return S(e,t),e.prototype.init=function(t,e,n){this.seriesIndex=this.componentIndex,this.dataTask=hy({count:a_,reset:s_}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),(n_(this).sourceManager=new zy(this)).prepareSource();var i=this.getInitialData(t,n);c_(i,this),this.dataTask.context.data=i,n_(this).dataBeforeProcessed=i,o_(this),this._initSelectedMapFromData(i)},e.prototype.mergeDefaultAndTheme=function(t,e){var n=Cm(this),i=n?Mm(t):{},r=this.subType;Am.hasClass(r)&&(r+="Series"),$i(t,e.getTheme().get(this.subType)),$i(t,this.getDefaultOption()),hc(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&km(t,i,n)},e.prototype.mergeOption=function(t,e){t=$i(this.option,t,!0),this.fillDataTextStyle(t.data);var n=Cm(this);n&&km(this.option,t,n);var i=n_(this).sourceManager;i.dirty(),i.prepareSource();var r=this.getInitialData(t,e);c_(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,n_(this).dataBeforeProcessed=r,o_(this),this._initSelectedMapFromData(r)},e.prototype.fillDataTextStyle=function(t){if(t&&!ar(t))for(var e=["show"],n=0;n=0&&u<0)&&(c=o,u=r,d=0),r===u&&(l[d++]=e))}),l.length=d,l},e.prototype.formatTooltip=function(t,e,n){return e_({series:this,dataIndex:t,multipleSeries:e})},e.prototype.isAnimationEnabled=function(){var t=this.ecModel;if(yi.node&&(!t||!t.ssr))return!1;var e=this.getShallow("animation");return e&&this.getData().count()>this.getShallow("animationThreshold")&&(e=!1),!!e},e.prototype.restoreData=function(){this.dataTask.dirty()},e.prototype.getColorFromPalette=function(t,e,n){var i=this.ecModel,r=ov.prototype.getColorFromPalette.call(this,t,e,n);return r||(r=i.getColorFromPalette(t,e,n)),r},e.prototype.coordDimToDataDim=function(t){return this.getRawData().mapDimensionsAll(t)},e.prototype.getProgressive=function(){return this.get("progressive")},e.prototype.getProgressiveThreshold=function(){return this.get("progressiveThreshold")},e.prototype.select=function(t,e){this._innerSelect(this.getData(e),t)},e.prototype.unselect=function(t,e){var n=this.option.selectedMap;if(n){var i=this.option.selectedMode,r=this.getData(e);if("series"===i||"all"===n)return this.option.selectedMap={},void(this._selectedDataIndicesMap={});for(var o=0;o=0&&n.push(r)}return n},e.prototype.isSelected=function(t,e){var n=this.option.selectedMap;if(!n)return!1;var i=this.getData(e);return("all"===n||n[i_(i,t)])&&!i.getItemModel(t).get(["select","disabled"])},e.prototype.isUniversalTransitionEnabled=function(){if(this.__universalTransitionEnabled)return!0;var t=this.option.universalTransition;return!!t&&(!0===t||t&&t.enabled)},e.prototype._innerSelect=function(t,e){var n,i,r=this.option,o=r.selectedMode,a=e.length;if(o&&a)if("series"===o)r.selectedMap="all";else if("multiple"===o){rr(r.selectedMap)||(r.selectedMap={});for(var s=r.selectedMap,l=0;l0&&this._innerSelect(t,e)}},e.registerClass=function(t){return Am.registerClass(t)},e.protoInitialize=((n=e.prototype).type="series.__base__",n.seriesIndex=0,n.ignoreStyleOnData=!1,n.hasSymbolVisual=!1,n.defaultSymbol="circle",n.visualStyleAccessPath="itemStyle",void(n.visualDrawType="fill")),e}(Am);function o_(t){var e=t.name;bc(t)||(t.name=function(t){var e=t.getRawData(),n=e.mapDimensionsAll("seriesName"),i=[];return Ui(n,function(t){var n=e.getDimensionInfo(t);n.displayName&&i.push(n.displayName)}),i.join(" ")}(t)||e)}function a_(t){return t.model.getRawData().count()}function s_(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),l_}function l_(t,e){e.outputData&&t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function c_(t,e){Ui(function(t,e){for(var n=new t.constructor(t.length+e.length),i=0;i=0?d():u=setTimeout(d,-r),l=i};return h.clear=function(){u&&(clearTimeout(u),u=null)},h.debounceNextCall=function(t){s=t},h}function M_(t,e,n,i){var r=t[e];if(r){var o=r[w_]||r,a=r[C_];if(r[S_]!==n||a!==i){if(null==n||!i)return t[e]=o;(r=t[e]=k_(o,n,"debounce"===i))[w_]=o,r[C_]=i,r[S_]=n}return r}}function T_(t,e){var n=t[e];n&&n[w_]&&(n.clear&&n.clear(),t[e]=n[w_])}var A_=Sc(),I_={itemStyle:Bc(sg,!0),lineStyle:Bc(rg,!0)},D_={lineStyle:"stroke",itemStyle:"fill"};function P_(t,e){var n=t.visualStyleMapper||I_[e];return n||(console.warn("Unknown style type '"+e+"'."),I_.itemStyle)}function L_(t,e){var n=t.visualDrawType||D_[e];return n||(console.warn("Unknown style type '"+e+"'."),"fill")}var E_={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=t.getModel(i),o=P_(t,i)(r),a=r.getShallow("decal");a&&(n.setVisual("decal",a),a.dirty=!0);var s=L_(t,i),l=o[s],c=tr(l)?l:null,u="auto"===o.fill||"auto"===o.stroke;if(!o[s]||c||u){var d=t.getColorFromPalette(t.name,null,e.getSeriesCount());o[s]||(o[s]=d,n.setVisual("colorFromPalette",!0)),o.fill="auto"===o.fill||tr(o.fill)?d:o.fill,o.stroke="auto"===o.stroke||tr(o.stroke)?d:o.stroke}if(n.setVisual("style",o),n.setVisual("drawType",s),!e.isSeriesFiltered(t)&&c)return n.setVisual("colorFromPalette",!1),{dataEach:function(e,n){var i=t.getDataParams(n),r=Fi({},o);r[s]=c(i),e.setItemVisual(n,"style",r)}}}},N_=new ug,R_={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){if(!t.ignoreStyleOnData&&!e.isSeriesFiltered(t)){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=P_(t,i),o=n.getVisual("drawType");return{dataEach:n.hasItemOption?function(t,e){var n=t.getRawDataItem(e);if(n&&n[i]){N_.option=n[i];var a=r(N_);Fi(t.ensureUniqueItemVisual(e,"style"),a),N_.option.decal&&(t.setItemVisual(e,"decal",N_.option.decal),N_.option.decal.dirty=!0),o in a&&t.setItemVisual(e,"colorFromPalette",!1)}}:null}}}},O_={performRawSeries:!0,overallReset:function(t){var e=Sr();t.eachSeries(function(t){var n=t.getColorBy();if(!t.isColorBySeries()){var i=t.type+"-"+n,r=e.get(i);r||(r={},e.set(i,r)),A_(t).scope=r}}),t.eachSeries(function(e){if(!e.isColorBySeries()&&!t.isSeriesFiltered(e)){var n=e.getRawData(),i={},r=e.getData(),o=A_(e).scope,a=e.visualStyleAccessPath||"itemStyle",s=L_(e,a);r.each(function(t){var e=r.getRawIndex(t);i[e]=t}),n.each(function(t){var a=i[t];if(r.getItemVisual(a,"colorFromPalette")){var l=r.ensureUniqueItemVisual(a,"style"),c=n.getName(t)||t+"",u=n.count();l[s]=e.getColorFromPalette(c,o,u)}})}})}},z_=Math.PI;var H_=function(){function t(t,e,n,i){this._stageTaskMap=Sr(),this.ecInstance=t,this.api=e,n=this._dataProcessorHandlers=n.slice(),i=this._visualHandlers=i.slice(),this._allHandlers=n.concat(i)}return t.prototype.restoreData=function(t,e){t.restoreData(e),this._stageTaskMap.each(function(t){var e=t.overallTask;e&&e.dirty()})},t.prototype.getPerformArgs=function(t,e){if(t.__pipeline){var n=this._pipelineMap.get(t.__pipeline.id),i=n.context,r=!e&&n.progressiveEnabled&&(!i||i.progressiveRender)&&t.__idxInPipeline>n.blockIndex?n.step:null,o=i&&i.modDataCount;return{step:r,modBy:null!=o?Math.ceil(o/r):null,modDataCount:o}}},t.prototype.getPipeline=function(t){return this._pipelineMap.get(t)},t.prototype.updateStreamModes=function(t,e){var n=this._pipelineMap.get(t.uid),i=t.getData().count(),r=n.progressiveEnabled&&e.incrementalPrepareRender&&i>=n.threshold,o=t.get("large")&&i>=t.get("largeThreshold"),a="mod"===t.get("progressiveChunkMode")?i:null;t.pipelineContext=n.context={progressiveRender:r,modDataCount:a,large:o}},t.prototype.restorePipelines=function(t){var e=this,n=e._pipelineMap=Sr();t.eachSeries(function(t){var i=t.getProgressive(),r=t.uid;n.set(r,{id:r,head:null,tail:null,threshold:t.getProgressiveThreshold(),progressiveEnabled:i&&!(t.preventIncremental&&t.preventIncremental()),blockIndex:-1,step:Math.round(i||700),count:0}),e._pipe(t,t.dataTask)})},t.prototype.prepareStageTasks=function(){var t=this._stageTaskMap,e=this.api.getModel(),n=this.api;Ui(this._allHandlers,function(i){var r=t.get(i.uid)||t.set(i.uid,{});gr(!(i.reset&&i.overallReset),""),i.reset&&this._createSeriesStageTask(i,r,e,n),i.overallReset&&this._createOverallStageTask(i,r,e,n)},this)},t.prototype.prepareView=function(t,e,n,i){var r=t.renderTask,o=r.context;o.model=e,o.ecModel=n,o.api=i,r.__block=!t.incrementalPrepareRender,this._pipe(e,r)},t.prototype.performDataProcessorTasks=function(t,e){this._performStageTasks(this._dataProcessorHandlers,t,e,{block:!0})},t.prototype.performVisualTasks=function(t,e,n){this._performStageTasks(this._visualHandlers,t,e,n)},t.prototype._performStageTasks=function(t,e,n,i){i=i||{};var r=!1,o=this;function a(t,e){return t.setDirty&&(!t.dirtyMap||t.dirtyMap.get(e.__pipeline.id))}Ui(t,function(t,s){if(!i.visualType||i.visualType===t.visualType){var l=o._stageTaskMap.get(t.uid),c=l.seriesTaskMap,u=l.overallTask;if(u){var d,h=u.agentStubMap;h.each(function(t){a(i,t)&&(t.dirty(),d=!0)}),d&&u.dirty(),o.updatePayload(u,n);var p=o.getPerformArgs(u,i.block);h.each(function(t){t.perform(p)}),u.perform(p)&&(r=!0)}else c&&c.each(function(s,l){a(i,s)&&s.dirty();var c=o.getPerformArgs(s,i.block);c.skip=!t.performRawSeries&&e.isSeriesFiltered(s.context.model),o.updatePayload(s,n),s.perform(c)&&(r=!0)})}}),this.unfinished=r||this.unfinished},t.prototype.performSeriesTasks=function(t){var e;t.eachSeries(function(t){e=t.dataTask.perform()||e}),this.unfinished=e||this.unfinished},t.prototype.plan=function(){this._pipelineMap.each(function(t){var e=t.tail;do{if(e.__block){t.blockIndex=e.__idxInPipeline;break}e=e.getUpstream()}while(e)})},t.prototype.updatePayload=function(t,e){"remain"!==e&&(t.context.payload=e)},t.prototype._createSeriesStageTask=function(t,e,n,i){var r=this,o=e.seriesTaskMap,a=e.seriesTaskMap=Sr(),s=t.seriesType,l=t.getTargetSeries;function c(e){var s=e.uid,l=a.set(s,o&&o.get(s)||hy({plan:W_,reset:j_,count:G_}));l.context={model:e,ecModel:n,api:i,useClearVisual:t.isVisual&&!t.isLayout,plan:t.plan,reset:t.reset,scheduler:r},r._pipe(e,l)}t.createOnAllSeries?n.eachRawSeries(c):s?n.eachRawSeriesByType(s,c):l&&l(n,i).each(c)},t.prototype._createOverallStageTask=function(t,e,n,i){var r=this,o=e.overallTask=e.overallTask||hy({reset:B_});o.context={ecModel:n,api:i,overallReset:t.overallReset,scheduler:r};var a=o.agentStubMap,s=o.agentStubMap=Sr(),l=t.seriesType,c=t.getTargetSeries,u=!0,d=!1;function h(t){var e=t.uid,n=s.set(e,a&&a.get(e)||(d=!0,hy({reset:$_,onDirty:V_})));n.context={model:t,overallProgress:u},n.agent=o,n.__block=u,r._pipe(t,n)}gr(!t.createOnAllSeries,""),l?n.eachRawSeriesByType(l,h):c?c(n,i).each(h):(u=!1,Ui(n.getSeries(),h)),d&&o.dirty()},t.prototype._pipe=function(t,e){var n=t.uid,i=this._pipelineMap.get(n);!i.head&&(i.head=e),i.tail&&i.tail.pipe(e),i.tail=e,e.__idxInPipeline=i.count++,e.__pipeline=i},t.wrapStageHandler=function(t,e){return tr(t)&&(t={overallReset:t,seriesType:X_(t)}),t.uid=hg("stageHandler"),e&&(t.visualType=e),t},t}();function B_(t){t.overallReset(t.ecModel,t.api,t.payload)}function $_(t){return t.overallProgress&&F_}function F_(){this.agent.dirty(),this.getDownstream().dirty()}function V_(){this.agent&&this.agent.dirty()}function W_(t){return t.plan?t.plan(t.model,t.ecModel,t.api,t.payload):null}function j_(t){t.useClearVisual&&t.data.clearAllVisual();var e=t.resetDefines=dc(t.reset(t.model,t.ecModel,t.api,t.payload));return e.length>1?Gi(e,function(t,e){return U_(e)}):q_}var q_=U_(0);function U_(t){return function(e,n){var i=n.data,r=n.resetDefines[t];if(r&&r.dataEach)for(var o=e.start;o0&&u===r.length-c.length){var d=r.slice(0,u);"data"!==d&&(e.mainType=d,e[c.toLowerCase()]=t,s=!0)}}a.hasOwnProperty(r)&&(n[r]=t,s=!0),s||(i[r]=t)})}return{cptQuery:e,dataQuery:n,otherQuery:i}},t.prototype.filter=function(t,e){var n=this.eventInfo;if(!n)return!0;var i=n.targetEl,r=n.packedEvent,o=n.model,a=n.view;if(!o||!a)return!0;var s=e.cptQuery,l=e.dataQuery;return c(s,o,"mainType")&&c(s,o,"subType")&&c(s,o,"index","componentIndex")&&c(s,o,"name")&&c(s,o,"id")&&c(l,r,"name")&&c(l,r,"dataIndex")&&c(l,r,"dataType")&&(!a.filterForExposedEvent||a.filterForExposedEvent(t,e.otherQuery,i,r));function c(t,e,n,i){return null==t[n]||e[i||n]===t[n]}},t.prototype.afterTrigger=function(){this.eventInfo=null},t}(),ab=["symbol","symbolSize","symbolRotate","symbolOffset"],sb=ab.concat(["symbolKeepAspect"]),lb={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData();if(t.legendIcon&&n.setVisual("legendIcon",t.legendIcon),t.hasSymbolVisual){for(var i={},r={},o=!1,a=0;a=0&&kb(l)?l:.5,t.createRadialGradient(a,s,0,a,s,l)}(t,e,n):function(t,e,n){var i=null==e.x?0:e.x,r=null==e.x2?1:e.x2,o=null==e.y?0:e.y,a=null==e.y2?0:e.y2;return e.global||(i=i*n.width+n.x,r=r*n.width+n.x,o=o*n.height+n.y,a=a*n.height+n.y),i=kb(i)?i:0,r=kb(r)?r:1,o=kb(o)?o:0,a=kb(a)?a:0,t.createLinearGradient(i,o,r,a)}(t,e,n),r=e.colorStops,o=0;o0&&(e=i.lineDash,n=i.lineWidth,e&&"solid"!==e&&n>0?"dashed"===e?[4*n,2*n]:"dotted"===e?[n]:ir(e)?[e]:Ji(e)?e:null:null),o=i.lineDashOffset;if(r){var a=i.strokeNoScale&&t.getLineScale?t.getLineScale():1;a&&1!==a&&(r=Gi(r,function(t){return t/a}),o/=a)}return[r,o]}var Db=new Zu(!0);function Pb(t){var e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))}function Lb(t){return"string"==typeof t&&"none"!==t}function Eb(t){var e=t.fill;return null!=e&&"none"!==e}function Nb(t,e){if(null!=e.fillOpacity&&1!==e.fillOpacity){var n=t.globalAlpha;t.globalAlpha=e.fillOpacity*e.opacity,t.fill(),t.globalAlpha=n}else t.fill()}function Rb(t,e){if(null!=e.strokeOpacity&&1!==e.strokeOpacity){var n=t.globalAlpha;t.globalAlpha=e.strokeOpacity*e.opacity,t.stroke(),t.globalAlpha=n}else t.stroke()}function Ob(t,e,n){var i=jc(e.image,e.__image,n);if(Uc(i)){var r=t.createPattern(i,e.repeat||"repeat");if("function"==typeof DOMMatrix&&r&&r.setTransform){var o=new DOMMatrix;o.translateSelf(e.x||0,e.y||0),o.rotateSelf(0,0,(e.rotation||0)*Tr),o.scaleSelf(e.scaleX||1,e.scaleY||1),r.setTransform(o)}return r}}var zb=["shadowBlur","shadowOffsetX","shadowOffsetY"],Hb=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function Bb(t,e,n,i,r){var o=!1;if(!i&&e===(n=n||{}))return!1;if(i||e.opacity!==n.opacity){Vb(t,r),o=!0;var a=Math.max(Math.min(e.opacity,1),0);t.globalAlpha=isNaN(a)?hu.opacity:a}(i||e.blend!==n.blend)&&(o||(Vb(t,r),o=!0),t.globalCompositeOperation=e.blend||hu.blend);for(var s=0;s0&&t.unfinished);t.unfinished||this._zr.flush()}}},e.prototype.getDom=function(){return this._dom},e.prototype.getId=function(){return this.id},e.prototype.getZr=function(){return this._zr},e.prototype.isSSR=function(){return this._ssr},e.prototype.setOption=function(t,e,n){if(!this[ix])if(this._disposed)this.id;else{var i,r,o;if(rr(e)&&(n=e.lazyUpdate,i=e.silent,r=e.replaceMerge,o=e.transition,e=e.notMerge),this[ix]=!0,Px(this),!this._model||e){var a=new fv(this._api),s=this._theme,l=this._model=new sv;l.scheduler=this._scheduler,l.ssr=this._ssr,l.init(null,null,null,s,this._locale,a)}this._model.setOption(t,{replaceMerge:r},Fx);var c={seriesTransition:o,optionChanged:!0};if(n)this[ox]={silent:i,updateParams:c},this[ix]=!1,this.getZr().wakeUp();else{try{hx(this),gx.update.call(this,null,c)}catch(t){throw this[ox]=null,this[ix]=!1,t}this._ssr||this._zr.flush(),this[ox]=null,this[ix]=!1,_x.call(this,i),bx.call(this,i)}}},e.prototype.setTheme=function(t,e){if(!this[ix])if(this._disposed)this.id;else{var n=this._model;if(n){var i=e&&e.silent,r=null;this[ox]&&(null==i&&(i=this[ox].silent),r=this[ox].updateParams,this[ox]=null),this[ix]=!0,Px(this);try{this._updateTheme(t),n.setTheme(this._theme),hx(this),gx.update.call(this,{type:"setTheme"},r)}catch(t){throw this[ix]=!1,t}this[ix]=!1,_x.call(this,i),bx.call(this,i)}}},e.prototype._updateTheme=function(t){er(t)&&(t=Wx[t]),t&&((t=Bi(t))&&Rv(t,!0),this._theme=t)},e.prototype.getModel=function(){return this._model},e.prototype.getOption=function(){return this._model&&this._model.getOption()},e.prototype.getWidth=function(){return this._zr.getWidth()},e.prototype.getHeight=function(){return this._zr.getHeight()},e.prototype.getDevicePixelRatio=function(){return this._zr.painter.dpr||yi.hasGlobalWindow&&window.devicePixelRatio||1},e.prototype.getRenderedCanvas=function(t){return this.renderToCanvas(t)},e.prototype.renderToCanvas=function(t){return t=t||{},this._zr.painter.getRenderedCanvas({backgroundColor:t.backgroundColor||this._model.get("backgroundColor"),pixelRatio:t.pixelRatio||this.getDevicePixelRatio()})},e.prototype.renderToSVGString=function(t){return t=t||{},this._zr.painter.renderToString({useViewBox:t.useViewBox})},e.prototype.getSvgDataURL=function(){var t=this._zr;return Ui(t.storage.getDisplayList(),function(t){t.stopAnimation(null,!0)}),t.painter.toDataURL()},e.prototype.getDataURL=function(t){if(!this._disposed){var e=(t=t||{}).excludeComponents,n=this._model,i=[],r=this;Ui(e,function(t){n.eachComponent({mainType:t},function(t){var e=r._componentsMap[t.__viewId];e.group.ignore||(i.push(e),e.group.ignore=!0)})});var o="svg"===this._zr.painter.getType()?this.getSvgDataURL():this.renderToCanvas(t).toDataURL("image/"+(t&&t.type||"png"));return Ui(i,function(t){t.group.ignore=!1}),o}this.id},e.prototype.getConnectedDataURL=function(t){if(!this._disposed){var e="svg"===t.type,n=this.group,i=Math.min,r=Math.max,o=1/0;if(Ux[n]){var a=o,s=o,l=-1/0,c=-1/0,u=[],d=t&&t.pixelRatio||this.getDevicePixelRatio();Ui(qx,function(o,d){if(o.group===n){var h=e?o.getZr().painter.getSvgDom().innerHTML:o.renderToCanvas(Bi(t)),p=o.getDom().getBoundingClientRect();a=i(p.left,a),s=i(p.top,s),l=r(p.right,l),c=r(p.bottom,c),u.push({dom:h,left:p.left,top:p.top})}});var h=(l*=d)-(a*=d),p=(c*=d)-(s*=d),f=Ci.createCanvas(),g=Bl(f,{renderer:e?"svg":"canvas"});if(g.resize({width:h,height:p}),e){var m="";return Ui(u,function(t){var e=t.left-a,n=t.top-s;m+=''+t.dom+""}),g.painter.getSvgRoot().innerHTML=m,t.connectedBackgroundColor&&g.painter.setBackgroundColor(t.connectedBackgroundColor),g.refreshImmediately(),g.painter.toDataURL()}return t.connectedBackgroundColor&&g.add(new Id({shape:{x:0,y:0,width:h,height:p},style:{fill:t.connectedBackgroundColor}})),Ui(u,function(t){var e=new wd({style:{x:t.left*d-a,y:t.top*d-s,image:t.dom}});g.add(e)}),g.refreshImmediately(),f.toDataURL("image/"+(t&&t.type||"png"))}return this.getDataURL(t)}this.id},e.prototype.convertToPixel=function(t,e,n){return mx(this,"convertToPixel",t,e,n)},e.prototype.convertToLayout=function(t,e,n){return mx(this,"convertToLayout",t,e,n)},e.prototype.convertFromPixel=function(t,e,n){return mx(this,"convertFromPixel",t,e,n)},e.prototype.containPixel=function(t,e){var n;if(!this._disposed)return Ui(kc(this._model,t),function(t,i){i.indexOf("Models")>=0&&Ui(t,function(t){var r=t.coordinateSystem;if(r&&r.containPoint)n=n||!!r.containPoint(e);else if("seriesModels"===i){var o=this._chartsMap[t.__viewId];o&&o.containPoint&&(n=n||o.containPoint(e,t))}},this)},this),!!n;this.id},e.prototype.getVisual=function(t,e){var n=kc(this._model,t,{defaultMainType:"series"}),i=n.seriesModel.getData(),r=n.hasOwnProperty("dataIndexInside")?n.dataIndexInside:n.hasOwnProperty("dataIndex")?i.indexOfRawIndex(n.dataIndex):null;return null!=r?function(t,e,n){switch(n){case"color":return t.getItemVisual(e,"style")[t.getVisual("drawType")];case"opacity":return t.getItemVisual(e,"style").opacity;case"symbol":case"symbolSize":case"liftZ":return t.getItemVisual(e,n)}}(i,r,e):function(t,e){switch(e){case"color":return t.getVisual("style")[t.getVisual("drawType")];case"opacity":return t.getVisual("style").opacity;case"symbol":case"symbolSize":case"liftZ":return t.getVisual(e)}}(i,e)},e.prototype.getViewOfComponentModel=function(t){return this._componentsMap[t.__viewId]},e.prototype.getViewOfSeriesModel=function(t){return this._chartsMap[t.__viewId]},e.prototype._initEvents=function(){var t=this;Ui(Ox,function(e){var n=function(n){var i,r=t.getModel(),o=n.target;if("globalout"===e?i={}:o&&db(o,function(t){var e=Ud(t);if(e&&null!=e.dataIndex){var n=e.dataModel||r.getSeriesByIndex(e.seriesIndex);return i=n&&n.getDataParams(e.dataIndex,e.dataType,o)||{},!0}if(e.eventData)return i=Fi({},e.eventData),!0},!0),i){var a=i.componentType,s=i.componentIndex;"markLine"!==a&&"markPoint"!==a&&"markArea"!==a||(a="series",s=i.seriesIndex);var l=a&&null!=s&&r.getComponent(a,s),c=l&&t["series"===l.mainType?"_chartsMap":"_componentsMap"][l.__viewId];i.event=n,i.type=e,t._$eventProcessor.eventInfo={targetEl:o,packedEvent:i,model:l,view:c},t.trigger(e,i)}};n.zrEventfulCallAtLast=!0,t._zr.on(e,n,t)});var e=this._messageCenter;Ui(Bx,function(n,i){e.on(i,function(e){t.trigger(i,e)})}),function(t,e,n){t.on("selectchanged",function(t){var i=n.getModel();t.isFromClick?(ub("map","selectchanged",e,i,t),ub("pie","selectchanged",e,i,t)):"select"===t.fromAction?(ub("map","selected",e,i,t),ub("pie","selected",e,i,t)):"unselect"===t.fromAction&&(ub("map","unselected",e,i,t),ub("pie","unselected",e,i,t))})}(e,this,this._api)},e.prototype.isDisposed=function(){return this._disposed},e.prototype.clear=function(){this._disposed?this.id:this.setOption({series:[]},!0)},e.prototype.dispose=function(){if(this._disposed)this.id;else{this._disposed=!0,this.getDom()&&Ic(this.getDom(),Xx,"");var t=this,e=t._api,n=t._model;Ui(t._componentsViews,function(t){t.dispose(n,e)}),Ui(t._chartsViews,function(t){t.dispose(n,e)}),t._zr.dispose(),t._dom=t._model=t._chartsMap=t._componentsMap=t._chartsViews=t._componentsViews=t._scheduler=t._api=t._zr=t._throttledZrFlush=t._theme=t._coordSysMgr=t._messageCenter=null,delete qx[t.id]}},e.prototype.resize=function(t){if(!this[ix])if(this._disposed)this.id;else{this._zr.resize(t);var e=this._model;if(this._loadingFX&&this._loadingFX.resize(),e){var n=e.resetOption("media"),i=t&&t.silent;this[ox]&&(null==i&&(i=this[ox].silent),n=!0,this[ox]=null),this[ix]=!0,Px(this);try{n&&hx(this),gx.update.call(this,{type:"resize",animation:Fi({duration:0},t&&t.animation)})}catch(t){throw this[ix]=!1,t}this[ix]=!1,_x.call(this,i),bx.call(this,i)}}},e.prototype.showLoading=function(t,e){if(this._disposed)this.id;else if(rr(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),jx[t]){var n=jx[t](this._api,e),i=this._zr;this._loadingFX=n,i.add(n)}},e.prototype.hideLoading=function(){this._disposed?this.id:(this._loadingFX&&this._zr.remove(this._loadingFX),this._loadingFX=null)},e.prototype.makeActionFromEvent=function(t){var e=Fi({},t);return e.type=Hx[t.type],e},e.prototype.dispatchAction=function(t,e){if(this._disposed)this.id;else if(rr(e)||(e={silent:!!e}),zx[t.type]&&this._model)if(this[ix])this._pendingActions.push(t);else{var n=e.silent;yx.call(this,t,n);var i=e.flush;i?this._zr.flush():!1!==i&&yi.browser.weChat&&this._throttledZrFlush(),_x.call(this,n),bx.call(this,n)}},e.prototype.updateLabelLayout=function(){Qb.trigger("series:layoutlabels",this._model,this._api,{updatedSeries:[]})},e.prototype.appendData=function(t){if(this._disposed)this.id;else{var e=t.seriesIndex;this.getModel().getSeriesByIndex(e).appendData(t),this._scheduler.unfinished=!0,this.getZr().wakeUp()}},e.internalField=function(){function t(t){t.clearColorPalette(),t.eachSeries(function(t){t.clearColorPalette()})}function e(t){for(var e=[],n=t.currentStates,i=0;i0?{duration:o,delay:i.get("delay"),easing:i.get("easing")}:null;n.eachRendered(function(t){if(t.states&&t.states.emphasis){if(of(t))return;if(t instanceof vd&&function(t){var e=Yd(t);e.normalFill=t.style.fill,e.normalStroke=t.style.stroke;var n=t.states.select||{};e.selectFill=n.style&&n.style.fill||null,e.selectStroke=n.style&&n.style.stroke||null}(t),t.__dirty){var n=t.prevStates;n&&t.useStates(n)}if(r){t.stateTransition=a;var i=t.getTextContent(),o=t.getTextGuideLine();i&&(i.stateTransition=a),o&&(o.stateTransition=a)}t.__dirty&&e(t)}})}hx=function(t){var e=t._scheduler;e.restorePipelines(t._model),e.prepareStageTasks(),px(t,!0),px(t,!1),e.plan()},px=function(t,e){for(var n=t._model,i=t._scheduler,r=e?t._componentsViews:t._chartsViews,o=e?t._componentsMap:t._chartsMap,a=t._zr,s=t._api,l=0;le.get("hoverLayerThreshold")&&!yi.node&&!yi.worker&&e.eachSeries(function(e){if(!e.preventUsingHoverLayer){var n=t._chartsMap[e.__viewId];n.__alive&&n.eachRendered(function(t){t.states.emphasis&&(t.states.emphasis.hoverLayer=!0)})}})}(t,e),Qb.trigger("series:afterupdate",e,o,s)},Ix=function(t){t[ax]=!0,t.getZr().wakeUp()},Px=function(t){t[rx]=(t[rx]+1)%1e3},Dx=function(t){t[ax]&&(t.getZr().storage.traverse(function(t){of(t)||e(t)}),t[ax]=!1)},Tx=function(t){return new(function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return S(n,e),n.prototype.getCoordinateSystems=function(){return t._coordSysMgr.getCoordinateSystems()},n.prototype.getComponentByElement=function(e){for(;e;){var n=e.__ecComponentInfo;if(null!=n)return t._model.getComponent(n.mainType,n.index);e=e.parent}},n.prototype.enterEmphasis=function(e,n){bh(e,n),Ix(t)},n.prototype.leaveEmphasis=function(e,n){xh(e,n),Ix(t)},n.prototype.enterBlur=function(e){!function(t){fh(t,ch)}(e),Ix(t)},n.prototype.leaveBlur=function(e){wh(e),Ix(t)},n.prototype.enterSelect=function(e){Sh(e),Ix(t)},n.prototype.leaveSelect=function(e){Ch(e),Ix(t)},n.prototype.getModel=function(){return t.getModel()},n.prototype.getViewOfComponentModel=function(e){return t.getViewOfComponentModel(e)},n.prototype.getViewOfSeriesModel=function(e){return t.getViewOfSeriesModel(e)},n.prototype.getMainProcessVersion=function(){return t[rx]},n}(hv))(t)},Ax=function(t){function e(t,e){for(var n=0;n=0)){nw.push(n);var o=H_.wrapStageHandler(n,r);o.__prio=e,o.__raw=n,t.push(o)}}function rw(t,e){jx[t]=e}var ow=function(t){var e=(t=Bi(t)).type;e||lc("");var n=e.split(":");2!==n.length&&lc("");var i=!1;"echarts"===n[0]&&(e=n[1],i=!0),t.__isBuiltIn=i,wy.set(e,t)};function aw(t,e,n,i){return{eventContent:{selected:Ph(n),isFromClick:e.isFromClick||!1}}}function sw(t){return null==t?0:t.length||1}function lw(t){return t}ew(tx,E_),ew(ex,R_),ew(ex,O_),ew(tx,lb),ew(ex,cb),ew(7e3,function(t,e){t.eachRawSeries(function(n){if(!t.isSeriesFiltered(n)){var i=n.getData();i.hasItemVisual()&&i.each(function(t){var n=i.getItemVisual(t,"decal");n&&(i.ensureUniqueItemVisual(t,"style").decal=Xb(n,e))});var r=i.getVisual("decal");if(r)i.getVisual("style").decal=Xb(r,e)}})}),Kx(Rv),Qx(900,function(t){var e=Sr();t.eachSeries(function(t){var n=t.get("stack");if(n){var i=e.get(n)||e.set(n,[]),r=t.getData(),o={stackResultDimension:r.getCalculationInfo("stackResultDimension"),stackedOverDimension:r.getCalculationInfo("stackedOverDimension"),stackedDimension:r.getCalculationInfo("stackedDimension"),stackedByDimension:r.getCalculationInfo("stackedByDimension"),isStackedByIndex:r.getCalculationInfo("isStackedByIndex"),data:r,seriesModel:t};if(!o.stackedDimension||!o.isStackedByIndex&&!o.stackedByDimension)return;i.push(o)}}),e.each(function(t){0!==t.length&&("seriesDesc"===(t[0].seriesModel.get("stackOrder")||"seriesAsc")&&t.reverse(),Ui(t,function(e,n){e.data.setCalculationInfo("stackedOnSeries",n>0?t[n-1].seriesModel:null)}),function(t){Ui(t,function(e,n){var i=[],r=[NaN,NaN],o=[e.stackResultDimension,e.stackedOverDimension],a=e.data,s=e.isStackedByIndex,l=e.seriesModel.get("stackStrategy")||"samesign";a.modify(o,function(o,c,u){var d,h,p=a.get(e.stackedDimension,u);if(isNaN(p))return r;s?h=a.getRawIndex(u):d=a.get(e.stackedByDimension,u);for(var f=NaN,g=n-1;g>=0;g--){var m=t[g];if(s||(h=m.data.rawIndexOf(m.stackedByDimension,d)),h>=0){var v=m.data.getByRawIndex(m.stackResultDimension,h);if("all"===l||"positive"===l&&v>0||"negative"===l&&v<0||"samesign"===l&&p>=0&&v>0||"samesign"===l&&p<=0&&v<0){p=Yl(p,v),f=v;break}}}return i[0]=p,i[1]=f,i})})}(t))})}),rw("default",function(t,e){Vi(e=e||{},{text:"loading",textColor:Im.color.primary,fontSize:12,fontWeight:"normal",fontStyle:"normal",fontFamily:"sans-serif",maskColor:"rgba(255,255,255,0.8)",showSpinner:!0,color:Im.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new Nl,i=new Id({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});n.add(i);var r,o=new Ed({style:{text:e.text,fill:e.textColor,fontSize:e.fontSize,fontWeight:e.fontWeight,fontStyle:e.fontStyle,fontFamily:e.fontFamily},zlevel:e.zlevel,z:10001}),a=new Id({style:{fill:"none"},textContent:o,textConfig:{position:"right",distance:10},zlevel:e.zlevel,z:10001});return n.add(a),e.showSpinner&&((r=new Hp({shape:{startAngle:-z_/2,endAngle:-z_/2+.1,r:e.spinnerRadius},style:{stroke:e.color,lineCap:"round",lineWidth:e.lineWidth},zlevel:e.zlevel,z:10001})).animateShape(!0).when(1e3,{endAngle:3*z_/2}).start("circularInOut"),r.animateShape(!0).when(1e3,{startAngle:3*z_/2}).delay(300).start("circularInOut"),n.add(r)),n.resize=function(){var n=o.getBoundingRect().width,s=e.showSpinner?e.spinnerRadius:0,l=(t.getWidth()-2*s-(e.showSpinner&&n?10:0)-n)/2-(e.showSpinner&&n?0:5+n/2)+(e.showSpinner?0:n/2)+(n?0:s),c=t.getHeight()/2;e.showSpinner&&r.setShape({cx:l,cy:c}),a.setShape({x:l-s,y:c-s,width:2*s,height:2*s}),i.setShape({x:0,y:0,width:t.getWidth(),height:t.getHeight()})},n.resize(),n}),tw({type:Jd,event:Jd,update:Jd},Mr),tw({type:th,event:th,update:th},Mr),tw({type:eh,event:rh,update:eh,action:Mr,refineEvent:aw,publishNonRefinedEvent:!0}),tw({type:nh,event:rh,update:nh,action:Mr,refineEvent:aw,publishNonRefinedEvent:!0}),tw({type:ih,event:rh,update:ih,action:Mr,refineEvent:aw,publishNonRefinedEvent:!0}),Zx("default",{}),Zx("dark",rb);var cw=function(){function t(t,e,n,i,r,o){this._old=t,this._new=e,this._oldKeyGetter=n||lw,this._newKeyGetter=i||lw,this.context=r,this._diffModeMultiple="multiple"===o}return t.prototype.add=function(t){return this._add=t,this},t.prototype.update=function(t){return this._update=t,this},t.prototype.updateManyToOne=function(t){return this._updateManyToOne=t,this},t.prototype.updateOneToMany=function(t){return this._updateOneToMany=t,this},t.prototype.updateManyToMany=function(t){return this._updateManyToMany=t,this},t.prototype.remove=function(t){return this._remove=t,this},t.prototype.execute=function(){this[this._diffModeMultiple?"_executeMultiple":"_executeOneToOne"]()},t.prototype._executeOneToOne=function(){var t=this._old,e=this._new,n={},i=new Array(t.length),r=new Array(e.length);this._initIndexMap(t,null,i,"_oldKeyGetter"),this._initIndexMap(e,n,r,"_newKeyGetter");for(var o=0;o1){var c=s.shift();1===s.length&&(n[a]=s[0]),this._update&&this._update(c,o)}else 1===l?(n[a]=null,this._update&&this._update(s,o)):this._remove&&this._remove(o)}this._performRestAdd(r,n)},t.prototype._executeMultiple=function(){var t=this._old,e=this._new,n={},i={},r=[],o=[];this._initIndexMap(t,n,r,"_oldKeyGetter"),this._initIndexMap(e,i,o,"_newKeyGetter");for(var a=0;a1&&1===d)this._updateManyToOne&&this._updateManyToOne(c,l),i[s]=null;else if(1===u&&d>1)this._updateOneToMany&&this._updateOneToMany(c,l),i[s]=null;else if(1===u&&1===d)this._update&&this._update(c,l),i[s]=null;else if(u>1&&d>1)this._updateManyToMany&&this._updateManyToMany(c,l),i[s]=null;else if(u>1)for(var h=0;h1)for(var a=0;a30}var bw,xw,ww,Sw,Cw,kw,Mw,Tw=rr,Aw=Gi,Iw="undefined"==typeof Int32Array?Array:Int32Array,Dw=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],Pw=["_approximateExtent"],Lw=function(){function t(t,e){var n;this.type="list",this._dimOmitted=!1,this._nameList=[],this._idList=[],this._visual={},this._layout={},this._itemVisuals=[],this._itemLayouts=[],this._graphicEls=[],this._approximateExtent={},this._calculationInfo={},this.hasItemOption=!1,this.TRANSFERABLE_METHODS=["cloneShallow","downSample","minmaxDownSample","lttbDownSample","map"],this.CHANGABLE_METHODS=["filterSelf","selectRange"],this.DOWNSAMPLE_METHODS=["downSample","minmaxDownSample","lttbDownSample"];var i=!1;mw(t)?(n=t.dimensions,this._dimOmitted=t.isDimensionOmitted(),this._schema=t):(i=!0,n=t),n=n||["x","y"];for(var r={},o=[],a={},s=!1,l={},c=0;c=e)){var n=this._store.getProvider();this._updateOrdinalMeta();var i=this._nameList,r=this._idList;if(n.getSource().sourceFormat===Bm&&!n.pure)for(var o=[],a=t;a0},t.prototype.ensureUniqueItemVisual=function(t,e){var n=this._itemVisuals,i=n[t];i||(i=n[t]={});var r=i[e];return null==r&&(Ji(r=this.getVisual(e))?r=r.slice():Tw(r)&&(r=Fi({},r)),i[e]=r),r},t.prototype.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{};this._itemVisuals[t]=i,Tw(e)?Fi(i,e):i[e]=n},t.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},t.prototype.setLayout=function(t,e){Tw(t)?Fi(this._layout,t):this._layout[t]=e},t.prototype.getLayout=function(t){return this._layout[t]},t.prototype.getItemLayout=function(t){return this._itemLayouts[t]},t.prototype.setItemLayout=function(t,e,n){this._itemLayouts[t]=n?Fi(this._itemLayouts[t]||{},e):e},t.prototype.clearItemLayouts=function(){this._itemLayouts.length=0},t.prototype.setItemGraphicEl=function(t,e){!function(t,e,n,i){if(i){var r=Ud(i);r.dataIndex=n,r.dataType=e,r.seriesIndex=t,r.ssrType="chart","group"===i.type&&i.traverse(function(i){var r=Ud(i);r.seriesIndex=t,r.dataIndex=n,r.dataType=e,r.ssrType="chart"})}}(this.hostModel&&this.hostModel.seriesIndex,this.dataType,t,e),this._graphicEls[t]=e},t.prototype.getItemGraphicEl=function(t){return this._graphicEls[t]},t.prototype.eachItemGraphicEl=function(t,e){Ui(this._graphicEls,function(n,i){n&&t&&t.call(e,n,i)})},t.prototype.cloneShallow=function(e){return e||(e=new t(this._schema?this._schema:Aw(this.dimensions,this._getDimInfo,this),this.hostModel)),Cw(e,this),e._store=this._store,e},t.prototype.wrapMethod=function(t,e){var n=this[t];tr(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(t),this[t]=function(){var t=n.apply(this,arguments);return e.apply(this,[t].concat(pr(arguments)))})},t.internalField=(bw=function(t){var e=t._invertedIndicesMap;Ui(e,function(n,i){var r=t._dimInfos[i],o=r.ordinalMeta,a=t._store;if(o){n=e[i]=new Iw(o.categories.length);for(var s=0;s1&&(s+="__ec__"+c),i[e]=s}})),t}();function Ew(t,e){Wv(t)||(t=qv(t));var n=(e=e||{}).coordDimensions||[],i=e.dimensionsDefine||t.dimensionsDefine||[],r=Sr(),o=[],a=function(t,e,n,i){var r=Math.max(t.dimensionsDetectedCount||1,e.length,n.length,i||0);return Ui(e,function(t){var e;rr(t)&&(e=t.dimsDef)&&(r=Math.max(r,e.length))}),r}(t,n,i,e.dimensionsCount),s=e.canOmitUnusedDimensions&&_w(a),l=i===t.dimensionsDefine,c=l?yw(t):vw(i),u=e.encodeDefine;!u&&e.encodeDefaulter&&(u=e.encodeDefaulter(t,a));for(var d=Sr(u),h=new Iy(a),p=0;p0&&(i.name=r+(o-1)),o++,e.set(r,o)}}(o),new gw({source:t,dimensions:o,fullDimensionCount:a,dimensionOmitted:s})}function Nw(t,e,n){if(n||e.hasKey(t)){for(var i=0;e.hasKey(t+i);)i++;t+=i}return e.set(t,!0),t}var Rw=function(t){this.coordSysDims=[],this.axisMap=Sr(),this.categoryAxisMap=Sr(),this.coordSysName=t};var Ow={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis",Tc).models[0],o=t.getReferringComponents("yAxis",Tc).models[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",o),zw(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),zw(o)&&(i.set("y",o),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis",Tc).models[0];e.coordSysDims=["single"],n.set("single",r),zw(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar",Tc).models[0],o=r.findAxisModel("radiusAxis"),a=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",o),n.set("angle",a),zw(o)&&(i.set("radius",o),e.firstCategoryDimIndex=0),zw(a)&&(i.set("angle",a),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},geo:function(t,e,n,i){e.coordSysDims=["lng","lat"]},parallel:function(t,e,n,i){var r=t.ecModel,o=r.getComponent("parallel",t.get("parallelIndex")),a=e.coordSysDims=o.dimensions.slice();Ui(o.parallelAxisIndex,function(t,o){var s=r.getComponent("parallelAxis",t),l=a[o];n.set(l,s),zw(s)&&(i.set(l,s),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=o))})},matrix:function(t,e,n,i){var r=t.getReferringComponents("matrix",Tc).models[0];e.coordSysDims=["x","y"];var o=r.getDimensionModel("x"),a=r.getDimensionModel("y");n.set("x",o),n.set("y",a),i.set("x",o),i.set("y",a)}};function zw(t){return"category"===t.get("type")}function Hw(t,e,n){var i,r,o,a=(n=n||{}).byIndex,s=n.stackedCoordDimension;!function(t){return!mw(t.schema)}(e)?(r=e.schema,i=r.dimensions,o=e.store):i=e;var l,c,u,d,h=!(!t||!t.get("stack"));if(Ui(i,function(t,e){er(t)&&(i[e]=t={name:t}),h&&!t.isExtraCoord&&(a||l||!t.ordinalMeta||(l=t),c||"ordinal"===t.type||"time"===t.type||s&&s!==t.coordDim||(c=t))}),!c||a||l||(a=!0),c){u="__\0ecstackresult_"+t.id,d="__\0ecstackedover_"+t.id,l&&(l.createInvertedIndices=!0);var p=c.coordDim,f=c.type,g=0;Ui(i,function(t){t.coordDim===p&&g++});var m={name:u,coordDim:p,coordDimIndex:g,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length},v={name:d,coordDim:d,coordDimIndex:g+1,type:f,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:i.length+1};r?(o&&(m.storeDimIndex=o.ensureCalculationDimension(d,f),v.storeDimIndex=o.ensureCalculationDimension(u,f)),r.appendCalculationDimension(m),r.appendCalculationDimension(v)):(i.push(m),i.push(v))}return{stackedDimension:c&&c.name,stackedByDimension:l&&l.name,isStackedByIndex:a,stackedOverDimension:d,stackResultDimension:u}}function Bw(t,e){return!!e&&e===t.getCalculationInfo("stackedDimension")}function $w(t,e,n){n=n||{};var i,r,o=e.getSourceManager();r=(i=o.getSource()).sourceFormat===Bm;var a=function(t){var e=t.get("coordinateSystem"),n=new Rw(e),i=Ow[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}(e),s=function(t,e){var n,i=t.get("coordinateSystem"),r=cm.get(i);return e&&e.coordSysDims&&(n=Gi(e.coordSysDims,function(t){var n={name:t},i=e.axisMap.get(t);if(i){var r=i.get("type");n.type=function(t){return"category"===t?"ordinal":"time"===t?"time":"float"}(r)}return n})),n||(n=r&&(r.getDimensionsInfo?r.getDimensionsInfo():r.dimensions.slice())||["x","y"]),n}(e,a),l=n.useEncodeDefaulter,c=tr(l)?l:l?Qi(Km,s,e):null,u=Ew(i,{coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:e.getEncode(),encodeDefaulter:c,canOmitUnusedDimensions:!r}),d=function(t,e,n){var i,r;return n&&Ui(t,function(t,o){var a=t.coordDim,s=n.categoryAxisMap.get(a);s&&(null==i&&(i=o),t.ordinalMeta=s.getOrdinalMeta(),e&&(t.createInvertedIndices=!0)),null!=t.otherDims.itemName&&(r=!0)}),r||null==i||(t[i].otherDims.itemName=0),i}(u.dimensions,n.createInvertedIndices,a),h=r?null:o.getSharedDataStore(u),p=Hw(e,{schema:u,store:h}),f=new Lw(u,e);f.setCalculationInfo(p);var g=null!=d&&function(t){if(t.sourceFormat===Bm){var e=function(t){var e=0;for(;er&&(a=o.interval=r);var s=o.intervalPrecision=jw(a);return function(t,e){!isFinite(t[0])&&(t[0]=e[0]),!isFinite(t[1])&&(t[1]=e[1]),qw(t,0,e),qw(t,1,e),t[0]>t[1]&&(t[0]=t[1])}(o.niceTickExtent=[Gl(Math.ceil(t[0]/a)*a,s),Gl(Math.floor(t[1]/a)*a,s)],t),o}function Ww(t){var e=Math.pow(10,tc(t)),n=t/e;return n?2===n?n=3:3===n?n=5:n*=2:n=1,Gl(n*e)}function jw(t){return Xl(t)+2}function qw(t,e,n){t[e]=Math.max(Math.min(t[e],n[1]),n[0])}function Uw(t,e){return t>=e[0]&&t<=e[1]}var Gw=function(){function t(){this.normalize=Xw,this.scale=Yw}return t.prototype.updateMethods=function(t){t.hasBreaks()?(this.normalize=Ki(t.normalize,t),this.scale=Ki(t.scale,t)):(this.normalize=Xw,this.scale=Yw)},t}();function Xw(t,e){return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])}function Yw(t,e){return t*(e[1]-e[0])+e[0]}function Zw(t,e,n){var i=Math.log(t);return[Math.log(n?e[0]:Math.max(0,e[0]))/i,Math.log(n?e[1]:Math.max(0,e[1]))/i]}var Kw=function(){function t(t){this._calculator=new Gw,this._setting=t||{},this._extent=[1/0,-1/0]}return t.prototype.getSetting=function(t){return this._setting[t]},t.prototype._innerUnionExtent=function(t){var e=this._extent;this._innerSetExtent(t[0]e[1]?t[1]:e[1])},t.prototype.unionExtentFromData=function(t,e){this._innerUnionExtent(t.getApproximateExtent(e))},t.prototype.getExtent=function(){return this._extent.slice()},t.prototype.setExtent=function(t,e){this._innerSetExtent(t,e)},t.prototype._innerSetExtent=function(t,e){var n=this._extent;isNaN(t)||(n[0]=t),isNaN(e)||(n[1]=e),this._brkCtx&&this._brkCtx.update(n)},t.prototype.setBreaksFromOption=function(t){},t.prototype._innerSetBreak=function(t){this._brkCtx&&(this._brkCtx.setBreaks(t),this._calculator.updateMethods(this._brkCtx),this._brkCtx.update(this._extent))},t.prototype._innerGetBreaks=function(){return this._brkCtx?this._brkCtx.breaks:[]},t.prototype.hasBreaks=function(){return!!this._brkCtx&&this._brkCtx.hasBreaks()},t.prototype._getExtentSpanWithBreaks=function(){return this._brkCtx&&this._brkCtx.hasBreaks()?this._brkCtx.getExtentSpan():this._extent[1]-this._extent[0]},t.prototype.isInExtentRange=function(t){return this._extent[0]<=t&&this._extent[1]>=t},t.prototype.isBlank=function(){return this._isBlank},t.prototype.setBlank=function(t){this._isBlank=t},t}();Hc(Kw);var Qw=0,Jw=function(){function t(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this.uid=++Qw,this._onCollect=t.onCollect}return t.createByAxisModel=function(e){var n=e.option,i=n.data,r=i&&Gi(i,tS);return new t({categories:r,needCollect:!r,deduplication:!1!==n.dedplication})},t.prototype.getOrdinal=function(t){return this._getOrCreateMap().get(t)},t.prototype.parseAndCollect=function(t){var e,n=this._needCollect;if(!er(t)&&!n)return t;if(n&&!this._deduplication)return e=this.categories.length,this.categories[e]=t,this._onCollect&&this._onCollect(t,e),e;var i=this._getOrCreateMap();return null==(e=i.get(t))&&(n?(e=this.categories.length,this.categories[e]=t,i.set(t,e),this._onCollect&&this._onCollect(t,e)):e=NaN),e},t.prototype._getOrCreateMap=function(){return this._map||(this._map=Sr(this.categories))},t}();function tS(t){return rr(t)&&null!=t.value?t.value:t+""}var eS=function(t){function e(e){var n=t.call(this,e)||this;n.type="ordinal";var i=n.getSetting("ordinalMeta");return i||(i=new Jw({})),Ji(i)&&(i=new Jw({categories:Gi(i,function(t){return rr(t)?t.value:t})})),n._ordinalMeta=i,n._extent=n.getSetting("extent")||[0,i.categories.length-1],n}return S(e,t),e.prototype.parse=function(t){return null==t?NaN:er(t)?this._ordinalMeta.getOrdinal(t):Math.round(t)},e.prototype.contain=function(t){return Uw(t,this._extent)&&t>=0&&t=0&&t=0&&t=t},e.prototype.getOrdinalMeta=function(){return this._ordinalMeta},e.prototype.calcNiceTicks=function(){},e.prototype.calcNiceExtent=function(){},e.type="ordinal",e}(Kw);Kw.registerClass(eS);var nS=Gl,iS=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="interval",e._interval=0,e._intervalPrecision=2,e}return S(e,t),e.prototype.parse=function(t){return null==t||""===t?NaN:Number(t)},e.prototype.contain=function(t){return Uw(t,this._extent)},e.prototype.normalize=function(t){return this._calculator.normalize(t,this._extent)},e.prototype.scale=function(t){return this._calculator.scale(t,this._extent)},e.prototype.getInterval=function(){return this._interval},e.prototype.setInterval=function(t){this._interval=t,this._niceExtent=this._extent.slice(),this._intervalPrecision=jw(t)},e.prototype.getTicks=function(t){t=t||{};var e=this._interval,n=this._extent,i=this._niceExtent,r=this._intervalPrecision,o=[];if(!e)return o;t.breakTicks;n[0]=0&&(s=nS(s+l*e,r))}if(o.length>0&&s===o[o.length-1].value)break;if(o.length>1e4)return[]}var c=o.length?o[o.length-1].value:i[1];return n[1]>c&&(t.expandToNicedExtent?o.push({value:nS(c+e,r)}):o.push({value:n[1]})),t.breakTicks,o},e.prototype.getMinorTicks=function(t){for(var e=this.getTicks({expandToNicedExtent:!0}),n=[],i=this.getExtent(),r=1;ri[0]&&d0&&(o=null===o?s:Math.min(o,s))}n[i]=o}}return n}(t),n=[];return Ui(t,function(t){var i,r=t.coordinateSystem.getBaseAxis(),o=r.getExtent();if("category"===r.type)i=r.getBandWidth();else if("value"===r.type||"time"===r.type){var a=r.dim+"_"+r.index,s=e[a],l=Math.abs(o[1]-o[0]),c=r.scale.getExtent(),u=Math.abs(c[1]-c[0]);i=s?l/u*s:l}else{var d=t.getData();i=Math.abs(o[1]-o[0])/d.count()}var h=ql(t.get("barWidth"),i),p=ql(t.get("barMaxWidth"),i),f=ql(t.get("barMinWidth")||(function(t){return t.pipelineContext&&t.pipelineContext.large}(t)?.5:1),i),g=t.get("barGap"),m=t.get("barCategoryGap"),v=t.get("defaultBarGap");n.push({bandWidth:i,barWidth:h,barMaxWidth:p,barMinWidth:f,barGap:g,barCategoryGap:m,defaultBarGap:v,axisKey:lS(r),stackId:sS(t)})}),function(t){var e={};Ui(t,function(t,n){var i=t.axisKey,r=t.bandWidth,o=e[i]||{bandWidth:r,remainedWidth:r,autoWidthCount:0,categoryGap:null,gap:t.defaultBarGap||0,stacks:{}},a=o.stacks;e[i]=o;var s=t.stackId;a[s]||o.autoWidthCount++,a[s]=a[s]||{width:0,maxWidth:0};var l=t.barWidth;l&&!a[s].width&&(a[s].width=l,l=Math.min(o.remainedWidth,l),o.remainedWidth-=l);var c=t.barMaxWidth;c&&(a[s].maxWidth=c);var u=t.barMinWidth;u&&(a[s].minWidth=u);var d=t.barGap;null!=d&&(o.gap=d);var h=t.barCategoryGap;null!=h&&(o.categoryGap=h)});var n={};return Ui(e,function(t,e){n[e]={};var i=t.stacks,r=t.bandWidth,o=t.categoryGap;if(null==o){var a=Zi(i).length;o=Math.max(35-4*a,15)+"%"}var s=ql(o,r),l=ql(t.gap,1),c=t.remainedWidth,u=t.autoWidthCount,d=(c-s)/(u+(u-1)*l);d=Math.max(d,0),Ui(i,function(t){var e=t.maxWidth,n=t.minWidth;if(t.width){i=t.width;e&&(i=Math.min(i,e)),n&&(i=Math.max(i,n)),t.width=i,c-=i+l*i,u--}else{var i=d;e&&ei&&(i=n),i!==d&&(t.width=i,c-=i+l*i,u--)}}),d=(c-s)/(u+(u-1)*l),d=Math.max(d,0);var h,p=0;Ui(i,function(t,e){t.width||(t.width=d),h=t,p+=t.width*(1+l)}),h&&(p-=h.width*l);var f=-p/2;Ui(i,function(t,i){n[e][i]=n[e][i]||{bandWidth:r,offset:f,width:t.width},f+=t.width*(1+l)})}),n}(n)}var uS=function(t){function e(e){var n=t.call(this,e)||this;return n.type="time",n}return S(e,t),e.prototype.getLabel=function(t){var e=this.getSetting("useUTC");return Og(t.value,Ig[function(t){switch(t){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}(Ng(this._minLevelUnit))]||Ig.second,e,this.getSetting("locale"))},e.prototype.getFormattedLabel=function(t,e,n){var i=this.getSetting("useUTC");return function(t,e,n,i,r){var o=null;if(er(n))o=n;else if(tr(n)){var a={time:t.time,level:t.time.level},s=null;s&&s.makeAxisLabelFormatterParamBreak(a,t.break),o=n(t.value,e,a)}else{var l=t.time;if(l){var c=n[l.lowerTimeUnit][l.upperTimeUnit];o=c[Math.min(l.level,c.length-1)]||""}else{var u=zg(t.value,r);o=n[u][u][0]}}return Og(new Date(t.value),o,r,i)}(t,e,n,this.getSetting("locale"),i)},e.prototype.getTicks=function(t){var e=this._interval,n=this._extent,i=[];if(!e)return i;var r=this.getSetting("useUTC"),o=zg(n[1],r);i.push({value:n[0],time:{level:0,upperTimeUnit:o,lowerTimeUnit:o}});var a=function(t,e,n,i,r,o){var a=1e4,s=Pg,l=0;function c(t,e,n,r,s,c,u){for(var d=function(t,e){var n=new Date(0);n[t](1);var i=n.getTime();n[t](1+e);var r=n.getTime()-i;return function(t,e){return Math.max(0,Math.round((e-t)/r))}}(s,t),h=e,p=new Date(h);ha));)if(p[s](p[r]()+t),h=p.getTime(),o){var f=o.calcNiceTickMultiple(h,d);f>0&&(p[s](p[r]()+f*t),h=p.getTime())}u.push({value:h,notAdd:!0})}function u(t,r,o){var a=[],s=!r.length;if(!function(t,e,n,i){return Hg(new Date(e),t,i).getTime()===Hg(new Date(n),t,i).getTime()}(Ng(t),i[0],i[1],n)){s&&(r=[{value:vS(i[0],t,n)},{value:i[1]}]);for(var l=0;l=i[0]&&u<=i[1]&&c(h,u,d,p,f,g,a),"year"===t&&o.length>1&&0===l&&o.unshift({value:o[0].value-h})}}for(l=0;l=i[0]&&_<=i[1]&&p++)}var b=r/e;if(p>1.5*b&&f>b/1.5)break;if(d.push(v),p>b||t===s[g])break}h=[]}}var x=Yi(Gi(d,function(t){return Yi(t,function(t){return t.value>=i[0]&&t.value<=i[1]&&!t.notAdd})}),function(t){return t.length>0}),w=[],S=x.length-1;for(g=0;gn&&(this._approxInterval=n);var r=dS.length,o=Math.min(function(t,e,n,i){for(;n>>1;t[r][1]16?16:t>7.5?7:t>3.5?4:t>1.5?2:1}function pS(t){return(t/=2592e6)>6?6:t>3?3:t>2?2:1}function fS(t){return(t/=Sg)>12?12:t>6?6:t>3.5?4:t>2?2:1}function gS(t,e){return(t/=e?wg:xg)>30?30:t>20?20:t>15?15:t>10?10:t>5?5:t>2?2:1}function mS(t){return ec(t)}function vS(t,e,n){var i=Math.max(0,Wi(Dg,e)-1);return Hg(new Date(t),Dg[i],n).getTime()}Kw.registerClass(uS);var yS=Gl,_S=Math.floor,bS=Math.ceil,xS=Math.pow,wS=Math.log,SS=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="log",e.base=10,e._originalScale=new iS,e}return S(e,t),e.prototype.getTicks=function(e){e=e||{};var n=this._extent.slice(),i=this._originalScale.getExtent(),r=t.prototype.getTicks.call(this,e),o=this.base;return this._originalScale._innerGetBreaks(),Gi(r,function(t){var e=t.value,r=null,a=xS(o,e);return e===n[0]&&this._fixMin?r=i[0]:e===n[1]&&this._fixMax&&(r=i[1]),null!=r&&(a=CS(a,r)),{value:a,break:void 0}},this)},e.prototype._getNonTransBreaks=function(){return this._originalScale._innerGetBreaks()},e.prototype.setExtent=function(e,n){this._originalScale.setExtent(e,n);var i=Zw(this.base,[e,n]);t.prototype.setExtent.call(this,i[0],i[1])},e.prototype.getExtent=function(){var e=this.base,n=t.prototype.getExtent.call(this);n[0]=xS(e,n[0]),n[1]=xS(e,n[1]);var i=this._originalScale.getExtent();return this._fixMin&&(n[0]=CS(n[0],i[0])),this._fixMax&&(n[1]=CS(n[1],i[1])),n},e.prototype.unionExtentFromData=function(t,e){this._originalScale.unionExtentFromData(t,e);var n=Zw(this.base,t.getApproximateExtent(e),!0);this._innerUnionExtent(n)},e.prototype.calcNiceTicks=function(t){t=t||10;var e=this._extent.slice(),n=this._getExtentSpanWithBreaks();if(isFinite(n)&&!(n<=0)){var i,r=(i=n,Math.pow(10,tc(i)));for(t/n*r<=.5&&(r*=10);!isNaN(r)&&Math.abs(r)<1&&Math.abs(r)>0;)r*=10;var o=[yS(bS(e[0]/r)*r),yS(_S(e[1]/r)*r)];this._interval=r,this._intervalPrecision=jw(r),this._niceExtent=o}},e.prototype.calcNiceExtent=function(e){t.prototype.calcNiceExtent.call(this,e),this._fixMin=e.fixMin,this._fixMax=e.fixMax},e.prototype.contain=function(e){return e=wS(e)/wS(this.base),t.prototype.contain.call(this,e)},e.prototype.normalize=function(e){return e=wS(e)/wS(this.base),t.prototype.normalize.call(this,e)},e.prototype.scale=function(e){return e=t.prototype.scale.call(this,e),xS(this.base,e)},e.prototype.setBreaksFromOption=function(t){},e.type="log",e}(iS);function CS(t,e){return yS(t,Xl(e))}Kw.registerClass(SS);var kS=function(){function t(t,e,n){this._prepareParams(t,e,n)}return t.prototype._prepareParams=function(t,e,n){n[1]0&&s>0&&!l&&(a=0),a<0&&s<0&&!c&&(s=0));var d=this._determinedMin,h=this._determinedMax;return null!=d&&(a=d,l=!0),null!=h&&(s=h,c=!0),{min:a,max:s,minFixed:l,maxFixed:c,isBlank:u}},t.prototype.modifyDataMinMax=function(t,e){this[TS[t]]=e},t.prototype.setDeterminedMinMax=function(t,e){this[MS[t]]=e},t.prototype.freeze=function(){this.frozen=!0},t}(),MS={min:"_determinedMin",max:"_determinedMax"},TS={min:"_dataMin",max:"_dataMax"};function AS(t,e){return null==e?null:cr(e)?NaN:t.parse(e)}function IS(t,e){var n=t.type,i=function(t,e,n){var i=t.rawExtentInfo;return i||(i=new kS(t,e,n),t.rawExtentInfo=i,i)}(t,e,t.getExtent()).calculate();t.setBlank(i.isBlank);var r=i.min,o=i.max,a=e.ecModel;if(a&&"time"===n){var s=function(t,e){var n=[];return e.eachSeriesByType(t,function(t){(function(t){return t.coordinateSystem&&"cartesian2d"===t.coordinateSystem.type})(t)&&n.push(t)}),n}("bar",a),l=!1;if(Ui(s,function(t){l=l||t.getBaseAxis()===e.axis}),l){var c=cS(s),u=function(t,e,n,i){var r=n.axis.getExtent(),o=Math.abs(r[1]-r[0]),a=function(t,e){if(t&&e)return t[lS(e)]}(i,n.axis);if(void 0===a)return{min:t,max:e};var s=1/0;Ui(a,function(t){s=Math.min(t.offset,s)});var l=-1/0;Ui(a,function(t){l=Math.max(t.offset+t.width,l)}),s=Math.abs(s),l=Math.abs(l);var c=s+l,u=e-t,d=u/(1-(s+l)/o)-u;return e+=d*(l/c),t-=d*(s/c),{min:t,max:e}}(r,o,e,c);r=u.min,o=u.max}}return{extent:[r,o],fixMin:i.minFixed,fixMax:i.maxFixed}}function DS(t,e){var n=e,i=IS(t,n),r=i.extent,o=n.get("splitNumber");t instanceof SS&&(t.base=n.get("logBase"));var a=t.type,s=n.get("interval"),l="interval"===a||"time"===a;t.setBreaksFromOption(HS(n)),t.setExtent(r[0],r[1]),t.calcNiceExtent({splitNumber:o,fixMin:i.fixMin,fixMax:i.fixMax,minInterval:l?n.get("minInterval"):null,maxInterval:l?n.get("maxInterval"):null}),null!=s&&t.setInterval&&t.setInterval(s)}function PS(t){var e=t.getLabelModel().get("formatter");if("time"===t.type){var n=Lg(e);return function(e,i){return t.scale.getFormattedLabel(e,i,n)}}if(er(e))return function(n){var i=t.scale.getLabel(n);return e.replace("{value}",null!=i?i:"")};if(tr(e)){if("category"===t.type)return function(n,i){return e(LS(t,n),n.value-t.scale.getExtent()[0],null)};var i=null;return function(n,r){var o=null;return i&&(o=i.makeAxisLabelFormatterParamBreak(o,n.break)),e(LS(t,n),r,o)}}return function(e){return t.scale.getLabel(e)}}function LS(t,e){return"category"===t.type?t.scale.getLabel(e):e.value}function ES(t){var e=t.get("interval");return null==e?"auto":e}function NS(t){return"category"===t.type&&0===ES(t.getLabelModel())}function RS(t,e){var n={};return Ui(t.mapDimensionsAll(e),function(e){n[function(t,e){return Bw(t,e)?t.getCalculationInfo("stackResultDimension"):e}(t,e)]=!0}),Zi(n)}function OS(t){return"middle"===t||"center"===t}function zS(t){return t.getShallow("show")}function HS(t){t.get("breaks",!0)}var BS=function(){function t(){}return t.prototype.getNeedCrossZero=function(){return!this.option.scale},t.prototype.getCoordSysModel=function(){},t}(),$S=[],FS={registerPreprocessor:Kx,registerProcessor:Qx,registerPostInit:function(t){Jx("afterinit",t)},registerPostUpdate:function(t){Jx("afterupdate",t)},registerUpdateLifecycle:Jx,registerAction:tw,registerCoordinateSystem:function(t,e){cm.register(t,e)},registerLayout:function(t,e){iw(Vx,t,e,1e3,"layout")},registerVisual:ew,registerTransform:ow,registerLoading:rw,registerMap:function(t,e,n){var i=Jb["registerMap"];i&&i(t,e,n)},registerImpl:function(t,e){Jb[t]=e},PRIORITY:nx,ComponentModel:Am,ComponentView:h_,SeriesModel:r_,ChartView:m_,registerComponentModel:function(t){Am.registerClass(t)},registerComponentView:function(t){h_.registerClass(t)},registerSeriesModel:function(t){r_.registerClass(t)},registerChartView:function(t){m_.registerClass(t)},registerCustomSeries:function(t,e){},registerSubTypeDefaulter:function(t,e){Am.registerSubTypeDefaulter(t,e)},registerPainter:function(t,e){var n;n=e,Rl[t]=n}};function VS(t){Ji(t)?Ui(t,function(t){VS(t)}):Wi($S,t)>=0||($S.push(t),tr(t)&&(t={install:t}),t.install(FS))}var WS=Sc(),jS=Sc(),qS=1,US=2;function GS(t){return{out:{noPxChangeTryDetermine:[]},kind:t}}function XS(t,e){var n=Gi(e,function(e){return t.scale.parse(e)});return"time"===t.type&&n.length>0&&(n.sort(),n.unshift(n[0]),n.push(n[n.length-1])),n}function YS(t,e){var n=t.getLabelModel().get("customValues");if(n){var i=PS(t),r=t.scale.getExtent();return{labels:Gi(Yi(XS(t,n),function(t){return t>=r[0]&&t<=r[1]}),function(e){var n={value:e};return{formattedLabel:i(n),rawLabel:t.scale.getLabel(n),tickValue:e,time:void 0,break:void 0}})}}return"category"===t.type?function(t,e){var n=t.getLabelModel(),i=KS(t,n,e);return!n.get("show")||t.scale.isBlank()?{labels:[]}:i}(t,e):function(t){var e=t.scale.getTicks(),n=PS(t);return{labels:Gi(e,function(e,i){return{formattedLabel:n(e,i),rawLabel:t.scale.getLabel(e),tickValue:e.value,time:e.time,break:e.break}})}}(t)}function ZS(t,e,n){var i=t.getTickModel().get("customValues");if(i){var r=t.scale.getExtent();return{ticks:Yi(XS(t,i),function(t){return t>=r[0]&&t<=r[1]})}}return"category"===t.type?function(t,e){var n,i,r=QS(t),o=ES(e),a=eC(r,o);if(a)return a;e.get("show")&&!t.scale.isBlank()||(n=[]);if(tr(o))n=aC(t,o,!0);else if("auto"===o){var s=KS(t,t.getLabelModel(),GS(US));i=s.labelCategoryInterval,n=Gi(s.labels,function(t){return t.tickValue})}else n=oC(t,i=o,!0);return nC(r,o,{ticks:n,tickCategoryInterval:i})}(t,e):{ticks:Gi(t.scale.getTicks(n),function(t){return t.value})}}function KS(t,e,n){var i,r,o=JS(t),a=ES(e),s=n.kind===qS;if(!s){var l=eC(o,a);if(l)return l}tr(a)?i=aC(t,a):(r="auto"===a?function(t,e){if(e.kind===qS){var n=t.calculateCategoryInterval(e);return e.out.noPxChangeTryDetermine.push(function(){return jS(t).autoInterval=n,!0}),n}var i=jS(t).autoInterval;return null!=i?i:jS(t).autoInterval=t.calculateCategoryInterval(e)}(t,n):a,i=oC(t,r));var c={labels:i,labelCategoryInterval:r};return s?n.out.noPxChangeTryDetermine.push(function(){return nC(o,a,c),!0}):nC(o,a,c),c}var QS=tC("axisTick"),JS=tC("axisLabel");function tC(t){return function(e){return jS(e)[t]||(jS(e)[t]={list:[]})}}function eC(t,e){for(var n=0;ne&&i.axisExtent0===r[0]&&i.axisExtent1===r[1])return o;i.lastTickCount=n,i.lastAutoInterval=e,i.axisExtent0=r[0],i.axisExtent1=r[1]}function oC(t,e,n){var i=PS(t),r=t.scale,o=r.getExtent(),a=t.getLabelModel(),s=[],l=Math.max((e||0)+1,1),c=o[0],u=r.count();0!==c&&l>1&&u/l>2&&(c=Math.round(Math.ceil(c/l)*l));var d=NS(t),h=a.get("showMinLabel")||d,p=a.get("showMaxLabel")||d;h&&c!==o[0]&&g(o[0]);for(var f=c;f<=o[1];f+=l)g(f);function g(t){var e={value:t};s.push(n?t:{formattedLabel:i(e),rawLabel:r.getLabel(e),tickValue:t,time:void 0,break:void 0})}return p&&f-l!==o[1]&&g(o[1]),s}function aC(t,e,n){var i=t.scale,r=PS(t),o=[];return Ui(i.getTicks(),function(t){var a=i.getLabel(t),s=t.value;e(t.value,a)&&o.push(n?s:{formattedLabel:r(t),rawLabel:a,tickValue:s,time:void 0,break:void 0})}),o}var sC=[0,1],lC=function(){function t(t,e,n){this.onBand=!1,this.inverse=!1,this.dim=t,this.scale=e,this._extent=n||[0,0]}return t.prototype.contain=function(t){var e=this._extent,n=Math.min(e[0],e[1]),i=Math.max(e[0],e[1]);return t>=n&&t<=i},t.prototype.containData=function(t){return this.scale.contain(this.scale.parse(t))},t.prototype.getExtent=function(){return this._extent.slice()},t.prototype.getPixelPrecision=function(t){return function(t,e){var n=Math.log,i=Math.LN10,r=Math.floor(n(t[1]-t[0])/i),o=Math.round(n(Wl(e[1]-e[0]))/i),a=Math.min(Math.max(-r+o,0),20);return isFinite(a)?a:20}(t||this.scale.getExtent(),this._extent)},t.prototype.setExtent=function(t,e){var n=this._extent;n[0]=t,n[1]=e},t.prototype.dataToCoord=function(t,e){var n=this._extent,i=this.scale;return t=i.normalize(i.parse(t)),this.onBand&&"ordinal"===i.type&&cC(n=n.slice(),i.count()),jl(t,sC,n,e)},t.prototype.coordToData=function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&cC(n=n.slice(),i.count());var r=jl(t,n,sC,e);return this.scale.scale(r)},t.prototype.pointToData=function(t,e){},t.prototype.getTicksCoords=function(t){var e=(t=t||{}).tickModel||this.getTickModel(),n=Gi(ZS(this,e,{breakTicks:t.breakTicks,pruneByBreak:t.pruneByBreak}).ticks,function(t){return{coord:this.dataToCoord("ordinal"===this.scale.type?this.scale.getRawOrdinalNumber(t):t),tickValue:t}},this);return function(t,e,n,i){var r=e.length;if(!t.onBand||n||!r)return;var o,a,s=t.getExtent();if(1===r)e[0].coord=s[0],e[0].onBand=!0,o=e[1]={coord:s[1],tickValue:e[0].tickValue,onBand:!0};else{var l=e[r-1].tickValue-e[0].tickValue,c=(e[r-1].coord-e[0].coord)/l;Ui(e,function(t){t.coord-=c/2,t.onBand=!0});var u=t.scale.getExtent();a=1+u[1]-e[r-1].tickValue,o={coord:e[r-1].coord+c*a,tickValue:u[1]+1,onBand:!0},e.push(o)}var d=s[0]>s[1];h(e[0].coord,s[0])&&(i?e[0].coord=s[0]:e.shift());i&&h(s[0],e[0].coord)&&e.unshift({coord:s[0],onBand:!0});h(s[1],o.coord)&&(i?o.coord=s[1]:e.pop());i&&h(o.coord,s[1])&&e.push({coord:s[1],onBand:!0});function h(t,e){return t=Gl(t),e=Gl(e),d?t>e:t0&&t<100||(t=5),Gi(this.scale.getMinorTicks(t),function(t){return Gi(t,function(t){return{coord:this.dataToCoord(t),tickValue:t}},this)},this)},t.prototype.getViewLabels=function(t){return YS(this,t=t||GS(US)).labels},t.prototype.getLabelModel=function(){return this.model.getModel("axisLabel")},t.prototype.getTickModel=function(){return this.model.getModel("axisTick")},t.prototype.getBandWidth=function(){var t=this._extent,e=this.scale.getExtent(),n=e[1]-e[0]+(this.onBand?1:0);0===n&&(n=1);var i=Math.abs(t[1]-t[0]);return Math.abs(i)/n},t.prototype.calculateCategoryInterval=function(t){return function(t,e){var n=e.kind,i=function(t){var e=t.getLabelModel();return{axisRotate:t.getRotate?t.getRotate():t.isHorizontal&&!t.isHorizontal()?90:0,labelRotate:e.get("rotate")||0,font:e.getFont()}}(t),r=PS(t),o=(i.axisRotate-i.labelRotate)/180*Math.PI,a=t.scale,s=a.getExtent(),l=a.count();if(s[1]-s[0]<1)return 0;var c=1;l>40&&(c=Math.max(1,Math.floor(l/40)));for(var u=s[0],d=t.dataToCoord(u+1)-t.dataToCoord(u),h=Math.abs(d*Math.cos(o)),p=Math.abs(d*Math.sin(o)),f=0,g=0;u<=s[1];u+=c){var m,v,y=vl(r({value:u}),i.font,"center","top");m=1.3*y.width,v=1.3*y.height,f=Math.max(f,m,7),g=Math.max(g,v,7)}var _=f/h,b=g/p;isNaN(_)&&(_=1/0),isNaN(b)&&(b=1/0);var x=Math.max(0,Math.floor(Math.min(_,b)));if(n===qS)return e.out.noPxChangeTryDetermine.push(Ki(iC,null,t,x,l)),x;var w=rC(t,x,l);return null!=w?w:x}(this,t=t||GS(US))},t}();function cC(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}var uC=["label","labelLine","layoutOption","priority","defaultAttr","marginForce","minMarginForce","marginDefault","suggestIgnore"];function dC(t,e,n){n=n||3,e?t.dirty|=n:t.dirty&=~n}function hC(t,e){return e=e||3,null==t.dirty||!!(t.dirty&e)}function pC(t){if(t)return hC(t)&&function(t,e,n){var i=e.getComputedTransform();t.transform=Rf(t.transform,i);var r=t.localRect=Nf(t.localRect,e.getBoundingRect()),o=e.style,a=o.margin,s=n&&n.marginForce,l=n&&n.minMarginForce,c=n&&n.marginDefault,u=o.__marginType;null==u&&c&&(a=c,u=Jf.textMargin);for(var d=0;d<4;d++)fC[d]=u===Jf.minMargin&&l&&null!=l[d]?l[d]:s&&null!=s[d]?s[d]:a?a[d]:0;u===Jf.textMargin&&Mf(r,fC,!1,!1);var h=t.rect=Nf(t.rect,r);i&&h.applyTransform(i);u===Jf.minMargin&&Mf(h,fC,!1,!1);t.axisAligned=Lf(i),(t.label=t.label||{}).ignore=e.ignore,dC(t,!1),dC(t,!0,2)}(t,t.label,t),t}var fC=[0,0,0,0];function gC(t,e){for(var n=0;n-1&&(s.style.stroke=s.style.fill,s.style.fill=Im.color.neutral00,s.style.lineWidth=2),e},e.type="series.line",e.dependencies=["grid","polar"],e.defaultOption={z:3,coordinateSystem:"cartesian2d",legendHoverLink:!0,clip:!0,label:{position:"top"},endLabel:{show:!1,valueAnimation:!0,distance:8},lineStyle:{width:2,type:"solid"},emphasis:{scale:!0},step:!1,smooth:!1,smoothMonotone:null,symbol:"emptyCircle",symbolSize:6,symbolRotate:null,showSymbol:!0,showAllSymbol:"auto",connectNulls:!1,sampling:"none",animationEasing:"linear",progressive:0,hoverLayerThreshold:1/0,universalTransition:{divideShape:"clone"},triggerLineEvent:!1},e}(r_);function _C(t,e){var n=t.mapDimensionsAll("defaultedLabel"),i=n.length;if(1===i){var r=ly(t,e,n[0]);return null!=r?r+"":null}if(i){for(var o=[],a=0;a0?+h:1;M.scaleX=this._sizeX*T,M.scaleY=this._sizeY*T,this.setSymbolScale(1),Eh(this,l,c,u)},e.prototype.setSymbolScale=function(t){this.scaleX=this.scaleY=t},e.prototype.fadeOut=function(t,e,n){var i=this.childAt(0),r=Ud(this).dataIndex,o=n&&n.animation;if(this.silent=i.silent=!0,n&&n.fadeLabel){var a=i.getTextContent();a&&af(a,{style:{opacity:0}},e,{dataIndex:r,removeOpt:o,cb:function(){i.removeTextContent()}})}else i.removeTextContent();af(i,{style:{opacity:0},scaleX:0,scaleY:0},e,{dataIndex:r,cb:t,removeOpt:o})},e.getSymbolSize=function(t,e){return Ji(n=t.getItemVisual(e,"symbolSize"))||(n=[+n,+n]),[n[0]||0,n[1]||0];var n},e.getSymbolZ2=function(t,e){return t.getItemVisual(e,"z2")},e}(Nl);function xC(t,e){this.parent.drift(t,e)}function wC(t,e,n,i){return e&&!isNaN(e[0])&&!isNaN(e[1])&&!(i.isIgnore&&i.isIgnore(n))&&!(i.clipShape&&!i.clipShape.contain(e[0],e[1]))&&"none"!==t.getItemVisual(n,"symbol")}function SC(t){return null==t||rr(t)||(t={isIgnore:t}),t||{}}function CC(t){var e=t.hostModel,n=e.getModel("emphasis");return{emphasisItemStyle:n.getModel("itemStyle").getItemStyle(),blurItemStyle:e.getModel(["blur","itemStyle"]).getItemStyle(),selectItemStyle:e.getModel(["select","itemStyle"]).getItemStyle(),focus:n.get("focus"),blurScope:n.get("blurScope"),emphasisDisabled:n.get("disabled"),hoverScale:n.get("scale"),labelStatesModels:Wf(e),cursorStyle:e.get("cursor")}}var kC=function(){function t(t){this.group=new Nl,this._SymbolCtor=t||bC}return t.prototype.updateData=function(t,e){this._progressiveEls=null,e=SC(e);var n=this.group,i=t.hostModel,r=this._data,o=this._SymbolCtor,a=e.disableAnimation,s=CC(t),l={disableAnimation:a},c=e.getSymbolPoint||function(e){return t.getItemLayout(e)};r||n.removeAll(),t.diff(r).add(function(i){var r=c(i);if(wC(t,r,i,e)){var a=new o(t,i,s,l);a.setPosition(r),t.setItemGraphicEl(i,a),n.add(a)}}).update(function(u,d){var h=r.getItemGraphicEl(d),p=c(u);if(wC(t,p,u,e)){var f=t.getItemVisual(u,"symbol")||"circle",g=h&&h.getSymbolType&&h.getSymbolType();if(!h||g&&g!==f)n.remove(h),(h=new o(t,u,s,l)).setPosition(p);else{h.updateData(t,u,s,l);var m={x:p[0],y:p[1]};a?h.attr(m):nf(h,m,i)}n.add(h),t.setItemGraphicEl(u,h)}else n.remove(h)}).remove(function(t){var e=r.getItemGraphicEl(t);e&&e.fadeOut(function(){n.remove(e)},i)}).execute(),this._getSymbolPoint=c,this._data=t},t.prototype.updateLayout=function(){var t=this,e=this._data;e&&e.eachItemGraphicEl(function(e,n){var i=t._getSymbolPoint(n);e.setPosition(i),e.markRedraw()})},t.prototype.incrementalPrepareUpdate=function(t){this._seriesScope=CC(t),this._data=null,this.group.removeAll()},t.prototype.incrementalUpdate=function(t,e,n){function i(t){t.isGroup||(t.incremental=!0,t.ensureState("emphasis").hoverLayer=!0)}this._progressiveEls=[],n=SC(n);for(var r=t.start;r0?n=i[0]:i[1]<0&&(n=i[1]);return n}(r,n),a=i.dim,s=r.dim,l=e.mapDimension(s),c=e.mapDimension(a),u="x"===s||"radius"===s?1:0,d=Gi(t.dimensions,function(t){return e.mapDimension(t)}),h=!1,p=e.getCalculationInfo("stackResultDimension");return Bw(e,d[0])&&(h=!0,d[0]=p),Bw(e,d[1])&&(h=!0,d[1]=p),{dataDimsForPoint:d,valueStart:o,valueAxisDim:s,baseAxisDim:a,stacked:!!h,valueDim:l,baseDim:c,baseDataOffset:u,stackedOverDimension:e.getCalculationInfo("stackedOverDimension")}}function TC(t,e,n,i){var r=NaN;t.stacked&&(r=n.get(n.getCalculationInfo("stackedOverDimension"),i)),isNaN(r)&&(r=t.valueStart);var o=t.baseDataOffset,a=[];return a[o]=n.get(t.baseDim,i),a[1-o]=r,e.dataToPoint(a)}var AC=Math.min,IC=Math.max;function DC(t,e){return isNaN(t)||isNaN(e)}function PC(t,e,n,i,r,o,a,s,l){for(var c,u,d,h,p,f,g=n,m=0;m=r||g<0)break;if(DC(v,y)){if(l){g+=o;continue}break}if(g===n)t[o>0?"moveTo":"lineTo"](v,y),d=v,h=y;else{var _=v-c,b=y-u;if(_*_+b*b<.5){g+=o;continue}if(a>0){for(var x=g+o,w=e[2*x],S=e[2*x+1];w===v&&S===y&&m=i||DC(w,S))p=v,f=y;else{M=w-c,T=S-u;var D=v-c,P=w-v,L=y-u,E=S-y,N=void 0,R=void 0;if("x"===s){var O=M>0?1:-1;p=v-O*(N=Math.abs(D))*a,f=y,A=v+O*(R=Math.abs(P))*a,I=y}else if("y"===s){var z=T>0?1:-1;p=v,f=y-z*(N=Math.abs(L))*a,A=v,I=y+z*(R=Math.abs(E))*a}else N=Math.sqrt(D*D+L*L),p=v-M*a*(1-(k=(R=Math.sqrt(P*P+E*E))/(R+N))),f=y-T*a*(1-k),I=y+T*a*k,A=AC(A=v+M*a*k,IC(w,v)),I=AC(I,IC(S,y)),A=IC(A,AC(w,v)),f=y-(T=(I=IC(I,AC(S,y)))-y)*N/R,p=AC(p=v-(M=A-v)*N/R,IC(c,v)),f=AC(f,IC(u,y)),A=v+(M=v-(p=IC(p,AC(c,v))))*R/N,I=y+(T=y-(f=IC(f,AC(u,y))))*R/N}t.bezierCurveTo(d,h,p,f,v,y),d=A,h=I}else t.lineTo(v,y)}c=v,u=y,g+=o}return m}var LC=function(){this.smooth=0,this.smoothConstraint=!0},EC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polyline",n}return S(e,t),e.prototype.getDefaultStyle=function(){return{stroke:Im.color.neutral99,fill:null}},e.prototype.getDefaultShape=function(){return new LC},e.prototype.buildPath=function(t,e){var n=e.points,i=0,r=n.length/2;if(e.connectNulls){for(;r>0&&DC(n[2*r-2],n[2*r-1]);r--);for(;i=0){var m=a?(u-i)*g+i:(c-n)*g+n;return a?[t,m]:[m,t]}n=c,i=u;break;case o.C:c=r[l++],u=r[l++],d=r[l++],h=r[l++],p=r[l++],f=r[l++];var v=a?ya(n,c,d,p,t,s):ya(i,u,h,f,t,s);if(v>0)for(var y=0;y=0){m=a?ma(i,u,h,f,_):ma(n,c,d,p,_);return a?[t,m]:[m,t]}}n=p,i=f}}},e}(vd),NC=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e}(LC),RC=function(t){function e(e){var n=t.call(this,e)||this;return n.type="ec-polygon",n}return S(e,t),e.prototype.getDefaultShape=function(){return new NC},e.prototype.buildPath=function(t,e){var n=e.points,i=e.stackedOnPoints,r=0,o=n.length/2,a=e.smoothMonotone;if(e.connectNulls){for(;o>0&&DC(n[2*o-2],n[2*o-1]);o--);for(;r=0&&t<=1){var i=t*(e.length-1),r=Math.floor(i),o=Math.ceil(i),a=qa(e[r]),s=qa(e[o]),l=i-r,c=Ya([Na(Ba(a[0],s[0],l)),Na(Ba(a[1],s[1],l)),Na(Ba(a[2],s[2],l)),Ra(Ba(a[3],s[3],l))],"rgba");return n?{color:c,leftIndex:r,rightIndex:o,value:i}:c}}((n-i)/(e.coord-i),[t.color,e.color])}}for(var s=0;se){i?r.push(a(i,l,e)):n&&r.push(a(n,l,0),a(n,l,e));break}n&&(r.push(a(n,l,0)),n=null),r.push(l),i=l}}return r}function VC(t,e,n){var i=t.get("showAllSymbol"),r="auto"===i;if(!i||r){var o=n.getAxesByScale("ordinal")[0];if(o&&(!r||!function(t,e){var n=t.getExtent(),i=Math.abs(n[1]-n[0])/t.scale.count();isNaN(i)&&(i=0);for(var r=e.count(),o=Math.max(1,Math.round(r/5)),a=0;ai)return!1;return!0}(o,e))){var a=e.mapDimension(o.dim),s={};return Ui(o.getViewLabels(),function(t){var e=o.scale.getRawOrdinalNumber(t.tickValue);s[e]=1}),function(t){return!s.hasOwnProperty(e.get(a,t))}}}}function WC(t,e){return isNaN(t)||isNaN(e)}function jC(t,e){return[t[2*e],t[2*e+1]]}function qC(t){if(t.get(["endLabel","show"]))return!0;for(var e=0;e=0;a--){var s=t.getDimensionInfo(i[a].dimension);if("x"===(r=s&&s.coordDim)||"y"===r){o=i[a];break}}if(o){var l=e.getAxis(r),c=Gi(o.stops,function(t){return{coord:l.toGlobalCoord(l.dataToCoord(t.value)),color:t.color}}),u=c.length,d=o.outerColors.slice();u&&c[0].coord>c[u-1].coord&&(c.reverse(),d.reverse());var h=FC(c,"x"===r?n.getWidth():n.getHeight()),p=h.length;if(!p&&u)return c[0].coord<0?d[1]?d[1]:c[u-1].color:d[0]?d[0]:c[0].color;var f=h[0].coord-10,g=h[p-1].coord+10,m=g-f;if(m<.001)return"transparent";Ui(h,function(t){t.offset=(t.coord-f)/m}),h.push({offset:p?h[p-1].offset:.5,color:d[1]||"transparent"}),h.unshift({offset:p?h[0].offset:.5,color:d[0]||"transparent"});var v=new Fp(0,0,0,0,h,!0);return v[r]=f,v[r+"2"]=g,v}}}(o,i,n)||o.getVisual("style")[o.getVisual("drawType")];if(h&&u.type===i.type&&k===this._step){m&&!p?p=this._newPolygon(l,_):p&&!m&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,am(M));var T=f.getClipPath();if(T)rf(T,{shape:UC(this,i,!1,t).shape},t);else f.setClipPath(UC(this,i,!0,t));b&&d.updateData(o,{isIgnore:w,clipShape:C,disableAnimation:!0,getSymbolPoint:function(t){return[l[2*t],l[2*t+1]]}}),OC(this._stackedOnPoints,_)&&OC(this._points,l)||(g?this._doUpdateAnimation(o,_,i,n,k,v,x):(k&&(_&&(_=$C(_,l,i,k,x)),l=$C(l,null,i,k,x)),h.setShape({points:l}),p&&p.setShape({points:l,stackedOnPoints:_})))}else b&&d.updateData(o,{isIgnore:w,clipShape:C,disableAnimation:!0,getSymbolPoint:function(t){return[l[2*t],l[2*t+1]]}}),g&&this._initSymbolLabelAnimation(o,i,C),k&&(_&&(_=$C(_,l,i,k,x)),l=$C(l,null,i,k,x)),h=this._newPolyline(l),m?p=this._newPolygon(l,_):p&&(f.remove(p),p=this._polygon=null),c||this._initOrUpdateEndLabel(t,i,am(M)),f.setClipPath(UC(this,i,!0,t));var A=t.getModel("emphasis"),I=A.get("focus"),D=A.get("blurScope"),P=A.get("disabled");(h.useStyle(Vi(a.getLineStyle(),{fill:"none",stroke:M,lineJoin:"bevel"})),Oh(h,t,"lineStyle"),h.style.lineWidth>0&&"bolder"===t.get(["emphasis","lineStyle","width"]))&&(h.getState("emphasis").style.lineWidth=+h.style.lineWidth+1);Ud(h).seriesIndex=t.seriesIndex,Eh(h,I,D,P);var L=BC(t.get("smooth")),E=t.get("smoothMonotone");if(h.setShape({smooth:L,smoothMonotone:E,connectNulls:x}),p){var N=o.getCalculationInfo("stackedOnSeries"),R=0;p.useStyle(Vi(s.getAreaStyle(),{fill:M,opacity:.7,lineJoin:"bevel",decal:o.getVisual("style").decal})),N&&(R=BC(N.get("smooth"))),p.setShape({smooth:L,stackedOnSmooth:R,smoothMonotone:E,connectNulls:x}),Oh(p,t,"areaStyle"),Ud(p).seriesIndex=t.seriesIndex,Eh(p,I,D,P)}var O=this._changePolyState;o.eachItemGraphicEl(function(t){t&&(t.onHoverStateChange=O)}),this._polyline.onHoverStateChange=O,this._data=o,this._coordSys=i,this._stackedOnPoints=_,this._points=l,this._step=k,this._valueOrigin=v,t.get("triggerLineEvent")&&(this.packEventData(t,h),p&&this.packEventData(t,p))},e.prototype.packEventData=function(t,e){Ud(e).eventData={componentType:"series",componentSubType:"line",componentIndex:t.componentIndex,seriesIndex:t.seriesIndex,seriesName:t.name,seriesType:"line"}},e.prototype.highlight=function(t,e,n,i){var r=t.getData(),o=wc(r,i);if(this._changePolyState("emphasis"),!(o instanceof Array)&&null!=o&&o>=0){var a=r.getLayout("points"),s=r.getItemGraphicEl(o);if(!s){var l=a[2*o],c=a[2*o+1];if(isNaN(l)||isNaN(c))return;if(this._clipShapeForSymbol&&!this._clipShapeForSymbol.contain(l,c))return;var u=t.get("zlevel")||0,d=t.get("z")||0;(s=new bC(r,o)).x=l,s.y=c,s.setZ(u,d);var h=s.getSymbolPath().getTextContent();h&&(h.zlevel=u,h.z=d,h.z2=this._polyline.z2+1),s.__temp=!0,r.setItemGraphicEl(o,s),s.stopSymbolAnimation(!0),this.group.add(s)}s.highlight()}else m_.prototype.highlight.call(this,t,e,n,i)},e.prototype.downplay=function(t,e,n,i){var r=t.getData(),o=wc(r,i);if(this._changePolyState("normal"),null!=o&&o>=0){var a=r.getItemGraphicEl(o);a&&(a.__temp?(r.setItemGraphicEl(o,null),this.group.remove(a)):a.downplay())}else m_.prototype.downplay.call(this,t,e,n,i)},e.prototype._changePolyState=function(t){var e=this._polygon;gh(this._polyline,t),e&&gh(e,t)},e.prototype._newPolyline=function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new EC({shape:{points:t},segmentIgnoreThreshold:2,z2:10}),this._lineGroup.add(e),this._polyline=e,e},e.prototype._newPolygon=function(t,e){var n=this._polygon;return n&&this._lineGroup.remove(n),n=new RC({shape:{points:t,stackedOnPoints:e},segmentIgnoreThreshold:2}),this._lineGroup.add(n),this._polygon=n,n},e.prototype._initSymbolLabelAnimation=function(t,e,n){var i,r,o=e.getBaseAxis(),a=o.inverse;"cartesian2d"===e.type?(i=o.isHorizontal(),r=!1):"polar"===e.type&&(i="angle"===o.dim,r=!0);var s=t.hostModel,l=s.get("animationDuration");tr(l)&&(l=l(null));var c=s.get("animationDelay")||0,u=tr(c)?c(null):c;t.eachItemGraphicEl(function(t,o){var s=t;if(s){var d=[t.x,t.y],h=void 0,p=void 0,f=void 0;if(n)if(r){var g=n,m=e.pointToCoord(d);i?(h=g.startAngle,p=g.endAngle,f=-m[1]/180*Math.PI):(h=g.r0,p=g.r,f=m[0])}else{var v=n;i?(h=v.x,p=v.x+v.width,f=t.x):(h=v.y+v.height,p=v.y,f=t.y)}var y=p===h?0:(f-h)/(p-h);a&&(y=1-y);var _=tr(c)?c(o):l*y+u,b=s.getSymbolPath(),x=b.getTextContent();s.attr({scaleX:0,scaleY:0}),s.animateTo({scaleX:1,scaleY:1},{duration:200,setToFinal:!0,delay:_}),x&&x.animateFrom({style:{opacity:0}},{duration:300,delay:_}),b.disableLabelAnimation=!0}})},e.prototype._initOrUpdateEndLabel=function(t,e,n){var i=t.getModel("endLabel");if(qC(t)){var r=t.getData(),o=this._polyline,a=r.getLayout("points");if(!a)return o.removeTextContent(),void(this._endLabel=null);var s=this._endLabel;s||((s=this._endLabel=new Ed({z2:200})).ignoreClip=!0,o.setTextContent(this._endLabel),o.disableLabelAnimation=!0);var l=function(t){for(var e=t.length/2;e>0&&WC(t[2*e-2],t[2*e-1]);e--);return e-1}(a);l>=0&&(Vf(o,Wf(t,"endLabel"),{inheritColor:n,labelFetcher:t,labelDataIndex:l,defaultText:function(t,e,n){return null!=n?function(t,e){var n=t.mapDimensionsAll("defaultedLabel");if(!Ji(e))return e+"";for(var i=[],r=0;r=0&&i.push(e[o])}return i.join(" ")}(r,n):_C(r,t)},enableTextSetter:!0},function(t,e){var n=e.getBaseAxis(),i=n.isHorizontal(),r=n.inverse,o=i?r?"right":"left":"center",a=i?"middle":r?"top":"bottom";return{normal:{align:t.get("align")||o,verticalAlign:t.get("verticalAlign")||a}}}(i,e)),o.textConfig.position=null)}else this._endLabel&&(this._polyline.removeTextContent(),this._endLabel=null)},e.prototype._endLabelOnDuring=function(t,e,n,i,r,o,a){var s=this._endLabel,l=this._polyline;if(s){t<1&&null==i.originalX&&(i.originalX=s.x,i.originalY=s.y);var c=n.getLayout("points"),u=n.hostModel,d=u.get("connectNulls"),h=o.get("precision"),p=o.get("distance")||0,f=a.getBaseAxis(),g=f.isHorizontal(),m=f.inverse,v=e.shape,y=m?g?v.x:v.y+v.height:g?v.x+v.width:v.y,_=(g?p:0)*(m?-1:1),b=(g?0:-p)*(m?-1:1),x=g?"x":"y",w=function(t,e,n){for(var i,r,o=t.length/2,a="x"===n?0:1,s=0,l=-1,c=0;c=e||i>=e&&r<=e){l=c;break}s=c,i=r}else i=r;return{range:[s,l],t:(e-i)/(r-i)}}(c,y,x),S=w.range,C=S[1]-S[0],k=void 0;if(C>=1){if(C>1&&!d){var M=jC(c,S[0]);s.attr({x:M[0]+_,y:M[1]+b}),r&&(k=u.getRawValue(S[0]))}else{(M=l.getPointOn(y,x))&&s.attr({x:M[0]+_,y:M[1]+b});var T=u.getRawValue(S[0]),A=u.getRawValue(S[1]);r&&(k=function(t,e,n,i,r){var o=null==e||"auto"===e;if(null==i)return i;if(ir(i))return Gl(f=cc(n||0,i,r),o?Math.max(Xl(n||0),Xl(i)):e);if(er(i))return r<1?n:i;for(var a=[],s=n,l=i,c=Math.max(s?s.length:0,l.length),u=0;u0?S[0]:0;M=jC(c,I);r&&(k=u.getRawValue(I)),s.attr({x:M[0]+_,y:M[1]+b})}if(r){var D=Qf(s);"function"==typeof D.setLabelText&&D.setLabelText(k)}}},e.prototype._doUpdateAnimation=function(t,e,n,i,r,o,a){var s=this._polyline,l=this._polygon,c=t.hostModel,u=function(t,e,n,i,r,o,a){for(var s=function(t,e){var n=[];return e.diff(t).add(function(t){n.push({cmd:"+",idx:t})}).update(function(t,e){n.push({cmd:"=",idx:e,idx1:t})}).remove(function(t){n.push({cmd:"-",idx:t})}).execute(),n}(t,e),l=[],c=[],u=[],d=[],h=[],p=[],f=[],g=MC(r,e,a),m=t.getLayout("points")||[],v=e.getLayout("points")||[],y=0;y3e3||l&&HC(h,f)>3e3)return s.stopAnimation(),s.setShape({points:p}),void(l&&(l.stopAnimation(),l.setShape({points:p,stackedOnPoints:f})));s.shape.__points=u.current,s.shape.points=d;var g={shape:{points:p}};u.current!==d&&(g.shape.__points=u.next),s.stopAnimation(),nf(s,g,c),l&&(l.setShape({points:d,stackedOnPoints:h}),l.stopAnimation(),nf(l,{shape:{stackedOnPoints:f}},c),s.shape.points!==l.shape.points&&(l.shape.points=s.shape.points));for(var m=[],v=u.status,y=0;ye&&(e=t[n]);return isFinite(e)?e:NaN},min:function(t){for(var e=1/0,n=0;ne[1]&&e.reverse(),e},e.prototype.pointToData=function(t,e){return this.coordToData(this.toLocalCoord(t["x"===this.dim?0:1]),e)},e.prototype.setCategorySortInfo=function(t){if("category"!==this.type)return!1;this.model.option.categorySortInfo=t,this.scale.setSortInfo(t)},e}(lC),hk="expandAxisBreak",pk=Math.PI,fk=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],gk=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],mk=Sc(),vk=Sc(),yk=function(){function t(t){this.recordMap={},this.resolveAxisNameOverlap=t}return t.prototype.ensureRecord=function(t){var e=t.axis.dim,n=t.componentIndex,i=this.recordMap,r=i[e]||(i[e]=[]);return r[n]||(r[n]={ready:{}})},t}();var _k=[1,0,0,1,0,0],bk=new Lo(0,0,0,0),xk=function(t,e,n,i,r,o){if(OS(t.nameLocation)){var a=o.stOccupiedRect;a&&wk(function(t,e,n){return t.transform=Rf(t.transform,n),t.localRect=Nf(t.localRect,e),t.rect=Nf(t.rect,e),n&&t.rect.applyTransform(n),t.axisAligned=Lf(n),t.obb=void 0,(t.label=t.label||{}).ignore=!1,t}({},a,o.transGroup.transform),i,r)}else Sk(o.labelInfoList,o.dirVec,i,r)};function wk(t,e,n){var i=new yo;vC(t,e,i,{direction:Math.atan2(n.y,n.x),bidirectional:!1,touchThreshold:.05})&&function(t,e){if(t){t.label.x+=e.x,t.label.y+=e.y,t.label.markRedraw();var n=t.transform;n&&(n[4]+=e.x,n[5]+=e.y);var i=t.rect;i&&(i.x+=e.x,i.y+=e.y);var r=t.obb;r&&r.fromBoundingRect(t.localRect,n)}}(e,i)}function Sk(t,e,n,i){for(var r=yo.dot(i,e)>=0,o=0,a=t.length;o0?"top":"bottom",i="center"):Kl(o-pk)?(r=n>0?"bottom":"top",i="center"):(r="middle",i=o>0&&o0?"right":"left":n>0?"left":"right"),{rotation:o,textAlign:i,textVerticalAlign:r}},t.makeAxisEventDataBase=function(t){var e={componentType:t.mainType,componentIndex:t.componentIndex};return e[t.mainType+"Index"]=t.componentIndex,e},t.isLabelSilent=function(t){var e=t.get("tooltip");return t.get("silent")||!(t.get("triggerEvent")||e&&e.show)},t}(),kk=["axisLine","axisTickLabelEstimate","axisTickLabelDetermine","axisName"],Mk={axisLine:function(t,e,n,i,r,o,a){var s=i.get(["axisLine","show"]);if("auto"===s&&(s=!0,null!=t.raw.axisLineAutoShow&&(s=!!t.raw.axisLineAutoShow)),s){var l=i.axis.getExtent(),c=o.transform,u=[l[0],0],d=[l[1],0],h=u[0]>d[0];c&&(zr(u,u,c),zr(d,d,c));var p=Fi({lineCap:"round"},i.getModel(["axisLine","lineStyle"]).getLineStyle()),f={strokeContainThreshold:t.raw.strokeContainThreshold||5,silent:!0,z2:1,style:p};if(i.get(["axisLine","breakLine"])&&i.axis.scale.hasBreaks())null.buildAxisBreakLine(i,r,o,f);else{var g=new Lp(Fi({shape:{x1:u[0],y1:u[1],x2:d[0],y2:d[1]}},f));yf(g.shape,g.style.lineWidth),g.anid="line",r.add(g)}var m=i.get(["axisLine","symbol"]);if(null!=m){var v=i.get(["axisLine","symbolSize"]);er(m)&&(m=[m,m]),(er(v)||ir(v))&&(v=[v,v]);var y=Cb(i.get(["axisLine","symbolOffset"])||0,v),_=v[0],b=v[1];Ui([{rotate:t.rotation+Math.PI/2,offset:y[0],r:0},{rotate:t.rotation-Math.PI/2,offset:y[1],r:Math.sqrt((u[0]-d[0])*(u[0]-d[0])+(u[1]-d[1])*(u[1]-d[1]))}],function(e,n){if("none"!==m[n]&&null!=m[n]){var i=Sb(m[n],-_/2,-b/2,_,b,p.stroke,!0),o=e.r+e.offset,a=h?d:u;i.attr({rotation:e.rotate,x:a[0]+o*Math.cos(t.rotation),y:a[1]-o*Math.sin(t.rotation),silent:!0,z2:11}),r.add(i)}})}}},axisTickLabelEstimate:function(t,e,n,i,r,o,a,s){Dk(e,r,s)&&Tk(t,e,n,i,r,o,a,qS)},axisTickLabelDetermine:function(t,e,n,i,r,o,a,s){Dk(e,r,s)&&Tk(t,e,n,i,r,o,a,US);var l=function(t,e,n,i){var r=i.axis,o=i.getModel("axisTick"),a=o.get("show");"auto"===a&&(a=!0,null!=t.raw.axisTickAutoShow&&(a=!!t.raw.axisTickAutoShow));if(!a||r.scale.isBlank())return[];for(var s=o.getModel("lineStyle"),l=t.tickDirection*o.get("length"),c=Ik(r.getTicksCoords(),n.transform,l,Vi(s.getLineStyle(),{stroke:i.get(["axisLine","lineStyle","color"])}),"ticks"),u=0;ui[1],l="start"===e&&!s||"start"!==e&&s;Kl(a-pk/2)?(o=l?"bottom":"top",r="center"):Kl(a-1.5*pk)?(o=l?"top":"bottom",r="center"):(o="middle",r=a<1.5*pk&&a>pk/2?l?"left":"right":l?"right":"left");return{rotation:a,textAlign:r,textVerticalAlign:o}}(t.rotation,u,x||0,f),null!=(b=t.raw.axisNameAvailableWidth)&&(b=Math.abs(b/Math.sin(_.rotation)),!isFinite(b)&&(b=null)));var w=h.getFont(),S=i.get("nameTruncate",!0)||{},C=S.ellipsis,k=ur(t.raw.nameTruncateMaxWidth,S.maxWidth,b),M=s.nameMarginLevel||0,T=new Ed({x:m.x,y:m.y,rotation:_.rotation,silent:Ck.isLabelSilent(i),style:jf(h,{text:c,font:w,overflow:"truncate",width:k,ellipsis:C,fill:h.getTextColor()||i.get(["axisLine","lineStyle","color"]),align:h.get("align")||_.textAlign,verticalAlign:h.get("verticalAlign")||_.textVerticalAlign}),z2:1});if(If({el:T,componentModel:i,itemName:c}),T.__fullText=c,T.anid="name",i.get("triggerEvent")){var A=Ck.makeAxisEventDataBase(i);A.targetType="axisName",A.name=c,Ud(T).eventData=A}o.add(T),T.updateTransform(),e.nameEl=T;var I=l.nameLayout=pC({label:T,priority:T.z2,defaultAttr:{ignore:T.ignore},marginDefault:OS(u)?fk[M]:gk[M]});if(l.nameLocation=u,r.add(T),T.decomposeTransform(),t.shouldNameMoveOverlap&&I){var D=n.ensureRecord(i);n.resolveAxisNameOverlap(t,n,i,I,v,D)}}}};function Tk(t,e,n,i,r,o,a,s){Pk(e)||function(t,e,n,i,r,o){var a=r.axis,s=ur(t.raw.axisLabelShow,r.get(["axisLabel","show"])),l=new Nl;n.add(l);var c=GS(i);if(!s||a.scale.isBlank())return void Lk(e,[],l,c);var u=r.getModel("axisLabel"),d=a.getViewLabels(c),h=(ur(t.raw.labelRotate,u.get("rotate"))||0)*pk/180,p=Ck.innerTextLayout(t.rotation,h,t.labelDirection),f=r.getCategories&&r.getCategories(!0),g=[],m=r.get("triggerEvent"),v=1/0,y=-1/0;Ui(d,function(t,e){var n,i="ordinal"===a.scale.type?a.scale.getRawOrdinalNumber(t.tickValue):t.tickValue,s=t.formattedLabel,c=t.rawLabel,h=u;if(f&&f[i]){var _=f[i];rr(_)&&_.textStyle&&(h=new ug(_.textStyle,u,r.ecModel))}var b=h.getTextColor()||r.get(["axisLine","lineStyle","color"]),x=h.getShallow("align",!0)||p.textAlign,w=dr(h.getShallow("alignMinLabel",!0),x),S=dr(h.getShallow("alignMaxLabel",!0),x),C=h.getShallow("verticalAlign",!0)||h.getShallow("baseline",!0)||p.textVerticalAlign,k=dr(h.getShallow("verticalAlignMinLabel",!0),C),M=dr(h.getShallow("verticalAlignMaxLabel",!0),C),T=10+((null===(n=t.time)||void 0===n?void 0:n.level)||0);v=Math.min(v,T),y=Math.max(y,T);var A=new Ed({x:0,y:0,rotation:0,silent:Ck.isLabelSilent(r),z2:T,style:jf(h,{text:s,align:0===e?w:e===d.length-1?S:x,verticalAlign:0===e?k:e===d.length-1?M:C,fill:tr(b)?b("category"===a.type?c:"value"===a.type?i+"":i,e):b})});A.anid="label_"+i;var I=mk(A);if(I.break=t.break,I.tickValue=i,I.layoutRotation=p.rotation,If({el:A,componentModel:r,itemName:s,formatterParamsExtra:{isTruncated:function(){return A.isTruncated},value:c,tickIndex:e}}),m){var D=Ck.makeAxisEventDataBase(r);D.targetType="axisLabel",D.value=c,D.tickIndex=e,t.break&&(D.break={start:t.break.parsedBreak.vmin,end:t.break.parsedBreak.vmax}),"category"===a.type&&(D.dataIndex=i),Ud(A).eventData=D,t.break&&function(t,e,n,i){n.on("click",function(n){var r={type:hk,breaks:[{start:i.parsedBreak.breakOption.start,end:i.parsedBreak.breakOption.end}]};r[t.axis.dim+"AxisIndex"]=t.componentIndex,e.dispatchAction(r)})}(r,o,A,t.break)}g.push(A),l.add(A)});var _=Gi(g,function(t){return{label:t,priority:mk(t).break?t.z2+(y-v+1):t.z2,defaultAttr:{ignore:t.ignore}}});Lk(e,_,l,c)}(t,e,r,s,i,a);var l=e.labelLayoutList;!function(t,e,n,i){var r=e.get(["axisLabel","margin"]);Ui(n,function(n,o){var a=pC(n);if(a){var s=a.label,l=mk(s);a.suggestIgnore=s.ignore,s.ignore=!1,ul(Ek,Nk),Ek.x=e.axis.dataToCoord(l.tickValue),Ek.y=t.labelOffset+t.labelDirection*r,Ek.rotation=l.layoutRotation,i.add(Ek),Ek.updateTransform(),i.remove(Ek),Ek.decomposeTransform(),ul(s,Ek),s.markRedraw(),dC(a,!0),pC(a)}})}(t,i,l,o),t.rotation;var c=t.optionHideOverlap;!function(t,e,n){if(NS(t.axis))return;function i(t,i,r){var o=pC(e[i]),a=pC(e[r]);if(o&&a)if(!1===t||o.suggestIgnore)Ak(o.label);else if(a.suggestIgnore)Ak(a.label);else{var s=.1;if(!n){var l=[0,0,0,0];o=gC({marginForce:l},o),a=gC({marginForce:l},a)}vC(o,a,null,{touchThreshold:s})&&Ak(t?a.label:o.label)}}var r=t.get(["axisLabel","showMinLabel"]),o=t.get(["axisLabel","showMaxLabel"]),a=e.length;i(r,0,1),i(o,a-1,a-2)}(i,l,c),c&&function(t){var e=[];function n(t){if(!t.ignore){var e=t.ensureState("emphasis");null==e.ignore&&(e.ignore=!1)}t.ignore=!0}t.sort(function(t,e){return(e.suggestIgnore?1:0)-(t.suggestIgnore?1:0)||e.priority-t.priority});for(var i=0;i.1?"x":"y",u=a.transGroup[c];if(s.sort(function(t,e){return Math.abs(t.label[c]-u)-Math.abs(e.label[c]-u)}),l&&r){var d=o.getExtent(),h=Math.min(d[0],d[1]),p=Math.max(d[0],d[1])-h;r.union(new Lo(h,0,p,1))}a.stOccupiedRect=r,a.labelInfoList=s}(t,n,i,l)}function Ak(t){t&&(t.ignore=!0)}function Ik(t,e,n,i,r){for(var o=[],a=[],s=[],l=0;l=0;o--){var a=t[+n[o]],s=a.model,l=a.scale;Fw(l)&&s.get("alignTicks")&&null==s.get("interval")?r.push(a):(DS(l,s),Fw(l)&&(e=a))}r.length&&(e||DS((e=r.pop()).scale,e.model),Ui(r,function(t){!function(t,e,n){var i=iS.prototype,r=i.getTicks.call(n),o=i.getTicks.call(n,{expandToNicedExtent:!0}),a=r.length-1,s=i.getInterval.call(n),l=IS(t,e),c=l.extent,u=l.fixMin,d=l.fixMax;"log"===t.type&&(c=Zw(t.base,c,!0)),t.setBreaksFromOption(HS(e)),t.setExtent(c[0],c[1]),t.calcNiceExtent({splitNumber:a,fixMin:u,fixMax:d});var h=i.getExtent.call(t);u&&(c[0]=h[0]),d&&(c[1]=h[1]);var p=i.getInterval.call(t),f=c[0],g=c[1];if(u&&d)p=(g-f)/a;else if(u)for(g=c[0]+p*a;gc[0]&&isFinite(f)&&isFinite(c[0]);)p=Ww(p),f=c[1]-p*a;else{t.getTicks().length-1>a&&(p=Ww(p));var m=p*a;(f=Gl((g=Math.ceil(c[1]/p)*p)-m))<0&&c[0]>=0?(f=0,g=Gl(m)):g>0&&c[1]<=0&&(g=0,f=-Gl(m))}var v=(r[0].value-o[0].value)/s,y=(r[a].value-o[a].value)/s;i.setExtent.call(t,f+p*v,g+p*y),i.setInterval.call(t,p),(v||y)&&i.setNiceExtent.call(t,f+p,g-p)}(t.scale,t.model,e.scale)}))}}this._updateScale(t,this.model),i(n.x),i(n.y);var r={};Ui(n.x,function(t){Fk(n,"y",t,r)}),Ui(n.y,function(t){Fk(n,"x",t,r)}),this.resize(this.model,e)},t.prototype.resize=function(t,e,n){var i=Sm(t,e),r=this._rect=xm(t.getBoxLayoutParams(),i.refContainer),o=this._axesMap,a=this._coordsList,s=t.get("containLabel");if(Wk(o,r),!n){var l=function(t,e,n,i,r){var o=new yk(Gk);return Ui(n,function(n){return Ui(n,function(n){if(zS(n.model)){var a=!i;n.axisBuilder=function(t,e,n,i,r,o){for(var a=Ok(t,n),s=!1,l=!1,c=0;c0&&i>0||n<0&&i<0)}(t)}function Wk(t,e){Ui(t.x,function(t){return jk(t,e.x,e.width)}),Ui(t.y,function(t){return jk(t,e.y,e.height)})}function jk(t,e,n){var i=[0,n],r=t.inverse?1:0;t.setExtent(i[r],i[1-r]),function(t,e){var n=t.getExtent(),i=n[0]+n[1];t.toGlobalCoord="x"===t.dim?function(t){return t+e}:function(t){return i-t+e},t.toLocalCoord="x"===t.dim?function(t){return t-e}:function(t){return i-t+e}}(t,e)}function qk(t,e,n,i,r,o,a){Uk(i,r,qS,e,!1,a);var s=[0,0,0,0];c(0),c(1),u(i,0,NaN),u(i,1,NaN);var l=null==function(t,e,n){if(t&&e)for(var i=0,r=t.length;i0});return Mf(i,s,!0,!0,n),Wk(r,i),l;function c(t){Ui(r[cf[t]],function(e){if(zS(e.model)){var n=o.ensureRecord(e.model),i=n.labelInfoList;if(i)for(var r=0;r0&&!cr(e)&&e>1e-4&&(t/=e),t}}function Uk(t,e,n,i,r,o){var a=n===US;Ui(e,function(e){return Ui(e,function(e){zS(e.model)&&(!function(t,e,n){var i=Ok(e,n);t.updateCfg(i)}(e.axisBuilder,t,e.model),e.axisBuilder.build(a?{axisTickLabelDetermine:!0}:{axisTickLabelEstimate:!0},{noPxChange:r}))})});var s={x:0,y:0};function l(e){s[cf[1-e]]=t[uf[e]]<=.5*o.refContainer[uf[e]]?0:1-e==1?2:1}l(0),l(1),Ui(e,function(t,e){return Ui(t,function(t){zS(t.model)&&(("all"===i||a)&&t.axisBuilder.build({axisName:!0},{nameMarginLevel:s[e]}),a&&t.axisBuilder.build({axisLine:!0}))})})}var Gk=function(t,e,n,i,r,o){var a="x"===n.axis.dim?"y":"x";xk(t,0,0,i,r,o),OS(t.nameLocation)||Ui(e.recordMap[a],function(t){t&&t.labelInfoList&&t.dirVec&&Sk(t.labelInfoList,t.dirVec,i,r)})};function Xk(t,e){var n={axesInfo:{},seriesInvolved:!1,coordSysAxesInfo:{},coordSysMap:{}};return function(t,e,n){var i=e.getComponent("tooltip"),r=e.getComponent("axisPointer"),o=r.get("link",!0)||[],a=[];Ui(n.getCoordinateSystems(),function(n){if(n.axisPointerEnabled){var s=Qk(n.model),l=t.coordSysAxesInfo[s]={};t.coordSysMap[s]=n;var c=n.model.getModel("tooltip",i);if(Ui(n.getAxes(),Qi(p,!1,null)),n.getTooltipAxes&&i&&c.get("show")){var u="axis"===c.get("trigger"),d="cross"===c.get(["axisPointer","type"]),h=n.getTooltipAxes(c.get(["axisPointer","axis"]));(u||d)&&Ui(h.baseAxes,Qi(p,!d||"cross",u)),d&&Ui(h.otherAxes,Qi(p,"cross",!1))}}function p(i,s,u){var d=u.model.getModel("axisPointer",r),h=d.get("show");if(h&&("auto"!==h||i||Kk(d))){null==s&&(s=d.get("triggerTooltip")),d=i?function(t,e,n,i,r,o){var a=e.getModel("axisPointer"),s={};Ui(["type","snap","lineStyle","shadowStyle","label","animation","animationDurationUpdate","animationEasingUpdate","z"],function(t){s[t]=Bi(a.get(t))}),s.snap="category"!==t.type&&!!o,"cross"===a.get("type")&&(s.type="line");var l=s.label||(s.label={});if(null==l.show&&(l.show=!1),"cross"===r){var c=a.get(["label","show"]);if(l.show=null==c||c,!o){var u=s.lineStyle=a.get("crossStyle");u&&Vi(l,u.textStyle)}}return t.model.getModel("axisPointer",new ug(s,n,i))}(u,c,r,e,i,s):d;var p=d.get("snap"),f=d.get("triggerEmphasis"),g=Qk(u.model),m=s||p||"category"===u.type,v=t.axesInfo[g]={key:g,axis:u,coordSys:n,axisPointerModel:d,triggerTooltip:s,triggerEmphasis:f,involveSeries:m,snap:p,useHandle:Kk(d),seriesModels:[],linkGroup:null};l[g]=v,t.seriesInvolved=t.seriesInvolved||m;var y=function(t,e){for(var n=e.model,i=e.dim,r=0;r=0||t===e}function Zk(t){var e=(t.ecModel.getComponent("axisPointer")||{}).coordSysAxesInfo;return e&&e.axesInfo[Qk(t)]}function Kk(t){return!!t.get(["handle","show"])}function Qk(t){return t.type+"||"+t.id}var Jk={},tM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.prototype.render=function(e,n,i,r){this.axisPointerClass&&function(t){var e=Zk(t);if(e){var n=e.axisPointerModel,i=e.axis.scale,r=n.option,o=n.get("status"),a=n.get("value");null!=a&&(a=i.parse(a));var s=Kk(n);null==o&&(r.status=s?"show":"hide");var l=i.getExtent().slice();l[0]>l[1]&&l.reverse(),(null==a||a>l[1])&&(a=l[1]),aa)return!0;if(o){var s=Zk(t).seriesDataCount,l=i.getExtent();return Math.abs(l[0]-l[1])/s>a}return!1}return!0===n},t.prototype.makeElOption=function(t,e,n,i,r){},t.prototype.createPointerEl=function(t,e,n,i){var r=e.pointer;if(r){var o=uM(t).pointerEl=new Bf[r.type](dM(e.pointer));t.add(o)}},t.prototype.createLabelEl=function(t,e,n,i){if(e.label){var r=uM(t).labelEl=new Ed(dM(e.label));t.add(r),mM(r,i)}},t.prototype.updatePointerEl=function(t,e,n){var i=uM(t).pointerEl;i&&e.pointer&&(i.setStyle(e.pointer.style),n(i,{shape:e.pointer.shape}))},t.prototype.updateLabelEl=function(t,e,n,i){var r=uM(t).labelEl;r&&(r.setStyle(e.label.style),n(r,{x:e.label.x,y:e.label.y}),mM(r,i))},t.prototype._renderHandle=function(t){if(!this._dragging&&this.updateHandleTransform){var e,n=this._axisPointerModel,i=this._api.getZr(),r=this._handle,o=n.getModel("handle"),a=n.get("status");if(!o.get("show")||!a||"hide"===a)return r&&i.remove(r),void(this._handle=null);this._handle||(e=!0,r=this._handle=Sf(o.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(t){so(t.event)},onmousedown:hM(this._onHandleDragMove,this,0,0),drift:hM(this._onHandleDragMove,this),ondragend:hM(this._onHandleDragEnd,this)}),i.add(r)),yM(r,n,!1),r.setStyle(o.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var s=o.get("size");Ji(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,M_(this,"_doDispatchAxisPointer",o.get("throttle")||0,"fixRate"),this._moveHandleToValue(t,e)}},t.prototype._moveHandleToValue=function(t,e){fM(this._axisPointerModel,!e&&this._moveAnimation,this._handle,vM(this.getHandleTransform(t,this._axisModel,this._axisPointerModel)))},t.prototype._onHandleDragMove=function(t,e){var n=this._handle;if(n){this._dragging=!0;var i=this.updateHandleTransform(vM(n),[t,e],this._axisModel,this._axisPointerModel);this._payloadInfo=i,n.stopAnimation(),n.attr(vM(i)),uM(n).lastProp=null,this._doDispatchAxisPointer()}},t.prototype._doDispatchAxisPointer=function(){if(this._handle){var t=this._payloadInfo,e=this._axisModel;this._api.dispatchAction({type:"updateAxisPointer",x:t.cursorPoint[0],y:t.cursorPoint[1],tooltipOption:t.tooltipOption,axesInfo:[{axisDim:e.axis.dim,axisIndex:e.componentIndex}]})}},t.prototype._onHandleDragEnd=function(){if(this._dragging=!1,this._handle){var t=this._axisPointerModel.get("value");this._moveHandleToValue(t),this._api.dispatchAction({type:"hideTip"})}},t.prototype.clear=function(t){this._lastValue=null,this._lastStatus=null;var e=t.getZr(),n=this._group,i=this._handle;e&&n&&(this._lastGraphicKey=null,n&&e.remove(n),i&&e.remove(i),this._group=null,this._handle=null,this._payloadInfo=null),T_(this,"_doDispatchAxisPointer")},t.prototype.doClear=function(){},t.prototype.buildLabel=function(t,e,n){return{x:t[n=n||0],y:t[1-n],width:e[n],height:e[1-n]}},t}();function fM(t,e,n,i){gM(uM(n).lastProp,i)||(uM(n).lastProp=i,e?nf(n,i,t):(n.stopAnimation(),n.attr(i)))}function gM(t,e){if(rr(t)&&rr(e)){var n=!0;return Ui(e,function(e,i){n=n&&gM(t[i],e)}),!!n}return t===e}function mM(t,e){t[e.get(["label","show"])?"show":"hide"]()}function vM(t){return{x:t.x||0,y:t.y||0,rotation:t.rotation||0}}function yM(t,e,n){var i=e.get("z"),r=e.get("zlevel");t&&t.traverse(function(t){"group"!==t.type&&(null!=i&&(t.z=i),null!=r&&(t.zlevel=r),t.silent=n)})}function _M(t,e,n,i,r){var o=bM(n.get("value"),e.axis,e.ecModel,n.get("seriesDataIndices"),{precision:n.get(["label","precision"]),formatter:n.get(["label","formatter"])}),a=n.getModel("label"),s=em(a.get("padding")||0),l=a.getFont(),c=vl(o,l),u=r.position,d=c.width+s[1]+s[3],h=c.height+s[0]+s[2],p=r.align;"right"===p&&(u[0]-=d),"center"===p&&(u[0]-=d/2);var f=r.verticalAlign;"bottom"===f&&(u[1]-=h),"middle"===f&&(u[1]-=h/2),function(t,e,n,i){var r=i.getWidth(),o=i.getHeight();t[0]=Math.min(t[0]+e,r)-e,t[1]=Math.min(t[1]+n,o)-n,t[0]=Math.max(t[0],0),t[1]=Math.max(t[1],0)}(u,d,h,i);var g=a.get("backgroundColor");g&&"auto"!==g||(g=e.get(["axisLine","lineStyle","color"])),t.label={x:u[0],y:u[1],style:jf(a,{text:o,font:l,fill:a.getTextColor(),padding:s,backgroundColor:g}),z2:10}}function bM(t,e,n,i,r){t=e.scale.parse(t);var o=e.scale.getLabel({value:t},{precision:r.precision}),a=r.formatter;if(a){var s={value:LS(e,{value:t}),axisDimension:e.dim,axisIndex:e.index,seriesData:[]};Ui(i,function(t){var e=n.getSeriesByIndex(t.seriesIndex),i=t.dataIndexInside,r=e&&e.getDataParams(i);r&&s.seriesData.push(r)}),er(a)?o=a.replace("{value}",o):tr(a)&&(o=a(s))}return o}function xM(t,e,n){var i=[1,0,0,1,0,0];return mo(i,i,n.rotation),go(i,i,n.position),bf([t.dataToCoord(e),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],i)}var wM=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return S(e,t),e.prototype.makeElOption=function(t,e,n,i,r){var o=n.axis,a=o.grid,s=i.get("type"),l=SM(a,o).getOtherAxis(o).getGlobalExtent(),c=o.toGlobalCoord(o.dataToCoord(e,!0));if(s&&"none"!==s){var u=function(t){var e,n=t.get("type"),i=t.getModel(n+"Style");return"line"===n?(e=i.getLineStyle()).fill=null:"shadow"===n&&((e=i.getAreaStyle()).stroke=null),e}(i),d=CM[s](o,c,l);d.style=u,t.graphicKey=d.type,t.pointer=d}!function(t,e,n,i,r,o){var a=Ck.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=r.get(["label","margin"]),_M(e,i,r,o,{position:xM(i.axis,t,n),align:a.textAlign,verticalAlign:a.textVerticalAlign})}(e,t,Ok(a.getRect(),n),n,i,r)},e.prototype.getHandleTransform=function(t,e,n){var i=Ok(e.axis.grid.getRect(),e,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var r=xM(e.axis,t,i);return{x:r[0],y:r[1],rotation:i.rotation+(i.labelDirection<0?Math.PI:0)}},e.prototype.updateHandleTransform=function(t,e,n,i){var r=n.axis,o=r.grid,a=r.getGlobalExtent(!0),s=SM(o,r).getOtherAxis(r).getGlobalExtent(),l="x"===r.dim?0:1,c=[t.x,t.y];c[l]+=e[l],c[l]=Math.min(a[1],c[l]),c[l]=Math.max(a[0],c[l]);var u=(s[1]+s[0])/2,d=[u,u];d[l]=c[l];return{x:c[0],y:c[1],rotation:t.rotation,cursorPoint:d,tooltipOption:[{verticalAlign:"middle"},{align:"center"}][l]}},e}(pM);function SM(t,e){var n={};return n[e.dim+"AxisIndex"]=e.index,t.getCartesian(n)}var CM={line:function(t,e,n){var i,r,o;return{type:"Line",subPixelOptimize:!0,shape:(i=[e,n[0]],r=[e,n[1]],o=kM(t),{x1:i[o=o||0],y1:i[1-o],x2:r[o],y2:r[1-o]})}},shadow:function(t,e,n){var i,r,o,a=Math.max(1,t.getBandWidth()),s=n[1]-n[0];return{type:"Rect",shape:(i=[e-a/2,n[0]],r=[a,s],o=kM(t),{x:i[o=o||0],y:i[1-o],width:r[o],height:r[1-o]})}}};function kM(t){return"x"===t.dim?0:1}var MM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.type="axisPointer",e.defaultOption={show:"auto",z:50,type:"line",snap:!1,triggerTooltip:!0,triggerEmphasis:!0,value:null,status:null,link:[],animation:null,animationDurationUpdate:200,lineStyle:{color:Im.color.border,width:1,type:"dashed"},shadowStyle:{color:Im.color.shadowTint},label:{show:!0,formatter:null,precision:"auto",margin:3,color:Im.color.neutral00,padding:[5,7,5,7],backgroundColor:Im.color.accent60,borderColor:null,borderWidth:0,borderRadius:3},handle:{show:!1,icon:"M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z",size:45,margin:50,color:Im.color.accent40,throttle:40}},e}(Am),TM=Sc(),AM=Ui;function IM(t,e,n){if(!yi.node){var i=e.getZr();TM(i).records||(TM(i).records={}),function(t,e){if(TM(t).initialized)return;function n(n,i){t.on(n,function(n){var r=function(t){var e={showTip:[],hideTip:[]},n=function(i){var r=e[i.type];r?r.push(i):(i.dispatchAction=n,t.dispatchAction(i))};return{dispatchAction:n,pendings:e}}(e);AM(TM(t).records,function(t){t&&i(t,n,r.dispatchAction)}),function(t,e){var n,i=t.showTip.length,r=t.hideTip.length;i?n=t.showTip[i-1]:r&&(n=t.hideTip[r-1]);n&&(n.dispatchAction=null,e.dispatchAction(n))}(r.pendings,e)})}TM(t).initialized=!0,n("click",Qi(PM,"click")),n("mousemove",Qi(PM,"mousemove")),n("globalout",DM)}(i,e),(TM(i).records[t]||(TM(i).records[t]={})).handler=n}}function DM(t,e,n){t.handler("leave",null,n)}function PM(t,e,n,i){e.handler(t,n,i)}function LM(t,e){if(!yi.node){var n=e.getZr();(TM(n).records||{})[t]&&(TM(n).records[t]=null)}}var EM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.prototype.render=function(t,e,n){var i=e.getComponent("tooltip"),r=t.get("triggerOn")||i&&i.get("triggerOn")||"mousemove|click";IM("axisPointer",n,function(t,e,n){"none"!==r&&("leave"===t||r.indexOf(t)>=0)&&n({type:"updateAxisPointer",currTrigger:t,x:e&&e.offsetX,y:e&&e.offsetY})})},e.prototype.remove=function(t,e){LM("axisPointer",e)},e.prototype.dispose=function(t,e){LM("axisPointer",e)},e.type="axisPointer",e}(h_);function NM(t,e){var n,i=[],r=t.seriesIndex;if(null==r||!(n=e.getSeriesByIndex(r)))return{point:[]};var o=n.getData(),a=wc(o,t);if(null==a||a<0||Ji(a))return{point:[]};var s=o.getItemGraphicEl(a),l=n.coordinateSystem;if(n.getTooltipPosition)i=n.getTooltipPosition(a)||[];else if(l&&l.dataToPoint)if(t.isStacked){var c=l.getBaseAxis(),u=l.getOtherAxis(c).dim,d=c.dim,h="x"===u||"radius"===u?1:0,p=o.mapDimension(d),f=[];f[h]=o.get(p,a),f[1-h]=o.get(o.getCalculationInfo("stackResultDimension"),a),i=l.dataToPoint(f)||[]}else i=l.dataToPoint(o.getValues(Gi(l.dimensions,function(t){return o.mapDimension(t)}),a))||[];else if(s){var g=s.getBoundingRect().clone();g.applyTransform(s.transform),i=[g.x+g.width/2,g.y+g.height/2]}return{point:i,el:s}}var RM=Sc();function OM(t,e,n){var i=t.currTrigger,r=[t.x,t.y],o=t,a=t.dispatchAction||Ki(n.dispatchAction,n),s=e.getComponent("axisPointer").coordSysAxesInfo;if(s){FM(r)&&(r=NM({seriesIndex:o.seriesIndex,dataIndex:o.dataIndex},e).point);var l=FM(r),c=o.axesInfo,u=s.axesInfo,d="leave"===i||FM(r),h={},p={},f={list:[],map:{}},g={showPointer:Qi(HM,p),showTooltip:Qi(BM,f)};Ui(s.coordSysMap,function(t,e){var n=l||t.containPoint(r);Ui(s.coordSysAxesInfo[e],function(t,e){var i=t.axis,o=function(t,e){for(var n=0;n<(t||[]).length;n++){var i=t[n];if(e.axis.dim===i.axisDim&&e.axis.model.componentIndex===i.axisIndex)return i}}(c,t);if(!d&&n&&(!c||o)){var a=o&&o.value;null!=a||l||(a=i.pointToData(r)),null!=a&&zM(t,a,g,!1,h)}})});var m={};return Ui(u,function(t,e){var n=t.linkGroup;n&&!p[e]&&Ui(n.axesInfo,function(e,i){var r=p[i];if(e!==t&&r){var o=r.value;n.mapper&&(o=t.axis.scale.parse(n.mapper(o,$M(e),$M(t)))),m[t.key]=o}})}),Ui(m,function(t,e){zM(u[e],t,g,!0,h)}),function(t,e,n){var i=n.axesInfo=[];Ui(e,function(e,n){var r=e.axisPointerModel.option,o=t[n];o?(!e.useHandle&&(r.status="show"),r.value=o.value,r.seriesDataIndices=(o.payloadBatch||[]).slice()):!e.useHandle&&(r.status="hide"),"show"===r.status&&i.push({axisDim:e.axis.dim,axisIndex:e.axis.model.componentIndex,value:r.value})})}(p,u,h),function(t,e,n,i){if(FM(e)||!t.list.length)return void i({type:"hideTip"});var r=((t.list[0].dataByAxis[0]||{}).seriesDataIndices||[])[0]||{};i({type:"showTip",escapeConnect:!0,x:e[0],y:e[1],tooltipOption:n.tooltipOption,position:n.position,dataIndexInside:r.dataIndexInside,dataIndex:r.dataIndex,seriesIndex:r.seriesIndex,dataByCoordSys:t.list})}(f,r,t,a),function(t,e,n){var i=n.getZr(),r="axisPointerLastHighlights",o=RM(i)[r]||{},a=RM(i)[r]={};Ui(t,function(t,e){var n=t.axisPointerModel.option;"show"===n.status&&t.triggerEmphasis&&Ui(n.seriesDataIndices,function(t){var e=t.seriesIndex+" | "+t.dataIndex;a[e]=t})});var s=[],l=[];Ui(o,function(t,e){!a[e]&&l.push(t)}),Ui(a,function(t,e){!o[e]&&s.push(t)}),l.length&&n.dispatchAction({type:"downplay",escapeConnect:!0,notBlur:!0,batch:l}),s.length&&n.dispatchAction({type:"highlight",escapeConnect:!0,notBlur:!0,batch:s})}(u,0,n),h}}function zM(t,e,n,i,r){var o=t.axis;if(!o.scale.isBlank()&&o.containData(e))if(t.involveSeries){var a=function(t,e){var n=e.axis,i=n.dim,r=t,o=[],a=Number.MAX_VALUE,s=-1;return Ui(e.seriesModels,function(e,l){var c,u,d=e.getData().mapDimensionsAll(i);if(e.getAxisTooltipData){var h=e.getAxisTooltipData(d,t,n);u=h.dataIndices,c=h.nestestValue}else{if(!(u=e.indicesOfNearest(i,d[0],t,"category"===n.type?.5:null)).length)return;c=e.getData().get(d[0],u[0])}if(null!=c&&isFinite(c)){var p=t-c,f=Math.abs(p);f<=a&&((f=0&&s<0)&&(a=f,s=p,r=c,o.length=0),Ui(u,function(t){o.push({seriesIndex:e.seriesIndex,dataIndexInside:t,dataIndex:e.getData().getRawIndex(t)})}))}}),{payloadBatch:o,snapToValue:r}}(e,t),s=a.payloadBatch,l=a.snapToValue;s[0]&&null==r.seriesIndex&&Fi(r,s[0]),!i&&t.snap&&o.containData(l)&&null!=l&&(e=l),n.showPointer(t,e,s),n.showTooltip(t,a,l)}else n.showPointer(t,e)}function HM(t,e,n,i){t[e.key]={value:n,payloadBatch:i}}function BM(t,e,n,i){var r=n.payloadBatch,o=e.axis,a=o.model,s=e.axisPointerModel;if(e.triggerTooltip&&r.length){var l=e.coordSys.model,c=Qk(l),u=t.map[c];u||(u=t.map[c]={coordSysId:l.id,coordSysIndex:l.componentIndex,coordSysType:l.type,coordSysMainType:l.mainType,dataByAxis:[]},t.list.push(u)),u.dataByAxis.push({axisDim:o.dim,axisIndex:a.componentIndex,axisType:a.type,axisId:a.id,value:i,valueLabelOpt:{precision:s.get(["label","precision"]),formatter:s.get(["label","formatter"])},seriesDataIndices:r.slice()})}}function $M(t){var e=t.axis.model,n={},i=n.axisDim=t.axis.dim;return n.axisIndex=n[i+"AxisIndex"]=e.componentIndex,n.axisName=n[i+"AxisName"]=e.name,n.axisId=n[i+"AxisId"]=e.id,n}function FM(t){return!t||null==t[0]||isNaN(t[0])||null==t[1]||isNaN(t[1])}function VM(t){tM.registerAxisPointerClass("CartesianAxisPointer",wM),t.registerComponentModel(MM),t.registerComponentView(EM),t.registerPreprocessor(function(t){if(t){(!t.axisPointer||0===t.axisPointer.length)&&(t.axisPointer={});var e=t.axisPointer.link;e&&!Ji(e)&&(t.axisPointer.link=[e])}}),t.registerProcessor(t.PRIORITY.PROCESSOR.STATISTIC,function(t,e){t.getComponent("axisPointer").coordSysAxesInfo=Xk(t,e)}),t.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},OM)}var WM=function(t){function e(){var n=null!==t&&t.apply(this,arguments)||this;return n.type=e.type,n}return S(e,t),e.type="tooltip",e.dependencies=["axisPointer"],e.defaultOption={z:60,show:!0,showContent:!0,trigger:"item",triggerOn:"mousemove|click",alwaysShowContent:!1,renderMode:"auto",confine:null,showDelay:0,hideDelay:100,transitionDuration:.4,displayTransition:!0,enterable:!1,backgroundColor:Im.color.neutral00,shadowBlur:10,shadowColor:"rgba(0, 0, 0, .2)",shadowOffsetX:1,shadowOffsetY:2,borderRadius:4,borderWidth:1,defaultBorderColor:Im.color.border,padding:null,extraCssText:"",axisPointer:{type:"line",axis:"auto",animation:"auto",animationDurationUpdate:200,animationEasingUpdate:"exponentialOut",crossStyle:{color:Im.color.borderShade,width:1,type:"dashed",textStyle:{}}},textStyle:{color:Im.color.tertiary,fontSize:14}},e}(Am);function jM(t){var e=t.get("confine");return null!=e?!!e:"richText"===t.get("renderMode")}function qM(t){if(yi.domSupported)for(var e=document.documentElement.style,n=0,i=t.length;n0&&r.push(function(t,e,n){var i="cubic-bezier(0.23,1,0.32,1)",r="",o="";return n&&(o="opacity"+(r=" "+t/2+"s "+i)+",visibility"+r),e||(r=" "+t+"s "+i,o+=(o.length?",":"")+(yi.transformSupported?""+YM+r:",left"+r+",top"+r)),XM+":"+o}(o,n,i)),a&&r.push("background-color:"+a),Ui(["width","color","radius"],function(e){var n="border-"+e,i=tm(n),o=t.get(i);null!=o&&r.push(n+":"+o+("color"===e?"":"px"))}),r.push(function(t){var e=[],n=t.get("fontSize"),i=t.getTextColor();i&&e.push("color:"+i),e.push("font:"+t.getFont());var r=dr(t.get("lineHeight"),Math.round(3*n/2));n&&e.push("line-height:"+r+"px");var o=t.get("textShadowColor"),a=t.get("textShadowBlur")||0,s=t.get("textShadowOffsetX")||0,l=t.get("textShadowOffsetY")||0;return o&&a&&e.push("text-shadow:"+s+"px "+l+"px "+a+"px "+o),Ui(["decoration","align"],function(n){var i=t.get(n);i&&e.push("text-"+n+":"+i)}),e.join(";")}(d)),null!=h&&r.push("padding:"+em(h).join("px ")+"px"),r.join(";")+";"}function JM(t,e,n,i,r){var o=e&&e.painter;if(n){var a=o&&o.getViewportRoot();a&&function(t,e,n,i,r){Xr(Gr,e,i,r,!0)&&Xr(t,n,Gr[0],Gr[1])}(t,a,n,i,r)}else{t[0]=i,t[1]=r;var s=o&&o.getViewportRootOffset();s&&(t[0]+=s.offsetLeft,t[1]+=s.offsetTop)}t[2]=t[0]/e.getWidth(),t[3]=t[1]/e.getHeight()}var tT=function(){function t(t,e){if(this._show=!1,this._styleCoord=[0,0,0,0],this._enterable=!0,this._alwaysShowContent=!1,this._firstShow=!0,this._longHide=!0,yi.wxa)return null;var n=document.createElement("div");n.domBelongToZr=!0,this.el=n;var i=this._zr=t.getZr(),r=e.appendTo,o=r&&(er(r)?document.querySelector(r):sr(r)?r:tr(r)&&r(t.getDom()));JM(this._styleCoord,i,o,t.getWidth()/2,t.getHeight()/2),(o||t.getDom()).appendChild(n),this._api=t,this._container=o;var a=this;n.onmouseenter=function(){a._enterable&&(clearTimeout(a._hideTimeout),a._show=!0),a._inContent=!0},n.onmousemove=function(t){if(t=t||window.event,!a._enterable){var e=i.handler;oo(i.painter.getViewportRoot(),t,!0),e.dispatch("mousemove",t)}},n.onmouseleave=function(){a._inContent=!1,a._enterable&&a._show&&a.hideLater(a._hideDelay)}}return t.prototype.update=function(t){if(!this._container){var e=this._api.getDom(),n=(o="position",(a=(r=e).currentStyle||document.defaultView&&document.defaultView.getComputedStyle(r))?a[o]:null),i=e.style;"absolute"!==i.position&&"absolute"!==n&&(i.position="relative")}var r,o,a,s=t.get("alwaysShowContent");s&&this._moveIfResized(),this._alwaysShowContent=s,this._enableDisplayTransition=t.get("displayTransition")&&t.get("transitionDuration")>0,this.el.className=t.get("className")||""},t.prototype.show=function(t,e){clearTimeout(this._hideTimeout),clearTimeout(this._longHideTimeout);var n=this.el,i=n.style,r=this._styleCoord;n.innerHTML?i.cssText=ZM+QM(t,!this._firstShow,this._longHide,this._enableDisplayTransition)+KM(r[0],r[1],!0)+"border-color:"+am(e)+";"+(t.get("extraCssText")||"")+";pointer-events:"+(this._enterable?"auto":"none"):i.display="none",this._show=!0,this._firstShow=!1,this._longHide=!1},t.prototype.setContent=function(t,e,n,i,r){var o=this.el;if(null!=t){var a="";if(er(r)&&"item"===n.get("trigger")&&!jM(n)&&(a=function(t,e,n){if(!er(n)||"inside"===n)return"";var i=t.get("backgroundColor"),r=t.get("borderWidth");e=am(e);var o,a,s="left"===(o=n)?"right":"right"===o?"left":"top"===o?"bottom":"top",l=Math.max(1.5*Math.round(r),6),c="",u=YM+":";Wi(["left","right"],s)>-1?(c+="top:50%",u+="translateY(-50%) rotate("+(a="left"===s?-225:-45)+"deg)"):(c+="left:50%",u+="translateX(-50%) rotate("+(a="top"===s?225:45)+"deg)");var d=a*Math.PI/180,h=l+r,p=h*Math.abs(Math.cos(d))+h*Math.abs(Math.sin(d)),f=e+" solid "+r+"px;";return'
'}(n,i,r)),er(t))o.innerHTML=t+a;else if(t){o.innerHTML="",Ji(t)||(t=[t]);for(var s=0;s=0?this._tryShow(n,i):"leave"===e&&this._hide(i))},this))},e.prototype._keepShow=function(){var t=this._tooltipModel,e=this._ecModel,n=this._api,i=t.get("triggerOn");if(null!=this._lastX&&null!=this._lastY&&"none"!==i&&"click"!==i){var r=this;clearTimeout(this._refreshUpdateTimeout),this._refreshUpdateTimeout=setTimeout(function(){!n.isDisposed()&&r.manuallyShowTip(t,e,n,{x:r._lastX,y:r._lastY,dataByCoordSys:r._lastDataByCoordSys})})}},e.prototype.manuallyShowTip=function(t,e,n,i){if(i.from!==this.uid&&!yi.node&&n.getDom()){var r=lT(i,n);this._ticket="";var o=i.dataByCoordSys,a=function(t,e,n){var i=Mc(t).queryOptionMap,r=i.keys()[0];if(!r||"series"===r)return;var o=Ac(e,r,i.get(r),{useDefault:!1,enableAll:!1,enableNone:!1}),a=o.models[0];if(!a)return;var s,l=n.getViewOfComponentModel(a);if(l.group.traverse(function(e){var n=Ud(e).tooltipConfig;if(n&&n.name===t.name)return s=e,!0}),s)return{componentMainType:r,componentIndex:a.componentIndex,el:s}}(i,e,n);if(a){var s=a.el.getBoundingRect().clone();s.applyTransform(a.el.transform),this._tryShow({offsetX:s.x+s.width/2,offsetY:s.y+s.height/2,target:a.el,position:i.position,positionDefault:"bottom"},r)}else if(i.tooltip&&null!=i.x&&null!=i.y){var l=oT;l.x=i.x,l.y=i.y,l.update(),Ud(l).tooltipConfig={name:null,option:i.tooltip},this._tryShow({offsetX:i.x,offsetY:i.y,target:l},r)}else if(o)this._tryShow({offsetX:i.x,offsetY:i.y,position:i.position,dataByCoordSys:o,tooltipOption:i.tooltipOption},r);else if(null!=i.seriesIndex){if(this._manuallyAxisShowTip(t,e,n,i))return;var c=NM(i,e),u=c.point[0],d=c.point[1];null!=u&&null!=d&&this._tryShow({offsetX:u,offsetY:d,target:c.el,position:i.position,positionDefault:"bottom"},r)}else null!=i.x&&null!=i.y&&(n.dispatchAction({type:"updateAxisPointer",x:i.x,y:i.y}),this._tryShow({offsetX:i.x,offsetY:i.y,position:i.position,target:n.getZr().findHover(i.x,i.y).target},r))}},e.prototype.manuallyHideTip=function(t,e,n,i){var r=this._tooltipContent;this._tooltipModel&&r.hideLater(this._tooltipModel.get("hideDelay")),this._lastX=this._lastY=this._lastDataByCoordSys=null,i.from!==this.uid&&this._hide(lT(i,n))},e.prototype._manuallyAxisShowTip=function(t,e,n,i){var r=i.seriesIndex,o=i.dataIndex,a=e.getComponent("axisPointer").coordSysAxesInfo;if(null!=r&&null!=o&&null!=a){var s=e.getSeriesByIndex(r);if(s)if("axis"===sT([s.getData().getItemModel(o),s,(s.coordinateSystem||{}).model],this._tooltipModel).get("trigger"))return n.dispatchAction({type:"updateAxisPointer",seriesIndex:r,dataIndex:o,position:i.position}),!0}},e.prototype._tryShow=function(t,e){var n=t.target;if(this._tooltipModel){this._lastX=t.offsetX,this._lastY=t.offsetY;var i=t.dataByCoordSys;if(i&&i.length)this._showAxisTooltip(i,t);else if(n){var r,o;if("legend"===Ud(n).ssrType)return;this._lastDataByCoordSys=null,db(n,function(t){if(t.tooltipDisabled)return r=o=null,!0;r||o||(null!=Ud(t).dataIndex?r=t:null!=Ud(t).tooltipConfig&&(o=t))},!0),r?this._showSeriesItemTooltip(t,r,e):o?this._showComponentItemTooltip(t,o,e):this._hide(e)}else this._lastDataByCoordSys=null,this._hide(e)}},e.prototype._showOrMove=function(t,e){var n=t.get("showDelay");e=Ki(e,this),clearTimeout(this._showTimout),n>0?this._showTimout=setTimeout(e,n):e()},e.prototype._showAxisTooltip=function(t,e){var n=this._ecModel,i=this._tooltipModel,r=[e.offsetX,e.offsetY],o=sT([e.tooltipOption],i),a=this._renderMode,s=[],l=jy("section",{blocks:[],noHeader:!0}),c=[],u=new t_;Ui(t,function(t){Ui(t.dataByAxis,function(t){var e=n.getComponent(t.axisDim+"Axis",t.axisIndex),r=t.value;if(e&&null!=r){var o=bM(r,e.axis,n,t.seriesDataIndices,t.valueLabelOpt),d=jy("section",{header:o,noHeader:!mr(o),sortBlocks:!0,blocks:[]});l.blocks.push(d),Ui(t.seriesDataIndices,function(l){var h=n.getSeriesByIndex(l.seriesIndex),p=l.dataIndexInside,f=h.getDataParams(p);if(!(f.dataIndex<0)){f.axisDim=t.axisDim,f.axisIndex=t.axisIndex,f.axisType=t.axisType,f.axisId=t.axisId,f.axisValue=LS(e.axis,{value:r}),f.axisValueLabel=o,f.marker=u.makeTooltipMarker("item",am(f.color),a);var g=dy(h.formatTooltip(p,!0,null)),m=g.frag;if(m){var v=sT([h],i).get("valueFormatter");d.blocks.push(v?Fi({valueFormatter:v},m):m)}g.text&&c.push(g.text),s.push(f)}})}})}),l.blocks.reverse(),c.reverse();var d=e.position,h=o.get("order"),p=Zy(l,u,a,h,n.get("useUTC"),o.get("textStyle"));p&&c.unshift(p);var f="richText"===a?"\n\n":"
",g=c.join(f);this._showOrMove(o,function(){this._updateContentNotChangedOnAxis(t,s)?this._updatePosition(o,d,r[0],r[1],this._tooltipContent,s):this._showTooltipContent(o,g,s,Math.random()+"",r[0],r[1],d,null,u)})},e.prototype._showSeriesItemTooltip=function(t,e,n){var i=this._ecModel,r=Ud(e),o=r.seriesIndex,a=i.getSeriesByIndex(o),s=r.dataModel||a,l=r.dataIndex,c=r.dataType,u=s.getData(c),d=this._renderMode,h=t.positionDefault,p=sT([u.getItemModel(l),s,a&&(a.coordinateSystem||{}).model],this._tooltipModel,h?{position:h}:null),f=p.get("trigger");if(null==f||"item"===f){var g=s.getDataParams(l,c),m=new t_;g.marker=m.makeTooltipMarker("item",am(g.color),d);var v=dy(s.formatTooltip(l,!1,c)),y=p.get("order"),_=p.get("valueFormatter"),b=v.frag,x=b?Zy(_?Fi({valueFormatter:_},b):b,m,d,y,i.get("useUTC"),p.get("textStyle")):v.text,w="item_"+s.name+"_"+l;this._showOrMove(p,function(){this._showTooltipContent(p,x,g,w,t.offsetX,t.offsetY,t.position,t.target,m)}),n({type:"showTip",dataIndexInside:l,dataIndex:u.getRawIndex(l),seriesIndex:o,from:this.uid})}},e.prototype._showComponentItemTooltip=function(t,e,n){var i="html"===this._renderMode,r=Ud(e),o=r.tooltipConfig.option||{},a=o.encodeHTMLContent;if(er(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=Bi(o)).content=Qr(o.content));var s=[o],l=this._ecModel.getComponent(r.componentMainType,r.componentIndex);l&&s.push(l),s.push({formatter:o.content});var c=t.positionDefault,u=sT(s,this._tooltipModel,c?{position:c}:null),d=u.get("content"),h=Math.random()+"",p=new t_;this._showOrMove(u,function(){var n=Bi(u.get("formatterParams")||{});this._showTooltipContent(u,d,n,h,t.offsetX,t.offsetY,t.position,e,p)}),n({type:"showTip",from:this.uid})},e.prototype._showTooltipContent=function(t,e,n,i,r,o,a,s,l){if(this._ticket="",t.get("showContent")&&t.get("show")){var c=this._tooltipContent;c.setEnterable(t.get("enterable"));var u=t.get("formatter");a=a||t.get("position");var d=e,h=this._getNearestPoint([r,o],n,t.get("trigger"),t.get("borderColor"),t.get("defaultBorderColor",!0)).color;if(u)if(er(u)){var p=t.ecModel.get("useUTC"),f=Ji(n)?n[0]:n;d=u,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(d=Og(f.axisValue,d,p)),d=om(d,n,!0)}else if(tr(u)){var g=Ki(function(e,i){e===this._ticket&&(c.setContent(i,l,t,h,a),this._updatePosition(t,a,r,o,c,n,s))},this);this._ticket=i,d=u(n,i,g)}else d=u;c.setContent(d,l,t,h,a),c.show(t,h),this._updatePosition(t,a,r,o,c,n,s)}},e.prototype._getNearestPoint=function(t,e,n,i,r){return"axis"===n||Ji(e)?{color:i||r}:Ji(e)?void 0:{color:i||e.color||e.borderColor}},e.prototype._updatePosition=function(t,e,n,i,r,o,a){var s=this._api.getWidth(),l=this._api.getHeight();e=e||t.get("position");var c=r.getSize(),u=t.get("align"),d=t.get("verticalAlign"),h=a&&a.getBoundingRect().clone();if(a&&h.applyTransform(a.transform),tr(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),Ji(e))n=ql(e[0],s),i=ql(e[1],l);else if(rr(e)){var p=e;p.width=c[0],p.height=c[1];var f=xm(p,{width:s,height:l});n=f.x,i=f.y,u=null,d=null}else if(er(e)&&a){var g=function(t,e,n,i){var r=n[0],o=n[1],a=Math.ceil(Math.SQRT2*i)+8,s=0,l=0,c=e.width,u=e.height;switch(t){case"inside":s=e.x+c/2-r/2,l=e.y+u/2-o/2;break;case"top":s=e.x+c/2-r/2,l=e.y-o-a;break;case"bottom":s=e.x+c/2-r/2,l=e.y+u+a;break;case"left":s=e.x-r-a,l=e.y+u/2-o/2;break;case"right":s=e.x+c+a,l=e.y+u/2-o/2}return[s,l]}(e,h,c,t.get("borderWidth"));n=g[0],i=g[1]}else{g=function(t,e,n,i,r,o,a){var s=n.getSize(),l=s[0],c=s[1];null!=o&&(t+l+o+2>i?t-=l+o:t+=o);null!=a&&(e+c+a>r?e-=c+a:e+=a);return[t,e]}(n,i,r,s,l,u?null:20,d?null:20);n=g[0],i=g[1]}if(u&&(n-=cT(u)?c[0]/2:"right"===u?c[0]:0),d&&(i-=cT(d)?c[1]/2:"bottom"===d?c[1]:0),jM(t)){g=function(t,e,n,i,r){var o=n.getSize(),a=o[0],s=o[1];return t=Math.min(t+a,i)-a,e=Math.min(e+s,r)-s,t=Math.max(t,0),e=Math.max(e,0),[t,e]}(n,i,r,s,l);n=g[0],i=g[1]}r.moveTo(n,i)},e.prototype._updateContentNotChangedOnAxis=function(t,e){var n=this._lastDataByCoordSys,i=this._cbParamsList,r=!!n&&n.length===t.length;return r&&Ui(n,function(n,o){var a=n.dataByAxis||[],s=(t[o]||{}).dataByAxis||[];(r=r&&a.length===s.length)&&Ui(a,function(t,n){var o=s[n]||{},a=t.seriesDataIndices||[],l=o.seriesDataIndices||[];(r=r&&t.value===o.value&&t.axisType===o.axisType&&t.axisId===o.axisId&&a.length===l.length)&&Ui(a,function(t,e){var n=l[e];r=r&&t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex}),i&&Ui(t.seriesDataIndices,function(t){var n=t.seriesIndex,o=e[n],a=i[n];o&&a&&a.data!==o.data&&(r=!1)})})}),this._lastDataByCoordSys=t,this._cbParamsList=e,!!r},e.prototype._hide=function(t){this._lastDataByCoordSys=null,t({type:"hideTip",from:this.uid})},e.prototype.dispose=function(t,e){!yi.node&&e.getDom()&&(T_(this,"_updatePosition"),this._tooltipContent.dispose(),LM("itemTooltip",e))},e.type="tooltip",e}(h_);function sT(t,e,n){var i,r=e.ecModel;n?(i=new ug(n,r,r),i=new ug(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof ug&&(a=a.get("tooltip",!0)),er(a)&&(a={formatter:a}),a&&(i=new ug(a,i,r)))}return i}function lT(t,e){return t.dispatchAction||Ki(e.dispatchAction,e)}function cT(t){return"center"===t||"middle"===t}var uT=Math.sin,dT=Math.cos,hT=Math.PI,pT=2*Math.PI,fT=180/hT,gT=function(){function t(){}return t.prototype.reset=function(t){this._start=!0,this._d=[],this._str="",this._p=Math.pow(10,t||4)},t.prototype.moveTo=function(t,e){this._add("M",t,e)},t.prototype.lineTo=function(t,e){this._add("L",t,e)},t.prototype.bezierCurveTo=function(t,e,n,i,r,o){this._add("C",t,e,n,i,r,o)},t.prototype.quadraticCurveTo=function(t,e,n,i){this._add("Q",t,e,n,i)},t.prototype.arc=function(t,e,n,i,r,o){this.ellipse(t,e,n,n,0,i,r,o)},t.prototype.ellipse=function(t,e,n,i,r,o,a,s){var l=a-o,c=!s,u=Math.abs(l),d=ns(u-pT)||(c?l>=pT:-l>=pT),h=l>0?l%pT:l%pT+pT,p=!1;p=!!d||!ns(u)&&h>=hT==!!c;var f=t+n*dT(o),g=e+i*uT(o);this._start&&this._add("M",f,g);var m=Math.round(r*fT);if(d){var v=1/this._p,y=(c?1:-1)*(pT-v);this._add("A",n,i,m,1,+c,t+n*dT(o+y),e+i*uT(o+y)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var _=t+n*dT(a),b=e+i*uT(a);this._add("A",n,i,m,+p,+c,_,b)}},t.prototype.rect=function(t,e,n,i){this._add("M",t,e),this._add("l",n,0),this._add("l",0,i),this._add("l",-n,0),this._add("Z")},t.prototype.closePath=function(){this._d.length>0&&this._add("Z")},t.prototype._add=function(t,e,n,i,r,o,a,s,l){for(var c=[],u=this._p,d=1;d"}(r,o)+("style"!==r?Qr(a):a||"")+(i?""+n+Gi(i,function(e){return t(e)}).join(n)+n:"")+("")}(t)}function TT(t){return{zrId:t,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function AT(t,e,n,i){return kT("svg","root",{width:t,height:e,xmlns:xT,"xmlns:xlink":wT,version:"1.1",baseProfile:"full",viewBox:!!i&&"0 0 "+t+" "+e},n)}var IT=0;function DT(){return IT++}var PT={cubicIn:"0.32,0,0.67,0",cubicOut:"0.33,1,0.68,1",cubicInOut:"0.65,0,0.35,1",quadraticIn:"0.11,0,0.5,0",quadraticOut:"0.5,1,0.89,1",quadraticInOut:"0.45,0,0.55,1",quarticIn:"0.5,0,0.75,0",quarticOut:"0.25,1,0.5,1",quarticInOut:"0.76,0,0.24,1",quinticIn:"0.64,0,0.78,0",quinticOut:"0.22,1,0.36,1",quinticInOut:"0.83,0,0.17,1",sinusoidalIn:"0.12,0,0.39,0",sinusoidalOut:"0.61,1,0.88,1",sinusoidalInOut:"0.37,0,0.63,1",exponentialIn:"0.7,0,0.84,0",exponentialOut:"0.16,1,0.3,1",exponentialInOut:"0.87,0,0.13,1",circularIn:"0.55,0,1,0.45",circularOut:"0,0.55,0.45,1",circularInOut:"0.85,0,0.15,1"},LT="transform-origin";function ET(t,e,n){var i=Fi({},t.shape);Fi(i,e),t.buildPath(n,i);var r=new gT;return r.reset(hs(t)),n.rebuildPath(r,1),r.generateStr(),r.getStr()}function NT(t,e){var n=e.originX,i=e.originY;(n||i)&&(t[LT]=n+"px "+i+"px")}var RT={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function OT(t,e){var n=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[n]=t,n}function zT(t){return er(t)?PT[t]?"cubic-bezier("+PT[t]+")":Aa(t)?t:"":""}function HT(t,e,n,i){var r=t.animators,o=r.length,a=[];if(t instanceof Bp){var s=function(t,e,n){var i,r,o=t.shape.paths,a={};if(Ui(o,function(t){var e=TT(n.zrId);e.animation=!0,HT(t,{},e,!0);var o=e.cssAnims,s=e.cssNodes,l=Zi(o),c=l.length;if(c){var u=o[r=l[c-1]];for(var d in u){var h=u[d];a[d]=a[d]||{d:""},a[d].d+=h.d||""}for(var p in s){var f=s[p].animation;f.indexOf(r)>=0&&(i=f)}}}),i){e.d=!1;var s=OT(a,n);return i.replace(r,s)}}(t,e,n);if(s)a.push(s);else if(!o)return}else if(!o)return;for(var l={},c=0;c0}).length)return OT(u,n)+" "+r[0]+" both"}for(var m in l){(s=g(l[m]))&&a.push(s)}if(a.length){var v=n.zrId+"-cls-"+DT();n.cssNodes["."+v]={animation:a.join(",")},e.class=v}}function BT(t,e,n,i){var r=JSON.stringify(t),o=n.cssStyleCache[r];o||(o=n.zrId+"-cls-"+DT(),n.cssStyleCache[r]=o,n.cssNodes["."+o+":hover"]=t),e.class=e.class?e.class+" "+o:o}var $T=Math.round;function FT(t){return t&&er(t.src)}function VT(t){return t&&tr(t.toDataURL)}function WT(t,e,n,i){bT(function(r,o){var a="fill"===r||"stroke"===r;a&&us(o)?tA(e,t,r,i):a&&ss(o)?eA(n,t,r,i):t[r]=o,a&&i.ssr&&"none"===o&&(t["pointer-events"]="visible")},e,n,!1),function(t,e,n){var i=t.style;if(function(t){return t&&(t.shadowBlur||t.shadowOffsetX||t.shadowOffsetY)}(i)){var r=function(t){var e=t.style,n=t.getGlobalScale();return[e.shadowColor,(e.shadowBlur||0).toFixed(2),(e.shadowOffsetX||0).toFixed(2),(e.shadowOffsetY||0).toFixed(2),n[0],n[1]].join(",")}(t),o=n.shadowCache,a=o[r];if(!a){var s=t.getGlobalScale(),l=s[0],c=s[1];if(!l||!c)return;var u=i.shadowOffsetX||0,d=i.shadowOffsetY||0,h=i.shadowBlur,p=ts(i.shadowColor),f=p.opacity,g=p.color,m=h/2/l+" "+h/2/c;a=n.zrId+"-s"+n.shadowIdx++,n.defs[a]=kT("filter",a,{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},[kT("feDropShadow","",{dx:u/l,dy:d/c,stdDeviation:m,"flood-color":g,"flood-opacity":f})]),o[r]=a}e.filter=ds(a)}}(n,t,i)}function jT(t,e){var n=function(t){if("function"==typeof zl)return zl(t)}(e);n&&(n.each(function(e,n){null!=e&&(t[(ST+n).toLowerCase()]=e+"")}),e.isSilent()&&(t[ST+"silent"]="true"))}function qT(t){return ns(t[0]-1)&&ns(t[1])&&ns(t[2])&&ns(t[3]-1)}function UT(t,e,n){if(e&&(!function(t){return ns(t[4])&&ns(t[5])}(e)||!qT(e))){var i=1e4;t.transform=qT(e)?"translate("+$T(e[4]*i)/i+" "+$T(e[5]*i)/i+")":function(t){return"matrix("+is(t[0])+","+is(t[1])+","+is(t[2])+","+is(t[3])+","+rs(t[4])+","+rs(t[5])+")"}(e)}}function GT(t,e,n){for(var i=t.points,r=[],o=0;o=0&&a||o;s&&(r=Qa(s))}var l=i.lineWidth;l&&(l/=!i.strokeNoScale&&t.transform?t.transform[0]:1);var c={cursor:"pointer"};r&&(c.fill=r),i.stroke&&(c.stroke=i.stroke),l&&(c["stroke-width"]=l),BT(c,e,n)}}(t,o,e),kT(s,t.id+"",o)}function JT(t,e){return t instanceof vd?QT(t,e):t instanceof wd?function(t,e){var n=t.style,i=n.image;if(i&&!er(i)&&(FT(i)?i=i.src:VT(i)&&(i=i.toDataURL())),i){var r=n.x||0,o=n.y||0,a={href:i,width:n.width,height:n.height};return r&&(a.x=r),o&&(a.y=o),UT(a,t.transform),WT(a,n,t,e),jT(a,t),e.animation&&HT(t,a,e),kT("image",t.id+"",a)}}(t,e):t instanceof _d?function(t,e){var n=t.style,i=n.text;if(null!=i&&(i+=""),i&&!isNaN(n.x)&&!isNaN(n.y)){var r=n.font||bi,o=n.x||0,a=function(t,e,n){return"top"===n?t+=e/2:"bottom"===n&&(t-=e/2),t}(n.y||0,bl(r),n.textBaseline),s={"dominant-baseline":"central","text-anchor":os[n.textAlign]||n.textAlign};if(Bd(n)){var l="",c=n.fontStyle,u=zd(n.fontSize);if(!parseFloat(u))return;var d=n.fontFamily||_i,h=n.fontWeight;l+="font-size:"+u+";font-family:"+d+";",c&&"normal"!==c&&(l+="font-style:"+c+";"),h&&"normal"!==h&&(l+="font-weight:"+h+";"),s.style=l}else s.style="font: "+r;return i.match(/\s/)&&(s["xml:space"]="preserve"),o&&(s.x=o),a&&(s.y=a),UT(s,t.transform),WT(s,n,t,e),jT(s,t),e.animation&&HT(t,s,e),kT("text",t.id+"",s,void 0,i)}}(t,e):void 0}function tA(t,e,n,i){var r,o=t[n],a={gradientUnits:o.global?"userSpaceOnUse":"objectBoundingBox"};if(ls(o))r="linearGradient",a.x1=o.x,a.y1=o.y,a.x2=o.x2,a.y2=o.y2;else{if(!cs(o))return;r="radialGradient",a.cx=dr(o.x,.5),a.cy=dr(o.y,.5),a.r=dr(o.r,.5)}for(var s=o.colorStops,l=[],c=0,u=s.length;cl?mA(t,null==n[d+1]?null:n[d+1].elm,n,s,d):vA(t,e,a,l))}(n,i,r):hA(r)?(hA(t.text)&&cA(n,""),mA(n,null,r,0,r.length-1)):hA(i)?vA(n,i,0,i.length-1):hA(t.text)&&cA(n,""):t.text!==e.text&&(hA(i)&&vA(n,i,0,i.length-1),cA(n,e.text)))}var bA=0,xA=function(){function t(t,e,n){if(this.type="svg",this.refreshHover=function(){},this.configLayer=function(){},this.storage=e,this._opts=n=Fi({},n),this.root=t,this._id="zr"+bA++,this._oldVNode=AT(n.width,n.height),t&&!n.ssr){var i=this._viewport=document.createElement("div");i.style.cssText="position:relative;overflow:hidden";var r=this._svgDom=this._oldVNode.elm=CT("svg");yA(null,this._oldVNode),i.appendChild(r),t.appendChild(i)}this.resize(n.width,n.height)}return t.prototype.getType=function(){return this.type},t.prototype.getViewportRoot=function(){return this._viewport},t.prototype.getViewportRootOffset=function(){var t=this.getViewportRoot();if(t)return{offsetLeft:t.offsetLeft||0,offsetTop:t.offsetTop||0}},t.prototype.getSvgDom=function(){return this._svgDom},t.prototype.refresh=function(){if(this.root){var t=this.renderToVNode({willUpdate:!0});t.attrs.style="position:absolute;left:0;top:0;user-select:none",function(t,e){if(fA(t,e))_A(t,e);else{var n=t.elm,i=sA(n);gA(e),null!==i&&(rA(i,e.elm,lA(n)),vA(i,[t],0,0))}}(this._oldVNode,t),this._oldVNode=t}},t.prototype.renderOneToVNode=function(t){return JT(t,TT(this._id))},t.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),n=this._width,i=this._height,r=TT(this._id);r.animation=t.animation,r.willUpdate=t.willUpdate,r.compress=t.compress,r.emphasis=t.emphasis,r.ssr=this._opts.ssr;var o=[],a=this._bgVNode=function(t,e,n,i){var r;if(n&&"none"!==n)if(r=kT("rect","bg",{width:t,height:e,x:"0",y:"0"}),us(n))tA({fill:n},r.attrs,"fill",i);else if(ss(n))eA({style:{fill:n},dirty:Mr,getBoundingRect:function(){return{width:t,height:e}}},r.attrs,"fill",i);else{var o=ts(n),a=o.color,s=o.opacity;r.attrs.fill=a,s<1&&(r.attrs["fill-opacity"]=s)}return r}(n,i,this._backgroundColor,r);a&&o.push(a);var s=t.compress?null:this._mainVNode=kT("g","main",{},[]);this._paintList(e,r,s?s.children:o),s&&o.push(s);var l=Gi(Zi(r.defs),function(t){return r.defs[t]});if(l.length&&o.push(kT("defs","defs",{},l)),t.animation){var c=function(t,e,n){var i=(n=n||{}).newline?"\n":"",r=" {"+i,o=i+"}",a=Gi(Zi(t),function(e){return e+r+Gi(Zi(t[e]),function(n){return n+":"+t[e][n]+";"}).join(i)+o}).join(i),s=Gi(Zi(e),function(t){return"@keyframes "+t+r+Gi(Zi(e[t]),function(n){return n+r+Gi(Zi(e[t][n]),function(i){var r=e[t][n][i];return"d"===i&&(r='path("'+r+'")'),i+":"+r+";"}).join(i)+o}).join(i)+o}).join(i);return a||s?[""].join(i):""}(r.cssNodes,r.cssAnims,{newline:!0});if(c){var u=kT("style","stl",{},[],c);o.push(u)}}return AT(n,i,o,t.useViewBox)},t.prototype.renderToString=function(t){return t=t||{},MT(this.renderToVNode({animation:dr(t.cssAnimation,!0),emphasis:dr(t.cssEmphasis,!0),willUpdate:!1,compress:!0,useViewBox:dr(t.useViewBox,!0)}),{newline:!0})},t.prototype.setBackgroundColor=function(t){this._backgroundColor=t},t.prototype.getSvgRoot=function(){return this._mainVNode&&this._mainVNode.elm},t.prototype._paintList=function(t,e,n){for(var i,r,o=t.length,a=[],s=0,l=0,c=0;c=0&&(!d||!r||d[f]!==r[f]);f--);for(var g=p-1;g>f;g--)i=a[--s-1];for(var m=f+1;m10&&"cartesian2d"===o.type&&r){var s=o.getBaseAxis(),l=o.getOtherAxis(s),c=s.getExtent(),u=n.getDevicePixelRatio(),d=Math.abs(c[1]-c[0])*(u||1),h=Math.round(a/d);if(isFinite(h)&&h>1){"lttb"===r?t.setData(i.lttbDownSample(i.mapDimension(l.dim),1/h)):"minmax"===r&&t.setData(i.minmaxDownSample(i.mapDimension(l.dim),1/h));var p=void 0;er(r)?p=XC[r]:tr(r)&&(p=r),p&&t.setData(i.downSample(i.mapDimension(l.dim),1/h,p,YC))}}}}}("line"))},function(t){VS(cM),VS(VM)},function(t){VS(VM),t.registerComponentModel(WM),t.registerComponentView(aT),t.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},Mr),t.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},Mr)},function(t){t.registerPainter("svg",xA)}]);class wA extends Nt{constructor(){super(...arguments),this.options=null,this.data=[],this.height="120px",this._chart=null,this._resizeObserver=null}render(){return gt`
`}connectedCallback(){super.connectedCallback(),this.hasUpdated&&!this._chart&&this.options&&(this._mount(),this._observeResize())}firstUpdated(){this._mount(),this._observeResize()}updated(t){(t.has("options")||t.has("data"))&&(this._chart&&this.options?this._chart.setOption(this._mergedOptions(),!0):!this._chart&&this.options&&this._mount()),t.has("height")&&this._chart&&this._chart.resize()}disconnectedCallback(){this._destroy(),super.disconnectedCallback()}_mount(){if(!this.options)return;const t=this.shadowRoot?.querySelector(".chart-host");t&&(this._chart=Yx(t,void 0,{renderer:"svg"}),this._chart.setOption(this._mergedOptions(),!0))}_mergedOptions(){if(!this.options)throw new Error("span-chart: options not set");return{...this.options,series:this.data}}_observeResize(){if("undefined"==typeof ResizeObserver)return;this._resizeObserver=new ResizeObserver(()=>{this._chart&&this._chart.resize()});const t=this.shadowRoot?.querySelector(".chart-host");t&&this._resizeObserver.observe(t)}_destroy(){this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._chart&&(this._chart.dispose(),this._chart=null)}}wA.styles=P` :host { display: block; width: 100%; @@ -55,13 +55,13 @@ var al={},sl={};var ll,cl=function(){function t(t,e,n){var i=this;this._sleepAft width: 100%; height: 100%; } - `,_([Et({attribute:!1})],GT.prototype,"options",void 0),_([Et({attribute:!1})],GT.prototype,"data",void 0),_([Et({type:String})],GT.prototype,"height",void 0);try{customElements.get("span-chart")||customElements.define("span-chart",GT)}catch{}function XT(t,e,n,i,r,a,s,l,c){const{options:u,series:d}=function(t,e,n,i,r,a=!1){n||(n=p[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)]),f=[{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}}],g=h.length>0?function(t){let e=0;for(const n of t)n[1]>e&&(e=n[1]);return e}(h):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(d?(m.min=n.fixedMin,m.max=n.fixedMax):g<1&&(m.min=0,m.max=1),r&&"current"===n.entityRole){const t=r.ratingA*r.continuousPct/100,e=r.ratingA*r.spikePct/100;m.min=0,m.max=Math.ceil(1.25*Math.max(t,e,g)),f.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}}),f.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 v={xAxis:{type:"time",min:u,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,r,a,l,c),h=s??120;t.style.minHeight=h+"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:h)+"px",f.options=u,f.data=d}function YT(t){return null===t?Wt:function(t){return(Math.abs(t)/1e3).toFixed(1)}(t)}function ZT(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):Wt,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:$t(o),partial:!1}),a&&(a.textContent=YT(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):Wt,c&&(c.textContent="A")}else l.textContent=YT($t(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):Wt,d&&(d.textContent="A")}else u.textContent=YT($t(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):Wt,p&&(p.textContent="A")}else h.textContent=YT($t(i)),p&&(p.textContent="kW")}const f=t.querySelector(".stat-battery .stat-value");if(f){const t=n.panel_entities?.battery_level,i=$t(t?e.states[t]:void 0);f.textContent=null===i?Wt:`${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:Wt}}(o,e,n,i,r)}function KT(t,e,n,i){const{hass:r,powerHistory:o,horizonMap:a,defaultDurationMs:s,chartMetric:l,monitoringStatus:c}=i,u=Oe(n,r),d=Be(n,u),h=Re(n,r),p=t.querySelector(".power-value");p&&(p.innerHTML="current"===l.entityRole?Yt(ze(n,r)):Xt(u)),Ke(t,h,Ue(n,r)),t.classList.toggle("circuit-off",!h),t.classList.toggle("circuit-producer",d),en(t,Ye(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)?Ln(a.get(e)):s,h=He(n),p=Ce(c,n),g=De(n,p);XT(f,0,i,u,l,d,r,g?{ratingA:g,...ke(p)}:void 0,h)}}class QT{get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this._retry=t?new be(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 JT(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 eA(t,e,n){return{members:t?ae(t):[{uuid:e,circuit:n}],capacityA:t&&t.members.length>1?t.circuit.breaker_rating_a??null:null}}class nA{constructor(){this.powerHistory=new Map,this.horizonMap=new Map,this.subDeviceHorizonMap=new Map,this.monitoringCache=new we,this.monitoringMultiCache=new Se,this.graphSettingsCache=new QT,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,JT(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,JT(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 Fn(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=$t(this._hass.states[r]);if(null===o)continue;const l=Ln(i),c=En(l),u=Nn(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 $n(this._topology))n.has(e)&&r.add(t);const o=new Map;try{await Fn(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=Pn(i),l=ce(n),c=[];for(const{circuit:t}of l){if(!t.entities?.power||He(t)||Qt(t))continue;const n=Oe(t,e);c.push(null===n?null:Math.abs(n))}ZT(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,powerHistory:r,horizonMap:o,defaultDurationMs:s,chartMetric:re(i),monitoringStatus:a};for(const e of l)for(const n of ae(e)){const i=t.querySelector(`.circuit-slot[data-uuid="${on(n.uuid)}"]`);if(!i)continue;const r=n.uuid===e.uuid?e.circuit:le(n.circuit,e);KT(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=Pn(i);for(const[i,s]of Object.entries(n.sub_devices)){const n=t.querySelector(`[data-subdev="${on(i)}"]`);if(!n)continue;const l=mn(s);if(l.headlineEid){const t=n.querySelector(".sub-power-value");t&&(t.innerHTML=Gt(_n(e,l.headlineEid)))}if(l.siteTotalEid){const t=_n(e,l.siteTotalEid),i=n.querySelector(".sub-site-total-value");i&&(i.innerHTML=Gt(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=f.power;e.endsWith("_soc")?s=f.soc:e.endsWith("_soe")&&(s=f.soe);const l=!!t.closest(".bess-chart-col");XT(t,0,n,o?.has(i)?Ln(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="${on(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=$t(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 an(n)){const n=t.querySelector(`.meter-tile[data-meter-uuid="${on(r)}"] .meter-readings`);n&&(n.innerHTML=cn(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,r=n?.closest(".toggle-pill");if(!r)return;const o=e.querySelector(".slide-confirm");if(!o||!o.classList.contains("confirmed"))return;t.stopPropagation(),t.preventDefault();const a=r.closest("[data-uuid]");if(!a||!this._topology||!this._hass)return;const s=a.dataset.uuid;if(!s)return;const l=this._topology.circuits[s];if(!l)return;const c=l.entities?.switch;if(!c)return;if("operable"!==Ue(l,this._hass))return;const u="on"===this._hass.states[c]?.state?"turn_off":"turn_on";this._hass.callService("switch",u,{},{entity_id:c}).catch(t=>{console.warn("SPAN Panel: switch service call failed",t),this._errorStore?.add({key:"service:relay",level:"error",message:i("error.relay_failed"),persistent:!1})})}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=Ce(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};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:yn(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?se(ce(n)).get(e.targetId):this._topology?se(ce(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=se(ce(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=Ce(l,a);r.refreshRating({...eA(s,o.uuid,a),monitoringInfo:c,monitoringGlobals:l?.global_settings??null})}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 be(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 be(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 xe(o?.response)}catch(t){return console.warn("SPAN Panel: fresh monitoring status fetch failed",t),null}}bindSlideConfirm(t,e){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 iA(t=""){const e=t?` value="${Ot(t)}"`:"",n=t?"":"display:none;";return`\n
\n \n \n
\n `}function rA(t,e,n,r,o,a,s,l){const c=Re(e,n),u=Ue(e,n),d=de([e]),h=Ot(e.name||i("grid.unknown")),p="current"===re(r).entityRole;let f;f=c?p?Yt(ze(e,n)):Xt(Oe(e,n)):"";const g=tn(a||"unknown");let m="";const v=$e(l,n,o);null!==v&&(m=`${Math.round(v)}%`);const y=``,_=Qt(e)?"":"none"===u?`${c?"ON":"OFF"}`:Ze(c,u);return`\n
\n ${d?`${d}`:""}\n ${m}\n ${h}\n ${g}\n ${_}\n \n ${f}\n \n ${y}\n \n
\n `}function oA(t,e,n,i,r){const o=Be(e,Oe(e,n)),a=Ne(0,r,Re(e,n),o),s=Ot(t);return`\n
\n
\n
\n
\n
\n `}function aA(t){return`
${Ot(t)}
`}function sA(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 lA(t,e,n){return{isOn:Re(t,e),value:"current"===(n.chart_metric||"power")?ze(t,e):Oe(t,e)}}function cA(t,e,n,i){const r=lA(t,n,i),o=lA(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 uA(t,e,n){return t.sort((t,i)=>cA(t[1],i[1],e,n))}class dA{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=uA(Object.entries(n.circuits),e,i),s=se(ce(n));let l=o+iA(this._searchQuery);l+=`
`;for(const[t,n]of a){const o=Ce(r,n),a=Ye(n,e),c=this._expandedUuids.has(t);l+=`
`,l+=rA(t,n,e,i,o,a,c,le(n,s.get(t))),c&&(l+=oA(t,n,e,0,o)),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=se(ce(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+iA(this._searchQuery);d+=`
`;for(const t of u){const n=c.get(t);if(!n)continue;const i=uA(n,e,r);d+=aA(t);for(const[t,n]of i){const i=Ce(o,n),a=Ye(n,e),s=this._expandedUuids.has(t);d+=`
`,d+=rA(t,n,e,r,i,a,s,le(n,l.get(t))),s&&(d+=oA(t,n,e,0,i)),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}=lA(a,e,i),c=t.querySelector(".list-power-value");c&&(c.innerHTML=s?r?Yt(l):Xt(l):""),Ke(t,s,Ue(a,e)),en(t,Ye(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)=>cA(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=sA(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=on(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=Ce(this._monitoringStatus,e),o=oA(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 hA=["entity_registry_updated","area_registry_updated","device_registry_updated"];async function pA(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 fA=["name","name_by_user"];async function gA(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:fA.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 mA="loaded";function vA(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 yA(t,e,n){const i=t.connection;return i?i.subscribeEvents(t=>{(function(t){const e=vA(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=vA(t);if(!e||!("circuit_ids"in e)||!Array.isArray(e.circuit_ids))return null;const n=e.circuit_ids;return n.every(t=>"string"==typeof t)?new Set(n):null}(t))},"span_panel_package_ratings_changed"):()=>{}}class _A{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 bA(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=Kt(o.panel_size)?o.panel_size:xA(o.circuits);if(!Jt(o,a))throw new Error(i("card.topology_error"));const s={type:"config/device_registry/list"},c=n?await n.callWS(t,s,{errorId:"fetch:topology"}):await t.callWS(s),u=o.panel_device_id??e,d=c.find(t=>t.id===u)??null;return function(t,e){const n=new Map(e.map(t=>[t.id,t]));for(const e of Object.values(t)){const t=e.device_id?n.get(e.device_id):void 0,i=t?Cn(t):"";i&&(e.name=i)}}(o.circuits,c),await pA(t,o),{topology:o,panelDevice:d,panelSize:a}}function xA(t){let e=0;for(const n of Object.values(t))if(n&&!Qt(n))for(const t of n.tabs)t>e&&(e=t);return e>0?e+e%2:0}const wA="_power",SA="Power";function CA(t,e){if(!t.endsWith(wA))return null;const n=`span_${e.toLowerCase()}_`,i=e&&t.startsWith(n)?t.slice(n.length,-6):t.split("_").slice(2,-1).join("_");return i?{circuitId:i,panelPrefix:t.slice(0,-(i.length+6+1))}:null}function kA(t,e){return`${t}_circuit_${e}`}function MA(t){if("string"!=typeof t||!t.startsWith("tabs ["))return null;const e=t.slice(6,-1),n=e.includes(":")?e.split(":").map(Number):[Number(e)];return n.every(Number.isFinite)?n:null}function TA(t,e){const n=e.filter(e=>t.startsWith(`${e} `)).sort((t,e)=>e.length-t.length)[0];return void 0===n?t:t.slice(n.length+1)}function AA(t,e){if(t===SA)return"";return TA(t.endsWith(` ${SA}`)?t.slice(0,-6):t,e)}function IA(t,e){const n=(t.model??"").toLowerCase(),i=n.includes("battery")||(t.identifiers??[]).some(t=>t[1].toLowerCase().includes("bess")),r=n.includes("drive")||(t.identifiers??[]).some(t=>t[1].toLowerCase().includes("evse")),o={};for(const t of e){const e={domain:t.entity_id.split(".")[0]??"",unique_id:t.unique_id},n=kn(t);n&&(e.original_name=n),o[t.entity_id]=e}return{name:Cn(t),type:i?"bess":r?"evse":"unknown",entities:o}}async function DA(t,e,n){const r={type:"config/device_registry/list"},o={type:"config/entity_registry/list"},[a,s]=await Promise.all([n?n.callWS(t,r,{errorId:"fetch:topology"}):t.callWS(r),n?n.callWS(t,o,{errorId:"fetch:topology"}):t.callWS(o)]),c=a.find(t=>t.id===e);if(!c)return{topology:null,panelDevice:null,panelSize:0};const u=function(t){let e="";for(const n of t.identifiers??[]){if(!Array.isArray(n)||n.length<2)continue;const[t,i]=n;t===l&&"string"==typeof i&&(e=i)}return e}(c),d=Cn(c),h=function(t){return[t.name_by_user,t.name].flatMap(t=>t?.trim()?[t.trim()]:[])}(c),p=a.filter(t=>t.parent_device_id===c.id),f=a.filter(t=>t.via_device_id===c.id),g=new Set(p.map(t=>t.id)),m=new Map([c,...p,...f].map(t=>[t.id,t])),v=new Map;for(const t of p)for(const e of t.identifiers??[])e[0]===l&&v.set(e[1],t);const y=new Map;for(const t of s){if("string"!=typeof t.device_id||!m.has(t.device_id))continue;const e=y.get(t.device_id);e?e.push(t):y.set(t.device_id,[t])}const _=y.get(c.id)??[],b=[...y.values()].flat(),x=new Map,w=new Map;for(const t of b)t.entity_id.startsWith("sensor.")?x.set(t.unique_id,t.entity_id):t.entity_id.startsWith("switch.")&&w.set(t.unique_id.toLowerCase(),t.entity_id);const S={};for(const e of b){const n=t.states[e.entity_id];if(!n)continue;const i=n.attributes,r=MA(i.tabs);if(!r)continue;const o=CA(e.unique_id,u);if(!o)continue;const{circuitId:a,panelPrefix:s}=o,l="string"==typeof e.device_id?m.get(e.device_id):void 0,d=l&&g.has(l.id)?l:v.get(kA(u,a)),p=(d?Cn(d):"")||AA(kn(e),h)||(l&&l!==c?TA(Cn(l),h):"")||e.entity_id,f="number"==typeof i.voltage?i.voltage:2===r.length?240:120,y={power:e.entity_id},_=w.get(`${s}_relay_${a}`.toLowerCase());_&&(y.switch=_);const b=x.get(`${s}_${a}_breaker_rating`);b&&(y.breaker_rating=b);const C={tabs:r,name:p,voltage:f,device_type:"string"==typeof i.device_type?i.device_type:"circuit",relay_state:"string"==typeof i.relay_state?i.relay_state:"UNKNOWN",is_user_controllable:!0,breaker_rating_a:null,entities:y};d&&(C.device_id=d.id),S[a]=C}let C=0;for(const e of _){const n=t.states[e.entity_id];if(n&&Kt(n.attributes.panel_size)){C=n.attributes.panel_size;break}}if(C||(C=xA(S)),!C)throw new Error(i("card.panel_size_error"));const k={};for(const t of f)k[t.id]=IA(t,y.get(t.id)??[]);const M={serial:u,firmware:c.sw_version??"",panel_size:C,device_id:e,device_name:d||i("header.default_name"),circuits:S,sub_devices:k};return await pA(t,M),{topology:M,panelDevice:c,panelSize:C}}function PA(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function LA(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)=>LA(t,e[n]));if(!PA(t)||!PA(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=>LA(t[n],e[n]))}const EA=["relay_state","relay_state_target","priority","priority_target"];function NA(t){const e={...t};for(const t of EA)delete e[t];return e}function RA(t){const e=Object.fromEntries(Object.entries(t.circuits).map(([t,e])=>[t,NA(e)]));return{...t,circuits:e}}function OA(t){const e=t.getRootNode();return e instanceof Document||e instanceof ShadowRoot?e.activeElement:null}function zA(t){return null!==t&&OA(t)===t}function HA(t){if(!t)return!1;const e=OA(t);return null!==e&&t.contains(e)}function BA(t){return function(t){if(!t)return null;const e=OA(t);return e instanceof HTMLElement&&t.contains(e)?e:null}(t)?.dataset.role??null}function $A(t,e){t.addEventListener("blur",()=>{queueMicrotask(()=>{t.isConnected&&e()})})}const FA={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 VA(t){t.addEventListener("wheel",e=>{zA(t)&&e.preventDefault()},{passive:!1})}function WA(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 jA(t){return t.circuit.package_ratings_a?.[1]??null}class qA{constructor(t){this._host=t,this._section=null,this._field=null}get element(){return this._section}mount(t){this._field=null;const e=WA(this._host.ratingsView);this._section=e?this._build(e):null,this._section&&t.after(this._section)}sync(t){const e=WA(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=BA(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=jA(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){VA(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()}),$A(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=jA(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?(zA(l)&&a?.focus(),l.remove()):null!==i&&!l&&s&&s.appendChild(this._buildReset(n.uuid)),this._syncWarning(t,n)}_storedInForce(){const t=WA(this._host.ratingsView);return t?jA(t.member):null}_save(t){const e=WA(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&&WA(this._host.ratingsView)?.member.uuid===t&&r.answerRefusal(e)&&(null===document.activeElement||document.activeElement===document.body||HA(n))&&i.focus()}_syncWarning(t,e){const n=t.querySelector('[data-role="rating-warning-region"]');if(!n)return;const i=Le(e.circuit,this._host.ratingsView?.monitoringInfo??null),r=n.firstElementChild instanceof HTMLElement?n.firstElementChild:null;if(r&&r.dataset.kind===i)return;const o=HA(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}}const UA="favorites-changed";async function GA(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 XA={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"};class YA extends HTMLElement{constructor(){super(),this.errorStore=null,this._thresholdReads=0,this._limitFields=[],this.attachShadow({mode:"open"}),this._hass=null,this._config=null,this._debounceTimers={},this._ratingsEditor=new qA(this)}set hass(t){this._hass=t,this.hasAttribute("open")&&this._config&&this._updateLiveState()}get hass(){return this._hass}disconnectedCallback(){this._clearDebounceTimers(),this._config=null}open(t){this._config=t,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;const r=n.querySelector(".subtitle");r&&(r.textContent=this._circuitSubtitle(i)),this._syncMonitoring()}close(){this._clearDebounceTimers(),this.removeAttribute("open"),this.removeAttribute("data-mode"),this._config=null,this.dispatchEvent(new CustomEvent("side-panel-closed",{bubbles:!0,composed:!0}))}_clearDebounceTimers(){for(const t of Object.keys(this._debounceTimers))clearTimeout(this._debounceTimers[t]);this._debounceTimers={}}_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 .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=yn(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-${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-${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._renderGraphHorizonSection(i,e),e.showMonitoring&&this._renderMonitoringSection(i,e)}_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[pe(e),e.length>1&&t.capacityA?r("sidepanel.capacity",{amps:String(t.capacityA)}):"",n.length>0?`${n.join("/")}V`:"",`Tabs [${ue(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=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=Ht(),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",()=>{Bt(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 GA(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(UA)),n?.favorites??{}}(this._hass,n):await async function(t,e){const n=await GA(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(UA)),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=bn(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"===Ue(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.textContent=i("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle";const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{if(!this._hass||"operable"!==Ue(e,this._hass))return;const t=a.checked;this._callService("switch",t?"turn_on":"turn_off",{entity_id:s}).catch(t=>{console.warn("SPAN Panel: relay toggle failed",t),this.errorStore?.add({key:"service:relay",level:"error",message:i("error.relay_failed"),persistent:!1})})}),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.textContent=i("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select";const s=e.entities.select;for(const t of m){const e=g[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",()=>{this._callService("select","select_option",{entity_id:s,option:a.value}).catch(t=>{console.warn("SPAN Panel: shedding update failed",t),this.errorStore?.add({key:"service:shedding",level:"error",message:i("error.shedding_failed"),persistent:!1})})}),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 this._callDomainService("set_circuit_package_ratings",this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return this._callDomainService("clear_circuit_package_ratings",this._ratingsPayload(t,{}))}reportRatingsFailure(t){!function(t,e,n){console.warn("SPAN Panel: package ratings update failed",n),ye(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"]'),r=e.querySelector('input[name="monitoring-mode"][value="custom"]'),o=e.querySelector('[data-role="threshold-fields"]');n&&(n.checked=!0),o&&(o.style.display="none"),this._thresholdReads+=1;const a={circuit_id:t.entities?.power||t.uuid};t.configEntryId&&(a.config_entry_id=t.configEntryId);try{await this._callDomainService("clear_circuit_threshold",a)}catch(e){return console.warn("SPAN Panel: monitoring update failed",e),this.errorStore?.add({key:"service:monitoring",level:"error",message:i("error.threshold_failed"),persistent:!1}),this._config===t&&(r&&(r.checked=!0),o&&(o.style.display="block")),!1}const s=this._config===t?t.monitoringGlobals??null:null;return this._monitoringChanged(t.uuid,{has_override:!1,continuous_threshold_pct:s?.continuous_threshold_pct,spike_threshold_pct:s?.spike_threshold_pct}),!0}async turnOffMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode)&&(!!await this._sendMonitoringEnabled(t,!1)&&(this._showMonitoringEnabled(t.uuid,!1),!0))}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},!0!==e.has_override&&this._showGlobalChoice(),this._syncMonitoring())}_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,HA(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)}_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:Ee(t)}):r("sidepanel.judged_against",{rating:`${t.amps} A`}):r("sidepanel.judged_against",{rating:i("monitoringRating.none")})}({amps:(e=t)?Ae(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";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=Ie(s);l&&a.setAttribute("checked",""),r.appendChild(o),r.appendChild(a),n.appendChild(r);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)}async _sendMonitoringEnabled(t,e){const n={circuit_id:t.entities?.power||t.uuid,monitoring_enabled:e};t.configEntryId&&(n.config_entry_id=t.configEntryId);try{return await this._callDomainService("set_circuit_threshold",n),!0}catch(t){return console.warn("SPAN Panel: monitoring update failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:i("error.threshold_failed"),persistent:!1}),!1}}_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&&HA(r);r.style.display=e?"block":"none",t&&i?.focus()}this._monitoringChanged(t,{monitoring_enabled:e})}_createLimitRow(t,e,n,i,o){const a=XA[e],{min:s,max:l}=FA[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}=FA[e];VA(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()}),$A(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){this._callDomainService("set_circuit_threshold",e).then(()=>this._readThresholds(t,e),t=>{console.warn("SPAN Panel: monitoring update failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:i("error.threshold_failed"),persistent:!1})})}_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){this._hass&&(t.disabled="operable"!==Ue(e,this._hass),qe(e,this._hass)?t.setAttribute("checked",""):t.removeAttribute("checked"))}_applySheddingSelect(t,e){if(!this._hass)return;const n=Ye(e,this._hass);m.includes(n)?t.value=n:t.selectedIndex=-1,t.disabled=!function(t,e){const n=Xe(t,e);return void 0!==n&&Fe.has(n)}(e,this._hass)}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=Ce(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 xe(e?.response)}_callService(t,e,n){return this._hass?Promise.resolve(this._hass.callService(t,e,n)):Promise.resolve()}_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",YA)}catch{}class ZA extends It{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?pt:ut`${this._errors.map(t=>ut` + `,C([Ht({attribute:!1})],wA.prototype,"options",void 0),C([Ht({attribute:!1})],wA.prototype,"data",void 0),C([Ht({type:String})],wA.prototype,"height",void 0);try{customElements.get("span-chart")||customElements.define("span-chart",wA)}catch{}function SA(t,e,n,i,r,a,s,l,c){const{options:u,series:d}=function(t,e,n,i,r,a=!1){n||(n=y[o]);const s=i?"140, 160, 220":"77, 217, 175",l=`rgb(${s})`,c=Date.now(),u=c-e,d=void 0!==n.fixedMin&&void 0!==n.fixedMax,h=(t??[]).filter(t=>t.time>=u).map(t=>[t.time,Math.abs(t.value)]),p=[{type:"line",data:h,showSymbol:!1,smooth:!1,...a?{}:{step:"end"},lineStyle:{width:1.5,color:l},areaStyle:{color:{type:"linear",x:0,y:0,x2:0,y2:1,colorStops:[{offset:0,color:`rgba(${s}, 0.18)`},{offset:1,color:`rgba(${s}, 0.18)`}]}},itemStyle:{color:l}}],f=h.length>0?function(t){let e=0;for(const n of t)n[1]>e&&(e=n[1]);return e}(h):0,g={type:"value",splitNumber:4,axisLabel:{fontSize:10,formatter:f<10?t=>0===t?"0":t.toFixed(1):t=>n.format(t)},splitLine:{lineStyle:{opacity:.15}}};if(d?(g.min=n.fixedMin,g.max=n.fixedMax):f<1&&(g.min=0,g.max=1),r&&"current"===n.entityRole){const t=r.ratingA*r.continuousPct/100,e=r.ratingA*r.spikePct/100;g.min=0,g.max=Math.ceil(1.25*Math.max(t,e,f)),p.push({type:"line",data:[[u,t],[c,t]],showSymbol:!1,lineStyle:{width:1,color:"rgba(255, 200, 40, 0.6)",type:"dashed"},itemStyle:{color:"transparent"},tooltip:{show:!1}}),p.push({type:"line",data:[[u,e],[c,e]],showSymbol:!1,lineStyle:{width:1.5,color:"rgba(255, 60, 60, 0.7)",type:"solid"},itemStyle:{color:"transparent"},tooltip:{show:!1}})}const m={xAxis:{type:"time",min:u,max:c,axisLabel:{fontSize:10},splitLine:{show:!1}},yAxis:g,grid:{top:8,right:4,bottom:0,left:0,containLabel:!0},tooltip:{trigger:"axis",axisPointer:{type:"line",lineStyle:{type:"dashed"}},formatter:t=>{if(!t||0===t.length)return"";const e=t[0],i=new Date(e.value[0]).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}),r=parseFloat(e.value[1].toFixed(2));return`
${i}
${n.format(r)} ${n.unit(r)}
`}},animation:!1};return{options:m,series:p}}(n,i,r,a,l,c),h=s??120;t.style.minHeight=h+"px";let p=t.querySelector("span-chart");p||(p=document.createElement("span-chart"),p.style.display="block",p.style.width="100%",t.innerHTML="",t.appendChild(p));const f=t.clientHeight;p.height=(f>0?f:h)+"px",p.options=u,p.data=d}function CA(t){return null===t?Xt:function(t){return(Math.abs(t)/1e3).toFixed(1)}(t)}function kA(t,e,n,i,r){const o=t.querySelector(".panel-stats");o&&function(t,e,n,i,r){const o="current"===(i.chart_metric||"power"),a=t.querySelector(".stat-consumption .stat-value"),s=t.querySelector(".stat-consumption .stat-unit");if(o){const t=n.panel_entities?.site_power,i=t?e.states[t]:null,r=i?parseFloat(i.attributes?.amperage):NaN;a&&(a.textContent=Number.isFinite(r)?Math.abs(r).toFixed(1):Xt,a.classList.remove("stat-partial")),s&&(s.textContent="A")}else{let t=r;const i=n.panel_entities?.site_power,o=i?e.states[i]:void 0;o&&(t={total:qt(o),partial:!1}),a&&(a.textContent=CA(t?.total??null),a.classList.toggle("stat-partial",t?.partial??!1)),s&&(s.textContent="kW")}const l=t.querySelector(".stat-upstream .stat-value"),c=t.querySelector(".stat-upstream .stat-unit");if(l){const t=n.panel_entities?.current_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;l.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Xt,c&&(c.textContent="A")}else l.textContent=CA(qt(i)),c&&(c.textContent="kW")}const u=t.querySelector(".stat-downstream .stat-value"),d=t.querySelector(".stat-downstream .stat-unit");if(u){const t=n.panel_entities?.feedthrough_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;u.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Xt,d&&(d.textContent="A")}else u.textContent=CA(qt(i)),d&&(d.textContent="kW")}const h=t.querySelector(".stat-solar .stat-value"),p=t.querySelector(".stat-solar .stat-unit");if(h){const t=n.panel_entities?.pv_power,i=t?e.states[t]:null;if(o){const t=i?parseFloat(i.attributes?.amperage):NaN;h.textContent=Number.isFinite(t)?Math.abs(t).toFixed(1):Xt,p&&(p.textContent="A")}else h.textContent=CA(qt(i)),p&&(p.textContent="kW")}const f=t.querySelector(".stat-battery .stat-value");if(f){const t=n.panel_entities?.battery_level,i=qt(t?e.states[t]:void 0);f.textContent=null===i?Xt:`${Math.round(i)}`}const g=t.querySelector(".stat-grid-state .stat-value");if(g){const t=n.panel_entities?.dsm_state,i=t?e.states[t]:null;g.textContent=i?e.formatEntityState?.(i)||i.state:Xt}}(o,e,n,i,r)}function MA(t,e,n,i){const{hass:r,powerHistory:o,horizonMap:a,defaultDurationMs:s,chartMetric:l,monitoringStatus:c}=i,u=cn(n,r),d=hn(n,u),h=ln(n,r),p=t.querySelector(".power-value");p&&(p.innerHTML="current"===l.entityRole?te(un(n,r)):Jt(u)),kn(t,h,_n(n,r),ge(i.topology,e)),t.classList.toggle("circuit-off",!h),t.classList.toggle("circuit-producer",d),In(t,wn(n,r));const f=t.querySelector(".chart-container");if(f){const i=o.get(e)||[],r=t.classList.contains("circuit-col-span")?200:100,u=a?.has(e)?si(a.get(e)):s,h=dn(n),p=Ze(c,n),g=nn(n,p);SA(f,0,i,u,l,d,r,g?{ratingA:g,...Ke(p)}:void 0,h)}}class TA{get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this._retry=t?new Ue(t):null}constructor(){this._errorStore=null,this._retry=null,this._settings=null,this._lastFetch=0,this._fetching=!1}async fetch(t,e){const n=Date.now();if(this._fetching)return this._settings;if(this._settings&&n-this._lastFetch<3e4)return this._settings;this._fetching=!0;try{const n={};e&&(n.config_entry_id=e);const r={type:"call_service",domain:l,service:"get_graph_settings",service_data:n,return_response:!0},o=this._retry?await this._retry.callWS(t,r,{errorId:"fetch:graph_settings",errorMessage:i("error.graph_settings_failed")}):await t.callWS(r);this._settings=o?.response??null,this._lastFetch=Date.now()}catch(t){console.warn("SPAN Panel: graph settings fetch failed",t),this._settings=null,this._retry||this._errorStore?.add({key:"fetch:graph_settings",level:"warning",message:i("error.graph_settings_failed"),persistent:!1})}finally{this._fetching=!1}return this._settings}invalidate(){this._lastFetch=0}get settings(){return this._settings}clear(){this._settings=null,this._lastFetch=0}}function AA(t,e){if(!t)return a;const n=t.circuits?.[e];return n?.has_override?n.horizon:t.global_horizon??a}function IA(t,e){if(!t)return a;const n=t.sub_devices?.[e];return n?.has_override?n.horizon:t.global_horizon??a}function DA(t,e,n){return{members:t?ze(t):[{uuid:e,circuit:n}],capacityA:t&&t.members.length>1?t.circuit.breaker_rating_a??null:null}}class PA{constructor(){this.powerHistory=new Map,this.horizonMap=new Map,this.subDeviceHorizonMap=new Map,this.monitoringCache=new Xe,this.monitoringMultiCache=new Ye,this.graphSettingsCache=new TA,this._errorStore=null,this._hass=null,this._topology=null,this._config=null,this._configEntryId=null,this._favRefs=null,this._favoritesMonitoringStatus=null,this._perPanelInfo=new Map,this._panelFavorites=null,this._showMonitoring=!1,this._updateInterval=null,this._recorderRefreshInterval=null,this._resizeObserver=null,this._lastWidth=0,this._resizeDebounce=null}get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this.monitoringCache.errorStore=t,this.graphSettingsCache.errorStore=t,this.monitoringMultiCache.errorStore=t}get hass(){return this._hass}set hass(t){this._hass=t}get topology(){return this._topology}get config(){return this._config}set showMonitoring(t){this._showMonitoring=t}init(t,e,n,i){this._topology=t,this._config=e,this._hass=n,this._configEntryId=i}setFavoriteRefs(t){this._favRefs=t}clearFavoriteRefs(){this._favRefs=null,this._favoritesMonitoringStatus=null}get monitoringStatus(){return this._favRefs?this._favoritesMonitoringStatus:this.monitoringCache.status}setPanelFavorites(t){this._panelFavorites=t}setFavoritesPerPanelInfo(t){this._perPanelInfo=t??new Map}get _inFavoritesView(){return null!==this._favRefs}get showFavorites(){return this._inFavoritesView||null!==this._panelFavorites}setConfig(t){this._config=t}buildHorizonMaps(t){if(this.horizonMap.clear(),this.subDeviceHorizonMap.clear(),t&&this._topology?.circuits)for(const e of Object.keys(this._topology.circuits))this.horizonMap.set(e,AA(t,e));if(t&&this._topology?.sub_devices)for(const e of Object.keys(this._topology.sub_devices))this.subDeviceHorizonMap.set(e,IA(t,e))}async fetchAndBuildHorizonMaps(){try{this._favRefs?await this._buildFavoritesHorizonMaps():(await this.graphSettingsCache.fetch(this._hass,this._configEntryId),this.buildHorizonMaps(this.graphSettingsCache.settings))}catch(t){console.warn("SPAN Panel: graph settings fetch failed",t),this.graphSettingsCache.errorStore||this._errorStore?.add({key:"fetch:graph_settings",level:"warning",message:i("error.graph_settings_failed"),persistent:!1})}}async fetchMergedMonitoringStatus(t){if(!this._hass||0===t.length)return null;const e=this._hass,n=function(t){let e=!1;const n={},i={};for(const r of t)r&&(e=!0,r.circuits&&Object.assign(n,r.circuits),r.mains&&Object.assign(i,r.mains));return e?{circuits:n,mains:i}:null}(await Promise.all(t.map(t=>this.monitoringMultiCache.fetchOne(e,t))));return this._favoritesMonitoringStatus=n,n}async _buildFavoritesHorizonMaps(){if(!this._hass||!this._favRefs||!this._topology)return;const t=new Set;for(const e of Object.values(this._favRefs))e.configEntryId&&t.add(e.configEntryId);const e=new Map;await Promise.all(Array.from(t).map(async t=>{e.set(t,await this._fetchGraphSettingsFresh(t))})),this.horizonMap.clear(),this.subDeviceHorizonMap.clear();for(const t of Object.keys(this._topology.circuits)){const n=this._favRefs[t],i=n?.configEntryId?e.get(n.configEntryId)??null:null,r=n?.targetId??t;this.horizonMap.set(t,AA(i,r))}if(this._topology.sub_devices)for(const t of Object.keys(this._topology.sub_devices)){const n=this._favRefs[t],i=n?.configEntryId?e.get(n.configEntryId)??null:null,r=n?.targetId??t;this.subDeviceHorizonMap.set(t,IA(i,r))}}async loadHistory(){await mi(this._hass,this._topology,this._config,this.powerHistory,this.horizonMap,this.subDeviceHorizonMap)}recordSamples(){if(!this._topology||!this._hass||!this._config)return;const t=Date.now();for(const[e,n]of Object.entries(this._topology.circuits)){const i=this.horizonMap.get(e)??a;if(!s[i]?.useRealtime)continue;const r=Oe(n,this._config);if(!r)continue;const o=qt(this._hass.states[r]);if(null===o)continue;const l=si(i),c=li(l),u=ci(l),d=t-l,h=this.powerHistory.get(e)??[];h.length>0&&t-h[h.length-1].time0&&t-h[h.length-1].time0&&this._topology)for(const{key:t,devId:e}of gi(this._topology))n.has(e)&&r.add(t);const o=new Map;try{await mi(this._hass,this._topology,this._config,o,e,n);for(const t of e.keys()){const e=o.get(t);e?this.powerHistory.set(t,e):this.powerHistory.delete(t)}for(const t of r){const e=o.get(t);e?this.powerHistory.set(t,e):this.powerHistory.delete(t)}this.updateDOM(t)}catch(t){console.warn("SPAN Panel: history refresh failed",t),this._errorStore?.add({key:"fetch:history",level:"warning",message:i("error.history_failed"),persistent:!1})}}updateDOM(t){this._hass&&this._topology&&this._config&&(function(t,e,n,i,r,o,a){if(!t||!n||!e)return;const s=ai(i),l=$e(n),c=[];for(const{circuit:t}of l){if(!t.entities?.power||dn(t)||Ie(t))continue;const n=cn(t,e);c.push(null===n?null:Math.abs(n))}kA(t,e,n,i,function(t){let e=null,n=!1;for(const i of t)null===i?n=!0:e=null===e?i:e+i;return{total:e,partial:n&&null!==e}}(c));const u={hass:e,topology:n,powerHistory:r,horizonMap:o,defaultDurationMs:s,chartMetric:Re(i),monitoringStatus:a};for(const e of l)for(const n of ze(e)){const i=t.querySelector(`.circuit-slot[data-uuid="${Ln(n.uuid)}"]`);if(!i)continue;const r=n.uuid===e.uuid?e.circuit:Be(n.circuit,e);MA(i,n.uuid,r,u)}}(t,this._hass,this._topology,this._config,this.powerHistory,this.horizonMap,this.monitoringStatus),function(t,e,n,i,r,o){if(!n.sub_devices)return;const a=ai(i);for(const[i,s]of Object.entries(n.sub_devices)){const n=t.querySelector(`[data-subdev="${Ln(i)}"]`);if(!n)continue;const l=Wn(s);if(l.headlineEid){const t=n.querySelector(".sub-power-value");t&&(t.innerHTML=Qt(Un(e,l.headlineEid)))}if(l.siteTotalEid){const t=Un(e,l.siteTotalEid),i=n.querySelector(".sub-site-total-value");i&&(i.innerHTML=Qt(t));const r=i?.closest(".sub-entity");r&&(r.hidden=null===t)}const c=n.querySelectorAll("[data-chart-key]");for(const t of c){const e=t.dataset.chartKey;if(!e)continue;const n=r.get(e)||[];let s=_.power;e.endsWith("_soc")?s=_.soc:e.endsWith("_soe")&&(s=_.soe);const l=!!t.closest(".bess-chart-col");SA(t,0,n,o?.has(i)?si(o.get(i)):a,s,!1,l?120:150,void 0,e.endsWith("_soc")||e.endsWith("_soe"))}for(const t of Object.keys(s.entities||{})){const i=n.querySelector(`[data-eid="${Ln(t)}"]`);if(!i)continue;const r=e.states[t];if(r){let t;if(e.formatEntityState)t=e.formatEntityState(r);else{t=r.state;const e=r.attributes.unit_of_measurement||"";e&&(t+=" "+e)}if("Wh"===(r.attributes.unit_of_measurement||"")){const e=qt(r);null!==e&&(t=(e/1e3).toFixed(1)+" kWh")}i.textContent=t}}}}(t,this._hass,this._topology,this._config,this.powerHistory,this.subDeviceHorizonMap),function(t,e,n,i){for(const[r,o]of En(n)){const n=t.querySelector(`.meter-tile[data-meter-uuid="${Ln(r)}"] .meter-readings`);n&&(n.innerHTML=On(o,e,i))}}(t,this._hass,this._topology,this._config))}async onGraphSettingsChanged(t){if(this._hass){this._favRefs?await this._buildFavoritesHorizonMaps():(this.graphSettingsCache.invalidate(),await this.graphSettingsCache.fetch(this._hass,this._configEntryId),this.buildHorizonMaps(this.graphSettingsCache.settings)),this.powerHistory.clear();try{await this.loadHistory()}catch{}this.updateDOM(t)}}onToggleClick(t,e){const n=t.target,i=n?.closest(".toggle-pill");if(!i)return;const r=e.querySelector(".slide-confirm");if(!r||!r.classList.contains("confirmed"))return;t.stopPropagation(),t.preventDefault();const o=i.closest("[data-uuid]");if(!o||!this._topology||!this._hass)return;const a=o.dataset.uuid;if(!a)return;const s=this._topology.circuits[a];if(!s)return;const l=s.entities?.switch;if(!l)return;if("operable"!==_n(s,this._hass))return;const c=ge(this._topology,a);if(!c.mayOperate)return void this._errorStore?.add({key:"service:relay",level:"warning",message:_e(c),persistent:!1});const u=this._hass;xe(u,c).setRelay(l,"on"!==u.states[l]?.state).catch(t=>Ce(u,this._errorStore,t,"relay"))}async onGearClick(t,e){const n=t.target,i=n?.closest(".gear-icon");if(!i)return;const r=e.querySelector("span-side-panel");if(!r||!this._hass)return;if(r.hass=this._hass,r.errorStore=this.errorStore,i.classList.contains("panel-gear")){if(this._inFavoritesView){const t=await this._buildFavoritesSections();if(0===t.length)return;return void r.open({favoritesMode:!0,perPanelSections:t})}if(!this._topology)return;return await this.graphSettingsCache.fetch(this._hass,this._configEntryId),void r.open({panelMode:!0,topology:this._topology,graphSettings:this.graphSettingsCache.settings,showFavorites:null!==this._panelFavorites,favoritePanelDeviceId:this._panelFavorites?.panelDeviceId,favoriteCircuitUuids:this._panelFavorites?.circuitUuids,favoriteSubDeviceIds:this._panelFavorites?.subDeviceIds,configEntryId:this._configEntryId})}const o=i.dataset.uuid;if(o&&this._topology){const t=this._topology.circuits[o];if(t){const e=this._favRefs?.[o]??null,n=e&&"circuit"===e.kind?e.targetId:o,i=e?.configEntryId??this._configEntryId;let s,l;e?[s,l]=await Promise.all([this._fetchGraphSettingsFresh(i),this._fetchMonitoringStatusFresh(i)]):(await Promise.all([this.graphSettingsCache.fetch(this._hass,i),this.monitoringCache.fetch(this._hass,i)]),s=this.graphSettingsCache.settings,l=this.monitoringCache.status);const c=Ze(l,t),u=s?.global_horizon??a,d=s?.circuits?.[n],h=d?{...d,globalHorizon:u}:{horizon:u,has_override:!1,globalHorizon:u},p=e?.panelDeviceId??this._panelFavorites?.panelDeviceId,f=null!==e||(this._panelFavorites?.circuitUuids.has(n)??!1),g=this._sidePanelSlot(o,e),m=e?this._perPanelInfo.get(e.panelDeviceId)?.topology:this._topology,v={uuid:n,name:t.name,entities:t.entities,...DA(g,n,t),is_user_controllable:t.is_user_controllable,always_on:t.always_on,relay_state:t.relay_state,priority:t.priority,device_type:t.device_type,monitoringInfo:c,monitoringGlobals:l?.global_settings??null,showMonitoring:this._showMonitoring,monitoringRatingOffered:!0===m?.monitoring_rating_offered,graphHorizonInfo:h,showFavorites:this.showFavorites,favoritePanelDeviceId:p,isFavorite:f,configEntryId:i,controlAccess:ge(this._topology,o)};return void r.open(v)}}const s=i.dataset.subdevId;if(s&&this._topology?.sub_devices?.[s]){const t=this._topology.sub_devices[s],e=this._favRefs?.[s]??null,n=e&&"sub_device"===e.kind?e.targetId:s,i=e?.configEntryId??this._configEntryId;let o;e?o=await this._fetchGraphSettingsFresh(i):(await this.graphSettingsCache.fetch(this._hass,i),o=this.graphSettingsCache.settings);const l=o?.global_horizon??a,c=o?.sub_devices?.[n],u=c?{...c,globalHorizon:l}:{horizon:l,has_override:!1,globalHorizon:l},d=e?.panelDeviceId??this._panelFavorites?.panelDeviceId,h=null!==e||(this._panelFavorites?.subDeviceIds.has(n)??!1);r.open({subDeviceMode:!0,subDeviceId:n,name:t.name??n,deviceType:t.type??"",entities:t.entities,hasChart:qn(t).length>0,graphHorizonInfo:u,showFavorites:this.showFavorites,favoritePanelDeviceId:d,isFavorite:h,configEntryId:i})}}_sidePanelSlot(t,e){const n="circuit"===e?.kind?this._perPanelInfo.get(e.panelDeviceId)?.topology:void 0;return n&&e?He($e(n)).get(e.targetId):this._topology?He($e(this._topology)).get(t):void 0}async refreshCircuitSidePanel(t,e,n,i=null){const r=t.querySelector("span-side-panel"),o=r?.openCircuit;if(!r||!o||o.configEntryId!==e)return;const a=n.circuits[o.uuid];if(!a)return;const s=He($e(n)).get(o.uuid);if(i&&!(s?.memberIds??[o.uuid]).some(t=>i.has(t)))return;const l=await this._fetchMonitoringStatusFresh(e);if(r.openCircuit?.uuid!==o.uuid)return;const c=Ze(l,a);r.refreshRating({...DA(s,o.uuid,a),monitoringInfo:c,monitoringGlobals:l?.global_settings??null})}refreshCircuitControlAccess(t,e,n){const i=t.querySelector("span-side-panel"),r=i?.openCircuit;i&&r&&r.configEntryId===e&&i.refreshControlAccess(pe(n))}async _buildFavoritesSections(){if(!this._hass||!this._favRefs)return[];const t=function(t,e){const n=new Map;for(const i of Object.values(t)){if("circuit"!==i.kind)continue;const t=e.get(i.panelDeviceId);if(void 0===t)continue;let r=n.get(i.panelDeviceId);void 0===r&&(r={panelDeviceId:i.panelDeviceId,panelName:t.panelName,topology:t.topology,configEntryId:t.configEntryId,favoriteCircuitUuids:new Set},n.set(i.panelDeviceId,r)),r.favoriteCircuitUuids.add(i.targetId)}return Array.from(n.values()).sort((t,e)=>t.panelName.localeCompare(e.panelName))}(this._favRefs,this._perPanelInfo);if(0===t.length)return[];return await Promise.all(t.map(async t=>({panelDeviceId:t.panelDeviceId,panelName:t.panelName,topology:t.topology,graphSettings:await this._fetchGraphSettingsFresh(t.configEntryId),favoriteCircuitUuids:t.favoriteCircuitUuids,configEntryId:t.configEntryId})))}async _fetchGraphSettingsFresh(t){if(!this._hass)return null;try{const e={};t&&(e.config_entry_id=t);const n={type:"call_service",domain:l,service:"get_graph_settings",service_data:e,return_response:!0},r=this._errorStore?new Ue(this._errorStore):null,o=r?await r.callWS(this._hass,n,{errorId:"fetch:graph_settings",errorMessage:i("error.graph_settings_failed")}):await this._hass.callWS(n);return o?.response??null}catch(t){return console.warn("SPAN Panel: fresh graph settings fetch failed",t),null}}async _fetchMonitoringStatusFresh(t){if(!this._hass)return null;try{const e={};t&&(e.config_entry_id=t);const n={type:"call_service",domain:l,service:"get_monitoring_status",service_data:e,return_response:!0},r=this._errorStore?new Ue(this._errorStore):null,o=r?await r.callWS(this._hass,n,{errorId:"fetch:monitoring",errorMessage:i("error.monitoring_failed")}):await this._hass.callWS(n);return Ge(o?.response)}catch(t){return console.warn("SPAN Panel: fresh monitoring status fetch failed",t),null}}bindSlideConfirm(t,e){if(t.classList.contains("slide-confirm-forbidden"))return;const n=t.querySelector(".slide-confirm-knob"),i=t.querySelector(".slide-confirm-text");if(!n||!i)return;let r=!1,o=0,a=0;const s=e=>{t.classList.contains("confirmed")||(r=!0,o=e-n.offsetLeft,a=t.offsetWidth-n.offsetWidth-4,n.classList.remove("snapping"))},l=t=>{if(!r)return;const e=Math.max(2,Math.min(t-o,a));n.style.left=e+"px"},c=()=>{if(!r)return;r=!1;(n.offsetLeft-2)/a>=.9?(n.style.left=a+"px",t.classList.add("confirmed"),n.querySelector("span-icon")?.setAttribute("icon","mdi:lock-open"),i.textContent=t.dataset.textOn??"",e&&e.classList.remove("switches-disabled")):(n.classList.add("snapping"),n.style.left="2px")};n.addEventListener("mousedown",t=>{t.preventDefault(),s(t.clientX)}),t.addEventListener("mousemove",t=>l(t.clientX)),t.addEventListener("mouseup",c),t.addEventListener("mouseleave",c),n.addEventListener("touchstart",t=>{t.preventDefault(),s(t.touches[0].clientX)},{passive:!1}),t.addEventListener("touchmove",t=>l(t.touches[0].clientX),{passive:!0}),t.addEventListener("touchend",c),t.addEventListener("touchcancel",c),t.addEventListener("click",()=>{t.classList.contains("confirmed")&&(t.classList.remove("confirmed"),n.classList.add("snapping"),n.style.left="2px",n.querySelector("span-icon")?.setAttribute("icon","mdi:lock"),i.textContent=t.dataset.textOff??"",e&&e.classList.add("switches-disabled"))})}startIntervals(t,e){this._updateInterval=setInterval(()=>{this.recordSamples(),this.updateDOM(t),e&&e()},1e3),this._recorderRefreshInterval=setInterval(()=>{this.refreshRecorderData(t)},3e4)}stopIntervals(){this._updateInterval&&(clearInterval(this._updateInterval),this._updateInterval=null),this._recorderRefreshInterval&&(clearInterval(this._recorderRefreshInterval),this._recorderRefreshInterval=null),this.cleanupResizeObserver()}setupResizeObserver(t,e){this.cleanupResizeObserver(),e&&(this._lastWidth=e.clientWidth,this._resizeObserver=new ResizeObserver(e=>{const n=e[0];if(!n)return;const i=n.contentRect.width;Math.abs(i-this._lastWidth)<5||(this._lastWidth=i,this._resizeDebounce&&clearTimeout(this._resizeDebounce),this._resizeDebounce=setTimeout(()=>{for(const e of t.querySelectorAll(".chart-container")){const t=e.querySelector("span-chart");t&&t.remove()}this.updateDOM(t)},150))}),this._resizeObserver.observe(e))}cleanupResizeObserver(){this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),this._resizeDebounce&&(clearTimeout(this._resizeDebounce),this._resizeDebounce=null)}reset(){this.powerHistory.clear(),this.horizonMap.clear(),this.subDeviceHorizonMap.clear(),this.monitoringCache.clear(),this.monitoringMultiCache.clear(),this.graphSettingsCache.clear()}}function LA(t=""){const e=t?` value="${Ft(t)}"`:"",n=t?"":"display:none;";return`\n
\n \n \n
\n `}function EA(t,e,n,r,o,a,s,l,c){const u=ln(e,n),d=_n(e,n),h=Ve([e]),p=Ft(e.name||i("grid.unknown")),f="current"===Re(r).entityRole;let g;g=u?f?te(un(e,n)):Jt(cn(e,n)):"";const m=An(a||"unknown");let v="";const y=pn(l,n,o);null!==y&&(v=`${Math.round(y)}%`);const _=``,b=Ie(e)?"":"none"===d?`${u?"ON":"OFF"}`:Cn(u,d,c);return`\n
\n ${h?`${h}`:""}\n ${v}\n ${p}\n ${m}\n ${b}\n \n ${g}\n \n ${_}\n \n
\n `}function NA(t,e,n,i,r){const o=hn(e,cn(e,n)),a=sn(0,r,ln(e,n),o),s=Ft(t);return`\n
\n
\n
\n
\n
\n `}function RA(t){return`
${Ft(t)}
`}function OA(t,e){const n=e.hysteresisPx??48,i=new WeakSet;let r=null;const o=t=>{const n=t.querySelector(e.nameSelector);return!!n&&(0!==t.clientWidth&&(n.clientWidth<1||n.scrollWidth>n.clientWidth+1))},a=()=>{const i=t.querySelectorAll(e.rowSelector);if(0===i.length)return;const a=i[0].clientWidth;if(0===a)return;if(null!==r){if(a>r+n){for(const t of i)t.classList.remove(e.foldClass);r=null}else for(const t of i)t.classList.add(e.foldClass);return}let s=!1;for(const t of i)if(o(t)){s=!0;break}if(s){for(const t of i)t.classList.add(e.foldClass);r=a}},s=new ResizeObserver(()=>a()),l=()=>{const n=t.querySelectorAll(e.rowSelector);for(const t of n)i.has(t)||(i.add(t),s.observe(t));requestAnimationFrame(()=>a())};l();const c=new MutationObserver(t=>{(t=>{const n=t=>{for(const n of t)if(n instanceof Element){if(n.matches(e.rowSelector))return!0;if(n.querySelector(e.rowSelector))return!0}return!1};for(const e of t)if(n(e.addedNodes)||n(e.removedNodes))return!0;return!1})(t)&&l()});return c.observe(t,{childList:!0,subtree:!0}),()=>{s.disconnect(),c.disconnect()}}function zA(t,e,n){return{isOn:ln(t,e),value:"current"===(n.chart_metric||"power")?un(t,e):cn(t,e)}}function HA(t,e,n,i){const r=zA(t,n,i),o=zA(e,n,i);return r.isOn&&!o.isOn?-1:!r.isOn&&o.isOn?1:null===r.value||null===o.value?r.value===o.value?0:null===r.value?1:-1:Math.abs(o.value)-Math.abs(r.value)}function BA(t,e,n){return t.sort((t,i)=>HA(t[1],i[1],e,n))}class $A{constructor(t){this._expandedUuids=new Set,this._searchQuery="",this._container=null,this._clickHandler=null,this._inputHandler=null,this._graphSettingsHandler=null,this._hass=null,this._topology=null,this._config=null,this._monitoringStatus=null,this._viewName=null,this._columns=1,this._foldUnobserve=null,this._ctrl=t}setColumns(t){const e=Math.max(1,Math.min(3,Math.floor(t)));this._columns=e}setInitialExpansion(t){this._expandedUuids=new Set(t)}setInitialSearchQuery(t){this._searchQuery=t}setViewName(t){this._viewName=t}renderActivityView(t,e,n,i,r,o){this._unbindEvents(),this._hass=e,this._topology=n,this._config=i,this._monitoringStatus=r;const a=BA(Object.entries(n.circuits),e,i),s=He($e(n));let l=o+LA(this._searchQuery);l+=`
`;for(const[t,o]of a){const a=Ze(r,o),c=wn(o,e),u=this._expandedUuids.has(t);l+=`
`,l+=EA(t,o,e,i,a,c,u,Be(o,s.get(t)),ge(n,t)),u&&(l+=NA(t,o,e,0,a)),l+="
"}l+="
",l+="",t.innerHTML=l;const c=t.querySelector("span-side-panel");c&&(c.hass=e,c.errorStore=this._ctrl.errorStore),this._bindEvents(t),this._searchQuery&&this._applyFilter(t),this._ctrl.updateDOM(t),this._attachFoldObserver(t)}renderAreaView(t,e,n,r,o,a){this._unbindEvents(),this._hass=e,this._topology=n,this._config=r,this._monitoringStatus=o;const s=i("list.unassigned_area"),l=He($e(n)),c=new Map;for(const[t,e]of Object.entries(n.circuits)){const n=e.area??s,i=c.get(n);i?i.push([t,e]):c.set(n,[[t,e]])}const u=[...c.keys()].sort((t,e)=>t===s?1:e===s?-1:t.localeCompare(e));let d=a+LA(this._searchQuery);d+=`
`;for(const t of u){const i=c.get(t);if(!i)continue;const a=BA(i,e,r);d+=RA(t);for(const[t,i]of a){const a=Ze(o,i),s=wn(i,e),c=this._expandedUuids.has(t);d+=`
`,d+=EA(t,i,e,r,a,s,c,Be(i,l.get(t)),ge(n,t)),c&&(d+=NA(t,i,e,0,a)),d+="
"}}d+="
",d+="",t.innerHTML=d;const h=t.querySelector("span-side-panel");h&&(h.hass=e,h.errorStore=this._ctrl.errorStore),this._bindEvents(t),this._searchQuery&&this._applyFilter(t),this._ctrl.updateDOM(t),this._attachFoldObserver(t)}updateCollapsedRows(t,e,n,i){const r="current"===Re(i).entityRole,o=t.querySelectorAll(".list-row[data-row-uuid]");for(const t of o){const o=t.dataset.rowUuid;if(!o)continue;const a=n.circuits[o];if(!a)continue;const{isOn:s,value:l}=zA(a,e,i),c=t.querySelector(".list-power-value");c&&(c.innerHTML=s?r?te(l):Jt(l):""),kn(t,s,_n(a,e),ge(n,o)),In(t,wn(a,e));const u=t.querySelector(".list-status-badge");u&&(u.textContent=s?"ON":"OFF",u.classList.toggle("list-status-on",s),u.classList.toggle("list-status-off",!s)),t.classList.toggle("circuit-off",!s)}!function(t,e,n,i){const r=t.querySelector(".list-view");if(r)for(const t of function(t,e){let n={anchor:null,units:[]};const i=[n];for(const r of[...t.children])if(r.classList.contains("area-header"))n={anchor:r,units:[]},i.push(n);else if(r.classList.contains("list-cell")){const t=r.dataset.cellUuid,i=t?e.circuits[t]:void 0;t&&i&&n.units.push({cell:r,uuid:t,circuit:i})}return i}(r,n)){if(t.units.length<2)continue;const n=[...t.units].sort((t,n)=>HA(t.circuit,n.circuit,e,i));if(!n.some((e,n)=>e.uuid!==t.units[n].uuid))continue;let o=t.anchor;for(const t of n)o?o.after(t.cell):r.prepend(t.cell),o=t.cell}}(t,e,n,i)}stop(){this._unbindEvents(),null===this._viewName&&(this._expandedUuids.clear(),this._searchQuery=""),this._hass=null,this._topology=null,this._config=null,this._monitoringStatus=null}_dispatchFavoritesViewState(){if(!this._viewName||!this._container)return;const t={view:this._viewName,expanded:[...this._expandedUuids],searchQuery:this._searchQuery};this._container.dispatchEvent(new CustomEvent("favorites-view-state-changed",{detail:t,bubbles:!0,composed:!0}))}_bindEvents(t){this._container=t,this._clickHandler=e=>{const n=e.target;if(!n)return;const i=n.closest(".list-expand-toggle");if(i){const t=i.dataset.expandUuid;return void(t&&this._toggleExpand(t))}if(n.closest(".gear-icon"))return void this._ctrl.onGearClick(e,t);if(n.closest(".toggle-pill"))return void this._ctrl.onToggleClick(e,t);if(n.closest(".list-search-clear")){const e=t.querySelector(".list-search");return void(e&&(e.value="",e.dispatchEvent(new Event("input",{bubbles:!0}))))}const r=n.closest(".unit-btn");if(r){const e=r.dataset.unit;e&&t.dispatchEvent(new CustomEvent("unit-changed",{detail:e,bubbles:!0,composed:!0}))}},this._inputHandler=e=>{const n=e.target;n&&n.classList.contains("list-search")&&(this._searchQuery=n.value.toLowerCase(),this._applyFilter(t),this._dispatchFavoritesViewState())},this._graphSettingsHandler=()=>{this._ctrl.onGraphSettingsChanged(t).then(()=>{this._ctrl.updateDOM(t)}).catch(()=>{})},t.addEventListener("click",this._clickHandler),t.addEventListener("input",this._inputHandler),t.addEventListener("graph-settings-changed",this._graphSettingsHandler);const e=t.querySelector(".slide-confirm");e&&(this._ctrl.bindSlideConfirm(e,t),t.classList.add("switches-disabled"))}_unbindEvents(){this._container&&(this._clickHandler&&this._container.removeEventListener("click",this._clickHandler),this._inputHandler&&this._container.removeEventListener("input",this._inputHandler),this._graphSettingsHandler&&this._container.removeEventListener("graph-settings-changed",this._graphSettingsHandler)),this._foldUnobserve&&(this._foldUnobserve(),this._foldUnobserve=null),this._container=null,this._clickHandler=null,this._inputHandler=null,this._graphSettingsHandler=null}_attachFoldObserver(t){this._foldUnobserve&&(this._foldUnobserve(),this._foldUnobserve=null),this._foldUnobserve=OA(t,{rowSelector:".list-row",nameSelector:".list-circuit-name",foldClass:"is-folded"})}_applyFilter(t){const e=t.querySelector(".list-search-clear");e&&(e.style.display=this._searchQuery?"":"none");const n=t.querySelectorAll(".list-cell[data-cell-uuid]");for(const t of n){const e=t.querySelector(".list-circuit-name"),n=(e?.textContent?.toLowerCase()??"").includes(this._searchQuery);t.style.display=n?"":"none"}const i=t.querySelectorAll(".area-header");for(const t of i){let e=!1,n=t.nextElementSibling;for(;n&&!n.classList.contains("area-header");){if(n.classList.contains("list-cell")&&"none"!==n.style.display){e=!0;break}n=n.nextElementSibling}t.style.display=e?"":"none"}}_toggleExpand(t){if(!(this._container&&this._hass&&this._topology&&this._config))return;const e=Ln(t),n=this._container.querySelector(`.list-cell[data-cell-uuid="${e}"]`);if(!n)return;const i=n.querySelector(`.list-row[data-row-uuid="${e}"]`),r=n.querySelector(`.list-expand-toggle[data-expand-uuid="${e}"]`);if(i){if(this._expandedUuids.has(t)){this._expandedUuids.delete(t);const o=n.querySelector(`.list-expanded-content[data-expanded-uuid="${e}"]`);o&&o.remove(),r&&r.classList.remove("expanded"),i.classList.remove("list-row-expanded")}else{this._expandedUuids.add(t);const e=this._topology.circuits[t];if(!e)return;const n=Ze(this._monitoringStatus,e),o=NA(t,e,this._hass,this._config,n);i.insertAdjacentHTML("afterend",o),r&&r.classList.add("expanded"),i.classList.add("list-row-expanded"),this._ctrl.updateDOM(this._container)}this._dispatchFavoritesViewState()}}}const FA=["entity_registry_updated","area_registry_updated","device_registry_updated"];async function VA(t,e){const[n,i,r]=await Promise.all([t.callWS({type:"config/area_registry/list"}),t.callWS({type:"config/entity_registry/list"}),t.callWS({type:"config/device_registry/list"})]),o=new Map;for(const t of n)o.set(t.area_id,t.name);const a=new Map,s=new Map;for(const t of i)t.area_id&&a.set(t.entity_id,t.area_id),t.device_id&&s.set(t.entity_id,t.device_id);const l=new Map;for(const t of r)t.area_id&&l.set(t.id,t.area_id);const c=e.panel_device_id??e.device_id,u=t=>t?l.get(t):void 0;for(const t of Object.values(e.circuits)){const e=Object.values(t.entities).filter(t=>!!t),n=[u(t.device_id),...e.map(t=>a.get(t)),...e.map(t=>u(s.get(t))),u(c)];t.area=n.map(t=>t?o.get(t):void 0).find(t=>!!t)}}const WA=["name","name_by_user"];async function jA(t,e,n){const i=t.connection;return i?i.subscribeEvents(t=>{const i=function(t){if("object"!=typeof t||null===t||!("data"in t))return null;const{data:e}=t;if("object"!=typeof e||null===e)return null;if(!("action"in e)||"update"!==e.action)return null;if(!("device_id"in e)||"string"!=typeof e.device_id)return null;if(!("changes"in e))return null;const{changes:n}=e;return"object"!=typeof n||null===n?null:WA.some(t=>t in n)?e.device_id:null}(t),r=i?e():null;i&&r&&function(t,e){return(t.panel_device_id??t.device_id)===e||!!Object.keys(t.sub_devices??{}).includes(e)||Object.values(t.circuits).some(t=>t.device_id===e)}(r,i)&&n()},"device_registry_updated"):()=>{}}const qA="loaded";function UA(t){if("object"!=typeof t||null===t||!("data"in t))return null;const{data:e}=t;return"object"==typeof e&&null!==e?e:null}async function GA(t,e,n){const i=t.connection;return i?i.subscribeEvents(t=>{(function(t){const e=UA(t);return e&&"config_entry_id"in e&&"string"==typeof e.config_entry_id?e.config_entry_id:null})(t)===e&&n(function(t){const e=UA(t);if(!e||!("circuit_ids"in e)||!Array.isArray(e.circuit_ids))return null;const n=e.circuit_ids;return n.every(t=>"string"==typeof t)?new Set(n):null}(t))},"span_panel_package_ratings_changed"):()=>{}}class XA{constructor(){this._persistent=new Map,this._transient=null,this._transientTimer=null,this._subscribers=new Set,this._watchedPanels=new Map}add(t){const e={...t,timestamp:Date.now()};if(e.persistent)this._persistent.set(e.key,e);else{this._clearTransient(),this._transient=e;const t=e.ttl??5e3;this._transientTimer=setTimeout(()=>{this._transient=null,this._transientTimer=null,this._notify()},t)}this._notify()}remove(t){if(this._persistent.has(t))return this._persistent.delete(t),void this._notify();this._transient?.key===t&&(this._clearTransient(),this._notify())}clear(t){void 0===t?(this._persistent.clear(),this._clearTransient(),this._watchedPanels.clear()):!0===t.persistent?this._persistent.clear():!1===t.persistent&&this._clearTransient(),this._notify()}get active(){const t=[...this._persistent.values()];return null!==this._transient&&t.push(this._transient),t}hasPersistent(t){return this._persistent.has(t)}hasAnyPanelOffline(){for(const t of this._persistent.keys())if("panel-offline"===t||t.startsWith("panel-offline:"))return!0;return!1}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}watchPanelStatus(t){this.watchPanelStatuses([{entityId:t,panelName:null}])}watchPanelStatuses(t){const e=this._watchedPanels,n=new Map;for(const i of t){const t=e.get(i.entityId);n.set(i.entityId,{panelName:i.panelName??null,wasOffline:t?.wasOffline??!1})}const i=this._isSingleUnnamed(e),r=this._isSingleUnnamed(n);for(const t of e.keys()){n.has(t)&&i===r||this._persistent.delete(this._offlineKey(t,i))}this._watchedPanels=n,this._notify()}clearPanelStatusWatch(){if(0===this._watchedPanels.size)return;const t=this._isSingleUnnamed(this._watchedPanels);for(const e of this._watchedPanels.keys())this._persistent.delete(this._offlineKey(e,t));this._watchedPanels.clear(),this._notify()}updateHass(t){if(0===this._watchedPanels.size)return;const e=this._isSingleUnnamed(this._watchedPanels);for(const[n,o]of this._watchedPanels){const a=t.states[n]?.state,s="on"===a,l=this._offlineKey(n,e),c=this._reconnectKey(n,e);if(s){const t=o.wasOffline;o.wasOffline=!1,this.remove(l),t&&this.add({key:c,level:"info",message:null===o.panelName?i("error.panel_reconnected"):r("error.panel_reconnected_named",{name:o.panelName}),persistent:!1})}else o.wasOffline=!0,this.hasPersistent(l)||this.add({key:l,level:"error",message:null===o.panelName?i("error.panel_offline"):r("error.panel_offline_named",{name:o.panelName}),persistent:!0})}}dispose(){this._clearTransient(),this._persistent.clear(),this._subscribers.clear(),this._watchedPanels.clear()}_isSingleUnnamed(t){if(1!==t.size)return!1;for(const e of t.values())return null===e.panelName;return!1}_offlineKey(t,e){return e?"panel-offline":`panel-offline:${t}`}_reconnectKey(t,e){return e?"panel-reconnected":`panel-reconnected:${t}`}_clearTransient(){null!==this._transientTimer&&(clearTimeout(this._transientTimer),this._transientTimer=null),this._transient=null}_notify(){for(const t of this._subscribers)try{t()}catch(t){console.warn("SPAN Panel: error-store subscriber threw",t)}}}async function YA(t,e,n){if(!e)throw new Error(i("card.device_not_found"));const r={type:`${l}/panel_topology`,device_id:e},o=n?await n.callWS(t,r,{errorId:"fetch:topology"}):await t.callWS(r),a=Ae(o.panel_size)?o.panel_size:ZA(o.circuits);if(!De(o,a))throw new Error(i("card.topology_error"));const s={type:"config/device_registry/list"},c=n?await n.callWS(t,s,{errorId:"fetch:topology"}):await t.callWS(s),u=o.panel_device_id??e,d=c.find(t=>t.id===u)??null;return function(t,e){const n=new Map(e.map(t=>[t.id,t]));for(const e of Object.values(t)){const t=e.device_id?n.get(e.device_id):void 0,i=t?Qn(t):"";i&&(e.name=i)}}(o.circuits,c),await VA(t,o),{topology:o,panelDevice:d,panelSize:a}}function ZA(t){let e=0;for(const n of Object.values(t))if(n&&!Ie(n))for(const t of n.tabs)t>e&&(e=t);return e>0?e+e%2:0}const KA="_power",QA="Power";function JA(t,e){if(!t.endsWith(KA))return null;const n=`span_${e.toLowerCase()}_`,i=e&&t.startsWith(n)?t.slice(n.length,-6):t.split("_").slice(2,-1).join("_");return i?{circuitId:i,panelPrefix:t.slice(0,-(i.length+6+1))}:null}function tI(t,e){return`${t}_circuit_${e}`}function eI(t){if("string"!=typeof t||!t.startsWith("tabs ["))return null;const e=t.slice(6,-1),n=e.includes(":")?e.split(":").map(Number):[Number(e)];return n.every(Number.isFinite)?n:null}function nI(t,e){const n=e.filter(e=>t.startsWith(`${e} `)).sort((t,e)=>e.length-t.length)[0];return void 0===n?t:t.slice(n.length+1)}function iI(t,e){if(t===QA)return"";return nI(t.endsWith(` ${QA}`)?t.slice(0,-6):t,e)}function rI(t,e){const n=(t.model??"").toLowerCase(),i=n.includes("battery")||(t.identifiers??[]).some(t=>t[1].toLowerCase().includes("bess")),r=n.includes("drive")||(t.identifiers??[]).some(t=>t[1].toLowerCase().includes("evse")),o={};for(const t of e){const e={domain:t.entity_id.split(".")[0]??"",unique_id:t.unique_id},n=Jn(t);n&&(e.original_name=n),o[t.entity_id]=e}return{name:Qn(t),type:i?"bess":r?"evse":"unknown",entities:o}}async function oI(t,e,n){const r={type:"config/device_registry/list"},o={type:"config/entity_registry/list"},[a,s]=await Promise.all([n?n.callWS(t,r,{errorId:"fetch:topology"}):t.callWS(r),n?n.callWS(t,o,{errorId:"fetch:topology"}):t.callWS(o)]),c=a.find(t=>t.id===e);if(!c)return{topology:null,panelDevice:null,panelSize:0};const u=function(t){let e="";for(const n of t.identifiers??[]){if(!Array.isArray(n)||n.length<2)continue;const[t,i]=n;t===l&&"string"==typeof i&&(e=i)}return e}(c),d=Qn(c),h=function(t){return[t.name_by_user,t.name].flatMap(t=>t?.trim()?[t.trim()]:[])}(c),p=a.filter(t=>t.parent_device_id===c.id&&Kn(t,c)),f=a.filter(t=>t.via_device_id===c.id&&Kn(t,c)),g=new Set(p.map(t=>t.id)),m=new Map([c,...p,...f].map(t=>[t.id,t])),v=new Map;for(const t of p)for(const e of t.identifiers??[])e[0]===l&&v.set(e[1],t);const y=new Map;for(const t of s){if("string"!=typeof t.device_id||!m.has(t.device_id))continue;const e=y.get(t.device_id);e?e.push(t):y.set(t.device_id,[t])}const _=y.get(c.id)??[],b=[...y.values()].flat(),x=new Map,w=new Map;for(const t of b)t.entity_id.startsWith("sensor.")?x.set(t.unique_id,t.entity_id):t.entity_id.startsWith("switch.")&&w.set(t.unique_id.toLowerCase(),t.entity_id);const S={};for(const e of b){const n=t.states[e.entity_id];if(!n)continue;const i=n.attributes,r=eI(i.tabs);if(!r)continue;const o=JA(e.unique_id,u);if(!o)continue;const{circuitId:a,panelPrefix:s}=o,l="string"==typeof e.device_id?m.get(e.device_id):void 0,d=l&&g.has(l.id)?l:v.get(tI(u,a)),p=(d?Qn(d):"")||iI(Jn(e),h)||(l&&l!==c?nI(Qn(l),h):"")||e.entity_id,f="number"==typeof i.voltage?i.voltage:2===r.length?240:120,y={power:e.entity_id},_=w.get(`${s}_relay_${a}`.toLowerCase());_&&(y.switch=_);const b=x.get(`${s}_${a}_breaker_rating`);b&&(y.breaker_rating=b);const C={tabs:r,name:p,voltage:f,device_type:"string"==typeof i.device_type?i.device_type:"circuit",relay_state:"string"==typeof i.relay_state?i.relay_state:"UNKNOWN",is_user_controllable:!0,breaker_rating_a:null,entities:y};d&&(C.device_id=d.id),S[a]=C}let C=0;for(const e of _){const n=t.states[e.entity_id];if(n&&Ae(n.attributes.panel_size)){C=n.attributes.panel_size;break}}if(C||(C=ZA(S)),!C)throw new Error(i("card.panel_size_error"));const k={};for(const t of f)k[t.id]=rI(t,y.get(t.id)??[]);const M={serial:u,firmware:c.sw_version??"",panel_size:C,device_id:e,device_name:d||i("header.default_name"),circuits:S,sub_devices:k};return await VA(t,M),{topology:M,panelDevice:c,panelSize:C}}function aI(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function sI(t,e){if(Object.is(t,e))return!0;if(Array.isArray(t)||Array.isArray(e))return Array.isArray(t)&&Array.isArray(e)&&t.length===e.length&&t.every((t,n)=>sI(t,e[n]));if(!aI(t)||!aI(e))return!1;const n=Object.keys(t).filter(e=>void 0!==t[e]),i=Object.keys(e).filter(t=>void 0!==e[t]);return n.length===i.length&&n.every(n=>sI(t[n],e[n]))}function lI(t){const e={...t};for(const t of le)delete e[t];return e}function cI(t){const e=Object.fromEntries(Object.entries(t.circuits).map(([t,e])=>[t,lI(e)]));return{...t,circuits:e}}function uI(t){const e=t.getRootNode();return e instanceof Document||e instanceof ShadowRoot?e.activeElement:null}function dI(t){return null!==t&&uI(t)===t}function hI(t){if(!t)return!1;const e=uI(t);return null!==e&&t.contains(e)}function pI(t){return function(t){if(!t)return null;const e=uI(t);return e instanceof HTMLElement&&t.contains(e)?e:null}(t)?.dataset.role??null}function fI(t,e){t.addEventListener("blur",()=>{queueMicrotask(()=>{t.isConnected&&e()})})}const gI={continuous_threshold_pct:{min:1,max:200},spike_threshold_pct:{min:1,max:200},window_duration_m:{min:1,max:180},cooldown_duration_m:{min:1,max:180}};function mI(t){t.addEventListener("wheel",e=>{dI(t)&&e.preventDefault()},{passive:!1})}function vI(t){if(!t?.offered)return null;const[e,...n]=t.members;if(!e||n.length>0)return null;const i=e.circuit.package_ratings_form,r=e.circuit.breaker_rating_a;return"one_space"!==i&&"two_spaces"!==i||null==r?null:{kind:i,member:e,panelA:r}}function yI(t){return t.circuit.package_ratings_a?.[1]??null}class _I{constructor(t){this._host=t,this._section=null,this._field=null}get element(){return this._section}mount(t){this._field=null;const e=vI(this._host.ratingsView);this._section=e?this._build(e):null,this._section&&t.after(this._section)}sync(t){const e=vI(this._host.ratingsView),n=this._section;if(n&&e&&n.dataset.kind===e.kind&&n.dataset.uuid===e.member.uuid)return void this._patch(n,e);const i=pI(n);this._field=null;const r=e?this._build(e):null;if(n&&r?n.replaceWith(r):n?n.remove():r&&t.after(r),this._section=r,null===i)return;const o=r?.querySelector(`[data-role="${i}"]`)??r?.querySelector('[data-role="rating-input"]');o?o.focus():this._host.focusAfterRatingsEditor()}_build(t){const e=document.createElement("div");e.dataset.role="rating-section",e.dataset.kind=t.kind,e.dataset.uuid=t.member.uuid,e.className="rating-section";const n=document.createElement("div");n.className="section-label",n.textContent=i("monitoringRating.title"),e.appendChild(n);const r=document.createElement("div");r.className="field-label",r.id="rating-guidance",r.dataset.role="rating-guidance",r.textContent=i("one_space"===t.kind?"monitoringRating.guidance":"monitoringRating.guidance_two_spaces"),e.appendChild(r);const o=document.createElement("div");o.className="field-label rating-feedback",o.id="rating-feedback",o.dataset.role="rating-feedback",o.setAttribute("aria-live","polite"),e.appendChild(this._buildRow(t,o)),e.appendChild(o);const a=document.createElement("div");return a.dataset.role="rating-warning-region",a.setAttribute("aria-live","polite"),e.appendChild(a),this._syncWarning(e,t.member),e}_buildRow(t,e){const{member:n}=t,o=document.createElement("div");o.className="field-row rating-row",o.dataset.role="rating-row",o.dataset.uuid=n.uuid;const a=document.createElement("span");a.className="field-label",a.id="rating-panel-rating",a.dataset.role="rating-panel-rating",a.textContent=r("monitoringRating.panel_rating",{panel:String(t.panelA)});const s=document.createElement("span");s.className="field-label",s.textContent=i("monitoringRating.other_breaker");const l=document.createElement("input");l.type="number",l.min="1",l.step="1",l.inputMode="numeric";const c=yI(n);return l.value=null!==c?String(c):"",l.setAttribute("aria-label",r("monitoringRating.other_breaker_label",{circuit:n.circuit.name})),l.setAttribute("aria-describedby","rating-panel-rating rating-guidance rating-feedback"),l.dataset.role="rating-input",this._field=function(t,e){mI(t);let n=!1,r=null;const o=n=>{n?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),e.report(n)},a=()=>{n=!1,r=null,o(null);const i=e.stored();t.value=null!==i?String(i):""},s=()=>{if(!n)return;const s=t.value.trim();if(""===s&&t.validity?.badInput)return void o(i("monitoringRating.invalid_other"));if(""===s)return void a();const l=Number(s);!Number.isSafeInteger(l)||l<1?o(i("monitoringRating.invalid_other")):(n=!1,o(null),l!==e.stored()&&(r=l,e.save(l)))};return t.addEventListener("input",()=>{n=!0,r=null,o(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&s()}),fI(t,s),{get dirty(){return n},revert:a,answerRefusal:t=>r===t&&(a(),!0)}}(l,{report:t=>{e.textContent=t??""},stored:()=>this._storedInForce(),save:t=>this._save(t)}),o.append(a,s,l),null!==c&&o.appendChild(this._buildReset(n.uuid)),o}_buildReset(t){const e=document.createElement("button");return e.type="button",e.className="text-btn",e.dataset.role="rating-reset",e.textContent=i("monitoringRating.reset"),e.addEventListener("click",()=>{this._field?.revert(),this._host.clearPackageRatings(t).catch(t=>this._host.reportRatingsFailure(t))}),e}_patch(t,e){const{member:n}=e,i=yI(n),o=t.querySelector('[data-role="rating-panel-rating"]');o&&(o.textContent=r("monitoringRating.panel_rating",{panel:String(e.panelA)}));const a=t.querySelector('[data-role="rating-input"]');this._field&&!this._field.dirty&&this._field.revert();const s=t.querySelector('[data-role="rating-row"]'),l=t.querySelector('[data-role="rating-reset"]');null===i&&l?(dI(l)&&a?.focus(),l.remove()):null!==i&&!l&&s&&s.appendChild(this._buildReset(n.uuid)),this._syncWarning(t,n)}_storedInForce(){const t=vI(this._host.ratingsView);return t?yI(t.member):null}_save(t){const e=vI(this._host.ratingsView);if(!e)return;const{member:n,panelA:i}=e;this._host.setPackageRatings(n.uuid,[i,t]).catch(e=>{this._host.reportRatingsFailure(e),this._answerRefusal(n.uuid,t)})}_answerRefusal(t,e){const n=this._section,i=n?.querySelector('[data-role="rating-input"]'),r=this._field;n&&i&&r&&n.dataset.uuid===t&&vI(this._host.ratingsView)?.member.uuid===t&&r.answerRefusal(e)&&(null===document.activeElement||document.activeElement===document.body||hI(n))&&i.focus()}_syncWarning(t,e){const n=t.querySelector('[data-role="rating-warning-region"]');if(!n)return;const i=on(e.circuit,this._host.ratingsView?.monitoringInfo??null),r=n.firstElementChild instanceof HTMLElement?n.firstElementChild:null;if(r&&r.dataset.kind===i)return;const o=hI(r);r?.remove(),i&&n.appendChild("averaged_legs"===i?this._buildAveragedLegsWarning():this._buildThresholdWarning(i)),o&&this._host.focusAfterRatingsEditor()}_buildThresholdWarning(t){const e="own"===t?i("monitoringRating.threshold_warning"):r("monitoringRating.threshold_warning_global",{settings:i("monitoring.global_settings"),tab:i("tab.monitoring")}),n=this._buildWarning("rating-threshold-warning",t,e);return"own"===t&&n.appendChild(this._buildActionButton("rating-threshold-reset",i("monitoringRating.use_global_thresholds"),()=>this._host.useGlobalThresholds())),n}_buildAveragedLegsWarning(){const t=this._buildWarning("rating-averaged-legs-warning","averaged_legs",i("monitoringRating.averaged_legs"));return t.appendChild(this._buildActionButton("rating-turn-off-monitoring",i("monitoringRating.turn_off_monitoring"),()=>this._host.turnOffMonitoring())),t}_buildWarning(t,e,n){const i=document.createElement("div");i.className="field-label rating-warning",i.dataset.role=t,i.dataset.kind=e,i.setAttribute("role","note");const r=document.createElement("span");return r.textContent=n,i.appendChild(r),i}_buildActionButton(t,e,n){const i=document.createElement("button");return i.type="button",i.className="text-btn",i.dataset.role=t,i.textContent=e,i.addEventListener("click",()=>{"true"!==i.getAttribute("aria-disabled")&&(i.setAttribute("aria-disabled","true"),n().then(t=>{t||i.removeAttribute("aria-disabled")}))}),i}}function bI(t){return!0===t?.user?.is_admin}function xI(){return i("monitoring.admin_only")}class wI extends Error{constructor(){super(xI()),this.name="MonitoringChangeRefused"}}function SI(t){const e=e=>n=>async function(t,e,n){if(!t||!bI(t))throw new wI;try{await t.callWS({type:"call_service",domain:l,service:e,service_data:n})}catch(t){throw ie(t)?new wI:t}}(t,e,n);return{setGlobalMonitoring:e("set_global_monitoring"),testNotification:e("test_notification"),setCircuitThreshold:e("set_circuit_threshold"),clearCircuitThreshold:e("clear_circuit_threshold"),setMainsThreshold:e("set_mains_threshold"),clearMainsThreshold:e("clear_mains_threshold"),setCircuitPackageRatings:e("set_circuit_package_ratings"),clearCircuitPackageRatings:e("clear_circuit_package_ratings")}}function CI(t,e){return t instanceof wI?t.message:e}function kI(t,e,n){console.warn(`SPAN Panel: ${n} failed`,e),t?.add({key:"service:monitoring",level:"error",message:CI(e,i("error.threshold_failed")),persistent:!1})}const MI=new Set(["number","text"]);function TI(t){for(let e=t;e;e=e.parentElement)if(""!==e.style.opacity&&Number(e.style.opacity)<1)return!0;return!1}const AI="favorites-changed";async function II(t,e,n={}){const i=await t.callWS({type:"call_service",domain:l,service:e,service_data:n,return_response:!0});return i?.response??null}const DI={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"},PI="relay-label",LI="priority-label",EI="controls-note";class NI{constructor(t,e){this.uuid=t,this._on=e,this._sent=0,this._from=0,this._pending=0}get on(){return this._on}get settled(){return 0===this._pending}answered(t){this._on=t}async send(t,e){const n=++this._sent;this._pending+=1;try{const i=await e();return i&&n>this._from&&(this._on=t,this._from=n),i}finally{this._pending-=1}}}class RI extends HTMLElement{constructor(){super(),this.errorStore=null,this._thresholdReads=0,this._limitFields=[],this._storedMonitoring=null,this._controlAccess=de,this.attachShadow({mode:"open"}),this._hass=null,this._config=null,this._debounceTimers={},this._ratingsEditor=new _I(this)}set hass(t){const e=bI(this._hass)!==bI(t);this._hass=t,this.hasAttribute("open")&&this._config&&(e&&this._showsMonitoring()?this._render():this._updateLiveState())}_showsMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!0!==t.showMonitoring)}get hass(){return this._hass}open(t){this._config=t,this._storedMonitoring=t.panelMode||t.subDeviceMode||t.favoritesMode?null:new NI(t.uuid,en(t.monitoringInfo)),this._controlAccess=t.panelMode||t.subDeviceMode||t.favoritesMode?de:t.controlAccess,this._render(),this.offsetHeight,this.setAttribute("open",""),this.setAttribute("data-mode",this._modeFor(t))}get openCircuit(){const t=this._config;return!t||!this.hasAttribute("open")||t.panelMode||t.subDeviceMode||t.favoritesMode?null:{uuid:t.uuid,configEntryId:t.configEntryId??null}}refreshRating(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i={...e,members:t.members,capacityA:t.capacityA,monitoringInfo:t.monitoringInfo,monitoringGlobals:t.monitoringGlobals};this._config=i,this._monitoringStoredAs(e.uuid,t.monitoringInfo);const r=n.querySelector(".subtitle");r&&(r.textContent=this._circuitSubtitle(i)),this._syncMonitoring()}close(){this.removeAttribute("open"),this.removeAttribute("data-mode"),this._config=null,this._storedMonitoring=null,this._controlAccess=de,this.dispatchEvent(new CustomEvent("side-panel-closed",{bubbles:!0,composed:!0}))}_modeFor(t){return t.favoritesMode?"favorites":t.panelMode?"panel":t.subDeviceMode?"subDevice":"circuit"}_render(){const t=this._config;if(!t)return;const e=this.shadowRoot;if(!e)return;e.innerHTML="";const n=document.createElement("style");n.textContent='\n :host {\n display: block;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n width: 360px;\n max-width: 90vw;\n z-index: 1000;\n transform: translateX(100%);\n transition: transform 0.3s ease;\n pointer-events: none;\n }\n :host([open]) {\n transform: translateX(0);\n pointer-events: auto;\n }\n\n .backdrop {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.3);\n z-index: -1;\n }\n :host([open]) .backdrop {\n display: block;\n }\n\n .panel {\n height: 100%;\n background: var(--card-background-color, #fff);\n border-left: 1px solid var(--divider-color, #e0e0e0);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n\n .panel-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px;\n border-bottom: 1px solid var(--divider-color, #e0e0e0);\n }\n .panel-header .title {\n font-size: 18px;\n font-weight: 500;\n color: var(--primary-text-color, #212121);\n margin: 0;\n }\n .panel-header .subtitle {\n font-size: 13px;\n color: var(--secondary-text-color, #727272);\n margin: 2px 0 0 0;\n }\n .close-btn {\n background: none;\n border: none;\n cursor: pointer;\n color: var(--secondary-text-color, #727272);\n padding: 4px;\n line-height: 1;\n font-size: 20px;\n }\n\n .panel-body {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n }\n\n .section {\n margin-bottom: 20px;\n }\n .section-label {\n font-size: 12px;\n font-weight: 600;\n text-transform: uppercase;\n color: var(--secondary-text-color, #727272);\n margin: 0 0 8px 0;\n letter-spacing: 0.5px;\n }\n\n .field-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 8px 0;\n }\n /* Why the section\'s relay or priority cannot be operated, under it. */\n .controls-note {\n margin: 4px 0 0;\n font-size: 0.85em;\n color: var(--secondary-text-color, #727272);\n }\n .field-label {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n }\n\n select {\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n }\n\n input[type="number"] {\n width: 72px;\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n text-align: right;\n }\n input[type="number"]:disabled {\n opacity: 0.5;\n }\n\n .radio-group {\n display: flex;\n gap: 16px;\n padding: 8px 0;\n }\n .radio-group label {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n cursor: pointer;\n }\n\n .horizon-bar {\n display: flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n margin-top: 4px;\n }\n .horizon-segment {\n flex: 1;\n padding: 6px 0;\n text-align: center;\n font-size: 13px;\n cursor: pointer;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n transition: background 0.15s ease, color 0.15s ease;\n user-select: none;\n line-height: 1.4;\n }\n .horizon-segment:last-child {\n border-right: none;\n }\n .horizon-segment:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .horizon-segment.active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n .horizon-segment.referenced {\n box-shadow: inset 0 -3px 0 var(--primary-color, #03a9f4);\n }\n\n .unit-toggle {\n display: inline-flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n }\n .unit-btn {\n padding: 4px 10px;\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease;\n }\n .unit-btn:last-child {\n border-right: none;\n }\n .unit-btn:hover:not(.unit-active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .unit-btn.unit-active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n\n .monitoring-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .fav-heart {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--secondary-text-color, #727272);\n border-radius: 4px;\n padding: 2px 6px;\n cursor: pointer;\n font-size: 0.9em;\n margin-right: 6px;\n line-height: 1;\n display: inline-flex;\n align-items: center;\n }\n .fav-heart.active {\n color: var(--primary-color, #03a9f4);\n border-color: var(--primary-color, #03a9f4);\n }\n .fav-heart:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .fav-heart span-icon {\n --mdc-icon-size: 16px;\n }\n\n .rating-section {\n margin-bottom: 8px;\n }\n .limit-row {\n flex-wrap: wrap;\n }\n .limit-feedback {\n flex-basis: 100%;\n }\n .rating-row {\n flex-wrap: wrap;\n justify-content: flex-start;\n gap: 6px 8px;\n }\n .rating-row [data-role="rating-panel-rating"] {\n flex-basis: 100%;\n }\n .rating-feedback {\n font-size: 13px;\n color: var(--error-color, #db4437);\n }\n .rating-warning {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 6px 8px;\n margin-top: 6px;\n padding: 8px;\n border-left: 3px solid var(--warning-color, #ffa600);\n border-radius: 4px;\n background: color-mix(in srgb, var(--warning-color, #ffa600) 12%, transparent);\n font-size: 13px;\n }\n\n .text-btn {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--primary-text-color, #212121);\n border-radius: 4px;\n padding: 4px 8px;\n font: inherit;\n font-size: 13px;\n line-height: 1.3;\n cursor: pointer;\n }\n .text-btn:hover:not(:disabled):not([aria-disabled="true"]) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .text-btn:focus-visible {\n outline: 2px solid var(--primary-color, #03a9f4);\n outline-offset: 1px;\n }\n .text-btn:disabled,\n .text-btn[aria-disabled="true"] {\n opacity: 0.5;\n cursor: default;\n }\n\n .panel-mode-info {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n line-height: 1.6;\n }\n .panel-mode-info p {\n margin: 0 0 12px 0;\n }\n\n',e.appendChild(n);const i=document.createElement("div");i.className="backdrop",i.addEventListener("click",()=>this.close()),e.appendChild(i);const r=document.createElement("div");r.className="panel",e.appendChild(r),t.favoritesMode?this._renderFavoritesMode(r):t.panelMode?this._renderPanelMode(r):t.subDeviceMode?this._renderSubDeviceMode(r,t):this._renderCircuitMode(r,t)}_renderPanelMode(t){const e=this._config,n=this._createHeader(i("sidepanel.graph_settings"),i("sidepanel.global_defaults"));t.appendChild(n);const r=document.createElement("div");r.className="panel-body";const o=e.graphSettings,l=e.topology,c=o?.global_horizon??a,u=o?.circuits??{};r.appendChild(this._buildListColumnsSection());const d=document.createElement("div");d.className="section";const h=document.createElement("div");h.className="section-label",h.textContent=i("sidepanel.graph_horizon"),d.appendChild(h);const p=document.createElement("div");p.className="field-row";const f=document.createElement("span");f.className="field-label",f.textContent=i("sidepanel.global_default"),p.appendChild(f);const g=document.createElement("select");for(const t of Object.keys(s)){const e=document.createElement("option");e.value=t;const n=`horizon.${t}`,r=i(n);e.textContent=r!==n?r:t,t===c&&(e.selected=!0),g.appendChild(e)}if(g.addEventListener("change",()=>{const t={horizon:g.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_graph_time_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})}),p.appendChild(g),d.appendChild(p),r.appendChild(d),l?.circuits){const t=document.createElement("div");t.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=i("sidepanel.circuit_scales"),t.appendChild(n);const o=Object.entries(l.circuits).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[n,i]of o){const r=this._buildPanelModeCircuitRow(n,i,u[n],c,e.configEntryId??null,e.showFavorites??!1,e.favoritePanelDeviceId,e.favoriteCircuitUuids);t.appendChild(r)}r.appendChild(t)}const m=o?.sub_devices??{};if(l?.sub_devices){const t=document.createElement("div");t.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=i("sidepanel.subdevice_scales"),t.appendChild(n);const o=Object.entries(l.sub_devices).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[n,r]of o){const o=qn(r).length>0,a=e.showFavorites&&e.favoritePanelDeviceId?this._buildSubDeviceFavoriteHeart(r.entities,e.favoriteSubDeviceIds?.has(n)??!1):null;if(!o&&!a)continue;const l=document.createElement("div");l.className="field-row";const u=document.createElement("span");if(u.className="field-label",u.textContent=r.name||n,u.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",l.appendChild(u),a&&l.appendChild(a),!o){t.appendChild(l);continue}const d=m[n]||{horizon:c,has_override:!1},h=d.has_override?d.horizon:c,p=document.createElement("select");p.dataset.subdevId=n;for(const t of Object.keys(s)){const e=document.createElement("option");e.value=t;const n=`horizon.${t}`,r=i(n);e.textContent=r!==n?r:t,t===h&&(e.selected=!0),p.appendChild(e)}if(p.addEventListener("change",()=>{this._debounce(`subdev-${e.configEntryId??""}-${n}`,500,()=>{const t={subdevice_id:n,horizon:p.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_subdevice_graph_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})})}),l.appendChild(p),d.has_override){const t=document.createElement("button");t.textContent="↺",t.title=i("sidepanel.reset_to_global"),Object.assign(t.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),t.addEventListener("click",()=>{const r={subdevice_id:n};e.configEntryId&&(r.config_entry_id=e.configEntryId),this._callDomainService("clear_subdevice_graph_horizon",r).then(()=>{p.value=c,t.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})}),l.appendChild(t)}t.appendChild(l)}t.children.length>1&&r.appendChild(t)}t.appendChild(r)}_buildPanelModeCircuitRow(t,e,n,r,o,a,l,c){const u=document.createElement("div");u.className="field-row";const d=document.createElement("span");if(d.className="field-label",d.textContent=e.name||t,d.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",u.appendChild(d),a&&l){const n=this._buildFavoriteHeart(e.entities,c?.has(t)??!1);n&&u.appendChild(n)}const h=n||{horizon:r,has_override:!1},p=h.has_override?h.horizon:r,f=document.createElement("select");f.dataset.uuid=t;for(const t of Object.keys(s)){const e=document.createElement("option");e.value=t;const n=`horizon.${t}`,r=i(n);e.textContent=r!==n?r:t,t===p&&(e.selected=!0),f.appendChild(e)}if(f.addEventListener("change",()=>{this._debounce(`circuit-${o??""}-${t}`,500,()=>{const e={circuit_id:t,horizon:f.value};o&&(e.config_entry_id=o),this._callDomainService("set_circuit_graph_horizon",e).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})})}),u.appendChild(f),h.has_override){const e=document.createElement("button");e.textContent="↺",e.title=i("sidepanel.reset_to_global"),Object.assign(e.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),e.addEventListener("click",()=>{const n={circuit_id:t};o&&(n.config_entry_id=o),this._callDomainService("clear_circuit_graph_horizon",n).then(()=>{f.value=r,e.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})}),u.appendChild(e)}return u}_renderFavoritesMode(t){const e=this._config,n=this._createHeader(i("sidepanel.graph_settings"),i("sidepanel.favorites_subtitle"));t.appendChild(n);const r=document.createElement("div");r.className="panel-body",r.appendChild(this._buildListColumnsSection());for(const t of e.perPanelSections)r.appendChild(this._buildFavoritesPanelSection(t));t.appendChild(r)}_buildFavoritesPanelSection(t){const e=document.createElement("div");e.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=t.panelName,e.appendChild(n);const i=t.graphSettings?.global_horizon??a,r=t.graphSettings?.circuits??{},o=function(t){const e=t.circuits??{};return Object.entries(e).map(([t,e])=>({uuid:t,circuit:e})).sort((t,e)=>(t.circuit.name||"").localeCompare(e.circuit.name||""))}(t.topology);for(const{uuid:n,circuit:a}of o){const o=this._buildPanelModeCircuitRow(n,a,r[n],i,t.configEntryId,!0,t.panelDeviceId,t.favoriteCircuitUuids);e.appendChild(o)}return e}_renderCircuitMode(t,e){const n=this._createHeader(e.name,this._circuitSubtitle(e));t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),this._renderRelaySection(i,e),e.showFavorites&&this._renderFavoriteSection(i,e),this._renderSheddingSection(i,e),this._placeControlNote(i),this._renderGraphHorizonSection(i,e),e.showMonitoring&&this._renderMonitoringSection(i,e)}_placeControlNote(t){t.querySelector('[data-role="controls-note"]')?.remove();const e=[...t.querySelectorAll('[data-role="relay-toggle"], [data-role="shedding-select"]')];e[0]?.closest(".section")?.insertAdjacentHTML("beforeend",Me(this._controlAccess));const n=t.querySelector('[data-role="controls-note"]');n&&(n.id=EI);for(const t of e)n?t.setAttribute("aria-describedby",EI):t.removeAttribute("aria-describedby")}refreshControlAccess(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i=this._controlAccess;i.mayOperate===t.mayOperate&&i.reason===t.reason||(this._controlAccess=t,this._updateLiveState(),this._placeControlNote(n))}_circuitSubtitle(t){const e=t.members.map(t=>t.circuit),n=[...new Set(e.flatMap(t=>t.voltage?[t.voltage]:[]))].sort((t,e)=>t-e);return[je(e),e.length>1&&t.capacityA?r("sidepanel.capacity",{amps:String(t.capacityA)}):"",n.length>0?`${n.join("/")}V`:"",`Tabs [${Fe(e).join(",")}]`].filter(Boolean).join(" · ")}_favoriteEntityId(t){return t?.current??t?.power??null}_buildSubDeviceFavoriteHeart(t,e){const n=Gn(t);return n?this._buildHeartButton(n,e):null}_buildListColumnsSection(){const t=document.createElement("div");t.className="section";const e=document.createElement("div");e.className="section-label",e.textContent=i("sidepanel.list_view_columns"),t.appendChild(e);const n=document.createElement("div");n.className="field-row";const r=document.createElement("span");r.className="field-label",r.textContent=i("sidepanel.columns"),n.appendChild(r);const o=Wt(),a=document.createElement("div");a.className="unit-toggle";for(const t of[1,2,3]){const e=document.createElement("button");e.type="button",e.className="unit-btn"+(t===o?" unit-active":""),e.dataset.columns=String(t),e.textContent=String(t),e.addEventListener("click",()=>{jt(t);for(const t of a.querySelectorAll(".unit-btn"))t.classList.toggle("unit-active",t===e);this.dispatchEvent(new CustomEvent("list-columns-changed",{detail:t,bubbles:!0,composed:!0}))}),a.appendChild(e)}return n.appendChild(a),t.appendChild(n),t}_buildFavoriteHeart(t,e){const n=this._favoriteEntityId(t);return n?this._buildHeartButton(n,e):(console.warn("SPAN Panel: circuit has no current/power sensor; favorite heart suppressed"),null)}_buildHeartButton(t,e){const n=document.createElement("button");n.type="button",n.className=e?"fav-heart active":"fav-heart",n.dataset.role="fav-heart",n.title=i("sidepanel.save_to_favorites"),n.setAttribute("role","switch"),n.setAttribute("aria-checked",String(e)),n.setAttribute("aria-label",i("sidepanel.save_to_favorites"));const r=document.createElement("span-icon");return r.setAttribute("icon",e?"mdi:heart":"mdi:heart-outline"),n.appendChild(r),n.addEventListener("click",e=>{e.stopPropagation(),this._toggleFavoriteEntity(n,r,t).catch(()=>{})}),n}async _toggleFavoriteEntity(t,e,n){if(!this._hass)return;const r=t.classList.contains("active"),o=!r;t.classList.toggle("active",o),e.setAttribute("icon",o?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(o));try{o?await async function(t,e){const n=await II(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(AI)),n?.favorites??{}}(this._hass,n):await async function(t,e){const n=await II(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(AI)),n?.favorites??{}}(this._hass,n)}catch(n){throw t.classList.toggle("active",r),e.setAttribute("icon",r?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(r)),console.warn("SPAN Panel: favorite toggle failed",n),this.errorStore?.add({key:"service:favorites",level:"error",message:i("error.favorites_toggle_failed"),persistent:!1}),n}}_renderFavoriteSection(t,e){const n=this._favoriteEntityId(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_appendFavoriteHeartSection(t,e,n){const r=document.createElement("div");r.className="section",r.innerHTML=``;const o=document.createElement("div");o.className="field-row";const a=document.createElement("span");a.className="field-label",a.textContent=i("sidepanel.save_to_favorites"),o.appendChild(a),o.appendChild(this._buildHeartButton(e,n)),r.appendChild(o),t.appendChild(r)}_renderSubDeviceMode(t,e){const n=this._createHeader(e.name,e.deviceType);t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),e.showFavorites&&this._renderSubDeviceFavoriteSection(i,e),e.hasChart&&this._renderSubDeviceHorizonSection(i,e)}_renderSubDeviceFavoriteSection(t,e){const n=Gn(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_renderSubDeviceHorizonSection(t,e){const n=document.createElement("div");n.className="section";const r=document.createElement("div");r.className="section-label",r.textContent=i("sidepanel.graph_horizon"),n.appendChild(r);const o=e.graphHorizonInfo,l=!0===o?.has_override,c=o?.horizon||a,u=o?.globalHorizon||a,d=document.createElement("div");d.className="horizon-bar";const h=[{key:"global",label:i("sidepanel.global")}];for(const t of Object.keys(s))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of d.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===u)}};for(const{key:t,label:n}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=n,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===u),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const n={subdevice_id:e.subDeviceId};e.configEntryId&&(n.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_subdevice_graph_horizon",n).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_subdevice_graph_horizon",{...n,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})}))}),d.appendChild(r)}n.appendChild(d),t.appendChild(n)}_createHeader(t,e){const n=document.createElement("div");n.className="panel-header";const i=document.createElement("div"),r=document.createElement("div");if(r.className="title",r.textContent=t,i.appendChild(r),e){const t=document.createElement("div");t.className="subtitle",t.textContent=e,i.appendChild(t)}const o=document.createElement("button");return o.className="close-btn",o.innerHTML="✕",o.addEventListener("click",()=>this.close()),n.appendChild(i),n.appendChild(o),n}_renderRelaySection(t,e){if(!this._hass||"none"===_n(e,this._hass))return;const n=document.createElement("div");n.className="section",n.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=PI,o.textContent=i("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle",a.setAttribute("aria-labelledby",PI);const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{const t=this._hass;t&&s&&"operable"===_n(e,t)&&xe(t,this._controlAccess).setRelay(s,a.checked).catch(n=>{Ce(t,this.errorStore,n,"relay"),this._applyRelayToggle(a,e)})}),r.appendChild(o),r.appendChild(a),n.appendChild(r),t.appendChild(n)}_renderSheddingSection(t,e){if(!e.entities?.select)return;const n=document.createElement("div");n.className="section",n.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=LI,o.textContent=i("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select",a.setAttribute("aria-labelledby",LI);const s=e.entities.select;for(const t of x){const e=b[t];if(!e)continue;const n=document.createElement("option");n.value=t,n.textContent=i(`shedding.select.${t}`)||e.label(),a.appendChild(n)}a.addEventListener("change",()=>{const t=this._hass;t&&xe(t,this._controlAccess).setPriority(s,a.value).catch(n=>{Ce(t,this.errorStore,n,"priority"),this._applySheddingSelect(a,e)})}),r.appendChild(o),r.appendChild(a),n.appendChild(r),t.appendChild(n),this._applySheddingSelect(a,e)}get ratingsView(){const t=this._config;return!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!t.showMonitoring?null:{members:t.members??[],monitoringInfo:t.monitoringInfo,offered:!0===t.monitoringRatingOffered}}setPackageRatings(t,e){return SI(this._hass).setCircuitPackageRatings(this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return SI(this._hass).clearCircuitPackageRatings(this._ratingsPayload(t,{}))}reportRatingsFailure(t){!function(t,e,n){console.warn("SPAN Panel: package ratings update failed",n),se(t,n,l,i("error.package_ratings_failed")).then(t=>{e?.add({key:"service:package-ratings",level:"error",message:t,persistent:!1})})}(this._hass,this.errorStore,t)}async useGlobalThresholds(){const t=this._config,e=this.shadowRoot;if(!t||!e||t.panelMode||t.subDeviceMode||t.favoritesMode)return!1;const n=e.querySelector('input[name="monitoring-mode"][value="global"]'),i=e.querySelector('input[name="monitoring-mode"][value="custom"]'),r=e.querySelector('[data-role="threshold-fields"]');n&&(n.checked=!0),r&&(r.style.display="none"),this._thresholdReads+=1;const o={circuit_id:t.entities?.power||t.uuid};t.configEntryId&&(o.config_entry_id=t.configEntryId);try{await SI(this._hass).clearCircuitThreshold(o)}catch(e){return kI(this.errorStore,e,"monitoring update"),this._config===t&&(i&&(i.checked=!0),r&&(r.style.display="block")),!1}const a=this._config===t?t.monitoringGlobals??null:null;return this._monitoringChanged(t.uuid,{has_override:!1,continuous_threshold_pct:a?.continuous_threshold_pct,spike_threshold_pct:a?.spike_threshold_pct}),!0}async turnOffMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode)&&this._sendMonitoringEnabled(t,!1)}focusAfterRatingsEditor(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"]:checked')??t?.querySelector('input[name="monitoring-mode"]');e?.focus()}_ratingsPayload(t,e){const n={circuit_id:t,...e},i=this._config,r=!i||i.panelMode||i.subDeviceMode||i.favoritesMode?null:i.configEntryId;return r&&(n.config_entry_id=r),n}_monitoringChanged(t,e){const n=this._openCircuitConfig(t);n&&(this._config={...n,monitoringInfo:{...n.monitoringInfo??{},...e}},this._syncMonitoring())}_monitoringAnswered(t,e,n){const i=this._openCircuitConfig(t);i&&(this._config={...i,monitoringInfo:e,monitoringGlobals:n},this._monitoringStoredAs(t,e),!0!==e.has_override&&this._showGlobalChoice(),this._syncMonitoring())}_monitoringStoredAs(t,e){const n=this._storedMonitoring;e&&n?.uuid===t&&n.answered(en(e))}_showStoredMonitoring(t){if(!t||t!==this._storedMonitoring||!t.settled)return;const e=this.shadowRoot?.querySelector('[data-role="monitoring-toggle"]')?.hasAttribute("checked");e!==t.on&&this._showMonitoringEnabled(t.uuid,t.on)}_showGlobalChoice(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"][value="global"]'),n=t?.querySelector('[data-role="threshold-fields"]');e&&n&&!e.checked&&!this._limitFields.some(t=>t.dirty)&&(e.checked=!0,hI(n)&&e.focus(),n.style.display="none")}_openCircuitConfig(t){const e=this._config;return!e||e.panelMode||e.subDeviceMode||e.favoritesMode||e.uuid!==t||!this.hasAttribute("open")?null:e}_syncMonitoring(){const t=this._config,e=this.shadowRoot?.querySelector('[data-role="judged-against"]');if(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!e)return;const n=this._judgedAgainstText(t.monitoringInfo);e.textContent!==n&&(e.textContent=n),this._ratingsEditor.sync(e),this._lockMonitoringIfReadOnly()}_renderGraphHorizonSection(t,e){const n=document.createElement("div");n.className="section",n.dataset.role="horizon-section";const r=document.createElement("div");r.className="section-label",r.textContent=i("sidepanel.graph_horizon"),n.appendChild(r);const o=e.graphHorizonInfo,l=!0===o?.has_override,c=o?.horizon||a,u=o?.globalHorizon||a,d=document.createElement("div");d.className="horizon-bar";const h=[{key:"global",label:i("sidepanel.global")}];for(const t of Object.keys(s))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of d.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===u)}};for(const{key:t,label:n}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=n,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===u),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const n={circuit_id:e.uuid};e.configEntryId&&(n.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_circuit_graph_horizon",n).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_circuit_graph_horizon",{...n,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:i("error.graph_horizon_failed"),persistent:!1})}))}),d.appendChild(r)}n.appendChild(d),t.appendChild(n)}_judgedAgainstText(t){return function(t){return t.amps?t.userSet?r("monitoringRating.judged_copied",{rating:String(t.amps),copied:an(t)}):r("sidepanel.judged_against",{rating:`${t.amps} A`}):r("sidepanel.judged_against",{rating:i("monitoringRating.none")})}({amps:(e=t)?tn(e):void 0,panelAmps:e?.breaker_rating_a,userSet:!0===e?.monitoring_rating_user_set,packageRatings:e?.package_ratings_a??null});var e}_renderMonitoringSection(t,e){const n=document.createElement("div");n.className="section",n.dataset.role="monitoring-section";const r=document.createElement("div");r.className="monitoring-header";const o=document.createElement("div");o.className="section-label",o.textContent=i("sidepanel.monitoring"),o.style.margin="0";const a=document.createElement("span-switch");a.dataset.role="monitoring-toggle";const s=e.monitoringInfo,l=en(s);l&&a.setAttribute("checked",""),r.appendChild(o),r.appendChild(a),n.appendChild(r),bI(this._hass)||n.appendChild(function(){const t=document.createElement("p");return t.dataset.role="monitoring-read-only",t.setAttribute("role","note"),t.style.cssText="margin:8px 0 12px;font-size:0.85em;color:var(--secondary-text-color);",t.textContent=xI(),t}());const c=document.createElement("div");c.dataset.role="monitoring-details",c.style.display=l?"block":"none",n.appendChild(c);const u=!0===s?.has_override,d=document.createElement("div");d.className="field-label",d.dataset.role="judged-against",d.setAttribute("aria-live","polite"),d.style.marginBottom="8px",d.textContent=this._judgedAgainstText(s),c.appendChild(d),this._ratingsEditor.mount(d);const h=document.createElement("div");h.className="radio-group",h.innerHTML=`\n \n \n `,c.appendChild(h),this._limitFields=[];const p=document.createElement("div");p.dataset.role="threshold-fields",p.style.display=u?"block":"none";const f=s?.continuous_threshold_pct??80,g=s?.spike_threshold_pct??100,m=s?.window_duration_m??15,v=s?.cooldown_duration_m??15;p.appendChild(this._createLimitRow(i("sidepanel.continuous_pct"),"continuous",f,null,e)),p.appendChild(this._createLimitRow(i("sidepanel.spike_pct"),"spike",g,null,e)),p.appendChild(this._createLimitRow(i("sidepanel.window_duration"),"window-m",m,"m",e)),p.appendChild(this._createLimitRow(i("sidepanel.cooldown"),"cooldown-m",v,"m",e)),c.appendChild(p),a.addEventListener("change",()=>{const t=a.checked;this._showMonitoringEnabled(e.uuid,t),this._sendMonitoringEnabled(e,t)});const y=h.querySelectorAll('input[type="radio"]');for(const t of y)t.addEventListener("change",()=>{t.checked&&("custom"===t.value?p.style.display="block":this.useGlobalThresholds())});t.appendChild(n),this._lockMonitoringIfReadOnly()}_lockMonitoringIfReadOnly(){const t=this.shadowRoot?.querySelector('[data-role="monitoring-section"]');t&&!bI(this._hass)&&function(t){const e=xI();for(const n of t.querySelectorAll("input, select, textarea, button, span-switch"))n instanceof HTMLInputElement&&MI.has(n.type)||n instanceof HTMLTextAreaElement?n.readOnly=!0:n.setAttribute("disabled",""),n.title=e,"span-switch"!==n.localName&&(TI(n)||(n.style.opacity="0.5"),n.style.cursor="not-allowed")}(t)}async _sendMonitoringEnabled(t,e){const n={circuit_id:t.entities?.power||t.uuid,monitoring_enabled:e};t.configEntryId&&(n.config_entry_id=t.configEntryId);const i=async()=>{try{return await SI(this._hass).setCircuitThreshold(n),!0}catch(t){return kI(this.errorStore,t,"monitoring update"),!1}},r=this._storedMonitoring;if(r?.uuid!==t.uuid)return i();const o=await r.send(e,i);return this._showStoredMonitoring(r),o}_showMonitoringEnabled(t,e){const n=this.shadowRoot;if(!this._openCircuitConfig(t)||!n)return;const i=n.querySelector('[data-role="monitoring-toggle"]');i?.toggleAttribute("checked",e);const r=n.querySelector('[data-role="monitoring-details"]');if(r){const t=!e&&hI(r);r.style.display=e?"block":"none",t&&i?.focus()}this._monitoringChanged(t,{monitoring_enabled:e})}_createLimitRow(t,e,n,i,o){const a=DI[e],{min:s,max:l}=gI[a],c=document.createElement("div");c.className="field-row limit-row";const u=document.createElement("span");u.className="field-label",u.id=`threshold-label-${e}`,u.textContent=t;const d=document.createElement("div"),h=document.createElement("input");if(h.type="number",h.setAttribute("aria-labelledby",u.id),h.min=String(s),h.max=String(l),h.step="1",h.value=String(n),h.dataset.role=`threshold-${e}`,h.setAttribute("aria-describedby",`threshold-feedback-${e}`),d.appendChild(h),i){const t=document.createElement("span");t.textContent=i,d.appendChild(t)}const p=document.createElement("div");p.className="field-label rating-feedback limit-feedback",p.id=`threshold-feedback-${e}`,p.dataset.role=`threshold-feedback-${e}`,p.setAttribute("aria-live","polite");const f=function(t,e,n){const{min:i,max:o}=gI[e];mI(t);let a=!1;const s=e=>{e?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),n.report(e)},l=()=>{const e=""===t.value.trim()?Number.NaN:Number(t.value);return Number.isSafeInteger(e)&&e>=i&&e<=o?e:(s(r("monitoring.limit_invalid",{min:String(i),max:String(o)})),null)},c=()=>{if(!a)return;const t=l();null!==t&&(a=!1,s(null),n.save(t))};return t.addEventListener("input",()=>{a=!0,s(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&c()}),fI(t,c),{get dirty(){return a},check:l}}(h,a,{report:t=>{p.textContent=t??""},save:t=>{const e={circuit_id:o.entities?.power||o.uuid,[a]:t};o.configEntryId&&(e.config_entry_id=o.configEntryId),this._saveThresholds(o,e)}});return this._limitFields.push(f),c.append(u,d,p),c}_saveThresholds(t,e){SI(this._hass).setCircuitThreshold(e).then(()=>this._readThresholds(t,e),t=>kI(this.errorStore,t,"monitoring update"))}_updateLiveState(){if(!this._config||this._config.panelMode)return;const t=this._config;if(!t.subDeviceMode&&!t.favoritesMode){if(t.entities?.switch){const e=this.shadowRoot?.querySelector('[data-role="relay-toggle"]');e&&this._applyRelayToggle(e,t)}if(t.entities?.select){const e=this.shadowRoot?.querySelector('[data-role="shedding-select"]');e&&this._applySheddingSelect(e,t)}}}_applyRelayToggle(t,e){if(!this._hass)return;const n=this._controlAccess;t.disabled=!n.mayOperate||"operable"!==_n(e,this._hass),ke(t,n),yn(e,this._hass)?t.setAttribute("checked",""):t.removeAttribute("checked")}_applySheddingSelect(t,e){if(!this._hass)return;const n=this._controlAccess,i=wn(e,this._hass);x.includes(i)?t.value=i:t.selectedIndex=-1,t.disabled=!n.mayOperate||!function(t,e){const n=xn(t,e);return void 0!==n&&fn.has(n)}(e,this._hass),ke(t,n)}async _readThresholds(t,e){const n=++this._thresholdReads;let i=null;try{i=await this._readMonitoringStatus(t.configEntryId??null)}catch(t){console.warn("SPAN Panel: monitoring status read failed",t)}if(n!==this._thresholdReads)return;const r=Ze(i,t);if(r)return void this._monitoringAnswered(t.uuid,r,i?.global_settings??null);const o={has_override:!0};"number"==typeof e.continuous_threshold_pct&&(o.continuous_threshold_pct=e.continuous_threshold_pct),"number"==typeof e.spike_threshold_pct&&(o.spike_threshold_pct=e.spike_threshold_pct),this._monitoringChanged(t.uuid,o)}async _readMonitoringStatus(t){if(!this._hass)return null;const e=await this._hass.callWS({type:"call_service",domain:l,service:"get_monitoring_status",service_data:t?{config_entry_id:t}:{},return_response:!0});return Ge(e?.response)}_callDomainService(t,e){return this._hass?this._hass.callWS({type:"call_service",domain:l,service:t,service_data:e}):Promise.resolve()}_debounce(t,e,n){this._debounceTimers[t]&&clearTimeout(this._debounceTimers[t]),this._debounceTimers[t]=setTimeout(()=>{delete this._debounceTimers[t],n()},e)}}try{customElements.get("span-side-panel")||customElements.define("span-side-panel",RI)}catch{}class OI extends Nt{constructor(){super(...arguments),this._store=null,this._unsub=null,this._errors=[]}set store(t){if(this._store===t)return;this._unsub?.(),this._unsub=null,this._store=t,this._errors=t.active;const e=t;this._unsub=t.subscribe(()=>{this._errors=e.active})}connectedCallback(){if(super.connectedCallback(),this._store&&!this._unsub){const t=this._store;this._errors=t.active,this._unsub=t.subscribe(()=>{this._errors=t.active})}}disconnectedCallback(){super.disconnectedCallback(),this._unsub?.(),this._unsub=null}render(){return 0===this._errors.length?yt:gt`${this._errors.map(t=>gt` - `)}`}_iconForLevel(t){switch(t){case"error":return"mdi:alert-circle";case"warning":return"mdi:alert";default:return"mdi:information"}}}ZA.styles=M` + `)}`}_iconForLevel(t){switch(t){case"error":return"mdi:alert-circle";case"warning":return"mdi:alert";default:return"mdi:information"}}}OI.styles=P` :host { display: block; } @@ -111,7 +111,7 @@ var al={},sl={};var ll,cl=function(){function t(t,e,n){var i=this;this._sleepAft .retry-btn:hover { opacity: 0.8; } - `,_([Nt()],ZA.prototype,"_errors",void 0);try{customElements.get("span-error-banner")||customElements.define("span-error-banner",ZA)}catch{}const KA=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"}),QA=new Set;class JA extends It{constructor(){super(...arguments),this.icon=""}render(){if(!this.icon)return pt;const t=KA[this.icon];return t?ut``:(e=this.icon,QA.has(e)||(QA.add(e),console.warn(`SPAN: unknown icon "${e}". Add it to MDI_PATHS in span-icon.ts.`)),pt);var e}}JA.styles=M` + `,C([Bt()],OI.prototype,"_errors",void 0);try{customElements.get("span-error-banner")||customElements.define("span-error-banner",OI)}catch{}const zI=Object.freeze({"mdi:alert":"M13 14H11V9H13M13 18H11V16H13M1 21H23L12 2L1 21Z","mdi:alert-circle":"M13,13H11V7H13M13,17H11V15H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z","mdi:battery":"M16.67,4H15V2H9V4H7.33A1.33,1.33 0 0,0 6,5.33V20.67C6,21.4 6.6,22 7.33,22H16.67A1.33,1.33 0 0,0 18,20.67V5.33C18,4.6 17.4,4 16.67,4Z","mdi:battery-alert-variant-outline":"M14 20H6V6H14M14.67 4H13V2H7V4H5.33C4.6 4 4 4.6 4 5.33V20.67C4 21.4 4.6 22 5.33 22H14.67C15.4 22 16 21.4 16 20.67V5.33C16 4.6 15.4 4 14.67 4M21 7H19V13H21V8M21 15H19V17H21V15Z","mdi:chevron-down":"M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z","mdi:close":"M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z","mdi:cog":"M12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5M19.43,12.97C19.47,12.65 19.5,12.33 19.5,12C19.5,11.67 19.47,11.34 19.43,11L21.54,9.37C21.73,9.22 21.78,8.95 21.66,8.73L19.66,5.27C19.54,5.05 19.27,4.96 19.05,5.05L16.56,6.05C16.04,5.66 15.5,5.32 14.87,5.07L14.5,2.42C14.46,2.18 14.25,2 14,2H10C9.75,2 9.54,2.18 9.5,2.42L9.13,5.07C8.5,5.32 7.96,5.66 7.44,6.05L4.95,5.05C4.73,4.96 4.46,5.05 4.34,5.27L2.34,8.73C2.21,8.95 2.27,9.22 2.46,9.37L4.57,11C4.53,11.34 4.5,11.67 4.5,12C4.5,12.33 4.53,12.65 4.57,12.97L2.46,14.63C2.27,14.78 2.21,15.05 2.34,15.27L4.34,18.73C4.46,18.95 4.73,19.03 4.95,18.95L7.44,17.94C7.96,18.34 8.5,18.68 9.13,18.93L9.5,21.58C9.54,21.82 9.75,22 10,22H14C14.25,22 14.46,21.82 14.5,21.58L14.87,18.93C15.5,18.67 16.04,18.34 16.56,17.94L19.05,18.95C19.27,19.03 19.54,18.95 19.66,18.73L21.66,15.27C21.78,15.05 21.73,14.78 21.54,14.63L19.43,12.97Z","mdi:heart":"M12,21.35L10.55,20.03C5.4,15.36 2,12.27 2,8.5C2,5.41 4.42,3 7.5,3C9.24,3 10.91,3.81 12,5.08C13.09,3.81 14.76,3 16.5,3C19.58,3 22,5.41 22,8.5C22,12.27 18.6,15.36 13.45,20.03L12,21.35Z","mdi:heart-outline":"M12.1,18.55L12,18.65L11.89,18.55C7.14,14.24 4,11.39 4,8.5C4,6.5 5.5,5 7.5,5C9.04,5 10.54,6 11.07,7.36H12.93C13.46,6 14.96,5 16.5,5C18.5,5 20,6.5 20,8.5C20,11.39 16.86,14.24 12.1,18.55M16.5,3C14.76,3 13.09,3.81 12,5.08C10.91,3.81 9.24,3 7.5,3C4.42,3 2,5.41 2,8.5C2,12.27 5.4,15.36 10.55,20.03L12,21.35L13.45,20.03C18.6,15.36 22,12.27 22,8.5C22,5.41 19.58,3 16.5,3Z","mdi:help":"M10,19H13V22H10V19M12,2C17.35,2.22 19.68,7.62 16.5,11.67C15.67,12.67 14.33,13.33 13.67,14.17C13,15 13,16 13,17H10C10,15.33 10,13.92 10.67,12.92C11.33,11.92 12.67,11.33 13.5,10.67C15.92,8.43 15.32,5.26 12,5A3,3 0 0,0 9,8H6A6,6 0 0,1 12,2Z","mdi:help-circle-outline":"M11,18H13V16H11V18M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,6A4,4 0 0,0 8,10H10A2,2 0 0,1 12,8A2,2 0 0,1 14,10C14,12 11,11.75 11,15H13C13,12.75 16,12.5 16,10A4,4 0 0,0 12,6Z","mdi:home-group":"M17,16H15V22H12V17H8V22H5V16H3L10,10L17,16M6,2L10,6H9V9H7V6H5V9H3V6H2L6,2M18,3L23,8H22V12H19V9H17V12H15.34L14,10.87V8H13L18,3Z","mdi:information":"M13,9H11V7H13M13,17H11V11H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z","mdi:lock":"M12,17A2,2 0 0,0 14,15C14,13.89 13.1,13 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6A2,2 0 0,1 4,20V10C4,8.89 4.9,8 6,8H7V6A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,3A3,3 0 0,0 9,6V8H15V6A3,3 0 0,0 12,3Z","mdi:lock-open":"M18,8A2,2 0 0,1 20,10V20A2,2 0 0,1 18,22H6C4.89,22 4,21.1 4,20V10A2,2 0 0,1 6,8H15V6A3,3 0 0,0 12,3A3,3 0 0,0 9,6H7A5,5 0 0,1 12,1A5,5 0 0,1 17,6V8H18M12,17A2,2 0 0,0 14,15A2,2 0 0,0 12,13A2,2 0 0,0 10,15A2,2 0 0,0 12,17Z","mdi:menu":"M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z","mdi:monitor-eye":"M3 4V16H21V4H3M3 2H21C22.1 2 23 2.89 23 4V16C23 16.53 22.79 17.04 22.41 17.41C22.04 17.79 21.53 18 21 18H14V20H16V22H8V20H10V18H3C2.47 18 1.96 17.79 1.59 17.41C1.21 17.04 1 16.53 1 16V4C1 2.89 1.89 2 3 2M10.84 8.93C11.15 8.63 11.57 8.45 12 8.45C12.43 8.46 12.85 8.63 13.16 8.94C13.46 9.24 13.64 9.66 13.64 10.09C13.64 10.53 13.46 10.94 13.16 11.25C12.85 11.56 12.43 11.73 12 11.73C11.57 11.73 11.15 11.55 10.84 11.25C10.54 10.94 10.36 10.53 10.36 10.09C10.36 9.66 10.54 9.24 10.84 8.93M10.07 12C10.58 12.53 11.28 12.82 12 12.82C12.72 12.82 13.42 12.53 13.93 12C14.44 11.5 14.73 10.81 14.73 10.09C14.73 9.37 14.44 8.67 13.93 8.16C13.42 7.65 12.72 7.36 12 7.36C11.28 7.36 10.58 7.65 10.07 8.16C9.56 8.67 9.27 9.37 9.27 10.09C9.27 10.81 9.56 11.5 10.07 12M6 10.09C6.94 7.7 9.27 6 12 6C14.73 6 17.06 7.7 18 10.09C17.06 12.5 14.73 14.18 12 14.18C9.27 14.18 6.94 12.5 6 10.09Z","mdi:router-wireless":"M20.2,5.9L21,5.1C19.6,3.7 17.8,3 16,3C14.2,3 12.4,3.7 11,5.1L11.8,5.9C13,4.8 14.5,4.2 16,4.2C17.5,4.2 19,4.8 20.2,5.9M19.3,6.7C18.4,5.8 17.2,5.3 16,5.3C14.8,5.3 13.6,5.8 12.7,6.7L13.5,7.5C14.2,6.8 15.1,6.5 16,6.5C16.9,6.5 17.8,6.8 18.5,7.5L19.3,6.7M19,13H17V9H15V13H5A2,2 0 0,0 3,15V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V15A2,2 0 0,0 19,13M8,18H6V16H8V18M11.5,18H9.5V16H11.5V18M15,18H13V16H15V18Z","mdi:sort-descending":"M19 7H22L18 3L14 7H17V21H19M2 17H12V19H2M6 5V7H2V5M2 11H9V13H2V11Z","mdi:transmission-tower":"M8.28,5.45L6.5,4.55L7.76,2H16.23L17.5,4.55L15.72,5.44L15,4H9L8.28,5.45M18.62,8H14.09L13.3,5H10.7L9.91,8H5.38L4.1,10.55L5.89,11.44L6.62,10H17.38L18.1,11.45L19.89,10.56L18.62,8M17.77,22H15.7L15.46,21.1L12,15.9L8.53,21.1L8.3,22H6.23L9.12,11H11.19L10.83,12.35L12,14.1L13.16,12.35L12.81,11H14.88L17.77,22M11.4,15L10.5,13.65L9.32,18.13L11.4,15M14.68,18.12L13.5,13.64L12.6,15L14.68,18.12Z","mdi:view-dashboard":"M13,3V9H21V3M13,21H21V11H13M3,21H11V15H3M3,13H11V3H3V13Z"}),HI=new Set;class BI extends Nt{constructor(){super(...arguments),this.icon=""}render(){if(!this.icon)return yt;const t=zI[this.icon];return t?gt``:(e=this.icon,HI.has(e)||(HI.add(e),console.warn(`SPAN: unknown icon "${e}". Add it to MDI_PATHS in span-icon.ts.`)),yt);var e}}BI.styles=P` :host { display: inline-flex; align-items: center; @@ -128,19 +128,22 @@ var al={},sl={};var ll,cl=function(){function t(t,e,n){var i=this;this._sleepAft display: block; fill: currentColor; } - `,_([Et({type:String})],JA.prototype,"icon",void 0);try{customElements.get("span-icon")||customElements.define("span-icon",JA)}catch{}class tI extends It{constructor(){super(...arguments),this.checked=!1,this.disabled=!1,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.hasAttribute("tabindex")||this.setAttribute("tabindex","0"),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))}render(){return ut` + `,C([Ht({type:String})],BI.prototype,"icon",void 0);try{customElements.get("span-icon")||customElements.define("span-icon",BI)}catch{}class $I extends Nt{constructor(){super(...arguments),this.checked=!1,this.disabled=!1,this._enabledTabIndex="0",this._onActivate=t=>{if(this.disabled)return t.preventDefault(),void t.stopPropagation();this.checked=!this.checked,this.dispatchEvent(new Event("change",{bubbles:!0,composed:!0}))},this._onKeydown=t=>{" "!==t.key&&"Enter"!==t.key||(t.preventDefault(),this._onActivate(t))}}connectedCallback(){super.connectedCallback(),this._syncFocusable(),this.hasAttribute("role")||this.setAttribute("role","switch"),this.setAttribute("aria-checked",String(this.checked)),this.addEventListener("click",this._onActivate),this.addEventListener("keydown",this._onKeydown)}disconnectedCallback(){this.removeEventListener("click",this._onActivate),this.removeEventListener("keydown",this._onKeydown),super.disconnectedCallback()}updated(t){t.has("checked")&&this.setAttribute("aria-checked",String(this.checked)),t.has("disabled")&&(this.setAttribute("aria-disabled",String(this.disabled)),this._syncFocusable())}_syncFocusable(){const t=this.getAttribute("tabindex");if(this.disabled){if(null===t)return;this._enabledTabIndex=t,this.removeAttribute("tabindex")}else null===t&&this.setAttribute("tabindex",this._enabledTabIndex)}render(){return gt`
- `}}tI.styles=M` + `}}$I.styles=P` :host { - --span-switch-on: var(--switch-checked-color, var(--primary-color, #4dd9af)); - --span-switch-off: var(--switch-unchecked-track-color, rgba(120, 120, 120, 0.45)); - --span-switch-thumb-on: var(--switch-checked-button-color, #fff); - --span-switch-thumb-off: var(--switch-unchecked-button-color, #fafafa); --span-switch-track-w: 36px; --span-switch-track-h: 20px; --span-switch-thumb: 14px; + --span-switch-border: 1px; + /* The thumb's gap to the inside of the track's border, the same on every side. */ + --span-switch-inset: calc((var(--span-switch-track-h) - 2 * var(--span-switch-border) - var(--span-switch-thumb)) / 2); + --span-switch-track-color: var(--ha-switch-background-color, var(--ha-color-fill-disabled-quiet-resting, rgba(120, 120, 120, 0.45))); + --span-switch-track-border-color: var(--ha-switch-border-color, var(--ha-color-border-neutral-normal, transparent)); + --span-switch-thumb-color: var(--ha-switch-thumb-background-color, var(--ha-color-on-neutral-normal, #fafafa)); + --span-switch-thumb-border-color: var(--ha-switch-thumb-border-color, var(--ha-color-on-neutral-normal, transparent)); display: inline-flex; align-items: center; vertical-align: middle; @@ -148,49 +151,95 @@ var al={},sl={};var ll,cl=function(){function t(t,e,n){var i=this;this._sleepAft user-select: none; -webkit-tap-highlight-color: transparent; } + :host(:not([checked]):not([disabled]):hover), + :host(:not([checked]):not([disabled]):focus-visible) { + --span-switch-track-color: var( + --ha-switch-background-color-hover, + var(--ha-switch-background-color, var(--ha-color-fill-disabled-quiet-hover, rgba(120, 120, 120, 0.45))) + ); + --span-switch-thumb-color: var( + --ha-switch-thumb-background-color-hover, + var(--ha-switch-thumb-background-color, var(--ha-color-on-neutral-normal, #fafafa)) + ); + --span-switch-thumb-border-color: var( + --ha-switch-thumb-border-color-hover, + var(--ha-switch-thumb-border-color, var(--ha-color-on-neutral-normal, transparent)) + ); + } + :host([checked]) { + --span-switch-track-color: var(--ha-switch-checked-background-color, var(--ha-color-fill-primary-normal-resting, var(--primary-color, #4dd9af))); + --span-switch-track-border-color: var(--ha-switch-checked-border-color, var(--ha-color-border-primary-loud, transparent)); + --span-switch-thumb-color: var(--ha-switch-checked-thumb-background-color, var(--ha-color-on-primary-normal, #fff)); + --span-switch-thumb-border-color: var(--ha-switch-checked-thumb-border-color, var(--ha-color-on-primary-normal, transparent)); + } + :host([checked]:not([disabled]):hover), + :host([checked]:not([disabled]):focus-visible) { + --span-switch-track-color: var( + --ha-switch-checked-background-color-hover, + var(--ha-switch-checked-background-color, var(--ha-color-fill-primary-normal-hover, var(--primary-color, #4dd9af))) + ); + --span-switch-track-border-color: var( + --ha-switch-checked-border-color-hover, + var(--ha-switch-checked-border-color, var(--ha-color-border-primary-loud, transparent)) + ); + --span-switch-thumb-color: var( + --ha-switch-checked-thumb-background-color-hover, + var(--ha-switch-checked-thumb-background-color, var(--ha-color-on-primary-normal, #fff)) + ); + --span-switch-thumb-border-color: var( + --ha-switch-checked-thumb-border-color-hover, + var(--ha-switch-checked-thumb-border-color, var(--ha-color-on-primary-normal, transparent)) + ); + } :host([disabled]) { cursor: not-allowed; - opacity: 0.5; } .track { position: relative; + box-sizing: border-box; width: var(--span-switch-track-w); height: var(--span-switch-track-h); + border: var(--span-switch-border) solid var(--span-switch-track-border-color); border-radius: calc(var(--span-switch-track-h) / 2); - background: var(--span-switch-off); - transition: background 0.2s ease; + background: var(--span-switch-track-color); + transition: + background 0.2s ease, + border-color 0.2s ease; + } + :host([disabled]) .track { + opacity: var(--ha-switch-disabled-opacity, 0.3); } .thumb { position: absolute; top: 50%; - left: 3px; + left: var(--span-switch-inset); + box-sizing: border-box; width: var(--span-switch-thumb); height: var(--span-switch-thumb); + border: var(--span-switch-border) solid var(--span-switch-thumb-border-color); border-radius: 50%; - background: var(--span-switch-thumb-off); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.35); + background: var(--span-switch-thumb-color); + box-shadow: var(--ha-switch-thumb-box-shadow, var(--ha-box-shadow-s, 0 1px 3px rgba(0, 0, 0, 0.35))); transform: translateY(-50%); transition: left 0.2s ease, - background 0.2s ease; - } - :host([checked]) .track { - background: var(--span-switch-on); + background 0.2s ease, + border-color 0.2s ease; } :host([checked]) .thumb { - left: calc(var(--span-switch-track-w) - var(--span-switch-thumb) - 3px); - background: var(--span-switch-thumb-on); + left: calc(var(--span-switch-track-w) - 2 * var(--span-switch-border) - var(--span-switch-inset) - var(--span-switch-thumb)); } - :host(:focus-visible) .track { - outline: 2px solid var(--span-switch-on); - outline-offset: 2px; + /* 's focus ring, which it draws on an enabled switch only: Home Assistant declares it on the document, so it reaches this shadow root, and re-declares it on a themed element. */ + :host(:focus-visible:not([disabled])) .track { + outline: var(--wa-focus-ring, 2px solid var(--ha-color-focus, var(--primary-color, #4dd9af))); + outline-offset: var(--wa-focus-ring-offset, 2px); } - `,_([Et({type:Boolean,reflect:!0})],tI.prototype,"checked",void 0),_([Et({type:Boolean,reflect:!0})],tI.prototype,"disabled",void 0);try{customElements.get("span-switch")||customElements.define("span-switch",tI)}catch{}const eI=[{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 nI=class extends It{constructor(){super(...arguments),this._config={},this._discovered=!1,this._discovering=!1,this._topology=null,this._activeTab="panel",this._panelDevice=null,this._positions=null,this._historyLoaded=!1,this._ctrl=new nA,this._listCtrl=new dA(this._ctrl),this._errorStore=new _A,this._areaSub=null,this._renameSub=null,this._reloadSub=null,this._ratingSub=null,this._topologySource=null,this._topologyRefresh=function(t){let e=null,n=!1;return async function i(){if(e)return n=!0,void await e.catch(()=>{});const r=(async()=>{try{await t()}finally{e=null,n&&(n=!1,await i())}})();e=r,await r}}(()=>this._refreshTopology()),this._beginTopologyEpoch=function(){let t=0;return()=>{t+=1;const e=t;return()=>t!==e}}(),this._tabBarCleanup=null}get _configEntryId(){return t=this._topology,e=this._panelDevice,t?.config_entry_id??e?.config_entry_id??null;var t,e}get _root(){const t=this.shadowRoot;if(!t)throw new Error("span-panel-card: shadow root is not available");return t}connectedCallback(){super.connectedCallback(),this._ctrl.startIntervals(this._root),this._discovered&&this._attachSubscriptions(!0)}disconnectedCallback(){this._ctrl.stopIntervals(),this._listCtrl.stop(),this._detachSubscriptions(),this._beginTopologyEpoch(),this._tabBarCleanup&&(this._tabBarCleanup(),this._tabBarCleanup=null),this._errorStore.dispose(),super.disconnectedCallback()}setConfig(t){this._detachSubscriptions(),this._beginTopologyEpoch(),this._errorStore.clear(),this._config=t,this._discovered=!1,this._discovering=!1,this._historyLoaded=!1,this._topology=null,this._topologySource=null,this._panelDevice=null,this._positions=null,this._activeTab="panel",this._ctrl.reset(),this._ctrl.setConfig(t),this._ctrl.errorStore=this._errorStore}getCardSize(){const t=this._topology?(e=this._topology,n=this._config,sn(e,n)?2:0):0;var e,n;return(this._positions?te(this._positions):0)+3+t}static getConfigElement(){return document.createElement("span-panel-card-editor")}static getStubConfig(){return{device_id:"",history_days:0,history_hours:0,history_minutes:5,chart_metric:o,show_panel:!0,show_battery:!0,show_evse:!0,show_solar:!0}}render(){if(n(this.hass?.language),!this._config.device_id)return this._renderPreview();if(!this._discovered){const t=this._errorStore.hasPersistent("discovery-failed");return ut` + `,C([Ht({type:Boolean,reflect:!0})],$I.prototype,"checked",void 0),C([Ht({type:Boolean,reflect:!0})],$I.prototype,"disabled",void 0);try{customElements.get("span-switch")||customElements.define("span-switch",$I)}catch{}const FI=[{name:"Kitchen",watts:"120",path:"M0,28 L8,26 L16,24 L24,22 L32,25 L40,20 L48,18 L56,22 L64,19 L72,16 L80,18 L88,15 L96,17 L104,14 L112,16 L120,13"},{name:"Living Room",watts:"85",path:"M0,22 L8,24 L16,20 L24,26 L32,18 L40,22 L48,16 L56,20 L64,24 L72,18 L80,22 L88,20 L96,16 L104,22 L112,18 L120,20"},{name:"Master Bed",watts:"193",path:"M0,8 L8,10 L16,8 L24,12 L32,10 L40,8 L48,10 L56,8 L64,10 L72,8 L80,12 L88,10 L96,8 L104,10 L112,8 L120,10"},{name:"HVAC",watts:"64",path:"M0,30 L8,28 L16,26 L24,22 L32,18 L40,14 L48,18 L56,22 L64,26 L72,22 L80,18 L88,22 L96,26 L104,22 L112,18 L120,22"}];let VI=class extends Nt{constructor(){super(...arguments),this._config={},this._discovered=!1,this._discovering=!1,this._topology=null,this._activeTab="panel",this._panelDevice=null,this._positions=null,this._historyLoaded=!1,this._ctrl=new PA,this._listCtrl=new $A(this._ctrl),this._errorStore=new XA,this._areaSub=null,this._renameSub=null,this._reloadSub=null,this._ratingSub=null,this._topologySource=null,this._topologyRefresh=function(t){let e=null,n=!1;return async function i(){if(e)return n=!0,void await e.catch(()=>{});const r=(async()=>{try{await t()}finally{e=null,n&&(n=!1,await i())}})();e=r,await r}}(()=>this._refreshTopology()),this._beginTopologyEpoch=function(){let t=0;return()=>{t+=1;const e=t;return()=>t!==e}}(),this._tabBarCleanup=null}get _configEntryId(){return t=this._topology,e=this._panelDevice,t?.config_entry_id??e?.config_entry_id??null;var t,e}get _root(){const t=this.shadowRoot;if(!t)throw new Error("span-panel-card: shadow root is not available");return t}connectedCallback(){super.connectedCallback(),this._ctrl.startIntervals(this._root),this._discovered&&this._attachSubscriptions(!0)}disconnectedCallback(){this._ctrl.stopIntervals(),this._listCtrl.stop(),this._detachSubscriptions(),this._beginTopologyEpoch(),this._tabBarCleanup&&(this._tabBarCleanup(),this._tabBarCleanup=null),this._errorStore.dispose(),super.disconnectedCallback()}setConfig(t){this._detachSubscriptions(),this._beginTopologyEpoch(),this._errorStore.clear(),this._config=t,this._discovered=!1,this._discovering=!1,this._historyLoaded=!1,this._topology=null,this._topologySource=null,this._panelDevice=null,this._positions=null,this._activeTab="panel",this._ctrl.reset(),this._ctrl.setConfig(t),this._ctrl.errorStore=this._errorStore}getCardSize(){const t=this._topology?(e=this._topology,n=this._config,Nn(e,n)?2:0):0;var e,n;return(this._positions?Pe(this._positions):0)+3+t}static getConfigElement(){return document.createElement("span-panel-card-editor")}static getStubConfig(){return{device_id:"",history_days:0,history_hours:0,history_minutes:5,chart_metric:o,show_panel:!0,show_battery:!0,show_evse:!0,show_solar:!0}}render(){if(n(this.hass?.language),!this._config.device_id)return this._renderPreview();if(!this._discovered){const t=this._errorStore.hasPersistent("discovery-failed");return gt`
- ${t?pt:ut`
${Ot(i("card.connecting"))}
`} + ${t?yt:gt`
${Ft(i("card.connecting"))}
`}
- `}return ut` + `}return gt`
- `}updated(t){if(t.has("hass")&&this.hass&&(n(this.hass.language),this._ctrl.hass=this.hass,this._errorStore.updateHass(this.hass),this._config.device_id))if(this._discovered||this._discovering){if(this._discovered){this._ctrl.recordSamples(),this._ctrl.updateDOM(this._root);const t=this._root.querySelector("span-side-panel");t&&(t.hass=this.hass,t.errorStore=this._errorStore)}this._discovered&&"panel"!==this._activeTab&&this._topology&&this._listCtrl.updateCollapsedRows(this._root,this.hass,this._topology,this._config)}else this._startDiscovery()}async _startDiscovery(){this._discovering||(this._discovering=!0,await this._discoverTopology(),this._errorStore.hasPersistent("discovery-failed")?this._discovering=!1:(this._discovered=!0,this._discovering=!1,this._ctrl.init(this._topology,this._config,this.hass,this._configEntryId),this.isConnected&&this._attachSubscriptions(!1),await this.updateComplete,this._populateCardContent(),this._loadHistory(),this._ctrl.monitoringCache.fetch(this.hass,this._configEntryId).then(()=>{this._discovered&&this._ctrl.updateDOM(this._root)})))}_adoptTopology(t){this._topology=t.topology,this._panelDevice=t.panelDevice,this._positions=Jt(t.topology,t.panelSize)}async _discoverTopology(){if(!this.hass)return;const t=new be(this._errorStore);try{return this._adoptTopology(await bA(this.hass,this._config.device_id,t)),void(this._topologySource="panel_topology")}catch(t){console.error("SPAN Panel: topology fetch failed, falling back to entity discovery",t)}try{this._adoptTopology(await DA(this.hass,this._config.device_id,t)),this._topologySource="entity_fallback"}catch(t){console.error("SPAN Panel: fallback discovery also failed",t),this._errorStore.add({key:"discovery-failed",level:"error",message:i("error.discovery_failed"),persistent:!0,retryFn:()=>{this._errorStore.remove("discovery-failed"),this._startDiscovery()}})}}async _refreshTopology(){const t=this._topologySource;if(!this.hass||!this._discovered||!t)return;const e=this._beginTopologyEpoch();let n;try{n="panel_topology"===t?await bA(this.hass,this._config.device_id,null):await DA(this.hass,this._config.device_id,null)}catch(t){return void console.warn("SPAN Panel: topology refresh failed; keeping the current topology:",fe(t))}if(e())return;if(!n.topology)return void console.warn("SPAN Panel: topology refresh found no panel; keeping the current topology");if(LA(n.topology,this._topology))return;const i=(r=n.topology,!(null!==(o=this._topology)&&LA(RA(r),RA(o))));var r,o;this._adoptTopology(n),this._ctrl.init(this._topology,this._config,this.hass,this._configEntryId),i&&(this._watchPanelStatus(),this._populateCardContent()),this._ctrl.updateDOM(this._root)}_attachSubscriptions(t){if(this._detachSubscriptions(),!this.hass)return;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 pA(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(hA.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=gA(this.hass,()=>this._topology,()=>{this._topologyRefresh()}).catch(t=>(console.warn("SPAN Panel: device rename subscription failed",t),()=>{})),this._reloadSub=async function(t,e,n,{initialIsReseed:i}){const r=t.connection;if(!r)return async()=>{};const o=new Map;let a=!1;return r.subscribeMessage(t=>{if(t.every(t=>null===t.type)){const r=a||i;a=!0,o.clear();for(const{entry:i}of t)e(i)&&(o.set(i.entry_id,i.state),r&&i.state===mA&&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===mA&&t!==mA&&n(r.entry_id)}},{type:"config_entries/subscribe",type_filter:["device"]})}(this.hass,t=>t.entry_id===this._configEntryId,()=>{this._topologyRefresh()},{initialIsReseed:t}).catch(t=>(console.warn("SPAN Panel: config entry subscription failed",t),async()=>{}));const e=this._configEntryId;"panel_topology"===this._topologySource&&e&&(this._ratingSub=yA(this.hass,e,()=>{this._onRatingChanged()}).catch(t=>(console.warn("SPAN Panel: monitoring rating subscription failed",t),()=>{}))),this._watchPanelStatus()}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,i=this._ratingSub;this._areaSub=null,this._renameSub=null,this._reloadSub=null,this._ratingSub=null,t?.then(t=>t()),e?.then(t=>t()),n?.then(t=>t()),i?.then(t=>t())}_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=Ot(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=te(this._positions),n=Zt(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?[Me(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 ce(t)){if(Qt(n))continue;const t=n.tabs;if(!t||0===t.length)continue;const r=Math.min(...t),s=1===t.length?"single":ie(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=ee(Math.max(...n));0===ne(t)?s.add(i):l.add(i)}function c(t){return{monInfo:Ce(r,t.circuit),sheddingPriority:Ye(t.circuit,n)}}const u=t=>t>=e.first&&t<=e.last,d=ee(e.first),h=ee(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}=c(f);p+=nn(f.uuid,f.circuit,e,"2 / 5","row-span",n,i,t,r,f.members),p+=v;continue}if(!s.has(t))if(!f||"col-span"!==f.layout&&"single"!==f.layout)!a.has(r)&&u(r)&&(p+=rn(e,"2"));else{const{monInfo:t,sheddingPriority:r}=c(f);p+=nn(f.uuid,f.circuit,e,"2",f.layout,n,i,t,r,f.members)}if(!l.has(t))if(!g||"col-span"!==g.layout&&"single"!==g.layout)!a.has(h)&&u(h)&&(p+=rn(e,"4"));else{const{monInfo:t,sheddingPriority:r}=c(g);p+=nn(g.uuid,g.circuit,e,"4",g.layout,n,i,t,r,g.members)}p+=v}return p}(this._topology,this._positions,this.hass,this._config,r),s=function(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=wn(Object.entries(t.sub_devices).filter(([,t])=>!(t.type===c&&!o||t.type===u&&!a||t.type===d&&!s)),function(t){if(!function(t){return"_favoriteRefs"in t}(t))return()=>"";const e=t._favoriteRefs;return t=>e[t]?.panelDeviceId??""}(t));if(0===l.length)return"";const h=[];for(const[t,i]of l){const r=mn(i),o=i.type===c,a=o?fn(i):null,s=o?gn(i):null,l=In(i,e,n,vn(i)),u=Dn(t,0,o,r.headlineEid,a,s),d=i.solar?Tn(i.solar,r,e):"";(r.headlineEid||u||l||d)&&h.push({devId:t,sub:i,power:r,chartsHTML:u,entHTML:l,solarHTML:d})}if(0===h.length)return"";const p=h.filter(t=>t.sub.type===u).length;let f=0,g="";for(const{devId:t,sub:n,power:o,chartsHTML:a,entHTML:s,solarHTML:l}of h){const d=Mn(n),h=o.headlineIsSiteTotal?`${Ot(i("subdevice.site_total"))}`:"",m=o.headlineEid?`${h}${Gt(_n(e,o.headlineEid))}`:"",v=xn(n,r.showFavorites)?``:"",y=n.type===c,_=n.type===u;let b="";y?b="sub-device-bess":_&&(f++,f===p&&p%2==1&&(b="sub-device-full")),g+=`\n
\n
\n ${Ot(d)}\n ${Ot(n.name||"")}\n ${m}\n ${v}\n
\n ${a}\n ${l}\n ${s}\n
\n `}return g}(this._topology,this.hass,this._config,{showFavorites:this._ctrl.showFavorites}),l=function(t,e,n){if(!sn(t,n))return"";const r=an(t).map(([t,r])=>`\n
\n ${Ot(r.name||i("grid.unknown"))}\n ${cn(r,e,n)}\n
`).join("");return`\n
\n
${Ot(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 h=t.querySelector(".slide-confirm");if(h){const t=this._root.querySelector(".span-card");this._ctrl.bindSlideConfirm(h,t),t&&t.classList.add("switches-disabled")}const p=this._root.querySelector("span-side-panel");p&&(p.hass=this.hass,p.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=Zt(this._topology,this._config);this._listCtrl.setColumns(Ht()),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=Zt(this._topology,this._config);this._listCtrl.setColumns(Ht()),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=eI.map(t=>ut` + `}updated(t){if(t.has("hass")&&this.hass&&(n(this.hass.language),this._ctrl.hass=this.hass,this._errorStore.updateHass(this.hass),this._config.device_id))if(this._discovered||this._discovering){if(this._discovered){this._ctrl.recordSamples(),this._ctrl.updateDOM(this._root),this._syncRatingSubscription();const t=this._root.querySelector("span-side-panel");t&&(t.hass=this.hass,t.errorStore=this._errorStore)}this._discovered&&"panel"!==this._activeTab&&this._topology&&this._listCtrl.updateCollapsedRows(this._root,this.hass,this._topology,this._config)}else this._startDiscovery()}async _startDiscovery(){this._discovering||(this._discovering=!0,await this._discoverTopology(),this._errorStore.hasPersistent("discovery-failed")?this._discovering=!1:(this._discovered=!0,this._discovering=!1,this._ctrl.init(this._topology,this._config,this.hass,this._configEntryId),this.isConnected&&this._attachSubscriptions(!1),await this.updateComplete,this._populateCardContent(),this._loadHistory(),this._ctrl.monitoringCache.fetch(this.hass,this._configEntryId).then(()=>{this._discovered&&this._ctrl.updateDOM(this._root)})))}_adoptTopology(t){this._topology=t.topology,this._panelDevice=t.panelDevice,this._positions=De(t.topology,t.panelSize)}async _discoverTopology(){if(!this.hass)return;const t=new Ue(this._errorStore);try{return this._adoptTopology(await YA(this.hass,this._config.device_id,t)),void(this._topologySource="panel_topology")}catch(t){console.error("SPAN Panel: topology fetch failed, falling back to entity discovery",t)}try{this._adoptTopology(await oI(this.hass,this._config.device_id,t)),this._topologySource="entity_fallback"}catch(t){console.error("SPAN Panel: fallback discovery also failed",t),this._errorStore.add({key:"discovery-failed",level:"error",message:i("error.discovery_failed"),persistent:!0,retryFn:()=>{this._errorStore.remove("discovery-failed"),this._startDiscovery()}})}}async _refreshTopology(){const t=this._topologySource;if(!this.hass||!this._discovered||!t)return;const e=this._beginTopologyEpoch();let n;try{n="panel_topology"===t?await YA(this.hass,this._config.device_id,null):await oI(this.hass,this._config.device_id,null)}catch(t){return void console.warn("SPAN Panel: topology refresh failed; keeping the current topology:",ee(t))}if(e())return;if(!n.topology)return void console.warn("SPAN Panel: topology refresh found no panel; keeping the current topology");if(sI(n.topology,this._topology))return;const i=(r=n.topology,!(null!==(o=this._topology)&&sI(cI(r),cI(o))));var r,o;this._adoptTopology(n),this._ctrl.init(this._topology,this._config,this.hass,this._configEntryId),this._ctrl.refreshCircuitControlAccess(this._root,this._configEntryId,n.topology),i&&(this._watchPanelStatus(),this._populateCardContent()),this._ctrl.updateDOM(this._root)}_attachSubscriptions(t){this._detachSubscriptions(),this.hass&&(this._areaSub=async function(t,e,n,r){const o=t.connection;if(!o)return()=>{};const a=async()=>{const o=e();if(o)try{const e=new Map;for(const[t,n]of Object.entries(o.circuits))e.set(t,n.area);await VA(t,o);for(const[t,i]of Object.entries(o.circuits))if(i.area!==e.get(t))return void n()}catch(t){console.warn("[span-panel] area registry update failed:",t),r?.add({key:"fetch:areas",level:"warning",message:i("error.areas_failed"),persistent:!1})}},s=await Promise.all(FA.map(t=>o.subscribeEvents(a,t)));return()=>{for(const t of s)t()}}(this.hass,()=>this._topology,()=>{"area"===this._activeTab&&this._discovered&&this._populateCardContent()},this._errorStore).catch(t=>(console.warn("SPAN Panel: area subscription failed",t),this._errorStore.add({key:"subscribe:area",level:"warning",message:i("error.areas_failed"),persistent:!1}),()=>{})),this._renameSub=jA(this.hass,()=>this._topology,()=>{this._topologyRefresh()}).catch(t=>(console.warn("SPAN Panel: device rename subscription failed",t),()=>{})),this._reloadSub=async function(t,e,n,{initialIsReseed:i}){const r=t.connection;if(!r)return async()=>{};const o=new Map;let a=!1;return r.subscribeMessage(t=>{if(t.every(t=>null===t.type)){const r=a||i;a=!0,o.clear();for(const{entry:i}of t)e(i)&&(o.set(i.entry_id,i.state),r&&i.state===qA&&n(i.entry_id));return}for(const{type:i,entry:r}of t){if(!e(r))continue;if("removed"===i){o.delete(r.entry_id);continue}const t=o.get(r.entry_id);o.set(r.entry_id,r.state),"updated"===i&&r.state===qA&&t!==qA&&n(r.entry_id)}},{type:"config_entries/subscribe",type_filter:["device"]})}(this.hass,t=>t.entry_id===this._configEntryId,()=>{this._topologyRefresh()},{initialIsReseed:t}).catch(t=>(console.warn("SPAN Panel: config entry subscription failed",t),async()=>{})),this._syncRatingSubscription(),this._watchPanelStatus())}_syncRatingSubscription(){if(t=this.hass,!0!==t?.user?.is_admin)return void this._dropRatingSubscription();var t;const e=this._configEntryId;this.isConnected&&!this._ratingSub&&"panel_topology"===this._topologySource&&e&&(this._ratingSub=GA(this.hass,e,()=>{this._onRatingChanged()}).catch(t=>(console.warn("SPAN Panel: monitoring rating subscription failed",t),()=>{})))}_dropRatingSubscription(){const t=this._ratingSub;this._ratingSub=null,t?.then(t=>t())}async _onRatingChanged(){this.hass&&this._discovered&&(this._ctrl.monitoringCache.invalidate(),await this._ctrl.monitoringCache.fetch(this.hass,this._configEntryId),await this._topologyRefresh())}_detachSubscriptions(){const t=this._areaSub,e=this._renameSub,n=this._reloadSub;this._areaSub=null,this._renameSub=null,this._reloadSub=null,t?.then(t=>t()),e?.then(t=>t()),n?.then(t=>t()),this._dropRatingSubscription()}_watchPanelStatus(){const t=this._topology?.panel_entities?.panel_status;t&&this.hass&&(this._errorStore.watchPanelStatus(t),this._errorStore.updateHass(this.hass))}async _loadHistory(){if(!this._historyLoaded&&this._topology&&this.hass){this._historyLoaded=!0,await this._ctrl.fetchAndBuildHorizonMaps();try{await this._ctrl.loadHistory(),this._ctrl.updateDOM(this._root)}catch(t){console.warn("SPAN Panel: history fetch failed, charts will populate live",t)}}}_populateCardContent(){const t=this._root.querySelector("#card-content");if(!(t&&this.hass&&this._topology&&this._positions))return;const e=this._root.querySelector("#card-tabs");if(e){const t=[{id:"panel",label:i("tab.by_panel"),icon:"mdi:view-dashboard"},{id:"activity",label:i("tab.by_activity"),icon:"mdi:sort-descending"},{id:"area",label:i("tab.by_area"),icon:"mdi:home-group"}];e.innerHTML=(n=t,r=this._activeTab,o=this._config.tab_style??"text",`
${n.map(t=>{const e=t.id===r?" active":"",n=Ft(t.id);return"icon"===o?``:``}).join("")}
`),this._tabBarCleanup&&(this._tabBarCleanup(),this._tabBarCleanup=null),this._tabBarCleanup=function(t,e){const n=t=>{const n=t.target.closest(".shared-tab");if(n){const t=n.dataset.tab;t&&e(t)}};return t.addEventListener("click",n),()=>{t.removeEventListener("click",n)}}(e,t=>{["panel","activity","area"].includes(t)&&(this._activeTab=t,this._listCtrl.stop(),this._populateCardContent())})}var n,r,o;if("panel"===this._activeTab){const e=Pe(this._positions),n=Te(this._topology,this._config),r=this._ctrl.monitoringCache.status,o=function(t){if(!t)return"";const e=Object.values(t.circuits??{}),n=Object.values(t.mains??{}),r=new Map(Object.entries(t.circuits??{}).map(([t,e])=>[void 0!==e.point_id?`point:${e.point_id}`:`entry:${t}`,e])),o=[...r.values(),...n],a=o.flatMap(t=>null!=t.utilization_pct?[Qe(t.utilization_pct,t)]:[]),s=a.filter(t=>"warning"===t).length,l=a.filter(t=>"alert"===t).length,c=o.filter(t=>t.has_override).length;return`\n
\n ✓ ${i("status.monitoring")} · ${e.length} ${i("status.circuits")} · ${n.length} ${i("status.mains")}\n \n ${s>0?`${s} ${i(s>1?"status.warnings":"status.warning")}`:""}\n ${l>0?`${l} ${i(l>1?"status.alerts":"status.alert")}`:""}\n ${c>0?`${c} ${i(c>1?"status.overrides":"status.override")}`:""}\n \n
\n `}(r),a=function(t,e,n,i,r){const o=new Map,a=new Set;for(const{uuid:e,circuit:n,members:i}of $e(t)){if(Ie(n))continue;const t=n.tabs;if(!t||0===t.length)continue;const r=Math.min(...t),s=1===t.length?"single":Ne(t)??"single";o.set(r,{uuid:e,circuit:n,members:i,layout:s});for(const e of t)a.add(e)}const s=new Set,l=new Set;for(const[t,e]of o)if("col-span"===e.layout){const n=e.circuit.tabs,i=Le(Math.max(...n));0===Ee(t)?s.add(i):l.add(i)}function c(e){return{monInfo:Ze(r,e.circuit),sheddingPriority:wn(e.circuit,n),access:ge(t,e.uuid)}}const u=t=>t>=e.first&&t<=e.last,d=Le(e.first),h=Le(e.last);let p="";for(let t=d;t<=h;t++){const e=t-d+1,r=2*t-1,h=2*t,f=o.get(r),g=o.get(h),m=u(r)?`
${r}
`:"",v=u(h)?`
${h}
`:"";if(p+=m,f&&"row-span"===f.layout){const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=Dn(f.uuid,f.circuit,e,"2 / 5","row-span",n,i,t,r,o,f.members),p+=v;continue}if(!s.has(t))if(!f||"col-span"!==f.layout&&"single"!==f.layout)!a.has(r)&&u(r)&&(p+=Pn(e,"2"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=Dn(f.uuid,f.circuit,e,"2",f.layout,n,i,t,r,o,f.members)}if(!l.has(t))if(!g||"col-span"!==g.layout&&"single"!==g.layout)!a.has(h)&&u(h)&&(p+=Pn(e,"4"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(g);p+=Dn(g.uuid,g.circuit,e,"4",g.layout,n,i,t,r,o,g.members)}p+=v}return p}(this._topology,this._positions,this.hass,this._config,r),s=ti(this._topology,this.hass,this._config,{showFavorites:this._ctrl.showFavorites}),l=function(t,e,n){if(!Nn(t,n))return"";const r=En(t).map(([t,r])=>`\n
\n ${Ft(r.name||i("grid.unknown"))}\n ${On(r,e,n)}\n
`).join("");return`\n
\n
${Ft(i("meters.title"))}
\n ${r}\n
\n `}(this._topology,this.hass,this._config);t.innerHTML=`\n ${n}\n ${o}\n ${s?`
${s}
`:""}\n ${l}\n ${!1!==this._config.show_panel?`
${a}
`:""}\n `;const c=t.querySelector(".slide-confirm");if(c){const t=this._root.querySelector(".span-card");this._ctrl.bindSlideConfirm(c,t),t&&t.classList.add("switches-disabled")}const u=this._root.querySelector("span-side-panel");u&&(u.hass=this.hass,u.errorStore=this._errorStore),this._ctrl.recordSamples(),this._ctrl.updateDOM(this._root),this._ctrl.setupResizeObserver(this._root,this._root.querySelector(".span-card"))}else if("activity"===this._activeTab){t.innerHTML="";const e=Te(this._topology,this._config);this._listCtrl.setColumns(Wt()),this._listCtrl.renderActivityView(t,this.hass,this._topology,this._config,this._ctrl.monitoringCache.status,e),this._ctrl.updateDOM(this._root)}else if("area"===this._activeTab){t.innerHTML="";const e=Te(this._topology,this._config);this._listCtrl.setColumns(Wt()),this._listCtrl.renderAreaView(t,this.hass,this._topology,this._config,this._ctrl.monitoringCache.status,e),this._ctrl.updateDOM(this._root)}}_onCardClick(t){if("panel"!==this._activeTab)return;const e=t.target;if(!e)return;const n=e.closest(".unit-btn");if(n)return void this._onUnitToggle(n);if(e.closest(".toggle-pill"))return void this._ctrl.onToggleClick(t,this._root);e.closest(".gear-icon")&&this._ctrl.onGearClick(t,this._root)}async _onUnitToggle(t){const e=t.dataset.unit;e&&e!==(this._config.chart_metric??"power")&&(this._config={...this._config,chart_metric:e},this._ctrl.setConfig(this._config),this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:this._config},bubbles:!0,composed:!0})),this._ctrl.powerHistory.clear(),this._historyLoaded=!1,this._populateCardContent(),await this._loadHistory(),this._ctrl.updateDOM(this._root))}async _onListUnitChanged(t){const e=t.detail;e&&e!==(this._config.chart_metric??"power")&&(this._config={...this._config,chart_metric:e},this._ctrl.setConfig(this._config),this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:this._config},bubbles:!0,composed:!0})),this._ctrl.powerHistory.clear(),this._historyLoaded=!1,this._populateCardContent(),await this._loadHistory(),this._ctrl.updateDOM(this._root))}_onGraphSettingsChanged(){this._ctrl.onGraphSettingsChanged(this._root)}_onListColumnsChanged(t){const e=t.detail;"number"!=typeof e||1!==e&&2!==e&&3!==e||"activity"!==this._activeTab&&"area"!==this._activeTab||this._populateCardContent()}_onSidePanelClosed(){this._ctrl.monitoringCache.invalidate(),this._ctrl.graphSettingsCache.invalidate()}_renderPreview(){const t=FI.map(t=>gt`
${t.name} @@ -216,7 +265,7 @@ var al={},sl={};var ll,cl=function(){function t(t,e,n){var i=this;this._sleepAft
- `);return ut` + `);return gt`
@@ -227,4 +276,4 @@ var al={},sl={};var ll,cl=function(){function t(t,e,n){var i=this;this._sleepAft
${i("card.no_device")}
- `}};function iI(t,e){return wn(Object.entries(t)).filter(([,t])=>t.type===e).map(([t,e])=>{const n=vn(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}})}nI.styles=k('\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 .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 .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\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'),_([Et({attribute:!1})],nI.prototype,"hass",void 0),_([Nt()],nI.prototype,"_config",void 0),_([Nt()],nI.prototype,"_discovered",void 0),_([Nt()],nI.prototype,"_discovering",void 0),_([Nt()],nI.prototype,"_topology",void 0),_([Nt()],nI.prototype,"_activeTab",void 0),nI=_([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})("span-panel-card")],nI);class rI extends HTMLElement{constructor(){super(...arguments),this._config={},this._hass=null,this._panels=null,this._availableRoles=null,this._built=!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._discoverPanels()}async _discoverPanels(){if(!this._hass)return;const t=await this._hass.callWS({type:"config/device_registry/list"});this._panels=t.filter(Sn).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 iI(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(p)){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}}))}}try{customElements.get("span-panel-card-editor")||customElements.define("span-panel-card-editor",rI)}catch{}window.customCards=window.customCards??[],window.customCards.push({type:"span-panel-card",name:"SPAN Panel",description:"Physical panel layout with live power charts matching the SPAN frontend",preview:!0}),console.warn("%c SPAN-PANEL-CARD %c v0.11.0 ","background: var(--primary-color, #4dd9af); color: var(--text-primary-color, #000); font-weight: 700; padding: 2px 6px; border-radius: 4px 0 0 4px;","background: var(--secondary-background-color, #333); color: var(--primary-text-color, #fff); padding: 2px 6px; border-radius: 0 4px 4px 0;"); + `}};function WI(t){const e=new Set;for(const n of Object.values(t.entities??{})){if(n.platform!==l||!n.device_id)continue;const i=t.devices?.[n.device_id]?.config_entry_id;i&&e.add(i)}return e}function jI(t,e){return Yn(Object.entries(t)).filter(([,t])=>t.type===e).map(([t,e])=>{const n=jn(e),i=e.name??"",r=Object.entries(e.entities??{}).filter(([t])=>!n.has(t)).map(([t,e])=>{let n=e.original_name??t;return i&&n.startsWith(i+" ")&&(n=n.slice(i.length+1)),{entityId:t,label:n}});return{devId:t,name:i||t,entities:r}})}VI.styles=D('\n :host {\n --span-accent: var(--primary-color, #4dd9af);\n }\n\n /* Card shell — replaces . Theme variables (--ha-card-*) are\n stable HA contracts (not the deprecated component APIs flagged by the\n 2026.4 frontend blog), so they stay in place to keep visual parity\n with the rest of HA\'s dashboards. */\n .span-card {\n display: block;\n padding: 24px;\n background: var(--card-background-color, #1c1c1c);\n color: var(--primary-text-color, #e0e0e0);\n border-radius: var(--ha-card-border-radius, 12px);\n border: var(--ha-card-border-width, 1px) solid var(--ha-card-border-color, var(--divider-color, #333));\n box-shadow: var(--ha-card-box-shadow, none);\n }\n\n .panel-header {\n display: flex;\n flex-wrap: wrap;\n justify-content: space-between;\n align-items: flex-start;\n gap: 8px 16px;\n margin-bottom: 20px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n .header-left { flex: 1 1 300px; min-width: 0; }\n .header-center { flex: 0 0 auto; }\n .header-right { flex: 0 1 auto; min-width: 0; }\n\n .panel-identity {\n display: flex;\n align-items: center;\n flex-wrap: wrap;\n gap: 8px 12px;\n margin-bottom: 12px;\n }\n\n .panel-title {\n font-size: 1.8em;\n font-weight: 700;\n margin: 0;\n color: var(--primary-text-color, #fff);\n }\n\n .panel-serial {\n font-size: 0.85em;\n color: var(--secondary-text-color, #999);\n font-family: monospace;\n }\n\n .panel-stats {\n display: flex;\n flex-wrap: wrap;\n gap: 16px 32px;\n }\n\n /* Favorites view header: gear + slide-to-arm + right-anchored legend/W-A cluster. */\n .favorites-summary {\n padding: 8px 24px;\n border-bottom: 1px solid var(--divider-color, #e0e0e0);\n display: flex;\n align-items: center;\n gap: 12px;\n }\n /* Override the generic .gear-icon { margin-left: auto } rule so the\n favorites gear stays flush-left instead of floating to the right of\n the flex row (same idea as .panel-identity .panel-gear does for\n real-panel headers). */\n .favorites-summary .favorites-gear {\n margin-left: 0;\n }\n /* Right-anchored cluster wrapping the shedding legend + W/A unit toggle.\n margin-left:auto moved here from .favorites-summary-unit-toggle so the\n legend and toggle cluster together, matching the real-panel header\n layout. */\n .favorites-summary-right {\n margin-left: auto;\n display: flex;\n align-items: center;\n gap: 16px;\n }\n .favorites-subdevices-section {\n padding: 8px 16px 0;\n }\n\n /* Favorites view: responsive grid of per-contributing-panel status cards. */\n .favorites-panel-stats-grid {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));\n gap: 12px;\n padding: 12px 24px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n .favorites-panel-card {\n background: var(--secondary-background-color, rgba(255, 255, 255, 0.04));\n border: 1px solid var(--divider-color, #333);\n border-radius: 8px;\n padding: 10px 14px;\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n .favorites-panel-card-title {\n font-size: 0.85em;\n font-weight: 600;\n color: var(--primary-text-color);\n opacity: 0.85;\n }\n .favorites-panel-card .controls-note {\n margin: 2px 0 6px;\n }\n .favorites-panel-card .panel-stats {\n gap: 10px 20px;\n }\n .favorites-panel-card .stat-value {\n font-size: 1.15em;\n }\n\n .stat { display: flex; flex-direction: column; }\n .stat-label { font-size: 0.8em; color: var(--secondary-text-color, #999); margin-bottom: 2px; }\n .stat-row { display: flex; align-items: baseline; gap: 2px; }\n .stat-value { font-size: 1.5em; font-weight: 700; color: var(--primary-text-color, #fff); }\n /* A sum that left out a term with no reading: dimmed, and marked as at least this much. */\n .stat-value.stat-partial { opacity: 0.7; }\n .stat-value.stat-partial::after { content: "+"; }\n .stat-unit { font-size: 0.7em; font-weight: 400; color: var(--secondary-text-color, #999); }\n\n .header-right { display: flex; flex-direction: column; align-items: flex-end; gap: 8px; padding-top: 8px; }\n .header-right-top { display: flex; gap: 20px; align-items: center; }\n .meta-item { font-size: 0.8em; color: var(--secondary-text-color, #999); }\n\n .shedding-legend { display: flex; gap: 12px; flex-wrap: wrap; justify-content: flex-end; }\n .shedding-legend-item { display: inline-flex; align-items: center; gap: 3px; }\n .shedding-legend-item span-icon { --mdc-icon-size: 16px; }\n .shedding-legend-secondary { --mdc-icon-size: 12px; opacity: 0.8; }\n .shedding-legend-text { font-size: 9px; font-weight: 600; }\n .shedding-legend-label { font-size: 0.7em; color: var(--secondary-text-color, #999); }\n\n .panel-gear {\n background: none;\n border: none;\n cursor: pointer;\n color: var(--secondary-text-color);\n opacity: 0.6;\n padding: 4px;\n margin-left: 8px;\n vertical-align: middle;\n }\n .panel-gear:hover { opacity: 1; }\n .header-center {\n display: flex;\n align-items: flex-start;\n justify-content: center;\n padding-top: 8px;\n }\n .panel-identity .panel-gear {\n margin-left: 0;\n }\n .slide-confirm {\n position: relative;\n display: inline-flex;\n align-items: center;\n width: 160px;\n height: 28px;\n border-radius: 14px;\n background: color-mix(in srgb, var(--primary-color, #4dd9af) 20%, var(--secondary-background-color, #333));\n vertical-align: middle;\n overflow: hidden;\n user-select: none;\n touch-action: none;\n }\n .slide-confirm-text {\n position: absolute;\n width: 100%;\n text-align: center;\n font-size: 0.65em;\n font-weight: 600;\n color: var(--secondary-text-color, #999);\n pointer-events: none;\n z-index: 0;\n }\n .slide-confirm-knob {\n position: absolute;\n left: 2px;\n top: 2px;\n width: 24px;\n height: 24px;\n border-radius: 50%;\n background: var(--secondary-text-color, #666);\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: grab;\n z-index: 1;\n transition: none;\n }\n .slide-confirm-knob span-icon {\n --mdc-icon-size: 14px;\n color: var(--card-background-color, #1c1c1c);\n }\n .slide-confirm-knob.snapping {\n transition: left 0.25s ease;\n }\n .slide-confirm.confirmed {\n background: color-mix(in srgb, var(--state-active-color, var(--span-accent)) 25%, transparent);\n }\n .slide-confirm.confirmed .slide-confirm-text {\n color: var(--state-active-color, var(--span-accent));\n }\n .slide-confirm.confirmed .slide-confirm-knob {\n background: var(--state-active-color, var(--span-accent));\n }\n .switches-disabled .toggle-pill {\n opacity: 0.3;\n pointer-events: none;\n }\n /* The slider where the user may operate none of the view\'s controls: dimmed, and never armed. */\n .slide-confirm.slide-confirm-forbidden {\n opacity: 0.5;\n cursor: not-allowed;\n }\n .slide-confirm.slide-confirm-forbidden .slide-confirm-knob {\n cursor: not-allowed;\n }\n /* Its note, saying why: on a line of its own under the panel\'s name, or under each panel\'s name in the Favorites stats grid. */\n .controls-note {\n margin: 0;\n font-size: 0.8em;\n color: var(--secondary-text-color, #727272);\n }\n .panel-identity .controls-note {\n flex-basis: 100%;\n }\n .unit-toggle {\n display: inline-flex;\n background: var(--secondary-background-color, #333);\n border-radius: 6px;\n overflow: hidden;\n margin-left: 8px;\n }\n .unit-btn {\n padding: 4px 10px;\n border: none;\n background: none;\n color: var(--secondary-text-color);\n font-size: 0.75em;\n font-weight: 600;\n cursor: pointer;\n }\n .unit-btn.unit-active {\n background: var(--primary-color, #4dd9af);\n color: var(--text-primary-color, #000);\n }\n\n .monitoring-summary {\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 6px 16px;\n font-size: 0.8em;\n background: rgba(76, 175, 80, 0.1);\n border: 1px solid var(--divider-color, #333);\n border-top: none;\n }\n .monitoring-active { color: #4caf50; }\n .monitoring-counts { display: flex; gap: 12px; }\n .count-warning { color: #ff9800; }\n .count-alert { color: #f44336; }\n .count-overrides { color: var(--secondary-text-color); }\n\n .panel-grid {\n display: grid;\n /* Five columns: left tab label, left cell, explicit 8px spacer,\n right cell, right tab label. Spacer is in-band rather than a\n column-gap so we can keep inter-cell space without paying an\n equal gap between each cell and its tab label. The tab columns\n are sized to fit a 2-digit breaker number (the font is 0.85em\n of the panel body ≈ 14px glyph width). */\n grid-template-columns: 14px 1fr 8px 1fr 14px;\n column-gap: 0;\n row-gap: 8px;\n align-items: stretch;\n }\n\n .tab-label {\n display: flex;\n align-items: center;\n font-size: 0.85em;\n font-weight: 600;\n color: var(--secondary-text-color, #999);\n user-select: none;\n }\n .tab-left { justify-content: flex-start; }\n .tab-right { justify-content: flex-end; }\n\n .circuit-slot {\n background: var(--secondary-background-color, var(--card-background-color, #2a2a2a));\n border: 1px solid var(--divider-color, #333);\n border-radius: 12px;\n padding: 14px 16px 20px;\n min-height: 140px;\n transition: opacity 0.3s;\n position: relative;\n overflow: hidden;\n }\n\n .circuit-col-span { min-height: 280px; }\n .circuit-row-span { border-left: 3px solid var(--span-accent); }\n .circuit-off .circuit-name,\n .circuit-off .breaker-badge,\n .circuit-off .power-value,\n .circuit-off .chart-container { opacity: 0.35; }\n .circuit-off .toggle-pill,\n .circuit-off .gear-icon { opacity: 1; }\n\n .circuit-empty {\n opacity: 0.2;\n min-height: 60px;\n display: flex;\n align-items: center;\n justify-content: center;\n border-style: dashed;\n }\n .empty-label { color: var(--secondary-text-color, #999); font-size: 0.85em; }\n\n .circuit-header {\n display: flex;\n justify-content: space-between;\n align-items: flex-start;\n margin-bottom: 6px;\n gap: 8px;\n }\n\n .circuit-info { display: flex; align-items: center; gap: 8px; flex: 1; min-width: 0; }\n\n .breaker-badge {\n background: color-mix(in srgb, var(--span-accent) 15%, transparent);\n color: var(--span-accent);\n font-size: 0.7em;\n font-weight: 700;\n padding: 2px 3px;\n border-radius: 4px;\n white-space: nowrap;\n border: 1px solid color-mix(in srgb, var(--span-accent) 25%, transparent);\n flex-shrink: 0;\n }\n\n /* The pencil that marks a rating from a copied package, a button so a tap or a key can show what it says. */\n .rating-user-set {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 24px;\n min-height: 24px;\n margin-left: 2px;\n padding: 0 2px;\n border: none;\n border-radius: 3px;\n background: none;\n color: inherit;\n font: inherit;\n font-weight: 400;\n line-height: inherit;\n cursor: help;\n }\n .rating-user-set:focus-visible {\n outline: 2px solid var(--primary-color, #03a9f4);\n outline-offset: 1px;\n }\n .rating-copied-note {\n display: block;\n margin-top: 2px;\n font-size: 0.85em;\n color: var(--secondary-text-color, #727272);\n white-space: normal;\n }\n .rating-copied-note[hidden] {\n display: none;\n }\n\n .circuit-name {\n font-size: 0.9em;\n font-weight: 500;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--primary-text-color, #e0e0e0);\n }\n\n .circuit-controls { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }\n\n /* Truncation-driven fold for By Panel breaker cells. The .is-folded\n class is added/removed by the JS observer in\n src/core/truncation-fold.ts when the .circuit-name actually\n ellipsizes. Pixel thresholds can\'t get this right because name\n length varies wildly per circuit (e.g. "Spa" vs\n "Commissioned PV System") — only measuring the live name vs its\n container catches the exact moment of truncation.\n\n When folded the nested flex wrappers (.circuit-header,\n .circuit-info, .circuit-controls, .circuit-status) collapse via\n \'display: contents\' so the leaf elements participate directly in\n the outer grid: name gets the whole first row, readings/controls/\n gear drop to a second row, chart stays as the full-width third. */\n .circuit-slot.is-folded {\n display: grid;\n /* Columns: badges + relay-toggle pack tight on the left, slack\n absorbed by the 1fr column between the relay and the power\n reading, keeping power + gear pinned to the right edge. The\n previous layout placed the slack between the shedding icon and\n the relay, which read as wasted padding the user pointed out. */\n grid-template-columns: auto auto auto auto 1fr auto auto;\n /* Rows: name and controls sized to content; chart absorbs any\n extra cell height. Without the explicit 1fr on row 3, a tall\n cell (e.g. .circuit-col-span\'s 280px min-height for 240V\n double-pole breakers) distributes excess space equally across\n all three rows via the default align-content:stretch, which\n pushes the chart down and vertically inflates the badge and\n relay toggle to fill the controls row. */\n grid-template-rows: auto auto 1fr;\n grid-template-areas:\n "name name name name name name name"\n "badge util shed status . power gear"\n "chart chart chart chart chart chart chart";\n row-gap: 6px;\n column-gap: 8px;\n }\n .circuit-slot.is-folded > .circuit-header,\n .circuit-slot.is-folded > .circuit-status,\n .circuit-slot.is-folded > .circuit-header > .circuit-info,\n .circuit-slot.is-folded > .circuit-header > .circuit-controls {\n display: contents;\n }\n .circuit-slot.is-folded .circuit-name {\n grid-area: name;\n justify-self: start;\n }\n .circuit-slot.is-folded .breaker-badge {\n grid-area: badge;\n }\n .circuit-slot.is-folded .utilization {\n grid-area: util;\n }\n .circuit-slot.is-folded .shedding-icon,\n .circuit-slot.is-folded .shedding-composite {\n grid-area: shed;\n }\n .circuit-slot.is-folded .toggle-pill {\n grid-area: status;\n justify-self: end;\n }\n .circuit-slot.is-folded .power-value {\n grid-area: power;\n justify-self: end;\n }\n .circuit-slot.is-folded .gear-icon.circuit-gear {\n grid-area: gear;\n justify-self: end;\n }\n .circuit-slot.is-folded > .chart-container {\n grid-area: chart;\n }\n\n .power-value { font-size: 0.9em; color: var(--primary-text-color, #fff); white-space: nowrap; }\n .power-value strong { font-weight: 700; font-size: 1.1em; }\n .power-unit { font-size: 0.8em; font-weight: 400; color: var(--secondary-text-color, #999); margin-left: 1px; }\n .circuit-producer .power-value strong { color: var(--info-color, #4fc3f7); }\n\n .toggle-pill {\n display: flex;\n align-items: center;\n gap: 3px;\n padding: 2px 4px;\n border-radius: 10px;\n cursor: pointer;\n font-size: 0.65em;\n font-weight: 600;\n transition: background 0.2s;\n user-select: none;\n min-width: 40px;\n }\n .toggle-on {\n padding-left: 6px;\n background: color-mix(in srgb, var(--state-active-color, var(--span-accent)) 25%, transparent);\n color: var(--state-active-color, var(--span-accent));\n }\n .toggle-off {\n padding-right: 6px;\n background: color-mix(in srgb, var(--secondary-text-color) 15%, transparent);\n color: var(--secondary-text-color, #999);\n }\n .toggle-knob {\n width: 14px;\n height: 14px;\n border-radius: 50%;\n transition: background 0.2s, margin 0.2s;\n }\n .toggle-on .toggle-knob {\n background: var(--state-active-color, var(--span-accent));\n margin-left: auto;\n }\n .toggle-off .toggle-knob {\n background: var(--secondary-text-color, #999);\n margin-right: auto;\n order: -1;\n }\n /* A switch Home Assistant reports unavailable: the relay state is still\n shown, but the pill cannot be operated. */\n .toggle-pill.toggle-unavailable {\n opacity: 0.4;\n pointer-events: none;\n cursor: default;\n }\n /* Locked switches dim every pill to 0.3; an inert one stays dimmer still. */\n .switches-disabled .toggle-pill.toggle-unavailable {\n opacity: 0.2;\n }\n /* A switch the user may not operate: the relay state is still shown, and the\n pill, titled with why, sends nothing. Dimmer still while the switches are locked. */\n .toggle-pill.toggle-forbidden {\n opacity: 0.4;\n cursor: not-allowed;\n }\n .switches-disabled .toggle-pill.toggle-forbidden {\n opacity: 0.2;\n }\n\n .circuit-status {\n display: flex;\n align-items: center;\n gap: 4px;\n margin-top: 4px;\n padding: 0 4px;\n }\n .shedding-icon { opacity: 0.8; cursor: default; }\n .shedding-composite {\n display: inline-flex;\n align-items: center;\n gap: 2px;\n }\n .shedding-icon-secondary { opacity: 0.8; }\n .shedding-label {\n font-size: 10px;\n font-weight: 600;\n opacity: 0.8;\n }\n .gear-icon {\n background: none;\n border: none;\n cursor: pointer;\n padding: 2px;\n opacity: 0.6;\n transition: opacity 0.2s;\n margin-left: auto;\n }\n .gear-icon:hover { opacity: 1; }\n .utilization {\n font-size: 0.75em;\n font-weight: 600;\n }\n .utilization-normal { color: #4caf50; }\n .utilization-warning { color: #ff9800; }\n .utilization-alert { color: #f44336; }\n .circuit-alert {\n border-color: #f44336 !important;\n box-shadow: 0 0 8px rgba(244, 67, 54, 0.3);\n }\n .chart-container {\n width: 100%;\n aspect-ratio: 4 / 1;\n margin-top: 4px;\n overflow: hidden;\n min-width: 0;\n }\n\n .sub-devices {\n display: grid;\n grid-template-columns: repeat(2, 1fr);\n gap: 12px;\n margin-bottom: 20px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n\n /* Meters outside the panel: no breaker space, so a strip above the grid. */\n .meters-strip {\n display: flex;\n flex-wrap: wrap;\n gap: 12px;\n margin-bottom: 20px;\n padding-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n .meters-title { flex-basis: 100%; font-size: 0.7em; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--span-accent); }\n .meter-tile {\n flex: 1 1 220px;\n min-width: 0;\n display: flex;\n flex-direction: column;\n gap: 6px;\n background: var(--secondary-background-color, var(--card-background-color, #2a2a2a));\n border: 1px solid var(--divider-color, #333);\n border-radius: 12px;\n padding: 12px 16px;\n }\n .meter-name {\n font-size: 0.9em;\n font-weight: 500;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n color: var(--primary-text-color, #e0e0e0);\n }\n .meter-readings { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 10px; font-size: 0.85em; color: var(--secondary-text-color, #999); }\n .meter-value { font-size: 1.05em; color: var(--primary-text-color, #fff); white-space: nowrap; }\n .meter-value strong { font-weight: 700; font-size: 1.1em; }\n .meter-direction:empty { display: none; }\n\n .sub-device {\n background: var(--secondary-background-color, var(--card-background-color, #2a2a2a));\n border: 1px solid var(--divider-color, #333);\n border-radius: 12px;\n padding: 14px 16px;\n }\n .sub-device-bess,\n .sub-device-full {\n grid-column: 1 / -1;\n }\n\n .sub-device-header { display: flex; gap: 10px; align-items: baseline; margin-bottom: 8px; }\n .sub-device-type { font-size: 0.7em; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--span-accent); }\n .sub-device-name { font-size: 0.85em; color: var(--secondary-text-color, #999); flex: 1; }\n .sub-power-value { font-size: 0.9em; color: var(--primary-text-color, #fff); white-space: nowrap; }\n .sub-power-value strong { font-weight: 700; font-size: 1.1em; }\n .sub-device .chart-container { margin-bottom: 8px; aspect-ratio: auto; }\n\n .bess-charts {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(0, 1fr));\n gap: 12px;\n margin-bottom: 10px;\n }\n .bess-chart-col { min-width: 0; }\n .bess-chart-title {\n font-size: 0.75em;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.04em;\n color: var(--secondary-text-color, #999);\n margin-bottom: 4px;\n }\n .bess-chart-col .chart-container { aspect-ratio: auto; }\n .sub-entity { display: flex; gap: 6px; padding: 3px 0; font-size: 0.85em; }\n .sub-entity-name { color: var(--secondary-text-color, #999); }\n .sub-entity-value { font-weight: 500; color: var(--primary-text-color, #e0e0e0); }\n .sub-identity { font-size: 0.85em; color: var(--secondary-text-color, #999); margin: 2px 0 6px; }\n .sub-note { font-size: 0.85em; color: var(--secondary-text-color, #999); font-style: italic; margin-top: 4px; }\n .sub-power-caption { font-size: 0.75em; color: var(--secondary-text-color, #999); margin-right: 6px; text-transform: uppercase; }\n\n /* ── Shared tab bar ────────────────────────────────────── */\n\n .shared-tab-bar {\n display: flex;\n gap: 0;\n margin-bottom: 16px;\n border-bottom: 1px solid var(--divider-color, #333);\n }\n\n .shared-tab {\n padding: 8px 16px;\n cursor: pointer;\n font-size: 0.9em;\n font-weight: 500;\n color: var(--primary-text-color);\n opacity: 0.6;\n border: none;\n border-bottom: 2px solid transparent;\n background: none;\n transition: opacity 0.15s;\n }\n\n .shared-tab:hover {\n opacity: 0.85;\n }\n\n .shared-tab.active {\n opacity: 1;\n border-bottom-color: var(--span-accent);\n }\n\n /* ── List view search ──────────────────────────────────── */\n\n .list-search-container {\n margin-bottom: 12px;\n position: relative;\n }\n\n .list-search {\n width: 100%;\n padding: 8px 36px 8px 12px;\n border-radius: 8px;\n border: 1px solid var(--divider-color, #333);\n background: var(--secondary-background-color, #2a2a2a);\n color: var(--primary-text-color);\n font-size: 0.9em;\n box-sizing: border-box;\n outline: none;\n }\n\n .list-search:focus {\n border-color: var(--span-accent);\n }\n\n .list-search-clear {\n position: absolute;\n right: 8px;\n top: 50%;\n transform: translateY(-50%);\n background: none;\n border: none;\n color: var(--secondary-text-color);\n cursor: pointer;\n padding: 2px;\n display: flex;\n align-items: center;\n opacity: 0.7;\n }\n\n .list-search-clear:hover {\n opacity: 1;\n }\n\n .list-unit-toggle {\n display: inline-flex;\n margin-bottom: 12px;\n }\n\n /* ── List rows ─────────────────────────────────────────── */\n\n .list-view {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n /* Each circuit is wrapped in a .list-cell so the row + its optional\n expanded chart stay together. In single-column flex mode the cell\n just stacks naturally. In multi-column grid mode the cell becomes\n one grid item, so the chart is always in the same column as its\n row. Area headers (rendered as siblings, not inside a cell) span\n all columns via their inline "grid-column: 1 / -1". */\n .list-cell {\n display: flex;\n flex-direction: column;\n min-width: 0;\n }\n .list-view[data-columns="2"],\n .list-view[data-columns="3"] {\n display: grid;\n grid-template-columns: repeat(var(--list-cols), minmax(0, 1fr));\n gap: 6px 8px;\n flex-direction: initial;\n }\n /* On narrow viewports a 2/3-column list would squeeze rows into an\n unreadable shape, so force stacking regardless of user preference. */\n @media (max-width: 599px) {\n .list-view[data-columns="2"],\n .list-view[data-columns="3"] {\n display: flex;\n flex-direction: column;\n }\n }\n\n .list-row {\n display: flex;\n align-items: center;\n padding: 12px 16px;\n gap: 10px;\n /* min-width: 0 lets the row shrink below the sum of its\n non-shrinking children when its parent .list-cell is in a\n narrow CSS-grid track (multi-column list mode). Without this\n the row would maintain its intrinsic min-content width and\n overflow the cell, leaving the name unshrunk and the\n truncation-fold observer with no signal to react to. */\n min-width: 0;\n background: var(--card-background-color, #1c1c1c);\n border: 1px solid var(--divider-color, #333);\n border-radius: 8px;\n cursor: pointer;\n transition: background 0.15s;\n }\n\n .list-row:hover {\n background: var(--secondary-background-color, #2a2a2a);\n }\n\n .list-row.circuit-off {\n opacity: 0.5;\n }\n\n .list-row.list-row-expanded {\n border-bottom-left-radius: 0;\n border-bottom-right-radius: 0;\n border-bottom-color: transparent;\n }\n\n .list-circuit-name {\n flex: 1;\n color: var(--primary-text-color);\n font-size: 0.9em;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .list-status-badge {\n font-size: 0.75em;\n font-weight: 600;\n padding: 2px 8px;\n border-radius: 4px;\n flex-shrink: 0;\n }\n\n .list-status-on {\n color: #4dd9af;\n }\n\n .list-status-off {\n color: #f44336;\n }\n\n .list-power-value {\n font-size: 0.9em;\n font-weight: 600;\n flex-shrink: 0;\n /* No min-width / text-align:right: the old 70px right-aligned\n cell left a visible blank column for short readings (e.g.\n "1.3A" in a 70px slot), which robbed horizontal space from\n .list-circuit-name on narrow rows. Let the value hug the\n preceding relay control and size to its content so the freed\n width flows back into the flex:1 name column. */\n }\n\n .list-expand-toggle {\n background: none;\n border: none;\n color: var(--secondary-text-color);\n cursor: pointer;\n padding: 4px;\n transition: transform 0.2s;\n display: flex;\n align-items: center;\n flex-shrink: 0;\n }\n\n .list-expand-toggle.expanded {\n transform: rotate(180deg);\n }\n\n .list-row .gear-icon {\n background: transparent;\n border: none;\n padding: 2px;\n cursor: pointer;\n color: #555;\n display: inline-flex;\n align-items: center;\n }\n .list-row .gear-icon:hover {\n color: var(--primary-text-color);\n }\n\n /* Truncation-driven fold for list rows. The .is-folded class is\n added/removed by the JS observer in src/core/truncation-fold.ts\n when the .list-circuit-name actually ellipsizes — pixel breakpoints\n can\'t track this because name length varies wildly per circuit\n ("Spa" vs "Commissioned PV System") and any single threshold\n misfires for the other end of the range. Switch to a two-row grid\n so the name gets the full width (paired only with the expand\n chevron) and the badges/controls/reading/gear drop to a secondary\n row underneath. Named areas keep the CSS readable despite the flat\n HTML child order. */\n .list-row.is-folded {\n display: grid;\n /* Row 1: name spans the row up to the chevron at the trailing\n column. Row 2: badge + util + shed + relay-toggle pack left,\n the 1fr column absorbs slack between the relay and the power\n reading, power + gear stay pinned to the right edge. The\n earlier layout placed the slack between the shedding icon and\n the relay, which the user flagged as wasted padding. */\n grid-template-columns: auto auto auto auto 1fr auto auto;\n grid-template-areas:\n "name name name name name name chevron"\n "badge util shed status . power gear";\n row-gap: 6px;\n column-gap: 8px;\n }\n .list-row.is-folded > .list-circuit-name {\n grid-area: name;\n justify-self: start;\n }\n .list-row.is-folded > .list-expand-toggle {\n grid-area: chevron;\n }\n .list-row.is-folded > .breaker-badge {\n grid-area: badge;\n }\n .list-row.is-folded > .utilization {\n grid-area: util;\n }\n .list-row.is-folded > .shedding-icon,\n .list-row.is-folded > .shedding-composite {\n grid-area: shed;\n }\n .list-row.is-folded > .toggle-pill,\n .list-row.is-folded > .list-status-badge {\n grid-area: status;\n }\n .list-row.is-folded > .list-power-value {\n grid-area: power;\n justify-self: end;\n }\n .list-row.is-folded > .gear-icon.circuit-gear {\n grid-area: gear;\n justify-self: end;\n }\n\n /* ── Expanded circuit content ──────────────────────────── */\n\n .list-expanded-content {\n padding: 0;\n background: var(--card-background-color, #1c1c1c);\n border: 1px solid var(--divider-color, #333);\n border-top: none;\n border-radius: 0 0 8px 8px;\n margin-top: -6px;\n margin-bottom: 2px;\n }\n\n .circuit-slot.circuit-chart-only {\n border: none;\n margin: 0;\n background: none;\n padding: 8px 12px;\n min-height: 0;\n }\n\n /* ── Area headers ──────────────────────────────────────── */\n\n .area-header {\n padding: 16px 12px 6px;\n font-weight: 600;\n font-size: 0.85em;\n color: var(--secondary-text-color);\n text-transform: uppercase;\n letter-spacing: 0.05em;\n }\n\n /* ── No results ────────────────────────────────────────── */\n\n .list-no-results {\n padding: 24px;\n text-align: center;\n color: var(--secondary-text-color);\n }\n\n'),C([Ht({attribute:!1})],VI.prototype,"hass",void 0),C([Bt()],VI.prototype,"_config",void 0),C([Bt()],VI.prototype,"_discovered",void 0),C([Bt()],VI.prototype,"_discovering",void 0),C([Bt()],VI.prototype,"_topology",void 0),C([Bt()],VI.prototype,"_activeTab",void 0),VI=C([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})(c)],VI);class qI extends HTMLElement{constructor(){super(...arguments),this._config={},this._hass=null,this._panels=null,this._availableRoles=null,this._built=!1,this._discovering=!1,this._panelSelect=null,this._daysInput=null,this._hoursInput=null,this._minsInput=null,this._metricSelect=null,this._checkboxes={},this._entityContainers={},this._tabStyleSelect=null}setConfig(t){this._config={...t},this._updateControls()}set hass(t){this._hass=t,this._panels?this._built||this._buildEditor():this._discovering||this._discoverPanels()}async _discoverPanels(){if(!this._hass)return;let t;this._discovering=!0;try{t=await async function(t){const e={type:"config_entries/get",domain:l},[n,i]=await Promise.all([t.callWS({type:"config/device_registry/list"}),t.callWS(e)]),r=new Set(i.map(t=>t.entry_id));return n.filter(t=>Zn(t,r))}(this._hass)}catch(t){return void console.warn("SPAN Panel: the card editor could not list the panels",t)}finally{this._discovering=!1}this._panels=t.map(t=>{const e=(t.identifiers??[]).find(t=>t[0]===l)?.[1]??"",n=t.name_by_user??t.name??i("editor.panel_label");return{device_id:t.id,label:`${n} (${e})`}}),this._buildEditor()}_buildEditor(){this.innerHTML="",this._built=!0;const t=document.createElement("div");t.style.padding="16px";const e="\n width: 100%;\n padding: 10px 12px;\n border-radius: 8px;\n border: 1px solid var(--divider-color, #333);\n background: var(--card-background-color, var(--secondary-background-color, #1c1c1c));\n color: var(--primary-text-color, #e0e0e0);\n font-size: 1em;\n cursor: pointer;\n appearance: auto;\n box-sizing: border-box;\n ",n="display: block; font-weight: 500; margin-bottom: 8px; color: var(--primary-text-color);",i="margin-bottom: 16px;";this._buildPanelSelector(t,e,n,i),this._buildTimeWindow(t,e,n,i),this._buildMetricSelector(t,e,n,i),this._buildTabStyleSelector(t,e,n,i),this._buildSectionCheckboxes(t,n,i),this.appendChild(t),this._populateMetricSelect(),this._config.device_id&&this._discoverAvailableRoles(this._config.device_id)}_buildPanelSelector(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.panel_label"),a.style.cssText=n;const s=document.createElement("select");s.style.cssText=e;const l=document.createElement("option");if(l.value="",l.textContent=i("editor.select_panel"),s.appendChild(l),this._panels)for(const t of this._panels){const e=document.createElement("option");e.value=t.device_id,e.textContent=t.label,t.device_id===this._config.device_id&&(e.selected=!0),s.appendChild(e)}s.addEventListener("change",()=>{this._config={...this._config,device_id:s.value},this._fireConfigChanged(),this._discoverAvailableRoles(s.value)}),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._panelSelect=s}_buildTimeWindow(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.chart_window"),a.style.cssText=n;const s=document.createElement("div");s.style.cssText="display: flex; gap: 12px; align-items: center; flex-wrap: wrap;";const l=e+"width: 70px; cursor: text;",c=(t,e,n,i)=>{const r=document.createElement("div");r.style.cssText="display: flex; align-items: center; gap: 6px;";const o=document.createElement("input");o.type="number",o.min=e,o.max=n,o.value=String(t),o.style.cssText=l;const a=document.createElement("span");return a.textContent=i,a.style.cssText="font-size: 0.9em; color: var(--secondary-text-color);",r.appendChild(o),r.appendChild(a),{wrap:r,input:o}},u=parseInt(String(this._config.history_days))||0,d=parseInt(String(this._config.history_hours))||0,h=parseInt(String(this._config.history_minutes))||0,p=c(u,"0","30",i("editor.days")),f=c(d,"0","23",i("editor.hours")),g=c(h,"0","59",i("editor.minutes")),m=()=>{this._config={...this._config,history_days:parseInt(p.input.value)||0,history_hours:parseInt(f.input.value)||0,history_minutes:parseInt(g.input.value)||0},this._fireConfigChanged()};p.input.addEventListener("change",m),f.input.addEventListener("change",m),g.input.addEventListener("change",m),s.appendChild(p.wrap),s.appendChild(f.wrap),s.appendChild(g.wrap),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._daysInput=p.input,this._hoursInput=f.input,this._minsInput=g.input}_buildMetricSelector(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.chart_metric"),a.style.cssText=n;const s=document.createElement("select");s.style.cssText=e,s.addEventListener("change",()=>{this._config={...this._config,chart_metric:s.value},this._fireConfigChanged()}),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._metricSelect=s}_buildTabStyleSelector(t,e,n,r){const o=document.createElement("div");o.style.cssText=r;const a=document.createElement("label");a.textContent=i("editor.tab_style"),a.style.cssText=n;const s=document.createElement("select");s.style.cssText=e;const l=[{value:"text",text:i("editor.tab_style_text")},{value:"icon",text:i("editor.tab_style_icon")}];for(const t of l){const e=document.createElement("option");e.value=t.value,e.textContent=t.text,t.value===(this._config.tab_style??"text")&&(e.selected=!0),s.appendChild(e)}s.addEventListener("change",()=>{this._config={...this._config,tab_style:s.value},this._fireConfigChanged()}),o.appendChild(a),o.appendChild(s),t.appendChild(o),this._tabStyleSelect=s}_buildSectionCheckboxes(t,e,n){const r=document.createElement("div");r.style.cssText=n;const o=document.createElement("label");o.textContent=i("editor.visible_sections"),o.style.cssText=e,r.appendChild(o);const a=[{key:"show_panel",label:i("editor.panel_circuits"),subDeviceType:null},{key:"show_battery",label:i("editor.battery_bess"),subDeviceType:"bess"},{key:"show_evse",label:i("editor.ev_charger_evse"),subDeviceType:"evse"},{key:"show_solar",label:i("editor.solar_pv"),subDeviceType:"pv"}];this._checkboxes={},this._entityContainers={};for(const t of a){const e=document.createElement("div");e.style.cssText="display: flex; align-items: center; gap: 8px; margin-bottom: 6px; cursor: pointer;";const n=document.createElement("input");n.type="checkbox",n.checked=!1!==this._config[t.key],n.style.cssText="width: 18px; height: 18px; cursor: pointer; accent-color: var(--primary-color);";const i=document.createElement("span");i.textContent=t.label,i.style.cssText="font-size: 0.9em; color: var(--primary-text-color); cursor: pointer;",e.appendChild(n),e.appendChild(i),r.appendChild(e),this._checkboxes[t.key]=n;let o=null;t.subDeviceType&&(o=document.createElement("div"),o.style.cssText="padding-left: 26px;",o.style.display=n.checked?"block":"none",r.appendChild(o),this._entityContainers[t.subDeviceType]=o),n.addEventListener("change",()=>{this._config={...this._config,[t.key]:n.checked},o&&(o.style.display=n.checked?"block":"none"),this._fireConfigChanged()})}t.appendChild(r)}_populateEntityCheckboxes(t){const e=this._config.visible_sub_entities??{},n="font-size: 0.85em; color: var(--primary-text-color); cursor: pointer;";for(const[r,o]of Object.entries(this._entityContainers)){o.innerHTML="";for(const a of jI(t,r)){const t=document.createElement("div");if(t.textContent=a.name,t.style.cssText="font-size: 0.85em; font-weight: 500; color: var(--secondary-text-color); margin: 8px 0 4px;",o.appendChild(t),0===a.entities.length){const t=document.createElement("div");t.textContent=i("editor.no_entities"),t.style.cssText=n,o.appendChild(t);continue}for(const{entityId:t,label:i}of a.entities){const r=document.createElement("div");r.style.cssText="display: flex; align-items: center; gap: 8px; margin-bottom: 5px; cursor: pointer;";const a=document.createElement("input");a.type="checkbox",a.checked=!0===e[t],a.style.cssText="width: 16px; height: 16px; cursor: pointer; accent-color: var(--primary-color);";const s=document.createElement("span");s.textContent=i,s.style.cssText=n,r.appendChild(a),r.appendChild(s),o.appendChild(r),a.addEventListener("change",()=>{const e={...this._config.visible_sub_entities??{}};a.checked?e[t]=!0:delete e[t],this._config={...this._config,visible_sub_entities:e},this._fireConfigChanged()})}}}}async _discoverAvailableRoles(t){if(this._hass&&t)try{const e=await this._hass.callWS({type:`${l}/panel_topology`,device_id:t}),n=new Set;for(const t of Object.values(e.circuits??{}))for(const e of Object.keys(t.entities??{}))n.add(e);this._availableRoles=n,this._populateMetricSelect(),e.sub_devices&&this._populateEntityCheckboxes(e.sub_devices)}catch{this._availableRoles=null,this._populateMetricSelect()}}_populateMetricSelect(){const t=this._metricSelect;if(!t)return;const e=this._config.chart_metric??o;t.innerHTML="";for(const[n,i]of Object.entries(y)){if(this._availableRoles&&!this._availableRoles.has(i.entityRole))continue;const r=document.createElement("option");r.value=n,r.textContent=i.label(),n===e&&(r.selected=!0),t.appendChild(r)}}_updateControls(){if(this._panelSelect&&(this._panelSelect.value=this._config.device_id??""),this._daysInput&&(this._daysInput.value=String(parseInt(String(this._config.history_days))||0)),this._hoursInput&&(this._hoursInput.value=String(parseInt(String(this._config.history_hours))||0)),this._minsInput&&(this._minsInput.value=String(parseInt(String(this._config.history_minutes))||0)),this._metricSelect&&(this._metricSelect.value=this._config.chart_metric??o),this._checkboxes)for(const[t,e]of Object.entries(this._checkboxes))e.checked=!1!==this._config[t];this._tabStyleSelect&&(this._tabStyleSelect.value=this._config.tab_style??"text")}_fireConfigChanged(){this.dispatchEvent(new CustomEvent("config-changed",{detail:{config:this._config}}))}}function UI(t){return function(t){const e={};for(const n in t)void 0!==t[n]&&(e[n]=t[n]);return e}({device_id:t.device_id,history_days:t.history_days,history_hours:t.history_hours,history_minutes:t.history_minutes,chart_metric:t.chart_metric,show_panel:t.show_panel,show_battery:t.show_battery,show_evse:t.show_evse,show_solar:t.show_solar,visible_sub_entities:t.visible_sub_entities,tab_style:t.tab_style})}class GI extends HTMLElement{static getStubConfig(t){const e=WI(t),n=Object.values(t.devices??{}).find(t=>Zn(t,e));return n?{type:h,device_id:n.id}:{type:h}}static async generate(t){return{type:"grid",cards:[{...UI(t),type:u,grid_options:{columns:"full"}}]}}}GI.registryDependencies=[];try{customElements.get("span-panel-card-editor")||customElements.define("span-panel-card-editor",qI)}catch{}try{customElements.get(p)||customElements.define(p,GI)}catch{}!function(t){const e=window.customCards??(window.customCards=[]);e.some(e=>e.type===t.type)||e.push(t)}({type:c,name:"SPAN Panel",description:"Physical panel layout with live power charts matching the SPAN frontend",preview:!0,getEntitySuggestion:function(t,e){const n=t.entities?.[e];if(n?.platform!==l||!n.device_id||!t.devices)return null;const i=t.devices[n.device_id],r=i?function(t,e,n){const i=t.parent_device_id||t.via_device_id,r=i?e[i]:t;return r&&Zn(r,n)&&Kn(t,r)?r:null}(i,t.devices,WI(t)):null;return r?{config:{type:u,device_id:r.id}}:null}}),function(t){const e=window.customStrategies??(window.customStrategies=[]);e.some(e=>e.type===t.type&&e.strategyType===t.strategyType)||e.push(t)}({type:d,strategyType:"section",name:"SPAN Panel",description:"A SPAN panel's breaker layout and live power charts, at the section's full width"}),console.warn("%c SPAN-PANEL-CARD %c v0.12.0 ","background: var(--primary-color, #4dd9af); color: var(--text-primary-color, #000); font-weight: 700; padding: 2px 6px; border-radius: 4px 0 0 4px;","background: var(--secondary-background-color, #333); color: var(--primary-text-color, #fff); padding: 2px 6px; border-radius: 0 4px 4px 0;"); diff --git a/custom_components/span_panel/frontend/dist/span-panel.js b/custom_components/span_panel/frontend/dist/span-panel.js index e3063d9b..22333348 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}","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.failed":"Failed","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","settings.heading":"Settings","settings.description":"General integration settings (entity naming, device prefix, circuit numbers) are managed through the integration's options flow.","settings.open_link":"Open SPAN Panel Integration Settings","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Panel monitoring settings","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.device_not_found":"Panel device not found. Check device_id in card config.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","card.panel_size_error":"Could not determine panel_size. No circuits found and no panel_size attribute. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.panel":"Panel","tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.settings":"Configuración","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.failed":"Falló","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","settings.heading":"Configuración","settings.description":"La configuración general de la integración (nombres de entidades, prefijo de dispositivo, números de circuito) se administra a través del flujo de opciones de la integración.","settings.open_link":"Abrir Configuración de Integración SPAN Panel","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configuración de monitoreo del panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.device_not_found":"Dispositivo de panel no encontrado. Verifique device_id en la configuración de la tarjeta.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","card.panel_size_error":"No se pudo determinar panel_size. No se encontraron circuitos ni atributo panel_size. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.panel":"Panneau","tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.settings":"Paramètres","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.failed":"Échoué","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","settings.heading":"Paramètres","settings.description":"Les paramètres généraux de l'intégration (noms d'entités, préfixe de l'appareil, numéros de circuit) sont gérés via le flux d'options de l'intégration.","settings.open_link":"Ouvrir les Paramètres d'Intégration SPAN Panel","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Paramètres de surveillance du panneau","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.device_not_found":"Appareil de panneau introuvable. Vérifiez device_id dans la configuration de la carte.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","card.panel_size_error":"Impossible de déterminer panel_size. Aucun circuit trouvé et aucun attribut panel_size. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.panel":"パネル","tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.settings":"設定","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.failed":"失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","settings.heading":"設定","settings.description":"統合の一般設定(エンティティ名、デバイスプレフィックス、回路番号)は統合のオプションフローで管理されます。","settings.open_link":"SPAN Panel統合設定を開く","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"パネルモニタリング設定","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.device_not_found":"パネルデバイスが見つかりません。カード設定のdevice_idを確認してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","card.panel_size_error":"panel_sizeを判定できません。回路がpanel_size属性が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.panel":"Painel","tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.settings":"Configurações","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.failed":"Falhou","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","settings.heading":"Configurações","settings.description":"As configurações gerais da integração (nomes de entidades, prefixo do dispositivo, números de circuito) são gerenciadas através do fluxo de opções da integração.","settings.open_link":"Abrir Configurações de Integração SPAN Panel","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configurações de monitoramento do painel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.device_not_found":"Dispositivo do painel não encontrado. Verifique device_id na configuração do cartão.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","card.panel_size_error":"Não foi possível determinar panel_size. Nenhum circuito encontrado e nenhum atributo panel_size. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){return e[t]?.[n]??e.en?.[n]??n}function i(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const r="power",o="5m",a={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},s="span_panel",l="bess",c="evse",d="pv",u="sub_",h={power:{entityRole:"power",label:()=>n("metric.power"),unit:t=>Math.abs(t)>=1e3?"kW":"W",format:t=>{const e=Math.abs(t);return e>=1e3?(e/1e3).toFixed(1):e<10&&e>0?e.toFixed(1):String(Math.round(e))}},current:{entityRole:"current",label:()=>n("metric.current"),unit:()=>"A",format:t=>Math.abs(t).toFixed(1)}},p={soc:{entityRole:"soc",label:()=>n("metric.soc"),unit:()=>"%",format:t=>String(Math.round(t)),fixedMin:0,fixedMax:100},soe:{entityRole:"soe",label:()=>n("metric.soe"),unit:()=>"kWh",format:t=>t.toFixed(1)},power:h.power},f={always_on:{icon:"mdi:battery",icon2:"mdi:router-wireless",color:"#4caf50",label:()=>n("shedding.always_on")},never:{icon:"mdi:battery",color:"#4caf50",label:()=>n("shedding.never")},soc_threshold:{icon:"mdi:battery-alert-variant-outline",color:"#9c27b0",label:()=>n("shedding.soc_threshold"),textLabel:"SoC"},off_grid:{icon:"mdi:transmission-tower",color:"#ff9800",label:()=>n("shedding.off_grid")},unknown:{icon:"mdi:help-circle-outline",color:"#888",label:()=>n("shedding.unknown")}},g=Object.keys(f).filter(t=>"unknown"!==t&&"always_on"!==t);var m=function(t,e){return m=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},m(t,e)};function v(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}m(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function _(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; +let t="en";const e={en:{"tab.panel":"Panel","tab.by_panel":"By Panel","tab.by_activity":"By Activity","tab.by_area":"By Area","tab.monitoring":"Monitoring","tab.settings":"Settings","tab.adopted":"Adopted","list.search_placeholder":"Search circuits...","list.unassigned_area":"Unassigned","list.no_results":"No circuits found","monitoring.heading":"Monitoring","monitoring.global_settings":"Global Settings","monitoring.enabled":"Enabled","monitoring.continuous":"Continuous (%)","monitoring.spike":"Spike (%)","monitoring.window":"Window (min)","monitoring.cooldown":"Cooldown (min)","monitoring.monitored_points":"Monitored Points","monitoring.col.name":"Name","monitoring.col.continuous":"Continuous","monitoring.col.spike":"Spike","monitoring.col.window":"Window","monitoring.col.cooldown":"Cooldown","monitoring.rating":"Rating","monitoring.all_none":"All / None","monitoring.reset":"Reset","monitoring.limit_invalid":"Enter a whole number from {min} to {max}.","monitoring.enable_invalid":"Monitoring was not turned on: correct the fields marked.","monitoring.point_field":"{field} for {name}","monitoring.reset_point":"Reset {name}","monitoring.admin_only":"Only an administrator can change monitoring.","notification.heading":"Notification Settings","notification.targets":"Notify Targets","notification.none_selected":"None selected","notification.targets_button":"Notify Targets: {targets}","notification.no_targets":"No notify targets found","notification.all_targets":"All","notification.event_bus_target":"Event Bus (HA event bus)","notification.priority":"Priority","notification.priority.default":"Default","notification.priority.passive":"Passive","notification.priority.active":"Active","notification.priority.time_sensitive":"Time-sensitive","notification.priority.critical":"Critical","notification.hint.critical":"Overrides silent/DND","notification.hint.time_sensitive":"Breaks through Focus","notification.hint.passive":"Delivers silently","notification.hint.active":"Standard delivery","notification.title_template":"Title Template","notification.message_template":"Message Template","notification.placeholders":"Placeholders:","notification.event_bus_help":"Event Bus fires event type","notification.event_bus_payload":"with payload:","notification.test_label":"Test Notification","notification.test_button":"Send Test","notification.test_sending":"Sending...","notification.test_sent":"Test notification sent","error.prefix":"Error:","error.failed_save":"Failed to save","error.failed":"Failed","error.panel_offline":"SPAN Panel unreachable","error.panel_reconnected":"SPAN Panel reconnected","error.panel_offline_named":"{name} unreachable","error.panel_reconnected_named":"{name} reconnected","error.discovery_failed":"Unable to connect to SPAN Panel","error.relay_failed":"Unable to toggle relay","error.shedding_failed":"Unable to update shedding priority","error.threshold_failed":"Unable to save threshold","error.graph_horizon_failed":"Unable to update graph time horizon","error.favorites_fetch_failed":"Unable to load favorites","error.favorites_toggle_failed":"Unable to update favorite","error.history_failed":"Unable to load historical data","error.monitoring_failed":"Unable to load monitoring status","error.graph_settings_failed":"Unable to load graph settings","error.areas_failed":"Area assignments may be out of sync","error.retry":"Retry","card.connecting":"Connecting to SPAN Panel...","monitoringRating.none":"no rating","monitoringRating.copied":"{package} from your SPAN app (the panel publishes {panel} A)","monitoringRating.copied_unnamed":"Copied from your SPAN app","monitoringRating.judged_copied":"Judged against {rating} A: {copied}","settings.heading":"Settings","settings.description":"General integration settings (entity naming, device prefix, circuit numbers) are managed through the integration's options flow.","settings.open_link":"Open SPAN Panel Integration Settings","adopted.heading":"Adopted entities","adopted.description":"Vendor readings and adopted devices arrive with minimal metadata. Curate one to set its device class, statistics class, and prominence — saved changes reload the integration and apply from the next startup on.","adopted.filter_placeholder":"Filter by entity or device name","adopted.no_results":"No adopted entities match this filter","adopted.none":"This panel publishes nothing to curate.","adopted.load_failed":"Unable to load adopted entities","adopted.count":"{count} adopted","adopted.vendor_readings":"VENDOR READINGS","adopted.adopted_device":"ADOPTED DEVICE","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURATED","adopted.stale":"STALE","adopted.stale_note":"The panel no longer supports what was saved for: {fields}","adopted.enable_entity":"Enable entity","adopted.enabled":"ENABLED","adopted.disabled":"DISABLED","adopted.enable_note":"Enabled when saved — curating never enables on its own","adopted.registry_unavailable":"Enable and name become available once this entity exists in the registry.","adopted.name":"Name","adopted.device_class":"Device class","adopted.device_class_note":"choices limited by the panel's unit ({unit})","adopted.device_class_note_unitless":"choices limited by what the panel publishes","adopted.no_device_class":"No device class","adopted.statistics_class":"Statistics class","adopted.statistics_note":"long-term statistics begin after the next reload","adopted.no_statistics":"No statistics","adopted.prominence":"Prominence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Display unit","adopted.unit_as_published":"As published","adopted.precision":"Precision","adopted.precision_default":"Default","adopted.read_only":"read-only","adopted.settable":"settable","adopted.save":"Save","adopted.clear":"Clear curation","adopted.reload_note":"Saving reloads the SPAN Panel integration","adopted.saved":"Saved — the integration is reloading","adopted.confirm_heading":"Confirm statistics class","adopted.confirm_setting":"You are setting {name} to {value}.","adopted.confirm_clearing_subject":"You are clearing the statistics class on {name}.","adopted.confirm_total_increasing":"Total increasing treats every drop in the value as a meter reset. If this reading can decrease for any other reason, long-term statistics will be permanently corrupted — fixing the class later does not repair history already written.","adopted.confirm_clearing":"Long-term statistics stop being compiled for this entity, and Home Assistant raises a repair against the statistics already collected under the class you are removing.","adopted.save_anyway":"Save anyway","adopted.cancel":"Cancel","adopted.warn_total_increasing":"Saved as total increasing — every drop in the reading now counts as a meter reset.","adopted.warn_statistics_removed":"This entity has no statistics class any more; Home Assistant will raise a repair against the statistics already collected.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Panel monitoring settings","header.graph_settings":"Graph time horizon settings","header.site":"Site","header.grid":"Grid","header.upstream":"Upstream","header.downstream":"Downstream","header.solar":"Solar","header.battery":"Battery","header.toggle_units":"Toggle Watts / Amps","header.enable_switches":"Enable Switches","header.switches_enabled":"Switches Enabled","controls.admin_only":"Only an administrator can operate this panel's controls.","controls.disabled":"Control of this panel is switched off in its options.","controls.read_only":"Your Home Assistant account can't operate this panel's controls.","controls.entity_unauthorized":"Your Home Assistant account can't operate this control.","controls.not_operable":"You can't operate this panel's controls.","grid.unknown":"Unknown","grid.configure":"Configure circuit","grid.configure_subdevice":"Configure device","grid.on":"On","grid.off":"Off","grid.shared_switch":"Switches every circuit in this space","meters.title":"Meters","meters.importing":"importing","meters.exporting":"exporting","meters.imported":"imported","meters.exported":"exported","subdevice.ev_charger":"EV Charger","subdevice.battery":"Battery","subdevice.fallback":"Sub-device","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Power","subdevice.solar":"Solar","subdevice.solar_inverter":"Solar inverter","subdevice.site_total":"Site total","subdevice.in_site_total":"Included in the site total","sidepanel.graph_settings":"Graph Settings","sidepanel.global_defaults":"Global defaults for all circuits","sidepanel.favorites_subtitle":"Favorites","sidepanel.global_default":"Global Default","sidepanel.list_view_columns":"List View Columns","sidepanel.columns":"Columns","sidepanel.circuit_scales":"Circuit Graph Scales","sidepanel.subdevice_scales":"Sub-Device Graph Scales","sidepanel.reset_to_global":"Reset to global default","sidepanel.relay":"Relay","sidepanel.breaker":"Breaker","sidepanel.capacity":"{amps} A capacity","monitoringRating.title":"Breaker ratings from the SPAN app","monitoringRating.panel_rating":"Panel publishes {panel} A","monitoringRating.other_breaker":"Other breaker (A)","monitoringRating.other_breaker_label":"Other breaker in the space of {circuit}","monitoringRating.reset":"Remove copied ratings","monitoringRating.invalid_other":"Enter the other breaker's rating as a whole number of amps, 1 or more.","monitoringRating.guidance":"If your SPAN app shows two ratings for this circuit, such as 20-20A, enter the second one here. SPAN Panel MAIN 32 panels report only the first, and monitoring then judges this space against both breakers together.","monitoringRating.guidance_two_spaces":"If your SPAN app shows two ratings for this circuit, such as 20-30A, enter the second one here.","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 panels report only the average of this circuit's two legs, which can hide an overloaded leg. We recommend turning monitoring off for this circuit.","monitoringRating.turn_off_monitoring":"Turn off monitoring","monitoringRating.threshold_warning":"This circuit's custom thresholds are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass.","monitoringRating.threshold_warning_global":"The global thresholds this circuit uses are above 100%. With the copied ratings they now apply to both breakers together, which can let a real overload pass; change them under {settings} on the {tab} tab.","monitoringRating.use_global_thresholds":"Use global thresholds","monitoringRating.note_title":"Tandem breakers on SPAN Panel MAIN 32","monitoringRating.note_problem":"SPAN Panel MAIN 32 panels do not report which breakers are tandems, or the rating of a tandem's second breaker. A tandem puts two breakers in one space, but the panel reports it as one circuit with only the first breaker's rating, while one sensor reads both breakers together. A 20-20 tandem shows 20 A here and can carry 40 A, so monitoring raises false alerts on it.","monitoringRating.note_steps":"To fix this, copy the ratings from your SPAN app:","monitoringRating.note_step_find":"In the SPAN app, find each circuit whose breaker shows two ratings, such as 20-20A.","monitoringRating.note_step_enter":"In the table below, type the second rating in that circuit's {column} field. Then press Enter or move to the next field.","monitoringRating.note_step_single":"Leave the field empty for a circuit with a single breaker.","monitoringRating.note_judged":"Monitoring then judges that space against both breakers together: 40 A for a 20-20. Only monitoring uses the copy, and the circuit's Breaker Rating sensor still shows what the panel reports. To remove a copied rating, select ✕ beside its field.","monitoringRating.note_thresholds":"If you raised a tandem's thresholds above 100% to stop its alerts, select {reset} on its row. Those thresholds now apply to both breakers together.","monitoringRating.note_two_spaces":"For a circuit that spans two spaces, enter the second rating the same way if your SPAN app shows two, such as 20-30A. SPAN Panel MAIN 32 panels report only the average of such a circuit's two legs, which can hide an overloaded leg, so the copy can't be applied and we recommend turning monitoring off for that circuit.","monitoringRating.note_guide":"Read more in the guide to tandem and multi-load breakers.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remove copied ratings for {circuit}","monitoringRating.table_threshold_warning":"This circuit's thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Select {reset} to use the global thresholds.","monitoringRating.table_threshold_warning_global":"The global thresholds are above 100% and now apply to both breakers together, which can let a real overload pass. Change them under {settings} above.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Unable to update the ratings copied from the SPAN app","sidepanel.judged_against":"Judged against: {rating}","sidepanel.shedding_priority":"Shedding Priority","sidepanel.priority_label":"Priority","sidepanel.monitoring":"Monitoring","sidepanel.global":"Global","sidepanel.custom":"Custom","sidepanel.continuous_pct":"Continuous %","sidepanel.spike_pct":"Spike %","sidepanel.window_duration":"Window duration","sidepanel.cooldown":"Cooldown","sidepanel.favorite":"Favorite","sidepanel.save_to_favorites":"Save to favorites","panel.favorites":"Favorites","status.monitoring":"Monitoring","status.circuits":"circuits","status.mains":"mains","status.warning":"warning","status.warnings":"warnings","status.alert":"alert","status.alerts":"alerts","status.override":"override","status.overrides":"overrides","card.no_device":"Open the card editor and select your SPAN Panel device.","card.device_not_found":"Panel device not found. Check device_id in card config.","card.topology_error":"Topology response missing panel_size and no circuits found. Update the SPAN Panel integration.","card.panel_size_error":"Could not determine panel_size. No circuits found and no panel_size attribute. Update the SPAN Panel integration.","editor.panel_label":"SPAN Panel","editor.select_panel":"Select a panel...","editor.chart_window":"Chart time window","editor.days":"days","editor.hours":"hours","editor.minutes":"minutes","editor.chart_metric":"Chart metric","editor.visible_sections":"Visible sections","editor.panel_circuits":"Panel circuits","editor.battery_bess":"Battery (BESS)","editor.ev_charger_evse":"EV Charger (EVSE)","editor.solar_pv":"Solar (PV)","editor.no_entities":"No entities to show","editor.tab_style":"Tab Style","editor.tab_style_text":"Text","editor.tab_style_icon":"Icon","metric.power":"Power","metric.current":"Current","metric.soc":"State of Charge","metric.soe":"State of Energy","shedding.always_on":"Critical","shedding.never":"Non-sheddable","shedding.soc_threshold":"SoC Threshold","shedding.off_grid":"Sheddable","shedding.unknown":"Unknown","shedding.select.never":"Stays on in an outage","shedding.select.soc_threshold":"Stays on until battery threshold","shedding.select.off_grid":"Turns off in an outage"},es:{"tab.panel":"Panel","tab.by_panel":"Por Panel","tab.by_activity":"Por Actividad","tab.by_area":"Por Área","tab.monitoring":"Monitoreo","tab.settings":"Configuración","tab.adopted":"Adoptadas","list.search_placeholder":"Buscar circuitos...","list.unassigned_area":"Sin asignar","list.no_results":"No se encontraron circuitos","monitoring.heading":"Monitoreo","monitoring.global_settings":"Configuración Global","monitoring.enabled":"Activado","monitoring.continuous":"Continuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Ventana (min)","monitoring.cooldown":"Enfriamiento (min)","monitoring.monitored_points":"Puntos Monitoreados","monitoring.col.name":"Nombre","monitoring.col.continuous":"Continuo","monitoring.col.spike":"Pico","monitoring.col.window":"Ventana","monitoring.col.cooldown":"Enfriamiento","monitoring.rating":"Calibre","monitoring.all_none":"Todos / Ninguno","monitoring.reset":"Restablecer","monitoring.limit_invalid":"Introduzca un número entero de {min} a {max}.","monitoring.enable_invalid":"No se activó el monitoreo: corrija los campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Restablecer {name}","monitoring.admin_only":"Solo un administrador puede cambiar el monitoreo.","notification.heading":"Configuración de Notificaciones","notification.targets":"Destinos de Notificación","notification.none_selected":"Ninguno seleccionado","notification.targets_button":"Destinos de Notificación: {targets}","notification.no_targets":"No se encontraron destinos de notificación","notification.all_targets":"Todos","notification.event_bus_target":"Bus de Eventos (bus de eventos de HA)","notification.priority":"Prioridad","notification.priority.default":"Predeterminado","notification.priority.passive":"Pasivo","notification.priority.active":"Activo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Anula silencio/No molestar","notification.hint.time_sensitive":"Atraviesa el modo Concentración","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega estándar","notification.title_template":"Plantilla de Título","notification.message_template":"Plantilla de Mensaje","notification.placeholders":"Variables:","notification.event_bus_help":"El Bus de Eventos dispara el tipo de evento","notification.event_bus_payload":"con datos:","notification.test_label":"Notificación de prueba","notification.test_button":"Enviar prueba","notification.test_sending":"Enviando...","notification.test_sent":"Notificación de prueba enviada","error.prefix":"Error:","error.failed_save":"Error al guardar","error.failed":"Falló","error.panel_offline":"SPAN Panel inaccesible","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inaccesible","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"No se puede conectar al SPAN Panel","error.relay_failed":"No se pudo cambiar el relé","error.shedding_failed":"No se pudo actualizar la prioridad de desconexión","error.threshold_failed":"No se pudo guardar el umbral","error.graph_horizon_failed":"No se pudo actualizar el horizonte temporal del gráfico","error.favorites_fetch_failed":"No se pudieron cargar los favoritos","error.favorites_toggle_failed":"No se pudo actualizar el favorito","error.history_failed":"No se pudieron cargar los datos históricos","error.monitoring_failed":"No se pudo cargar el estado de monitoreo","error.graph_settings_failed":"No se pudo cargar la configuración del gráfico","error.areas_failed":"Las asignaciones de áreas pueden estar desincronizadas","error.retry":"Reintentar","card.connecting":"Conectando al SPAN Panel...","monitoringRating.none":"sin calibre","monitoringRating.copied":"{package} de su app de SPAN (el panel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado de su app de SPAN","monitoringRating.judged_copied":"Evaluado según {rating} A: {copied}","settings.heading":"Configuración","settings.description":"La configuración general de la integración (nombres de entidades, prefijo de dispositivo, números de circuito) se administra a través del flujo de opciones de la integración.","settings.open_link":"Abrir Configuración de Integración SPAN Panel","adopted.heading":"Entidades adoptadas","adopted.description":"Las lecturas del proveedor y los dispositivos adoptados llegan con metadatos mínimos. Cura una para definir su clase de dispositivo, clase de estadísticas y prominencia — los cambios guardados recargan la integración y se aplican desde el siguiente arranque.","adopted.filter_placeholder":"Filtrar por nombre de entidad o dispositivo","adopted.no_results":"Ninguna entidad adoptada coincide con este filtro","adopted.none":"Este panel no publica nada que curar.","adopted.load_failed":"No se pudieron cargar las entidades adoptadas","adopted.count":"{count} adoptadas","adopted.vendor_readings":"LECTURAS DEL PROVEEDOR","adopted.adopted_device":"DISPOSITIVO ADOPTADO","adopted.via_panel":"vía SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"El panel ya no admite lo guardado para: {fields}","adopted.enable_entity":"Activar entidad","adopted.enabled":"ACTIVADA","adopted.disabled":"DESACTIVADA","adopted.enable_note":"Se activa al guardar — curar nunca activa por sí solo","adopted.registry_unavailable":"La activación y el nombre estarán disponibles cuando esta entidad exista en el registro.","adopted.name":"Nombre","adopted.device_class":"Clase de dispositivo","adopted.device_class_note":"opciones limitadas por la unidad del panel ({unit})","adopted.device_class_note_unitless":"opciones limitadas por lo que publica el panel","adopted.no_device_class":"Sin clase de dispositivo","adopted.statistics_class":"Clase de estadísticas","adopted.statistics_note":"las estadísticas a largo plazo comienzan tras la próxima recarga","adopted.no_statistics":"Sin estadísticas","adopted.prominence":"Prominencia","adopted.diagnostic":"Diagnóstico","adopted.standard":"Estándar","adopted.display_unit":"Unidad mostrada","adopted.unit_as_published":"Tal como se publica","adopted.precision":"Precisión","adopted.precision_default":"Predeterminada","adopted.read_only":"solo lectura","adopted.settable":"editable","adopted.save":"Guardar","adopted.clear":"Borrar curación","adopted.reload_note":"Guardar recarga la integración SPAN Panel","adopted.saved":"Guardado — la integración se está recargando","adopted.confirm_heading":"Confirmar clase de estadísticas","adopted.confirm_setting":"Vas a definir {name} como {value}.","adopted.confirm_clearing_subject":"Vas a borrar la clase de estadísticas de {name}.","adopted.confirm_total_increasing":"Total creciente interpreta cada caída del valor como un reinicio del contador. Si esta lectura puede disminuir por cualquier otro motivo, las estadísticas a largo plazo quedarán corrompidas de forma permanente — corregir la clase más tarde no repara el historial ya escrito.","adopted.confirm_clearing":"Dejarán de compilarse estadísticas a largo plazo para esta entidad, y Home Assistant abrirá una reparación sobre las estadísticas ya recogidas bajo la clase que estás quitando.","adopted.save_anyway":"Guardar de todos modos","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Guardado como total creciente — cada caída de la lectura cuenta ahora como un reinicio del contador.","adopted.warn_statistics_removed":"Esta entidad ya no tiene clase de estadísticas; Home Assistant abrirá una reparación sobre las estadísticas ya recogidas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configuración de monitoreo del panel","header.graph_settings":"Configuración del horizonte temporal del gráfico","header.site":"Sitio","header.grid":"Red","header.upstream":"Aguas arriba","header.downstream":"Aguas abajo","header.solar":"Solar","header.battery":"Batería","header.toggle_units":"Alternar Watts / Amperios","header.enable_switches":"Habilitar Interruptores","header.switches_enabled":"Interruptores Habilitados","controls.admin_only":"Solo un administrador puede operar los controles de este panel.","controls.disabled":"El control de este panel está desactivado en sus opciones.","controls.read_only":"Su cuenta de Home Assistant no puede operar los controles de este panel.","controls.entity_unauthorized":"Su cuenta de Home Assistant no puede operar este control.","controls.not_operable":"No puede operar los controles de este panel.","grid.unknown":"Desconocido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Enc","grid.off":"Apag","grid.shared_switch":"Conmuta todos los circuitos de este espacio","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Cargador EV","subdevice.battery":"Batería","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potencia","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total del sitio","subdevice.in_site_total":"Incluido en el total del sitio","sidepanel.graph_settings":"Configuración de Gráficos","sidepanel.global_defaults":"Valores predeterminados globales para todos los circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Predeterminado Global","sidepanel.list_view_columns":"Columnas de la lista","sidepanel.columns":"Columnas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Restablecer al valor global","sidepanel.relay":"Relé","sidepanel.breaker":"Interruptor","sidepanel.capacity":"capacidad de {amps} A","monitoringRating.title":"Calibres de interruptor de la app de SPAN","monitoringRating.panel_rating":"El panel publica {panel} A","monitoringRating.other_breaker":"Otro interruptor (A)","monitoringRating.other_breaker_label":"Otro interruptor en el espacio de {circuit}","monitoringRating.reset":"Quitar los calibres copiados","monitoringRating.invalid_other":"Introduzca el calibre del otro interruptor como un número entero de amperios, 1 o más.","monitoringRating.guidance":"Si su app de SPAN muestra dos calibres para este circuito, como 20-20A, introduzca aquí el segundo. Los paneles SPAN Panel MAIN 32 informan solo el primero, y el monitoreo juzga entonces este espacio según ambos interruptores juntos.","monitoringRating.guidance_two_spaces":"Si su app de SPAN muestra dos calibres para este circuito, como 20-30A, introduzca aquí el segundo.","monitoringRating.averaged_legs":"Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de este circuito, lo que puede ocultar una fase sobrecargada. Recomendamos desactivar el monitoreo de este circuito.","monitoringRating.turn_off_monitoring":"Desactivar el monitoreo","monitoringRating.threshold_warning":"Los umbrales personalizados de este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real.","monitoringRating.threshold_warning_global":"Los umbrales globales que usa este circuito superan el 100 %. Con los calibres copiados se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real; cámbielos en {settings}, en la pestaña {tab}.","monitoringRating.use_global_thresholds":"Usar los umbrales globales","monitoringRating.note_title":"Interruptores tándem en SPAN Panel MAIN 32","monitoringRating.note_problem":"Los paneles SPAN Panel MAIN 32 no informan qué interruptores son tándem ni el calibre del segundo interruptor de un tándem. Un tándem pone dos interruptores en un espacio, pero el panel lo informa como un solo circuito con solo el calibre del primer interruptor, mientras un solo sensor lee ambos interruptores juntos. Un tándem 20-20 muestra 20 A aquí y puede llevar 40 A, por lo que el monitoreo genera falsas alertas en él.","monitoringRating.note_steps":"Para corregirlo, copie los calibres de su app de SPAN:","monitoringRating.note_step_find":"En la app de SPAN, busque cada circuito cuyo interruptor muestre dos calibres, como 20-20A.","monitoringRating.note_step_enter":"En la tabla de abajo, escriba el segundo calibre en el campo {column} de ese circuito. Luego pulse Intro o pase al siguiente campo.","monitoringRating.note_step_single":"Deje el campo vacío para un circuito con un solo interruptor.","monitoringRating.note_judged":"El monitoreo juzga entonces ese espacio según ambos interruptores juntos: 40 A para un 20-20. Solo el monitoreo usa la copia, y el sensor Breaker Rating del circuito sigue mostrando lo que informa el panel. Para quitar un calibre copiado, seleccione ✕ junto a su campo.","monitoringRating.note_thresholds":"Si subió los umbrales de un tándem por encima del 100 % para detener sus alertas, seleccione {reset} en su fila. Esos umbrales se aplican ahora a ambos interruptores juntos.","monitoringRating.note_two_spaces":"Para un circuito que ocupa dos espacios, introduzca el segundo calibre del mismo modo si su app de SPAN muestra dos, como 20-30A. Los paneles SPAN Panel MAIN 32 informan solo el promedio de las dos fases de un circuito así, lo que puede ocultar una fase sobrecargada, por lo que la copia no se puede aplicar y recomendamos desactivar el monitoreo de ese circuito.","monitoringRating.note_guide":"Lea más en la guía de interruptores tándem y de cargas múltiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Quitar los calibres copiados de {circuit}","monitoringRating.table_threshold_warning":"Los umbrales de este circuito superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Seleccione {reset} para usar los umbrales globales.","monitoringRating.table_threshold_warning_global":"Los umbrales globales superan el 100 % y se aplican ahora a ambos interruptores juntos, lo que puede dejar pasar una sobrecarga real. Cámbielos en {settings}, arriba.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"No se pudieron actualizar los calibres copiados de la app de SPAN","sidepanel.judged_against":"Evaluado según: {rating}","sidepanel.shedding_priority":"Prioridad de Desconexción","sidepanel.priority_label":"Prioridad","sidepanel.monitoring":"Monitoreo","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Continuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duración de ventana","sidepanel.cooldown":"Enfriamiento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Guardar en favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoreo","status.circuits":"circuitos","status.mains":"alimentación","status.warning":"advertencia","status.warnings":"advertencias","status.alert":"alerta","status.alerts":"alertas","status.override":"anulación","status.overrides":"anulaciones","card.no_device":"Abra el editor de tarjeta y seleccione su dispositivo SPAN Panel.","card.device_not_found":"Dispositivo de panel no encontrado. Verifique device_id en la configuración de la tarjeta.","card.topology_error":"La respuesta de topología no contiene panel_size y no se encontraron circuitos. Actualice la integración SPAN Panel.","card.panel_size_error":"No se pudo determinar panel_size. No se encontraron circuitos ni atributo panel_size. Actualice la integración SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Seleccione un panel...","editor.chart_window":"Ventana de tiempo del gráfico","editor.days":"días","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica del gráfico","editor.visible_sections":"Secciones visibles","editor.panel_circuits":"Circuitos del panel","editor.battery_bess":"Batería (BESS)","editor.ev_charger_evse":"Cargador EV (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"No hay entidades para mostrar","editor.tab_style":"Estilo de pestañas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícono","metric.power":"Potencia","metric.current":"Corriente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energía","shedding.always_on":"Crítico","shedding.never":"No desconectable","shedding.soc_threshold":"Umbral SoC","shedding.off_grid":"Desconectable","shedding.unknown":"Desconocido","shedding.select.never":"Permanece encendido en un corte","shedding.select.soc_threshold":"Encendido hasta umbral de batería","shedding.select.off_grid":"Se apaga en un corte"},fr:{"tab.panel":"Panneau","tab.by_panel":"Par Panneau","tab.by_activity":"Par Activité","tab.by_area":"Par Zone","tab.monitoring":"Surveillance","tab.settings":"Paramètres","tab.adopted":"Adoptées","list.search_placeholder":"Rechercher des circuits...","list.unassigned_area":"Non attribué","list.no_results":"Aucun circuit trouvé","monitoring.heading":"Surveillance","monitoring.global_settings":"Paramètres Globaux","monitoring.enabled":"Activé","monitoring.continuous":"Continu (%)","monitoring.spike":"Pic (%)","monitoring.window":"Fenêtre (min)","monitoring.cooldown":"Refroidissement (min)","monitoring.monitored_points":"Points Surveillés","monitoring.col.name":"Nom","monitoring.col.continuous":"Continu","monitoring.col.spike":"Pic","monitoring.col.window":"Fenêtre","monitoring.col.cooldown":"Refroidissement","monitoring.rating":"Calibre","monitoring.all_none":"Tous / Aucun","monitoring.reset":"Réinitialiser","monitoring.limit_invalid":"Saisissez un nombre entier de {min} à {max}.","monitoring.enable_invalid":"La surveillance n'a pas été activée : corrigez les champs signalés.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Réinitialiser {name}","monitoring.admin_only":"Seul un administrateur peut modifier la surveillance.","notification.heading":"Paramètres de Notification","notification.targets":"Cibles de Notification","notification.none_selected":"Aucune sélection","notification.targets_button":"Cibles de Notification : {targets}","notification.no_targets":"Aucune cible de notification trouvée","notification.all_targets":"Tous","notification.event_bus_target":"Bus d'événements (bus d'événements HA)","notification.priority":"Priorité","notification.priority.default":"Par défaut","notification.priority.passive":"Passif","notification.priority.active":"Actif","notification.priority.time_sensitive":"Urgent","notification.priority.critical":"Critique","notification.hint.critical":"Outrepasse silencieux/NPD","notification.hint.time_sensitive":"Traverse le mode Concentration","notification.hint.passive":"Livraison silencieuse","notification.hint.active":"Livraison standard","notification.title_template":"Modèle de Titre","notification.message_template":"Modèle de Message","notification.placeholders":"Variables :","notification.event_bus_help":"Le Bus d'événements déclenche le type d'événement","notification.event_bus_payload":"avec les données :","notification.test_label":"Notification de test","notification.test_button":"Envoyer un test","notification.test_sending":"Envoi...","notification.test_sent":"Notification de test envoyée","error.prefix":"Erreur :","error.failed_save":"Échec de la sauvegarde","error.failed":"Échoué","error.panel_offline":"SPAN Panel inaccessible","error.panel_reconnected":"SPAN Panel reconnecté","error.panel_offline_named":"{name} inaccessible","error.panel_reconnected_named":"{name} reconnecté","error.discovery_failed":"Impossible de se connecter au SPAN Panel","error.relay_failed":"Impossible de basculer le relais","error.shedding_failed":"Impossible de mettre à jour la priorité de délestage","error.threshold_failed":"Impossible d'enregistrer le seuil","error.graph_horizon_failed":"Impossible de mettre à jour l'horizon temporel du graphique","error.favorites_fetch_failed":"Impossible de charger les favoris","error.favorites_toggle_failed":"Impossible de mettre à jour le favori","error.history_failed":"Impossible de charger les données historiques","error.monitoring_failed":"Impossible de charger l'état de surveillance","error.graph_settings_failed":"Impossible de charger les paramètres du graphique","error.areas_failed":"Les affectations de zones peuvent être désynchronisées","error.retry":"Réessayer","card.connecting":"Connexion au SPAN Panel...","monitoringRating.none":"aucun calibre","monitoringRating.copied":"{package} depuis votre application SPAN (le panneau publie {panel} A)","monitoringRating.copied_unnamed":"Copié depuis votre application SPAN","monitoringRating.judged_copied":"Évalué selon {rating} A : {copied}","settings.heading":"Paramètres","settings.description":"Les paramètres généraux de l'intégration (noms d'entités, préfixe de l'appareil, numéros de circuit) sont gérés via le flux d'options de l'intégration.","settings.open_link":"Ouvrir les Paramètres d'Intégration SPAN Panel","adopted.heading":"Entités adoptées","adopted.description":"Les relevés du fournisseur et les appareils adoptés arrivent avec des métadonnées minimales. Curez-en un pour définir sa classe d'appareil, sa classe de statistiques et sa proéminence — les modifications enregistrées rechargent l'intégration et s'appliquent dès le prochain démarrage.","adopted.filter_placeholder":"Filtrer par nom d'entité ou d'appareil","adopted.no_results":"Aucune entité adoptée ne correspond à ce filtre","adopted.none":"Ce panneau ne publie rien à curer.","adopted.load_failed":"Impossible de charger les entités adoptées","adopted.count":"{count} adoptées","adopted.vendor_readings":"RELEVÉS DU FOURNISSEUR","adopted.adopted_device":"APPAREIL ADOPTÉ","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURÉE","adopted.stale":"OBSOLÈTE","adopted.stale_note":"Le panneau ne prend plus en charge ce qui a été enregistré pour : {fields}","adopted.enable_entity":"Activer l'entité","adopted.enabled":"ACTIVÉE","adopted.disabled":"DÉSACTIVÉE","adopted.enable_note":"Activée à l'enregistrement — la curation n'active jamais d'elle-même","adopted.registry_unavailable":"L'activation et le nom seront disponibles dès que cette entité existera dans le registre.","adopted.name":"Nom","adopted.device_class":"Classe d'appareil","adopted.device_class_note":"choix limités par l'unité du panneau ({unit})","adopted.device_class_note_unitless":"choix limités par ce que le panneau publie","adopted.no_device_class":"Aucune classe d'appareil","adopted.statistics_class":"Classe de statistiques","adopted.statistics_note":"les statistiques à long terme commencent après le prochain rechargement","adopted.no_statistics":"Aucune statistique","adopted.prominence":"Proéminence","adopted.diagnostic":"Diagnostic","adopted.standard":"Standard","adopted.display_unit":"Unité affichée","adopted.unit_as_published":"Telle que publiée","adopted.precision":"Précision","adopted.precision_default":"Par défaut","adopted.read_only":"lecture seule","adopted.settable":"modifiable","adopted.save":"Enregistrer","adopted.clear":"Effacer la curation","adopted.reload_note":"L'enregistrement recharge l'intégration SPAN Panel","adopted.saved":"Enregistré — l'intégration se recharge","adopted.confirm_heading":"Confirmer la classe de statistiques","adopted.confirm_setting":"Vous définissez {name} sur {value}.","adopted.confirm_clearing_subject":"Vous effacez la classe de statistiques de {name}.","adopted.confirm_total_increasing":"Total croissant interprète chaque baisse de la valeur comme une remise à zéro du compteur. Si ce relevé peut diminuer pour une autre raison, les statistiques à long terme seront corrompues de façon permanente — corriger la classe plus tard ne répare pas l'historique déjà écrit.","adopted.confirm_clearing":"Les statistiques à long terme cesseront d'être compilées pour cette entité, et Home Assistant ouvrira une réparation sur les statistiques déjà collectées sous la classe que vous retirez.","adopted.save_anyway":"Enregistrer quand même","adopted.cancel":"Annuler","adopted.warn_total_increasing":"Enregistré en total croissant — chaque baisse du relevé compte désormais comme une remise à zéro du compteur.","adopted.warn_statistics_removed":"Cette entité n'a plus de classe de statistiques ; Home Assistant ouvrira une réparation sur les statistiques déjà collectées.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Paramètres de surveillance du panneau","header.graph_settings":"Paramètres d'horizon temporel du graphique","header.site":"Site","header.grid":"Réseau","header.upstream":"Amont","header.downstream":"Aval","header.solar":"Solaire","header.battery":"Batterie","header.toggle_units":"Basculer Watts / Ampères","header.enable_switches":"Activer les interrupteurs","header.switches_enabled":"Interrupteurs activés","controls.admin_only":"Seul un administrateur peut utiliser les commandes de ce panneau.","controls.disabled":"La commande de ce panneau est désactivée dans ses options.","controls.read_only":"Votre compte Home Assistant ne peut pas utiliser les commandes de ce panneau.","controls.entity_unauthorized":"Votre compte Home Assistant ne peut pas utiliser cette commande.","controls.not_operable":"Vous ne pouvez pas utiliser les commandes de ce panneau.","grid.unknown":"Inconnu","grid.configure":"Configurer le circuit","grid.configure_subdevice":"Configurer l'appareil","grid.on":"On","grid.off":"Off","grid.shared_switch":"Commute tous les circuits de cet emplacement","meters.title":"Compteurs","meters.importing":"en import","meters.exporting":"en export","meters.imported":"importés","meters.exported":"exportés","subdevice.ev_charger":"Chargeur VE","subdevice.battery":"Batterie","subdevice.fallback":"Sous-appareil","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Puissance","subdevice.solar":"Solaire","subdevice.solar_inverter":"Onduleur solaire","subdevice.site_total":"Total du site","subdevice.in_site_total":"Inclus dans le total du site","sidepanel.graph_settings":"Paramètres des Graphiques","sidepanel.global_defaults":"Valeurs par défaut globales pour tous les circuits","sidepanel.favorites_subtitle":"Favoris","sidepanel.global_default":"Défaut Global","sidepanel.list_view_columns":"Colonnes de la liste","sidepanel.columns":"Colonnes","sidepanel.circuit_scales":"Échelles des Graphiques de Circuits","sidepanel.subdevice_scales":"Échelles des Graphiques de Sous-Appareils","sidepanel.reset_to_global":"Réinitialiser à la valeur globale","sidepanel.relay":"Relais","sidepanel.breaker":"Disjoncteur","sidepanel.capacity":"capacité de {amps} A","monitoringRating.title":"Calibres des disjoncteurs dans l'application SPAN","monitoringRating.panel_rating":"Le panneau publie {panel} A","monitoringRating.other_breaker":"Autre disjoncteur (A)","monitoringRating.other_breaker_label":"Autre disjoncteur dans l'emplacement de {circuit}","monitoringRating.reset":"Supprimer les calibres copiés","monitoringRating.invalid_other":"Saisissez le calibre de l'autre disjoncteur en nombre entier d'ampères, 1 ou plus.","monitoringRating.guidance":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-20A, saisissez ici le second. Les panneaux SPAN Panel MAIN 32 n'indiquent que le premier, et la surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble.","monitoringRating.guidance_two_spaces":"Si votre application SPAN affiche deux calibres pour ce circuit, par exemple 20-30A, saisissez ici le second.","monitoringRating.averaged_legs":"Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases de ce circuit, ce qui peut masquer une phase en surcharge. Nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.turn_off_monitoring":"Désactiver la surveillance","monitoringRating.threshold_warning":"Les seuils personnalisés de ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge.","monitoringRating.threshold_warning_global":"Les seuils globaux qu'utilise ce circuit dépassent 100 %. Avec les calibres copiés, ils s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge ; modifiez-les dans {settings}, onglet {tab}.","monitoringRating.use_global_thresholds":"Utiliser les seuils globaux","monitoringRating.note_title":"Disjoncteurs tandem sur SPAN Panel MAIN 32","monitoringRating.note_problem":"Les panneaux SPAN Panel MAIN 32 n'indiquent pas quels disjoncteurs sont des tandems, ni le calibre du second disjoncteur d'un tandem. Un tandem place deux disjoncteurs dans un emplacement, mais le panneau l'indique comme un seul circuit avec le calibre du premier disjoncteur seulement, tandis qu'un seul capteur lit les deux disjoncteurs ensemble. Un tandem 20-20 affiche 20 A ici et peut supporter 40 A, si bien que la surveillance déclenche de fausses alertes sur lui.","monitoringRating.note_steps":"Pour corriger cela, copiez les calibres depuis votre application SPAN :","monitoringRating.note_step_find":"Dans l'application SPAN, trouvez chaque circuit dont le disjoncteur affiche deux calibres, par exemple 20-20A.","monitoringRating.note_step_enter":"Dans le tableau ci-dessous, saisissez le second calibre dans le champ {column} de ce circuit. Appuyez ensuite sur Entrée ou passez au champ suivant.","monitoringRating.note_step_single":"Laissez le champ vide pour un circuit à disjoncteur unique.","monitoringRating.note_judged":"La surveillance juge alors cet emplacement par rapport aux deux disjoncteurs ensemble : 40 A pour un 20-20. Seule la surveillance utilise la copie, et le capteur Breaker Rating du circuit affiche toujours ce que le panneau indique. Pour supprimer un calibre copié, sélectionnez ✕ à côté de son champ.","monitoringRating.note_thresholds":"Si vous avez relevé les seuils d'un tandem au-dessus de 100 % pour faire cesser ses alertes, sélectionnez {reset} sur sa ligne. Ces seuils s'appliquent désormais aux deux disjoncteurs ensemble.","monitoringRating.note_two_spaces":"Pour un circuit qui occupe deux emplacements, saisissez le second calibre de la même façon si votre application SPAN en affiche deux, par exemple 20-30A. Les panneaux SPAN Panel MAIN 32 n'indiquent que la moyenne des deux phases d'un tel circuit, ce qui peut masquer une phase en surcharge : la copie ne peut donc pas être appliquée, et nous recommandons de désactiver la surveillance de ce circuit.","monitoringRating.note_guide":"Pour en savoir plus, consultez le guide des disjoncteurs tandem et à charges multiples.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Supprimer les calibres copiés de {circuit}","monitoringRating.table_threshold_warning":"Les seuils de ce circuit dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Sélectionnez {reset} pour utiliser les seuils globaux.","monitoringRating.table_threshold_warning_global":"Les seuils globaux dépassent 100 % et s'appliquent désormais aux deux disjoncteurs ensemble, ce qui peut laisser passer une vraie surcharge. Modifiez-les dans {settings} ci-dessus.","monitoringRating.warning_announcement":"{circuit} : {warning}","error.package_ratings_failed":"Impossible de mettre à jour les calibres copiés depuis l'application SPAN","sidepanel.judged_against":"Évalué selon : {rating}","sidepanel.shedding_priority":"Priorité de Délestage","sidepanel.priority_label":"Priorité","sidepanel.monitoring":"Surveillance","sidepanel.global":"Global","sidepanel.custom":"Personnalisé","sidepanel.continuous_pct":"Continu %","sidepanel.spike_pct":"Pic %","sidepanel.window_duration":"Durée de fenêtre","sidepanel.cooldown":"Refroidissement","sidepanel.favorite":"Favori","sidepanel.save_to_favorites":"Enregistrer dans les favoris","panel.favorites":"Favoris","status.monitoring":"Surveillance","status.circuits":"circuits","status.mains":"alimentation","status.warning":"avertissement","status.warnings":"avertissements","status.alert":"alerte","status.alerts":"alertes","status.override":"remplacement","status.overrides":"remplacements","card.no_device":"Ouvrez l'éditeur de carte et sélectionnez votre appareil SPAN Panel.","card.device_not_found":"Appareil de panneau introuvable. Vérifiez device_id dans la configuration de la carte.","card.topology_error":"La réponse de topologie ne contient pas panel_size et aucun circuit trouvé. Mettez à jour l'intégration SPAN Panel.","card.panel_size_error":"Impossible de déterminer panel_size. Aucun circuit trouvé et aucun attribut panel_size. Mettez à jour l'intégration SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Sélectionnez un panneau...","editor.chart_window":"Fenêtre de temps du graphique","editor.days":"jours","editor.hours":"heures","editor.minutes":"minutes","editor.chart_metric":"Métrique du graphique","editor.visible_sections":"Sections visibles","editor.panel_circuits":"Circuits du panneau","editor.battery_bess":"Batterie (BESS)","editor.ev_charger_evse":"Chargeur VE (EVSE)","editor.solar_pv":"Solaire (PV)","editor.no_entities":"Aucune entité à afficher","editor.tab_style":"Style des onglets","editor.tab_style_text":"Texte","editor.tab_style_icon":"Icône","metric.power":"Puissance","metric.current":"Courant","metric.soc":"État de Charge","metric.soe":"État d'Énergie","shedding.always_on":"Critique","shedding.never":"Non délestable","shedding.soc_threshold":"Seuil SoC","shedding.off_grid":"Délestable","shedding.unknown":"Inconnu","shedding.select.never":"Reste allumé en cas de coupure","shedding.select.soc_threshold":"Allumé jusqu'au seuil batterie","shedding.select.off_grid":"S'éteint en cas de coupure"},ja:{"tab.panel":"パネル","tab.by_panel":"パネル別","tab.by_activity":"活動別","tab.by_area":"エリア別","tab.monitoring":"モニタリング","tab.settings":"設定","tab.adopted":"採用済み","list.search_placeholder":"回路を検索...","list.unassigned_area":"未割り当て","list.no_results":"回路が見つかりません","monitoring.heading":"モニタリング","monitoring.global_settings":"グローバル設定","monitoring.enabled":"有効","monitoring.continuous":"継続 (%)","monitoring.spike":"スパイク (%)","monitoring.window":"ウィンドウ (分)","monitoring.cooldown":"クールダウン (分)","monitoring.monitored_points":"監視ポイント","monitoring.col.name":"名前","monitoring.col.continuous":"継続","monitoring.col.spike":"スパイク","monitoring.col.window":"ウィンドウ","monitoring.col.cooldown":"クールダウン","monitoring.rating":"定格","monitoring.all_none":"全選択 / 全解除","monitoring.reset":"リセット","monitoring.limit_invalid":"{min} から {max} までの整数を入力してください。","monitoring.enable_invalid":"モニタリングは有効になっていません。マークされた項目を修正してください。","monitoring.point_field":"{name}の{field}","monitoring.reset_point":"{name}をリセット","monitoring.admin_only":"モニタリングを変更できるのは管理者のみです。","notification.heading":"通知設定","notification.targets":"通知先","notification.none_selected":"未選択","notification.targets_button":"通知先: {targets}","notification.no_targets":"通知先が見つかりません","notification.all_targets":"すべて","notification.event_bus_target":"イベントバス (HAイベントバス)","notification.priority":"優先度","notification.priority.default":"デフォルト","notification.priority.passive":"パッシブ","notification.priority.active":"アクティブ","notification.priority.time_sensitive":"緊急","notification.priority.critical":"重大","notification.hint.critical":"サイレント/おやすみモードを無視","notification.hint.time_sensitive":"集中モードを突破","notification.hint.passive":"サイレント配信","notification.hint.active":"標準配信","notification.title_template":"タイトルテンプレート","notification.message_template":"メッセージテンプレート","notification.placeholders":"プレースホルダー:","notification.event_bus_help":"イベントバスが発行するイベントタイプ","notification.event_bus_payload":"ペイロード:","notification.test_label":"テスト通知","notification.test_button":"テスト送信","notification.test_sending":"送信中...","notification.test_sent":"テスト通知を送信しました","error.prefix":"エラー:","error.failed_save":"保存に失敗","error.failed":"失敗","error.panel_offline":"SPANパネルに接続できません","error.panel_reconnected":"SPANパネルが再接続されました","error.panel_offline_named":"{name}に接続できません","error.panel_reconnected_named":"{name}が再接続されました","error.discovery_failed":"SPANパネルへの接続に失敗しました","error.relay_failed":"リレーの切り替えに失敗しました","error.shedding_failed":"シェディング優先度の更新に失敗しました","error.threshold_failed":"しきい値の保存に失敗しました","error.graph_horizon_failed":"グラフの時間範囲の更新に失敗しました","error.favorites_fetch_failed":"お気に入りの読み込みに失敗しました","error.favorites_toggle_failed":"お気に入りの更新に失敗しました","error.history_failed":"履歴データの読み込みに失敗しました","error.monitoring_failed":"監視ステータスの読み込みに失敗しました","error.graph_settings_failed":"グラフ設定の読み込みに失敗しました","error.areas_failed":"エリア割り当てが同期されていない可能性があります","error.retry":"再試行","card.connecting":"SPANパネルに接続中...","monitoringRating.none":"定格なし","monitoringRating.copied":"SPAN アプリの {package}(パネルの公開値 {panel} A)","monitoringRating.copied_unnamed":"SPAN アプリからコピー","monitoringRating.judged_copied":"判定基準 {rating} A: {copied}","settings.heading":"設定","settings.description":"統合の一般設定(エンティティ名、デバイスプレフィックス、回路番号)は統合のオプションフローで管理されます。","settings.open_link":"SPAN Panel統合設定を開く","adopted.heading":"採用済みエンティティ","adopted.description":"ベンダーの測定値と採用済みデバイスは最小限のメタデータで登録されます。キュレーションでデバイスクラス、統計クラス、表示区分を設定できます。保存すると統合が再読み込みされ、次回の起動から適用されます。","adopted.filter_placeholder":"エンティティ名またはデバイス名で絞り込み","adopted.no_results":"この条件に一致する採用済みエンティティはありません","adopted.none":"このパネルにキュレーション対象はありません。","adopted.load_failed":"採用済みエンティティを読み込めません","adopted.count":"{count} 件","adopted.vendor_readings":"ベンダー測定値","adopted.adopted_device":"採用済みデバイス","adopted.via_panel":"SPAN Panel 経由","adopted.curated":"キュレーション済み","adopted.stale":"無効","adopted.stale_note":"パネルは保存された次の項目をサポートしなくなりました: {fields}","adopted.enable_entity":"エンティティを有効化","adopted.enabled":"有効","adopted.disabled":"無効","adopted.enable_note":"保存時に有効化されます — キュレーション自体が有効化することはありません","adopted.registry_unavailable":"有効化・名前は、このエンティティがレジストリに登録された後に利用できます。","adopted.name":"名前","adopted.device_class":"デバイスクラス","adopted.device_class_note":"パネルの単位({unit})により選択肢が制限されます","adopted.device_class_note_unitless":"パネルが公開する内容により選択肢が制限されます","adopted.no_device_class":"デバイスクラスなし","adopted.statistics_class":"統計クラス","adopted.statistics_note":"長期統計は次回の再読み込み後に開始されます","adopted.no_statistics":"統計なし","adopted.prominence":"表示区分","adopted.diagnostic":"診断","adopted.standard":"標準","adopted.display_unit":"表示単位","adopted.unit_as_published":"公開されたまま","adopted.precision":"小数点以下桁数","adopted.precision_default":"既定","adopted.read_only":"読み取り専用","adopted.settable":"書き込み可","adopted.save":"保存","adopted.clear":"キュレーションを消去","adopted.reload_note":"保存すると SPAN Panel 統合が再読み込みされます","adopted.saved":"保存しました — 統合を再読み込みしています","adopted.confirm_heading":"統計クラスの確認","adopted.confirm_setting":"{name} を {value} に設定しようとしています。","adopted.confirm_clearing_subject":"{name} の統計クラスを消去しようとしています。","adopted.confirm_total_increasing":"積算増加は値の低下をすべてメーターのリセットとして扱います。この測定値が他の理由でも下がる場合、長期統計は恒久的に破損します。後からクラスを直しても、既に書き込まれた履歴は修復されません。","adopted.confirm_clearing":"このエンティティの長期統計は収集されなくなり、削除するクラスの下で既に収集された統計について Home Assistant が修復項目を作成します。","adopted.save_anyway":"それでも保存","adopted.cancel":"キャンセル","adopted.warn_total_increasing":"積算増加として保存しました — 測定値の低下はすべてメーターのリセットとして数えられます。","adopted.warn_statistics_removed":"このエンティティに統計クラスはなくなりました。既に収集された統計について Home Assistant が修復項目を作成します。","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"パネルモニタリング設定","header.graph_settings":"グラフ時間範囲設定","header.site":"サイト","header.grid":"グリッド","header.upstream":"上流","header.downstream":"下流","header.solar":"ソーラー","header.battery":"バッテリー","header.toggle_units":"ワット/アンペア切り替え","header.enable_switches":"スイッチを有効化","header.switches_enabled":"スイッチ有効","controls.admin_only":"このパネルのコントロールを操作できるのは管理者のみです。","controls.disabled":"このパネルのコントロールはオプションで無効になっています。","controls.read_only":"お使いのHome Assistantアカウントでは、このパネルのコントロールを操作できません。","controls.entity_unauthorized":"お使いのHome Assistantアカウントでは、このコントロールを操作できません。","controls.not_operable":"このパネルのコントロールは操作できません。","grid.unknown":"不明","grid.configure":"回路を設定","grid.configure_subdevice":"デバイスを設定","grid.on":"オン","grid.off":"オフ","grid.shared_switch":"このスペースのすべての回路を切り替えます","meters.title":"メーター","meters.importing":"受電中","meters.exporting":"送電中","meters.imported":"受電","meters.exported":"送電","subdevice.ev_charger":"EV充電器","subdevice.battery":"バッテリー","subdevice.fallback":"サブデバイス","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"電力","subdevice.solar":"ソーラー","subdevice.solar_inverter":"ソーラーインバーター","subdevice.site_total":"サイト合計","subdevice.in_site_total":"サイト合計に含まれます","sidepanel.graph_settings":"グラフ設定","sidepanel.global_defaults":"全回路のグローバルデフォルト","sidepanel.favorites_subtitle":"お気に入り","sidepanel.global_default":"グローバルデフォルト","sidepanel.list_view_columns":"リスト表示の列数","sidepanel.columns":"列","sidepanel.circuit_scales":"回路グラフスケール","sidepanel.subdevice_scales":"サブデバイスグラフスケール","sidepanel.reset_to_global":"グローバルにリセット","sidepanel.relay":"リレー","sidepanel.breaker":"ブレーカー","sidepanel.capacity":"容量 {amps} A","monitoringRating.title":"SPAN アプリのブレーカー定格","monitoringRating.panel_rating":"パネルの公開値 {panel} A","monitoringRating.other_breaker":"もう一方のブレーカー (A)","monitoringRating.other_breaker_label":"{circuit} のスペースにあるもう一方のブレーカー","monitoringRating.reset":"コピーした定格を削除","monitoringRating.invalid_other":"もう一方のブレーカーの定格を 1 以上の整数のアンペアで入力してください。","monitoringRating.guidance":"SPAN アプリでこの回路に 20-20A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。SPAN Panel MAIN 32 パネルが報告するのは 1 つ目だけで、モニタリングはこのスペースを両方のブレーカーの合計で判定します。","monitoringRating.guidance_two_spaces":"SPAN アプリでこの回路に 20-30A のように 2 つの定格が表示されている場合は、2 つ目をここに入力してください。","monitoringRating.averaged_legs":"SPAN Panel MAIN 32 パネルはこの回路の 2 本の線の平均値しか報告しないため、過負荷の線が見えなくなることがあります。この回路のモニタリングをオフにすることをおすすめします。","monitoringRating.turn_off_monitoring":"モニタリングをオフにする","monitoringRating.threshold_warning":"この回路のカスタムしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。","monitoringRating.threshold_warning_global":"この回路が使用するグローバルしきい値は 100% を超えています。コピーした定格により、しきい値は両方のブレーカーの合計に適用されるようになったため、実際の過負荷を見逃すおそれがあります。{tab}タブの{settings}で変更してください。","monitoringRating.use_global_thresholds":"グローバルしきい値を使用","monitoringRating.note_title":"SPAN Panel MAIN 32 のタンデムブレーカー","monitoringRating.note_problem":"SPAN Panel MAIN 32 パネルは、どのブレーカーがタンデムかも、タンデムの 2 つ目のブレーカーの定格も報告しません。タンデムは 1 つのスペースに 2 つのブレーカーを収めますが、パネルはそれを 1 つ目のブレーカーの定格だけを持つ 1 つの回路として報告し、1 つのセンサーが両方のブレーカーの合計を読み取ります。20-20 のタンデムはここでは 20 A と表示されますが 40 A まで流せるため、モニタリングが誤ったアラートを出します。","monitoringRating.note_steps":"これを直すには、次の手順で SPAN アプリから定格をコピーします。","monitoringRating.note_step_find":"SPAN アプリで、ブレーカーに 20-20A のように 2 つの定格が表示されている回路をすべて探します。","monitoringRating.note_step_enter":"下の表で、その回路の{column}フィールドに 2 つ目の定格を入力します。続けて Enter キーを押すか、次のフィールドに移動します。","monitoringRating.note_step_single":"ブレーカーが 1 つだけの回路では、フィールドを空のままにします。","monitoringRating.note_judged":"するとモニタリングは、そのスペースを両方のブレーカーの合計で判定します。20-20 なら 40 A です。コピーを使うのはモニタリングだけで、回路の Breaker Rating センサーは引き続きパネルが報告する値を表示します。コピーした定格を削除するには、フィールドの横の ✕ を選択します。","monitoringRating.note_thresholds":"アラートを止めるためにタンデムのしきい値を 100% より上に上げていた場合は、その行の{reset}を選択してください。それらのしきい値は今後、両方のブレーカーの合計に適用されます。","monitoringRating.note_two_spaces":"2 つのスペースにまたがる回路でも、SPAN アプリに 20-30A のように 2 つの定格が表示されていれば、同じ方法で 2 つ目の定格を入力します。SPAN Panel MAIN 32 パネルはそのような回路の 2 本の線の平均値しか報告せず、過負荷の線が見えなくなることがあるため、コピーは適用できません。その回路のモニタリングをオフにすることをおすすめします。","monitoringRating.note_guide":"詳しくは、タンデムブレーカーと複数負荷ブレーカーのガイドをご覧ください。","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"{circuit} のコピーした定格を削除","monitoringRating.table_threshold_warning":"この回路のしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。{reset}を選択するとグローバルしきい値を使用します。","monitoringRating.table_threshold_warning_global":"グローバルしきい値は 100% を超えており、今後は両方のブレーカーの合計に適用されるため、実際の過負荷を見逃すおそれがあります。上の{settings}で変更してください。","monitoringRating.warning_announcement":"{circuit}:{warning}","error.package_ratings_failed":"SPAN アプリからコピーした定格の更新に失敗しました","sidepanel.judged_against":"判定基準: {rating}","sidepanel.shedding_priority":"シェディング優先度","sidepanel.priority_label":"優先度","sidepanel.monitoring":"モニタリング","sidepanel.global":"グローバル","sidepanel.custom":"カスタム","sidepanel.continuous_pct":"継続 %","sidepanel.spike_pct":"スパイク %","sidepanel.window_duration":"ウィンドウ時間","sidepanel.cooldown":"クールダウン","sidepanel.favorite":"お気に入り","sidepanel.save_to_favorites":"お気に入りに保存","panel.favorites":"お気に入り","status.monitoring":"モニタリング","status.circuits":"回路","status.mains":"主電源","status.warning":"警告","status.warnings":"警告","status.alert":"アラート","status.alerts":"アラート","status.override":"上書き","status.overrides":"上書き","card.no_device":"カードエディタを開いてSPAN Panelデバイスを選択してください。","card.device_not_found":"パネルデバイスが見つかりません。カード設定のdevice_idを確認してください。","card.topology_error":"トポロジー応答にpanel_sizeがなく、回路が見つかりません。SPAN Panel統合を更新してください。","card.panel_size_error":"panel_sizeを判定できません。回路がpanel_size属性が見つかりません。SPAN Panel統合を更新してください。","editor.panel_label":"SPAN Panel","editor.select_panel":"パネルを選択...","editor.chart_window":"グラフ時間ウィンドウ","editor.days":"日","editor.hours":"時間","editor.minutes":"分","editor.chart_metric":"グラフ指標","editor.visible_sections":"表示セクション","editor.panel_circuits":"パネル回路","editor.battery_bess":"バッテリー (BESS)","editor.ev_charger_evse":"EV充電器 (EVSE)","editor.solar_pv":"ソーラー (PV)","editor.no_entities":"表示するエンティティがありません","editor.tab_style":"タブスタイル","editor.tab_style_text":"テキスト","editor.tab_style_icon":"アイコン","metric.power":"電力","metric.current":"電流","metric.soc":"充電状態","metric.soe":"エネルギー状態","shedding.always_on":"重要","shedding.never":"切断不可","shedding.soc_threshold":"SoCしきい値","shedding.off_grid":"切断可能","shedding.unknown":"不明","shedding.select.never":"停電時もオンを維持","shedding.select.soc_threshold":"バッテリーしきい値までオン","shedding.select.off_grid":"停電時にオフ"},pt:{"tab.panel":"Painel","tab.by_panel":"Por Painel","tab.by_activity":"Por Atividade","tab.by_area":"Por Área","tab.monitoring":"Monitoramento","tab.settings":"Configurações","tab.adopted":"Adotadas","list.search_placeholder":"Pesquisar circuitos...","list.unassigned_area":"Não atribuído","list.no_results":"Nenhum circuito encontrado","monitoring.heading":"Monitoramento","monitoring.global_settings":"Configurações Globais","monitoring.enabled":"Ativado","monitoring.continuous":"Contínuo (%)","monitoring.spike":"Pico (%)","monitoring.window":"Janela (min)","monitoring.cooldown":"Resfriamento (min)","monitoring.monitored_points":"Pontos Monitorados","monitoring.col.name":"Nome","monitoring.col.continuous":"Contínuo","monitoring.col.spike":"Pico","monitoring.col.window":"Janela","monitoring.col.cooldown":"Resfriamento","monitoring.rating":"Corrente nominal","monitoring.all_none":"Todos / Nenhum","monitoring.reset":"Redefinir","monitoring.limit_invalid":"Digite um número inteiro de {min} a {max}.","monitoring.enable_invalid":"O monitoramento não foi ativado: corrija os campos marcados.","monitoring.point_field":"{field} de {name}","monitoring.reset_point":"Redefinir {name}","monitoring.admin_only":"Somente um administrador pode alterar o monitoramento.","notification.heading":"Configurações de Notificação","notification.targets":"Destinos de Notificação","notification.none_selected":"Nenhum selecionado","notification.targets_button":"Destinos de Notificação: {targets}","notification.no_targets":"Nenhum destino de notificação encontrado","notification.all_targets":"Todos","notification.event_bus_target":"Barramento de Eventos (barramento de eventos do HA)","notification.priority":"Prioridade","notification.priority.default":"Padrão","notification.priority.passive":"Passivo","notification.priority.active":"Ativo","notification.priority.time_sensitive":"Urgente","notification.priority.critical":"Crítico","notification.hint.critical":"Substitui silencioso/Não perturbar","notification.hint.time_sensitive":"Atravessa o modo Foco","notification.hint.passive":"Entrega silenciosa","notification.hint.active":"Entrega padrão","notification.title_template":"Modelo de Título","notification.message_template":"Modelo de Mensagem","notification.placeholders":"Variáveis:","notification.event_bus_help":"O Barramento de Eventos dispara o tipo de evento","notification.event_bus_payload":"com dados:","notification.test_label":"Notificação de teste","notification.test_button":"Enviar teste","notification.test_sending":"Enviando...","notification.test_sent":"Notificação de teste enviada","error.prefix":"Erro:","error.failed_save":"Falha ao salvar","error.failed":"Falhou","error.panel_offline":"SPAN Panel inacessível","error.panel_reconnected":"SPAN Panel reconectado","error.panel_offline_named":"{name} inacessível","error.panel_reconnected_named":"{name} reconectado","error.discovery_failed":"Não foi possível conectar ao SPAN Panel","error.relay_failed":"Não foi possível alternar o relé","error.shedding_failed":"Não foi possível atualizar a prioridade de desligamento","error.threshold_failed":"Não foi possível salvar o limite","error.graph_horizon_failed":"Não foi possível atualizar o horizonte temporal do gráfico","error.favorites_fetch_failed":"Não foi possível carregar os favoritos","error.favorites_toggle_failed":"Não foi possível atualizar o favorito","error.history_failed":"Não foi possível carregar os dados históricos","error.monitoring_failed":"Não foi possível carregar o status de monitoramento","error.graph_settings_failed":"Não foi possível carregar as configurações do gráfico","error.areas_failed":"As atribuições de áreas podem estar fora de sincronização","error.retry":"Tentar novamente","card.connecting":"Conectando ao SPAN Panel...","monitoringRating.none":"sem corrente nominal","monitoringRating.copied":"{package} do seu app SPAN (o painel publica {panel} A)","monitoringRating.copied_unnamed":"Copiado do seu app SPAN","monitoringRating.judged_copied":"Avaliado com base em {rating} A: {copied}","settings.heading":"Configurações","settings.description":"As configurações gerais da integração (nomes de entidades, prefixo do dispositivo, números de circuito) são gerenciadas através do fluxo de opções da integração.","settings.open_link":"Abrir Configurações de Integração SPAN Panel","adopted.heading":"Entidades adotadas","adopted.description":"As leituras do fornecedor e os dispositivos adotados chegam com metadados mínimos. Faça a curadoria de uma para definir sua classe de dispositivo, classe de estatísticas e proeminência — alterações salvas recarregam a integração e valem a partir da próxima inicialização.","adopted.filter_placeholder":"Filtrar por nome de entidade ou dispositivo","adopted.no_results":"Nenhuma entidade adotada corresponde a este filtro","adopted.none":"Este painel não publica nada para curadoria.","adopted.load_failed":"Não foi possível carregar as entidades adotadas","adopted.count":"{count} adotadas","adopted.vendor_readings":"LEITURAS DO FORNECEDOR","adopted.adopted_device":"DISPOSITIVO ADOTADO","adopted.via_panel":"via SPAN Panel","adopted.curated":"CURADA","adopted.stale":"OBSOLETA","adopted.stale_note":"O painel não suporta mais o que foi salvo para: {fields}","adopted.enable_entity":"Ativar entidade","adopted.enabled":"ATIVADA","adopted.disabled":"DESATIVADA","adopted.enable_note":"Ativada ao salvar — a curadoria nunca ativa por conta própria","adopted.registry_unavailable":"Ativação e nome ficam disponíveis assim que esta entidade existir no registro.","adopted.name":"Nome","adopted.device_class":"Classe de dispositivo","adopted.device_class_note":"opções limitadas pela unidade do painel ({unit})","adopted.device_class_note_unitless":"opções limitadas pelo que o painel publica","adopted.no_device_class":"Sem classe de dispositivo","adopted.statistics_class":"Classe de estatísticas","adopted.statistics_note":"as estatísticas de longo prazo começam após a próxima recarga","adopted.no_statistics":"Sem estatísticas","adopted.prominence":"Proeminência","adopted.diagnostic":"Diagnóstico","adopted.standard":"Padrão","adopted.display_unit":"Unidade exibida","adopted.unit_as_published":"Como publicada","adopted.precision":"Precisão","adopted.precision_default":"Padrão","adopted.read_only":"somente leitura","adopted.settable":"editável","adopted.save":"Salvar","adopted.clear":"Limpar curadoria","adopted.reload_note":"Salvar recarrega a integração SPAN Panel","adopted.saved":"Salvo — a integração está recarregando","adopted.confirm_heading":"Confirmar classe de estatísticas","adopted.confirm_setting":"Você está definindo {name} como {value}.","adopted.confirm_clearing_subject":"Você está limpando a classe de estatísticas de {name}.","adopted.confirm_total_increasing":"Total crescente trata toda queda do valor como uma reinicialização do medidor. Se esta leitura puder diminuir por qualquer outro motivo, as estatísticas de longo prazo ficarão permanentemente corrompidas — corrigir a classe depois não repara o histórico já gravado.","adopted.confirm_clearing":"As estatísticas de longo prazo deixarão de ser compiladas para esta entidade, e o Home Assistant abrirá um reparo sobre as estatísticas já coletadas na classe que você está removendo.","adopted.save_anyway":"Salvar mesmo assim","adopted.cancel":"Cancelar","adopted.warn_total_increasing":"Salvo como total crescente — cada queda da leitura agora conta como uma reinicialização do medidor.","adopted.warn_statistics_removed":"Esta entidade não tem mais classe de estatísticas; o Home Assistant abrirá um reparo sobre as estatísticas já coletadas.","horizon.5m":"5 Minutes","horizon.1h":"1 Hour","horizon.1d":"1 Day","horizon.1w":"1 Week","horizon.1M":"1 Month","settings.graph_horizon_heading":"Graph Time Horizon","settings.graph_horizon_description":"Default time window for all circuit graphs. Individual circuits can override this in their settings panel.","settings.global_default":"Global Default","settings.default_scale":"Default Scale","settings.circuit_graph_scales":"Circuit Graph Scales","settings.col.circuit":"Circuit","settings.col.scale":"Scale","sidepanel.graph_horizon":"Graph Time Horizon","header.default_name":"SPAN Panel","header.monitoring_settings":"Configurações de monitoramento do painel","header.graph_settings":"Configurações do horizonte temporal do gráfico","header.site":"Local","header.grid":"Rede","header.upstream":"Montante","header.downstream":"Jusante","header.solar":"Solar","header.battery":"Bateria","header.toggle_units":"Alternar Watts / Amperes","header.enable_switches":"Ativar Interruptores","header.switches_enabled":"Interruptores Ativados","controls.admin_only":"Somente um administrador pode operar os controles deste painel.","controls.disabled":"O controle deste painel está desativado nas suas opções.","controls.read_only":"Sua conta do Home Assistant não pode operar os controles deste painel.","controls.entity_unauthorized":"Sua conta do Home Assistant não pode operar este controle.","controls.not_operable":"Você não pode operar os controles deste painel.","grid.unknown":"Desconhecido","grid.configure":"Configurar circuito","grid.configure_subdevice":"Configurar dispositivo","grid.on":"Lig","grid.off":"Des","grid.shared_switch":"Liga e desliga todos os circuitos deste espaço","meters.title":"Medidores","meters.importing":"importando","meters.exporting":"exportando","meters.imported":"importados","meters.exported":"exportados","subdevice.ev_charger":"Carregador VE","subdevice.battery":"Bateria","subdevice.fallback":"Sub-dispositivo","subdevice.soc":"SoC","subdevice.soe":"SoE","subdevice.power":"Potência","subdevice.solar":"Solar","subdevice.solar_inverter":"Inversor solar","subdevice.site_total":"Total do local","subdevice.in_site_total":"Incluído no total do local","sidepanel.graph_settings":"Configurações de Gráficos","sidepanel.global_defaults":"Padrões globais para todos os circuitos","sidepanel.favorites_subtitle":"Favoritos","sidepanel.global_default":"Padrão Global","sidepanel.list_view_columns":"Colunas da Lista","sidepanel.columns":"Colunas","sidepanel.circuit_scales":"Escalas de Gráficos de Circuitos","sidepanel.subdevice_scales":"Escalas de Gráficos de Sub-Dispositivos","sidepanel.reset_to_global":"Redefinir para o padrão global","sidepanel.relay":"Relé","sidepanel.breaker":"Disjuntor","sidepanel.capacity":"capacidade de {amps} A","monitoringRating.title":"Correntes nominais dos disjuntores no app SPAN","monitoringRating.panel_rating":"O painel publica {panel} A","monitoringRating.other_breaker":"Outro disjuntor (A)","monitoringRating.other_breaker_label":"Outro disjuntor no espaço de {circuit}","monitoringRating.reset":"Remover as correntes nominais copiadas","monitoringRating.invalid_other":"Digite a corrente nominal do outro disjuntor como um número inteiro de amperes, 1 ou mais.","monitoringRating.guidance":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-20A, digite a segunda aqui. Os painéis SPAN Panel MAIN 32 informam apenas a primeira, e o monitoramento então avalia este espaço pelos dois disjuntores juntos.","monitoringRating.guidance_two_spaces":"Se o seu app SPAN mostrar duas correntes nominais para este circuito, como 20-30A, digite a segunda aqui.","monitoringRating.averaged_legs":"Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases deste circuito, o que pode esconder uma fase sobrecarregada. Recomendamos desativar o monitoramento deste circuito.","monitoringRating.turn_off_monitoring":"Desativar o monitoramento","monitoringRating.threshold_warning":"Os limites personalizados deste circuito passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real.","monitoringRating.threshold_warning_global":"Os limites globais que este circuito usa passam de 100%. Com as correntes nominais copiadas, eles agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real; altere-os em {settings}, na aba {tab}.","monitoringRating.use_global_thresholds":"Usar os limites globais","monitoringRating.note_title":"Disjuntores tandem no SPAN Panel MAIN 32","monitoringRating.note_problem":"Os painéis SPAN Panel MAIN 32 não informam quais disjuntores são tandem, nem a corrente nominal do segundo disjuntor de um tandem. Um tandem coloca dois disjuntores em um espaço, mas o painel o informa como um único circuito com apenas a corrente nominal do primeiro disjuntor, enquanto um único sensor lê os dois disjuntores juntos. Um tandem 20-20 mostra 20 A aqui e pode conduzir 40 A, então o monitoramento gera alertas falsos nele.","monitoringRating.note_steps":"Para corrigir isso, copie as correntes nominais do seu app SPAN:","monitoringRating.note_step_find":"No app SPAN, encontre cada circuito cujo disjuntor mostra duas correntes nominais, como 20-20A.","monitoringRating.note_step_enter":"Na tabela abaixo, digite a segunda corrente nominal no campo {column} desse circuito. Depois pressione Enter ou vá para o próximo campo.","monitoringRating.note_step_single":"Deixe o campo vazio para um circuito com um único disjuntor.","monitoringRating.note_judged":"O monitoramento então avalia esse espaço pelos dois disjuntores juntos: 40 A para um 20-20. Só o monitoramento usa a cópia, e o sensor Breaker Rating do circuito continua mostrando o que o painel informa. Para remover uma corrente nominal copiada, selecione ✕ ao lado do seu campo.","monitoringRating.note_thresholds":"Se você aumentou os limites de um tandem acima de 100% para interromper os alertas dele, selecione {reset} na linha dele. Esses limites agora se aplicam aos dois disjuntores juntos.","monitoringRating.note_two_spaces":"Para um circuito que ocupa dois espaços, digite a segunda corrente nominal da mesma forma se o seu app SPAN mostrar duas, como 20-30A. Os painéis SPAN Panel MAIN 32 informam apenas a média das duas fases de um circuito assim, o que pode esconder uma fase sobrecarregada, então a cópia não pode ser aplicada e recomendamos desativar o monitoramento desse circuito.","monitoringRating.note_guide":"Leia mais no guia de disjuntores tandem e de cargas múltiplas.","monitoringRating.panel_plus":"{panel} A +","monitoringRating.judged_equals":"= {rating} A","monitoringRating.clear_label":"Remover as correntes nominais copiadas de {circuit}","monitoringRating.table_threshold_warning":"Os limites deste circuito passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Selecione {reset} para usar os limites globais.","monitoringRating.table_threshold_warning_global":"Os limites globais passam de 100% e agora se aplicam aos dois disjuntores juntos, o que pode deixar passar uma sobrecarga real. Altere-os em {settings}, acima.","monitoringRating.warning_announcement":"{circuit}: {warning}","error.package_ratings_failed":"Não foi possível atualizar as correntes nominais copiadas do app SPAN","sidepanel.judged_against":"Avaliado com base em: {rating}","sidepanel.shedding_priority":"Prioridade de Desligamento","sidepanel.priority_label":"Prioridade","sidepanel.monitoring":"Monitoramento","sidepanel.global":"Global","sidepanel.custom":"Personalizado","sidepanel.continuous_pct":"Contínuo %","sidepanel.spike_pct":"Pico %","sidepanel.window_duration":"Duração da janela","sidepanel.cooldown":"Resfriamento","sidepanel.favorite":"Favorito","sidepanel.save_to_favorites":"Salvar nos favoritos","panel.favorites":"Favoritos","status.monitoring":"Monitoramento","status.circuits":"circuitos","status.mains":"alimentação","status.warning":"aviso","status.warnings":"avisos","status.alert":"alerta","status.alerts":"alertas","status.override":"substituição","status.overrides":"substituições","card.no_device":"Abra o editor do cartão e selecione seu dispositivo SPAN Panel.","card.device_not_found":"Dispositivo do painel não encontrado. Verifique device_id na configuração do cartão.","card.topology_error":"A resposta de topologia não contém panel_size e nenhum circuito encontrado. Atualize a integração SPAN Panel.","card.panel_size_error":"Não foi possível determinar panel_size. Nenhum circuito encontrado e nenhum atributo panel_size. Atualize a integração SPAN Panel.","editor.panel_label":"SPAN Panel","editor.select_panel":"Selecione um painel...","editor.chart_window":"Janela de tempo do gráfico","editor.days":"dias","editor.hours":"horas","editor.minutes":"minutos","editor.chart_metric":"Métrica do gráfico","editor.visible_sections":"Seções visíveis","editor.panel_circuits":"Circuitos do painel","editor.battery_bess":"Bateria (BESS)","editor.ev_charger_evse":"Carregador VE (EVSE)","editor.solar_pv":"Solar (FV)","editor.no_entities":"Nenhuma entidade para mostrar","editor.tab_style":"Estilo das abas","editor.tab_style_text":"Texto","editor.tab_style_icon":"Ícone","metric.power":"Potência","metric.current":"Corrente","metric.soc":"Estado de Carga","metric.soe":"Estado de Energia","shedding.always_on":"Crítico","shedding.never":"Não desligável","shedding.soc_threshold":"Limite SoC","shedding.off_grid":"Desligável","shedding.unknown":"Desconhecido","shedding.select.never":"Permanece ligado em uma queda","shedding.select.soc_threshold":"Ligado até limite da bateria","shedding.select.off_grid":"Desliga em uma queda"}};function n(n){return e[t]?.[n]??e.en?.[n]??n}function i(n,i){return(e[t]?.[n]??e.en?.[n]??n).replace(/\{(\w+)\}/g,(t,e)=>Object.prototype.hasOwnProperty.call(i,e)?i[e]:`{${e}}`)}const r="power",o="5m",a={"5m":{ms:3e5,refreshMs:1e3,useRealtime:!0},"1h":{ms:36e5,refreshMs:3e4,useRealtime:!1},"1d":{ms:864e5,refreshMs:6e4,useRealtime:!1},"1w":{ms:6048e5,refreshMs:6e4,useRealtime:!1},"1M":{ms:2592e6,refreshMs:6e4,useRealtime:!1}},s="span_panel",l="bess",c="evse",d="pv",u="sub_",h={power:{entityRole:"power",label:()=>n("metric.power"),unit:t=>Math.abs(t)>=1e3?"kW":"W",format:t=>{const e=Math.abs(t);return e>=1e3?(e/1e3).toFixed(1):e<10&&e>0?e.toFixed(1):String(Math.round(e))}},current:{entityRole:"current",label:()=>n("metric.current"),unit:()=>"A",format:t=>Math.abs(t).toFixed(1)}},p={soc:{entityRole:"soc",label:()=>n("metric.soc"),unit:()=>"%",format:t=>String(Math.round(t)),fixedMin:0,fixedMax:100},soe:{entityRole:"soe",label:()=>n("metric.soe"),unit:()=>"kWh",format:t=>t.toFixed(1)},power:h.power},f={always_on:{icon:"mdi:battery",icon2:"mdi:router-wireless",color:"#4caf50",label:()=>n("shedding.always_on")},never:{icon:"mdi:battery",color:"#4caf50",label:()=>n("shedding.never")},soc_threshold:{icon:"mdi:battery-alert-variant-outline",color:"#9c27b0",label:()=>n("shedding.soc_threshold"),textLabel:"SoC"},off_grid:{icon:"mdi:transmission-tower",color:"#ff9800",label:()=>n("shedding.off_grid")},unknown:{icon:"mdi:help-circle-outline",color:"#888",label:()=>n("shedding.unknown")}},g=Object.keys(f).filter(t=>"unknown"!==t&&"always_on"!==t);var m=function(t,e){return m=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},m(t,e)};function v(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}m(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function _(t,e,n,i){var r,o=arguments.length,a=o<3?e:null===i?i=Object.getOwnPropertyDescriptor(e,n):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(t,e,n,i);else for(var s=t.length-1;s>=0;s--)(r=t[s])&&(a=(o<3?r(a):o>3?r(e,n,a):r(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}"function"==typeof SuppressedError&&SuppressedError; /** * @license * Copyright 2019 Google LLC @@ -15,7 +15,7 @@ const y=globalThis,b=y.ShadowRoot&&(void 0===y.ShadyCSS||y.ShadyCSS.nativeShadow * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ -const V=globalThis,j=t=>t,W=V.trustedTypes,q=W?W.createPolicy("lit-html",{createHTML:t=>t}):void 0,U="$lit$",G=`lit$${Math.random().toFixed(9).slice(2)}$`,X="?"+G,Y=`<${X}>`,Z=document,K=()=>Z.createComment(""),Q=t=>null===t||"object"!=typeof t&&"function"!=typeof t,J=Array.isArray,tt="[ \t\n\f\r]",et=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,nt=/-->/g,it=/>/g,rt=RegExp(`>|${tt}(?:([^\\s"'>=/]+)(${tt}*=${tt}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),ot=/'/g,at=/"/g,st=/^(?:script|style|textarea|title)$/i,lt=t=>(e,...n)=>({_$litType$:t,strings:e,values:n}),ct=lt(1),dt=lt(2),ut=Symbol.for("lit-noChange"),ht=Symbol.for("lit-nothing"),pt=new WeakMap,ft=Z.createTreeWalker(Z,129);function gt(t,e){if(!J(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==q?q.createHTML(e):e}const mt=(t,e)=>{const n=t.length-1,i=[];let r,o=2===e?"":3===e?"":"",a=et;for(let e=0;e"===l[0]?(a=r??et,c=-1):void 0===l[1]?c=-2:(c=a.lastIndex-l[2].length,s=l[1],a=void 0===l[3]?rt:'"'===l[3]?at:ot):a===at||a===ot?a=rt:a===nt||a===it?a=et:(a=rt,r=void 0);const u=a===rt&&t[e+1].startsWith("/>")?" ":"";o+=a===et?n+Y:c>=0?(i.push(s),n.slice(0,c)+U+n.slice(c)+G+u):n+G+(-2===c?e:u)}return[gt(t,o+(t[n]||"")+(2===e?"":3===e?"":"")),i]};class vt{constructor({strings:t,_$litType$:e},n){let i;this.parts=[];let r=0,o=0;const a=t.length-1,s=this.parts,[l,c]=mt(t,e);if(this.el=vt.createElement(l,n),ft.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(i=ft.nextNode())&&s.length0){i.textContent=W?W.emptyScript:"";for(let n=0;nJ(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==ht&&Q(this._$AH)?this._$AA.nextSibling.data=t:this.T(Z.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:n}=t,i="number"==typeof n?this._$AC(t):(void 0===n.el&&(n.el=vt.createElement(gt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===i)this._$AH.p(e);else{const t=new yt(i,this),n=t.u(this.options);t.p(e),this.T(n),this._$AH=t}}_$AC(t){let e=pt.get(t.strings);return void 0===e&&pt.set(t.strings,e=new vt(t)),e}k(t){J(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let n,i=0;for(const r of t)i===e.length?e.push(n=new bt(this.O(K()),this.O(K()),this,this.options)):n=e[i],n._$AI(r),i++;i2||""!==n[0]||""!==n[1]?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=ht}_$AI(t,e=this,n,i){const r=this.strings;let o=!1;if(void 0===r)t=_t(this,t,e,0),o=!Q(t)||t!==this._$AH&&t!==ut,o&&(this._$AH=t);else{const i=t;let a,s;for(t=r[0],a=0;at,q=V.trustedTypes,W=q?q.createPolicy("lit-html",{createHTML:t=>t}):void 0,U="$lit$",G=`lit$${Math.random().toFixed(9).slice(2)}$`,X="?"+G,Y=`<${X}>`,Z=document,K=()=>Z.createComment(""),Q=t=>null===t||"object"!=typeof t&&"function"!=typeof t,J=Array.isArray,tt="[ \t\n\f\r]",et=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,nt=/-->/g,it=/>/g,rt=RegExp(`>|${tt}(?:([^\\s"'>=/]+)(${tt}*=${tt}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),ot=/'/g,at=/"/g,st=/^(?:script|style|textarea|title)$/i,lt=t=>(e,...n)=>({_$litType$:t,strings:e,values:n}),ct=lt(1),dt=lt(2),ut=Symbol.for("lit-noChange"),ht=Symbol.for("lit-nothing"),pt=new WeakMap,ft=Z.createTreeWalker(Z,129);function gt(t,e){if(!J(t)||!t.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==W?W.createHTML(e):e}const mt=(t,e)=>{const n=t.length-1,i=[];let r,o=2===e?"":3===e?"":"",a=et;for(let e=0;e"===l[0]?(a=r??et,c=-1):void 0===l[1]?c=-2:(c=a.lastIndex-l[2].length,s=l[1],a=void 0===l[3]?rt:'"'===l[3]?at:ot):a===at||a===ot?a=rt:a===nt||a===it?a=et:(a=rt,r=void 0);const u=a===rt&&t[e+1].startsWith("/>")?" ":"";o+=a===et?n+Y:c>=0?(i.push(s),n.slice(0,c)+U+n.slice(c)+G+u):n+G+(-2===c?e:u)}return[gt(t,o+(t[n]||"")+(2===e?"":3===e?"":"")),i]};class vt{constructor({strings:t,_$litType$:e},n){let i;this.parts=[];let r=0,o=0;const a=t.length-1,s=this.parts,[l,c]=mt(t,e);if(this.el=vt.createElement(l,n),ft.currentNode=this.el.content,2===e||3===e){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(i=ft.nextNode())&&s.length0){i.textContent=q?q.emptyScript:"";for(let n=0;nJ(t)||"function"==typeof t?.[Symbol.iterator])(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==ht&&Q(this._$AH)?this._$AA.nextSibling.data=t:this.T(Z.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:n}=t,i="number"==typeof n?this._$AC(t):(void 0===n.el&&(n.el=vt.createElement(gt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===i)this._$AH.p(e);else{const t=new yt(i,this),n=t.u(this.options);t.p(e),this.T(n),this._$AH=t}}_$AC(t){let e=pt.get(t.strings);return void 0===e&&pt.set(t.strings,e=new vt(t)),e}k(t){J(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let n,i=0;for(const r of t)i===e.length?e.push(n=new bt(this.O(K()),this.O(K()),this,this.options)):n=e[i],n._$AI(r),i++;i2||""!==n[0]||""!==n[1]?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=ht}_$AI(t,e=this,n,i){const r=this.strings;let o=!1;if(void 0===r)t=_t(this,t,e,0),o=!Q(t)||t!==this._$AH&&t!==ut,o&&(this._$AH=t);else{const i=t;let a,s;for(t=r[0],a=0;a(...e)=>({_$litDirective$:t,values:e}))(zt);class $t{constructor(){this._persistent=new Map,this._transient=null,this._transientTimer=null,this._subscribers=new Set,this._watchedPanels=new Map}add(t){const e={...t,timestamp:Date.now()};if(e.persistent)this._persistent.set(e.key,e);else{this._clearTransient(),this._transient=e;const t=e.ttl??5e3;this._transientTimer=setTimeout(()=>{this._transient=null,this._transientTimer=null,this._notify()},t)}this._notify()}remove(t){if(this._persistent.has(t))return this._persistent.delete(t),void this._notify();this._transient?.key===t&&(this._clearTransient(),this._notify())}clear(t){void 0===t?(this._persistent.clear(),this._clearTransient(),this._watchedPanels.clear()):!0===t.persistent?this._persistent.clear():!1===t.persistent&&this._clearTransient(),this._notify()}get active(){const t=[...this._persistent.values()];return null!==this._transient&&t.push(this._transient),t}hasPersistent(t){return this._persistent.has(t)}hasAnyPanelOffline(){for(const t of this._persistent.keys())if("panel-offline"===t||t.startsWith("panel-offline:"))return!0;return!1}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}watchPanelStatus(t){this.watchPanelStatuses([{entityId:t,panelName:null}])}watchPanelStatuses(t){const e=this._watchedPanels,n=new Map;for(const i of t){const t=e.get(i.entityId);n.set(i.entityId,{panelName:i.panelName??null,wasOffline:t?.wasOffline??!1})}const i=this._isSingleUnnamed(e),r=this._isSingleUnnamed(n);for(const t of e.keys()){n.has(t)&&i===r||this._persistent.delete(this._offlineKey(t,i))}this._watchedPanels=n,this._notify()}clearPanelStatusWatch(){if(0===this._watchedPanels.size)return;const t=this._isSingleUnnamed(this._watchedPanels);for(const e of this._watchedPanels.keys())this._persistent.delete(this._offlineKey(e,t));this._watchedPanels.clear(),this._notify()}updateHass(t){if(0===this._watchedPanels.size)return;const e=this._isSingleUnnamed(this._watchedPanels);for(const[r,o]of this._watchedPanels){const a=t.states[r]?.state,s="on"===a,l=this._offlineKey(r,e),c=this._reconnectKey(r,e);if(s){const t=o.wasOffline;o.wasOffline=!1,this.remove(l),t&&this.add({key:c,level:"info",message:null===o.panelName?n("error.panel_reconnected"):i("error.panel_reconnected_named",{name:o.panelName}),persistent:!1})}else o.wasOffline=!0,this.hasPersistent(l)||this.add({key:l,level:"error",message:null===o.panelName?n("error.panel_offline"):i("error.panel_offline_named",{name:o.panelName}),persistent:!0})}}dispose(){this._clearTransient(),this._persistent.clear(),this._subscribers.clear(),this._watchedPanels.clear()}_isSingleUnnamed(t){if(1!==t.size)return!1;for(const e of t.values())return null===e.panelName;return!1}_offlineKey(t,e){return e?"panel-offline":`panel-offline:${t}`}_reconnectKey(t,e){return e?"panel-reconnected":`panel-reconnected:${t}`}_clearTransient(){null!==this._transientTimer&&(clearTimeout(this._transientTimer),this._transientTimer=null),this._transient=null}_notify(){for(const t of this._subscribers)try{t()}catch(t){console.warn("SPAN Panel: error-store subscriber threw",t)}}}const Ht={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ft(t){return String(t).replace(/[&<>"']/g,t=>Ht[t]??t)}const Bt="span_panel_list_columns";function Vt(){try{const t=localStorage.getItem(Bt);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function jt(t){try{localStorage.setItem(Bt,String(t))}catch{}}function Wt(t){return(void 0===t.monitoring_rating_a?t.breaker_rating_a:t.monitoring_rating_a)??null}function qt(t){return null!=t&&!1!==t.monitoring_enabled}function Ut(t,e){return qt(e)?Wt(t):t.breaker_rating_a??null}const Gt=["continuous_threshold_pct","spike_threshold_pct"];function Xt(t,e){return qt(e)?function(t,e){return"averaged_legs"===t?.package_ratings_state&&qt(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?Wt(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="Validation error: ",ee={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 ne(t,e){return"object"==typeof t&&null!==t?ee[e](t):void 0}async function ie(t,e,n,i){const r=ne(e,"translation_key");if(t&&"string"==typeof r&&ne(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=ne(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(te)?o.slice(18):o;return a&&"[object Object]"!==a?a:i}function re(t){const e=t.getRootNode();return e instanceof Document||e instanceof ShadowRoot?e.activeElement:null}function oe(t){return null!==t&&re(t)===t}function ae(t){if(!t)return!1;const e=re(t);return null!==e&&t.contains(e)}function se(t){if(!t)return null;const e=re(t);return e instanceof HTMLElement&&t.contains(e)?e:null}function le(){return null===document.activeElement||document.activeElement===document.body}function ce(t,e){t.addEventListener("blur",()=>{queueMicrotask(()=>{t.isConnected&&e()})})}const de={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}},ue=["continuous_threshold_pct","spike_threshold_pct","window_duration_m","cooldown_duration_m"];function he(t){return ue.some(e=>e===t)}function pe(t){t.addEventListener("wheel",e=>{oe(t)&&e.preventDefault()},{passive:!1})}function fe(t,e,n){const{min:r,max:o}=de[e];pe(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()}),ce(t,c),{get dirty(){return a},check:l}}function ge(t,e){pe(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()}),ce(t,s),{get dirty(){return i},revert:a,answerRefusal:t=>r===t&&(a(),!0)}}function me(t,e,i){console.warn("SPAN Panel: package ratings update failed",i),ie(t,i,s,n("error.package_ratings_failed")).then(t=>{e?.add({key:"service:package-ratings",level:"error",message:t,persistent:!1})})}function ve(t){return t.members.map((e,n)=>({uuid:t.memberIds[n],circuit:e}))}function _e(t){return new Map(t.flatMap(t=>t.memberIds.map(e=>[e,t])))}function ye(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 be(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:xe(o),breaker_rating_a:s?s.breaker_rating_a:Se(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 xe(t){return[...new Set(t.flatMap(t=>t.tabs))].sort((t,e)=>t-e)}function we(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 Se(t){let e=0;for(const n of t){if(!n.breaker_rating_a)return null;e+=n.breaker_rating_a}return e}function Ce(t){if(1===t.length){const e=t[0].breaker_rating_a;return e?`${e}A`:""}return we(t)}function ke(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 Me(t){return t.circuit.package_ratings_a?.[1]??null}class Te{constructor(t){this._host=t,this._section=null,this._field=null}get element(){return this._section}mount(t){this._field=null;const e=ke(this._host.ratingsView);this._section=e?this._build(e):null,this._section&&t.after(this._section)}sync(t){const e=ke(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,se(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=Me(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=ge(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=Me(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?(oe(l)&&a?.focus(),l.remove()):null!==r&&!l&&s&&s.appendChild(this._buildReset(n.uuid)),this._syncWarning(t,n)}_storedInForce(){const t=ke(this._host.ratingsView);return t?Me(t.member):null}_save(t){const e=ke(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&&ke(this._host.ratingsView)?.member.uuid===t&&r.answerRefusal(e)&&(le()||ae(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=ae(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 Ae(t){return new Promise(e=>setTimeout(e,t))}class Ie{constructor(t){this._store=t}async callWS(t,e,n){const i=n?.retries??3,r=n?.errorId??`ws:${String(e.type??"unknown")}`;return this._withRetry(()=>t.callWS(e),i,r,n?.errorMessage)}async callService(t,e,n,i,r,o){const a=o?.retries??3,s=o?.errorId??`svc:${e}.${n}`;return this._withRetry(()=>t.callService(e,n,i,r),a,s,o?.errorMessage)}async _withRetry(t,e,i,r){if(this._store.hasAnyPanelOffline())try{const e=await t();return this._store.remove(i),e}catch(t){const e=t instanceof Error?t:new Error(Jt(t));throw this._store.add({key:i,level:"error",message:r??n("error.panel_offline"),persistent:!1}),e}let o;for(let n=0;n<=e;n++)try{const e=await t();return this._store.remove(i),e}catch(t){if(o=t instanceof Error?t:new Error(Jt(t)),n{try{const i={};e&&(i.config_entry_id=e);const o={type:"call_service",domain:s,service:"get_monitoring_status",service_data:i,return_response:!0},a=this._retry?await this._retry.callWS(t,o,{errorId:"fetch:monitoring",errorMessage:n("error.monitoring_failed")}):await t.callWS(o),l=Pe(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 Le{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 De,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 Ee(t){return t.entities?.current??t.entities?.power??""}function Re(t,e){return function(t,e){return t?.circuits?t.circuits[e]??null:null}(t,Ee(e))}function Ne(t){const e=new Map;for(const n of Object.values(t?.circuits??{})){const t=Ee(n);t&&n.name&&e.set(t,n.name)}return e}function ze(t){return{continuousPct:t?.continuous_threshold_pct??80,spikePct:t?.spike_threshold_pct??100}}function Oe(t,e){const{continuousPct:n,spikePct:i}=ze(e);return t>=i?"alert":t>=n?"warning":"normal"}function $e(t,e){return`utilization-${Oe(t,e)}`}const He="favorites-changed";async function Fe(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 Be{get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this._retry=t?new Ie(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 Ve(t){return Object.keys(t).some(e=>je(t,e))}function je(t,e){const n=t[e];return(n?.circuits?.length??0)>0||(n?.sub_devices?.length??0)>0}const We={names:["power","battery power"],suffixes:["_power"]},qe={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},Ue={names:["state of energy"],suffixes:["_soe_kwh"]};function Ge(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 Xe(t){return Ge(t,qe)}function Ye(t){return Ge(t,Ue)}function Ze(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}function Ke(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,Ge(n,We)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function Qe(t){const{headlineEid:e,siteTotalEid:n}=Ke(t),i=[e,n];return t.type===l&&i.push(Xe(t),Ye(t)),new Set(i.filter(t=>null!==t))}function Je(t){const e=[{role:"power",entityId:Ke(t).headlineEid}];return t.type===l&&e.push({role:"soc",entityId:Xe(t)},{role:"soe",entityId:Ye(t)}),e.filter(t=>null!==t.entityId)}function tn(t,e){return Ze(t.states[e])}function en(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 nn(t,e){return Je(t).length>0||e&&null!==en(t.entities)}function rn(t){return"number"==typeof t&&Number.isInteger(t)&&t>0}function on(t){return!0===t.outside_panel}function an(t,e){if(!t)return null;let n=null,i=null;const{first_position:r,last_position:o}=t;rn(r)&&rn(o)&&r<=o?(n=r,i=o):rn(e)&&(n=1,i=e);for(const e of Object.values(t.circuits))if(e&&!on(e))for(const t of e.tabs??[])rn(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 sn(t){return Math.ceil(t/2)}function ln(t){return t%2==0?1:0}function cn(t){if(2!==t.length)return null;const[e,n]=[Math.min(...t),Math.max(...t)];return sn(e)===sn(n)?"row-span":ln(e)===ln(n)?"col-span":"row-span"}function dn(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 un(t,e){return on(t)||xn(t,e)}function hn(t,e){const n=t.entities?.power;return Ze(n?e.states[n]:void 0)}function pn(t,e){const n=t.entities?.current;return Ze(n?e.states[n]:void 0)}function fn(t){return t.is_generation??"pv"===t.device_type}function gn(t,e){return fn(t)||null!==e&&e<0}function mn(t,e,n){const i=pn(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 vn=new Set(g),_n={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function yn(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function bn(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 xn(t,e){const n=yn(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(bn(t,e,"relay_state")??t.relay_state)}function wn(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=yn(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function Sn(t){return void 0===t?void 0:_n[t]}function Cn(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function kn(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=Cn(t,e);return void 0!==n&&vn.has(n)?n:Sn(bn(t,e,"shed_priority"))??Sn(t.priority)??"unknown"}const Mn={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"};class Tn extends HTMLElement{constructor(){super(),this.errorStore=null,this._thresholdReads=0,this._limitFields=[],this.attachShadow({mode:"open"}),this._hass=null,this._config=null,this._debounceTimers={},this._ratingsEditor=new Te(this)}set hass(t){this._hass=t,this.hasAttribute("open")&&this._config&&this._updateLiveState()}get hass(){return this._hass}disconnectedCallback(){this._clearDebounceTimers(),this._config=null}open(t){this._config=t,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;const r=n.querySelector(".subtitle");r&&(r.textContent=this._circuitSubtitle(i)),this._syncMonitoring()}close(){this._clearDebounceTimers(),this.removeAttribute("open"),this.removeAttribute("data-mode"),this._config=null,this.dispatchEvent(new CustomEvent("side-panel-closed",{bubbles:!0,composed:!0}))}_clearDebounceTimers(){for(const t of Object.keys(this._debounceTimers))clearTimeout(this._debounceTimers[t]);this._debounceTimers={}}_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 .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=Je(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-${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-${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._renderGraphHorizonSection(i,e),e.showMonitoring&&this._renderMonitoringSection(i,e)}_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[Ce(e),e.length>1&&t.capacityA?i("sidepanel.capacity",{amps:String(t.capacityA)}):"",n.length>0?`${n.join("/")}V`:"",`Tabs [${xe(e).join(",")}]`].filter(Boolean).join(" · ")}_favoriteEntityId(t){return t?.current??t?.power??null}_buildSubDeviceFavoriteHeart(t,e){const n=en(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 Fe(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(He)),n?.favorites??{}}(this._hass,i):await async function(t,e){const n=await Fe(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(He)),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=en(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"===wn(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.textContent=n("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle";const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{if(!this._hass||"operable"!==wn(e,this._hass))return;const t=a.checked;this._callService("switch",t?"turn_on":"turn_off",{entity_id:s}).catch(t=>{console.warn("SPAN Panel: relay toggle failed",t),this.errorStore?.add({key:"service:relay",level:"error",message:n("error.relay_failed"),persistent:!1})})}),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.textContent=n("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select";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",()=>{this._callService("select","select_option",{entity_id:s,option:a.value}).catch(t=>{console.warn("SPAN Panel: shedding update failed",t),this.errorStore?.add({key:"service:shedding",level:"error",message:n("error.shedding_failed"),persistent:!1})})}),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 this._callDomainService("set_circuit_package_ratings",this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return this._callDomainService("clear_circuit_package_ratings",this._ratingsPayload(t,{}))}reportRatingsFailure(t){me(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 i=e.querySelector('input[name="monitoring-mode"][value="global"]'),r=e.querySelector('input[name="monitoring-mode"][value="custom"]'),o=e.querySelector('[data-role="threshold-fields"]');i&&(i.checked=!0),o&&(o.style.display="none"),this._thresholdReads+=1;const a={circuit_id:t.entities?.power||t.uuid};t.configEntryId&&(a.config_entry_id=t.configEntryId);try{await this._callDomainService("clear_circuit_threshold",a)}catch(e){return console.warn("SPAN Panel: monitoring update failed",e),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1}),this._config===t&&(r&&(r.checked=!0),o&&(o.style.display="block")),!1}const s=this._config===t?t.monitoringGlobals??null:null;return this._monitoringChanged(t.uuid,{has_override:!1,continuous_threshold_pct:s?.continuous_threshold_pct,spike_threshold_pct:s?.spike_threshold_pct}),!0}async turnOffMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode)&&(!!await this._sendMonitoringEnabled(t,!1)&&(this._showMonitoringEnabled(t.uuid,!1),!0))}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},!0!==e.has_override&&this._showGlobalChoice(),this._syncMonitoring())}_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,ae(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)}_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";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=qt(s);l&&a.setAttribute("checked",""),r.appendChild(o),r.appendChild(a),i.appendChild(r);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)}async _sendMonitoringEnabled(t,e){const i={circuit_id:t.entities?.power||t.uuid,monitoring_enabled:e};t.configEntryId&&(i.config_entry_id=t.configEntryId);try{return await this._callDomainService("set_circuit_threshold",i),!0}catch(t){return console.warn("SPAN Panel: monitoring update failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1}),!1}}_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&&ae(r);r.style.display=e?"block":"none",t&&i?.focus()}this._monitoringChanged(t,{monitoring_enabled:e})}_createLimitRow(t,e,n,i,r){const o=Mn[e],{min:a,max:s}=de[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=fe(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){this._callDomainService("set_circuit_threshold",e).then(()=>this._readThresholds(t,e),t=>{console.warn("SPAN Panel: monitoring update failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1})})}_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){this._hass&&(t.disabled="operable"!==wn(e,this._hass),xn(e,this._hass)?t.setAttribute("checked",""):t.removeAttribute("checked"))}_applySheddingSelect(t,e){if(!this._hass)return;const n=kn(e,this._hass);g.includes(n)?t.value=n:t.selectedIndex=-1,t.disabled=!function(t,e){const n=Cn(t,e);return void 0!==n&&vn.has(n)}(e,this._hass)}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=Re(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 Pe(e?.response)}_callService(t,e,n){return this._hass?Promise.resolve(this._hass.callService(t,e,n)):Promise.resolve()}_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",Tn)}catch{}class An 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 zt=class extends Nt{constructor(t){if(super(t),this.it=ht,t.type!==Rt)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===ht||null==t)return this._t=void 0,this.it=t;if(t===ut)return t;if("string"!=typeof t)throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const e=[t];return e.raw=e,this._t={_$litType$:this.constructor.resultType,strings:e,values:[]}}};zt.directiveName="unsafeHTML",zt.resultType=1;const Ot=(t=>(...e)=>({_$litDirective$:t,values:e}))(zt);class $t{constructor(){this._persistent=new Map,this._transient=null,this._transientTimer=null,this._subscribers=new Set,this._watchedPanels=new Map}add(t){const e={...t,timestamp:Date.now()};if(e.persistent)this._persistent.set(e.key,e);else{this._clearTransient(),this._transient=e;const t=e.ttl??5e3;this._transientTimer=setTimeout(()=>{this._transient=null,this._transientTimer=null,this._notify()},t)}this._notify()}remove(t){if(this._persistent.has(t))return this._persistent.delete(t),void this._notify();this._transient?.key===t&&(this._clearTransient(),this._notify())}clear(t){void 0===t?(this._persistent.clear(),this._clearTransient(),this._watchedPanels.clear()):!0===t.persistent?this._persistent.clear():!1===t.persistent&&this._clearTransient(),this._notify()}get active(){const t=[...this._persistent.values()];return null!==this._transient&&t.push(this._transient),t}hasPersistent(t){return this._persistent.has(t)}hasAnyPanelOffline(){for(const t of this._persistent.keys())if("panel-offline"===t||t.startsWith("panel-offline:"))return!0;return!1}subscribe(t){return this._subscribers.add(t),()=>{this._subscribers.delete(t)}}watchPanelStatus(t){this.watchPanelStatuses([{entityId:t,panelName:null}])}watchPanelStatuses(t){const e=this._watchedPanels,n=new Map;for(const i of t){const t=e.get(i.entityId);n.set(i.entityId,{panelName:i.panelName??null,wasOffline:t?.wasOffline??!1})}const i=this._isSingleUnnamed(e),r=this._isSingleUnnamed(n);for(const t of e.keys()){n.has(t)&&i===r||this._persistent.delete(this._offlineKey(t,i))}this._watchedPanels=n,this._notify()}clearPanelStatusWatch(){if(0===this._watchedPanels.size)return;const t=this._isSingleUnnamed(this._watchedPanels);for(const e of this._watchedPanels.keys())this._persistent.delete(this._offlineKey(e,t));this._watchedPanels.clear(),this._notify()}updateHass(t){if(0===this._watchedPanels.size)return;const e=this._isSingleUnnamed(this._watchedPanels);for(const[r,o]of this._watchedPanels){const a=t.states[r]?.state,s="on"===a,l=this._offlineKey(r,e),c=this._reconnectKey(r,e);if(s){const t=o.wasOffline;o.wasOffline=!1,this.remove(l),t&&this.add({key:c,level:"info",message:null===o.panelName?n("error.panel_reconnected"):i("error.panel_reconnected_named",{name:o.panelName}),persistent:!1})}else o.wasOffline=!0,this.hasPersistent(l)||this.add({key:l,level:"error",message:null===o.panelName?n("error.panel_offline"):i("error.panel_offline_named",{name:o.panelName}),persistent:!0})}}dispose(){this._clearTransient(),this._persistent.clear(),this._subscribers.clear(),this._watchedPanels.clear()}_isSingleUnnamed(t){if(1!==t.size)return!1;for(const e of t.values())return null===e.panelName;return!1}_offlineKey(t,e){return e?"panel-offline":`panel-offline:${t}`}_reconnectKey(t,e){return e?"panel-reconnected":`panel-reconnected:${t}`}_clearTransient(){null!==this._transientTimer&&(clearTimeout(this._transientTimer),this._transientTimer=null),this._transient=null}_notify(){for(const t of this._subscribers)try{t()}catch(t){console.warn("SPAN Panel: error-store subscriber threw",t)}}}const Ht={"&":"&","<":"<",">":">",'"':""","'":"'"};function Ft(t){return String(t).replace(/[&<>"']/g,t=>Ht[t]??t)}const Bt="span_panel_list_columns";function Vt(){try{const t=localStorage.getItem(Bt);if(!t)return 1;const e=parseInt(t,10);return 1===e||2===e||3===e?e:1}catch{return 1}}function jt(t){try{localStorage.setItem(Bt,String(t))}catch{}}function qt(t){return(void 0===t.monitoring_rating_a?t.breaker_rating_a:t.monitoring_rating_a)??null}function Wt(t){return null!=t&&!1!==t.monitoring_enabled}function Ut(t,e){return Wt(e)?qt(t):t.breaker_rating_a??null}const Gt=["continuous_threshold_pct","spike_threshold_pct"];function Xt(t,e){return Wt(e)?function(t,e){return"averaged_legs"===t?.package_ratings_state&&Wt(e)}(t,e)?"averaged_legs":function(t,e){return t&&e&&function(t){const e=t.package_ratings_state;return"applies"===e||"pending"===e&&"one_space"===t.package_ratings_form}(t)&&Gt.some(t=>(e[t]??0)>100)?!0===e.has_override?"own":"global":null}(t,e):null}function Yt(t){return{amps:t?qt(t):void 0,panelAmps:t?.breaker_rating_a,userSet:!0===t?.monitoring_rating_user_set,packageRatings:t?.package_ratings_a??null}}function Zt(t){return t.packageRatings?.length&&t.panelAmps?i("monitoringRating.copied",{package:t.packageRatings.join("-"),panel:String(t.panelAmps)}):n("monitoringRating.copied_unnamed")}function Kt(t){if(!t.amps)return"";const e=`${Ft(t.amps)}A`;return t.userSet?`${e}${function(t){const e=Ft(Zt(t));return``}(t)}`:e}function Qt(t){const e=t.nextElementSibling;e instanceof HTMLElement&&e.classList.contains("rating-copied-note")&&(e.hidden=!e.hidden,t.setAttribute("aria-expanded",String(!e.hidden)))}function Jt(t){return t instanceof Error||"object"==typeof t&&null!==t&&"message"in t&&"string"==typeof t.message?t.message:String(t)}const te=new Set(["Unauthorized","UnknownUser"]);function ee(t){if("object"!=typeof t||null===t)return!1;const e="code"in t?t.code:void 0;return"unauthorized"===e||"home_assistant_error"===e&&"message"in t&&te.has(t.message)}const ne="Validation error: ",ie={translation_domain:t=>"translation_domain"in t?t.translation_domain:void 0,translation_key:t=>"translation_key"in t?t.translation_key:void 0,translation_placeholders:t=>"translation_placeholders"in t?t.translation_placeholders:void 0};function re(t,e){return"object"==typeof t&&null!==t?ie[e](t):void 0}async function oe(t,e,n,i){const r=re(e,"translation_key");if(t&&"string"==typeof r&&re(e,"translation_domain")===n){const i=`component.${n}.exceptions.${r}.message`;try{const r=t.loadBackendTranslation?await t.loadBackendTranslation("exceptions",n):t.localize,o=r?.(i,function(t){const e=re(t,"translation_placeholders");if("object"!=typeof e||null===e)return{};const n={};for(const[t,i]of Object.entries(e))"string"!=typeof i&&"number"!=typeof i||(n[t]=i);return n}(e));if(o)return o}catch{}}const o=Jt(e),a=o.startsWith(ne)?o.slice(18):o;return a&&"[object Object]"!==a?a:i}function ae(t){const e=t.getRootNode();return e instanceof Document||e instanceof ShadowRoot?e.activeElement:null}function se(t){return null!==t&&ae(t)===t}function le(t){if(!t)return!1;const e=ae(t);return null!==e&&t.contains(e)}function ce(t){if(!t)return null;const e=ae(t);return e instanceof HTMLElement&&t.contains(e)?e:null}function de(){return null===document.activeElement||document.activeElement===document.body}function ue(t,e){t.addEventListener("blur",()=>{queueMicrotask(()=>{t.isConnected&&e()})})}const he={continuous_threshold_pct:{min:1,max:200},spike_threshold_pct:{min:1,max:200},window_duration_m:{min:1,max:180},cooldown_duration_m:{min:1,max:180}},pe=["continuous_threshold_pct","spike_threshold_pct","window_duration_m","cooldown_duration_m"];function fe(t){return pe.some(e=>e===t)}function ge(t){t.addEventListener("wheel",e=>{se(t)&&e.preventDefault()},{passive:!1})}function me(t,e,n){const{min:r,max:o}=he[e];ge(t);let a=!1;const s=e=>{e?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),n.report(e)},l=()=>{const e=""===t.value.trim()?Number.NaN:Number(t.value);return Number.isSafeInteger(e)&&e>=r&&e<=o?e:(s(i("monitoring.limit_invalid",{min:String(r),max:String(o)})),null)},c=()=>{if(!a)return;const t=l();null!==t&&(a=!1,s(null),n.save(t))};return t.addEventListener("input",()=>{a=!0,s(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&c()}),ue(t,c),{get dirty(){return a},check:l}}function ve(t,e){ge(t);let i=!1,r=null;const o=n=>{n?t.setAttribute("aria-invalid","true"):t.removeAttribute("aria-invalid"),e.report(n)},a=()=>{i=!1,r=null,o(null);const n=e.stored();t.value=null!==n?String(n):""},s=()=>{if(!i)return;const s=t.value.trim();if(""===s&&t.validity?.badInput)return void o(n("monitoringRating.invalid_other"));if(""===s)return void a();const l=Number(s);!Number.isSafeInteger(l)||l<1?o(n("monitoringRating.invalid_other")):(i=!1,o(null),l!==e.stored()&&(r=l,e.save(l)))};return t.addEventListener("input",()=>{i=!0,r=null,o(null)}),t.addEventListener("keydown",t=>{"Enter"===t.key&&s()}),ue(t,s),{get dirty(){return i},revert:a,answerRefusal:t=>r===t&&(a(),!0)}}function _e(t,e,i){console.warn("SPAN Panel: package ratings update failed",i),oe(t,i,s,n("error.package_ratings_failed")).then(t=>{e?.add({key:"service:package-ratings",level:"error",message:t,persistent:!1})})}function ye(t){return t.members.map((e,n)=>({uuid:t.memberIds[n],circuit:e}))}function be(t){return new Map(t.flatMap(t=>t.memberIds.map(e=>[e,t])))}function xe(t,e){if(!e)return t;const{breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}=e.circuit;return{...t,breaker_rating_a:n,monitoring_rating_a:i,monitoring_rating_user_set:r}}function we(t){const e=t.circuits,n=new Map;for(const[t,i]of Object.entries(e)){const e=i.shared_meter_group;e&&n.set(e,[...n.get(e)??[],[t,i]])}const i=[];for(const[r,o]of Object.entries(e)){const e=o.shared_meter_group,a=e?n.get(e):void 0;if(e&&a){if(a[0][0]===r){const[n,r]=a.find(([t])=>t===e)??a[0],o=a.map(([,t])=>t),s=t.shared_meter_groups?.[e];i.push({uuid:n,circuit:{...r,tabs:Se(o),breaker_rating_a:s?s.breaker_rating_a:ke(o),monitoring_rating_a:s?.monitoring_rating_a,monitoring_rating_user_set:!0===s?.monitoring_rating_user_set},members:o,memberIds:a.map(([t])=>t)})}}else i.push({uuid:r,circuit:o,members:[o],memberIds:[r]})}return i}function Se(t){return[...new Set(t.flatMap(t=>t.tabs))].sort((t,e)=>t-e)}function Ce(t){const e=function(t){return t.some(t=>!t.breaker_rating_a)?"":t.map(t=>Math.round(t.breaker_rating_a)).join("·")}(t);return e?1===t.length?`${e}A`:`${e} A`:""}function ke(t){let e=0;for(const n of t){if(!n.breaker_rating_a)return null;e+=n.breaker_rating_a}return e}function Me(t){if(1===t.length){const e=t[0].breaker_rating_a;return e?`${e}A`:""}return Ce(t)}function Te(t){if(!t?.offered)return null;const[e,...n]=t.members;if(!e||n.length>0)return null;const i=e.circuit.package_ratings_form,r=e.circuit.breaker_rating_a;return"one_space"!==i&&"two_spaces"!==i||null==r?null:{kind:i,member:e,panelA:r}}function Ae(t){return t.circuit.package_ratings_a?.[1]??null}class Ie{constructor(t){this._host=t,this._section=null,this._field=null}get element(){return this._section}mount(t){this._field=null;const e=Te(this._host.ratingsView);this._section=e?this._build(e):null,this._section&&t.after(this._section)}sync(t){const e=Te(this._host.ratingsView),n=this._section;if(n&&e&&n.dataset.kind===e.kind&&n.dataset.uuid===e.member.uuid)return void this._patch(n,e);const i=(r=n,ce(r)?.dataset.role??null);var r;this._field=null;const o=e?this._build(e):null;if(n&&o?n.replaceWith(o):n?n.remove():o&&t.after(o),this._section=o,null===i)return;const a=o?.querySelector(`[data-role="${i}"]`)??o?.querySelector('[data-role="rating-input"]');a?a.focus():this._host.focusAfterRatingsEditor()}_build(t){const e=document.createElement("div");e.dataset.role="rating-section",e.dataset.kind=t.kind,e.dataset.uuid=t.member.uuid,e.className="rating-section";const i=document.createElement("div");i.className="section-label",i.textContent=n("monitoringRating.title"),e.appendChild(i);const r=document.createElement("div");r.className="field-label",r.id="rating-guidance",r.dataset.role="rating-guidance",r.textContent=n("one_space"===t.kind?"monitoringRating.guidance":"monitoringRating.guidance_two_spaces"),e.appendChild(r);const o=document.createElement("div");o.className="field-label rating-feedback",o.id="rating-feedback",o.dataset.role="rating-feedback",o.setAttribute("aria-live","polite"),e.appendChild(this._buildRow(t,o)),e.appendChild(o);const a=document.createElement("div");return a.dataset.role="rating-warning-region",a.setAttribute("aria-live","polite"),e.appendChild(a),this._syncWarning(e,t.member),e}_buildRow(t,e){const{member:r}=t,o=document.createElement("div");o.className="field-row rating-row",o.dataset.role="rating-row",o.dataset.uuid=r.uuid;const a=document.createElement("span");a.className="field-label",a.id="rating-panel-rating",a.dataset.role="rating-panel-rating",a.textContent=i("monitoringRating.panel_rating",{panel:String(t.panelA)});const s=document.createElement("span");s.className="field-label",s.textContent=n("monitoringRating.other_breaker");const l=document.createElement("input");l.type="number",l.min="1",l.step="1",l.inputMode="numeric";const c=Ae(r);return l.value=null!==c?String(c):"",l.setAttribute("aria-label",i("monitoringRating.other_breaker_label",{circuit:r.circuit.name})),l.setAttribute("aria-describedby","rating-panel-rating rating-guidance rating-feedback"),l.dataset.role="rating-input",this._field=ve(l,{report:t=>{e.textContent=t??""},stored:()=>this._storedInForce(),save:t=>this._save(t)}),o.append(a,s,l),null!==c&&o.appendChild(this._buildReset(r.uuid)),o}_buildReset(t){const e=document.createElement("button");return e.type="button",e.className="text-btn",e.dataset.role="rating-reset",e.textContent=n("monitoringRating.reset"),e.addEventListener("click",()=>{this._field?.revert(),this._host.clearPackageRatings(t).catch(t=>this._host.reportRatingsFailure(t))}),e}_patch(t,e){const{member:n}=e,r=Ae(n),o=t.querySelector('[data-role="rating-panel-rating"]');o&&(o.textContent=i("monitoringRating.panel_rating",{panel:String(e.panelA)}));const a=t.querySelector('[data-role="rating-input"]');this._field&&!this._field.dirty&&this._field.revert();const s=t.querySelector('[data-role="rating-row"]'),l=t.querySelector('[data-role="rating-reset"]');null===r&&l?(se(l)&&a?.focus(),l.remove()):null!==r&&!l&&s&&s.appendChild(this._buildReset(n.uuid)),this._syncWarning(t,n)}_storedInForce(){const t=Te(this._host.ratingsView);return t?Ae(t.member):null}_save(t){const e=Te(this._host.ratingsView);if(!e)return;const{member:n,panelA:i}=e;this._host.setPackageRatings(n.uuid,[i,t]).catch(e=>{this._host.reportRatingsFailure(e),this._answerRefusal(n.uuid,t)})}_answerRefusal(t,e){const n=this._section,i=n?.querySelector('[data-role="rating-input"]'),r=this._field;n&&i&&r&&n.dataset.uuid===t&&Te(this._host.ratingsView)?.member.uuid===t&&r.answerRefusal(e)&&(de()||le(n))&&i.focus()}_syncWarning(t,e){const n=t.querySelector('[data-role="rating-warning-region"]');if(!n)return;const i=Xt(e.circuit,this._host.ratingsView?.monitoringInfo??null),r=n.firstElementChild instanceof HTMLElement?n.firstElementChild:null;if(r&&r.dataset.kind===i)return;const o=le(r);r?.remove(),i&&n.appendChild("averaged_legs"===i?this._buildAveragedLegsWarning():this._buildThresholdWarning(i)),o&&this._host.focusAfterRatingsEditor()}_buildThresholdWarning(t){const e="own"===t?n("monitoringRating.threshold_warning"):i("monitoringRating.threshold_warning_global",{settings:n("monitoring.global_settings"),tab:n("tab.monitoring")}),r=this._buildWarning("rating-threshold-warning",t,e);return"own"===t&&r.appendChild(this._buildActionButton("rating-threshold-reset",n("monitoringRating.use_global_thresholds"),()=>this._host.useGlobalThresholds())),r}_buildAveragedLegsWarning(){const t=this._buildWarning("rating-averaged-legs-warning","averaged_legs",n("monitoringRating.averaged_legs"));return t.appendChild(this._buildActionButton("rating-turn-off-monitoring",n("monitoringRating.turn_off_monitoring"),()=>this._host.turnOffMonitoring())),t}_buildWarning(t,e,n){const i=document.createElement("div");i.className="field-label rating-warning",i.dataset.role=t,i.dataset.kind=e,i.setAttribute("role","note");const r=document.createElement("span");return r.textContent=n,i.appendChild(r),i}_buildActionButton(t,e,n){const i=document.createElement("button");return i.type="button",i.className="text-btn",i.dataset.role=t,i.textContent=e,i.addEventListener("click",()=>{"true"!==i.getAttribute("aria-disabled")&&(i.setAttribute("aria-disabled","true"),n().then(t=>{t||i.removeAttribute("aria-disabled")}))}),i}}function Pe(t){return new Promise(e=>setTimeout(e,t))}class De{constructor(t){this._store=t}async callWS(t,e,n){const i=n?.retries??3,r=n?.errorId??`ws:${String(e.type??"unknown")}`;return this._withRetry(()=>t.callWS(e),i,r,n?.errorMessage)}async _withRetry(t,e,i,r){if(this._store.hasAnyPanelOffline())try{const e=await t();return this._store.remove(i),e}catch(t){const e=t instanceof Error?t:new Error(Jt(t));throw this._store.add({key:i,level:"error",message:r??n("error.panel_offline"),persistent:!1}),e}let o;for(let n=0;n<=e;n++)try{const e=await t();return this._store.remove(i),e}catch(t){if(o=t instanceof Error?t:new Error(Jt(t)),n{try{const i={};e&&(i.config_entry_id=e);const o={type:"call_service",domain:s,service:"get_monitoring_status",service_data:i,return_response:!0},a=this._retry?await this._retry.callWS(t,o,{errorId:"fetch:monitoring",errorMessage:n("error.monitoring_failed")}):await t.callWS(o),l=Le(a?.response);return r===this._generation&&(this._status=l,this._lastFetch=Date.now()),l}catch(t){return console.warn("SPAN Panel: monitoring status fetch failed",t),r===this._generation&&(this._status=null),this._retry||this._errorStore?.add({key:"fetch:monitoring",level:"warning",message:n("error.monitoring_failed"),persistent:!1}),null}finally{this._inflight?.gen===r&&(this._inflight=null)}})();return this._inflight={gen:r,promise:o},o}invalidate(){this._lastFetch=0,this._generation++}get status(){return this._status}clear(){this._status=null,this._lastFetch=0,this._generation++}}class Re{constructor(){this._caches=new Map,this._errorStore=null}get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t;for(const e of this._caches.values())e.errorStore=t}async fetchOne(t,e){let n=this._caches.get(e);return n||(n=new Ee,n.errorStore=this._errorStore,this._caches.set(e,n)),n.fetch(t,e)}invalidate(){for(const t of this._caches.values())t.invalidate()}clear(){this._caches.clear()}}function Ne(t){return t.entities?.current??t.entities?.power??""}function ze(t,e){return function(t,e){return t?.circuits?t.circuits[e]??null:null}(t,Ne(e))}function Oe(t){const e=new Map;for(const n of Object.values(t?.circuits??{})){const t=Ne(n);t&&n.name&&e.set(t,n.name)}return e}function $e(t){return{continuousPct:t?.continuous_threshold_pct??80,spikePct:t?.spike_threshold_pct??100}}function He(t,e){const{continuousPct:n,spikePct:i}=$e(e);return t>=i?"alert":t>=n?"warning":"normal"}function Fe(t,e){return`utilization-${He(t,e)}`}function Be(t){return!0===t?.user?.is_admin}function Ve(){return n("monitoring.admin_only")}class je extends Error{constructor(){super(Ve()),this.name="MonitoringChangeRefused"}}function qe(t){const e=e=>n=>async function(t,e,n){if(!t||!Be(t))throw new je;try{await t.callWS({type:"call_service",domain:s,service:e,service_data:n})}catch(t){throw ee(t)?new je:t}}(t,e,n);return{setGlobalMonitoring:e("set_global_monitoring"),testNotification:e("test_notification"),setCircuitThreshold:e("set_circuit_threshold"),clearCircuitThreshold:e("clear_circuit_threshold"),setMainsThreshold:e("set_mains_threshold"),clearMainsThreshold:e("clear_mains_threshold"),setCircuitPackageRatings:e("set_circuit_package_ratings"),clearCircuitPackageRatings:e("clear_circuit_package_ratings")}}function We(t,e){return t instanceof je?t.message:e}function Ue(t,e,i){console.warn(`SPAN Panel: ${i} failed`,e),t?.add({key:"service:monitoring",level:"error",message:We(e,n("error.threshold_failed")),persistent:!1})}const Ge=new Set(["number","text"]);function Xe(t){for(let e=t;e;e=e.parentElement)if(""!==e.style.opacity&&Number(e.style.opacity)<1)return!0;return!1}function Ye(t,e){const n=Ve();for(const i of t.querySelectorAll("input, select, textarea, button, span-switch"))void 0!==e&&i.matches(e)||(i instanceof HTMLInputElement&&Ge.has(i.type)||i instanceof HTMLTextAreaElement?i.readOnly=!0:i.setAttribute("disabled",""),i.title=n,"span-switch"!==i.localName&&(Xe(i)||(i.style.opacity="0.5"),i.style.cursor="not-allowed"))}function Ze(){const t=document.createElement("p");return t.dataset.role="monitoring-read-only",t.setAttribute("role","note"),t.style.cssText="margin:8px 0 12px;font-size:0.85em;color:var(--secondary-text-color);",t.textContent=Ve(),t}const Ke=["relay_state","relay_state_target","priority","priority_target"];function Qe(t){return"_favoriteRefs"in t}const Je=Object.freeze({mayOperate:!0,reason:null}),tn=Object.freeze({mayOperate:!1,reason:null}),en=["control_disabled","admin_only","read_only"];function nn(t){const e=t?.control_access;return"object"==typeof e&&null!==e&&"may_operate"in e&&"boolean"==typeof e.may_operate?e.may_operate?Je:{mayOperate:!1,reason:"reason"in e&&(n=e.reason,en.some(t=>t===n))?e.reason:null}:Je;var n}function rn(t){return"circuit"===t?.kind}function on(t,e){if(!t||!Qe(t))return nn(t);const n=t._favoriteRefs[e];return rn(n)?n.controlAccess:tn}function an(t){if(!t||!Qe(t))return nn(t);const e=[...cn(t,sn).values()],[n]=e;return!n||e.some(t=>t.mayOperate)?Je:n}function sn(t){return!!t?.entities?.switch&&!1!==t.is_user_controllable}function ln(t){return sn(t)||!!t?.entities?.select}function cn(t,e){const n=new Map;for(const[i,r]of Object.entries(t._favoriteRefs))rn(r)&&e(t.circuits[i])&&n.set(r.panelDeviceId,r.controlAccess);return n}const dn={control_disabled:()=>n("controls.disabled"),admin_only:()=>n("controls.admin_only"),read_only:()=>n("controls.read_only")};function un(t){return t.mayOperate?"":t.reason?dn[t.reason]():n("controls.not_operable")}class hn extends Error{constructor(t){super(t),this.name="ControlChangeRefused"}}function pn(t,e){return{setRelay:(n,i)=>fn(t,e,"switch",i?"turn_on":"turn_off",n,{}),setPriority:(n,i)=>fn(t,e,"select","select_option",n,{option:i})}}async function fn(t,e,i,r,o,a){if(!e.mayOperate)throw new hn(un(e));try{await t.callWS({type:"call_service",domain:i,service:r,service_data:a,target:{entity_id:o}})}catch(t){throw ee(t)?new hn(n("controls.entity_unauthorized")):t}}const gn={relay:{key:"service:relay",fallback:()=>n("error.relay_failed")},priority:{key:"service:shedding",fallback:()=>n("error.shedding_failed")}};function mn(t,e,n,i){console.warn(`SPAN Panel: ${i} change failed`,n);const{key:r,fallback:o}=gn[i];oe(t,n,s,o()).then(t=>{e?.add({key:r,level:"error",message:t,persistent:!1})})}function vn(t,e){const n=un(e);n?t.title=n:t.removeAttribute("title")}function _n(t){const e=un(t);return e?`

${Ft(e)}

`:""}const yn="favorites-changed";async function bn(t,e,n={}){const i=await t.callWS({type:"call_service",domain:s,service:e,service_data:n,return_response:!0});return i?.response??null}class xn{get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this._retry=t?new De(t):null}constructor(){this._errorStore=null,this._retry=null,this._map=null,this._lastFetch=0,this._inflight=null,this._generation=0}async fetch(t){const e=Date.now();if(this._inflight&&this._inflight.gen===this._generation)return this._inflight.promise;if(this._map&&e-this._lastFetch<3e4)return this._map;const i=this._generation,r=(async()=>{try{const e={type:"call_service",domain:s,service:"get_favorites",service_data:{},return_response:!0},r=this._retry?await this._retry.callWS(t,e,{errorId:"fetch:favorites",errorMessage:n("error.favorites_fetch_failed")}):await t.callWS(e),o=r?.response?.favorites??{};return i===this._generation&&(this._map=o,this._lastFetch=Date.now()),o}catch(t){return console.warn("SPAN Panel: favorites fetch failed",t),this._retry||this._errorStore?.add({key:"fetch:favorites",level:"warning",message:n("error.favorites_fetch_failed"),persistent:!1}),this._map??{}}finally{this._inflight?.gen===i&&(this._inflight=null)}})();return this._inflight={gen:i,promise:r},r}invalidate(){this._lastFetch=0,this._generation++}clear(){this._map=null,this._lastFetch=0,this._generation++}get map(){return this._map??{}}}function wn(t){return Object.keys(t).some(e=>Sn(t,e))}function Sn(t,e){const n=t[e];return(n?.circuits?.length??0)>0||(n?.sub_devices?.length??0)>0}const Cn={names:["power","battery power"],suffixes:["_power"]},kn={names:["battery level","battery percentage"],suffixes:["_battery_level","_battery_percentage"]},Mn={names:["state of energy"],suffixes:["_soe_kwh"]};function Tn(t,e){if(!t.entities)return null;for(const[n,i]of Object.entries(t.entities)){if("sensor"!==i.domain)continue;const t=(i.original_name??"").toLowerCase();if(e.names.some(e=>t===e))return n;if(i.unique_id&&e.suffixes.some(t=>i.unique_id.endsWith(t)))return n}return null}function An(t){return Tn(t,kn)}function In(t){return Tn(t,Mn)}function Pn(t){if(!t)return null;const e=Number.parseFloat(t.state);return Number.isFinite(e)?e:null}function Dn(t){const e=t.solar;return e?"inverter"===e.role?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:null}:e.power_entity_id?{headlineEid:e.power_entity_id,headlineIsSiteTotal:!1,siteTotalEid:e.site_power_entity_id}:{headlineEid:e.site_power_entity_id,headlineIsSiteTotal:null!==e.site_power_entity_id,siteTotalEid:null}:{headlineEid:(n=t,Tn(n,Cn)),headlineIsSiteTotal:!1,siteTotalEid:null};var n}function Ln(t){const{headlineEid:e,siteTotalEid:n}=Dn(t),i=[e,n];return t.type===l&&i.push(An(t),In(t)),new Set(i.filter(t=>null!==t))}function En(t){const e=[{role:"power",entityId:Dn(t).headlineEid}];return t.type===l&&e.push({role:"soc",entityId:An(t)},{role:"soe",entityId:In(t)}),e.filter(t=>null!==t.entityId)}function Rn(t,e){return Pn(t.states[e])}function Nn(t){if(!t)return null;let e=null;for(const[n,i]of Object.entries(t)){if("sensor"===i.domain)return n;e||(e=n)}return e}function zn(t,e){return En(t).length>0||e&&null!==Nn(t.entities)}function On(t){return"number"==typeof t&&Number.isInteger(t)&&t>0}function $n(t){return!0===t.outside_panel}function Hn(t,e){if(!t)return null;let n=null,i=null;const{first_position:r,last_position:o}=t;On(r)&&On(o)&&r<=o?(n=r,i=o):On(e)&&(n=1,i=e);for(const e of Object.values(t.circuits))if(e&&!$n(e))for(const t of e.tabs??[])On(t)&&(n=null===n?t:Math.min(n,t),i=null===i?t:Math.max(i,t));return null===n||null===i?null:{first:n,last:i}}function Fn(t){return Math.ceil(t/2)}function Bn(t){return t%2==0?1:0}function Vn(t){if(2!==t.length)return null;const[e,n]=[Math.min(...t),Math.max(...t)];return Fn(e)===Fn(n)?"row-span":Bn(e)===Bn(n)?"col-span":"row-span"}function jn(t,e,n,i){const r=[];return n||r.push("circuit-off"),i&&r.push("circuit-producer"),function(t){return!!t&&null!=t.over_threshold_since}(e)&&r.push("circuit-alert"),r.join(" ")}function qn(t,e){return $n(t)||ti(t,e)}function Wn(t,e){const n=t.entities?.power;return Pn(n?e.states[n]:void 0)}function Un(t,e){const n=t.entities?.current;return Pn(n?e.states[n]:void 0)}function Gn(t){return t.is_generation??"pv"===t.device_type}function Xn(t,e){return Gn(t)||null!==e&&e<0}function Yn(t,e,n){const i=Un(t,e);if(t.entities?.current&&null===i)return null;const r=n?.utilization_pct??null,o=Ut(t,n);return null===r&&null!==i&&o?Math.round(Math.abs(i)/o*1e3)/10:r}const Zn=new Set(g),Kn={NEVER:"never",SOC_THRESHOLD:"soc_threshold",OFF_GRID:"off_grid"};function Qn(t,e){const n=t.entities?.switch;return n?e.states[n]?.state:void 0}function Jn(t,e,n){const i=t.entities?.power,r=i?e.states[i]?.attributes?.[n]:void 0;return"string"==typeof r&&r?r:void 0}function ti(t,e){const n=Qn(t,e);return"on"===n||"off"===n?"on"===n:"CLOSED"===(Jn(t,e,"relay_state")??t.relay_state)}function ei(t,e){if(!t.entities?.switch||!1===t.is_user_controllable)return"none";const n=Qn(t,e);return void 0===n?"none":"on"===n||"off"===n?"operable":"inert"}function ni(t){return void 0===t?void 0:Kn[t]}function ii(t,e){const n=t.entities?.select;return n?e.states[n]?.state:void 0}function ri(t,e){if(t.always_on)return"always_on";if(!t.entities?.select)return"unknown";const n=ii(t,e);return void 0!==n&&Zn.has(n)?n:ni(Jn(t,e,"shed_priority"))??ni(t.priority)??"unknown"}const oi={continuous:"continuous_threshold_pct",spike:"spike_threshold_pct","window-m":"window_duration_m","cooldown-m":"cooldown_duration_m"},ai="relay-label",si="priority-label",li="controls-note";class ci{constructor(t,e){this.uuid=t,this._on=e,this._sent=0,this._from=0,this._pending=0}get on(){return this._on}get settled(){return 0===this._pending}answered(t){this._on=t}async send(t,e){const n=++this._sent;this._pending+=1;try{const i=await e();return i&&n>this._from&&(this._on=t,this._from=n),i}finally{this._pending-=1}}}class di extends HTMLElement{constructor(){super(),this.errorStore=null,this._thresholdReads=0,this._limitFields=[],this._storedMonitoring=null,this._controlAccess=tn,this.attachShadow({mode:"open"}),this._hass=null,this._config=null,this._debounceTimers={},this._ratingsEditor=new Ie(this)}set hass(t){const e=Be(this._hass)!==Be(t);this._hass=t,this.hasAttribute("open")&&this._config&&(e&&this._showsMonitoring()?this._render():this._updateLiveState())}_showsMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!0!==t.showMonitoring)}get hass(){return this._hass}open(t){this._config=t,this._storedMonitoring=t.panelMode||t.subDeviceMode||t.favoritesMode?null:new ci(t.uuid,Wt(t.monitoringInfo)),this._controlAccess=t.panelMode||t.subDeviceMode||t.favoritesMode?tn:t.controlAccess,this._render(),this.offsetHeight,this.setAttribute("open",""),this.setAttribute("data-mode",this._modeFor(t))}get openCircuit(){const t=this._config;return!t||!this.hasAttribute("open")||t.panelMode||t.subDeviceMode||t.favoritesMode?null:{uuid:t.uuid,configEntryId:t.configEntryId??null}}refreshRating(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i={...e,members:t.members,capacityA:t.capacityA,monitoringInfo:t.monitoringInfo,monitoringGlobals:t.monitoringGlobals};this._config=i,this._monitoringStoredAs(e.uuid,t.monitoringInfo);const r=n.querySelector(".subtitle");r&&(r.textContent=this._circuitSubtitle(i)),this._syncMonitoring()}close(){this.removeAttribute("open"),this.removeAttribute("data-mode"),this._config=null,this._storedMonitoring=null,this._controlAccess=tn,this.dispatchEvent(new CustomEvent("side-panel-closed",{bubbles:!0,composed:!0}))}_modeFor(t){return t.favoritesMode?"favorites":t.panelMode?"panel":t.subDeviceMode?"subDevice":"circuit"}_render(){const t=this._config;if(!t)return;const e=this.shadowRoot;if(!e)return;e.innerHTML="";const n=document.createElement("style");n.textContent='\n :host {\n display: block;\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n width: 360px;\n max-width: 90vw;\n z-index: 1000;\n transform: translateX(100%);\n transition: transform 0.3s ease;\n pointer-events: none;\n }\n :host([open]) {\n transform: translateX(0);\n pointer-events: auto;\n }\n\n .backdrop {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.3);\n z-index: -1;\n }\n :host([open]) .backdrop {\n display: block;\n }\n\n .panel {\n height: 100%;\n background: var(--card-background-color, #fff);\n border-left: 1px solid var(--divider-color, #e0e0e0);\n display: flex;\n flex-direction: column;\n overflow: hidden;\n }\n\n .panel-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 16px;\n border-bottom: 1px solid var(--divider-color, #e0e0e0);\n }\n .panel-header .title {\n font-size: 18px;\n font-weight: 500;\n color: var(--primary-text-color, #212121);\n margin: 0;\n }\n .panel-header .subtitle {\n font-size: 13px;\n color: var(--secondary-text-color, #727272);\n margin: 2px 0 0 0;\n }\n .close-btn {\n background: none;\n border: none;\n cursor: pointer;\n color: var(--secondary-text-color, #727272);\n padding: 4px;\n line-height: 1;\n font-size: 20px;\n }\n\n .panel-body {\n flex: 1;\n overflow-y: auto;\n padding: 16px;\n }\n\n .section {\n margin-bottom: 20px;\n }\n .section-label {\n font-size: 12px;\n font-weight: 600;\n text-transform: uppercase;\n color: var(--secondary-text-color, #727272);\n margin: 0 0 8px 0;\n letter-spacing: 0.5px;\n }\n\n .field-row {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: 8px 0;\n }\n /* Why the section\'s relay or priority cannot be operated, under it. */\n .controls-note {\n margin: 4px 0 0;\n font-size: 0.85em;\n color: var(--secondary-text-color, #727272);\n }\n .field-label {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n }\n\n select {\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n }\n\n input[type="number"] {\n width: 72px;\n padding: 6px 8px;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 4px;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 14px;\n text-align: right;\n }\n input[type="number"]:disabled {\n opacity: 0.5;\n }\n\n .radio-group {\n display: flex;\n gap: 16px;\n padding: 8px 0;\n }\n .radio-group label {\n display: flex;\n align-items: center;\n gap: 6px;\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n cursor: pointer;\n }\n\n .horizon-bar {\n display: flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n margin-top: 4px;\n }\n .horizon-segment {\n flex: 1;\n padding: 6px 0;\n text-align: center;\n font-size: 13px;\n cursor: pointer;\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n transition: background 0.15s ease, color 0.15s ease;\n user-select: none;\n line-height: 1.4;\n }\n .horizon-segment:last-child {\n border-right: none;\n }\n .horizon-segment:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .horizon-segment.active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n .horizon-segment.referenced {\n box-shadow: inset 0 -3px 0 var(--primary-color, #03a9f4);\n }\n\n .unit-toggle {\n display: inline-flex;\n border: 1px solid var(--divider-color, #e0e0e0);\n border-radius: 6px;\n overflow: hidden;\n }\n .unit-btn {\n padding: 4px 10px;\n border: none;\n border-right: 1px solid var(--divider-color, #e0e0e0);\n background: var(--card-background-color, #fff);\n color: var(--primary-text-color, #212121);\n font-size: 13px;\n font-weight: 500;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease;\n }\n .unit-btn:last-child {\n border-right: none;\n }\n .unit-btn:hover:not(.unit-active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .unit-btn.unit-active {\n background: var(--primary-color, #03a9f4);\n color: #fff;\n font-weight: 600;\n }\n\n .monitoring-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n }\n\n .fav-heart {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--secondary-text-color, #727272);\n border-radius: 4px;\n padding: 2px 6px;\n cursor: pointer;\n font-size: 0.9em;\n margin-right: 6px;\n line-height: 1;\n display: inline-flex;\n align-items: center;\n }\n .fav-heart.active {\n color: var(--primary-color, #03a9f4);\n border-color: var(--primary-color, #03a9f4);\n }\n .fav-heart:hover:not(.active) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .fav-heart span-icon {\n --mdc-icon-size: 16px;\n }\n\n .rating-section {\n margin-bottom: 8px;\n }\n .limit-row {\n flex-wrap: wrap;\n }\n .limit-feedback {\n flex-basis: 100%;\n }\n .rating-row {\n flex-wrap: wrap;\n justify-content: flex-start;\n gap: 6px 8px;\n }\n .rating-row [data-role="rating-panel-rating"] {\n flex-basis: 100%;\n }\n .rating-feedback {\n font-size: 13px;\n color: var(--error-color, #db4437);\n }\n .rating-warning {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: 6px 8px;\n margin-top: 6px;\n padding: 8px;\n border-left: 3px solid var(--warning-color, #ffa600);\n border-radius: 4px;\n background: color-mix(in srgb, var(--warning-color, #ffa600) 12%, transparent);\n font-size: 13px;\n }\n\n .text-btn {\n background: none;\n border: 1px solid var(--divider-color, #e0e0e0);\n color: var(--primary-text-color, #212121);\n border-radius: 4px;\n padding: 4px 8px;\n font: inherit;\n font-size: 13px;\n line-height: 1.3;\n cursor: pointer;\n }\n .text-btn:hover:not(:disabled):not([aria-disabled="true"]) {\n background: var(--secondary-background-color, #f5f5f5);\n }\n .text-btn:focus-visible {\n outline: 2px solid var(--primary-color, #03a9f4);\n outline-offset: 1px;\n }\n .text-btn:disabled,\n .text-btn[aria-disabled="true"] {\n opacity: 0.5;\n cursor: default;\n }\n\n .panel-mode-info {\n font-size: 14px;\n color: var(--primary-text-color, #212121);\n line-height: 1.6;\n }\n .panel-mode-info p {\n margin: 0 0 12px 0;\n }\n\n',e.appendChild(n);const i=document.createElement("div");i.className="backdrop",i.addEventListener("click",()=>this.close()),e.appendChild(i);const r=document.createElement("div");r.className="panel",e.appendChild(r),t.favoritesMode?this._renderFavoritesMode(r):t.panelMode?this._renderPanelMode(r):t.subDeviceMode?this._renderSubDeviceMode(r,t):this._renderCircuitMode(r,t)}_renderPanelMode(t){const e=this._config,i=this._createHeader(n("sidepanel.graph_settings"),n("sidepanel.global_defaults"));t.appendChild(i);const r=document.createElement("div");r.className="panel-body";const s=e.graphSettings,l=e.topology,c=s?.global_horizon??o,d=s?.circuits??{};r.appendChild(this._buildListColumnsSection());const u=document.createElement("div");u.className="section";const h=document.createElement("div");h.className="section-label",h.textContent=n("sidepanel.graph_horizon"),u.appendChild(h);const p=document.createElement("div");p.className="field-row";const f=document.createElement("span");f.className="field-label",f.textContent=n("sidepanel.global_default"),p.appendChild(f);const g=document.createElement("select");for(const t of Object.keys(a)){const e=document.createElement("option");e.value=t;const i=`horizon.${t}`,r=n(i);e.textContent=r!==i?r:t,t===c&&(e.selected=!0),g.appendChild(e)}if(g.addEventListener("change",()=>{const t={horizon:g.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_graph_time_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})}),p.appendChild(g),u.appendChild(p),r.appendChild(u),l?.circuits){const t=document.createElement("div");t.className="section";const i=document.createElement("div");i.className="section-label",i.textContent=n("sidepanel.circuit_scales"),t.appendChild(i);const o=Object.entries(l.circuits).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[n,i]of o){const r=this._buildPanelModeCircuitRow(n,i,d[n],c,e.configEntryId??null,e.showFavorites??!1,e.favoritePanelDeviceId,e.favoriteCircuitUuids);t.appendChild(r)}r.appendChild(t)}const m=s?.sub_devices??{};if(l?.sub_devices){const t=document.createElement("div");t.className="section";const i=document.createElement("div");i.className="section-label",i.textContent=n("sidepanel.subdevice_scales"),t.appendChild(i);const o=Object.entries(l.sub_devices).sort(([,t],[,e])=>(t.name||"").localeCompare(e.name||""));for(const[i,r]of o){const o=En(r).length>0,s=e.showFavorites&&e.favoritePanelDeviceId?this._buildSubDeviceFavoriteHeart(r.entities,e.favoriteSubDeviceIds?.has(i)??!1):null;if(!o&&!s)continue;const l=document.createElement("div");l.className="field-row";const d=document.createElement("span");if(d.className="field-label",d.textContent=r.name||i,d.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",l.appendChild(d),s&&l.appendChild(s),!o){t.appendChild(l);continue}const u=m[i]||{horizon:c,has_override:!1},h=u.has_override?u.horizon:c,p=document.createElement("select");p.dataset.subdevId=i;for(const t of Object.keys(a)){const e=document.createElement("option");e.value=t;const i=`horizon.${t}`,r=n(i);e.textContent=r!==i?r:t,t===h&&(e.selected=!0),p.appendChild(e)}if(p.addEventListener("change",()=>{this._debounce(`subdev-${e.configEntryId??""}-${i}`,500,()=>{const t={subdevice_id:i,horizon:p.value};e.configEntryId&&(t.config_entry_id=e.configEntryId),this._callDomainService("set_subdevice_graph_horizon",t).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})})}),l.appendChild(p),u.has_override){const t=document.createElement("button");t.textContent="↺",t.title=n("sidepanel.reset_to_global"),Object.assign(t.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),t.addEventListener("click",()=>{const r={subdevice_id:i};e.configEntryId&&(r.config_entry_id=e.configEntryId),this._callDomainService("clear_subdevice_graph_horizon",r).then(()=>{p.value=c,t.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})}),l.appendChild(t)}t.appendChild(l)}t.children.length>1&&r.appendChild(t)}t.appendChild(r)}_buildPanelModeCircuitRow(t,e,i,r,o,s,l,c){const d=document.createElement("div");d.className="field-row";const u=document.createElement("span");if(u.className="field-label",u.textContent=e.name||t,u.style.cssText="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:1;",d.appendChild(u),s&&l){const n=this._buildFavoriteHeart(e.entities,c?.has(t)??!1);n&&d.appendChild(n)}const h=i||{horizon:r,has_override:!1},p=h.has_override?h.horizon:r,f=document.createElement("select");f.dataset.uuid=t;for(const t of Object.keys(a)){const e=document.createElement("option");e.value=t;const i=`horizon.${t}`,r=n(i);e.textContent=r!==i?r:t,t===p&&(e.selected=!0),f.appendChild(e)}if(f.addEventListener("change",()=>{this._debounce(`circuit-${o??""}-${t}`,500,()=>{const e={circuit_id:t,horizon:f.value};o&&(e.config_entry_id=o),this._callDomainService("set_circuit_graph_horizon",e).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})})}),d.appendChild(f),h.has_override){const e=document.createElement("button");e.textContent="↺",e.title=n("sidepanel.reset_to_global"),Object.assign(e.style,{background:"none",border:"1px solid var(--divider-color, #e0e0e0)",color:"var(--primary-text-color)",borderRadius:"4px",padding:"3px 6px",cursor:"pointer",marginLeft:"4px",fontSize:"0.85em"}),e.addEventListener("click",()=>{const i={circuit_id:t};o&&(i.config_entry_id=o),this._callDomainService("clear_circuit_graph_horizon",i).then(()=>{f.value=r,e.remove(),this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})}),d.appendChild(e)}return d}_renderFavoritesMode(t){const e=this._config,i=this._createHeader(n("sidepanel.graph_settings"),n("sidepanel.favorites_subtitle"));t.appendChild(i);const r=document.createElement("div");r.className="panel-body",r.appendChild(this._buildListColumnsSection());for(const t of e.perPanelSections)r.appendChild(this._buildFavoritesPanelSection(t));t.appendChild(r)}_buildFavoritesPanelSection(t){const e=document.createElement("div");e.className="section";const n=document.createElement("div");n.className="section-label",n.textContent=t.panelName,e.appendChild(n);const i=t.graphSettings?.global_horizon??o,r=t.graphSettings?.circuits??{},a=function(t){const e=t.circuits??{};return Object.entries(e).map(([t,e])=>({uuid:t,circuit:e})).sort((t,e)=>(t.circuit.name||"").localeCompare(e.circuit.name||""))}(t.topology);for(const{uuid:n,circuit:o}of a){const a=this._buildPanelModeCircuitRow(n,o,r[n],i,t.configEntryId,!0,t.panelDeviceId,t.favoriteCircuitUuids);e.appendChild(a)}return e}_renderCircuitMode(t,e){const n=this._createHeader(e.name,this._circuitSubtitle(e));t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),this._renderRelaySection(i,e),e.showFavorites&&this._renderFavoriteSection(i,e),this._renderSheddingSection(i,e),this._placeControlNote(i),this._renderGraphHorizonSection(i,e),e.showMonitoring&&this._renderMonitoringSection(i,e)}_placeControlNote(t){t.querySelector('[data-role="controls-note"]')?.remove();const e=[...t.querySelectorAll('[data-role="relay-toggle"], [data-role="shedding-select"]')];e[0]?.closest(".section")?.insertAdjacentHTML("beforeend",_n(this._controlAccess));const n=t.querySelector('[data-role="controls-note"]');n&&(n.id=li);for(const t of e)n?t.setAttribute("aria-describedby",li):t.removeAttribute("aria-describedby")}refreshControlAccess(t){const e=this._config,n=this.shadowRoot;if(!e||!n||!this.hasAttribute("open")||e.panelMode||e.subDeviceMode||e.favoritesMode)return;const i=this._controlAccess;i.mayOperate===t.mayOperate&&i.reason===t.reason||(this._controlAccess=t,this._updateLiveState(),this._placeControlNote(n))}_circuitSubtitle(t){const e=t.members.map(t=>t.circuit),n=[...new Set(e.flatMap(t=>t.voltage?[t.voltage]:[]))].sort((t,e)=>t-e);return[Me(e),e.length>1&&t.capacityA?i("sidepanel.capacity",{amps:String(t.capacityA)}):"",n.length>0?`${n.join("/")}V`:"",`Tabs [${Se(e).join(",")}]`].filter(Boolean).join(" · ")}_favoriteEntityId(t){return t?.current??t?.power??null}_buildSubDeviceFavoriteHeart(t,e){const n=Nn(t);return n?this._buildHeartButton(n,e):null}_buildListColumnsSection(){const t=document.createElement("div");t.className="section";const e=document.createElement("div");e.className="section-label",e.textContent=n("sidepanel.list_view_columns"),t.appendChild(e);const i=document.createElement("div");i.className="field-row";const r=document.createElement("span");r.className="field-label",r.textContent=n("sidepanel.columns"),i.appendChild(r);const o=Vt(),a=document.createElement("div");a.className="unit-toggle";for(const t of[1,2,3]){const e=document.createElement("button");e.type="button",e.className="unit-btn"+(t===o?" unit-active":""),e.dataset.columns=String(t),e.textContent=String(t),e.addEventListener("click",()=>{jt(t);for(const t of a.querySelectorAll(".unit-btn"))t.classList.toggle("unit-active",t===e);this.dispatchEvent(new CustomEvent("list-columns-changed",{detail:t,bubbles:!0,composed:!0}))}),a.appendChild(e)}return i.appendChild(a),t.appendChild(i),t}_buildFavoriteHeart(t,e){const n=this._favoriteEntityId(t);return n?this._buildHeartButton(n,e):(console.warn("SPAN Panel: circuit has no current/power sensor; favorite heart suppressed"),null)}_buildHeartButton(t,e){const i=document.createElement("button");i.type="button",i.className=e?"fav-heart active":"fav-heart",i.dataset.role="fav-heart",i.title=n("sidepanel.save_to_favorites"),i.setAttribute("role","switch"),i.setAttribute("aria-checked",String(e)),i.setAttribute("aria-label",n("sidepanel.save_to_favorites"));const r=document.createElement("span-icon");return r.setAttribute("icon",e?"mdi:heart":"mdi:heart-outline"),i.appendChild(r),i.addEventListener("click",e=>{e.stopPropagation(),this._toggleFavoriteEntity(i,r,t).catch(()=>{})}),i}async _toggleFavoriteEntity(t,e,i){if(!this._hass)return;const r=t.classList.contains("active"),o=!r;t.classList.toggle("active",o),e.setAttribute("icon",o?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(o));try{o?await async function(t,e){const n=await bn(t,"add_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(yn)),n?.favorites??{}}(this._hass,i):await async function(t,e){const n=await bn(t,"remove_favorite",{entity_id:e});return document.dispatchEvent(new CustomEvent(yn)),n?.favorites??{}}(this._hass,i)}catch(i){throw t.classList.toggle("active",r),e.setAttribute("icon",r?"mdi:heart":"mdi:heart-outline"),t.setAttribute("aria-checked",String(r)),console.warn("SPAN Panel: favorite toggle failed",i),this.errorStore?.add({key:"service:favorites",level:"error",message:n("error.favorites_toggle_failed"),persistent:!1}),i}}_renderFavoriteSection(t,e){const n=this._favoriteEntityId(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_appendFavoriteHeartSection(t,e,i){const r=document.createElement("div");r.className="section",r.innerHTML=``;const o=document.createElement("div");o.className="field-row";const a=document.createElement("span");a.className="field-label",a.textContent=n("sidepanel.save_to_favorites"),o.appendChild(a),o.appendChild(this._buildHeartButton(e,i)),r.appendChild(o),t.appendChild(r)}_renderSubDeviceMode(t,e){const n=this._createHeader(e.name,e.deviceType);t.appendChild(n);const i=document.createElement("div");i.className="panel-body",t.appendChild(i),e.showFavorites&&this._renderSubDeviceFavoriteSection(i,e),e.hasChart&&this._renderSubDeviceHorizonSection(i,e)}_renderSubDeviceFavoriteSection(t,e){const n=Nn(e.entities);n&&this._appendFavoriteHeartSection(t,n,!0===e.isFavorite)}_renderSubDeviceHorizonSection(t,e){const i=document.createElement("div");i.className="section";const r=document.createElement("div");r.className="section-label",r.textContent=n("sidepanel.graph_horizon"),i.appendChild(r);const s=e.graphHorizonInfo,l=!0===s?.has_override,c=s?.horizon||o,d=s?.globalHorizon||o,u=document.createElement("div");u.className="horizon-bar";const h=[{key:"global",label:n("sidepanel.global")}];for(const t of Object.keys(a))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of u.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===d)}};for(const{key:t,label:i}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=i,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===d),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const i={subdevice_id:e.subDeviceId};e.configEntryId&&(i.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_subdevice_graph_horizon",i).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_subdevice_graph_horizon",{...i,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})}))}),u.appendChild(r)}i.appendChild(u),t.appendChild(i)}_createHeader(t,e){const n=document.createElement("div");n.className="panel-header";const i=document.createElement("div"),r=document.createElement("div");if(r.className="title",r.textContent=t,i.appendChild(r),e){const t=document.createElement("div");t.className="subtitle",t.textContent=e,i.appendChild(t)}const o=document.createElement("button");return o.className="close-btn",o.innerHTML="✕",o.addEventListener("click",()=>this.close()),n.appendChild(i),n.appendChild(o),n}_renderRelaySection(t,e){if(!this._hass||"none"===ei(e,this._hass))return;const i=document.createElement("div");i.className="section",i.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=ai,o.textContent=n("sidepanel.breaker");const a=document.createElement("span-switch");a.dataset.role="relay-toggle",a.setAttribute("aria-labelledby",ai);const s=e.entities.switch;this._applyRelayToggle(a,e),a.addEventListener("change",()=>{const t=this._hass;t&&s&&"operable"===ei(e,t)&&pn(t,this._controlAccess).setRelay(s,a.checked).catch(n=>{mn(t,this.errorStore,n,"relay"),this._applyRelayToggle(a,e)})}),r.appendChild(o),r.appendChild(a),i.appendChild(r),t.appendChild(i)}_renderSheddingSection(t,e){if(!e.entities?.select)return;const i=document.createElement("div");i.className="section",i.innerHTML=``;const r=document.createElement("div");r.className="field-row";const o=document.createElement("span");o.className="field-label",o.id=si,o.textContent=n("sidepanel.priority_label");const a=document.createElement("select");a.dataset.role="shedding-select",a.setAttribute("aria-labelledby",si);const s=e.entities.select;for(const t of g){const e=f[t];if(!e)continue;const i=document.createElement("option");i.value=t,i.textContent=n(`shedding.select.${t}`)||e.label(),a.appendChild(i)}a.addEventListener("change",()=>{const t=this._hass;t&&pn(t,this._controlAccess).setPriority(s,a.value).catch(n=>{mn(t,this.errorStore,n,"priority"),this._applySheddingSelect(a,e)})}),r.appendChild(o),r.appendChild(a),i.appendChild(r),t.appendChild(i),this._applySheddingSelect(a,e)}get ratingsView(){const t=this._config;return!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!t.showMonitoring?null:{members:t.members??[],monitoringInfo:t.monitoringInfo,offered:!0===t.monitoringRatingOffered}}setPackageRatings(t,e){return qe(this._hass).setCircuitPackageRatings(this._ratingsPayload(t,{package_ratings_a:[...e]}))}clearPackageRatings(t){return qe(this._hass).clearCircuitPackageRatings(this._ratingsPayload(t,{}))}reportRatingsFailure(t){_e(this._hass,this.errorStore,t)}async useGlobalThresholds(){const t=this._config,e=this.shadowRoot;if(!t||!e||t.panelMode||t.subDeviceMode||t.favoritesMode)return!1;const n=e.querySelector('input[name="monitoring-mode"][value="global"]'),i=e.querySelector('input[name="monitoring-mode"][value="custom"]'),r=e.querySelector('[data-role="threshold-fields"]');n&&(n.checked=!0),r&&(r.style.display="none"),this._thresholdReads+=1;const o={circuit_id:t.entities?.power||t.uuid};t.configEntryId&&(o.config_entry_id=t.configEntryId);try{await qe(this._hass).clearCircuitThreshold(o)}catch(e){return Ue(this.errorStore,e,"monitoring update"),this._config===t&&(i&&(i.checked=!0),r&&(r.style.display="block")),!1}const a=this._config===t?t.monitoringGlobals??null:null;return this._monitoringChanged(t.uuid,{has_override:!1,continuous_threshold_pct:a?.continuous_threshold_pct,spike_threshold_pct:a?.spike_threshold_pct}),!0}async turnOffMonitoring(){const t=this._config;return!(!t||t.panelMode||t.subDeviceMode||t.favoritesMode)&&this._sendMonitoringEnabled(t,!1)}focusAfterRatingsEditor(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"]:checked')??t?.querySelector('input[name="monitoring-mode"]');e?.focus()}_ratingsPayload(t,e){const n={circuit_id:t,...e},i=this._config,r=!i||i.panelMode||i.subDeviceMode||i.favoritesMode?null:i.configEntryId;return r&&(n.config_entry_id=r),n}_monitoringChanged(t,e){const n=this._openCircuitConfig(t);n&&(this._config={...n,monitoringInfo:{...n.monitoringInfo??{},...e}},this._syncMonitoring())}_monitoringAnswered(t,e,n){const i=this._openCircuitConfig(t);i&&(this._config={...i,monitoringInfo:e,monitoringGlobals:n},this._monitoringStoredAs(t,e),!0!==e.has_override&&this._showGlobalChoice(),this._syncMonitoring())}_monitoringStoredAs(t,e){const n=this._storedMonitoring;e&&n?.uuid===t&&n.answered(Wt(e))}_showStoredMonitoring(t){if(!t||t!==this._storedMonitoring||!t.settled)return;const e=this.shadowRoot?.querySelector('[data-role="monitoring-toggle"]')?.hasAttribute("checked");e!==t.on&&this._showMonitoringEnabled(t.uuid,t.on)}_showGlobalChoice(){const t=this.shadowRoot,e=t?.querySelector('input[name="monitoring-mode"][value="global"]'),n=t?.querySelector('[data-role="threshold-fields"]');e&&n&&!e.checked&&!this._limitFields.some(t=>t.dirty)&&(e.checked=!0,le(n)&&e.focus(),n.style.display="none")}_openCircuitConfig(t){const e=this._config;return!e||e.panelMode||e.subDeviceMode||e.favoritesMode||e.uuid!==t||!this.hasAttribute("open")?null:e}_syncMonitoring(){const t=this._config,e=this.shadowRoot?.querySelector('[data-role="judged-against"]');if(!t||t.panelMode||t.subDeviceMode||t.favoritesMode||!e)return;const n=this._judgedAgainstText(t.monitoringInfo);e.textContent!==n&&(e.textContent=n),this._ratingsEditor.sync(e),this._lockMonitoringIfReadOnly()}_renderGraphHorizonSection(t,e){const i=document.createElement("div");i.className="section",i.dataset.role="horizon-section";const r=document.createElement("div");r.className="section-label",r.textContent=n("sidepanel.graph_horizon"),i.appendChild(r);const s=e.graphHorizonInfo,l=!0===s?.has_override,c=s?.horizon||o,d=s?.globalHorizon||o,u=document.createElement("div");u.className="horizon-bar";const h=[{key:"global",label:n("sidepanel.global")}];for(const t of Object.keys(a))h.push({key:t,label:t});const p=l?c:"global",f=t=>{for(const e of u.querySelectorAll(".horizon-segment")){const n=e.dataset.horizon;e.classList.toggle("active",n===t),e.classList.toggle("referenced","global"===t&&n===d)}};for(const{key:t,label:i}of h){const r=document.createElement("button");r.type="button",r.className="horizon-segment",r.dataset.horizon=t,r.textContent=i,r.classList.toggle("active",t===p),r.classList.toggle("referenced","global"===p&&t===d),r.addEventListener("click",()=>{if(r.classList.contains("active"))return;const i={circuit_id:e.uuid};e.configEntryId&&(i.config_entry_id=e.configEntryId),"global"===t?(f("global"),this._callDomainService("clear_circuit_graph_horizon",i).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})})):(f(t),this._callDomainService("set_circuit_graph_horizon",{...i,horizon:t}).then(()=>{this.dispatchEvent(new CustomEvent("graph-settings-changed",{bubbles:!0,composed:!0}))}).catch(t=>{console.warn("SPAN Panel: graph horizon service failed",t),this.errorStore?.add({key:"service:graph_horizon",level:"error",message:n("error.graph_horizon_failed"),persistent:!1})}))}),u.appendChild(r)}i.appendChild(u),t.appendChild(i)}_judgedAgainstText(t){return function(t){return t.amps?t.userSet?i("monitoringRating.judged_copied",{rating:String(t.amps),copied:Zt(t)}):i("sidepanel.judged_against",{rating:`${t.amps} A`}):i("sidepanel.judged_against",{rating:n("monitoringRating.none")})}(Yt(t))}_renderMonitoringSection(t,e){const i=document.createElement("div");i.className="section",i.dataset.role="monitoring-section";const r=document.createElement("div");r.className="monitoring-header";const o=document.createElement("div");o.className="section-label",o.textContent=n("sidepanel.monitoring"),o.style.margin="0";const a=document.createElement("span-switch");a.dataset.role="monitoring-toggle";const s=e.monitoringInfo,l=Wt(s);l&&a.setAttribute("checked",""),r.appendChild(o),r.appendChild(a),i.appendChild(r),Be(this._hass)||i.appendChild(Ze());const c=document.createElement("div");c.dataset.role="monitoring-details",c.style.display=l?"block":"none",i.appendChild(c);const d=!0===s?.has_override,u=document.createElement("div");u.className="field-label",u.dataset.role="judged-against",u.setAttribute("aria-live","polite"),u.style.marginBottom="8px",u.textContent=this._judgedAgainstText(s),c.appendChild(u),this._ratingsEditor.mount(u);const h=document.createElement("div");h.className="radio-group",h.innerHTML=`\n \n \n `,c.appendChild(h),this._limitFields=[];const p=document.createElement("div");p.dataset.role="threshold-fields",p.style.display=d?"block":"none";const f=s?.continuous_threshold_pct??80,g=s?.spike_threshold_pct??100,m=s?.window_duration_m??15,v=s?.cooldown_duration_m??15;p.appendChild(this._createLimitRow(n("sidepanel.continuous_pct"),"continuous",f,null,e)),p.appendChild(this._createLimitRow(n("sidepanel.spike_pct"),"spike",g,null,e)),p.appendChild(this._createLimitRow(n("sidepanel.window_duration"),"window-m",m,"m",e)),p.appendChild(this._createLimitRow(n("sidepanel.cooldown"),"cooldown-m",v,"m",e)),c.appendChild(p),a.addEventListener("change",()=>{const t=a.checked;this._showMonitoringEnabled(e.uuid,t),this._sendMonitoringEnabled(e,t)});const _=h.querySelectorAll('input[type="radio"]');for(const t of _)t.addEventListener("change",()=>{t.checked&&("custom"===t.value?p.style.display="block":this.useGlobalThresholds())});t.appendChild(i),this._lockMonitoringIfReadOnly()}_lockMonitoringIfReadOnly(){const t=this.shadowRoot?.querySelector('[data-role="monitoring-section"]');t&&!Be(this._hass)&&Ye(t)}async _sendMonitoringEnabled(t,e){const n={circuit_id:t.entities?.power||t.uuid,monitoring_enabled:e};t.configEntryId&&(n.config_entry_id=t.configEntryId);const i=async()=>{try{return await qe(this._hass).setCircuitThreshold(n),!0}catch(t){return Ue(this.errorStore,t,"monitoring update"),!1}},r=this._storedMonitoring;if(r?.uuid!==t.uuid)return i();const o=await r.send(e,i);return this._showStoredMonitoring(r),o}_showMonitoringEnabled(t,e){const n=this.shadowRoot;if(!this._openCircuitConfig(t)||!n)return;const i=n.querySelector('[data-role="monitoring-toggle"]');i?.toggleAttribute("checked",e);const r=n.querySelector('[data-role="monitoring-details"]');if(r){const t=!e&&le(r);r.style.display=e?"block":"none",t&&i?.focus()}this._monitoringChanged(t,{monitoring_enabled:e})}_createLimitRow(t,e,n,i,r){const o=oi[e],{min:a,max:s}=he[o],l=document.createElement("div");l.className="field-row limit-row";const c=document.createElement("span");c.className="field-label",c.id=`threshold-label-${e}`,c.textContent=t;const d=document.createElement("div"),u=document.createElement("input");if(u.type="number",u.setAttribute("aria-labelledby",c.id),u.min=String(a),u.max=String(s),u.step="1",u.value=String(n),u.dataset.role=`threshold-${e}`,u.setAttribute("aria-describedby",`threshold-feedback-${e}`),d.appendChild(u),i){const t=document.createElement("span");t.textContent=i,d.appendChild(t)}const h=document.createElement("div");h.className="field-label rating-feedback limit-feedback",h.id=`threshold-feedback-${e}`,h.dataset.role=`threshold-feedback-${e}`,h.setAttribute("aria-live","polite");const p=me(u,o,{report:t=>{h.textContent=t??""},save:t=>{const e={circuit_id:r.entities?.power||r.uuid,[o]:t};r.configEntryId&&(e.config_entry_id=r.configEntryId),this._saveThresholds(r,e)}});return this._limitFields.push(p),l.append(c,d,h),l}_saveThresholds(t,e){qe(this._hass).setCircuitThreshold(e).then(()=>this._readThresholds(t,e),t=>Ue(this.errorStore,t,"monitoring update"))}_updateLiveState(){if(!this._config||this._config.panelMode)return;const t=this._config;if(!t.subDeviceMode&&!t.favoritesMode){if(t.entities?.switch){const e=this.shadowRoot?.querySelector('[data-role="relay-toggle"]');e&&this._applyRelayToggle(e,t)}if(t.entities?.select){const e=this.shadowRoot?.querySelector('[data-role="shedding-select"]');e&&this._applySheddingSelect(e,t)}}}_applyRelayToggle(t,e){if(!this._hass)return;const n=this._controlAccess;t.disabled=!n.mayOperate||"operable"!==ei(e,this._hass),vn(t,n),ti(e,this._hass)?t.setAttribute("checked",""):t.removeAttribute("checked")}_applySheddingSelect(t,e){if(!this._hass)return;const n=this._controlAccess,i=ri(e,this._hass);g.includes(i)?t.value=i:t.selectedIndex=-1,t.disabled=!n.mayOperate||!function(t,e){const n=ii(t,e);return void 0!==n&&Zn.has(n)}(e,this._hass),vn(t,n)}async _readThresholds(t,e){const n=++this._thresholdReads;let i=null;try{i=await this._readMonitoringStatus(t.configEntryId??null)}catch(t){console.warn("SPAN Panel: monitoring status read failed",t)}if(n!==this._thresholdReads)return;const r=ze(i,t);if(r)return void this._monitoringAnswered(t.uuid,r,i?.global_settings??null);const o={has_override:!0};"number"==typeof e.continuous_threshold_pct&&(o.continuous_threshold_pct=e.continuous_threshold_pct),"number"==typeof e.spike_threshold_pct&&(o.spike_threshold_pct=e.spike_threshold_pct),this._monitoringChanged(t.uuid,o)}async _readMonitoringStatus(t){if(!this._hass)return null;const e=await this._hass.callWS({type:"call_service",domain:s,service:"get_monitoring_status",service_data:t?{config_entry_id:t}:{},return_response:!0});return Le(e?.response)}_callDomainService(t,e){return this._hass?this._hass.callWS({type:"call_service",domain:s,service:t,service_data:e}):Promise.resolve()}_debounce(t,e,n){this._debounceTimers[t]&&clearTimeout(this._debounceTimers[t]),this._debounceTimers[t]=setTimeout(()=>{delete this._debounceTimers[t],n()},e)}}try{customElements.get("span-side-panel")||customElements.define("span-side-panel",di)}catch{}class ui extends At{constructor(){super(...arguments),this._store=null,this._unsub=null,this._errors=[]}set store(t){if(this._store===t)return;this._unsub?.(),this._unsub=null,this._store=t,this._errors=t.active;const e=t;this._unsub=t.subscribe(()=>{this._errors=e.active})}connectedCallback(){if(super.connectedCallback(),this._store&&!this._unsub){const t=this._store;this._errors=t.active,this._unsub=t.subscribe(()=>{this._errors=t.active})}}disconnectedCallback(){super.disconnectedCallback(),this._unsub?.(),this._unsub=null}render(){return 0===this._errors.length?ht:ct`${this._errors.map(t=>ct` - `)}`}_iconForLevel(t){switch(t){case"error":return"mdi:alert-circle";case"warning":return"mdi:alert";default:return"mdi:information"}}}An.styles=k` + `)}`}_iconForLevel(t){switch(t){case"error":return"mdi:alert-circle";case"warning":return"mdi:alert";default:return"mdi:information"}}}ui.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()],An.prototype,"_errors",void 0);try{customElements.get("span-error-banner")||customElements.define("span-error-banner",An)}catch{}var In="M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z";const Pn=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":In,"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"}),Dn=new Set;class Ln extends At{constructor(){super(...arguments),this.icon=""}render(){if(!this.icon)return ht;const t=Pn[this.icon];return t?ct``:(e=this.icon,Dn.has(e)||(Dn.add(e),console.warn(`SPAN: unknown icon "${e}". Add it to MDI_PATHS in span-icon.ts.`)),ht);var e}}Ln.styles=k` + `,_([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` :host { display: inline-flex; align-items: center; @@ -119,19 +119,22 @@ const Pt={attribute:!0,type:String,converter:$,reflect:!1,hasChanged:H},Dt=(t=Pt display: block; fill: currentColor; } - `,_([Lt({type:String})],Ln.prototype,"icon",void 0);try{customElements.get("span-icon")||customElements.define("span-icon",Ln)}catch{}class En extends At{constructor(){super(...arguments),this.checked=!1,this.disabled=!1,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.hasAttribute("tabindex")||this.setAttribute("tabindex","0"),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))}render(){return ct` + `,_([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`
- `}}En.styles=k` + `}}mi.styles=k` :host { - --span-switch-on: var(--switch-checked-color, var(--primary-color, #4dd9af)); - --span-switch-off: var(--switch-unchecked-track-color, rgba(120, 120, 120, 0.45)); - --span-switch-thumb-on: var(--switch-checked-button-color, #fff); - --span-switch-thumb-off: var(--switch-unchecked-button-color, #fafafa); --span-switch-track-w: 36px; --span-switch-track-h: 20px; --span-switch-thumb: 14px; + --span-switch-border: 1px; + /* The thumb's gap to the inside of the track's border, the same on every side. */ + --span-switch-inset: calc((var(--span-switch-track-h) - 2 * var(--span-switch-border) - var(--span-switch-thumb)) / 2); + --span-switch-track-color: var(--ha-switch-background-color, var(--ha-color-fill-disabled-quiet-resting, rgba(120, 120, 120, 0.45))); + --span-switch-track-border-color: var(--ha-switch-border-color, var(--ha-color-border-neutral-normal, transparent)); + --span-switch-thumb-color: var(--ha-switch-thumb-background-color, var(--ha-color-on-neutral-normal, #fafafa)); + --span-switch-thumb-border-color: var(--ha-switch-thumb-border-color, var(--ha-color-on-neutral-normal, transparent)); display: inline-flex; align-items: center; vertical-align: middle; @@ -139,48 +142,94 @@ const Pt={attribute:!0,type:String,converter:$,reflect:!1,hasChanged:H},Dt=(t=Pt user-select: none; -webkit-tap-highlight-color: transparent; } + :host(:not([checked]):not([disabled]):hover), + :host(:not([checked]):not([disabled]):focus-visible) { + --span-switch-track-color: var( + --ha-switch-background-color-hover, + var(--ha-switch-background-color, var(--ha-color-fill-disabled-quiet-hover, rgba(120, 120, 120, 0.45))) + ); + --span-switch-thumb-color: var( + --ha-switch-thumb-background-color-hover, + var(--ha-switch-thumb-background-color, var(--ha-color-on-neutral-normal, #fafafa)) + ); + --span-switch-thumb-border-color: var( + --ha-switch-thumb-border-color-hover, + var(--ha-switch-thumb-border-color, var(--ha-color-on-neutral-normal, transparent)) + ); + } + :host([checked]) { + --span-switch-track-color: var(--ha-switch-checked-background-color, var(--ha-color-fill-primary-normal-resting, var(--primary-color, #4dd9af))); + --span-switch-track-border-color: var(--ha-switch-checked-border-color, var(--ha-color-border-primary-loud, transparent)); + --span-switch-thumb-color: var(--ha-switch-checked-thumb-background-color, var(--ha-color-on-primary-normal, #fff)); + --span-switch-thumb-border-color: var(--ha-switch-checked-thumb-border-color, var(--ha-color-on-primary-normal, transparent)); + } + :host([checked]:not([disabled]):hover), + :host([checked]:not([disabled]):focus-visible) { + --span-switch-track-color: var( + --ha-switch-checked-background-color-hover, + var(--ha-switch-checked-background-color, var(--ha-color-fill-primary-normal-hover, var(--primary-color, #4dd9af))) + ); + --span-switch-track-border-color: var( + --ha-switch-checked-border-color-hover, + var(--ha-switch-checked-border-color, var(--ha-color-border-primary-loud, transparent)) + ); + --span-switch-thumb-color: var( + --ha-switch-checked-thumb-background-color-hover, + var(--ha-switch-checked-thumb-background-color, var(--ha-color-on-primary-normal, #fff)) + ); + --span-switch-thumb-border-color: var( + --ha-switch-checked-thumb-border-color-hover, + var(--ha-switch-checked-thumb-border-color, var(--ha-color-on-primary-normal, transparent)) + ); + } :host([disabled]) { cursor: not-allowed; - opacity: 0.5; } .track { position: relative; + box-sizing: border-box; width: var(--span-switch-track-w); height: var(--span-switch-track-h); + border: var(--span-switch-border) solid var(--span-switch-track-border-color); border-radius: calc(var(--span-switch-track-h) / 2); - background: var(--span-switch-off); - transition: background 0.2s ease; + background: var(--span-switch-track-color); + transition: + background 0.2s ease, + border-color 0.2s ease; + } + :host([disabled]) .track { + opacity: var(--ha-switch-disabled-opacity, 0.3); } .thumb { position: absolute; top: 50%; - left: 3px; + left: var(--span-switch-inset); + box-sizing: border-box; width: var(--span-switch-thumb); height: var(--span-switch-thumb); + border: var(--span-switch-border) solid var(--span-switch-thumb-border-color); border-radius: 50%; - background: var(--span-switch-thumb-off); - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.35); + background: var(--span-switch-thumb-color); + box-shadow: var(--ha-switch-thumb-box-shadow, var(--ha-box-shadow-s, 0 1px 3px rgba(0, 0, 0, 0.35))); transform: translateY(-50%); transition: left 0.2s ease, - background 0.2s ease; - } - :host([checked]) .track { - background: var(--span-switch-on); + background 0.2s ease, + border-color 0.2s ease; } :host([checked]) .thumb { - left: calc(var(--span-switch-track-w) - var(--span-switch-thumb) - 3px); - background: var(--span-switch-thumb-on); + left: calc(var(--span-switch-track-w) - 2 * var(--span-switch-border) - var(--span-switch-inset) - var(--span-switch-thumb)); } - :host(:focus-visible) .track { - outline: 2px solid var(--span-switch-on); - outline-offset: 2px; + /* 's focus ring, which it draws on an enabled switch only: Home Assistant declares it on the document, so it reaches this shadow root, and re-declares it on a themed element. */ + :host(:focus-visible:not([disabled])) .track { + 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})],En.prototype,"checked",void 0),_([Lt({type:Boolean,reflect:!0})],En.prototype,"disabled",void 0);try{customElements.get("span-switch")||customElements.define("span-switch",En)}catch{}class Rn 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})],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` - `}}Rn.styles=k` + `}}vi.styles=k` :host { display: none; align-items: center; @@ -214,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})],Rn.prototype,"narrow",void 0);try{customElements.get("span-menu-button")||customElements.define("span-menu-button",Rn)}catch{}const Nn=["entity_registry_updated","area_registry_updated","device_registry_updated"];async function zn(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)}}function On(t){return(t.identifiers??[]).some(t=>t[0]===s)&&!t.via_device_id&&!t.parent_device_id}function $n(t){return(t.name_by_user||t.name||"").trim()}async function Hn(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=rn(o.panel_size)?o.panel_size:function(t){let e=0;for(const n of Object.values(t))if(n&&!on(n))for(const t of n.tabs)t>e&&(e=t);return e>0?e+e%2:0}(o.circuits);if(!an(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),d=o.panel_device_id??e,u=c.find(t=>t.id===d)??null;return function(t,e){const n=new Map(e.map(t=>[t.id,t]));for(const e of Object.values(t)){const t=e.device_id?n.get(e.device_id):void 0,i=t?$n(t):"";i&&(e.name=i)}}(o.circuits,c),await zn(t,o),{topology:o,panelDevice:u,panelSize:a}}const Fn=h.power,Bn=h.current,Vn="--",jn=`${Vn}`;function Wn(t){return Fn.unit(t)}function qn(t){return(t<0?"-":"")+Fn.format(t)}function Un(t){return null===t?jn:`${qn(t)} ${Wn(t)}`}function Gn(t){return null===t?jn:`${qn(t)}${Wn(t)}`}function Xn(t){return null===t?jn:`${Bn.format(t)}A`}function Yn(){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 Zn(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 ${Vn}\n ${r?"A":"kW"}\n
\n
`:""}\n ${a?`\n
\n ${n("header.grid")}\n
\n ${Vn}\n
\n
`:""}\n ${s?`\n
\n ${n("header.upstream")}\n
\n ${Vn}\n ${r?"A":"kW"}\n
\n
`:""}\n ${l?`\n
\n ${n("header.downstream")}\n
\n ${Vn}\n ${r?"A":"kW"}\n
\n
`:""}\n ${c?`\n
\n ${n("header.solar")}\n
\n ${Vn}\n ${r?"A":"kW"}\n
\n
`:""}\n ${d?`\n
\n ${n("header.battery")}\n
\n ${Vn}\n %\n
\n
`:""}\n
\n `}function Kn(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?`
\n ${Ft(n("header.enable_switches"))}\n
\n \n
\n
`:""}\n
\n ${Zn(t,e)}\n
\n
\n
\n ${a}\n
\n \n \n
\n
\n ${Yn()}\n
\n
\n `}function Qn(t){const e=t.chart_metric??r;return h[e]??h[r]}function Jn(t,e){const n=function(t){return Qn(t).entityRole}(e);return t.entities?.[n]??t.entities?.power??null}function ti(t,e,i=!1){if("none"===e)return"";const r=["toggle-pill",t?"toggle-on":"toggle-off"];"inert"===e&&r.push("toggle-unavailable"),i&&r.push("toggle-shared");const o=i?` title="${Ft(n("grid.shared_switch"))}"`:"";return`
\n ${n(t?"grid.on":"grid.off")}\n \n
`}function ei(t,e,i){const r=t.querySelector(".toggle-pill");if(!r)return;r.classList.toggle("toggle-on",e),r.classList.toggle("toggle-off",!e),r.classList.toggle("toggle-unavailable","operable"!==i);const o=r.querySelector(".toggle-label");o&&(o.textContent=n(e?"grid.on":"grid.off"))}function ni(t){return"unknown"===t?void 0:f[t]}const ii="display:none;";function ri(t){const e=ni(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 oi(t,e){const n=t.querySelector(".shedding-composite");if(!n)return;const i=ni(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 ai(t,e,i,r,o,a,s,l,c,d=[e],u=!1){const h=hn(e,a),p=gn(e,h),f=xn(e,a),g=wn(e,a),m=d.length>1,v=we(d),_=Ft(d.map(t=>t.name||n("grid.unknown")).join(" · ")),y="current"===Qn(s).entityRole?Xn(pn(e,a)):Gn(h),b=ri(c||"unknown"),x=``;let w="";const S=mn(e,a,l);null!==S&&(w=`${Math.round(S)}%`);return`\n
\n
\n
\n ${v?`${v}`:""}\n ${w}\n ${_}\n
\n
\n \n ${y}\n \n ${ti(f,g,m&&function(t){const e=t[0]?.shared_relay_group;return!!e&&t.every(t=>t.shared_relay_group===e)}(d))}\n
\n
\n
\n ${b}\n ${x}\n
\n
\n
\n `}function si(t,e){return`\n
\n —\n
\n `}function li(t){return"function"==typeof globalThis.CSS?.escape?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function ci(t){return Object.entries(t.circuits).filter(([,t])=>on(t))}function di(t,e,n){return`${Ft(function(t){const e=Ze(t);if(null===e)return Vn;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 ui(t,e,i){const r=hn(t,e),o=null===r||0===r?"":n(r>0?"meters.importing":"meters.exporting");return`\n ${"current"===Qn(i).entityRole?Xn(pn(t,e)):Gn(r)}\n ${Ft(o)}\n ${di(e,t.entities?.consumed_energy,n("meters.imported"))}\n ${di(e,t.entities?.produced_energy,n("meters.exported"))}\n `}function hi(t,e,i){if(!function(t,e){return!1!==e.show_panel&&ci(t).length>0}(t,i))return"";const r=ci(t).map(([t,r])=>`\n
\n ${Ft(r.name||n("grid.unknown"))}\n ${ui(r,e,i)}\n
`).join("");return`\n
\n
${Ft(n("meters.title"))}
\n ${r}\n
\n `}function pi(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(!function(t){return"_favoriteRefs"in t}(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=Ke(n),o=n.type===l,a=o?Xe(n):null,s=o?Ye(n):null,c=vi(n,e,i,Qe(n)),d=_i(t,n,o,r.headlineEid,a,s),u=n.solar?gi(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=fi(i),h=o.headlineIsSiteTotal?`${Ft(n("subdevice.site_total"))}`:"",m=o.headlineEid?`${h}${Un(tn(e,o.headlineEid))}`:"",v=nn(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 fi(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 gi(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=tn(i,e.siteTotalEid);r+=`\n
\n ${Ft(n("subdevice.site_total"))}:\n ${Un(t)}\n
`}return"inverter"!==t.role||e.headlineEid||(r+=`
${Ft(n("subdevice.in_site_total"))}
`),r}function mi(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&&$n(r)||e}function vi(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||mi(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=Ze(s);null!==t&&(d=(t/1e3).toFixed(1)+" kWh")}o+=`\n
\n ${Ft(l)}:\n ${Ft(d)}\n
\n `}return o}function _i(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 yi(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 bi(t){const e=a[t];return e?e.ms:a[o].ms}function xi(t){const e=t/1e3;return e<=600?Math.ceil(e):Math.min(5e3,Math.ceil(e/5))}function wi(t){return Math.max(500,Math.floor(t/5e3))}function Si(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 ki(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 Ti(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=xi(i),l=wi(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 Ai(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 Je(i))e.push({entityId:r,key:`${u}${n}_${t}`,devId:n});return e}async function Ii(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=Jn(i,n);if(!e)continue;let o;o=r&&r.has(t)?bi(r.get(t)):yi(n),ki(a,o,e,t)}for(const{entityId:t,key:i,devId:r}of Ai(e)){let e;e=o&&o.has(r)?bi(o.get(r)):yi(n),ki(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(Ti(t,n.entityIds,n.keysByEntity,e,i))}await Promise.all(s)}var Pi=function(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1},Di=new function(){this.browser=new Pi,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?(Di.wxa=!0,Di.touchEventsSupported=!0):"undefined"==typeof document&&"undefined"!=typeof self?Di.worker=!0:!Di.hasGlobalWindow||"Deno"in window||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Node.js")>-1?(Di.node=!0,Di.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,Di);var Li="sans-serif",Ei="12px "+Li;var Ri,Ni,zi=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(){or(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?ro(s,a):ro(a,s))}(a,o,r);if(s)return s(t,n,i),!0}return!1}function lo(t){return"CANVAS"===t.nodeName.toUpperCase()}var co=/([&<>"'])/g,uo={"&":"&","<":"<",">":">",'"':""","'":"'"};function ho(t){return null==t?"":(t+"").replace(co,function(t,e){return uo[e]})}var po=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,fo=[],go=Di.browser.firefox&&+Di.browser.version.split(".")[0]<39;function mo(t,e,n,i){return n=n||{},i?vo(t,e,n):go&&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):vo(t,e,n),n}function vo(t,e,n){if(Di.domSupported&&t.getBoundingClientRect){var i=e.clientX,r=e.clientY;if(lo(t)){var o=t.getBoundingClientRect();return n.zrX=i-o.left,void(n.zrY=r-o.top)}if(so(fo,t,i,r))return n.zrX=fo[0],void(n.zrY=fo[1])}n.zrX=n.zrY=0}function _o(t){return t||window.event}function yo(t,e,n){if(null!=(e=_o(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&&mo(t,r,e,n)}else{mo(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&&po.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function bo(t,e,n,i){t.removeEventListener(e,n,i)}var xo=function(t){t.preventDefault(),t.stopPropagation(),t.cancelBubble=!0},wo=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 ko(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 To(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 Ao(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 Io(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 Po(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 Do=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}(),Lo=Math.min,Eo=Math.max,Ro=Math.abs,No=["x","y"],zo=["width","height"],Oo=new Do,$o=new Do,Ho=new Do,Fo=new Do,Bo=Yo(),Vo=Bo.minTv,jo=Bo.maxTv,Wo=[0,0],qo=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=Lo(t.x,this.x),n=Lo(t.y,this.y);isFinite(this.x)&&isFinite(this.width)?this.width=Eo(t.x+t.width,this.x+this.width)-e:this.width=t.width,isFinite(this.y)&&isFinite(this.height)?this.height=Eo(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 Ao(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]),Ao(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&&Do.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(Uo,e.x,e.y,e.width,e.height)),n instanceof t||(n=t.set(Go,n.x,n.y,n.width,n.height));var s=!!i;Bo.reset(r,s);var l=Bo.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))}Oo.x=Ho.x=n.x,Oo.y=Fo.y=n.y,$o.x=Fo.x=n.x+n.width,$o.y=Ho.y=n.y+n.height,Oo.transform(i),Fo.transform(i),$o.transform(i),Ho.transform(i),e.x=Lo(Oo.x,$o.x,Ho.x,Fo.x),e.y=Lo(Oo.y,$o.y,Ho.y,Fo.y);var l=Eo(Oo.x,$o.x,Ho.x,Fo.x),c=Eo(Oo.y,$o.y,Ho.y,Fo.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Uo=new qo(0,0,0,0),Go=new qo(0,0,0,0);function Xo(t,e,n,i,r,o,a,s){var l=Ro(e-n),c=Ro(i-t),d=Lo(l,c),u=No[r],h=No[1-r],p=zo[r];e=c||!Bo.bidirectional)&&(Vo[u]=-c,Vo[h]=0,Bo.useDir&&Bo.calcDirMTV())))}function Yo(){var t=0,e=new Do,n=new Do,i={minTv:new Do,maxTv:new Do,useDir:!1,dirMinTv:new Do,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(r,o){i.touchThreshold=0,r&&null!=r.touchThreshold&&(i.touchThreshold=Eo(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||(ea.copy(d.getBoundingRect()),d.transform&&ea.applyTransform(d.transform),ea.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=ia(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==Zo)){e.target=a;break}}}function oa(t,e,n){var i=t.painter;return e<0||e>i.getWidth()||n<0||n>i.getHeight()}or(["click","mousedown","mouseup","mousewheel","dblclick","contextmenu"],function(t){na.prototype[t]=function(e){var n,i,r=e.zrX,o=e.zrY,a=oa(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||Xr(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function aa(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 sa(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 la(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 ca(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 da(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=ca(t[d],t,l,c,0,e);l+=h,0!==(c-=h)&&0!==(u=la(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-la(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=aa(t,n,i,e))s&&(l=s),sa(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 ha=!1;function pa(){ha||(ha=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function fa(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var ga,ma=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=fa}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}();ga=Di.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){return setTimeout(t,16)};var va={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-va.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*va.bounceIn(2*t):.5*va.bounceOut(2*t-1)+.5}},_a=Math.pow,ya=Math.sqrt,ba=1e-8,xa=1e-4,wa=ya(3),Sa=1/3,Ca=Br(),ka=Br(),Ma=Br();function Ta(t){return t>-1e-8&&tba||t<-1e-8}function Ia(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 Pa(t,e,n,i,r){var o=1-r;return 3*(((e-t)*o+2*(n-e)*r)*o+(i-n)*r*r)}function Da(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(Ta(d)&&Ta(u)){if(Ta(s))o[0]=0;else(C=-l/s)>=0&&C<=1&&(o[p++]=C)}else{var f=u*u-4*d*h;if(Ta(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=ya(f),_=d*s+1.5*a*(-u+v),y=d*s+1.5*a*(-u-v);(C=(-s-((_=_<0?-_a(-_,Sa):_a(_,Sa))+(y=y<0?-_a(-y,Sa):_a(y,Sa))))/(3*a))>=0&&C<=1&&(o[p++]=C)}else{var b=(2*d*s-3*a*u)/(2*ya(d*d*d)),x=Math.acos(b)/3,w=ya(d),S=Math.cos(x),C=(-s-2*w*S)/(3*a),k=(m=(-s+w*(S+wa*Math.sin(x)))/(3*a),(-s+w*(S-wa*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 La(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(Ta(a)){if(Aa(o))(d=-s/o)>=0&&d<=1&&(r[l++]=d)}else{var c=o*o-4*a*s;if(Ta(c))r[0]=-o/(2*a);else if(c>0){var d,u=ya(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 Ea(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 Ra(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=Ia(t,n,r,a,f),m=Ia(e,i,o,s,f),v=g-c,_=m-d;u+=Math.sqrt(v*v+_*_),c=g,d=m}return u}function Na(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function za(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function Oa(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function $a(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 Ha(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=Na(t,n,r,h),f=Na(e,i,o,h),g=p-s,m=f-l;c+=Math.sqrt(g*g+m*m),s=p,l=f}return c}var Fa=/cubic-bezier\(([0-9,\.e ]+)\)/;function Ba(t){var e=t&&Fa.exec(t);if(e){var n=e[1].split(","),i=+Ir(n[0]),r=+Ir(n[1]),o=+Ir(n[2]),a=+Ir(n[3]);if(isNaN(i+r+o+a))return;var s=[];return function(t){return t<=0?0:t>=1?1:Da(0,i,o,1,t,s)&&Ia(0,r,a,1,s[0])}}}var Va=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||Hr,this.ondestroy=t.ondestroy||Hr,this.onrestart=t.onrestart||Hr,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=pr(t)?t:va[t]||Ba(t)},t}(),ja=function(t){this.value=t},Wa=function(){function t(){this._len=0}return t.prototype.insert=function(t){var e=new ja(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}(),qa=function(){function t(t){this._list=new Wa,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 ja(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}(),Ua={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 Ga(t){return(t=Math.round(t))<0?0:t>255?255:t}function Xa(t){return t<0?0:t>1?1:t}function Ya(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Ga(parseFloat(e)/100*255):Ga(parseInt(e,10))}function Za(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Xa(parseFloat(e)/100):Xa(parseFloat(e))}function Ka(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 Qa(t,e,n){return t+(e-t)*n}function Ja(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function ts(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}var es=new qa(20),ns=null;function is(t,e){ns&&ts(ns,e),ns=es.put(t,ns||e.slice())}function rs(t,e){if(t){e=e||[];var n=es.get(t);if(n)return ts(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in Ua)return ts(e,Ua[i]),is(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?(Ja(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),is(t,e),e):void Ja(e,0,0,0,1):7===o||9===o?(r=parseInt(i.slice(1,7),16))>=0&&r<=16777215?(Ja(e,(16711680&r)>>16,(65280&r)>>8,255&r,9===o?parseInt(i.slice(7),16)/255:1),is(t,e),e):void Ja(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?Ja(e,+c[0],+c[1],+c[2],1):Ja(e,0,0,0,1);d=Za(c.pop());case"rgb":return c.length>=3?(Ja(e,Ya(c[0]),Ya(c[1]),Ya(c[2]),3===c.length?d:Za(c[3])),is(t,e),e):void Ja(e,0,0,0,1);case"hsla":return 4!==c.length?void Ja(e,0,0,0,1):(c[3]=Za(c[3]),os(c,e),is(t,e),e);case"hsl":return 3!==c.length?void Ja(e,0,0,0,1):(os(c,e),is(t,e),e);default:return}}Ja(e,0,0,0,1)}}function os(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=Za(t[1]),r=Za(t[2]),o=r<=.5?r*(i+1):r+i-r*i,a=2*r-o;return Ja(e=e||[],Ga(255*Ka(a,o,n+1/3)),Ga(255*Ka(a,o,n)),Ga(255*Ka(a,o,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function as(t,e){var n=rs(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 ls(n,4===n.length?"rgba":"rgb")}}function ss(t,e,n,i){var r=rs(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]=Za(pr(n)?n(r[1]):n)),null!=i&&(r[2]=Za(pr(i)?i(r[2]):i)),ls(os(r),"rgba")}function ls(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 cs(t,e){var n=rs(t);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*e:0}var ds=new qa(100);function us(t){if(fr(t)){var e=ds.get(t);return e||(e=as(t,-.1),ds.put(t,e)),e}if(xr(t)){var n=tr({},t);return n.colorStops=ar(t.colorStops,function(t){return{offset:t.offset,color:as(t.color,-.1)}}),n}return t}var hs=Math.round;function ps(t){var e;if(t&&"transparent"!==t){if("string"==typeof t&&t.indexOf("rgba")>-1){var n=rs(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 fs=1e-4;function gs(t){return t-1e-4}function ms(t){return hs(1e3*t)/1e3}function vs(t){return hs(1e4*t)/1e4}var _s={left:"start",right:"end",center:"middle",middle:"middle"};function ys(t){return t&&!!t.image}function bs(t){return ys(t)||function(t){return t&&!!t.svgElement}(t)}function xs(t){return"linear"===t.type}function ws(t){return"radial"===t.type}function Ss(t){return t&&("linear"===t.type||"radial"===t.type)}function Cs(t){return"url(#"+t+")"}function ks(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)*Fr,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("+hs(a*Fr)+"deg, "+hs(s*Fr)+"deg)"),l.join(" ")}var Ts=Di.hasGlobalWindow&&pr(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},As=Array.prototype.slice;function Is(t,e,n){return(e-t)*n+t}function Ps(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(rr(e)){var l=function(t){return rr(t&&t[0])?2:1}(e);a=l,(1===l&&!mr(e[0])||2===l&&!mr(e[0][0]))&&(o=!0)}else if(mr(e)&&!wr(e))a=0;else if(fr(e))if(isNaN(+e)){var c=rs(e);c&&(s=c,a=3)}else a=0;else if(xr(e)){var d=tr({},s);d.colorStops=ar(e.colorStops,function(t){return{offset:t.offset,color:rs(t.color)}}),xs(e)?a=4:ws(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=pr(n)?n:va[n]||Ba(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=$s(i),l=Os(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?Hs:t[d];if(!$s(s)&&!u||m||(m=this._additiveValue=[]),this.discrete)t[d]=g<1?i.rawValue:r.rawValue;else if($s(s))1===s?Ps(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,Ns(l),i),this._trackKeys.push(a)}s.addKeyframe(t,Ns(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 Vs(){return(new Date).getTime()}var js,Ws,qs=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=Vs()-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,ga(function e(){t._running&&(ga(e),!t._paused&&t.update())})},e.prototype.start=function(){this._running||(this._time=Vs(),this._pausedTime=0,this._startLoop())},e.prototype.stop=function(){this._running=!1},e.prototype.pause=function(){this._paused||(this._pauseStart=Vs(),this._paused=!0)},e.prototype.resume=function(){this._paused&&(this._pausedTime+=Vs()-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 Bs(t,e.loop);return this.addAnimator(n),n},e}(eo),Us=Di.domSupported,Gs=(Ws={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},{mouse:js=["click","dblclick","mousewheel","wheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],touch:["touchstart","touchend","touchmove"],pointer:ar(js,function(t){var e=t.replace("mouse","pointer");return Ws.hasOwnProperty(e)?e:t})}),Xs=["mousemove","mouseup"],Ys=["pointermove","pointerup"],Zs=!1;function Ks(t){var e=t.pointerType;return"pen"===e||"touch"===e}function Qs(t){t&&(t.zrByTouch=!0)}function Js(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 tl=function(t,e){this.stopPropagation=Hr,this.stopImmediatePropagation=Hr,this.preventDefault=Hr,this.type=e.type,this.target=this.currentTarget=t.dom,this.pointerType=e.pointerType,this.clientX=e.clientX,this.clientY=e.clientY},el={mousedown:function(t){t=yo(this.dom,t),this.__mayPointerCapture=[t.zrX,t.zrY],this.trigger("mousedown",t)},mousemove:function(t){t=yo(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=yo(this.dom,t),this.__togglePointerCapture(!1),this.trigger("mouseup",t)},mouseout:function(t){Js(this,(t=yo(this.dom,t)).toElement||t.relatedTarget)||(this.__pointerCapturing&&(t.zrEventControl="no_globalout"),this.trigger("mouseout",t))},wheel:function(t){Zs=!0,t=yo(this.dom,t),this.trigger("mousewheel",t)},mousewheel:function(t){Zs||(t=yo(this.dom,t),this.trigger("mousewheel",t))},touchstart:function(t){Qs(t=yo(this.dom,t)),this.__lastTouchMoment=new Date,this.handler.processGesture(t,"start"),el.mousemove.call(this,t),el.mousedown.call(this,t)},touchmove:function(t){Qs(t=yo(this.dom,t)),this.handler.processGesture(t,"change"),el.mousemove.call(this,t)},touchend:function(t){Qs(t=yo(this.dom,t)),this.handler.processGesture(t,"end"),el.mouseup.call(this,t),+new Date-+this.__lastTouchMoment<300&&el.click.call(this,t)},pointerdown:function(t){el.mousedown.call(this,t)},pointermove:function(t){Ks(t)||el.mousemove.call(this,t)},pointerup:function(t){el.mouseup.call(this,t)},pointerout:function(t){Ks(t)||el.mouseout.call(this,t)}};or(["click","dblclick","contextmenu"],function(t){el[t]=function(e){e=yo(this.dom,e),this.trigger(t,e)}});var nl={pointermove:function(t){Ks(t)||nl.mousemove.call(this,t)},pointerup:function(t){nl.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 il(t,e){var n=e.domHandlers;Di.pointerEventsSupported?or(Gs.pointer,function(i){ol(e,i,function(e){n[i].call(t,e)})}):(Di.touchEventsSupported&&or(Gs.touch,function(i){ol(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)})}),or(Gs.mouse,function(i){ol(e,i,function(r){r=_o(r),e.touching||n[i].call(t,r)})}))}function rl(t,e){function n(n){ol(e,n,function(i){i=_o(i),Js(t,i.target)||(i=function(t,e){return yo(t.dom,new tl(t,e),!0)}(t,i),e.domHandlers[n].call(t,i))},{capture:!0})}Di.pointerEventsSupported?or(Ys,n):Di.touchEventsSupported||or(Xs,n)}function ol(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 al(t){var e=t.mounted;for(var n in e)e.hasOwnProperty(n)&&bo(t.domTarget,n,e[n],t.listenerOpts[n]);t.mounted={}}var sl=function(t,e){this.mounted={},this.listenerOpts={},this.touching=!1,this.domTarget=t,this.domHandlers=e},ll=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 sl(e,el),Us&&(i._globalHandlerScope=new sl(document,nl)),il(i,i._localHandlerScope),i}return v(e,t),e.prototype.dispose=function(){al(this._localHandlerScope),Us&&al(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,Us&&+this.__pointerCapturing^+t){this.__pointerCapturing=t;var e=this._globalHandlerScope;t?rl(this,e):al(e)}},e}(eo),cl=1;Di.hasGlobalWindow&&(cl=Math.max(window.devicePixelRatio||window.screen&&window.screen.deviceXDPI/window.screen.logicalXDPI||1,1));var dl=cl,ul="#333",hl="#ccc",pl=ko,fl=5e-5;function gl(t){return t>fl||t<-5e-5}var ml,vl=[],_l=[],yl=[1,0,0,1,0,0],bl=Math.abs,xl=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 gl(this.rotation)||gl(this.x)||gl(this.y)||gl(this.scaleX-1)||gl(this.scaleY-1)||gl(this.skewX)||gl(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):pl(n),t&&(e?To(n,t,n):Mo(n,t)),this.transform=n,this._resolveGlobalScaleRatio(n)):n&&(pl(n),this.invTransform=null)},t.prototype._resolveGlobalScaleRatio=function(t){var e=this.globalScaleRatio;if(null!=e&&1!==e){this.getGlobalScale(vl);var n=vl[0]<0?-1:1,i=vl[1]<0?-1:1,r=((vl[0]-n)*e+n)/vl[0]||0,o=((vl[1]-i)*e+i)/vl[1]||0;t[0]*=r,t[1]*=r,t[2]*=o,t[3]*=o}this.invTransform=this.invTransform||[1,0,0,1,0,0],Po(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],To(_l,t.invTransform,e),e=_l);var n=this.originX,i=this.originY;(n||i)&&(yl[4]=n,yl[5]=i,To(_l,e,yl),_l[4]-=n,_l[5]-=i,e=_l),this.setLocalTransform(e)}},t.prototype.getGlobalScale=function(t){var e=this.transform;return t=t||[],e?(t[0]=Math.sqrt(e[0]*e[0]+e[1]*e[1]),t[1]=Math.sqrt(e[2]*e[2]+e[3]*e[3]),e[0]<0&&(t[0]=-t[0]),e[3]<0&&(t[1]=-t[1]),t):(t[0]=1,t[1]=1,t)},t.prototype.transformCoordToLocal=function(t,e){var n=[t,e],i=this.invTransform;return i&&Zr(n,n,i),n},t.prototype.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&Zr(n,n,i),n},t.prototype.getLineScale=function(){var t=this.transform;return t&&bl(t[0]-1)>1e-10&&bl(t[3]-1)>1e-10?Math.sqrt(bl(t[0]*t[3]-t[2]*t[1])):1},t.prototype.copyTransform=function(t){Sl(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&&Io(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}(),wl=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function Sl(t,e){for(var n=0;n=Ml)){t=t||Ei;for(var e=[],n=+new Date,i=0;i<=127;i++)e[i]=Oi.measureText(String.fromCharCode(i),t).width;var r=+new Date-n;return r>16?kl=Ml:r>2&&kl++,e}}(t.font),t.asciiWidthMapTried=!0),0<=e&&e<=127?null!=t.asciiWidthMap?t.asciiWidthMap[e]:t.asciiCharWidth:t.stWideCharWidth}function Al(t,e){var n=t.strWidthCache,i=n.get(e);return null==i&&(i=Oi.measureText(e,t.font).width,n.put(e,i)),i}function Il(t,e,n,i){var r=Al(Cl(e),t),o=El(e),a=Dl(0,r,n),s=Ll(0,o,i);return new qo(a,s,r,o)}function Pl(t,e,n,i){var r=((t||"")+"").split("\n");if(1===r.length)return Il(r[0],e,n,i);for(var o=new qo(0,0,0,0),a=0;a=0?parseFloat(t)/100*e:parseFloat(t):t}function Nl(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+=Rl(i[0],n.width),c+=Rl(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 zl="__zr_normal__",Ol=wl.concat(["ignore"]),$l=sr(wl,function(t,e){return t[e]=!0,t},{ignore:!1}),Hl={},Fl=new qo(0,0,0,0),Bl=[],Vl=function(){function t(t){this.id=Zi(),this.animators=[],this.currentStates=[],this.states={},this._init(t)}return t.prototype._init=function(t){this.attr(t)},t.prototype.drift=function(t,e,n){switch(this.draggable){case"horizontal":e=0;break;case"vertical":t=0}var i=this.transform;i||(i=this.transform=[1,0,0,1,0,0]),i[4]+=t,i[5]+=e,this.decomposeTransform(),this.markRedraw()},t.prototype.beforeUpdate=function(){},t.prototype.afterUpdate=function(){},t.prototype.update=function(){this.updateTransform(),this.__dirty&&this.updateInnerText()},t.prototype.updateInnerText=function(t){var e=this._textContent;if(e&&(!e.ignore||t)){this.textConfig||(this.textConfig={});var n=this.textConfig,i=n.local,r=e.innerTransformable,o=void 0,a=void 0,s=!1;r.parent=i?this:null;var l=!1;r.copyTransform(e);var c=null!=n.position,d=n.autoOverflowArea,u=void 0;if((d||c)&&(u=Fl,n.layoutRect?u.copy(n.layoutRect):u.copy(this.getBoundingRect()),i||u.applyTransform(this.transform)),c){this.calculateTextPosition?this.calculateTextPosition(Hl,n,u):Nl(Hl,n,u),r.x=Hl.x,r.y=Hl.y,o=Hl.align,a=Hl.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=Rl(h[0],u.width),f=Rl(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 qo(0,0,0,0);r.getLocalTransform(Bl),Po(Bl,Bl),qo.copy(v,u),v.applyTransform(Bl)}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()?hl:ul},t.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),n="string"==typeof e&&rs(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,ls(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||{},tr(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(vr(t))for(var n=cr(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(zl,!1,t)},t.prototype.useState=function(t,e,n,i){var r=t===zl;if(this.hasState()||!r){var o=this.currentStates,a=this.stateTransition;if(!(nr(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}Ki("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=nr(i,t),o=nr(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=nr(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=nr(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)}}function bi(t){return(t.name_by_user||t.name||"").trim()}async function xi(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=On(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),d=o.panel_device_id??e,u=c.find(t=>t.id===d)??null;return function(t,e){const n=new Map(e.map(t=>[t.id,t]));for(const e of Object.values(t)){const t=e.device_id?n.get(e.device_id):void 0,i=t?bi(t):"";i&&(e.name=i)}}(o.circuits,c),await yi(t,o),{topology:o,panelDevice:u,panelSize:a}}const wi=h.power,Si=h.current,Ci="--",ki=`${Ci}`;function Mi(t){return wi.unit(t)}function Ti(t){return(t<0?"-":"")+wi.format(t)}function Ai(t){return null===t?ki:`${Ti(t)} ${Mi(t)}`}function Ii(t){return null===t?ki:`${Ti(t)}${Mi(t)}`}function Pi(t){return null===t?ki:`${Si.format(t)}A`}function Di(t,e={}){const i=!t.mayOperate;return`
\n ${Ft(n("header.enable_switches"))}\n
\n \n
\n
${!1===e.note?"":_n(t)}`}function Li(){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 Ei(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 ${Ci}\n ${r?"A":"kW"}\n
\n
`:""}\n ${a?`\n
\n ${n("header.grid")}\n
\n ${Ci}\n
\n
`:""}\n ${s?`\n
\n ${n("header.upstream")}\n
\n ${Ci}\n ${r?"A":"kW"}\n
\n
`:""}\n ${l?`\n
\n ${n("header.downstream")}\n
\n ${Ci}\n ${r?"A":"kW"}\n
\n
`:""}\n ${c?`\n
\n ${n("header.solar")}\n
\n ${Ci}\n ${r?"A":"kW"}\n
\n
`:""}\n ${d?`\n
\n ${n("header.battery")}\n
\n ${Ci}\n %\n
\n
`:""}\n
\n `}function Ri(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?Di(an(t)):""}\n
\n ${Ei(t,e)}\n
\n
\n
\n ${a}\n
\n \n \n
\n
\n ${Li()}\n
\n
\n `}function Ni(t){const e=t.chart_metric??r;return h[e]??h[r]}function zi(t,e){const n=function(t){return Ni(t).entityRole}(e);return t.entities?.[n]??t.entities?.power??null}function Oi(t,e){return un(t)||(e?n("grid.shared_switch"):"")}function $i(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=Oi(i,r);return`
\n ${n(t?"grid.on":"grid.off")}\n \n
`}function Hi(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=Oi(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 Fi(t){return"unknown"===t?void 0:f[t]}const Bi="display:none;";function Vi(t){const e=Fi(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=Fi(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 qi(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"===Ni(s).entityRole?Pi(Un(e,a)):Ii(p),x=Vi(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 ${$i(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 Wi(t,e){return`\n
\n —\n
\n `}function Ui(t){return"function"==typeof globalThis.CSS?.escape?CSS.escape(t):t.replace(/["\\]/g,"\\$&")}function Gi(t){return Object.entries(t.circuits).filter(([,t])=>$n(t))}function Xi(t,e,n){return`${Ft(function(t){const e=Pn(t);if(null===e)return Ci;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 Yi(t,e,i){const r=Wn(t,e),o=null===r||0===r?"":n(r>0?"meters.importing":"meters.exporting");return`\n ${"current"===Ni(i).entityRole?Pi(Un(t,e)):Ii(r)}\n ${Ft(o)}\n ${Xi(e,t.entities?.consumed_energy,n("meters.imported"))}\n ${Xi(e,t.entities?.produced_energy,n("meters.exported"))}\n `}function Zi(t,e,i){if(!function(t,e){return!1!==e.show_panel&&Gi(t).length>0}(t,i))return"";const r=Gi(t).map(([t,r])=>`\n
\n ${Ft(r.name||n("grid.unknown"))}\n ${Yi(r,e,i)}\n
`).join("");return`\n
\n
${Ft(n("meters.title"))}
\n ${r}\n
\n `}function Ki(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=er(n,e,i,Ln(n)),d=nr(t,n,o,r.headlineEid,a,s),u=n.solar?Ji(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=Qi(i),h=o.headlineIsSiteTotal?`${Ft(n("subdevice.site_total"))}`:"",m=o.headlineEid?`${h}${Ai(Rn(e,o.headlineEid))}`:"",v=zn(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 Qi(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 Ji(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 ${Ai(t)}\n
`}return"inverter"!==t.role||e.headlineEid||(r+=`
${Ft(n("subdevice.in_site_total"))}
`),r}function tr(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&&bi(r)||e}function er(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||tr(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 nr(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 ir(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 rr(t){const e=a[t];return e?e.ms:a[o].ms}function or(t){const e=t/1e3;return e<=600?Math.ceil(e):Math.min(5e3,Math.ceil(e/5))}function ar(t){return Math.max(500,Math.floor(t/5e3))}function sr(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 lr(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 cr(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 dr(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 ur(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=or(i),l=ar(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,lr(n,s,l))}}}function hr(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 pr(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)?rr(r.get(t)):ir(n),cr(a,o,e,t)}for(const{entityId:t,key:i,devId:r}of hr(e)){let e;e=o&&o.has(r)?rr(o.get(r)):ir(n),cr(a,e,t,i)}const s=[];for(const[e,n]of a){if(0===n.entityIds.length)continue;e>2592e5?s.push(dr(t,n.entityIds,n.keysByEntity,e,i)):s.push(ur(t,n.entityIds,n.keysByEntity,e,i))}await Promise.all(s)}var fr=function(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1},gr=new function(){this.browser=new fr,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?(gr.wxa=!0,gr.touchEventsSupported=!0):"undefined"==typeof document&&"undefined"!=typeof self?gr.worker=!0:!gr.hasGlobalWindow||"Deno"in window||"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent&&navigator.userAgent.indexOf("Node.js")>-1?(gr.node=!0,gr.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,gr);var mr="sans-serif",vr="12px "+mr;var _r,yr,br=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 Go(t){return"CANVAS"===t.nodeName.toUpperCase()}var Xo=/([&<>"'])/g,Yo={"&":"&","<":"<",">":">",'"':""","'":"'"};function Zo(t){return null==t?"":(t+"").replace(Xo,function(t,e){return Yo[e]})}var Ko=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Qo=[],Jo=gr.browser.firefox&&+gr.browser.version.split(".")[0]<39;function ta(t,e,n,i){return n=n||{},i?ea(t,e,n):Jo&&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):ea(t,e,n),n}function ea(t,e,n){if(gr.domSupported&&t.getBoundingClientRect){var i=e.clientX,r=e.clientY;if(Go(t)){var o=t.getBoundingClientRect();return n.zrX=i-o.left,void(n.zrY=r-o.top)}if(Uo(Qo,t,i,r))return n.zrX=Qo[0],void(n.zrY=Qo[1])}n.zrX=n.zrY=0}function na(t){return t||window.event}function ia(t,e,n){if(null!=(e=na(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&&ta(t,r,e,n)}else{ta(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&&Ko.test(e.type)&&(e.which=1&a?1:2&a?3:4&a?2:0),e}function ra(t,e,n,i){t.removeEventListener(e,n,i)}var oa=function(t){t.preventDefault(),t.stopPropagation(),t.cancelBubble=!0},aa=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=sa(r)/sa(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 ca(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=0,t[5]=0,t}function da(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 ua(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 ha(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 pa(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 fa(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 ga=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,va=Math.max,_a=Math.abs,ya=["x","y"],ba=["width","height"],xa=new ga,wa=new ga,Sa=new ga,Ca=new ga,ka=Ea(),Ma=ka.minTv,Ta=ka.maxTv,Aa=[0,0],Ia=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=va(t.x+t.width,this.x+this.width)-e:this.width=t.width,isFinite(this.y)&&isFinite(this.height)?this.height=va(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 ha(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]),ha(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&&ga.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(Pa,e.x,e.y,e.width,e.height)),n instanceof t||(n=t.set(Da,n.x,n.y,n.width,n.height));var s=!!i;ka.reset(r,s);var l=ka.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))}xa.x=Sa.x=n.x,xa.y=Ca.y=n.y,wa.x=Ca.x=n.x+n.width,wa.y=Sa.y=n.y+n.height,xa.transform(i),Ca.transform(i),wa.transform(i),Sa.transform(i),e.x=ma(xa.x,wa.x,Sa.x,Ca.x),e.y=ma(xa.y,wa.y,Sa.y,Ca.y);var l=va(xa.x,wa.x,Sa.x,Ca.x),c=va(xa.y,wa.y,Sa.y,Ca.y);e.width=l-e.x,e.height=c-e.y}else e!==n&&t.copy(e,n)},t}(),Pa=new Ia(0,0,0,0),Da=new Ia(0,0,0,0);function La(t,e,n,i,r,o,a,s){var l=_a(e-n),c=_a(i-t),d=ma(l,c),u=ya[r],h=ya[1-r],p=ba[r];e=c||!ka.bidirectional)&&(Ma[u]=-c,Ma[h]=0,ka.useDir&&ka.calcDirMTV())))}function Ea(){var t=0,e=new ga,n=new ga,i={minTv:new ga,maxTv:new ga,useDir:!1,dirMinTv:new ga,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(r,o){i.touchThreshold=0,r&&null!=r.touchThreshold&&(i.touchThreshold=va(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||(Ha.copy(d.getBoundingRect()),d.transform&&Ha.applyTransform(d.transform),Ha.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=Ba(a,n,i))&&(!e.topTarget&&(e.topTarget=a),s!==Ra)){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){Fa.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||Eo(this._downPoint,[e.zrX,e.zrY])>4)return;this._downPoint=null}this.dispatchToElement(n,t,e)}});function qa(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 Wa(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 Ua(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 Ga(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 Xa(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=Ga(t[d],t,l,c,0,e);l+=h,0!==(c-=h)&&0!==(u=Ua(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-Ua(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=qa(t,n,i,e))s&&(l=s),Wa(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 Za=!1;function Ka(){Za||(Za=!0,console.warn("z / z2 / zlevel of displayable is invalid, which may cause unexpected errors"))}function Qa(t,e){return t.zlevel===e.zlevel?t.z===e.z?t.z2-e.z2:t.z-e.z:t.zlevel-e.zlevel}var Ja,ts=function(){function t(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=Qa}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}();Ja=gr.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(t){return setTimeout(t,16)};var es={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-es.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*es.bounceIn(2*t):.5*es.bounceOut(2*t-1)+.5}},ns=Math.pow,is=Math.sqrt,rs=1e-8,os=1e-4,as=is(3),ss=1/3,ls=Mo(),cs=Mo(),ds=Mo();function us(t){return t>-1e-8&&trs||t<-1e-8}function ps(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 fs(t,e,n,i,r){var o=1-r;return 3*(((e-t)*o+2*(n-e)*r)*o+(i-n)*r*r)}function gs(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(us(d)&&us(u)){if(us(s))o[0]=0;else(C=-l/s)>=0&&C<=1&&(o[p++]=C)}else{var f=u*u-4*d*h;if(us(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=is(f),_=d*s+1.5*a*(-u+v),y=d*s+1.5*a*(-u-v);(C=(-s-((_=_<0?-ns(-_,ss):ns(_,ss))+(y=y<0?-ns(-y,ss):ns(y,ss))))/(3*a))>=0&&C<=1&&(o[p++]=C)}else{var b=(2*d*s-3*a*u)/(2*is(d*d*d)),x=Math.acos(b)/3,w=is(d),S=Math.cos(x),C=(-s-2*w*S)/(3*a),k=(m=(-s+w*(S+as*Math.sin(x)))/(3*a),(-s+w*(S-as*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(us(a)){if(hs(o))(d=-s/o)>=0&&d<=1&&(r[l++]=d)}else{var c=o*o-4*a*s;if(us(c))r[0]=-o/(2*a);else if(c>0){var d,u=is(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 vs(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 _s(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=ps(t,n,r,a,f),m=ps(e,i,o,s,f),v=g-c,_=m-d;u+=Math.sqrt(v*v+_*_),c=g,d=m}return u}function ys(t,e,n,i){var r=1-i;return r*(r*t+2*i*e)+i*i*n}function bs(t,e,n,i){return 2*((1-i)*(e-t)+i*(n-e))}function xs(t,e,n){var i=t+n-2*e;return 0===i?.5:(t-e)/i}function ws(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 Ss(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=ys(t,n,r,h),f=ys(e,i,o,h),g=p-s,m=f-l;c+=Math.sqrt(g*g+m*m),s=p,l=f}return c}var Cs=/cubic-bezier\(([0-9,\.e ]+)\)/;function ks(t){var e=t&&Cs.exec(t);if(e){var n=e[1].split(","),i=+fo(n[0]),r=+fo(n[1]),o=+fo(n[2]),a=+fo(n[3]);if(isNaN(i+r+o+a))return;var s=[];return function(t){return t<=0?0:t>=1?1:gs(0,i,o,1,t,s)&&ps(0,r,a,1,s[0])}}}var Ms=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||Co,this.ondestroy=t.ondestroy||Co,this.onrestart=t.onrestart||Co,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=Kr(t)?t:es[t]||ks(t)},t}(),Ts=function(t){this.value=t},As=function(){function t(){this._len=0}return t.prototype.insert=function(t){var e=new Ts(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}(),Is=function(){function t(t){this._list=new As,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 Ts(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}(),Ps={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 Ds(t){return(t=Math.round(t))<0?0:t>255?255:t}function Ls(t){return t<0?0:t>1?1:t}function Es(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Ds(parseFloat(e)/100*255):Ds(parseInt(e,10))}function Rs(t){var e=t;return e.length&&"%"===e.charAt(e.length-1)?Ls(parseFloat(e)/100):Ls(parseFloat(e))}function Ns(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 Os(t,e,n,i,r){return t[0]=e,t[1]=n,t[2]=i,t[3]=r,t}function $s(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t}var Hs=new Is(20),Fs=null;function Bs(t,e){Fs&&$s(Fs,e),Fs=Hs.put(t,Fs||e.slice())}function Vs(t,e){if(t){e=e||[];var n=Hs.get(t);if(n)return $s(e,n);var i=(t+="").replace(/ /g,"").toLowerCase();if(i in Ps)return $s(e,Ps[i]),Bs(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?(Os(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),Bs(t,e),e):void Os(e,0,0,0,1):7===o||9===o?(r=parseInt(i.slice(1,7),16))>=0&&r<=16777215?(Os(e,(16711680&r)>>16,(65280&r)>>8,255&r,9===o?parseInt(i.slice(7),16)/255:1),Bs(t,e),e):void Os(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?Os(e,+c[0],+c[1],+c[2],1):Os(e,0,0,0,1);d=Rs(c.pop());case"rgb":return c.length>=3?(Os(e,Es(c[0]),Es(c[1]),Es(c[2]),3===c.length?d:Rs(c[3])),Bs(t,e),e):void Os(e,0,0,0,1);case"hsla":return 4!==c.length?void Os(e,0,0,0,1):(c[3]=Rs(c[3]),js(c,e),Bs(t,e),e);case"hsl":return 3!==c.length?void Os(e,0,0,0,1):(js(c,e),Bs(t,e),e);default:return}}Os(e,0,0,0,1)}}function js(t,e){var n=(parseFloat(t[0])%360+360)%360/360,i=Rs(t[1]),r=Rs(t[2]),o=r<=.5?r*(i+1):r+i-r*i,a=2*r-o;return Os(e=e||[],Ds(255*Ns(a,o,n+1/3)),Ds(255*Ns(a,o,n)),Ds(255*Ns(a,o,n-1/3)),1),4===t.length&&(e[3]=t[3]),e}function qs(t,e){var n=Vs(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 Us(n,4===n.length?"rgba":"rgb")}}function Ws(t,e,n,i){var r=Vs(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]=Rs(Kr(n)?n(r[1]):n)),null!=i&&(r[2]=Rs(Kr(i)?i(r[2]):i)),Us(js(r),"rgba")}function Us(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 Gs(t,e){var n=Vs(t);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*e:0}var Xs=new Is(100);function Ys(t){if(Qr(t)){var e=Xs.get(t);return e||(e=qs(t,-.1),Xs.put(t,e)),e}if(oo(t)){var n=$r({},t);return n.colorStops=qr(t.colorStops,function(t){return{offset:t.offset,color:qs(t.color,-.1)}}),n}return t}var Zs=Math.round;function Ks(t){var e;if(t&&"transparent"!==t){if("string"==typeof t&&t.indexOf("rgba")>-1){var n=Vs(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 Qs=1e-4;function Js(t){return t-1e-4}function tl(t){return Zs(1e3*t)/1e3}function el(t){return Zs(1e4*t)/1e4}var nl={left:"start",right:"end",center:"middle",middle:"middle"};function il(t){return t&&!!t.image}function rl(t){return il(t)||function(t){return t&&!!t.svgElement}(t)}function ol(t){return"linear"===t.type}function al(t){return"radial"===t.type}function sl(t){return t&&("linear"===t.type||"radial"===t.type)}function ll(t){return"url(#"+t+")"}function cl(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 dl(t){var e=t.x||0,n=t.y||0,i=(t.rotation||0)*ko,r=lo(t.scaleX,1),o=lo(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("+Zs(a*ko)+"deg, "+Zs(s*ko)+"deg)"),l.join(" ")}var ul=gr.hasGlobalWindow&&Kr(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},hl=Array.prototype.slice;function pl(t,e,n){return(e-t)*n+t}function fl(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(Vr(e)){var l=function(t){return Vr(t&&t[0])?2:1}(e);a=l,(1===l&&!to(e[0])||2===l&&!to(e[0][0]))&&(o=!0)}else if(to(e)&&!ao(e))a=0;else if(Qr(e))if(isNaN(+e)){var c=Vs(e);c&&(s=c,a=3)}else a=0;else if(oo(e)){var d=$r({},s);d.colorStops=qr(e.colorStops,function(t){return{offset:t.offset,color:Vs(t.color)}}),ol(e)?a=4:al(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=Kr(n)?n:es[n]||ks(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=wl(i),l=xl(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?Sl:t[d];if(!wl(s)&&!u||m||(m=this._additiveValue=[]),this.discrete)t[d]=g<1?i.rawValue:r.rawValue;else if(wl(s))1===s?fl(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,yl(l),i),this._trackKeys.push(a)}s.addKeyframe(t,yl(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 Ml(){return(new Date).getTime()}var Tl,Al,Il=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=Ml()-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,Ja(function e(){t._running&&(Ja(e),!t._paused&&t.update())})},e.prototype.start=function(){this._running||(this._time=Ml(),this._pausedTime=0,this._startLoop())},e.prototype.stop=function(){this._running=!1},e.prototype.pause=function(){this._paused||(this._pauseStart=Ml(),this._paused=!0)},e.prototype.resume=function(){this._paused&&(this._pausedTime+=Ml()-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 kl(t,e.loop);return this.addAnimator(n),n},e}(Fo),Pl=gr.domSupported,Dl=(Al={pointerdown:1,pointerup:1,pointermove:1,pointerout:1},{mouse:Tl=["click","dblclick","mousewheel","wheel","mouseout","mouseup","mousedown","mousemove","contextmenu"],touch:["touchstart","touchend","touchmove"],pointer:qr(Tl,function(t){var e=t.replace("mouse","pointer");return Al.hasOwnProperty(e)?e:t})}),Ll=["mousemove","mouseup"],El=["pointermove","pointerup"],Rl=!1;function Nl(t){var e=t.pointerType;return"pen"===e||"touch"===e}function zl(t){t&&(t.zrByTouch=!0)}function Ol(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 $l=function(t,e){this.stopPropagation=Co,this.stopImmediatePropagation=Co,this.preventDefault=Co,this.type=e.type,this.target=this.currentTarget=t.dom,this.pointerType=e.pointerType,this.clientX=e.clientX,this.clientY=e.clientY},Hl={mousedown:function(t){t=ia(this.dom,t),this.__mayPointerCapture=[t.zrX,t.zrY],this.trigger("mousedown",t)},mousemove:function(t){t=ia(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=ia(this.dom,t),this.__togglePointerCapture(!1),this.trigger("mouseup",t)},mouseout:function(t){Ol(this,(t=ia(this.dom,t)).toElement||t.relatedTarget)||(this.__pointerCapturing&&(t.zrEventControl="no_globalout"),this.trigger("mouseout",t))},wheel:function(t){Rl=!0,t=ia(this.dom,t),this.trigger("mousewheel",t)},mousewheel:function(t){Rl||(t=ia(this.dom,t),this.trigger("mousewheel",t))},touchstart:function(t){zl(t=ia(this.dom,t)),this.__lastTouchMoment=new Date,this.handler.processGesture(t,"start"),Hl.mousemove.call(this,t),Hl.mousedown.call(this,t)},touchmove:function(t){zl(t=ia(this.dom,t)),this.handler.processGesture(t,"change"),Hl.mousemove.call(this,t)},touchend:function(t){zl(t=ia(this.dom,t)),this.handler.processGesture(t,"end"),Hl.mouseup.call(this,t),+new Date-+this.__lastTouchMoment<300&&Hl.click.call(this,t)},pointerdown:function(t){Hl.mousedown.call(this,t)},pointermove:function(t){Nl(t)||Hl.mousemove.call(this,t)},pointerup:function(t){Hl.mouseup.call(this,t)},pointerout:function(t){Nl(t)||Hl.mouseout.call(this,t)}};jr(["click","dblclick","contextmenu"],function(t){Hl[t]=function(e){e=ia(this.dom,e),this.trigger(t,e)}});var Fl={pointermove:function(t){Nl(t)||Fl.mousemove.call(this,t)},pointerup:function(t){Fl.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 Bl(t,e){var n=e.domHandlers;gr.pointerEventsSupported?jr(Dl.pointer,function(i){jl(e,i,function(e){n[i].call(t,e)})}):(gr.touchEventsSupported&&jr(Dl.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(Dl.mouse,function(i){jl(e,i,function(r){r=na(r),e.touching||n[i].call(t,r)})}))}function Vl(t,e){function n(n){jl(e,n,function(i){i=na(i),Ol(t,i.target)||(i=function(t,e){return ia(t.dom,new $l(t,e),!0)}(t,i),e.domHandlers[n].call(t,i))},{capture:!0})}gr.pointerEventsSupported?jr(El,n):gr.touchEventsSupported||jr(Ll,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 ql(t){var e=t.mounted;for(var n in e)e.hasOwnProperty(n)&&ra(t.domTarget,n,e[n],t.listenerOpts[n]);t.mounted={}}var Wl=function(t,e){this.mounted={},this.listenerOpts={},this.touching=!1,this.domTarget=t,this.domHandlers=e},Ul=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 Wl(e,Hl),Pl&&(i._globalHandlerScope=new Wl(document,Fl)),Bl(i,i._localHandlerScope),i}return v(e,t),e.prototype.dispose=function(){ql(this._localHandlerScope),Pl&&ql(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,Pl&&+this.__pointerCapturing^+t){this.__pointerCapturing=t;var e=this._globalHandlerScope;t?Vl(this,e):ql(e)}},e}(Fo),Gl=1;gr.hasGlobalWindow&&(Gl=Math.max(window.devicePixelRatio||window.screen&&window.screen.deviceXDPI/window.screen.logicalXDPI||1,1));var Xl=Gl,Yl="#333",Zl="#ccc",Kl=ca,Ql=5e-5;function Jl(t){return t>Ql||t<-5e-5}var tc,ec=[],nc=[],ic=[1,0,0,1,0,0],rc=Math.abs,oc=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 Jl(this.rotation)||Jl(this.x)||Jl(this.y)||Jl(this.scaleX-1)||Jl(this.scaleY-1)||Jl(this.skewX)||Jl(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):Kl(n),t&&(e?ua(n,t,n):da(n,t)),this.transform=n,this._resolveGlobalScaleRatio(n)):n&&(Kl(n),this.invTransform=null)},t.prototype._resolveGlobalScaleRatio=function(t){var e=this.globalScaleRatio;if(null!=e&&1!==e){this.getGlobalScale(ec);var n=ec[0]<0?-1:1,i=ec[1]<0?-1:1,r=((ec[0]-n)*e+n)/ec[0]||0,o=((ec[1]-i)*e+i)/ec[1]||0;t[0]*=r,t[1]*=r,t[2]*=o,t[3]*=o}this.invTransform=this.invTransform||[1,0,0,1,0,0],fa(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],ua(nc,t.invTransform,e),e=nc);var n=this.originX,i=this.originY;(n||i)&&(ic[4]=n,ic[5]=i,ua(nc,e,ic),nc[4]-=n,nc[5]-=i,e=nc),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&&No(n,n,i),n},t.prototype.transformCoordToGlobal=function(t,e){var n=[t,e],i=this.transform;return i&&No(n,n,i),n},t.prototype.getLineScale=function(){var t=this.transform;return t&&rc(t[0]-1)>1e-10&&rc(t[3]-1)>1e-10?Math.sqrt(rc(t[0]*t[3]-t[2]*t[1])):1},t.prototype.copyTransform=function(t){sc(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&&pa(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}(),ac=["x","y","originX","originY","anchorX","anchorY","rotation","scaleX","scaleY","skewX","skewY"];function sc(t,e){for(var n=0;n=dc)){t=t||vr;for(var e=[],n=+new Date,i=0;i<=127;i++)e[i]=xr.measureText(String.fromCharCode(i),t).width;var r=+new Date-n;return r>16?cc=dc:r>2&&cc++,e}}(t.font),t.asciiWidthMapTried=!0),0<=e&&e<=127?null!=t.asciiWidthMap?t.asciiWidthMap[e]:t.asciiCharWidth:t.stWideCharWidth}function hc(t,e){var n=t.strWidthCache,i=n.get(e);return null==i&&(i=xr.measureText(e,t.font).width,n.put(e,i)),i}function pc(t,e,n,i){var r=hc(lc(e),t),o=vc(e),a=gc(0,r,n),s=mc(0,o,i);return new Ia(a,s,r,o)}function fc(t,e,n,i){var r=((t||"")+"").split("\n");if(1===r.length)return pc(r[0],e,n,i);for(var o=new Ia(0,0,0,0),a=0;a=0?parseFloat(t)/100*e:parseFloat(t):t}function yc(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+=_c(i[0],n.width),c+=_c(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 bc="__zr_normal__",xc=ac.concat(["ignore"]),wc=Wr(ac,function(t,e){return t[e]=!0,t},{ignore:!1}),Sc={},Cc=new Ia(0,0,0,0),kc=[],Mc=function(){function t(t){this.id=Rr(),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=Cc,n.layoutRect?u.copy(n.layoutRect):u.copy(this.getBoundingRect()),i||u.applyTransform(this.transform)),c){this.calculateTextPosition?this.calculateTextPosition(Sc,n,u):yc(Sc,n,u),r.x=Sc.x,r.y=Sc.y,o=Sc.align,a=Sc.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=_c(h[0],u.width),f=_c(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 Ia(0,0,0,0);r.getLocalTransform(kc),fa(kc,kc),Ia.copy(v,u),v.applyTransform(kc)}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()?Zl:Yl},t.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),n="string"==typeof e&&Vs(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,Us(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||{},$r(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(eo(t))for(var n=Gr(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(bc,!1,t)},t.prototype.useState=function(t,e,n,i){var r=t===bc;if(this.hasState()||!r){var o=this.currentStates,a=this.stateTransition;if(!(Fr(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}Nr("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=Fr(i,t),o=Fr(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=Fr(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=Fr(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 rc=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 oc(t,e,n)};function oc(t,e,n){return fr(t)?(i=t,i.replace(/^\s+|\s+$/g,"")).match(/%$/)?parseFloat(t)/100*e+(n||0):parseFloat(t):null==t?NaN:+t;var i}function ac(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function sc(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 lc(t,e){var n=Math.max(sc(t),sc(e)),i=t+e;return n>20?i:ac(i,n)}function cc(t){var e=2*Math.PI;return(t%e+e)%e}function dc(t){return t>-1e-4&&t=10&&e++,e}function fc(t,e){var n=pc(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 gc(t){var e=parseFloat(t);return e==t&&(0!==e||!fr(t)||t.indexOf("x")<=0)?e:NaN}function mc(){return Math.round(9*Math.random())}function vc(t,e){return 0===e?t:vc(e,t%e)}function _c(t,e){return null==t?e:null==e?t:t*e/vc(t,e)}var yc="undefined"!=typeof console&&console.warn&&console.log;function bc(t,e){!function(t,e){yc&&console[t]("[ECharts] "+e)}("error",t)}function xc(t){throw new Error(t)}function wc(t,e,n){return(e-t)*n+t}var Sc="series\0";function Cc(t){return t instanceof Array?t:null==t?[]:[t]}function kc(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&&nr(r,s)<0)){var l=n.getShallow(s,e);null!=l&&(o[t[a][0]]=l)}}return o}}var Jc=Qc([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),td=function(){function t(){}return t.prototype.getAreaStyle=function(t,e){return Jc(this,t,e)},t}(),ed=new qa(50);function nd(t){if("string"==typeof t){var e=ed.get(t);return e&&e.image}return t}function id(t,e,n,i,r){if(t){if("string"==typeof t){if(e&&e.__zrImageSrc===t||!n)return e;var o=ed.get(t),a={hostEl:n,cb:i,cbPayload:r};return o?!od(e=o.image)&&o.pending.push(a):((e=Oi.loadImage(t,rd,rd)).__zrImageSrc=t,ed.put(t,e.__cachedImgObj={image:e,pending:[a]})),e}return t}return e}function rd(){var t=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=s;c++)l-=s;var d=Al(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 cd(t,e,n){var i=n.containerWidth,r=n.contentWidth,o=n.fontMeasureInfo;if(!i)return t.textLine="",void(t.isTruncated=!1);var a=Al(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?dd(e,r,o):a>0?Math.floor(e.length*r/a):0;a=Al(o,e=e.substr(0,l))}""===e&&(e=n.placeholder),t.textLine=e,t.isTruncated=!0}function dd(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=vd(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=Cl(d),v=0;v=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}(t)||!!gd[t]}function vd(t,e,n,i,r){for(var o=[],a=[],s="",l="",c=0,d=0,u=Cl(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 _d(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;qo.set(yd,Dl(n,a,r),Ll(i,s,o),a,s),qo.intersect(e,yd,null,bd);var l=bd.outIntersectRect;t.outerWidth=l.width,t.outerHeight=l.height,t.baseX=Dl(l.x,l.width,r,!0),t.baseY=Ll(l.y,l.height,o,!0)}}var yd=new qo(0,0,0,0),bd={outIntersectRect:{},clamp:!0};function xd(t){return null!=t?t+="":t=""}function wd(t,e,n,i){var r=new qo(Dl(t.x||0,e,t.textAlign),Ll(t.y||0,n,t.textBaseline),e,n),o=null!=i?i:Sd(t)?t.lineWidth:0;return o>0&&(r.x-=o/2,r.y-=o/2,r.width+=o,r.height+=o),r}function Sd(t){var e=t.stroke;return null!=e&&"none"!==e&&t.lineWidth>0}var Cd="__zr_style_"+Math.round(10*Math.random()),kd={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},Md={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};kd[Cd]=!0;var Td=["z","z2","invisible"],Ad=["invisible"],Id=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=cr(e),i=0;i1e-4)return s[0]=t-n,s[1]=e-i,l[0]=t+n,void(l[1]=e+i);if(Od[0]=Nd(r)*n+t,Od[1]=Rd(r)*i+e,$d[0]=Nd(o)*n+t,$d[1]=Rd(o)*i+e,c(s,Od,$d),d(l,Od,$d),(r%=zd)<0&&(r+=zd),(o%=zd)<0&&(o+=zd),r>o&&!a?o+=zd:rr&&(Hd[0]=Nd(p)*n+t,Hd[1]=Rd(p)*i+e,c(s,Hd,s),d(l,Hd,l))}var Ud={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},Gd=[],Xd=[],Yd=[],Zd=[],Kd=[],Qd=[],Jd=Math.min,tu=Math.max,eu=Math.cos,nu=Math.sin,iu=Math.abs,ru=Math.PI,ou=2*ru,au="undefined"!=typeof Float32Array,su=[];function lu(t){return Math.round(t/ru*1e8)/1e8%2*ru}var cu=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=iu(n/dl/t)||0,this._uy=iu(n/dl/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(Ud.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=iu(t-this._xi),i=iu(e-this._yi),r=n>this._ux||i>this._uy;if(this.addData(Ud.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(Ud.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(Ud.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(),su[0]=i,su[1]=r,function(t,e){var n=lu(t[0]);n<0&&(n+=ou);var i=n-t[0],r=t[1];r+=i,!e&&r-n>=ou?r=n+ou:e&&n-r>=ou?r=n-ou:!e&&n>r?r=n+(ou-lu(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(){Yd[0]=Yd[1]=Kd[0]=Kd[1]=Number.MAX_VALUE,Zd[0]=Zd[1]=Qd[0]=Qd[1]=-Number.MAX_VALUE;var t,e=this.data,n=0,i=0,r=0,o=0;for(t=0;tn||iu(m)>i||u===e-1)&&(f=Math.sqrt(I*I+m*m),r=g,o=y);break;case Ud.C:var v=t[u++],_=t[u++],y=(g=t[u++],t[u++]),b=t[u++],x=t[u++];f=Ra(r,o,v,_,g,y,b,x,10),r=b,o=x;break;case Ud.Q:f=Ha(r,o,v=t[u++],_=t[u++],g=t[u++],y=t[u++],10),r=g,o=y;break;case Ud.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=eu(M)*C+w,s=nu(M)*k+S),f=tu(C,k)*Jd(ou,Math.abs(T)),r=eu(A)*C+w,o=nu(A)*k+S;break;case Ud.R:a=r=t[u++],s=o=t[u++],f=2*t[u++]+2*t[u++];break;case Ud.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 Ud.M:n=r=h[b++],i=o=h[b++],t.moveTo(r,o);break;case Ud.L:a=h[b++],s=h[b++];var S=iu(a-r),C=iu(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 Ud.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){Ea(r,T,I,D,k=(c-v)/X,Gd),Ea(o,A,P,L,k,Xd),t.bezierCurveTo(Gd[1],Xd[1],Gd[2],Xd[2],Gd[3],Xd[3]);break t}v+=X}t.bezierCurveTo(T,A,I,P,D,L),r=D,o=L;break;case Ud.Q:T=h[b++],A=h[b++],I=h[b++],P=h[b++];if(m){if(v+(X=l[_++])>c){$a(r,T,I,k=(c-v)/X,Gd),$a(o,A,P,k,Xd),t.quadraticCurveTo(Gd[1],Xd[1],Gd[2],Xd[2]);break t}v+=X}t.quadraticCurveTo(T,A,I,P),r=I,o=P;break;case Ud.A:var E=h[b++],R=h[b++],N=h[b++],z=h[b++],O=h[b++],$=h[b++],H=h[b++],F=!h[b++],B=N>z?N:z,V=iu(N-z)>.001,j=O+$,W=!1;if(m)v+(X=l[_++])>c&&(j=O+$*(c-v)/X,W=!0),v+=X;if(V&&t.ellipse?t.ellipse(E,R,N,z,H,O,j,F):t.arc(E,R,B,O,j,F),W)break t;w&&(n=eu(O)*N+E,i=nu(O)*z+R),r=eu(j)*N+E,o=nu(j)*z+R;break;case Ud.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[_++])>c){var G=c-v;t.moveTo(a,s),t.lineTo(a+Jd(G,q),s),(G-=q)>0&&t.lineTo(a+q,s+Jd(G,U)),(G-=U)>0&&t.lineTo(a+tu(q-G,0),s+U),(G-=q)>0&&t.lineTo(a,s+tu(U-G,0));break t}v+=X}t.rect(a,s,q,U);break;case Ud.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=Ud,t.initDefaultProps=((e=t.prototype)._saveData=!0,e._ux=0,e._uy=0,e._pendingPtDist=0,void(e._version=0)),t}();function du(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+=gu);var h=Math.atan2(l,s);return h<0&&(h+=gu),h>=i&&h<=r||h+gu>=i&&h+gu<=r}function vu(t,e,n,i,r,o){if(o>e&&o>i||or?s:0}var _u=cu.CMD,yu=2*Math.PI;var bu=[-1,-1,-1],xu=[-1,-1];function wu(){var t=xu[0];xu[0]=xu[1],xu[1]=t}function Su(t,e,n,i,r,o,a,s,l,c){if(c>e&&c>i&&c>o&&c>s||c1&&wu(),p=Ia(e,i,o,s,xu[0]),h>1&&(f=Ia(e,i,o,s,xu[1]))),2===h?me&&s>i&&s>o||s=0&&d<=1&&(r[l++]=d);else{var c=a*a-4*o*s;if(Ta(c))(d=-a/(2*o))>=0&&d<=1&&(r[l++]=d);else if(c>0){var d,u=ya(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,bu);if(0===l)return 0;var c=Oa(e,i,o);if(c>=0&&c<=1){for(var d=0,u=Na(e,i,o,c),h=0;hn||s<-n)return 0;var l=Math.sqrt(n*n-s*s);bu[0]=-l,bu[1]=l;var c=Math.abs(i-r);if(c<1e-4)return 0;if(c>=yu-1e-4){i=0,r=yu;var d=o?1:-1;return a>=bu[0]+t&&a<=bu[1]+t?d:0}if(i>r){var u=i;i=r,r=u}i<0&&(i+=yu,r+=yu);for(var h=0,p=0;p<2;p++){var f=bu[p];if(f+t>a){var g=Math.atan2(s,f);d=o?1:-1;g<0&&(g=yu+g),(g>=i&&g<=r||g+yu>=i&&g+yu<=r)&&(g>Math.PI/2&&g<1.5*Math.PI&&(d=-d),h+=d)}}return h}function Mu(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+=vu(d,u,h,p,i,r))),m&&(h=d=s[f],p=u=s[f+1]),g){case _u.M:d=h=s[f++],u=p=s[f++];break;case _u.L:if(n){if(du(d,u,s[f],s[f+1],e,i,r))return!0}else c+=vu(d,u,s[f],s[f+1],i,r)||0;d=s[f++],u=s[f++];break;case _u.C:if(n){if(uu(d,u,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=Su(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 _u.Q:if(n){if(hu(d,u,s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=Cu(d,u,s[f++],s[f++],s[f],s[f+1],i,r)||0;d=s[f++],u=s[f++];break;case _u.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+=vu(d,u,o,a,i,r);var C=(i-v)*b/y+v;if(n){if(mu(v,_,b,x,x+w,S,e,C,r))return!0}else c+=ku(v,_,b,x,x+w,S,C,r);d=Math.cos(x+w)*y+v,u=Math.sin(x+w)*b+_;break;case _u.R:if(h=d=s[f++],p=u=s[f++],o=h+s[f++],a=p+s[f++],n){if(du(h,p,o,p,e,i,r)||du(o,p,o,a,e,i,r)||du(o,a,h,a,e,i,r)||du(h,a,h,p,e,i,r))return!0}else c+=vu(o,p,o,a,i,r),c+=vu(h,a,h,p,i,r);break;case _u.Z:if(n){if(du(d,u,h,p,e,i,r))return!0}else c+=vu(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+=vu(d,u,h,p,i,r)||0),0!==c}var Tu=er({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},kd),Au={style:er({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},Md.style)},Iu=wl.concat(["invisible","culling","z","z2","zlevel","parent"]),Pu=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?ul:e>.2?"#eee":hl}if(t)return hl}return ul},e.prototype.getInsideTextStroke=function(t){var e=this.style.fill;if(fr(e)){var n=this.__zr;if(!(!n||!n.isDarkMode())===cs(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 cu(!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 Mu(t,e,!0,n,i)}(o,a/s,t,e)))return!0}if(this.hasFill())return function(t,e,n){return Mu(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:tr(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(4&this.__dirty)},e.prototype.createStyle=function(t){return Or(Tu,t)},e.prototype._innerSaveToNormal=function(e){t.prototype._innerSaveToNormal.call(this,e);var n=this._normalState;e.shape&&!n.shape&&(n.shape=tr({},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=tr({},i.shape),tr(s,n.shape)):(s=tr({},r?this.shape:i.shape),tr(s,n.shape)):l&&(s=i.shape),s)if(o){this.shape=tr({},this.shape);for(var c={},d=cr(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}(Pu);Vu.prototype.type="rect";var ju={fill:"#000"},Wu={},qu={style:er({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},Md.style)},Uu=function(t){function e(e){var n=t.call(this)||this;return n.type="text",n._children=[],n._defaultStyle=ju,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=ld(g,c,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),x={},w=0;w0,k=0;kg&&fd(o,a.substring(g,m),e,f),fd(o,h[2],e,f,h[1]),g=ad.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&&rh(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=nh(r,o,u),c-=t.height/2-u[0]-t.innerHeight/2);var h=this._getOrCreateChild(Lu),p=h.createStyle();h.useStyle(p);var f=this._defaultStyle,g=!1,m=0,v=!1,_=eh("fill"in s?s.fill:"fill"in e?e.fill:(g=!0,f.fill)),y=th("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||Ei,p.opacity=kr(s.opacity,e.opacity,1),Ku(p,s),y&&(p.lineWidth=kr(s.lineWidth,e.lineWidth,m),p.lineDash=Cr(s.lineDash,e.lineDash),p.lineDashOffset=e.lineDashOffset||0,p.stroke=y),_&&(p.fill=_),h.setBoundingRect(wd(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(Vu)).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(Nu)).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=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 _=(a||s).style;_.shadowBlur=t.shadowBlur||0,_.shadowColor=t.shadowColor||"transparent",_.shadowOffsetX=t.shadowOffsetX||0,_.shadowOffsetY=t.shadowOffsetY||0,_.opacity=kr(t.opacity,e.opacity,1)},e.makeFont=function(t){var e="";return Qu(t)&&(e=[t.fontStyle,t.fontWeight,Zu(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),e&&Ir(e)||t.textFont||t.font},e}(Id),Gu={left:!0,right:1,center:1},Xu={top:1,bottom:1,middle:1},Yu=["fontStyle","fontWeight","fontSize","fontFamily"];function Zu(t){return"string"!=typeof t||-1===t.indexOf("px")&&-1===t.indexOf("rem")&&-1===t.indexOf("em")?isNaN(+t)?"12px":t+"px":t}function Ku(t,e){for(var n=0;n=0,o=!1;if(t instanceof Pu){var a=lh(t),s=r&&a.selectFill||a.normalFill,l=r&&a.selectStroke||a.normalStroke;if(_h(s)||_h(l)){var c=(i=i||{}).style||{};"inherit"===c.fill?(o=!0,i=tr({},i),(c=tr({},c)).fill=s):!_h(c.fill)&&_h(s)?(o=!0,i=tr({},i),(c=tr({},c)).fill=us(s)):!_h(c.stroke)&&_h(l)&&(o||(i=tr({},i),c=tr({},c)),c.stroke=us(l)),i.style=c}}if(i&&null==i.z2){o||(i=tr({},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=nr(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 qh(t,e,n){Zh(t,!0),Th(t,Ph),function(t,e,n){var i=oh(t);null!=e?(i.focus=e,i.blurScope=n):i.focus&&(i.focus=null)}(t,e,n)}function Uh(t,e,n,i){i?function(t){Zh(t,!1)}(t):qh(t,e,n)}var Gh=["emphasis","blur","select"],Xh={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function Yh(t,e,n,i){n=n||"itemStyle";for(var r=0;r1&&(a*=rp(f),s*=rp(f));var g=(r===o?-1:1)*rp((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+ap(u)*m-op(u)*v,y=(e+i)/2+op(u)*m+ap(u)*v,b=dp([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=dp(x,w);if(cp(x,w)<=-1&&(S=sp),cp(x,w)>=1&&(S=0),S<0){var C=Math.round(S/sp*1e6)/1e6;S=2*sp+C%2*sp}d.addData(c,_,y,a,s,b,S,u,o)}var hp=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,pp=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;var fp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e.prototype.applyTransform=function(t){},e}(Pu);function gp(t){return null!=t.setData}function mp(t,e){var n=function(t){var e=new cu;if(!t)return e;var n,i=0,r=0,o=i,a=r,s=cu.CMD,l=t.match(hp);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 Ep(t,e){var n,i=Ip(e.r,0),r=Ip(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=Tp(l-s),p=h>wp&&h%wp;if(p>Dp&&(h=p),i>Dp)if(h>wp-Dp)t.moveTo(c+i*Cp(s),d+i*Sp(s)),t.arc(c,d,i,s,l,!u),r>Dp&&(t.moveTo(c+r*Cp(l),d+r*Sp(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*Cp(s),D=i*Sp(s),L=r*Cp(l),E=r*Sp(l),R=h>Dp;if(R){var N=e.cornerRadius;N&&(n=function(t){var e;if(hr(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 z=Tp(i-r)/2;if(_=Pp(z,m),y=Pp(z,v),b=Pp(z,f),x=Pp(z,g),C=w=Ip(_,y),k=S=Ip(b,x),(w>Dp||S>Dp)&&(M=i*Cp(l),T=i*Sp(l),A=r*Cp(s),I=r*Sp(s),hDp){var W=Pp(m,C),q=Pp(v,C),U=Lp(A,I,P,D,i,W,u),G=Lp(M,T,L,E,i,q,u);t.moveTo(c+U.cx+U.x0,d+U.cy+U.y0),C0&&t.arc(c+U.cx,d+U.cy,W,Mp(U.y0,U.x0),Mp(U.y1,U.x1),!u),t.arc(c,d,i,Mp(U.cy+U.y1,U.cx+U.x1),Mp(G.cy+G.y1,G.cx+G.x1),!u),q>0&&t.arc(c+G.cx,d+G.cy,q,Mp(G.y1,G.x1),Mp(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>Dp&&R)if(k>Dp){W=Pp(f,k),U=Lp(L,E,M,T,r,-(q=Pp(g,k)),u),G=Lp(P,D,A,I,r,-W,u);t.lineTo(c+U.cx+U.x0,d+U.cy+U.y0),k0&&t.arc(c+U.cx,d+U.cy,q,Mp(U.y0,U.x0),Mp(U.y1,U.x1),!u),t.arc(c,d,r,Mp(U.cy+U.y1,U.cx+U.x1),Mp(G.cy+G.y1,G.cx+G.x1),u),W>0&&t.arc(c+G.cx,d+G.cy,W,Mp(G.y1,G.x1),Mp(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 Rp=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},Np=function(t){function e(e){return t.call(this,e)||this}return v(e,t),e.prototype.getDefaultShape=function(){return new Rp},e.prototype.buildPath=function(t,e){Ep(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(Pu);Np.prototype.type="sector";var zp=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},Op=function(t){function e(e){return t.call(this,e)||this}return v(e,t),e.prototype.getDefaultShape=function(){return new zp},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}(Pu);function $p(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;hsf[1]){if(r=!1,lf.negativeSize||n)return r;var s=of(sf[0]-af[1]),l=of(af[0]-sf[1]);nf(s,l)>df.len()&&(s=l||!lf.bidirectional)&&(Do.scale(cf,a,-l*i),lf.useDir&&lf.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 mf(t,e,n,i,r,o){gf("update",t,e,n,i,r,o)}function vf(t,e,n,i,r,o){gf("enter",t,e,n,i,r,o)}function _f(t){if(!t.__zr)return!0;for(var e=0;e=-1e-6)return!1;var f=t-r,g=e-o,m=$f(f,g,c,d)/p;if(m<0||m>1)return!1;var v=$f(f,g,u,h)/p;return!(v<0||v>1)}function $f(t,e,n,i){return t*i-n*e}function Hf(t,e,n,i,r){return null==e||(mr(e)?Ff[0]=Ff[1]=Ff[2]=Ff[3]=e:(Ff[0]=e[0],Ff[1]=e[1],Ff[2]=e[2],Ff[3]=e[3]),i&&(Ff[0]=ec(0,Ff[0]),Ff[1]=ec(0,Ff[1]),Ff[2]=ec(0,Ff[2]),Ff[3]=ec(0,Ff[3])),n&&(Ff[0]=-Ff[0],Ff[1]=-Ff[1],Ff[2]=-Ff[2],Ff[3]=-Ff[3]),Bf(t,Ff,"x","width",3,1,r&&r[0]||0),Bf(t,Ff,"y","height",0,2,r&&r[1]||0)),t}var Ff=[0,0,0,0];function Bf(t,e,n,i,r,o,a){var s=e[o]+e[r],l=t[i];t[i]+=s,a=ec(0,tc(a,l)),t[i]=0?-e[r]:e[o]>=0?l+e[o]:nc(s)>1e-8?(l-a)*e[r]/s:0):t[n]-=e[r]}function Vf(t){var e=t.itemTooltipOption,n=t.componentModel,i=t.itemName,r=fr(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&&or(cr(l),function(t){$r(s,t)||(s[t]=l[t],s.$vars.push(t))});var c=oh(t.el);c.componentMainType=o,c.componentIndex=a,c.tooltipConfig={name:i,option:er({content:i,encodeHTMLContent:!0,formatterParams:s},r)}}function jf(t,e){var n;t.isGroup&&(n=e(t)),n||t.traverse(e)}function Wf(t,e){if(t)if(hr(t))for(var n=0;ne&&(e=i),ie&&(n=e=0),{min:n,max:e}},clipPointsByRect:function(t,e){return ar(t,function(t){var n=t[0];n=ec(n,e.x),n=tc(n,e.x+e.width);var i=t[1];return i=ec(i,e.y),[n,i=tc(i,e.y+e.height)]})},clipRectByRect:function(t,e){var n=ec(t.x,e.x),i=tc(t.x+t.width,e.x+e.width),r=ec(t.y,e.y),o=tc(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:zf,ensureCopyRect:Gf,ensureCopyTransform:Xf,expandOrShrinkRect:Hf,extendPath:function(t,e){return Cf(t,e)},extendShape:function(t){return Pu.extend(t)},getShapeClass:function(t){if(xf.hasOwnProperty(t))return xf[t]},getTransform:function(t,e){for(var n=ko([]);t&&t!==e;)To(n,t.getLocalTransform(),n),t=t.parent;return n},groupTransition:Nf,initProps:vf,isBoundingRectAxisAligned:qf,isElementRemoved:_f,lineLineIntersect:Of,linePolygonIntersect:function(t,e,n,i,r){for(var o=0,a=r[r.length-1];onc(o[1])?o[0]>0?"right":"left":o[1]>0?"bottom":"top"},traverseElements:Wf,traverseUpdateZ:Zf,updateProps:mf}),Jf={};function tg(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=pr(t.defaultText)?t.defaultText(o,t,n):t.defaultText);for(var l={normal:i},c=0;c-1?Mg:Ag;function Lg(t,e){t=t.toUpperCase(),Pg[t]=new Sg(e),Ig[t]=e}Lg(Tg,{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:". "}}}}),Lg(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 Eg(){return null}var Rg=1e3,Ng=6e4,zg=36e5,Og=864e5,$g=31536e6,Hg={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})/},Fg={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}"},Bg="{yyyy}-{MM}-{dd}",Vg={year:"{yyyy}",month:"{yyyy}-{MM}",day:Bg,hour:Bg+" "+Fg.hour,minute:Bg+" "+Fg.minute,second:Bg+" "+Fg.second,millisecond:"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}"},jg=["year","month","day","hour","minute","second","millisecond"],Wg=["year","half-year","quarter","month","week","half-week","day","half-day","quarter-day","hour","minute","second","millisecond"];function qg(t){return fr(t)||pr(t)?t:function(t){t=t||{};var e={},n=!0;return or(jg,function(e){n&&(n=null==t[e])}),or(jg,function(i,r){var o=t[i];e[i]={};for(var a=null,s=r;s>=0;s--){var l=jg[s],c=vr(o)&&!hr(o)?o[l]:o,d=void 0;hr(c)?a=(d=c.slice())[0]||"":fr(c)?d=[a=c]:(null==a?a=Fg[i]:Hg[l].test(a)||(a=e[l][l][0]+" "+a),d=[a],n&&(d[1]="{primary|"+a+"}")),e[i][l]=d}}),e}(t)}function Ug(t,e){return"0000".substr(0,e-(t+="").length)+t}function Gg(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 Xg(t){return t===Gg(t)}function Yg(t,e,n,i){var r=hc(t),o=r[Qg(n)](),a=r[Jg(n)]()+1,s=Math.floor((a-1)/3)+1,l=r[tm(n)](),c=r["get"+(n?"UTC":"")+"Day"](),d=r[em(n)](),u=(d-1)%12+1,h=r[nm(n)](),p=r[im(n)](),f=r[rm(n)](),g=d>=12?"pm":"am",m=g.toUpperCase(),v=i instanceof Sg?i:function(t){return Pg[t]}(i||Dg)||Pg[Ag],_=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,Ug(o%100+"",2)).replace(/{Q}/g,s+"").replace(/{MMMM}/g,y[a-1]).replace(/{MMM}/g,b[a-1]).replace(/{MM}/g,Ug(a,2)).replace(/{M}/g,a+"").replace(/{dd}/g,Ug(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,x[c]).replace(/{ee}/g,w[c]).replace(/{e}/g,c+"").replace(/{HH}/g,Ug(d,2)).replace(/{H}/g,d+"").replace(/{hh}/g,Ug(u+"",2)).replace(/{h}/g,u+"").replace(/{mm}/g,Ug(h,2)).replace(/{m}/g,h+"").replace(/{ss}/g,Ug(p,2)).replace(/{s}/g,p+"").replace(/{SSS}/g,Ug(f,3)).replace(/{S}/g,f+"")}function Zg(t,e){var n=hc(t),i=n[Jg(e)]()+1,r=n[tm(e)](),o=n[em(e)](),a=n[nm(e)](),s=n[im(e)](),l=0===n[rm(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 Kg(t,e,n){switch(e){case"year":t[am(n)](0);case"month":t[sm(n)](1);case"day":t[lm(n)](0);case"hour":t[cm(n)](0);case"minute":t[dm(n)](0);case"second":t[um(n)](0)}return t}function Qg(t){return t?"getUTCFullYear":"getFullYear"}function Jg(t){return t?"getUTCMonth":"getMonth"}function tm(t){return t?"getUTCDate":"getDate"}function em(t){return t?"getUTCHours":"getHours"}function nm(t){return t?"getUTCMinutes":"getMinutes"}function im(t){return t?"getUTCSeconds":"getSeconds"}function rm(t){return t?"getUTCMilliseconds":"getMilliseconds"}function om(t){return t?"setUTCFullYear":"setFullYear"}function am(t){return t?"setUTCMonth":"setMonth"}function sm(t){return t?"setUTCDate":"setDate"}function lm(t){return t?"setUTCHours":"setHours"}function cm(t){return t?"setUTCMinutes":"setMinutes"}function dm(t){return t?"setUTCSeconds":"setSeconds"}function um(t){return t?"setUTCMilliseconds":"setMilliseconds"}function hm(t){if(isNaN(gc(t)))return fr(t)?t:"-";var e=(t+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function pm(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 fm=Tr;function gm(t,e,n){function i(t){return t&&Ir(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?hc(t):t;if(!isNaN(+s))return Yg(s,"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}",n);if(a)return"-"}if("ordinal"===e)return gr(t)?i(t):mr(t)&&r(t)?t+"":"-";var l=gc(t);return r(l)?hm(l):gr(t)?i(t):"boolean"==typeof t?t+"":"-"}var mm=["a","b","c","d","e","f","g"],vm=function(t,e){return"{"+t+(null==e?"":e)+"}"};function _m(t,e,n){hr(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 Rm(t,e,n){n=fm(n||0);var i=e.width,r=e.height,o=rc(t.left,i),a=rc(t.top,r),s=rc(t.right,i),l=rc(t.bottom,r),c=rc(t.width,i),d=rc(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 qo((e.x||0)+o+n[3],(e.y||0)+a+n[0],c,d);return f.margin=n,f}ur(Em,"vertical"),ur(Em,"horizontal");var Nm=1;function zm(t,e,n){var i,r,o,a,s=t.boxCoordinateSystem;if(s){var l=function(t){var e=t.getShallow("coord",!0),n=Sm;if(null==e){var i=km.get(t.type);i&&i.getCoord2&&(n=Cm,e=i.getCoord2(t))}return{coord:e,from:n}}(t),c=l.coord,d=l.from;if(s.dataToLayout){o=Nm,a=d;var u=s.dataToLayout(c);i=u.contentRect||u.rect}}return null==o&&(o=Nm),o===Nm&&(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 Om(t){var e=t.layoutMode||t.constructor.layoutMode;return vr(e)?e:e?{type:e}:null}function $m(t,e,n){var i=n&&n.ignoreSize;!hr(i)&&(i=[i,i]);var r=a(Lm[0],0),o=a(Lm[1],1);function a(n,r){var o={},a=0,l={},c=0;if(Pm(n,function(e){l[e]=t[e]}),Pm(n,function(t){$r(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=Ji(o,n[a],!0);e.defaultOption=o}return e.defaultOption},e.prototype.getReferringComponents=function(t,e){var n=t+"Index",i=t+"Id";return Bc(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}(Sg);Gc(Bm,Sg),Kc(Bm),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){var i=qc(t);e[i.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var o=qc(n).main;t.hasSubTypes(n)&&e[o]&&(r=e[o](i))}return r}}(Bm),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 or(t,function(o){var a=n(i,o),s=function(t,e){var n=[];return or(t,function(t){nr(e,t)>=0&&n.push(t)}),n}(a.originalDeps=e(o),t);a.entryCount=s.length,0===a.entryCount&&r.push(o),or(s,function(t){nr(a.predecessor,t)<0&&a.predecessor.push(t);var e=n(i,t);nr(e.successor,t)<0&&e.successor.push(o)})}),{graph:i,noEntryList:r}}(i),s=a.graph,l=a.noEntryList,c={};for(or(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]),or(u.successor,h?f:p)}or(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)}}}(Bm,function(t){var e=[];or(Bm.getClassesByMainType(t),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=ar(e,function(t){return qc(t).main}),"dataset"!==t&&nr(e,"dataset")<=0&&e.unshift("dataset");return e});var Vm={color:{},darkColor:{},size:{}},jm=Vm.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 Wm in tr(jm,{primary:jm.neutral80,secondary:jm.neutral70,tertiary:jm.neutral60,quaternary:jm.neutral50,disabled:jm.neutral20,border:jm.neutral30,borderTint:jm.neutral20,borderShade:jm.neutral40,background:jm.neutral05,backgroundTint:"rgba(234,237,245,0.5)",backgroundTransparent:"rgba(255,255,255,0)",backgroundShade:jm.neutral10,shadow:"rgba(0,0,0,0.2)",shadowTint:"rgba(129,130,136,0.2)",axisLine:jm.neutral70,axisLineTint:jm.neutral40,axisTick:jm.neutral70,axisTickMinor:jm.neutral60,axisLabel:jm.neutral70,axisSplitLine:jm.neutral15,axisMinorSplitLine:jm.neutral05}),jm)if(jm.hasOwnProperty(Wm)){var qm=jm[Wm];"theme"===Wm?Vm.darkColor.theme=jm.theme.slice():"highlight"===Wm?Vm.darkColor.highlight="rgba(255,231,130,0.4)":0===Wm.indexOf("accent")?Vm.darkColor[Wm]=ss(qm,0,function(t){return.5*t},function(t){return Math.min(1,1.3-t)}):Vm.darkColor[Wm]=ss(qm,0,function(t){return.9*t},function(t){return 1-Math.pow(t,1.5)})}Vm.size={xxs:2,xs:5,s:10,m:15,l:20,xl:30,xxl:40,xxxl:50};var Um="";"undefined"!=typeof navigator&&(Um=navigator.platform||"");var Gm="rgba(0, 0, 0, 0.2)",Xm=Vm.color.theme[0],Ym=ss(Xm,0,null,.9),Zm={darkMode:"auto",colorBy:"series",color:Vm.color.theme,gradientColor:[Ym,Xm],aria:{decal:{decals:[{color:Gm,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:Gm,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:Gm,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:Gm,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:Gm,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:Gm,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:Um.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},Km=zr(["tooltip","label","itemName","itemId","itemGroupId","itemChildGroupId","seriesName"]),Qm="original",Jm="arrayRows",tv="objectRows",ev="keyedColumns",nv="typedArray",iv="unknown",rv="column",ov="row",av=1,sv=2,lv=3,cv=zc();function dv(t,e,n){var i={},r=uv(e);if(!r||!t)return i;var o,a,s=[],l=[],c=e.ecModel,d=cv(c).datasetMap,u=r.uid+"_"+n.seriesLayoutBy;or(t=t.slice(),function(e,n){var r=vr(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,fv,i,r,t,e,n)},t.prototype.clearColorPalette=function(){!function(t,e){e(t).paletteIdx=0,e(t).paletteNameMap={}}(this,fv)},t}();var yv="\0_ec_inner",bv=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 Sg(i),this._locale=new Sg(r),this._optionManager=o},e.prototype.setOption=function(t,e,n){var i=Sv(e);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,e){return this._resetOption(t,Sv(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)):vv(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&&or(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=zr(),s=e&&e.replaceMergeMainTypeMap;cv(this).datasetMap=zr(),or(t,function(t,e){null!=t&&(Bm.hasClass(e)?e&&(o.push(e),a.set(e,!0)):n[e]=null==n[e]?Qi(t):Ji(n[e],t,!0))}),s&&s.each(function(t,e){Bm.hasClass(e)&&!a.get(e)&&(o.push(e),a.set(e,!0))}),Bm.topologicalTravel(o,Bm.getAllClassMainTypes(),function(e){var o=function(t,e,n){var i=pv.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=Ic(a,o,l);(function(t,e,n){or(t,function(t){var i=t.newOption;vr(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,Bm),n[e]=null,i.set(e,null),r.set(e,0);var d,u=[],h=[],p=0;or(c,function(t,n){var i=t.existing,r=t.newOption;if(r){var o="series"===e,a=Bm.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=tr({componentIndex:n},t.keyInfo);tr(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&&gv(this)},this),this._seriesIndices||gv(this)},e.prototype.getOption=function(){var t=Qi(this.option);return or(t,function(e,n){if(Bm.hasClass(n)){for(var i=Cc(e),r=i.length,o=!1,a=r-1;a>=0;a--)i[a]&&!Rc(i[a])?o=!0:(i[a]=null,!o&&r--);i.length=r,t[n]=i}}),delete t[yv],t},e.prototype.setTheme=function(t){this._theme=new Sg(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 Iv=or,Pv=vr,Dv=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function Lv(t){var e=t&&t.itemStyle;if(e)for(var n=0,i=Dv.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 x_(this.getData(e),t)},t.prototype.formatTooltip=function(t,e,n){},t}();function C_(t){var e,n;return vr(t)?t.type&&(n=t):e=t,{text:e,frag:n}}function k_(t){return new M_(t)}var M_=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}(),P_=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 A_(t,e)},t}();function D_(t){if(!O_(t.sourceFormat)){xc("")}return t.data}function L_(t){var e=t.sourceFormat,n=t.data;if(!O_(e)){xc("")}if(e===Jm){for(var i=[],r=0,o=n.length;r65535?F_:B_}function U_(){return[1/0,-1/0]}function G_(t){var e=t.constructor;return e===Array?t.slice():new e(t)}function X_(t,e,n,i,r){var o=W_[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=ar(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(q_(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 A_(t[i],this._dimensions[i])}$_={arrayRows:t,objectRows:function(t,e,n,i){return A_(t[e],this._dimensions[i])},keyedColumns:t,original:function(t,e,n,i){var r=t&&(null==t.value?t:t.value);return A_(r instanceof Array?r[i]:r,this._dimensions[i])},typedArray:function(t,e,n,i){return t[i]}}}(),t}(),Z_=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(K_(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=yr(a=o.get("data",!0))?nv:Qm,e=[];var d=this._getSourceMetaRawOption()||{},u=l&&l.metaRawOption||{},h=Cr(d.seriesLayoutBy,u.seriesLayoutBy)||null,p=Cr(d.sourceHeader,u.sourceHeader),f=Cr(d.dimensions,u.dimensions);t=h!==u.seriesLayoutBy||!!p!=!!u.sourceHeader||f?[i_(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=[i_(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&&Q_("")}var o,a=[],s=[];return or(t,function(t){t.prepareSource();var e=t.getSource(r||0);null==r||e||Q_(""),a.push(e),s.push(t._getVersionSign())}),i?e=function(t,e){var n=Cc(t),i=n.length;i||xc("");for(var r=0,o=i;r1||n>0&&!t.noHeader;return or(t.blocks,function(t){var n=ay(t);n>=e&&(e=n+ +(i&&(!n||ry(t)&&!t.noHeader)))}),e}return 0}function sy(t,e,n,i){var r,o=e.noHeader,a=(r=ay(e),{html:ey[r],richText:ny[r]}),s=[],l=e.blocks||[];Ar(!l||hr(l)),l=l||[];var c=t.orderMode;if(e.sortBlocks&&c){l=l.slice();var d={valueAsc:"asc",valueDesc:"desc"};if($r(d,c)){var u=new I_(d[c],null);l.sort(function(t,e){return u.evaluate(t.sortParam,e.sortParam)})}else"seriesDesc"===c&&l.reverse()}or(l,function(n,r){var o=e.valueFormatter,l=oy(n)(o?tr(tr({},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):dy(i,s.join(""),o?n:a.html);if(o)return h;var p=gm(e.header,"ordinal",t.useUTC),f=ty(i,t.renderMode).nameStyle,g=J_(i);return"richText"===t.renderMode?uy(t,p,f)+a.richText+h:dy(i,'
'+ho(p)+"
"+h,n)}function ly(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 ar(t=hr(t)?t:[t],function(t,e){return gm(t,hr(p)?p[e]:p,c)})};if(!o||!a){var u=s?"":t.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||Vm.color.secondary,r),h=o?"":gm(l,"ordinal",c),p=e.valueType,f=a?[]:d(e.value,e.dataIndex),g=!s||!o,m=!s&&o,v=ty(i,r),_=v.nameStyle,y=v.valueStyle;return"richText"===r?(s?"":u)+(o?"":uy(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(hr(e)?e.join(" "):e,o)}(t,f,g,m,y)):dy(i,(s?"":u)+(o?"":function(t,e,n){return''+ho(t)+""}(h,!s,_))+(a?"":function(t,e,n,i){var r=n?"10px":"20px",o=e?"float:right;margin-left:"+r:"";return t=hr(t)?t:[t],''+ar(t,function(t){return ho(t)}).join("  ")+""}(f,g,m,y)),n)}}function cy(t,e,n,i,r,o){if(t)return oy(t)({useUTC:r,renderMode:n,orderMode:i,markupStyleCreator:e,valueFormatter:t.valueFormatter},t,0,o)}function dy(t,e,n){return'
'+e+'
'}function uy(t,e,n){return t.markupStyleCreator.wrapRichTextStyle(e,n)}function hy(t,e){var n=t.get("padding");return null!=n?n:"richText"===e?[8,10]:10}var py=function(){function t(){this.richTextStyles={},this._nextStyleNameId=mc()}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=fr(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 fr(r)?r:(this.richTextStyles[i]=r.style,r.content)},t.prototype.wrapRichTextStyle=function(t,e){var n={};hr(e)?or(e,function(t){return tr(n,t)}):tr(n,e);var i=this._generateStyleName();return this.richTextStyles[i]=n,"{"+i+"|"+t+"}"},t}();function fy(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=hr(u),p=function(t,e){return ym(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=sr(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(iy("nameValue",{markerType:"subItem",markerColor:r,name:n.displayName,value:t,valueType:n.type})):(s.push(t),l.push(n.type)))}return i.length?or(i,function(t){d(x_(o,n,t),t)}):or(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=x_(l,a,c[0]),n=g.type}else r=e=h?u[0]:u;var m=Ec(o),v=m&&o.name||"",_=l.getName(a),y=s?v:_;return iy("section",{header:v,noHeader:s||!m,sortParam:r,blocks:[iy("nameValue",{markerType:"item",markerColor:p,name:y,noName:!Ir(y),value:e,valueType:n,dataIndex:a})].concat(i||[])})}var gy=zc();function my(t,e){return t.getName(e)||t.getId(e)}var vy=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=k_({count:yy,reset:by}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),(gy(this).sourceManager=new Z_(this)).prepareSource();var i=this.getInitialData(t,n);wy(i,this),this.dataTask.context.data=i,gy(this).dataBeforeProcessed=i,_y(this),this._initSelectedMapFromData(i)},e.prototype.mergeDefaultAndTheme=function(t,e){var n=Om(this),i=n?Hm(t):{},r=this.subType;Bm.hasClass(r)&&(r+="Series"),Ji(t,e.getTheme().get(this.subType)),Ji(t,this.getDefaultOption()),kc(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&$m(t,i,n)},e.prototype.mergeOption=function(t,e){t=Ji(this.option,t,!0),this.fillDataTextStyle(t.data);var n=Om(this);n&&$m(this.option,t,n);var i=gy(this).sourceManager;i.dirty(),i.prepareSource();var r=this.getInitialData(t,e);wy(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,gy(this).dataBeforeProcessed=r,_y(this),this._initSelectedMapFromData(r)},e.prototype.fillDataTextStyle=function(t){if(t&&!yr(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 fy({series:this,dataIndex:t,multipleSeries:e})},e.prototype.isAnimationEnabled=function(){var t=this.ecModel;if(Di.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=_v.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[my(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){vr(r.selectedMap)||(r.selectedMap={});for(var s=r.selectedMap,l=0;l0&&this._innerSelect(t,e)}},e.registerClass=function(t){return Bm.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}(Bm);function _y(t){var e=t.name;Ec(t)||(t.name=function(t){var e=t.getRawData(),n=e.mapDimensionsAll("seriesName"),i=[];return or(n,function(t){var n=e.getDimensionInfo(t);n.displayName&&i.push(n.displayName)}),i.join(" ")}(t)||e)}function yy(t){return t.model.getRawData().count()}function by(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),xy}function xy(t,e){e.outputData&&t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function wy(t,e){or(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 Hy(t,e,n,i){var r=t[e];if(r){var o=r[Ny]||r,a=r[Oy];if(r[zy]!==n||a!==i){if(null==n||!i)return t[e]=o;(r=t[e]=$y(o,n,"debounce"===i))[Ny]=o,r[Oy]=i,r[zy]=n}return r}}function Fy(t,e){var n=t[e];n&&n[Ny]&&(n.clear&&n.clear(),t[e]=n[Ny])}var By=zc(),Vy={itemStyle:Qc(bg,!0),lineStyle:Qc(vg,!0)},jy={lineStyle:"stroke",itemStyle:"fill"};function Wy(t,e){var n=t.visualStyleMapper||Vy[e];return n||(console.warn("Unknown style type '"+e+"'."),Vy.itemStyle)}function qy(t,e){var n=t.visualDrawType||jy[e];return n||(console.warn("Unknown style type '"+e+"'."),"fill")}var Uy={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=t.getModel(i),o=Wy(t,i)(r),a=r.getShallow("decal");a&&(n.setVisual("decal",a),a.dirty=!0);var s=qy(t,i),l=o[s],c=pr(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||pr(o.fill)?u:o.fill,o.stroke="auto"===o.stroke||pr(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=tr({},o);r[s]=c(i),e.setItemVisual(n,"style",r)}}}},Gy=new Sg,Xy={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){if(!t.ignoreStyleOnData&&!e.isSeriesFiltered(t)){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=Wy(t,i),o=n.getVisual("drawType");return{dataEach:n.hasItemOption?function(t,e){var n=t.getRawDataItem(e);if(n&&n[i]){Gy.option=n[i];var a=r(Gy);tr(t.ensureUniqueItemVisual(e,"style"),a),Gy.option.decal&&(t.setItemVisual(e,"decal",Gy.option.decal),Gy.option.decal.dirty=!0),o in a&&t.setItemVisual(e,"colorFromPalette",!1)}}:null}}}},Yy={performRawSeries:!0,overallReset:function(t){var e=zr();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)),By(t).scope=r}}),t.eachSeries(function(e){if(!e.isColorBySeries()&&!t.isSeriesFiltered(e)){var n=e.getRawData(),i={},r=e.getData(),o=By(e).scope,a=e.visualStyleAccessPath||"itemStyle",s=qy(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)}})}})}},Zy=Math.PI;var Ky=function(){function t(t,e,n,i){this._stageTaskMap=zr(),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=zr();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;or(this._allHandlers,function(i){var r=t.get(i.uid)||t.set(i.uid,{});Ar(!(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))}or(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=zr(),s=t.seriesType,l=t.getTargetSeries;function c(e){var s=e.uid,l=a.set(s,o&&o.get(s)||k_({plan:nb,reset:ib,count:ab}));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||k_({reset:Qy});o.context={ecModel:n,api:i,overallReset:t.overallReset,scheduler:r};var a=o.agentStubMap,s=o.agentStubMap=zr(),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,k_({reset:Jy,onDirty:eb})));n.context={model:t,overallProgress:d},n.agent=o,n.__block=d,r._pipe(t,n)}Ar(!t.createOnAllSeries,""),l?n.eachRawSeriesByType(l,h):c?c(n,i).each(h):(d=!1,or(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 pr(t)&&(t={overallReset:t,seriesType:sb(t)}),t.uid=kg("stageHandler"),e&&(t.visualType=e),t},t}();function Qy(t){t.overallReset(t.ecModel,t.api,t.payload)}function Jy(t){return t.overallProgress&&tb}function tb(){this.agent.dirty(),this.getDownstream().dirty()}function eb(){this.agent&&this.agent.dirty()}function nb(t){return t.plan?t.plan(t.model,t.ecModel,t.api,t.payload):null}function ib(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?ar(e,function(t,e){return ob(e)}):rb}var rb=ob(0);function ob(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}(),yb=["symbol","symbolSize","symbolRotate","symbolOffset"],bb=yb.concat(["symbolKeepAspect"]),xb={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&&$b(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=$b(i)?i:0,r=$b(r)?r:1,o=$b(o)?o:0,a=$b(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]:mr(e)?[e]:hr(e)?e:null:null),o=i.lineDashOffset;if(r){var a=i.strokeNoScale&&t.getLineScale?t.getLineScale():1;a&&1!==a&&(r=ar(r,function(t){return t/a}),o/=a)}return[r,o]}var jb=new cu(!0);function Wb(t){var e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))}function qb(t){return"string"==typeof t&&"none"!==t}function Ub(t){var e=t.fill;return null!=e&&"none"!==e}function Gb(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 Xb(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 Yb(t,e,n){var i=id(e.image,e.__image,n);if(od(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)*Fr),o.scaleSelf(e.scaleX||1,e.scaleY||1),r.setTransform(o)}return r}}var Zb=["shadowBlur","shadowOffsetX","shadowOffsetY"],Kb=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function Qb(t,e,n,i,r){var o=!1;if(!i&&e===(n=n||{}))return!1;if(i||e.opacity!==n.opacity){ex(t,r),o=!0;var a=Math.max(Math.min(e.opacity,1),0);t.globalAlpha=isNaN(a)?kd.opacity:a}(i||e.blend!==n.blend)&&(o||(ex(t,r),o=!0),t.globalCompositeOperation=e.blend||kd.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[mx])if(this._disposed)this.id;else{var i,r,o;if(vr(e)&&(n=e.lazyUpdate,i=e.silent,r=e.replaceMerge,o=e.transition,e=e.notMerge),this[mx]=!0,Wx(this),!this._model||e){var a=new Tv(this._api),s=this._theme,l=this._model=new bv;l.scheduler=this._scheduler,l.ssr=this._ssr,l.init(null,null,null,s,this._locale,a)}this._model.setOption(t,{replaceMerge:r},tw);var c={seriesTransition:o,optionChanged:!0};if(n)this[_x]={silent:i,updateParams:c},this[mx]=!1,this.getZr().wakeUp();else{try{Mx(this),Ix.update.call(this,null,c)}catch(t){throw this[_x]=null,this[mx]=!1,t}this._ssr||this._zr.flush(),this[_x]=null,this[mx]=!1,Ex.call(this,i),Rx.call(this,i)}}},e.prototype.setTheme=function(t,e){if(!this[mx])if(this._disposed)this.id;else{var n=this._model;if(n){var i=e&&e.silent,r=null;this[_x]&&(null==i&&(i=this[_x].silent),r=this[_x].updateParams,this[_x]=null),this[mx]=!0,Wx(this);try{this._updateTheme(t),n.setTheme(this._theme),Mx(this),Ix.update.call(this,{type:"setTheme"},r)}catch(t){throw this[mx]=!1,t}this[mx]=!1,Ex.call(this,i),Rx.call(this,i)}}},e.prototype._updateTheme=function(t){fr(t)&&(t=nw[t]),t&&((t=Qi(t))&&Xv(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||Di.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 or(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;or(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 or(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(ow[n]){var a=o,s=o,l=-1/0,c=-1/0,d=[],u=t&&t.pixelRatio||this.getDevicePixelRatio();or(rw,function(o,u){if(o.group===n){var h=e?o.getZr().painter.getSvgDom().innerHTML:o.renderToCanvas(Qi(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=Oi.createCanvas(),g=Ql(f,{renderer:e?"svg":"canvas"});if(g.resize({width:h,height:p}),e){var m="";return or(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 Vu({shape:{x:0,y:0,width:h,height:p},style:{fill:t.connectedBackgroundColor}})),or(d,function(t){var e=new Nu({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 Px(this,"convertToPixel",t,e,n)},e.prototype.convertToLayout=function(t,e,n){return Px(this,"convertToLayout",t,e,n)},e.prototype.convertFromPixel=function(t,e,n){return Px(this,"convertFromPixel",t,e,n)},e.prototype.containPixel=function(t,e){var n;if(!this._disposed)return or($c(this._model,t),function(t,i){i.indexOf("Models")>=0&&or(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=$c(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;or(Yx,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=oh(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=tr({},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;or(Qx,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?(Sb("map","selectchanged",e,i,t),Sb("pie","selectchanged",e,i,t)):"select"===t.fromAction?(Sb("map","selected",e,i,t),Sb("pie","selected",e,i,t)):"unselect"===t.fromAction&&(Sb("map","unselected",e,i,t),Sb("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()&&Vc(this.getDom(),sw,"");var t=this,e=t._api,n=t._model;or(t._componentsViews,function(t){t.dispose(n,e)}),or(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 rw[t.id]}},e.prototype.resize=function(t){if(!this[mx])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[_x]&&(null==i&&(i=this[_x].silent),n=!0,this[_x]=null),this[mx]=!0,Wx(this);try{n&&Mx(this),Ix.update.call(this,{type:"resize",animation:tr({duration:0},t&&t.animation)})}catch(t){throw this[mx]=!1,t}this[mx]=!1,Ex.call(this,i),Rx.call(this,i)}}},e.prototype.showLoading=function(t,e){if(this._disposed)this.id;else if(vr(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),iw[t]){var n=iw[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=tr({},t);return e.type=Kx[t.type],e},e.prototype.dispatchAction=function(t,e){if(this._disposed)this.id;else if(vr(e)||(e={silent:!!e}),Zx[t.type]&&this._model)if(this[mx])this._pendingActions.push(t);else{var n=e.silent;Lx.call(this,t,n);var i=e.flush;i?this._zr.flush():!1!==i&&Di.browser.weChat&&this._throttledZrFlush(),Ex.call(this,n),Rx.call(this,n)}},e.prototype.updateLabelLayout=function(){ux.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(_f(t))return;if(t instanceof Pu&&function(t){var e=lh(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)}})}Mx=function(t){var e=t._scheduler;e.restorePipelines(t._model),e.prepareStageTasks(),Tx(t,!0),Tx(t,!1),e.plan()},Tx=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")&&!Di.node&&!Di.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),ux.trigger("series:afterupdate",e,o,s)},Vx=function(t){t[yx]=!0,t.getZr().wakeUp()},Wx=function(t){t[vx]=(t[vx]+1)%1e3},jx=function(t){t[yx]&&(t.getZr().storage.traverse(function(t){_f(t)||e(t)}),t[yx]=!1)},Fx=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){Eh(e,n),Vx(t)},n.prototype.leaveEmphasis=function(e,n){Rh(e,n),Vx(t)},n.prototype.enterBlur=function(e){!function(t){Th(t,wh)}(e),Vx(t)},n.prototype.leaveBlur=function(e){Nh(e),Vx(t)},n.prototype.enterSelect=function(e){zh(e),Vx(t)},n.prototype.leaveSelect=function(e){Oh(e),Vx(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[vx]},n}(kv))(t)},Bx=function(t){function e(t,e){for(var n=0;n=0)){gw.push(n);var o=Ky.wrapStageHandler(n,r);o.__prio=e,o.__raw=n,t.push(o)}}function vw(t,e){iw[t]=e}var _w=function(t){var e=(t=Qi(t)).type;e||xc("");var n=e.split(":");2!==n.length&&xc("");var i=!1;"echarts"===n[0]&&(e=n[1],i=!0),t.__isBuiltIn=i,N_.set(e,t)};function yw(t,e,n,i){return{eventContent:{selected:Wh(n),isFromClick:e.isFromClick||!1}}}function bw(t){return null==t?0:t.length||1}function xw(t){return t}fw(px,Uy),fw(fx,Xy),fw(fx,Yy),fw(px,xb),fw(fx,wb),fw(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=sx(n,e))});var r=i.getVisual("decal");if(r)i.getVisual("style").decal=sx(r,e)}})}),dw(Xv),uw(900,function(t){var e=zr();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(),or(t,function(e,n){e.data.setCalculationInfo("stackedOnSeries",n>0?t[n-1].seriesModel:null)}),function(t){or(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=lc(p,v),f=v;break}}}return i[0]=p,i[1]=f,i})})}(t))})}),vw("default",function(t,e){er(e=e||{},{text:"loading",textColor:Vm.color.primary,fontSize:12,fontWeight:"normal",fontStyle:"normal",fontFamily:"sans-serif",maskColor:"rgba(255,255,255,0.8)",showSpinner:!0,color:Vm.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new Gl,i=new Vu({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});n.add(i);var r,o=new Uu({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 Vu({style:{fill:"none"},textContent:o,textConfig:{position:"right",distance:10},zlevel:e.zlevel,z:10001});return n.add(a),e.showSpinner&&((r=new Kp({shape:{startAngle:-Zy/2,endAngle:-Zy/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*Zy/2}).start("circularInOut"),r.animateShape(!0).when(1e3,{startAngle:3*Zy/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}),pw({type:hh,event:hh,update:hh},Hr),pw({type:ph,event:ph,update:ph},Hr),pw({type:fh,event:vh,update:fh,action:Hr,refineEvent:yw,publishNonRefinedEvent:!0}),pw({type:gh,event:vh,update:gh,action:Hr,refineEvent:yw,publishNonRefinedEvent:!0}),pw({type:mh,event:vh,update:mh,action:Hr,refineEvent:yw,publishNonRefinedEvent:!0}),cw("default",{}),cw("dark",vb);var ww=function(){function t(t,e,n,i,r,o){this._old=t,this._new=e,this._oldKeyGetter=n||xw,this._newKeyGetter=i||xw,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 Ew,Rw,Nw,zw,Ow,$w,Hw,Fw=vr,Bw=ar,Vw="undefined"==typeof Int32Array?Array:Int32Array,jw=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],Ww=["_approximateExtent"],qw=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;Iw(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===Qm&&!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&&(hr(r=this.getVisual(e))?r=r.slice():Fw(r)&&(r=tr({},r)),i[e]=r),r},t.prototype.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{};this._itemVisuals[t]=i,Fw(e)?tr(i,e):i[e]=n},t.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},t.prototype.setLayout=function(t,e){Fw(t)?tr(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?tr(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=oh(i);r.dataIndex=n,r.dataType=e,r.seriesIndex=t,r.ssrType="chart","group"===i.type&&i.traverse(function(i){var r=oh(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){or(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:Bw(this.dimensions,this._getDimInfo,this),this.hostModel)),Ow(e,this),e._store=this._store,e},t.prototype.wrapMethod=function(t,e){var n=this[t];pr(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=(Ew=function(t){var e=t._invertedIndicesMap;or(e,function(n,i){var r=t._dimInfos[i],o=r.ordinalMeta,a=t._store;if(o){n=e[i]=new Vw(o.categories.length);for(var s=0;s1&&(s+="__ec__"+c),i[e]=s}})),t}();function Uw(t,e){n_(t)||(t=r_(t));var n=(e=e||{}).coordDimensions||[],i=e.dimensionsDefine||t.dimensionsDefine||[],r=zr(),o=[],a=function(t,e,n,i){var r=Math.max(t.dimensionsDetectedCount||1,e.length,n.length,i||0);return or(e,function(t){var e;vr(t)&&(e=t.dimsDef)&&(r=Math.max(r,e.length))}),r}(t,n,i,e.dimensionsCount),s=e.canOmitUnusedDimensions&&Lw(a),l=i===t.dimensionsDefine,c=l?Dw(t):Pw(i),d=e.encodeDefine;!d&&e.encodeDefaulter&&(d=e.encodeDefaulter(t,a));for(var u=zr(d),h=new V_(a),p=0;p0&&(i.name=r+(o-1)),o++,e.set(r,o)}}(o),new Aw({source:t,dimensions:o,fullDimensionCount:a,dimensionOmitted:s})}function Gw(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 Xw=function(t){this.coordSysDims=[],this.axisMap=zr(),this.categoryAxisMap=zr(),this.coordSysName=t};var Yw={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis",Fc).models[0],o=t.getReferringComponents("yAxis",Fc).models[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",o),Zw(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),Zw(o)&&(i.set("y",o),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis",Fc).models[0];e.coordSysDims=["single"],n.set("single",r),Zw(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar",Fc).models[0],o=r.findAxisModel("radiusAxis"),a=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",o),n.set("angle",a),Zw(o)&&(i.set("radius",o),e.firstCategoryDimIndex=0),Zw(a)&&(i.set("angle",a),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},geo:function(t,e,n,i){e.coordSysDims=["lng","lat"]},parallel:function(t,e,n,i){var r=t.ecModel,o=r.getComponent("parallel",t.get("parallelIndex")),a=e.coordSysDims=o.dimensions.slice();or(o.parallelAxisIndex,function(t,o){var s=r.getComponent("parallelAxis",t),l=a[o];n.set(l,s),Zw(s)&&(i.set(l,s),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=o))})},matrix:function(t,e,n,i){var r=t.getReferringComponents("matrix",Fc).models[0];e.coordSysDims=["x","y"];var o=r.getDimensionModel("x"),a=r.getDimensionModel("y");n.set("x",o),n.set("y",a),i.set("x",o),i.set("y",a)}};function Zw(t){return"category"===t.get("type")}function Kw(t,e,n){var i,r,o,a=(n=n||{}).byIndex,s=n.stackedCoordDimension;!function(t){return!Iw(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(or(i,function(t,e){fr(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;or(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 Qw(t,e){return!!e&&e===t.getCalculationInfo("stackedDimension")}function Jw(t,e,n){n=n||{};var i,r,o=e.getSourceManager();r=(i=o.getSource()).sourceFormat===Qm;var a=function(t){var e=t.get("coordinateSystem"),n=new Xw(e),i=Yw[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}(e),s=function(t,e){var n,i=t.get("coordinateSystem"),r=wm.get(i);return e&&e.coordSysDims&&(n=ar(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=pr(l)?l:l?ur(dv,s,e):null,d=Uw(i,{coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:e.getEncode(),encodeDefaulter:c,canOmitUnusedDimensions:!r}),u=function(t,e,n){var i,r;return n&&or(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=Kw(e,{schema:d,store:h}),f=new qw(d,e);f.setCalculationInfo(p);var g=null!=u&&function(t){if(t.sourceFormat===Qm){var e=function(t){var e=0;for(;er&&(a=o.interval=r);var s=o.intervalPrecision=iS(a);return function(t,e){!isFinite(t[0])&&(t[0]=e[0]),!isFinite(t[1])&&(t[1]=e[1]),rS(t,0,e),rS(t,1,e),t[0]>t[1]&&(t[0]=t[1])}(o.niceTickExtent=[ac(Math.ceil(t[0]/a)*a,s),ac(Math.floor(t[1]/a)*a,s)],t),o}function nS(t){var e=Math.pow(10,pc(t)),n=t/e;return n?2===n?n=3:3===n?n=5:n*=2:n=1,ac(n*e)}function iS(t){return sc(t)+2}function rS(t,e,n){t[e]=Math.max(Math.min(t[e],n[1]),n[0])}function oS(t,e){return t>=e[0]&&t<=e[1]}var aS=function(){function t(){this.normalize=sS,this.scale=lS}return t.prototype.updateMethods=function(t){t.hasBreaks()?(this.normalize=dr(t.normalize,t),this.scale=dr(t.scale,t)):(this.normalize=sS,this.scale=lS)},t}();function sS(t,e){return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])}function lS(t,e){return t*(e[1]-e[0])+e[0]}function cS(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 dS=function(){function t(t){this._calculator=new aS,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}();Kc(dS);var uS=0,hS=function(){function t(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this.uid=++uS,this._onCollect=t.onCollect}return t.createByAxisModel=function(e){var n=e.option,i=n.data,r=i&&ar(i,pS);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(!fr(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=zr(this.categories))},t}();function pS(t){return vr(t)&&null!=t.value?t.value:t+""}var fS=function(t){function e(e){var n=t.call(this,e)||this;n.type="ordinal";var i=n.getSetting("ordinalMeta");return i||(i=new hS({})),hr(i)&&(i=new hS({categories:ar(i,function(t){return vr(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:fr(t)?this._ordinalMeta.getOrdinal(t):Math.round(t)},e.prototype.contain=function(t){return oS(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}(dS);dS.registerClass(fS);var gS=ac,mS=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 oS(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=iS(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=gS(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:gS(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 or(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=rc(t.get("barWidth"),i),p=rc(t.get("barMaxWidth"),i),f=rc(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:xS(r),stackId:bS(t)})}),function(t){var e={};or(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 or(e,function(t,e){n[e]={};var i=t.stacks,r=t.bandWidth,o=t.categoryGap;if(null==o){var a=cr(i).length;o=Math.max(35-4*a,15)+"%"}var s=rc(o,r),l=rc(t.gap,1),c=t.remainedWidth,d=t.autoWidthCount,u=(c-s)/(d+(d-1)*l);u=Math.max(u,0),or(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;or(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;or(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 SS=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 Yg(t.value,Vg[function(t){switch(t){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}(Gg(this._minLevelUnit))]||Vg.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(fr(n))o=n;else if(pr(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=Zg(t.value,r);o=n[d][d][0]}}return Yg(new Date(t.value),o,r,i)}(t,e,n,this.getSetting("locale"),i)},e.prototype.getTicks=function(t){var e=this._interval,n=this._extent,i=[];if(!e)return i;var r=this.getSetting("useUTC"),o=Zg(n[1],r);i.push({value:n[0],time:{level:0,upperTimeUnit:o,lowerTimeUnit:o}});var a=function(t,e,n,i,r,o){var a=1e4,s=Wg,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 Kg(new Date(e),t,i).getTime()===Kg(new Date(n),t,i).getTime()}(Gg(t),i[0],i[1],n)){s&&(r=[{value:PS(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=lr(ar(u,function(t){return lr(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 MS(t){return(t/=2592e6)>6?6:t>3?3:t>2?2:1}function TS(t){return(t/=zg)>12?12:t>6?6:t>3.5?4:t>2?2:1}function AS(t,e){return(t/=e?Ng:Rg)>30?30:t>20?20:t>15?15:t>10?10:t>5?5:t>2?2:1}function IS(t){return fc(t)}function PS(t,e,n){var i=Math.max(0,nr(jg,e)-1);return Kg(new Date(t),jg[i],n).getTime()}dS.registerClass(SS);var DS=ac,LS=Math.floor,ES=Math.ceil,RS=Math.pow,NS=Math.log,zS=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="log",e.base=10,e._originalScale=new mS,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(),ar(r,function(t){var e=t.value,r=null,a=RS(o,e);return e===n[0]&&this._fixMin?r=i[0]:e===n[1]&&this._fixMax&&(r=i[1]),null!=r&&(a=OS(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=cS(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]=RS(e,n[0]),n[1]=RS(e,n[1]);var i=this._originalScale.getExtent();return this._fixMin&&(n[0]=OS(n[0],i[0])),this._fixMax&&(n[1]=OS(n[1],i[1])),n},e.prototype.unionExtentFromData=function(t,e){this._originalScale.unionExtentFromData(t,e);var n=cS(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,pc(i)));for(t/n*r<=.5&&(r*=10);!isNaN(r)&&Math.abs(r)<1&&Math.abs(r)>0;)r*=10;var o=[DS(ES(e[0]/r)*r),DS(LS(e[1]/r)*r)];this._interval=r,this._intervalPrecision=iS(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=NS(e)/NS(this.base),t.prototype.contain.call(this,e)},e.prototype.normalize=function(e){return e=NS(e)/NS(this.base),t.prototype.normalize.call(this,e)},e.prototype.scale=function(e){return e=t.prototype.scale.call(this,e),RS(this.base,e)},e.prototype.setBreaksFromOption=function(t){},e.type="log",e}(mS);function OS(t,e){return DS(t,sc(e))}dS.registerClass(zS);var $S=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[FS[t]]=e},t.prototype.setDeterminedMinMax=function(t,e){this[HS[t]]=e},t.prototype.freeze=function(){this.frozen=!0},t}(),HS={min:"_determinedMin",max:"_determinedMax"},FS={min:"_dataMin",max:"_dataMax"};function BS(t,e){return null==e?null:wr(e)?NaN:t.parse(e)}function VS(t,e){var n=t.type,i=function(t,e,n){var i=t.rawExtentInfo;return i||(i=new $S(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(or(s,function(t){l=l||t.getBaseAxis()===e.axis}),l){var c=wS(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[xS(e)]}(i,n.axis);if(void 0===a)return{min:t,max:e};var s=1/0;or(a,function(t){s=Math.min(t.offset,s)});var l=-1/0;or(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 jS(t,e){var n=e,i=VS(t,n),r=i.extent,o=n.get("splitNumber");t instanceof zS&&(t.base=n.get("logBase"));var a=t.type,s=n.get("interval"),l="interval"===a||"time"===a;t.setBreaksFromOption(KS(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 WS(t){var e=t.getLabelModel().get("formatter");if("time"===t.type){var n=qg(e);return function(e,i){return t.scale.getFormattedLabel(e,i,n)}}if(fr(e))return function(n){var i=t.scale.getLabel(n);return e.replace("{value}",null!=i?i:"")};if(pr(e)){if("category"===t.type)return function(n,i){return e(qS(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(qS(t,n),r,o)}}return function(e){return t.scale.getLabel(e)}}function qS(t,e){return"category"===t.type?t.scale.getLabel(e):e.value}function US(t){var e=t.get("interval");return null==e?"auto":e}function GS(t){return"category"===t.type&&0===US(t.getLabelModel())}function XS(t,e){var n={};return or(t.mapDimensionsAll(e),function(e){n[function(t,e){return Qw(t,e)?t.getCalculationInfo("stackResultDimension"):e}(t,e)]=!0}),cr(n)}function YS(t){return"middle"===t||"center"===t}function ZS(t){return t.getShallow("show")}function KS(t){t.get("breaks",!0)}var QS=function(){function t(){}return t.prototype.getNeedCrossZero=function(){return!this.option.scale},t.prototype.getCoordSysModel=function(){},t}(),JS=[],tC={registerPreprocessor:dw,registerProcessor:uw,registerPostInit:function(t){hw("afterinit",t)},registerPostUpdate:function(t){hw("afterupdate",t)},registerUpdateLifecycle:hw,registerAction:pw,registerCoordinateSystem:function(t,e){wm.register(t,e)},registerLayout:function(t,e){mw(ew,t,e,1e3,"layout")},registerVisual:fw,registerTransform:_w,registerLoading:vw,registerMap:function(t,e,n){var i=hx["registerMap"];i&&i(t,e,n)},registerImpl:function(t,e){hx[t]=e},PRIORITY:gx,ComponentModel:Bm,ComponentView:ky,SeriesModel:vy,ChartView:Iy,registerComponentModel:function(t){Bm.registerClass(t)},registerComponentView:function(t){ky.registerClass(t)},registerSeriesModel:function(t){vy.registerClass(t)},registerChartView:function(t){Iy.registerClass(t)},registerCustomSeries:function(t,e){},registerSubTypeDefaulter:function(t,e){Bm.registerSubTypeDefaulter(t,e)},registerPainter:function(t,e){var n;n=e,Xl[t]=n}};function eC(t){hr(t)?or(t,function(t){eC(t)}):nr(JS,t)>=0||(JS.push(t),pr(t)&&(t={install:t}),t.install(tC))}var nC=zc(),iC=zc(),rC=1,oC=2;function aC(t){return{out:{noPxChangeTryDetermine:[]},kind:t}}function sC(t,e){var n=ar(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 lC(t,e){var n=t.getLabelModel().get("customValues");if(n){var i=WS(t),r=t.scale.getExtent();return{labels:ar(lr(sC(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=dC(t,n,e);return!n.get("show")||t.scale.isBlank()?{labels:[]}:i}(t,e):function(t){var e=t.scale.getTicks(),n=WS(t);return{labels:ar(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 cC(t,e,n){var i=t.getTickModel().get("customValues");if(i){var r=t.scale.getExtent();return{ticks:lr(sC(t,i),function(t){return t>=r[0]&&t<=r[1]})}}return"category"===t.type?function(t,e){var n,i,r=uC(t),o=US(e),a=fC(r,o);if(a)return a;e.get("show")&&!t.scale.isBlank()||(n=[]);if(pr(o))n=yC(t,o,!0);else if("auto"===o){var s=dC(t,t.getLabelModel(),aC(oC));i=s.labelCategoryInterval,n=ar(s.labels,function(t){return t.tickValue})}else n=_C(t,i=o,!0);return gC(r,o,{ticks:n,tickCategoryInterval:i})}(t,e):{ticks:ar(t.scale.getTicks(n),function(t){return t.value})}}function dC(t,e,n){var i,r,o=hC(t),a=US(e),s=n.kind===rC;if(!s){var l=fC(o,a);if(l)return l}pr(a)?i=yC(t,a):(r="auto"===a?function(t,e){if(e.kind===rC){var n=t.calculateCategoryInterval(e);return e.out.noPxChangeTryDetermine.push(function(){return iC(t).autoInterval=n,!0}),n}var i=iC(t).autoInterval;return null!=i?i:iC(t).autoInterval=t.calculateCategoryInterval(e)}(t,n):a,i=_C(t,r));var c={labels:i,labelCategoryInterval:r};return s?n.out.noPxChangeTryDetermine.push(function(){return gC(o,a,c),!0}):gC(o,a,c),c}var uC=pC("axisTick"),hC=pC("axisLabel");function pC(t){return function(e){return iC(e)[t]||(iC(e)[t]={list:[]})}}function fC(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 _C(t,e,n){var i=WS(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=GS(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 yC(t,e,n){var i=t.scale,r=WS(t),o=[];return or(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 bC=[0,1],xC=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(nc(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&&wC(n=n.slice(),i.count()),ic(t,bC,n,e)},t.prototype.coordToData=function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&wC(n=n.slice(),i.count());var r=ic(t,n,bC,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=ar(cC(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;or(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=ac(t),e=ac(e),u?t>e:t0&&t<100||(t=5),ar(this.scale.getMinorTicks(t),function(t){return ar(t,function(t){return{coord:this.dataToCoord(t),tickValue:t}},this)},this)},t.prototype.getViewLabels=function(t){return lC(this,t=t||aC(oC)).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=WS(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,_=Pl(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===rC)return e.out.noPxChangeTryDetermine.push(dr(mC,null,t,x,l)),x;var w=vC(t,x,l);return null!=w?w:x}(this,t=t||aC(oC))},t}();function wC(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}var SC=["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 kC(t,e){return e=e||3,null==t.dirty||!!(t.dirty&e)}function MC(t){if(t)return kC(t)&&function(t,e,n){var i=e.getComputedTransform();t.transform=Xf(t.transform,i);var r=t.localRect=Gf(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=hg.textMargin);for(var u=0;u<4;u++)TC[u]=d===hg.minMargin&&l&&null!=l[u]?l[u]:s&&null!=s[u]?s[u]:a?a[u]:0;d===hg.textMargin&&Hf(r,TC,!1,!1);var h=t.rect=Gf(t.rect,r);i&&h.applyTransform(i);d===hg.minMargin&&Hf(h,TC,!1,!1);t.axisAligned=qf(i),(t.label=t.label||{}).ignore=e.ignore,CC(t,!1),CC(t,!0,2)}(t,t.label,t),t}var TC=[0,0,0,0];function AC(t,e){for(var n=0;n-1&&(s.style.stroke=s.style.fill,s.style.fill=Vm.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}(vy);function LC(t,e){var n=t.mapDimensionsAll("defaultedLabel"),i=n.length;if(1===i){var r=x_(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),Uh(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=oh(this).dataIndex,o=n&&n.animation;if(this.silent=i.silent=!0,n&&n.fadeLabel){var a=i.getTextContent();a&&yf(a,{style:{opacity:0}},e,{dataIndex:r,removeOpt:o,cb:function(){i.removeTextContent()}})}else i.removeTextContent();yf(i,{style:{opacity:0},scaleX:0,scaleY:0},e,{dataIndex:r,cb:t,removeOpt:o})},e.getSymbolSize=function(t,e){return hr(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}(Gl);function RC(t,e){this.parent.drift(t,e)}function NC(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 zC(t){return null==t||vr(t)||(t={isIgnore:t}),t||{}}function OC(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:ng(e),cursorStyle:e.get("cursor")}}var $C=function(){function t(t){this.group=new Gl,this._SymbolCtor=t||EC}return t.prototype.updateData=function(t,e){this._progressiveEls=null,e=zC(e);var n=this.group,i=t.hostModel,r=this._data,o=this._SymbolCtor,a=e.disableAnimation,s=OC(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(NC(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(NC(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):mf(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=OC(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=zC(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=ar(t.dimensions,function(t){return e.mapDimension(t)}),h=!1,p=e.getCalculationInfo("stackResultDimension");return Qw(e,u[0])&&(h=!0,u[0]=p),Qw(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 FC(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 BC=Math.min,VC=Math.max;function jC(t,e){return isNaN(t)||isNaN(e)}function WC(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(jC(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||jC(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 z=M>0?1:-1;p=v-z*(R=Math.abs(P))*a,f=_,A=v+z*(N=Math.abs(D))*a,I=_}else if("y"===s){var O=T>0?1:-1;p=v,f=_-O*(R=Math.abs(L))*a,A=v,I=_+O*(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=BC(A=v+M*a*k,VC(w,v)),I=BC(I,VC(S,_)),A=VC(A,BC(w,v)),f=_-(T=(I=VC(I,BC(S,_)))-_)*R/N,p=BC(p=v-(M=A-v)*R/N,VC(c,v)),f=BC(f,VC(d,_)),A=v+(M=v-(p=VC(p,BC(c,v))))*N/R,I=_+(T=_-(f=VC(f,BC(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 qC=function(){this.smooth=0,this.smoothConstraint=!0},UC=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:Vm.color.neutral99,fill:null}},e.prototype.getDefaultShape=function(){return new qC},e.prototype.buildPath=function(t,e){var n=e.points,i=0,r=n.length/2;if(e.connectNulls){for(;r>0&&jC(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?Da(n,c,u,p,t,s):Da(i,d,h,f,t,s);if(v>0)for(var _=0;_=0){m=a?Ia(i,d,h,f,y):Ia(n,c,u,p,y);return a?[t,m]:[m,t]}}n=p,i=f}}},e}(Pu),GC=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e}(qC),XC=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 GC},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&&jC(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=rs(e[r]),s=rs(e[o]),l=i-r,c=ls([Ga(Qa(a[0],s[0],l)),Ga(Qa(a[1],s[1],l)),Ga(Qa(a[2],s[2],l)),Xa(Qa(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 ek(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 or(o.getViewLabels(),function(t){var e=o.scale.getRawOrdinalNumber(t.tickValue);s[e]=1}),function(t){return!s.hasOwnProperty(e.get(a,t))}}}}function nk(t,e){return isNaN(t)||isNaN(e)}function ik(t,e){return[t[2*e],t[2*e+1]]}function rk(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=ar(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=tk(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";or(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 tf(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,ym(M));var T=f.getClipPath();if(T)vf(T,{shape:ok(this,i,!1,t).shape},t);else f.setClipPath(ok(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]]}}),YC(this._stackedOnPoints,y)&&YC(this._points,l)||(g?this._doUpdateAnimation(o,y,i,n,k,v,x):(k&&(y&&(y=JC(y,l,i,k,x)),l=JC(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=JC(y,l,i,k,x)),l=JC(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,ym(M)),f.setClipPath(ok(this,i,!0,t));var A=t.getModel("emphasis"),I=A.get("focus"),P=A.get("blurScope"),D=A.get("disabled");(h.useStyle(er(a.getLineStyle(),{fill:"none",stroke:M,lineJoin:"bevel"})),Yh(h,t,"lineStyle"),h.style.lineWidth>0&&"bolder"===t.get(["emphasis","lineStyle","width"]))&&(h.getState("emphasis").style.lineWidth=+h.style.lineWidth+1);oh(h).seriesIndex=t.seriesIndex,Uh(h,I,P,D);var L=QC(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(er(s.getAreaStyle(),{fill:M,opacity:.7,lineJoin:"bevel",decal:o.getVisual("style").decal})),R&&(N=QC(R.get("smooth"))),p.setShape({smooth:L,stackedOnSmooth:N,smoothMonotone:E,connectNulls:x}),Yh(p,t,"areaStyle"),oh(p).seriesIndex=t.seriesIndex,Uh(p,I,P,D)}var z=this._changePolyState;o.eachItemGraphicEl(function(t){t&&(t.onHoverStateChange=z)}),this._polyline.onHoverStateChange=z,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){oh(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=Nc(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 EC(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 Iy.prototype.highlight.call(this,t,e,n,i)},e.prototype.downplay=function(t,e,n,i){var r=t.getData(),o=Nc(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 Iy.prototype.downplay.call(this,t,e,n,i)},e.prototype._changePolyState=function(t){var e=this._polygon;Ah(this._polyline,t),e&&Ah(e,t)},e.prototype._newPolyline=function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new UC({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 XC({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");pr(l)&&(l=l(null));var c=s.get("animationDelay")||0,d=pr(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=pr(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(rk(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 Uu({z2:200})).ignoreClip=!0,o.setTextContent(this._endLabel),o.disableLabelAnimation=!0);var l=function(t){for(var e=t.length/2;e>0&&nk(t[2*e-2],t[2*e-1]);e--);return e-1}(a);l>=0&&(eg(o,ng(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(!hr(e))return e+"";for(var i=[],r=0;r=0&&i.push(e[o])}return i.join(" ")}(r,n):LC(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=ik(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(mr(i))return ac(f=wc(n||0,i,r),o?Math.max(sc(n||0),sc(i)):e);if(fr(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=ik(c,I);r&&(k=d.getRawValue(I)),s.attr({x:M[0]+y,y:M[1]+b})}if(r){var P=ug(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=HC(r,e,a),m=t.getLayout("points")||[],v=e.getLayout("points")||[],_=0;_3e3||l&&KC(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(),mf(s,g,c),l&&(l.setShape({points:u,stackedOnPoints:h}),l.stopAnimation(),mf(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}(xC),kk="expandAxisBreak",Mk=Math.PI,Tk=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],Ak=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],Ik=zc(),Pk=zc(),Dk=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 Lk=[1,0,0,1,0,0],Ek=new qo(0,0,0,0),Rk=function(t,e,n,i,r,o){if(YS(t.nameLocation)){var a=o.stOccupiedRect;a&&Nk(function(t,e,n){return t.transform=Xf(t.transform,n),t.localRect=Gf(t.localRect,e),t.rect=Gf(t.rect,e),n&&t.rect.applyTransform(n),t.axisAligned=qf(n),t.obb=void 0,(t.label=t.label||{}).ignore=!1,t}({},a,o.transGroup.transform),i,r)}else zk(o.labelInfoList,o.dirVec,i,r)};function Nk(t,e,n){var i=new Do;PC(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 zk(t,e,n,i){for(var r=Do.dot(i,e)>=0,o=0,a=t.length;o0?"top":"bottom",i="center"):dc(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}(),$k=["axisLine","axisTickLabelEstimate","axisTickLabelDetermine","axisName"],Hk={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&&(Zr(d,d,c),Zr(u,u,c));var p=tr({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 qp(tr({shape:{x1:d[0],y1:d[1],x2:u[0],y2:u[1]}},f));Df(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"]);fr(m)&&(m=[m,m]),(fr(v)||mr(v))&&(v=[v,v]);var _=Ob(i.get(["axisLine","symbolOffset"])||0,v),y=v[0],b=v[1];or([{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=zb(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){jk(e,r,s)&&Fk(t,e,n,i,r,o,a,rC)},axisTickLabelDetermine:function(t,e,n,i,r,o,a,s){jk(e,r,s)&&Fk(t,e,n,i,r,o,a,oC);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=Vk(r.getTicksCoords(),n.transform,l,er(s.getLineStyle(),{stroke:i.get(["axisLine","lineStyle","color"])}),"ticks"),d=0;di[1],l="start"===e&&!s||"start"!==e&&s;dc(a-Mk/2)?(o=l?"bottom":"top",r="center"):dc(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,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=Sr(t.raw.nameTruncateMaxWidth,S.maxWidth,b),M=s.nameMarginLevel||0,T=new Uu({x:m.x,y:m.y,rotation:y.rotation,silent:Ok.isLabelSilent(i),style:ig(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(Vf({el:T,componentModel:i,itemName:c}),T.__fullText=c,T.anid="name",i.get("triggerEvent")){var A=Ok.makeAxisEventDataBase(i);A.targetType="axisName",A.name=c,oh(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:YS(d)?Tk[M]:Ak[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 Fk(t,e,n,i,r,o,a,s){Wk(e)||function(t,e,n,i,r,o){var a=r.axis,s=Sr(t.raw.axisLabelShow,r.get(["axisLabel","show"])),l=new Gl;n.add(l);var c=aC(i);if(!s||a.scale.isBlank())return void qk(e,[],l,c);var d=r.getModel("axisLabel"),u=a.getViewLabels(c),h=(Sr(t.raw.labelRotate,d.get("rotate"))||0)*Mk/180,p=Ok.innerTextLayout(t.rotation,h,t.labelDirection),f=r.getCategories&&r.getCategories(!0),g=[],m=r.get("triggerEvent"),v=1/0,_=-1/0;or(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];vr(y)&&y.textStyle&&(h=new Sg(y.textStyle,d,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),_=Math.max(_,T);var A=new Uu({x:0,y:0,rotation:0,silent:Ok.isLabelSilent(r),z2:T,style:ig(h,{text:s,align:0===e?w:e===u.length-1?S:x,verticalAlign:0===e?k:e===u.length-1?M:C,fill:pr(b)?b("category"===a.type?c:"value"===a.type?i+"":i,e):b})});A.anid="label_"+i;var I=Ik(A);if(I.break=t.break,I.tickValue=i,I.layoutRotation=p.rotation,Vf({el:A,componentModel:r,itemName:s,formatterParamsExtra:{isTruncated:function(){return A.isTruncated},value:c,tickIndex:e}}),m){var P=Ok.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),oh(A).eventData=P,t.break&&function(t,e,n,i){n.on("click",function(n){var r={type:kk,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=ar(g,function(t){return{label:t,priority:Ik(t).break?t.z2+(_-v+1):t.z2,defaultAttr:{ignore:t.ignore}}});qk(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"]);or(n,function(n,o){var a=MC(n);if(a){var s=a.label,l=Ik(s);a.suggestIgnore=s.ignore,s.ignore=!1,Sl(Uk,Gk),Uk.x=e.axis.dataToCoord(l.tickValue),Uk.y=t.labelOffset+t.labelDirection*r,Uk.rotation=l.layoutRotation,i.add(Uk),Uk.updateTransform(),i.remove(Uk),Uk.decomposeTransform(),Sl(s,Uk),s.markRedraw(),CC(a,!0),MC(a)}})}(t,i,l,o),t.rotation;var c=t.optionHideOverlap;!function(t,e,n){if(GS(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)Bk(o.label);else if(a.suggestIgnore)Bk(a.label);else{var s=.1;if(!n){var l=[0,0,0,0];o=AC({marginForce:l},o),a=AC({marginForce:l},a)}PC(o,a,null,{touchThreshold:s})&&Bk(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 qo(h,0,p,1))}a.stOccupiedRect=r,a.labelInfoList=s}(t,n,i,l)}function Bk(t){t&&(t.ignore=!0)}function Vk(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;tS(l)&&s.get("alignTicks")&&null==s.get("interval")?r.push(a):(jS(l,s),tS(l)&&(e=a))}r.length&&(e||jS((e=r.pop()).scale,e.model),or(r,function(t){!function(t,e,n){var i=mS.prototype,r=i.getTicks.call(n),o=i.getTicks.call(n,{expandToNicedExtent:!0}),a=r.length-1,s=i.getInterval.call(n),l=VS(t,e),c=l.extent,d=l.fixMin,u=l.fixMax;"log"===t.type&&(c=cS(t.base,c,!0)),t.setBreaksFromOption(KS(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=nS(p),f=c[1]-p*a;else{t.getTicks().length-1>a&&(p=nS(p));var m=p*a;(f=ac((g=Math.ceil(c[1]/p)*p)-m))<0&&c[0]>=0?(f=0,g=ac(m)):g>0&&c[1]<=0&&(g=0,f=-ac(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={};or(n.x,function(t){tM(n,"y",t,r)}),or(n.y,function(t){tM(n,"x",t,r)}),this.resize(this.model,e)},t.prototype.resize=function(t,e,n){var i=zm(t,e),r=this._rect=Rm(t.getBoxLayoutParams(),i.refContainer),o=this._axesMap,a=this._coordsList,s=t.get("containLabel");if(nM(o,r),!n){var l=function(t,e,n,i,r){var o=new Dk(aM);return or(n,function(n){return or(n,function(n){if(ZS(n.model)){var a=!i;n.axisBuilder=function(t,e,n,i,r,o){for(var a=Yk(t,n),s=!1,l=!1,c=0;c0&&i>0||n<0&&i<0)}(t)}function nM(t,e){or(t.x,function(t){return iM(t,e.x,e.width)}),or(t.y,function(t){return iM(t,e.y,e.height)})}function iM(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 rM(t,e,n,i,r,o,a){oM(i,r,rC,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 Hf(i,s,!0,!0,n),nM(r,i),l;function c(t){or(r[wf[t]],function(e){if(ZS(e.model)){var n=o.ensureRecord(e.model),i=n.labelInfoList;if(i)for(var r=0;r0&&!wr(e)&&e>1e-4&&(t/=e),t}}function oM(t,e,n,i,r,o){var a=n===oC;or(e,function(e){return or(e,function(e){ZS(e.model)&&(!function(t,e,n){var i=Yk(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[wf[1-e]]=t[Sf[e]]<=.5*o.refContainer[Sf[e]]?0:1-e==1?2:1}l(0),l(1),or(e,function(t,e){return or(t,function(t){ZS(t.model)&&(("all"===i||a)&&t.axisBuilder.build({axisName:!0},{nameMarginLevel:s[e]}),a&&t.axisBuilder.build({axisLine:!0}))})})}var aM=function(t,e,n,i,r,o){var a="x"===n.axis.dim?"y":"x";Rk(t,0,0,i,r,o),YS(t.nameLocation)||or(e.recordMap[a],function(t){t&&t.labelInfoList&&t.dirVec&&zk(t.labelInfoList,t.dirVec,i,r)})};function sM(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=[];or(n.getCoordinateSystems(),function(n){if(n.axisPointerEnabled){var s=uM(n.model),l=t.coordSysAxesInfo[s]={};t.coordSysMap[s]=n;var c=n.model.getModel("tooltip",i);if(or(n.getAxes(),ur(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)&&or(h.baseAxes,ur(p,!u||"cross",d)),u&&or(h.otherAxes,ur(p,"cross",!1))}}function p(i,s,d){var u=d.model.getModel("axisPointer",r),h=u.get("show");if(h&&("auto"!==h||i||dM(u))){null==s&&(s=u.get("triggerTooltip")),u=i?function(t,e,n,i,r,o){var a=e.getModel("axisPointer"),s={};or(["type","snap","lineStyle","shadowStyle","label","animation","animationDurationUpdate","animationEasingUpdate","z"],function(t){s[t]=Qi(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&&er(l,d.textStyle)}}return t.model.getModel("axisPointer",new Sg(s,n,i))}(d,c,r,e,i,s):u;var p=u.get("snap"),f=u.get("triggerEmphasis"),g=uM(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:dM(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 cM(t){var e=(t.ecModel.getComponent("axisPointer")||{}).coordSysAxesInfo;return e&&e.axesInfo[uM(t)]}function dM(t){return!!t.get(["handle","show"])}function uM(t){return t.type+"||"+t.id}var hM={},pM=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=cM(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=dM(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=cM(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=SM(t).pointerEl=new Qf[r.type](CM(e.pointer));t.add(o)}},t.prototype.createLabelEl=function(t,e,n,i){if(e.label){var r=SM(t).labelEl=new Uu(CM(e.label));t.add(r),IM(r,i)}},t.prototype.updatePointerEl=function(t,e,n){var i=SM(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=SM(t).labelEl;r&&(r.setStyle(e.label.style),n(r,{x:e.label.x,y:e.label.y}),IM(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=zf(o.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(t){xo(t.event)},onmousedown:kM(this._onHandleDragMove,this,0,0),drift:kM(this._onHandleDragMove,this),ondragend:kM(this._onHandleDragEnd,this)}),i.add(r)),DM(r,n,!1),r.setStyle(o.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var s=o.get("size");hr(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,Hy(this,"_doDispatchAxisPointer",o.get("throttle")||0,"fixRate"),this._moveHandleToValue(t,e)}},t.prototype._moveHandleToValue=function(t,e){TM(this._axisPointerModel,!e&&this._moveAnimation,this._handle,PM(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(PM(n),[t,e],this._axisModel,this._axisPointerModel);this._payloadInfo=i,n.stopAnimation(),n.attr(PM(i)),SM(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),Fy(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 TM(t,e,n,i){AM(SM(n).lastProp,i)||(SM(n).lastProp=i,e?mf(n,i,t):(n.stopAnimation(),n.attr(i)))}function AM(t,e){if(vr(t)&&vr(e)){var n=!0;return or(e,function(e,i){n=n&&AM(t[i],e)}),!!n}return t===e}function IM(t,e){t[e.get(["label","show"])?"show":"hide"]()}function PM(t){return{x:t.x||0,y:t.y||0,rotation:t.rotation||0}}function DM(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 LM(t,e,n,i,r){var o=EM(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=fm(a.get("padding")||0),l=a.getFont(),c=Pl(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:ig(a,{text:o,font:l,fill:a.getTextColor(),padding:s,backgroundColor:g}),z2:10}}function EM(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:qS(e,{value:t}),axisDimension:e.dim,axisIndex:e.index,seriesData:[]};or(i,function(t){var e=n.getSeriesByIndex(t.seriesIndex),i=t.dataIndexInside,r=e&&e.getDataParams(i);r&&s.seriesData.push(r)}),fr(a)?o=a.replace("{value}",o):pr(a)&&(o=a(s))}return o}function RM(t,e,n){var i=[1,0,0,1,0,0];return Io(i,i,n.rotation),Ao(i,i,n.position),Ef([t.dataToCoord(e),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],i)}var NM=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=zM(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=OM[s](o,c,l);u.style=d,t.graphicKey=u.type,t.pointer=u}!function(t,e,n,i,r,o){var a=Ok.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=r.get(["label","margin"]),LM(e,i,r,o,{position:RM(i.axis,t,n),align:a.textAlign,verticalAlign:a.textVerticalAlign})}(e,t,Yk(a.getRect(),n),n,i,r)},e.prototype.getHandleTransform=function(t,e,n){var i=Yk(e.axis.grid.getRect(),e,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var r=RM(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=zM(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}(MM);function zM(t,e){var n={};return n[e.dim+"AxisIndex"]=e.index,t.getCartesian(n)}var OM={line:function(t,e,n){var i,r,o;return{type:"Line",subPixelOptimize:!0,shape:(i=[e,n[0]],r=[e,n[1]],o=$M(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=$M(t),{x:i[o=o||0],y:i[1-o],width:r[o],height:r[1-o]})}}};function $M(t){return"x"===t.dim?0:1}var HM=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:Vm.color.border,width:1,type:"dashed"},shadowStyle:{color:Vm.color.shadowTint},label:{show:!0,formatter:null,precision:"auto",margin:3,color:Vm.color.neutral00,padding:[5,7,5,7],backgroundColor:Vm.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:Vm.color.accent40,throttle:40}},e}(Bm),FM=zc(),BM=or;function VM(t,e,n){if(!Di.node){var i=e.getZr();FM(i).records||(FM(i).records={}),function(t,e){if(FM(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);BM(FM(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)})}FM(t).initialized=!0,n("click",ur(WM,"click")),n("mousemove",ur(WM,"mousemove")),n("globalout",jM)}(i,e),(FM(i).records[t]||(FM(i).records[t]={})).handler=n}}function jM(t,e,n){t.handler("leave",null,n)}function WM(t,e,n,i){e.handler(t,n,i)}function qM(t,e){if(!Di.node){var n=e.getZr();(FM(n).records||{})[t]&&(FM(n).records[t]=null)}}var UM=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";VM("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){qM("axisPointer",e)},e.prototype.dispose=function(t,e){qM("axisPointer",e)},e.type="axisPointer",e}(ky);function GM(t,e){var n,i=[],r=t.seriesIndex;if(null==r||!(n=e.getSeriesByIndex(r)))return{point:[]};var o=n.getData(),a=Nc(o,t);if(null==a||a<0||hr(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(ar(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 XM=zc();function YM(t,e,n){var i=t.currTrigger,r=[t.x,t.y],o=t,a=t.dispatchAction||dr(n.dispatchAction,n),s=e.getComponent("axisPointer").coordSysAxesInfo;if(s){tT(r)&&(r=GM({seriesIndex:o.seriesIndex,dataIndex:o.dataIndex},e).point);var l=tT(r),c=o.axesInfo,d=s.axesInfo,u="leave"===i||tT(r),h={},p={},f={list:[],map:{}},g={showPointer:ur(KM,p),showTooltip:ur(QM,f)};or(s.coordSysMap,function(t,e){var n=l||t.containPoint(r);or(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&&ZM(t,a,g,!1,h)}})});var m={};return or(d,function(t,e){var n=t.linkGroup;n&&!p[e]&&or(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,JM(e),JM(t)))),m[t.key]=o}})}),or(m,function(t,e){ZM(d[e],t,g,!0,h)}),function(t,e,n){var i=n.axesInfo=[];or(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(tT(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=XM(i)[r]||{},a=XM(i)[r]={};or(t,function(t,e){var n=t.axisPointerModel.option;"show"===n.status&&t.triggerEmphasis&&or(n.seriesDataIndices,function(t){var e=t.seriesIndex+" | "+t.dataIndex;a[e]=t})});var s=[],l=[];or(o,function(t,e){!a[e]&&l.push(t)}),or(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 ZM(t,e,n,i,r){var o=t.axis;if(!o.scale.isBlank()&&o.containData(e))if(t.involveSeries){var a=function(t,e){var n=e.axis,i=n.dim,r=t,o=[],a=Number.MAX_VALUE,s=-1;return or(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),or(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&&tr(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 KM(t,e,n,i){t[e.key]={value:n,payloadBatch:i}}function QM(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=uM(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 JM(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 tT(t){return!t||null==t[0]||isNaN(t[0])||null==t[1]||isNaN(t[1])}function eT(t){pM.registerAxisPointerClass("CartesianAxisPointer",NM),t.registerComponentModel(HM),t.registerComponentView(UM),t.registerPreprocessor(function(t){if(t){(!t.axisPointer||0===t.axisPointer.length)&&(t.axisPointer={});var e=t.axisPointer.link;e&&!hr(e)&&(t.axisPointer.link=[e])}}),t.registerProcessor(t.PRIORITY.PROCESSOR.STATISTIC,function(t,e){t.getComponent("axisPointer").coordSysAxesInfo=sM(t,e)}),t.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},YM)}var nT=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:Vm.color.neutral00,shadowBlur:10,shadowColor:"rgba(0, 0, 0, .2)",shadowOffsetX:1,shadowOffsetY:2,borderRadius:4,borderWidth:1,defaultBorderColor:Vm.color.border,padding:null,extraCssText:"",axisPointer:{type:"line",axis:"auto",animation:"auto",animationDurationUpdate:200,animationEasingUpdate:"exponentialOut",crossStyle:{color:Vm.color.borderShade,width:1,type:"dashed",textStyle:{}}},textStyle:{color:Vm.color.tertiary,fontSize:14}},e}(Bm);function iT(t){var e=t.get("confine");return null!=e?!!e:"richText"===t.get("renderMode")}function rT(t){if(Di.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?",":"")+(Di.transformSupported?""+lT+r:",left"+r+",top"+r)),sT+":"+o}(o,n,i)),a&&r.push("background-color:"+a),or(["width","color","radius"],function(e){var n="border-"+e,i=pm(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),or(["decoration","align"],function(n){var i=t.get(n);i&&e.push("text-"+n+":"+i)}),e.join(";")}(u)),null!=h&&r.push("padding:"+fm(h).join("px ")+"px"),r.join(";")+";"}function hT(t,e,n,i,r){var o=e&&e.painter;if(n){var a=o&&o.getViewportRoot();a&&function(t,e,n,i,r){so(ao,e,i,r,!0)&&so(t,n,ao[0],ao[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 pT=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,Di.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&&(fr(r)?document.querySelector(r):br(r)?r:pr(r)&&r(t.getDom()));hT(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;yo(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=cT+uT(t,!this._firstShow,this._longHide,this._enableDisplayTransition)+dT(r[0],r[1],!0)+"border-color:"+ym(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(fr(r)&&"item"===n.get("trigger")&&!iT(n)&&(a=function(t,e,n){if(!fr(n)||"inside"===n)return"";var i=t.get("backgroundColor"),r=t.get("borderWidth");e=ym(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=lT+":";nr(["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)),fr(t))o.innerHTML=t+a;else if(t){o.innerHTML="",hr(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&&!Di.node&&n.getDom()){var r=xT(i,n);this._ticket="";var o=i.dataByCoordSys,a=function(t,e,n){var i=Hc(t).queryOptionMap,r=i.keys()[0];if(!r||"series"===r)return;var o=Bc(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=oh(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=_T;l.x=i.x,l.y=i.y,l.update(),oh(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=GM(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(xT(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"===bT([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"===oh(n).ssrType)return;this._lastDataByCoordSys=null,Cb(n,function(t){if(t.tooltipDisabled)return r=o=null,!0;r||o||(null!=oh(t).dataIndex?r=t:null!=oh(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=dr(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=bT([e.tooltipOption],i),a=this._renderMode,s=[],l=iy("section",{blocks:[],noHeader:!0}),c=[],d=new py;or(t,function(t){or(t.dataByAxis,function(t){var e=n.getComponent(t.axisDim+"Axis",t.axisIndex),r=t.value;if(e&&null!=r){var o=EM(r,e.axis,n,t.seriesDataIndices,t.valueLabelOpt),u=iy("section",{header:o,noHeader:!Ir(o),sortBlocks:!0,blocks:[]});l.blocks.push(u),or(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=qS(e.axis,{value:r}),f.axisValueLabel=o,f.marker=d.makeTooltipMarker("item",ym(f.color),a);var g=C_(h.formatTooltip(p,!0,null)),m=g.frag;if(m){var v=bT([h],i).get("valueFormatter");u.blocks.push(v?tr({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=cy(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=oh(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=bT([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 py;g.marker=m.makeTooltipMarker("item",ym(g.color),u);var v=C_(s.formatTooltip(l,!1,c)),_=p.get("order"),y=p.get("valueFormatter"),b=v.frag,x=b?cy(y?tr({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=oh(e),o=r.tooltipConfig.option||{},a=o.encodeHTMLContent;if(fr(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=Qi(o)).content=ho(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=bT(s,this._tooltipModel,c?{position:c}:null),u=d.get("content"),h=Math.random()+"",p=new py;this._showOrMove(d,function(){var n=Qi(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(fr(d)){var p=t.ecModel.get("useUTC"),f=hr(n)?n[0]:n;u=d,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(u=Yg(f.axisValue,u,p)),u=_m(u,n,!0)}else if(pr(d)){var g=dr(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||hr(e)?{color:i||r}:hr(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),pr(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),hr(e))n=rc(e[0],s),i=rc(e[1],l);else if(vr(e)){var p=e;p.width=c[0],p.height=c[1];var f=Rm(p,{width:s,height:l});n=f.x,i=f.y,d=null,u=null}else if(fr(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-=wT(d)?c[0]/2:"right"===d?c[0]:0),u&&(i-=wT(u)?c[1]/2:"bottom"===u?c[1]:0),iT(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&&or(n,function(n,o){var a=n.dataByAxis||[],s=(t[o]||{}).dataByAxis||[];(r=r&&a.length===s.length)&&or(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)&&or(a,function(t,e){var n=l[e];r=r&&t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex}),i&&or(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){!Di.node&&e.getDom()&&(Fy(this,"_updatePosition"),this._tooltipContent.dispose(),qM("itemTooltip",e))},e.type="tooltip",e}(ky);function bT(t,e,n){var i,r=e.ecModel;n?(i=new Sg(n,r,r),i=new Sg(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof Sg&&(a=a.get("tooltip",!0)),fr(a)&&(a={formatter:a}),a&&(i=new Sg(a,i,r)))}return i}function xT(t,e){return t.dispatchAction||dr(e.dispatchAction,e)}function wT(t){return"center"===t||"middle"===t}var ST=Math.sin,CT=Math.cos,kT=Math.PI,MT=2*Math.PI,TT=180/kT,AT=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=gs(d-MT)||(c?l>=MT:-l>=MT),h=l>0?l%MT:l%MT+MT,p=!1;p=!!u||!gs(d)&&h>=kT==!!c;var f=t+n*CT(o),g=e+i*ST(o);this._start&&this._add("M",f,g);var m=Math.round(r*TT);if(u){var v=1/this._p,_=(c?1:-1)*(MT-v);this._add("A",n,i,m,1,+c,t+n*CT(o+_),e+i*ST(o+_)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var y=t+n*CT(a),b=e+i*ST(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?ho(a):a||"")+(i?""+n+ar(i,function(e){return t(e)}).join(n)+n:"")+("")}(t)}function FT(t){return{zrId:t,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function BT(t,e,n,i){return $T("svg","root",{width:t,height:e,xmlns:RT,"xmlns:xlink":NT,version:"1.1",baseProfile:"full",viewBox:!!i&&"0 0 "+t+" "+e},n)}var VT=0;function jT(){return VT++}var WT={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"},qT="transform-origin";function UT(t,e,n){var i=tr({},t.shape);tr(i,e),t.buildPath(n,i);var r=new AT;return r.reset(ks(t)),n.rebuildPath(r,1),r.generateStr(),r.getStr()}function GT(t,e){var n=e.originX,i=e.originY;(n||i)&&(t[qT]=n+"px "+i+"px")}var XT={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function YT(t,e){var n=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[n]=t,n}function ZT(t){return fr(t)?WT[t]?"cubic-bezier("+WT[t]+")":Ba(t)?t:"":""}function KT(t,e,n,i){var r=t.animators,o=r.length,a=[];if(t instanceof Qp){var s=function(t,e,n){var i,r,o=t.shape.paths,a={};if(or(o,function(t){var e=FT(n.zrId);e.animation=!0,KT(t,{},e,!0);var o=e.cssAnims,s=e.cssNodes,l=cr(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=YT(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 YT(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-"+jT();n.cssNodes["."+v]={animation:a.join(",")},e.class=v}}function QT(t,e,n,i){var r=JSON.stringify(t),o=n.cssStyleCache[r];o||(o=n.zrId+"-cls-"+jT(),n.cssStyleCache[r]=o,n.cssNodes["."+o+":hover"]=t),e.class=e.class?e.class+" "+o:o}var JT=Math.round;function tA(t){return t&&fr(t.src)}function eA(t){return t&&pr(t.toDataURL)}function nA(t,e,n,i){ET(function(r,o){var a="fill"===r||"stroke"===r;a&&Ss(o)?pA(e,t,r,i):a&&bs(o)?fA(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=ps(i.shadowColor),f=p.opacity,g=p.color,m=h/2/l+" "+h/2/c;a=n.zrId+"-s"+n.shadowIdx++,n.defs[a]=$T("filter",a,{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},[$T("feDropShadow","",{dx:d/l,dy:u/c,stdDeviation:m,"flood-color":g,"flood-opacity":f})]),o[r]=a}e.filter=Cs(a)}}(n,t,i)}function iA(t,e){var n=function(t){if("function"==typeof Zl)return Zl(t)}(e);n&&(n.each(function(e,n){null!=e&&(t[(zT+n).toLowerCase()]=e+"")}),e.isSilent()&&(t[zT+"silent"]="true"))}function rA(t){return gs(t[0]-1)&&gs(t[1])&&gs(t[2])&&gs(t[3]-1)}function oA(t,e,n){if(e&&(!function(t){return gs(t[4])&&gs(t[5])}(e)||!rA(e))){var i=1e4;t.transform=rA(e)?"translate("+JT(e[4]*i)/i+" "+JT(e[5]*i)/i+")":function(t){return"matrix("+ms(t[0])+","+ms(t[1])+","+ms(t[2])+","+ms(t[3])+","+vs(t[4])+","+vs(t[5])+")"}(e)}}function aA(t,e,n){for(var i=t.points,r=[],o=0;o=0&&a||o;s&&(r=us(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),QT(c,e,n)}}(t,o,e),$T(s,t.id+"",o)}function hA(t,e){return t instanceof Pu?uA(t,e):t instanceof Nu?function(t,e){var n=t.style,i=n.image;if(i&&!fr(i)&&(tA(i)?i=i.src:eA(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),oA(a,t.transform),nA(a,n,t,e),iA(a,t),e.animation&&KT(t,a,e),$T("image",t.id+"",a)}}(t,e):t instanceof Lu?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||Ei,o=n.x||0,a=function(t,e,n){return"top"===n?t+=e/2:"bottom"===n&&(t-=e/2),t}(n.y||0,El(r),n.textBaseline),s={"dominant-baseline":"central","text-anchor":_s[n.textAlign]||n.textAlign};if(Qu(n)){var l="",c=n.fontStyle,d=Zu(n.fontSize);if(!parseFloat(d))return;var u=n.fontFamily||Li,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),oA(s,t.transform),nA(s,n,t,e),iA(s,t),e.animation&&KT(t,s,e),$T("text",t.id+"",s,void 0,i)}}(t,e):void 0}function pA(t,e,n,i){var r,o=t[n],a={gradientUnits:o.global?"userSpaceOnUse":"objectBoundingBox"};if(xs(o))r="linearGradient",a.x1=o.x,a.y1=o.y,a.x2=o.x2,a.y2=o.y2;else{if(!ws(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,d=s.length;cl?IA(t,null==n[u+1]?null:n[u+1].elm,n,s,u):PA(t,e,a,l))}(n,i,r):kA(r)?(kA(t.text)&&wA(n,""),IA(n,null,r,0,r.length-1)):kA(i)?PA(n,i,0,i.length-1):kA(t.text)&&wA(n,""):t.text!==e.text&&(kA(i)&&PA(n,i,0,i.length-1),wA(n,e.text)))}var EA=0,RA=function(){function t(t,e,n){if(this.type="svg",this.refreshHover=function(){},this.configLayer=function(){},this.storage=e,this._opts=n=tr({},n),this.root=t,this._id="zr"+EA++,this._oldVNode=BT(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=OT("svg");DA(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(TA(t,e))LA(t,e);else{var n=t.elm,i=bA(n);AA(e),null!==i&&(vA(i,e.elm,xA(n)),PA(i,[t],0,0))}}(this._oldVNode,t),this._oldVNode=t}},t.prototype.renderOneToVNode=function(t){return hA(t,FT(this._id))},t.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),n=this._width,i=this._height,r=FT(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=$T("rect","bg",{width:t,height:e,x:"0",y:"0"}),Ss(n))pA({fill:n},r.attrs,"fill",i);else if(bs(n))fA({style:{fill:n},dirty:Hr,getBoundingRect:function(){return{width:t,height:e}}},r.attrs,"fill",i);else{var o=ps(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=$T("g","main",{},[]);this._paintList(e,r,s?s.children:o),s&&o.push(s);var l=ar(cr(r.defs),function(t){return r.defs[t]});if(l.length&&o.push($T("defs","defs",{},l)),t.animation){var c=function(t,e,n){var i=(n=n||{}).newline?"\n":"",r=" {"+i,o=i+"}",a=ar(cr(t),function(e){return e+r+ar(cr(t[e]),function(n){return n+":"+t[e][n]+";"}).join(i)+o}).join(i),s=ar(cr(e),function(t){return"@keyframes "+t+r+ar(cr(e[t]),function(n){return n+r+ar(cr(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=$T("style","stl",{},[],c);o.push(d)}}return BT(n,i,o,t.useViewBox)},t.prototype.renderToString=function(t){return t=t||{},HT(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&&(!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;fr(r)?p=sk[r]:pr(r)&&(p=r),p&&t.setData(i.downSample(i.mapDimension(l.dim),1/h,p,lk))}}}}}("line"))},function(t){eC(wM),eC(eT)},function(t){eC(eT),t.registerComponentModel(nT),t.registerComponentView(yT),t.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},Hr),t.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},Hr)},function(t){t.registerPainter("svg",RA)}]);class NA 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=lw(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)}}NA.styles=k` +var Lc={},Ec={};var Rc,Nc=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 ts,o=n.renderer||"canvas";Lc[o]||(o=Gr(Lc)[0]),n.useDirtyRect=null!=n.useDirtyRect&&n.useDirtyRect;var a=new Lc[o](e,r,n,t),s=n.ssr||a.ssrOnly;this.storage=r,this.painter=a;var l,c=gr.node||gr.worker||s?null:new Ul(a.getViewportRoot(),a.root),d=n.useCoarsePointer;(null==d||"auto"===d?gr.touchEventsSupported:!!d)&&(l=lo(n.pointerSize,44)),this.handler=new Fa(r,a,c,a.root,l),this.animation=new Il({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 Gs(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 Vc=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 Qr(t)?(i=t,i.replace(/^\s+|\s+$/g,"")).match(/%$/)?parseFloat(t)/100*e+(n||0):parseFloat(t):null==t?NaN:+t;var i}function qc(t,e,n){return null==e&&(e=10),e=Math.min(Math.max(0,e),20),t=(+t).toFixed(e),n?t:+t}function Wc(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 Uc(t,e){var n=Math.max(Wc(t),Wc(e)),i=t+e;return n>20?i:qc(i,n)}function Gc(t){var e=2*Math.PI;return(t%e+e)%e}function Xc(t){return t>-1e-4&&t=10&&e++,e}function Qc(t,e){var n=Kc(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 Jc(t){var e=parseFloat(t);return e==t&&(0!==e||!Qr(t)||t.indexOf("x")<=0)?e:NaN}function td(){return Math.round(9*Math.random())}function ed(t,e){return 0===e?t:ed(e,t%e)}function nd(t,e){return null==t?e:null==e?t:t*e/ed(t,e)}var id="undefined"!=typeof console&&console.warn&&console.log;function rd(t,e){!function(t,e){id&&console[t]("[ECharts] "+e)}("error",t)}function od(t){throw new Error(t)}function ad(t,e,n){return(e-t)*n+t}var sd="series\0";function ld(t){return t instanceof Array?t:null==t?[]:[t]}function cd(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&&Fr(r,s)<0)){var l=n.getShallow(s,e);null!=l&&(o[t[a][0]]=l)}}return o}}var Od=zd([["fill","color"],["shadowBlur"],["shadowOffsetX"],["shadowOffsetY"],["opacity"],["shadowColor"]]),$d=function(){function t(){}return t.prototype.getAreaStyle=function(t,e){return Od(this,t,e)},t}(),Hd=new Is(50);function Fd(t){if("string"==typeof t){var e=Hd.get(t);return e&&e.image}return t}function Bd(t,e,n,i,r){if(t){if("string"==typeof t){if(e&&e.__zrImageSrc===t||!n)return e;var o=Hd.get(t),a={hostEl:n,cb:i,cbPayload:r};return o?!jd(e=o.image)&&o.pending.push(a):((e=xr.loadImage(t,Vd,Vd)).__zrImageSrc=t,Hd.put(t,e.__cachedImgObj={image:e,pending:[a]})),e}return t}return e}function Vd(){var t=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var e=0;e=s;c++)l-=s;var d=hc(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 Gd(t,e,n){var i=n.containerWidth,r=n.contentWidth,o=n.fontMeasureInfo;if(!i)return t.textLine="",void(t.isTruncated=!1);var a=hc(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?Xd(e,r,o):a>0?Math.floor(e.length*r/a):0;a=hc(o,e=e.substr(0,l))}""===e&&(e=n.placeholder),t.textLine=e,t.isTruncated=!0}function Xd(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=eu(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=lc(d),v=0;v=32&&e<=591||e>=880&&e<=4351||e>=4608&&e<=5119||e>=7680&&e<=8303}(t)||!!Jd[t]}function eu(t,e,n,i,r){for(var o=[],a=[],s="",l="",c=0,d=0,u=lc(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 nu(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;Ia.set(iu,gc(n,a,r),mc(i,s,o),a,s),Ia.intersect(e,iu,null,ru);var l=ru.outIntersectRect;t.outerWidth=l.width,t.outerHeight=l.height,t.baseX=gc(l.x,l.width,r,!0),t.baseY=mc(l.y,l.height,o,!0)}}var iu=new Ia(0,0,0,0),ru={outIntersectRect:{},clamp:!0};function ou(t){return null!=t?t+="":t=""}function au(t,e,n,i){var r=new Ia(gc(t.x||0,e,t.textAlign),mc(t.y||0,n,t.textBaseline),e,n),o=null!=i?i:su(t)?t.lineWidth:0;return o>0&&(r.x-=o/2,r.y-=o/2,r.width+=o,r.height+=o),r}function su(t){var e=t.stroke;return null!=e&&"none"!==e&&t.lineWidth>0}var lu="__zr_style_"+Math.round(10*Math.random()),cu={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}};cu[lu]=!0;var uu=["z","z2","invisible"],hu=["invisible"],pu=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=Gr(e),i=0;i1e-4)return s[0]=t-n,s[1]=e-i,l[0]=t+n,void(l[1]=e+i);if(xu[0]=yu(r)*n+t,xu[1]=_u(r)*i+e,wu[0]=yu(o)*n+t,wu[1]=_u(o)*i+e,c(s,xu,wu),d(l,xu,wu),(r%=bu)<0&&(r+=bu),(o%=bu)<0&&(o+=bu),r>o&&!a?o+=bu:rr&&(Su[0]=yu(p)*n+t,Su[1]=_u(p)*i+e,c(s,Su,s),d(l,Su,l))}var Pu={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},Du=[],Lu=[],Eu=[],Ru=[],Nu=[],zu=[],Ou=Math.min,$u=Math.max,Hu=Math.cos,Fu=Math.sin,Bu=Math.abs,Vu=Math.PI,ju=2*Vu,qu="undefined"!=typeof Float32Array,Wu=[];function Uu(t){return Math.round(t/Vu*1e8)/1e8%2*Vu}var Gu=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=Bu(n/Xl/t)||0,this._uy=Bu(n/Xl/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=Bu(t-this._xi),i=Bu(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(),Wu[0]=i,Wu[1]=r,function(t,e){var n=Uu(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-Uu(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(){Eu[0]=Eu[1]=Nu[0]=Nu[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||Bu(m)>i||u===e-1)&&(f=Math.sqrt(I*I+m*m),r=g,o=y);break;case Pu.C:var v=t[u++],_=t[u++],y=(g=t[u++],t[u++]),b=t[u++],x=t[u++];f=_s(r,o,v,_,g,y,b,x,10),r=b,o=x;break;case Pu.Q:f=Ss(r,o,v=t[u++],_=t[u++],g=t[u++],y=t[u++],10),r=g,o=y;break;case Pu.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=Hu(M)*C+w,s=Fu(M)*k+S),f=$u(C,k)*Ou(ju,Math.abs(T)),r=Hu(A)*C+w,o=Fu(A)*k+S;break;case Pu.R:a=r=t[u++],s=o=t[u++],f=2*t[u++]+2*t[u++];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[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 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=Bu(a-r),C=Bu(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 Pu.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){vs(r,T,I,D,k=(c-v)/X,Du),vs(o,A,P,L,k,Lu),t.bezierCurveTo(Du[1],Lu[1],Du[2],Lu[2],Du[3],Lu[3]);break t}v+=X}t.bezierCurveTo(T,A,I,P,D,L),r=D,o=L;break;case Pu.Q:T=h[b++],A=h[b++],I=h[b++],P=h[b++];if(m){if(v+(X=l[_++])>c){ws(r,T,I,k=(c-v)/X,Du),ws(o,A,P,k,Lu),t.quadraticCurveTo(Du[1],Lu[1],Du[2],Lu[2]);break t}v+=X}t.quadraticCurveTo(T,A,I,P),r=I,o=P;break;case Pu.A:var E=h[b++],R=h[b++],N=h[b++],z=h[b++],O=h[b++],$=h[b++],H=h[b++],F=!h[b++],B=N>z?N:z,V=Bu(N-z)>.001,j=O+$,q=!1;if(m)v+(X=l[_++])>c&&(j=O+$*(c-v)/X,q=!0),v+=X;if(V&&t.ellipse?t.ellipse(E,R,N,z,H,O,j,F):t.arc(E,R,B,O,j,F),q)break t;w&&(n=Hu(O)*N+E,i=Fu(O)*z+R),r=Hu(j)*N+E,o=Fu(j)*z+R;break;case Pu.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+Ou(G,W),s),(G-=W)>0&&t.lineTo(a+W,s+Ou(G,U)),(G-=U)>0&&t.lineTo(a+$u(W-G,0),s+U),(G-=W)>0&&t.lineTo(a,s+$u(U-G,0));break t}v+=X}t.rect(a,s,W,U);break;case Pu.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=Pu,t.initDefaultProps=((e=t.prototype)._saveData=!0,e._ux=0,e._uy=0,e._pendingPtDist=0,void(e._version=0)),t}();function Xu(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+=Ju);var h=Math.atan2(l,s);return h<0&&(h+=Ju),h>=i&&h<=r||h+Ju>=i&&h+Ju<=r}function eh(t,e,n,i,r,o){if(o>e&&o>i||or?s:0}var nh=Gu.CMD,ih=2*Math.PI;var rh=[-1,-1,-1],oh=[-1,-1];function ah(){var t=oh[0];oh[0]=oh[1],oh[1]=t}function sh(t,e,n,i,r,o,a,s,l,c){if(c>e&&c>i&&c>o&&c>s||c1&&ah(),p=ps(e,i,o,s,oh[0]),h>1&&(f=ps(e,i,o,s,oh[1]))),2===h?me&&s>i&&s>o||s=0&&d<=1&&(r[l++]=d);else{var c=a*a-4*o*s;if(us(c))(d=-a/(2*o))>=0&&d<=1&&(r[l++]=d);else if(c>0){var d,u=is(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,rh);if(0===l)return 0;var c=xs(e,i,o);if(c>=0&&c<=1){for(var d=0,u=ys(e,i,o,c),h=0;hn||s<-n)return 0;var l=Math.sqrt(n*n-s*s);rh[0]=-l,rh[1]=l;var c=Math.abs(i-r);if(c<1e-4)return 0;if(c>=ih-1e-4){i=0,r=ih;var d=o?1:-1;return a>=rh[0]+t&&a<=rh[1]+t?d:0}if(i>r){var u=i;i=r,r=u}i<0&&(i+=ih,r+=ih);for(var h=0,p=0;p<2;p++){var f=rh[p];if(f+t>a){var g=Math.atan2(s,f);d=o?1:-1;g<0&&(g=ih+g),(g>=i&&g<=r||g+ih>=i&&g+ih<=r)&&(g>Math.PI/2&&g<1.5*Math.PI&&(d=-d),h+=d)}}return h}function dh(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+=eh(d,u,h,p,i,r))),m&&(h=d=s[f],p=u=s[f+1]),g){case nh.M:d=h=s[f++],u=p=s[f++];break;case nh.L:if(n){if(Xu(d,u,s[f],s[f+1],e,i,r))return!0}else c+=eh(d,u,s[f],s[f+1],i,r)||0;d=s[f++],u=s[f++];break;case nh.C:if(n){if(Yu(d,u,s[f++],s[f++],s[f++],s[f++],s[f],s[f+1],e,i,r))return!0}else c+=sh(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 nh.Q:if(n){if(Zu(d,u,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+1],i,r)||0;d=s[f++],u=s[f++];break;case nh.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+=eh(d,u,o,a,i,r);var C=(i-v)*b/y+v;if(n){if(th(v,_,b,x,x+w,S,e,C,r))return!0}else c+=ch(v,_,b,x,x+w,S,C,r);d=Math.cos(x+w)*y+v,u=Math.sin(x+w)*b+_;break;case nh.R:if(h=d=s[f++],p=u=s[f++],o=h+s[f++],a=p+s[f++],n){if(Xu(h,p,o,p,e,i,r)||Xu(o,p,o,a,e,i,r)||Xu(o,a,h,a,e,i,r)||Xu(h,a,h,p,e,i,r))return!0}else c+=eh(o,p,o,a,i,r),c+=eh(h,a,h,p,i,r);break;case nh.Z:if(n){if(Xu(d,u,h,p,e,i,r))return!0}else c+=eh(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+=eh(d,u,h,p,i,r)||0),0!==c}var uh=Hr({fill:"#000",stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:"butt",miterLimit:10,strokeNoScale:!1,strokeFirst:!1},cu),hh={style:Hr({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},du.style)},ph=ac.concat(["invisible","culling","z","z2","zlevel","parent"]),fh=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?Yl:e>.2?"#eee":Zl}if(t)return Zl}return Yl},e.prototype.getInsideTextStroke=function(t){var e=this.style.fill;if(Qr(e)){var n=this.__zr;if(!(!n||!n.isDarkMode())===Gs(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 Gu(!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 dh(t,e,!0,n,i)}(o,a/s,t,e)))return!0}if(this.hasFill())return function(t,e,n){return dh(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:$r(n,t),this.dirtyShape(),this},e.prototype.shapeChanged=function(){return!!(4&this.__dirty)},e.prototype.createStyle=function(t){return wo(uh,t)},e.prototype._innerSaveToNormal=function(e){t.prototype._innerSaveToNormal.call(this,e);var n=this._normalState;e.shape&&!n.shape&&(n.shape=$r({},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=$r({},i.shape),$r(s,n.shape)):(s=$r({},r?this.shape:i.shape),$r(s,n.shape)):l&&(s=i.shape),s)if(o){this.shape=$r({},this.shape);for(var c={},d=Gr(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}(fh);Mh.prototype.type="rect";var Th={fill:"#000"},Ah={},Ih={style:Hr({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)},Ph=function(t){function e(e){var n=t.call(this)||this;return n.type="text",n._children=[],n._defaultStyle=Th,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=Ud(g,c,e.ellipsis,{minChar:e.truncateMinChar,placeholder:e.placeholder}),x={},w=0;w0,k=0;kg&&Qd(o,a.substring(g,m),e,f),Qd(o,h[2],e,f,h[1]),g=qd.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&&Vh(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=Fh(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,_=Hh("fill"in s?s.fill:"fill"in e?e.fill:(g=!0,f.fill)),y=$h("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||vr,p.opacity=co(s.opacity,e.opacity,1),Nh(p,s),y&&(p.lineWidth=co(s.lineWidth,e.lineWidth,m),p.lineDash=lo(s.lineDash,e.lineDash),p.lineDashOffset=e.lineDashOffset||0,p.stroke=y),_&&(p.fill=_),h.setBoundingRect(au(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(Mh)).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=lo(t.fillOpacity,1);else if(h){(s=this._getOrCreateChild(yh)).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=lo(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=co(t.opacity,e.opacity,1)},e.makeFont=function(t){var e="";return zh(t)&&(e=[t.fontStyle,t.fontWeight,Rh(t.fontSize),t.fontFamily||"sans-serif"].join(" ")),e&&fo(e)||t.textFont||t.font},e}(pu),Dh={left:!0,right:1,center:1},Lh={top:1,bottom:1,middle:1},Eh=["fontStyle","fontWeight","fontSize","fontFamily"];function Rh(t){return"string"!=typeof t||-1===t.indexOf("px")&&-1===t.indexOf("rem")&&-1===t.indexOf("em")?isNaN(+t)?"12px":t+"px":t}function Nh(t,e){for(var n=0;n=0,o=!1;if(t instanceof fh){var a=Uh(t),s=r&&a.selectFill||a.normalFill,l=r&&a.selectStroke||a.normalStroke;if(np(s)||np(l)){var c=(i=i||{}).style||{};"inherit"===c.fill?(o=!0,i=$r({},i),(c=$r({},c)).fill=s):!np(c.fill)&&np(s)?(o=!0,i=$r({},i),(c=$r({},c)).fill=Ys(s)):!np(c.stroke)&&np(l)&&(o||(i=$r({},i),c=$r({},c)),c.stroke=Ys(l)),i.style=c}}if(i&&null==i.z2){o||(i=$r({},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=Fr(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 Ip(t,e,n){Rp(t,!0),up(t,fp),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 Pp(t,e,n,i){i?function(t){Rp(t,!1)}(t):Ip(t,e,n)}var Dp=["emphasis","blur","select"],Lp={itemStyle:"getItemStyle",lineStyle:"getLineStyle",areaStyle:"getAreaStyle"};function Ep(t,e,n,i){n=n||"itemStyle";for(var r=0;r1&&(a*=Vp(f),s*=Vp(f));var g=(r===o?-1:1)*Vp((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+qp(u)*m-jp(u)*v,y=(e+i)/2+jp(u)*m+qp(u)*v,b=Xp([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=Xp(x,w);if(Gp(x,w)<=-1&&(S=Wp),Gp(x,w)>=1&&(S=0),S<0){var C=Math.round(S/Wp*1e6)/1e6;S=2*Wp+C%2*Wp}d.addData(c,_,y,a,s,b,S,u,o)}var Zp=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,Kp=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;var Qp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e.prototype.applyTransform=function(t){},e}(fh);function Jp(t){return null!=t.setData}function tf(t,e){var n=function(t){var e=new Gu;if(!t)return e;var n,i=0,r=0,o=i,a=r,s=Gu.CMD,l=t.match(Zp);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 _f(t,e){var n,i=ff(e.r,0),r=ff(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=hf(l-s),p=h>sf&&h%sf;if(p>mf&&(h=p),i>mf)if(h>sf-mf)t.moveTo(c+i*cf(s),d+i*lf(s)),t.arc(c,d,i,s,l,!u),r>mf&&(t.moveTo(c+r*cf(l),d+r*lf(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*cf(s),D=i*lf(s),L=r*cf(l),E=r*lf(l),R=h>mf;if(R){var N=e.cornerRadius;N&&(n=function(t){var e;if(Zr(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 z=hf(i-r)/2;if(_=gf(z,m),y=gf(z,v),b=gf(z,f),x=gf(z,g),C=w=ff(_,y),k=S=ff(b,x),(w>mf||S>mf)&&(M=i*cf(l),T=i*lf(l),A=r*cf(s),I=r*lf(s),hmf){var q=gf(m,C),W=gf(v,C),U=vf(A,I,P,D,i,q,u),G=vf(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,uf(U.y0,U.x0),uf(U.y1,U.x1),!u),t.arc(c,d,i,uf(U.cy+U.y1,U.cx+U.x1),uf(G.cy+G.y1,G.cx+G.x1),!u),W>0&&t.arc(c+G.cx,d+G.cy,W,uf(G.y1,G.x1),uf(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=gf(f,k),U=vf(L,E,M,T,r,-(W=gf(g,k)),u),G=vf(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,uf(U.y0,U.x0),uf(U.y1,U.x1),!u),t.arc(c,d,r,uf(U.cy+U.y1,U.cx+U.x1),uf(G.cy+G.y1,G.cx+G.x1),u),q>0&&t.arc(c+G.cx,d+G.cy,q,uf(G.y1,G.x1),uf(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 yf=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},bf=function(t){function e(e){return t.call(this,e)||this}return v(e,t),e.prototype.getDefaultShape=function(){return new yf},e.prototype.buildPath=function(t,e){_f(t,e)},e.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},e}(fh);bf.prototype.type="sector";var xf=function(){this.cx=0,this.cy=0,this.r=0,this.r0=0},wf=function(t){function e(e){return t.call(this,e)||this}return v(e,t),e.prototype.getDefaultShape=function(){return new xf},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}(fh);function Sf(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;hWf[1]){if(r=!1,Uf.negativeSize||n)return r;var s=jf(Wf[0]-qf[1]),l=jf(qf[0]-Wf[1]);Bf(s,l)>Xf.len()&&(s=l||!Uf.bidirectional)&&(ga.scale(Gf,a,-l*i),Uf.useDir&&Uf.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 tg(t,e,n,i,r,o){Jf("update",t,e,n,i,r,o)}function eg(t,e,n,i,r,o){Jf("enter",t,e,n,i,r,o)}function ng(t){if(!t.__zr)return!0;for(var e=0;e=-1e-6)return!1;var f=t-r,g=e-o,m=wg(f,g,c,d)/p;if(m<0||m>1)return!1;var v=wg(f,g,u,h)/p;return!(v<0||v>1)}function wg(t,e,n,i){return t*i-n*e}function Sg(t,e,n,i,r){return null==e||(to(e)?Cg[0]=Cg[1]=Cg[2]=Cg[3]=e:(Cg[0]=e[0],Cg[1]=e[1],Cg[2]=e[2],Cg[3]=e[3]),i&&(Cg[0]=Hc(0,Cg[0]),Cg[1]=Hc(0,Cg[1]),Cg[2]=Hc(0,Cg[2]),Cg[3]=Hc(0,Cg[3])),n&&(Cg[0]=-Cg[0],Cg[1]=-Cg[1],Cg[2]=-Cg[2],Cg[3]=-Cg[3]),kg(t,Cg,"x","width",3,1,r&&r[0]||0),kg(t,Cg,"y","height",0,2,r&&r[1]||0)),t}var Cg=[0,0,0,0];function kg(t,e,n,i,r,o,a){var s=e[o]+e[r],l=t[i];t[i]+=s,a=Hc(0,$c(a,l)),t[i]=0?-e[r]:e[o]>=0?l+e[o]:Fc(s)>1e-8?(l-a)*e[r]/s:0):t[n]-=e[r]}function Mg(t){var e=t.itemTooltipOption,n=t.componentModel,i=t.itemName,r=Qr(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(Gr(l),function(t){So(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:Hr({content:i,encodeHTMLContent:!0,formatterParams:s},r)}}function Tg(t,e){var n;t.isGroup&&(n=e(t)),n||t.traverse(e)}function Ag(t,e){if(t)if(Zr(t))for(var n=0;ne&&(e=i),ie&&(n=e=0),{min:n,max:e}},clipPointsByRect:function(t,e){return qr(t,function(t){var n=t[0];n=Hc(n,e.x),n=$c(n,e.x+e.width);var i=t[1];return i=Hc(i,e.y),[n,i=$c(i,e.y+e.height)]})},clipRectByRect:function(t,e){var n=Hc(t.x,e.x),i=$c(t.x+t.width,e.x+e.width),r=Hc(t.y,e.y),o=$c(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:bg,ensureCopyRect:Dg,ensureCopyTransform:Lg,expandOrShrinkRect:Sg,extendPath:function(t,e){return lg(t,e)},extendShape:function(t){return fh.extend(t)},getShapeClass:function(t){if(og.hasOwnProperty(t))return og[t]},getTransform:function(t,e){for(var n=ca([]);t&&t!==e;)ua(n,t.getLocalTransform(),n),t=t.parent;return n},groupTransition:yg,initProps:eg,isBoundingRectAxisAligned:Ig,isElementRemoved:ng,lineLineIntersect:xg,linePolygonIntersect:function(t,e,n,i,r){for(var o=0,a=r[r.length-1];oFc(o[1])?o[0]>0?"right":"left":o[1]>0?"bottom":"top"},traverseElements:Ag,traverseUpdateZ:Rg,updateProps:tg}),Og={};function $g(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=Kr(t.defaultText)?t.defaultText(o,t,n):t.defaultText);for(var l={normal:i},c=0;c-1?dm:hm;function mm(t,e){t=t.toUpperCase(),fm[t]=new sm(e),pm[t]=e}mm(um,{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(dm,{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 vm(){return null}var _m=1e3,ym=6e4,bm=36e5,xm=864e5,wm=31536e6,Sm={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})/},Cm={year:"{yyyy}",month:"{MMM}",day:"{d}",hour:"{HH}:{mm}",minute:"{HH}:{mm}",second:"{HH}:{mm}:{ss}",millisecond:"{HH}:{mm}:{ss} {SSS}"},km="{yyyy}-{MM}-{dd}",Mm={year:"{yyyy}",month:"{yyyy}-{MM}",day:km,hour:km+" "+Cm.hour,minute:km+" "+Cm.minute,second:km+" "+Cm.second,millisecond:"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}"},Tm=["year","month","day","hour","minute","second","millisecond"],Am=["year","half-year","quarter","month","week","half-week","day","half-day","quarter-day","hour","minute","second","millisecond"];function Im(t){return Qr(t)||Kr(t)?t:function(t){t=t||{};var e={},n=!0;return jr(Tm,function(e){n&&(n=null==t[e])}),jr(Tm,function(i,r){var o=t[i];e[i]={};for(var a=null,s=r;s>=0;s--){var l=Tm[s],c=eo(o)&&!Zr(o)?o[l]:o,d=void 0;Zr(c)?a=(d=c.slice())[0]||"":Qr(c)?d=[a=c]:(null==a?a=Cm[i]:Sm[l].test(a)||(a=e[l][l][0]+" "+a),d=[a],n&&(d[1]="{primary|"+a+"}")),e[i][l]=d}}),e}(t)}function Pm(t,e){return"0000".substr(0,e-(t+="").length)+t}function Dm(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 Lm(t){return t===Dm(t)}function Em(t,e,n,i){var r=Zc(t),o=r[zm(n)](),a=r[Om(n)]()+1,s=Math.floor((a-1)/3)+1,l=r[$m(n)](),c=r["get"+(n?"UTC":"")+"Day"](),d=r[Hm(n)](),u=(d-1)%12+1,h=r[Fm(n)](),p=r[Bm(n)](),f=r[Vm(n)](),g=d>=12?"pm":"am",m=g.toUpperCase(),v=i instanceof sm?i:function(t){return fm[t]}(i||gm)||fm[hm],_=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,Pm(o%100+"",2)).replace(/{Q}/g,s+"").replace(/{MMMM}/g,y[a-1]).replace(/{MMM}/g,b[a-1]).replace(/{MM}/g,Pm(a,2)).replace(/{M}/g,a+"").replace(/{dd}/g,Pm(l,2)).replace(/{d}/g,l+"").replace(/{eeee}/g,x[c]).replace(/{ee}/g,w[c]).replace(/{e}/g,c+"").replace(/{HH}/g,Pm(d,2)).replace(/{H}/g,d+"").replace(/{hh}/g,Pm(u+"",2)).replace(/{h}/g,u+"").replace(/{mm}/g,Pm(h,2)).replace(/{m}/g,h+"").replace(/{ss}/g,Pm(p,2)).replace(/{s}/g,p+"").replace(/{SSS}/g,Pm(f,3)).replace(/{S}/g,f+"")}function Rm(t,e){var n=Zc(t),i=n[Om(e)]()+1,r=n[$m(e)](),o=n[Hm(e)](),a=n[Fm(e)](),s=n[Bm(e)](),l=0===n[Vm(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 Nm(t,e,n){switch(e){case"year":t[qm(n)](0);case"month":t[Wm(n)](1);case"day":t[Um(n)](0);case"hour":t[Gm(n)](0);case"minute":t[Xm(n)](0);case"second":t[Ym(n)](0)}return t}function zm(t){return t?"getUTCFullYear":"getFullYear"}function Om(t){return t?"getUTCMonth":"getMonth"}function $m(t){return t?"getUTCDate":"getDate"}function Hm(t){return t?"getUTCHours":"getHours"}function Fm(t){return t?"getUTCMinutes":"getMinutes"}function Bm(t){return t?"getUTCSeconds":"getSeconds"}function Vm(t){return t?"getUTCMilliseconds":"getMilliseconds"}function jm(t){return t?"setUTCFullYear":"setFullYear"}function qm(t){return t?"setUTCMonth":"setMonth"}function Wm(t){return t?"setUTCDate":"setDate"}function Um(t){return t?"setUTCHours":"setHours"}function Gm(t){return t?"setUTCMinutes":"setMinutes"}function Xm(t){return t?"setUTCSeconds":"setSeconds"}function Ym(t){return t?"setUTCMilliseconds":"setMilliseconds"}function Zm(t){if(isNaN(Jc(t)))return Qr(t)?t:"-";var e=(t+"").split(".");return e[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,"$1,")+(e.length>1?"."+e[1]:"")}function Km(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 Qm=ho;function Jm(t,e,n){function i(t){return t&&fo(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?Zc(t):t;if(!isNaN(+s))return Em(s,"{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}",n);if(a)return"-"}if("ordinal"===e)return Jr(t)?i(t):to(t)&&r(t)?t+"":"-";var l=Jc(t);return r(l)?Zm(l):Jr(t)?i(t):"boolean"==typeof t?t+"":"-"}var tv=["a","b","c","d","e","f","g"],ev=function(t,e){return"{"+t+(null==e?"":e)+"}"};function nv(t,e,n){Zr(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 _v(t,e,n){n=Qm(n||0);var i=e.width,r=e.height,o=Vc(t.left,i),a=Vc(t.top,r),s=Vc(t.right,i),l=Vc(t.bottom,r),c=Vc(t.width,i),d=Vc(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 Ia((e.x||0)+o+n[3],(e.y||0)+a+n[0],c,d);return f.margin=n,f}Yr(vv,"vertical"),Yr(vv,"horizontal");var yv=1;function bv(t,e,n){var i,r,o,a,s=t.boxCoordinateSystem;if(s){var l=function(t){var e=t.getShallow("coord",!0),n=sv;if(null==e){var i=cv.get(t.type);i&&i.getCoord2&&(n=lv,e=i.getCoord2(t))}return{coord:e,from:n}}(t),c=l.coord,d=l.from;if(s.dataToLayout){o=yv,a=d;var u=s.dataToLayout(c);i=u.contentRect||u.rect}}return null==o&&(o=yv),o===yv&&(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 xv(t){var e=t.layoutMode||t.constructor.layoutMode;return eo(e)?e:e?{type:e}:null}function wv(t,e,n){var i=n&&n.ignoreSize;!Zr(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(fv(n,function(e){l[e]=t[e]}),fv(n,function(t){So(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=Or(o,n[a],!0);e.defaultOption=o}return e.defaultOption},e.prototype.getReferringComponents=function(t,e){var n=t+"Index",i=t+"Id";return kd(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}(sm);Dd(kv,sm),Nd(kv),function(t){var e={};t.registerSubTypeDefaulter=function(t,n){var i=Id(t);e[i.main]=n},t.determineSubType=function(n,i){var r=i.type;if(!r){var o=Id(n).main;t.hasSubTypes(n)&&e[o]&&(r=e[o](i))}return r}}(kv),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){Fr(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){Fr(a.predecessor,t)<0&&a.predecessor.push(t);var e=n(i,t);Fr(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)}}}(kv,function(t){var e=[];jr(kv.getClassesByMainType(t),function(t){e=e.concat(t.dependencies||t.prototype.dependencies||[])}),e=qr(e,function(t){return Id(t).main}),"dataset"!==t&&Fr(e,"dataset")<=0&&e.unshift("dataset");return e});var Mv={color:{},darkColor:{},size:{}},Tv=Mv.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 Av in $r(Tv,{primary:Tv.neutral80,secondary:Tv.neutral70,tertiary:Tv.neutral60,quaternary:Tv.neutral50,disabled:Tv.neutral20,border:Tv.neutral30,borderTint:Tv.neutral20,borderShade:Tv.neutral40,background:Tv.neutral05,backgroundTint:"rgba(234,237,245,0.5)",backgroundTransparent:"rgba(255,255,255,0)",backgroundShade:Tv.neutral10,shadow:"rgba(0,0,0,0.2)",shadowTint:"rgba(129,130,136,0.2)",axisLine:Tv.neutral70,axisLineTint:Tv.neutral40,axisTick:Tv.neutral70,axisTickMinor:Tv.neutral60,axisLabel:Tv.neutral70,axisSplitLine:Tv.neutral15,axisMinorSplitLine:Tv.neutral05}),Tv)if(Tv.hasOwnProperty(Av)){var Iv=Tv[Av];"theme"===Av?Mv.darkColor.theme=Tv.theme.slice():"highlight"===Av?Mv.darkColor.highlight="rgba(255,231,130,0.4)":0===Av.indexOf("accent")?Mv.darkColor[Av]=Ws(Iv,0,function(t){return.5*t},function(t){return Math.min(1,1.3-t)}):Mv.darkColor[Av]=Ws(Iv,0,function(t){return.9*t},function(t){return 1-Math.pow(t,1.5)})}Mv.size={xxs:2,xs:5,s:10,m:15,l:20,xl:30,xxl:40,xxxl:50};var Pv="";"undefined"!=typeof navigator&&(Pv=navigator.platform||"");var Dv="rgba(0, 0, 0, 0.2)",Lv=Mv.color.theme[0],Ev=Ws(Lv,0,null,.9),Rv={darkMode:"auto",colorBy:"series",color:Mv.color.theme,gradientColor:[Ev,Lv],aria:{decal:{decals:[{color:Dv,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:Dv,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:Dv,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:Dv,dashArrayX:[[6,6],[0,6,6,0]],dashArrayY:[6,0]},{color:Dv,dashArrayX:[[1,0],[1,6]],dashArrayY:[1,0,6,0],rotation:Math.PI/4},{color:Dv,symbol:"triangle",dashArrayX:[[9,9],[0,9,9,0]],dashArrayY:[7,2],symbolSize:.75}]}},textStyle:{fontFamily:Pv.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},Nv=xo(["tooltip","label","itemName","itemId","itemGroupId","itemChildGroupId","seriesName"]),zv="original",Ov="arrayRows",$v="objectRows",Hv="keyedColumns",Fv="typedArray",Bv="unknown",Vv="column",jv="row",qv=1,Wv=2,Uv=3,Gv=bd();function Xv(t,e,n){var i={},r=Yv(e);if(!r||!t)return i;var o,a,s=[],l=[],c=e.ecModel,d=Gv(c).datasetMap,u=r.uid+"_"+n.seriesLayoutBy;jr(t=t.slice(),function(e,n){var r=eo(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,Qv,i,r,t,e,n)},t.prototype.clearColorPalette=function(){!function(t,e){e(t).paletteIdx=0,e(t).paletteNameMap={}}(this,Qv)},t}();var i_="\0_ec_inner",r_=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 sm(i),this._locale=new sm(r),this._optionManager=o},e.prototype.setOption=function(t,e,n){var i=s_(e);this._optionManager.setOption(t,n,i),this._resetOption(null,i)},e.prototype.resetOption=function(t,e){return this._resetOption(t,s_(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)):e_(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=xo(),s=e&&e.replaceMergeMainTypeMap;Gv(this).datasetMap=xo(),jr(t,function(t,e){null!=t&&(kv.hasClass(e)?e&&(o.push(e),a.set(e,!0)):n[e]=null==n[e]?zr(t):Or(n[e],t,!0))}),s&&s.each(function(t,e){kv.hasClass(e)&&!a.get(e)&&(o.push(e),a.set(e,!0))}),kv.topologicalTravel(o,kv.getAllClassMainTypes(),function(e){var o=function(t,e,n){var i=Kv.get(e);if(!i)return n;var r=i(t);return r?n.concat(r):n}(this,e,ld(t[e])),a=i.get(e),l=a?s&&s.get(e)?"replaceMerge":"normalMerge":"replaceAll",c=pd(a,o,l);(function(t,e,n){jr(t,function(t){var i=t.newOption;eo(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,kv),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=kv.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=$r({componentIndex:n},t.keyInfo);$r(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&&Jv(this)},this),this._seriesIndices||Jv(this)},e.prototype.getOption=function(){var t=zr(this.option);return jr(t,function(e,n){if(kv.hasClass(n)){for(var i=ld(e),r=i.length,o=!1,a=r-1;a>=0;a--)i[a]&&!_d(i[a])?o=!0:(i[a]=null,!o&&r--);i.length=r,t[n]=i}}),delete t[i_],t},e.prototype.setTheme=function(t){this._theme=new sm(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 p_=jr,f_=eo,g_=["areaStyle","lineStyle","nodeStyle","linkStyle","chordStyle","label","labelLine"];function m_(t){var e=t&&t.itemStyle;if(e)for(var n=0,i=g_.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 oy(this.getData(e),t)},t.prototype.formatTooltip=function(t,e,n){},t}();function ly(t){var e,n;return eo(t)?t.type&&(n=t):e=t,{text:e,frag:n}}function cy(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=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}(),fy=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 hy(t,e)},t}();function gy(t){if(!xy(t.sourceFormat)){od("")}return t.data}function my(t){var e=t.sourceFormat,n=t.data;if(!xy(e)){od("")}if(e===Ov){for(var i=[],r=0,o=n.length;r65535?Cy:ky}function Py(){return[1/0,-1/0]}function Dy(t){var e=t.constructor;return e===Array?t.slice():new e(t)}function Ly(t,e,n,i,r){var o=Ay[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=qr(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(Iy(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 hy(t[i],this._dimensions[i])}wy={arrayRows:t,objectRows:function(t,e,n,i){return hy(t[e],this._dimensions[i])},keyedColumns:t,original:function(t,e,n,i){var r=t&&(null==t.value?t:t.value);return hy(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(Ny(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=io(a=o.get("data",!0))?Fv:zv,e=[];var d=this._getSourceMetaRawOption()||{},u=l&&l.metaRawOption||{},h=lo(d.seriesLayoutBy,u.seriesLayoutBy)||null,p=lo(d.sourceHeader,u.sourceHeader),f=lo(d.dimensions,u.dimensions);t=h!==u.seriesLayoutBy||!!p!=!!u.sourceHeader||f?[B_(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=[B_(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 jr(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=ld(t),i=n.length;i||od("");for(var r=0,o=i;r1||n>0&&!t.noHeader;return jr(t.blocks,function(t){var n=qy(t);n>=e&&(e=n+ +(i&&(!n||Vy(t)&&!t.noHeader)))}),e}return 0}function Wy(t,e,n,i){var r,o=e.noHeader,a=(r=qy(e),{html:Hy[r],richText:Fy[r]}),s=[],l=e.blocks||[];po(!l||Zr(l)),l=l||[];var c=t.orderMode;if(e.sortBlocks&&c){l=l.slice();var d={valueAsc:"asc",valueDesc:"desc"};if(So(d,c)){var u=new py(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?$r($r({},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):Xy(i,s.join(""),o?n:a.html);if(o)return h;var p=Jm(e.header,"ordinal",t.useUTC),f=$y(i,t.renderMode).nameStyle,g=Oy(i);return"richText"===t.renderMode?Yy(t,p,f)+a.richText+h:Xy(i,'
'+Zo(p)+"
"+h,n)}function Uy(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 qr(t=Zr(t)?t:[t],function(t,e){return Jm(t,Zr(p)?p[e]:p,c)})};if(!o||!a){var u=s?"":t.markupStyleCreator.makeTooltipMarker(e.markerType,e.markerColor||Mv.color.secondary,r),h=o?"":Jm(l,"ordinal",c),p=e.valueType,f=a?[]:d(e.value,e.dataIndex),g=!s||!o,m=!s&&o,v=$y(i,r),_=v.nameStyle,y=v.valueStyle;return"richText"===r?(s?"":u)+(o?"":Yy(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(Zr(e)?e.join(" "):e,o)}(t,f,g,m,y)):Xy(i,(s?"":u)+(o?"":function(t,e,n){return''+Zo(t)+""}(h,!s,_))+(a?"":function(t,e,n,i){var r=n?"10px":"20px",o=e?"float:right;margin-left:"+r:"";return t=Zr(t)?t:[t],''+qr(t,function(t){return Zo(t)}).join("  ")+""}(f,g,m,y)),n)}}function Gy(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 Xy(t,e,n){return'
'+e+'
'}function Yy(t,e,n){return t.markupStyleCreator.wrapRichTextStyle(e,n)}function Zy(t,e){var n=t.get("padding");return null!=n?n:"richText"===e?[8,10]:10}var Ky=function(){function t(){this.richTextStyles={},this._nextStyleNameId=td()}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=Qr(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 Qr(r)?r:(this.richTextStyles[i]=r.style,r.content)},t.prototype.wrapRichTextStyle=function(t,e){var n={};Zr(e)?jr(e,function(t){return $r(n,t)}):$r(n,e);var i=this._generateStyleName();return this.richTextStyles[i]=n,"{"+i+"|"+t+"}"},t}();function Qy(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=Zr(u),p=function(t,e){return iv(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=Wr(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(By("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(oy(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=oy(l,a,c[0]),n=g.type}else r=e=h?u[0]:u;var m=vd(o),v=m&&o.name||"",_=l.getName(a),y=s?v:_;return By("section",{header:v,noHeader:s||!m,sortParam:r,blocks:[By("nameValue",{markerType:"item",markerColor:p,name:y,noName:!fo(y),value:e,valueType:n,dataIndex:a})].concat(i||[])})}var Jy=bd();function tb(t,e){return t.getName(e)||t.getId(e)}var eb=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=cy({count:ib,reset:rb}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(t,n),(Jy(this).sourceManager=new Ry(this)).prepareSource();var i=this.getInitialData(t,n);ab(i,this),this.dataTask.context.data=i,Jy(this).dataBeforeProcessed=i,nb(this),this._initSelectedMapFromData(i)},e.prototype.mergeDefaultAndTheme=function(t,e){var n=xv(this),i=n?Sv(t):{},r=this.subType;kv.hasClass(r)&&(r+="Series"),Or(t,e.getTheme().get(this.subType)),Or(t,this.getDefaultOption()),cd(t,"label",["show"]),this.fillDataTextStyle(t.data),n&&wv(t,i,n)},e.prototype.mergeOption=function(t,e){t=Or(this.option,t,!0),this.fillDataTextStyle(t.data);var n=xv(this);n&&wv(this.option,t,n);var i=Jy(this).sourceManager;i.dirty(),i.prepareSource();var r=this.getInitialData(t,e);ab(r,this),this.dataTask.dirty(),this.dataTask.context.data=r,Jy(this).dataBeforeProcessed=r,nb(this),this._initSelectedMapFromData(r)},e.prototype.fillDataTextStyle=function(t){if(t&&!io(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 Qy({series:this,dataIndex:t,multipleSeries:e})},e.prototype.isAnimationEnabled=function(){var t=this.ecModel;if(gr.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=n_.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[tb(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){eo(r.selectedMap)||(r.selectedMap={});for(var s=r.selectedMap,l=0;l0&&this._innerSelect(t,e)}},e.registerClass=function(t){return kv.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}(kv);function nb(t){var e=t.name;vd(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 ib(t){return t.model.getRawData().count()}function rb(t){var e=t.model;return e.setData(e.getRawData().cloneShallow()),ob}function ob(t,e){e.outputData&&t.end>e.outputData.count()&&e.model.getRawData().cloneShallow(e.outputData)}function ab(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 Sb(t,e,n,i){var r=t[e];if(r){var o=r[yb]||r,a=r[xb];if(r[bb]!==n||a!==i){if(null==n||!i)return t[e]=o;(r=t[e]=wb(o,n,"debounce"===i))[yb]=o,r[xb]=i,r[bb]=n}return r}}function Cb(t,e){var n=t[e];n&&n[yb]&&(n.clear&&n.clear(),t[e]=n[yb])}var kb=bd(),Mb={itemStyle:zd(rm,!0),lineStyle:zd(em,!0)},Tb={lineStyle:"stroke",itemStyle:"fill"};function Ab(t,e){var n=t.visualStyleMapper||Mb[e];return n||(console.warn("Unknown style type '"+e+"'."),Mb.itemStyle)}function Ib(t,e){var n=t.visualDrawType||Tb[e];return n||(console.warn("Unknown style type '"+e+"'."),"fill")}var Pb={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=t.getModel(i),o=Ab(t,i)(r),a=r.getShallow("decal");a&&(n.setVisual("decal",a),a.dirty=!0);var s=Ib(t,i),l=o[s],c=Kr(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||Kr(o.fill)?u:o.fill,o.stroke="auto"===o.stroke||Kr(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=$r({},o);r[s]=c(i),e.setItemVisual(n,"style",r)}}}},Db=new sm,Lb={createOnAllSeries:!0,performRawSeries:!0,reset:function(t,e){if(!t.ignoreStyleOnData&&!e.isSeriesFiltered(t)){var n=t.getData(),i=t.visualStyleAccessPath||"itemStyle",r=Ab(t,i),o=n.getVisual("drawType");return{dataEach:n.hasItemOption?function(t,e){var n=t.getRawDataItem(e);if(n&&n[i]){Db.option=n[i];var a=r(Db);$r(t.ensureUniqueItemVisual(e,"style"),a),Db.option.decal&&(t.setItemVisual(e,"decal",Db.option.decal),Db.option.decal.dirty=!0),o in a&&t.setItemVisual(e,"colorFromPalette",!1)}}:null}}}},Eb={performRawSeries:!0,overallReset:function(t){var e=xo();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)),kb(t).scope=r}}),t.eachSeries(function(e){if(!e.isColorBySeries()&&!t.isSeriesFiltered(e)){var n=e.getRawData(),i={},r=e.getData(),o=kb(e).scope,a=e.visualStyleAccessPath||"itemStyle",s=Ib(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)}})}})}},Rb=Math.PI;var Nb=function(){function t(t,e,n,i){this._stageTaskMap=xo(),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=xo();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,{});po(!(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=xo(),s=t.seriesType,l=t.getTargetSeries;function c(e){var s=e.uid,l=a.set(s,o&&o.get(s)||cy({plan:Fb,reset:Bb,count:qb}));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||cy({reset:zb});o.context={ecModel:n,api:i,overallReset:t.overallReset,scheduler:r};var a=o.agentStubMap,s=o.agentStubMap=xo(),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,cy({reset:Ob,onDirty:Hb})));n.context={model:t,overallProgress:d},n.agent=o,n.__block=d,r._pipe(t,n)}po(!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 Kr(t)&&(t={overallReset:t,seriesType:Wb(t)}),t.uid=cm("stageHandler"),e&&(t.visualType=e),t},t}();function zb(t){t.overallReset(t.ecModel,t.api,t.payload)}function Ob(t){return t.overallProgress&&$b}function $b(){this.agent.dirty(),this.getDownstream().dirty()}function Hb(){this.agent&&this.agent.dirty()}function Fb(t){return t.plan?t.plan(t.model,t.ecModel,t.api,t.payload):null}function Bb(t){t.useClearVisual&&t.data.clearAllVisual();var e=t.resetDefines=ld(t.reset(t.model,t.ecModel,t.api,t.payload));return e.length>1?qr(e,function(t,e){return jb(e)}):Vb}var Vb=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}(),ix=["symbol","symbolSize","symbolRotate","symbolOffset"],rx=ix.concat(["symbolKeepAspect"]),ox={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&&Sx(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=Sx(i)?i:0,r=Sx(r)?r:1,o=Sx(o)?o:0,a=Sx(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]:to(e)?[e]:Zr(e)?e:null:null),o=i.lineDashOffset;if(r){var a=i.strokeNoScale&&t.getLineScale?t.getLineScale():1;a&&1!==a&&(r=qr(r,function(t){return t/a}),o/=a)}return[r,o]}var Ax=new Gu(!0);function Ix(t){var e=t.stroke;return!(null==e||"none"===e||!(t.lineWidth>0))}function Px(t){return"string"==typeof t&&"none"!==t}function Dx(t){var e=t.fill;return null!=e&&"none"!==e}function Lx(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 Ex(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 Rx(t,e,n){var i=Bd(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)*ko),o.scaleSelf(e.scaleX||1,e.scaleY||1),r.setTransform(o)}return r}}var Nx=["shadowBlur","shadowOffsetX","shadowOffsetY"],zx=[["lineCap","butt"],["lineJoin","miter"],["miterLimit",10]];function Ox(t,e,n,i,r){var o=!1;if(!i&&e===(n=n||{}))return!1;if(i||e.opacity!==n.opacity){Fx(t,r),o=!0;var a=Math.max(Math.min(e.opacity,1),0);t.globalAlpha=isNaN(a)?cu.opacity:a}(i||e.blend!==n.blend)&&(o||(Fx(t,r),o=!0),t.globalCompositeOperation=e.blend||cu.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[ew])if(this._disposed)this.id;else{var i,r,o;if(eo(e)&&(n=e.lazyUpdate,i=e.silent,r=e.replaceMerge,o=e.transition,e=e.notMerge),this[ew]=!0,Aw(this),!this._model||e){var a=new u_(this._api),s=this._theme,l=this._model=new r_;l.scheduler=this._scheduler,l.ssr=this._ssr,l.init(null,null,null,s,this._locale,a)}this._model.setOption(t,{replaceMerge:r},$w);var c={seriesTransition:o,optionChanged:!0};if(n)this[iw]={silent:i,updateParams:c},this[ew]=!1,this.getZr().wakeUp();else{try{dw(this),pw.update.call(this,null,c)}catch(t){throw this[iw]=null,this[ew]=!1,t}this._ssr||this._zr.flush(),this[iw]=null,this[ew]=!1,vw.call(this,i),_w.call(this,i)}}},e.prototype.setTheme=function(t,e){if(!this[ew])if(this._disposed)this.id;else{var n=this._model;if(n){var i=e&&e.silent,r=null;this[iw]&&(null==i&&(i=this[iw].silent),r=this[iw].updateParams,this[iw]=null),this[ew]=!0,Aw(this);try{this._updateTheme(t),n.setTheme(this._theme),dw(this),pw.update.call(this,{type:"setTheme"},r)}catch(t){throw this[ew]=!1,t}this[ew]=!1,vw.call(this,i),_w.call(this,i)}}},e.prototype._updateTheme=function(t){Qr(t)&&(t=Fw[t]),t&&((t=zr(t))&&L_(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||gr.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(Vw,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=xr.createCanvas(),g=zc(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 Mh({shape:{x:0,y:0,width:h,height:p},style:{fill:t.connectedBackgroundColor}})),jr(d,function(t){var e=new yh({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 fw(this,"convertToPixel",t,e,n)},e.prototype.convertToLayout=function(t,e,n){return fw(this,"convertToLayout",t,e,n)},e.prototype.convertFromPixel=function(t,e,n){return fw(this,"convertFromPixel",t,e,n)},e.prototype.containPixel=function(t,e){var n;if(!this._disposed)return jr(wd(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=wd(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(Ew,function(e){var n=function(n){var i,r=t.getModel(),o=n.target;if("globalout"===e?i={}:o&&lx(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=$r({},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(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?(sx("map","selectchanged",e,i,t),sx("pie","selectchanged",e,i,t)):"select"===t.fromAction?(sx("map","selected",e,i,t),sx("pie","selected",e,i,t)):"unselect"===t.fromAction&&(sx("map","unselected",e,i,t),sx("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()&&Md(this.getDom(),Ww,"");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 Vw[t.id]}},e.prototype.resize=function(t){if(!this[ew])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[iw]&&(null==i&&(i=this[iw].silent),n=!0,this[iw]=null),this[ew]=!0,Aw(this);try{n&&dw(this),pw.update.call(this,{type:"resize",animation:$r({duration:0},t&&t.animation)})}catch(t){throw this[ew]=!1,t}this[ew]=!1,vw.call(this,i),_w.call(this,i)}}},e.prototype.showLoading=function(t,e){if(this._disposed)this.id;else if(eo(t)&&(e=t,t=""),t=t||"default",this.hideLoading(),Bw[t]){var n=Bw[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=$r({},t);return e.type=Nw[t.type],e},e.prototype.dispatchAction=function(t,e){if(this._disposed)this.id;else if(eo(e)||(e={silent:!!e}),Rw[t.type]&&this._model)if(this[ew])this._pendingActions.push(t);else{var n=e.silent;mw.call(this,t,n);var i=e.flush;i?this._zr.flush():!1!==i&&gr.browser.weChat&&this._throttledZrFlush(),vw.call(this,n),_w.call(this,n)}},e.prototype.updateLabelLayout=function(){Zx.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(ng(t))return;if(t instanceof fh&&function(t){var e=Uh(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)}})}dw=function(t){var e=t._scheduler;e.restorePipelines(t._model),e.prepareStageTasks(),uw(t,!0),uw(t,!1),e.plan()},uw=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")&&!gr.node&&!gr.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),Zx.trigger("series:afterupdate",e,o,s)},Mw=function(t){t[rw]=!0,t.getZr().wakeUp()},Aw=function(t){t[nw]=(t[nw]+1)%1e3},Tw=function(t){t[rw]&&(t.getZr().storage.traverse(function(t){ng(t)||e(t)}),t[rw]=!1)},Cw=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){vp(e,n),Mw(t)},n.prototype.leaveEmphasis=function(e,n){_p(e,n),Mw(t)},n.prototype.enterBlur=function(e){!function(t){up(t,ap)}(e),Mw(t)},n.prototype.leaveBlur=function(e){yp(e),Mw(t)},n.prototype.enterSelect=function(e){bp(e),Mw(t)},n.prototype.leaveSelect=function(e){xp(e),Mw(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[nw]},n}(c_))(t)},kw=function(t){function e(t,e){for(var n=0;n=0)){Jw.push(n);var o=Nb.wrapStageHandler(n,r);o.__prio=e,o.__raw=n,t.push(o)}}function eS(t,e){Bw[t]=e}var nS=function(t){var e=(t=zr(t)).type;e||od("");var n=e.split(":");2!==n.length&&od("");var i=!1;"echarts"===n[0]&&(e=n[1],i=!0),t.__isBuiltIn=i,yy.set(e,t)};function iS(t,e,n,i){return{eventContent:{selected:Ap(n),isFromClick:e.isFromClick||!1}}}function rS(t){return null==t?0:t.length||1}function oS(t){return t}Qw(Qx,Pb),Qw(Jx,Lb),Qw(Jx,Eb),Qw(Qx,ox),Qw(Jx,ax),Qw(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=Ux(n,e))});var r=i.getVisual("decal");if(r)i.getVisual("style").decal=Ux(r,e)}})}),Xw(L_),Yw(900,function(t){var e=xo();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=Uc(p,v),f=v;break}}}return i[0]=p,i[1]=f,i})})}(t))})}),eS("default",function(t,e){Hr(e=e||{},{text:"loading",textColor:Mv.color.primary,fontSize:12,fontWeight:"normal",fontStyle:"normal",fontFamily:"sans-serif",maskColor:"rgba(255,255,255,0.8)",showSpinner:!0,color:Mv.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new Dc,i=new Mh({style:{fill:e.maskColor},zlevel:e.zlevel,z:1e4});n.add(i);var r,o=new Ph({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 Mh({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:-Rb/2,endAngle:-Rb/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*Rb/2}).start("circularInOut"),r.animateShape(!0).when(1e3,{startAngle:3*Rb/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}),Kw({type:Zh,event:Zh,update:Zh},Co),Kw({type:Kh,event:Kh,update:Kh},Co),Kw({type:Qh,event:ep,update:Qh,action:Co,refineEvent:iS,publishNonRefinedEvent:!0}),Kw({type:Jh,event:ep,update:Jh,action:Co,refineEvent:iS,publishNonRefinedEvent:!0}),Kw({type:tp,event:ep,update:tp,action:Co,refineEvent:iS,publishNonRefinedEvent:!0}),Gw("default",{}),Gw("dark",ex);var aS=function(){function t(t,e,n,i,r,o){this._old=t,this._new=e,this._oldKeyGetter=n||oS,this._newKeyGetter=i||oS,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 vS,_S,yS,bS,xS,wS,SS,CS=eo,kS=qr,MS="undefined"==typeof Int32Array?Array:Int32Array,TS=["hasItemOption","_nameList","_idList","_invertedIndicesMap","_dimSummary","userOutput","_rawData","_dimValueGetter","_nameDimIdx","_idDimIdx","_nameRepeatCount"],AS=["_approximateExtent"],IS=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;pS(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&&(Zr(r=this.getVisual(e))?r=r.slice():CS(r)&&(r=$r({},r)),i[e]=r),r},t.prototype.setItemVisual=function(t,e,n){var i=this._itemVisuals[t]||{};this._itemVisuals[t]=i,CS(e)?$r(i,e):i[e]=n},t.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},t.prototype.setLayout=function(t,e){CS(t)?$r(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?$r(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:kS(this.dimensions,this._getDimInfo,this),this.hostModel)),xS(e,this),e._store=this._store,e},t.prototype.wrapMethod=function(t,e){var n=this[t];Kr(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(t),this[t]=function(){var t=n.apply(this,arguments);return e.apply(this,[t].concat(uo(arguments)))})},t.internalField=(vS=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 MS(o.categories.length);for(var s=0;s1&&(s+="__ec__"+c),i[e]=s}})),t}();function PS(t,e){F_(t)||(t=V_(t));var n=(e=e||{}).coordDimensions||[],i=e.dimensionsDefine||t.dimensionsDefine||[],r=xo(),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;eo(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?gS(t):fS(i),d=e.encodeDefine;!d&&e.encodeDefaulter&&(d=e.encodeDefaulter(t,a));for(var u=xo(d),h=new My(a),p=0;p0&&(i.name=r+(o-1)),o++,e.set(r,o)}}(o),new hS({source:t,dimensions:o,fullDimensionCount:a,dimensionOmitted:s})}function DS(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 LS=function(t){this.coordSysDims=[],this.axisMap=xo(),this.categoryAxisMap=xo(),this.coordSysName=t};var ES={cartesian2d:function(t,e,n,i){var r=t.getReferringComponents("xAxis",Cd).models[0],o=t.getReferringComponents("yAxis",Cd).models[0];e.coordSysDims=["x","y"],n.set("x",r),n.set("y",o),RS(r)&&(i.set("x",r),e.firstCategoryDimIndex=0),RS(o)&&(i.set("y",o),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=1))},singleAxis:function(t,e,n,i){var r=t.getReferringComponents("singleAxis",Cd).models[0];e.coordSysDims=["single"],n.set("single",r),RS(r)&&(i.set("single",r),e.firstCategoryDimIndex=0)},polar:function(t,e,n,i){var r=t.getReferringComponents("polar",Cd).models[0],o=r.findAxisModel("radiusAxis"),a=r.findAxisModel("angleAxis");e.coordSysDims=["radius","angle"],n.set("radius",o),n.set("angle",a),RS(o)&&(i.set("radius",o),e.firstCategoryDimIndex=0),RS(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),RS(s)&&(i.set(l,s),null==e.firstCategoryDimIndex&&(e.firstCategoryDimIndex=o))})},matrix:function(t,e,n,i){var r=t.getReferringComponents("matrix",Cd).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 RS(t){return"category"===t.get("type")}function NS(t,e,n){var i,r,o,a=(n=n||{}).byIndex,s=n.stackedCoordDimension;!function(t){return!pS(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){Qr(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 zS(t,e){return!!e&&e===t.getCalculationInfo("stackedDimension")}function OS(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 LS(e),i=ES[e];if(i)return i(t,n,n.axisMap,n.categoryAxisMap),n}(e),s=function(t,e){var n,i=t.get("coordinateSystem"),r=av.get(i);return e&&e.coordSysDims&&(n=qr(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=Kr(l)?l:l?Yr(Xv,s,e):null,d=PS(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=NS(e,{schema:d,store:h}),f=new IS(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=BS(a);return function(t,e){!isFinite(t[0])&&(t[0]=e[0]),!isFinite(t[1])&&(t[1]=e[1]),VS(t,0,e),VS(t,1,e),t[0]>t[1]&&(t[0]=t[1])}(o.niceTickExtent=[qc(Math.ceil(t[0]/a)*a,s),qc(Math.floor(t[1]/a)*a,s)],t),o}function FS(t){var e=Math.pow(10,Kc(t)),n=t/e;return n?2===n?n=3:3===n?n=5:n*=2:n=1,qc(n*e)}function BS(t){return Wc(t)+2}function VS(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 qS=function(){function t(){this.normalize=WS,this.scale=US}return t.prototype.updateMethods=function(t){t.hasBreaks()?(this.normalize=Xr(t.normalize,t),this.scale=Xr(t.scale,t)):(this.normalize=WS,this.scale=US)},t}();function WS(t,e){return e[1]===e[0]?.5:(t-e[0])/(e[1]-e[0])}function US(t,e){return t*(e[1]-e[0])+e[0]}function GS(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 XS=function(){function t(t){this._calculator=new qS,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}();Nd(XS);var YS=0,ZS=function(){function t(t){this.categories=t.categories||[],this._needCollect=t.needCollect,this._deduplication=t.deduplication,this.uid=++YS,this._onCollect=t.onCollect}return t.createByAxisModel=function(e){var n=e.option,i=n.data,r=i&&qr(i,KS);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(!Qr(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=xo(this.categories))},t}();function KS(t){return eo(t)&&null!=t.value?t.value:t+""}var QS=function(t){function e(e){var n=t.call(this,e)||this;n.type="ordinal";var i=n.getSetting("ordinalMeta");return i||(i=new ZS({})),Zr(i)&&(i=new ZS({categories:qr(i,function(t){return eo(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:Qr(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}(XS);XS.registerClass(QS);var JS=qc,tC=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=BS(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=JS(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:JS(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=Vc(t.get("barWidth"),i),p=Vc(t.get("barMaxWidth"),i),f=Vc(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:oC(r),stackId:rC(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=Gr(i).length;o=Math.max(35-4*a,15)+"%"}var s=Vc(o,r),l=Vc(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 sC=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 Em(t.value,Mm[function(t){switch(t){case"year":case"month":return"day";case"millisecond":return"millisecond";default:return"second"}}(Dm(this._minLevelUnit))]||Mm.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(Qr(n))o=n;else if(Kr(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=Rm(t.value,r);o=n[d][d][0]}}return Em(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=Rm(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=Am,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 Nm(new Date(e),t,i).getTime()===Nm(new Date(n),t,i).getTime()}(Dm(t),i[0],i[1],n)){s&&(r=[{value:fC(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=Ur(qr(u,function(t){return Ur(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=lC.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 dC(t){return(t/=2592e6)>6?6:t>3?3:t>2?2:1}function uC(t){return(t/=bm)>12?12:t>6?6:t>3.5?4:t>2?2:1}function hC(t,e){return(t/=e?ym:_m)>30?30:t>20?20:t>15?15:t>10?10:t>5?5:t>2?2:1}function pC(t){return Qc(t)}function fC(t,e,n){var i=Math.max(0,Fr(Tm,e)-1);return Nm(new Date(t),Tm[i],n).getTime()}XS.registerClass(sC);var gC=qc,mC=Math.floor,vC=Math.ceil,_C=Math.pow,yC=Math.log,bC=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.type="log",e.base=10,e._originalScale=new tC,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(),qr(r,function(t){var e=t.value,r=null,a=_C(o,e);return e===n[0]&&this._fixMin?r=i[0]:e===n[1]&&this._fixMax&&(r=i[1]),null!=r&&(a=xC(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=GS(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]=_C(e,n[0]),n[1]=_C(e,n[1]);var i=this._originalScale.getExtent();return this._fixMin&&(n[0]=xC(n[0],i[0])),this._fixMax&&(n[1]=xC(n[1],i[1])),n},e.prototype.unionExtentFromData=function(t,e){this._originalScale.unionExtentFromData(t,e);var n=GS(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,Kc(i)));for(t/n*r<=.5&&(r*=10);!isNaN(r)&&Math.abs(r)<1&&Math.abs(r)>0;)r*=10;var o=[gC(vC(e[0]/r)*r),gC(mC(e[1]/r)*r)];this._interval=r,this._intervalPrecision=BS(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=yC(e)/yC(this.base),t.prototype.contain.call(this,e)},e.prototype.normalize=function(e){return e=yC(e)/yC(this.base),t.prototype.normalize.call(this,e)},e.prototype.scale=function(e){return e=t.prototype.scale.call(this,e),_C(this.base,e)},e.prototype.setBreaksFromOption=function(t){},e.type="log",e}(tC);function xC(t,e){return gC(t,Wc(e))}XS.registerClass(bC);var wC=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[CC[t]]=e},t.prototype.setDeterminedMinMax=function(t,e){this[SC[t]]=e},t.prototype.freeze=function(){this.frozen=!0},t}(),SC={min:"_determinedMin",max:"_determinedMax"},CC={min:"_dataMin",max:"_dataMax"};function kC(t,e){return null==e?null:ao(e)?NaN:t.parse(e)}function MC(t,e){var n=t.type,i=function(t,e,n){var i=t.rawExtentInfo;return i||(i=new wC(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=aC(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[oC(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 TC(t,e){var n=e,i=MC(t,n),r=i.extent,o=n.get("splitNumber");t instanceof bC&&(t.base=n.get("logBase"));var a=t.type,s=n.get("interval"),l="interval"===a||"time"===a;t.setBreaksFromOption(NC(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 AC(t){var e=t.getLabelModel().get("formatter");if("time"===t.type){var n=Im(e);return function(e,i){return t.scale.getFormattedLabel(e,i,n)}}if(Qr(e))return function(n){var i=t.scale.getLabel(n);return e.replace("{value}",null!=i?i:"")};if(Kr(e)){if("category"===t.type)return function(n,i){return e(IC(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(IC(t,n),r,o)}}return function(e){return t.scale.getLabel(e)}}function IC(t,e){return"category"===t.type?t.scale.getLabel(e):e.value}function PC(t){var e=t.get("interval");return null==e?"auto":e}function DC(t){return"category"===t.type&&0===PC(t.getLabelModel())}function LC(t,e){var n={};return jr(t.mapDimensionsAll(e),function(e){n[function(t,e){return zS(t,e)?t.getCalculationInfo("stackResultDimension"):e}(t,e)]=!0}),Gr(n)}function EC(t){return"middle"===t||"center"===t}function RC(t){return t.getShallow("show")}function NC(t){t.get("breaks",!0)}var zC=function(){function t(){}return t.prototype.getNeedCrossZero=function(){return!this.option.scale},t.prototype.getCoordSysModel=function(){},t}(),OC=[],$C={registerPreprocessor:Xw,registerProcessor:Yw,registerPostInit:function(t){Zw("afterinit",t)},registerPostUpdate:function(t){Zw("afterupdate",t)},registerUpdateLifecycle:Zw,registerAction:Kw,registerCoordinateSystem:function(t,e){av.register(t,e)},registerLayout:function(t,e){tS(Hw,t,e,1e3,"layout")},registerVisual:Qw,registerTransform:nS,registerLoading:eS,registerMap:function(t,e,n){var i=Kx["registerMap"];i&&i(t,e,n)},registerImpl:function(t,e){Kx[t]=e},PRIORITY:tw,ComponentModel:kv,ComponentView:cb,SeriesModel:eb,ChartView:pb,registerComponentModel:function(t){kv.registerClass(t)},registerComponentView:function(t){cb.registerClass(t)},registerSeriesModel:function(t){eb.registerClass(t)},registerChartView:function(t){pb.registerClass(t)},registerCustomSeries:function(t,e){},registerSubTypeDefaulter:function(t,e){kv.registerSubTypeDefaulter(t,e)},registerPainter:function(t,e){var n;n=e,Lc[t]=n}};function HC(t){Zr(t)?jr(t,function(t){HC(t)}):Fr(OC,t)>=0||(OC.push(t),Kr(t)&&(t={install:t}),t.install($C))}var FC=bd(),BC=bd(),VC=1,jC=2;function qC(t){return{out:{noPxChangeTryDetermine:[]},kind:t}}function WC(t,e){var n=qr(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 UC(t,e){var n=t.getLabelModel().get("customValues");if(n){var i=AC(t),r=t.scale.getExtent();return{labels:qr(Ur(WC(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=XC(t,n,e);return!n.get("show")||t.scale.isBlank()?{labels:[]}:i}(t,e):function(t){var e=t.scale.getTicks(),n=AC(t);return{labels:qr(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 GC(t,e,n){var i=t.getTickModel().get("customValues");if(i){var r=t.scale.getExtent();return{ticks:Ur(WC(t,i),function(t){return t>=r[0]&&t<=r[1]})}}return"category"===t.type?function(t,e){var n,i,r=YC(t),o=PC(e),a=QC(r,o);if(a)return a;e.get("show")&&!t.scale.isBlank()||(n=[]);if(Kr(o))n=ik(t,o,!0);else if("auto"===o){var s=XC(t,t.getLabelModel(),qC(jC));i=s.labelCategoryInterval,n=qr(s.labels,function(t){return t.tickValue})}else n=nk(t,i=o,!0);return JC(r,o,{ticks:n,tickCategoryInterval:i})}(t,e):{ticks:qr(t.scale.getTicks(n),function(t){return t.value})}}function XC(t,e,n){var i,r,o=ZC(t),a=PC(e),s=n.kind===VC;if(!s){var l=QC(o,a);if(l)return l}Kr(a)?i=ik(t,a):(r="auto"===a?function(t,e){if(e.kind===VC){var n=t.calculateCategoryInterval(e);return e.out.noPxChangeTryDetermine.push(function(){return BC(t).autoInterval=n,!0}),n}var i=BC(t).autoInterval;return null!=i?i:BC(t).autoInterval=t.calculateCategoryInterval(e)}(t,n):a,i=nk(t,r));var c={labels:i,labelCategoryInterval:r};return s?n.out.noPxChangeTryDetermine.push(function(){return JC(o,a,c),!0}):JC(o,a,c),c}var YC=KC("axisTick"),ZC=KC("axisLabel");function KC(t){return function(e){return BC(e)[t]||(BC(e)[t]={list:[]})}}function QC(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 nk(t,e,n){var i=AC(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=DC(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 ik(t,e,n){var i=t.scale,r=AC(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 rk=[0,1],ok=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(Fc(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&&ak(n=n.slice(),i.count()),Bc(t,rk,n,e)},t.prototype.coordToData=function(t,e){var n=this._extent,i=this.scale;this.onBand&&"ordinal"===i.type&&ak(n=n.slice(),i.count());var r=Bc(t,n,rk,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=qr(GC(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=qc(t),e=qc(e),u?t>e:t0&&t<100||(t=5),qr(this.scale.getMinorTicks(t),function(t){return qr(t,function(t){return{coord:this.dataToCoord(t),tickValue:t}},this)},this)},t.prototype.getViewLabels=function(t){return UC(this,t=t||qC(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=AC(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,_=fc(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===VC)return e.out.noPxChangeTryDetermine.push(Xr(tk,null,t,x,l)),x;var w=ek(t,x,l);return null!=w?w:x}(this,t=t||qC(jC))},t}();function ak(t,e){var n=(t[1]-t[0])/e/2;t[0]+=n,t[1]-=n}var sk=["label","labelLine","layoutOption","priority","defaultAttr","marginForce","minMarginForce","marginDefault","suggestIgnore"];function lk(t,e,n){n=n||3,e?t.dirty|=n:t.dirty&=~n}function ck(t,e){return e=e||3,null==t.dirty||!!(t.dirty&e)}function dk(t){if(t)return ck(t)&&function(t,e,n){var i=e.getComputedTransform();t.transform=Lg(t.transform,i);var r=t.localRect=Dg(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=Zg.textMargin);for(var u=0;u<4;u++)uk[u]=d===Zg.minMargin&&l&&null!=l[u]?l[u]:s&&null!=s[u]?s[u]:a?a[u]:0;d===Zg.textMargin&&Sg(r,uk,!1,!1);var h=t.rect=Dg(t.rect,r);i&&h.applyTransform(i);d===Zg.minMargin&&Sg(h,uk,!1,!1);t.axisAligned=Ig(i),(t.label=t.label||{}).ignore=e.ignore,lk(t,!1),lk(t,!0,2)}(t,t.label,t),t}var uk=[0,0,0,0];function hk(t,e){for(var n=0;n-1&&(s.style.stroke=s.style.fill,s.style.fill=Mv.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}(eb);function mk(t,e){var n=t.mapDimensionsAll("defaultedLabel"),i=n.length;if(1===i){var r=oy(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),Pp(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&&ig(a,{style:{opacity:0}},e,{dataIndex:r,removeOpt:o,cb:function(){i.removeTextContent()}})}else i.removeTextContent();ig(i,{style:{opacity:0},scaleX:0,scaleY:0},e,{dataIndex:r,cb:t,removeOpt:o})},e.getSymbolSize=function(t,e){return Zr(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}(Dc);function _k(t,e){this.parent.drift(t,e)}function yk(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 bk(t){return null==t||eo(t)||(t={isIgnore:t}),t||{}}function xk(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:Fg(e),cursorStyle:e.get("cursor")}}var wk=function(){function t(t){this.group=new Dc,this._SymbolCtor=t||vk}return t.prototype.updateData=function(t,e){this._progressiveEls=null,e=bk(e);var n=this.group,i=t.hostModel,r=this._data,o=this._SymbolCtor,a=e.disableAnimation,s=xk(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(yk(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(yk(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):tg(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=xk(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=bk(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=qr(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 Ck(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 kk=Math.min,Mk=Math.max;function Tk(t,e){return isNaN(t)||isNaN(e)}function Ak(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(Tk(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||Tk(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 z=M>0?1:-1;p=v-z*(R=Math.abs(P))*a,f=_,A=v+z*(N=Math.abs(D))*a,I=_}else if("y"===s){var O=T>0?1:-1;p=v,f=_-O*(R=Math.abs(L))*a,A=v,I=_+O*(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=kk(A=v+M*a*k,Mk(w,v)),I=kk(I,Mk(S,_)),A=Mk(A,kk(w,v)),f=_-(T=(I=Mk(I,kk(S,_)))-_)*R/N,p=kk(p=v-(M=A-v)*R/N,Mk(c,v)),f=kk(f,Mk(d,_)),A=v+(M=v-(p=Mk(p,kk(c,v))))*N/R,I=_+(T=_-(f=Mk(f,kk(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 Ik=function(){this.smooth=0,this.smoothConstraint=!0},Pk=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:Mv.color.neutral99,fill:null}},e.prototype.getDefaultShape=function(){return new Ik},e.prototype.buildPath=function(t,e){var n=e.points,i=0,r=n.length/2;if(e.connectNulls){for(;r>0&&Tk(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?gs(n,c,u,p,t,s):gs(i,d,h,f,t,s);if(v>0)for(var _=0;_=0){m=a?ps(i,d,h,f,y):ps(n,c,u,p,y);return a?[t,m]:[m,t]}}n=p,i=f}}},e}(fh),Dk=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return v(e,t),e}(Ik),Lk=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 Dk},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&&Tk(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=Vs(e[r]),s=Vs(e[o]),l=i-r,c=Us([Ds(zs(a[0],s[0],l)),Ds(zs(a[1],s[1],l)),Ds(zs(a[2],s[2],l)),Ls(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 Hk(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 Fk(t,e){return isNaN(t)||isNaN(e)}function Bk(t,e){return[t[2*e],t[2*e+1]]}function Vk(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=qr(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=$k(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 Hf(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,iv(M));var T=f.getClipPath();if(T)eg(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]]}}),Ek(this._stackedOnPoints,y)&&Ek(this._points,l)||(g?this._doUpdateAnimation(o,y,i,n,k,v,x):(k&&(y&&(y=Ok(y,l,i,k,x)),l=Ok(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=Ok(y,l,i,k,x)),l=Ok(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,iv(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(Hr(a.getLineStyle(),{fill:"none",stroke:M,lineJoin:"bevel"})),Ep(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,Pp(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(Hr(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}),Ep(p,t,"areaStyle"),jh(p).seriesIndex=t.seriesIndex,Pp(p,I,P,D)}var z=this._changePolyState;o.eachItemGraphicEl(function(t){t&&(t.onHoverStateChange=z)}),this._polyline.onHoverStateChange=z,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=yd(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 vk(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 pb.prototype.highlight.call(this,t,e,n,i)},e.prototype.downplay=function(t,e,n,i){var r=t.getData(),o=yd(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 pb.prototype.downplay.call(this,t,e,n,i)},e.prototype._changePolyState=function(t){var e=this._polygon;hp(this._polyline,t),e&&hp(e,t)},e.prototype._newPolyline=function(t){var e=this._polyline;return e&&this._lineGroup.remove(e),e=new Pk({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 Lk({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");Kr(l)&&(l=l(null));var c=s.get("animationDelay")||0,d=Kr(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=Kr(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(Vk(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 Ph({z2:200})).ignoreClip=!0,o.setTextContent(this._endLabel),o.disableLabelAnimation=!0);var l=function(t){for(var e=t.length/2;e>0&&Fk(t[2*e-2],t[2*e-1]);e--);return e-1}(a);l>=0&&(Hg(o,Fg(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(!Zr(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=Bk(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(to(i))return qc(f=ad(n||0,i,r),o?Math.max(Wc(n||0),Wc(i)):e);if(Qr(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=Bk(c,I);r&&(k=d.getRawValue(I)),s.attr({x:M[0]+y,y:M[1]+b})}if(r){var P=Yg(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=Sk(r,e,a),m=t.getLayout("points")||[],v=e.getLayout("points")||[],_=0;_3e3||l&&Nk(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(),tg(s,g,c),l&&(l.setShape({points:u,stackedOnPoints:h}),l.stopAnimation(),tg(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}(ok),cM="expandAxisBreak",dM=Math.PI,uM=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],hM=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],pM=bd(),fM=bd(),gM=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],vM=new Ia(0,0,0,0),_M=function(t,e,n,i,r,o){if(EC(t.nameLocation)){var a=o.stOccupiedRect;a&&yM(function(t,e,n){return t.transform=Lg(t.transform,n),t.localRect=Dg(t.localRect,e),t.rect=Dg(t.rect,e),n&&t.rect.applyTransform(n),t.axisAligned=Ig(n),t.obb=void 0,(t.label=t.label||{}).ignore=!1,t}({},a,o.transGroup.transform),i,r)}else bM(o.labelInfoList,o.dirVec,i,r)};function yM(t,e,n){var i=new ga;fk(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 bM(t,e,n,i){for(var r=ga.dot(i,e)>=0,o=0,a=t.length;o0?"top":"bottom",i="center"):Xc(o-dM)?(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}(),wM=["axisLine","axisTickLabelEstimate","axisTickLabelDetermine","axisName"],SM={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&&(No(d,d,c),No(u,u,c));var p=$r({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 Pf($r({shape:{x1:d[0],y1:d[1],x2:u[0],y2:u[1]}},f));gg(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"]);Qr(m)&&(m=[m,m]),(Qr(v)||to(v))&&(v=[v,v]);var _=xx(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=bx(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){TM(e,r,s)&&CM(t,e,n,i,r,o,a,VC)},axisTickLabelDetermine:function(t,e,n,i,r,o,a,s){TM(e,r,s)&&CM(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=MM(r.getTicksCoords(),n.transform,l,Hr(s.getLineStyle(),{stroke:i.get(["axisLine","lineStyle","color"])}),"ticks"),d=0;di[1],l="start"===e&&!s||"start"!==e&&s;Xc(a-dM/2)?(o=l?"bottom":"top",r="center"):Xc(a-1.5*dM)?(o=l?"top":"bottom",r="center"):(o="middle",r=a<1.5*dM&&a>dM/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=so(t.raw.nameTruncateMaxWidth,S.maxWidth,b),M=s.nameMarginLevel||0,T=new Ph({x:m.x,y:m.y,rotation:y.rotation,silent:xM.isLabelSilent(i),style:Bg(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(Mg({el:T,componentModel:i,itemName:c}),T.__fullText=c,T.anid="name",i.get("triggerEvent")){var A=xM.makeAxisEventDataBase(i);A.targetType="axisName",A.name=c,jh(T).eventData=A}o.add(T),T.updateTransform(),e.nameEl=T;var I=l.nameLayout=dk({label:T,priority:T.z2,defaultAttr:{ignore:T.ignore},marginDefault:EC(d)?uM[M]:hM[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 CM(t,e,n,i,r,o,a,s){AM(e)||function(t,e,n,i,r,o){var a=r.axis,s=so(t.raw.axisLabelShow,r.get(["axisLabel","show"])),l=new Dc;n.add(l);var c=qC(i);if(!s||a.scale.isBlank())return void IM(e,[],l,c);var d=r.getModel("axisLabel"),u=a.getViewLabels(c),h=(so(t.raw.labelRotate,d.get("rotate"))||0)*dM/180,p=xM.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];eo(y)&&y.textStyle&&(h=new sm(y.textStyle,d,r.ecModel))}var b=h.getTextColor()||r.get(["axisLine","lineStyle","color"]),x=h.getShallow("align",!0)||p.textAlign,w=lo(h.getShallow("alignMinLabel",!0),x),S=lo(h.getShallow("alignMaxLabel",!0),x),C=h.getShallow("verticalAlign",!0)||h.getShallow("baseline",!0)||p.textVerticalAlign,k=lo(h.getShallow("verticalAlignMinLabel",!0),C),M=lo(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 Ph({x:0,y:0,rotation:0,silent:xM.isLabelSilent(r),z2:T,style:Bg(h,{text:s,align:0===e?w:e===u.length-1?S:x,verticalAlign:0===e?k:e===u.length-1?M:C,fill:Kr(b)?b("category"===a.type?c:"value"===a.type?i+"":i,e):b})});A.anid="label_"+i;var I=pM(A);if(I.break=t.break,I.tickValue=i,I.layoutRotation=p.rotation,Mg({el:A,componentModel:r,itemName:s,formatterParamsExtra:{isTruncated:function(){return A.isTruncated},value:c,tickIndex:e}}),m){var P=xM.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:cM,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=qr(g,function(t){return{label:t,priority:pM(t).break?t.z2+(_-v+1):t.z2,defaultAttr:{ignore:t.ignore}}});IM(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=dk(n);if(a){var s=a.label,l=pM(s);a.suggestIgnore=s.ignore,s.ignore=!1,sc(PM,DM),PM.x=e.axis.dataToCoord(l.tickValue),PM.y=t.labelOffset+t.labelDirection*r,PM.rotation=l.layoutRotation,i.add(PM),PM.updateTransform(),i.remove(PM),PM.decomposeTransform(),sc(s,PM),s.markRedraw(),lk(a,!0),dk(a)}})}(t,i,l,o),t.rotation;var c=t.optionHideOverlap;!function(t,e,n){if(DC(t.axis))return;function i(t,i,r){var o=dk(e[i]),a=dk(e[r]);if(o&&a)if(!1===t||o.suggestIgnore)kM(o.label);else if(a.suggestIgnore)kM(a.label);else{var s=.1;if(!n){var l=[0,0,0,0];o=hk({marginForce:l},o),a=hk({marginForce:l},a)}fk(o,a,null,{touchThreshold:s})&&kM(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 Ia(h,0,p,1))}a.stOccupiedRect=r,a.labelInfoList=s}(t,n,i,l)}function kM(t){t&&(t.ignore=!0)}function MM(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;$S(l)&&s.get("alignTicks")&&null==s.get("interval")?r.push(a):(TC(l,s),$S(l)&&(e=a))}r.length&&(e||TC((e=r.pop()).scale,e.model),jr(r,function(t){!function(t,e,n){var i=tC.prototype,r=i.getTicks.call(n),o=i.getTicks.call(n,{expandToNicedExtent:!0}),a=r.length-1,s=i.getInterval.call(n),l=MC(t,e),c=l.extent,d=l.fixMin,u=l.fixMax;"log"===t.type&&(c=GS(t.base,c,!0)),t.setBreaksFromOption(NC(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=FS(p),f=c[1]-p*a;else{t.getTicks().length-1>a&&(p=FS(p));var m=p*a;(f=qc((g=Math.ceil(c[1]/p)*p)-m))<0&&c[0]>=0?(f=0,g=qc(m)):g>0&&c[1]<=0&&(g=0,f=-qc(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){$M(n,"y",t,r)}),jr(n.y,function(t){$M(n,"x",t,r)}),this.resize(this.model,e)},t.prototype.resize=function(t,e,n){var i=bv(t,e),r=this._rect=_v(t.getBoxLayoutParams(),i.refContainer),o=this._axesMap,a=this._coordsList,s=t.get("containLabel");if(FM(o,r),!n){var l=function(t,e,n,i,r){var o=new gM(qM);return jr(n,function(n){return jr(n,function(n){if(RC(n.model)){var a=!i;n.axisBuilder=function(t,e,n,i,r,o){for(var a=EM(t,n),s=!1,l=!1,c=0;c0&&i>0||n<0&&i<0)}(t)}function FM(t,e){jr(t.x,function(t){return BM(t,e.x,e.width)}),jr(t.y,function(t){return BM(t,e.y,e.height)})}function BM(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 VM(t,e,n,i,r,o,a){jM(i,r,VC,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 Sg(i,s,!0,!0,n),FM(r,i),l;function c(t){jr(r[ag[t]],function(e){if(RC(e.model)){var n=o.ensureRecord(e.model),i=n.labelInfoList;if(i)for(var r=0;r0&&!ao(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){RC(e.model)&&(!function(t,e,n){var i=EM(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[ag[1-e]]=t[sg[e]]<=.5*o.refContainer[sg[e]]?0:1-e==1?2:1}l(0),l(1),jr(e,function(t,e){return jr(t,function(t){RC(t.model)&&(("all"===i||a)&&t.axisBuilder.build({axisName:!0},{nameMarginLevel:s[e]}),a&&t.axisBuilder.build({axisLine:!0}))})})}var qM=function(t,e,n,i,r,o){var a="x"===n.axis.dim?"y":"x";_M(t,0,0,i,r,o),EC(t.nameLocation)||jr(e.recordMap[a],function(t){t&&t.labelInfoList&&t.dirVec&&bM(t.labelInfoList,t.dirVec,i,r)})};function WM(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=YM(n.model),l=t.coordSysAxesInfo[s]={};t.coordSysMap[s]=n;var c=n.model.getModel("tooltip",i);if(jr(n.getAxes(),Yr(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,Yr(p,!u||"cross",d)),u&&jr(h.otherAxes,Yr(p,"cross",!1))}}function p(i,s,d){var u=d.model.getModel("axisPointer",r),h=u.get("show");if(h&&("auto"!==h||i||XM(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]=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&&Hr(l,d.textStyle)}}return t.model.getModel("axisPointer",new sm(s,n,i))}(d,c,r,e,i,s):u;var p=u.get("snap"),f=u.get("triggerEmphasis"),g=YM(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:XM(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 GM(t){var e=(t.ecModel.getComponent("axisPointer")||{}).coordSysAxesInfo;return e&&e.axesInfo[YM(t)]}function XM(t){return!!t.get(["handle","show"])}function YM(t){return t.type+"||"+t.id}var ZM={},KM=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=GM(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=XM(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=GM(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=sT(t).pointerEl=new zg[r.type](lT(e.pointer));t.add(o)}},t.prototype.createLabelEl=function(t,e,n,i){if(e.label){var r=sT(t).labelEl=new Ph(lT(e.label));t.add(r),pT(r,i)}},t.prototype.updatePointerEl=function(t,e,n){var i=sT(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=sT(t).labelEl;r&&(r.setStyle(e.label.style),n(r,{x:e.label.x,y:e.label.y}),pT(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=bg(o.get("icon"),{cursor:"move",draggable:!0,onmousemove:function(t){oa(t.event)},onmousedown:cT(this._onHandleDragMove,this,0,0),drift:cT(this._onHandleDragMove,this),ondragend:cT(this._onHandleDragEnd,this)}),i.add(r)),gT(r,n,!1),r.setStyle(o.getItemStyle(null,["color","borderColor","borderWidth","opacity","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY"]));var s=o.get("size");Zr(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,Sb(this,"_doDispatchAxisPointer",o.get("throttle")||0,"fixRate"),this._moveHandleToValue(t,e)}},t.prototype._moveHandleToValue=function(t,e){uT(this._axisPointerModel,!e&&this._moveAnimation,this._handle,fT(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(fT(n),[t,e],this._axisModel,this._axisPointerModel);this._payloadInfo=i,n.stopAnimation(),n.attr(fT(i)),sT(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),Cb(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 uT(t,e,n,i){hT(sT(n).lastProp,i)||(sT(n).lastProp=i,e?tg(n,i,t):(n.stopAnimation(),n.attr(i)))}function hT(t,e){if(eo(t)&&eo(e)){var n=!0;return jr(e,function(e,i){n=n&&hT(t[i],e)}),!!n}return t===e}function pT(t,e){t[e.get(["label","show"])?"show":"hide"]()}function fT(t){return{x:t.x||0,y:t.y||0,rotation:t.rotation||0}}function gT(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=vT(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=Qm(a.get("padding")||0),l=a.getFont(),c=fc(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:Bg(a,{text:o,font:l,fill:a.getTextColor(),padding:s,backgroundColor:g}),z2:10}}function vT(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:IC(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)}),Qr(a)?o=a.replace("{value}",o):Kr(a)&&(o=a(s))}return o}function _T(t,e,n){var i=[1,0,0,1,0,0];return pa(i,i,n.rotation),ha(i,i,n.position),vg([t.dataToCoord(e),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],i)}var yT=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=bT(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=xT[s](o,c,l);u.style=d,t.graphicKey=u.type,t.pointer=u}!function(t,e,n,i,r,o){var a=xM.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=r.get(["label","margin"]),mT(e,i,r,o,{position:_T(i.axis,t,n),align:a.textAlign,verticalAlign:a.textVerticalAlign})}(e,t,EM(a.getRect(),n),n,i,r)},e.prototype.getHandleTransform=function(t,e,n){var i=EM(e.axis.grid.getRect(),e,{labelInside:!1});i.labelMargin=n.get(["handle","margin"]);var r=_T(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=bT(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}(dT);function bT(t,e){var n={};return n[e.dim+"AxisIndex"]=e.index,t.getCartesian(n)}var xT={line:function(t,e,n){var i,r,o;return{type:"Line",subPixelOptimize:!0,shape:(i=[e,n[0]],r=[e,n[1]],o=wT(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=wT(t),{x:i[o=o||0],y:i[1-o],width:r[o],height:r[1-o]})}}};function wT(t){return"x"===t.dim?0:1}var 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.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:Mv.color.border,width:1,type:"dashed"},shadowStyle:{color:Mv.color.shadowTint},label:{show:!0,formatter:null,precision:"auto",margin:3,color:Mv.color.neutral00,padding:[5,7,5,7],backgroundColor:Mv.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:Mv.color.accent40,throttle:40}},e}(kv),CT=bd(),kT=jr;function MT(t,e,n){if(!gr.node){var i=e.getZr();CT(i).records||(CT(i).records={}),function(t,e){if(CT(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);kT(CT(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)})}CT(t).initialized=!0,n("click",Yr(AT,"click")),n("mousemove",Yr(AT,"mousemove")),n("globalout",TT)}(i,e),(CT(i).records[t]||(CT(i).records[t]={})).handler=n}}function TT(t,e,n){t.handler("leave",null,n)}function AT(t,e,n,i){e.handler(t,n,i)}function IT(t,e){if(!gr.node){var n=e.getZr();(CT(n).records||{})[t]&&(CT(n).records[t]=null)}}var PT=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";MT("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){IT("axisPointer",e)},e.prototype.dispose=function(t,e){IT("axisPointer",e)},e.type="axisPointer",e}(cb);function DT(t,e){var n,i=[],r=t.seriesIndex;if(null==r||!(n=e.getSeriesByIndex(r)))return{point:[]};var o=n.getData(),a=yd(o,t);if(null==a||a<0||Zr(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(qr(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 LT=bd();function ET(t,e,n){var i=t.currTrigger,r=[t.x,t.y],o=t,a=t.dispatchAction||Xr(n.dispatchAction,n),s=e.getComponent("axisPointer").coordSysAxesInfo;if(s){$T(r)&&(r=DT({seriesIndex:o.seriesIndex,dataIndex:o.dataIndex},e).point);var l=$T(r),c=o.axesInfo,d=s.axesInfo,u="leave"===i||$T(r),h={},p={},f={list:[],map:{}},g={showPointer:Yr(NT,p),showTooltip:Yr(zT,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&&RT(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,OT(e),OT(t)))),m[t.key]=o}})}),jr(m,function(t,e){RT(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($T(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=LT(i)[r]||{},a=LT(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 RT(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&&$r(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 NT(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=YM(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 OT(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 $T(t){return!t||null==t[0]||isNaN(t[0])||null==t[1]||isNaN(t[1])}function HT(t){KM.registerAxisPointerClass("CartesianAxisPointer",yT),t.registerComponentModel(ST),t.registerComponentView(PT),t.registerPreprocessor(function(t){if(t){(!t.axisPointer||0===t.axisPointer.length)&&(t.axisPointer={});var e=t.axisPointer.link;e&&!Zr(e)&&(t.axisPointer.link=[e])}}),t.registerProcessor(t.PRIORITY.PROCESSOR.STATISTIC,function(t,e){t.getComponent("axisPointer").coordSysAxesInfo=WM(t,e)}),t.registerAction({type:"updateAxisPointer",event:"updateAxisPointer",update:":updateAxisPointer"},ET)}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.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:Mv.color.neutral00,shadowBlur:10,shadowColor:"rgba(0, 0, 0, .2)",shadowOffsetX:1,shadowOffsetY:2,borderRadius:4,borderWidth:1,defaultBorderColor:Mv.color.border,padding:null,extraCssText:"",axisPointer:{type:"line",axis:"auto",animation:"auto",animationDurationUpdate:200,animationEasingUpdate:"exponentialOut",crossStyle:{color:Mv.color.borderShade,width:1,type:"dashed",textStyle:{}}},textStyle:{color:Mv.color.tertiary,fontSize:14}},e}(kv);function BT(t){var e=t.get("confine");return null!=e?!!e:"richText"===t.get("renderMode")}function VT(t){if(gr.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?",":"")+(gr.transformSupported?""+UT+r:",left"+r+",top"+r)),WT+":"+o}(o,n,i)),a&&r.push("background-color:"+a),jr(["width","color","radius"],function(e){var n="border-"+e,i=Km(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=lo(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:"+Qm(h).join("px ")+"px"),r.join(";")+";"}function ZT(t,e,n,i,r){var o=e&&e.painter;if(n){var a=o&&o.getViewportRoot();a&&function(t,e,n,i,r){Uo(Wo,e,i,r,!0)&&Uo(t,n,Wo[0],Wo[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 KT=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,gr.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&&(Qr(r)?document.querySelector(r):ro(r)?r:Kr(r)&&r(t.getDom()));ZT(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;ia(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=GT+YT(t,!this._firstShow,this._longHide,this._enableDisplayTransition)+XT(r[0],r[1],!0)+"border-color:"+iv(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(Qr(r)&&"item"===n.get("trigger")&&!BT(n)&&(a=function(t,e,n){if(!Qr(n)||"inside"===n)return"";var i=t.get("backgroundColor"),r=t.get("borderWidth");e=iv(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=UT+":";Fr(["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)),Qr(t))o.innerHTML=t+a;else if(t){o.innerHTML="",Zr(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&&!gr.node&&n.getDom()){var r=oA(i,n);this._ticket="";var o=i.dataByCoordSys,a=function(t,e,n){var i=Sd(t).queryOptionMap,r=i.keys()[0];if(!r||"series"===r)return;var o=kd(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=nA;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=DT(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(oA(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"===rA([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,lx(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=Xr(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=rA([e.tooltipOption],i),a=this._renderMode,s=[],l=By("section",{blocks:[],noHeader:!0}),c=[],d=new Ky;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=vT(r,e.axis,n,t.seriesDataIndices,t.valueLabelOpt),u=By("section",{header:o,noHeader:!fo(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=IC(e.axis,{value:r}),f.axisValueLabel=o,f.marker=d.makeTooltipMarker("item",iv(f.color),a);var g=ly(h.formatTooltip(p,!0,null)),m=g.frag;if(m){var v=rA([h],i).get("valueFormatter");u.blocks.push(v?$r({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=Gy(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=rA([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 Ky;g.marker=m.makeTooltipMarker("item",iv(g.color),u);var v=ly(s.formatTooltip(l,!1,c)),_=p.get("order"),y=p.get("valueFormatter"),b=v.frag,x=b?Gy(y?$r({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(Qr(o)){o={content:o,formatter:o},a=!0}a&&i&&o.content&&((o=zr(o)).content=Zo(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=rA(s,this._tooltipModel,c?{position:c}:null),u=d.get("content"),h=Math.random()+"",p=new Ky;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(Qr(d)){var p=t.ecModel.get("useUTC"),f=Zr(n)?n[0]:n;u=d,f&&f.axisType&&f.axisType.indexOf("time")>=0&&(u=Em(f.axisValue,u,p)),u=nv(u,n,!0)}else if(Kr(d)){var g=Xr(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||Zr(e)?{color:i||r}:Zr(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),Kr(e)&&(e=e([n,i],o,r.el,h,{viewSize:[s,l],contentSize:c.slice()})),Zr(e))n=Vc(e[0],s),i=Vc(e[1],l);else if(eo(e)){var p=e;p.width=c[0],p.height=c[1];var f=_v(p,{width:s,height:l});n=f.x,i=f.y,d=null,u=null}else if(Qr(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-=aA(d)?c[0]/2:"right"===d?c[0]:0),u&&(i-=aA(u)?c[1]/2:"bottom"===u?c[1]:0),BT(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){!gr.node&&e.getDom()&&(Cb(this,"_updatePosition"),this._tooltipContent.dispose(),IT("itemTooltip",e))},e.type="tooltip",e}(cb);function rA(t,e,n){var i,r=e.ecModel;n?(i=new sm(n,r,r),i=new sm(e.option,i,r)):i=e;for(var o=t.length-1;o>=0;o--){var a=t[o];a&&(a instanceof sm&&(a=a.get("tooltip",!0)),Qr(a)&&(a={formatter:a}),a&&(i=new sm(a,i,r)))}return i}function oA(t,e){return t.dispatchAction||Xr(e.dispatchAction,e)}function aA(t){return"center"===t||"middle"===t}var sA=Math.sin,lA=Math.cos,cA=Math.PI,dA=2*Math.PI,uA=180/cA,hA=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=Js(d-dA)||(c?l>=dA:-l>=dA),h=l>0?l%dA:l%dA+dA,p=!1;p=!!u||!Js(d)&&h>=cA==!!c;var f=t+n*lA(o),g=e+i*sA(o);this._start&&this._add("M",f,g);var m=Math.round(r*uA);if(u){var v=1/this._p,_=(c?1:-1)*(dA-v);this._add("A",n,i,m,1,+c,t+n*lA(o+_),e+i*sA(o+_)),v>.01&&this._add("A",n,i,m,0,+c,f,g)}else{var y=t+n*lA(a),b=e+i*sA(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?Zo(a):a||"")+(i?""+n+qr(i,function(e){return t(e)}).join(n)+n:"")+("")}(t)}function CA(t){return{zrId:t,shadowCache:{},patternCache:{},gradientCache:{},clipPathCache:{},defs:{},cssNodes:{},cssAnims:{},cssStyleCache:{},cssAnimIdx:0,shadowIdx:0,gradientIdx:0,patternIdx:0,clipPathIdx:0}}function kA(t,e,n,i){return wA("svg","root",{width:t,height:e,xmlns:_A,"xmlns:xlink":yA,version:"1.1",baseProfile:"full",viewBox:!!i&&"0 0 "+t+" "+e},n)}var MA=0;function TA(){return MA++}var AA={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"},IA="transform-origin";function PA(t,e,n){var i=$r({},t.shape);$r(i,e),t.buildPath(n,i);var r=new hA;return r.reset(cl(t)),n.rebuildPath(r,1),r.generateStr(),r.getStr()}function DA(t,e){var n=e.originX,i=e.originY;(n||i)&&(t[IA]=n+"px "+i+"px")}var LA={fill:"fill",opacity:"opacity",lineWidth:"stroke-width",lineDashOffset:"stroke-dashoffset"};function EA(t,e){var n=e.zrId+"-ani-"+e.cssAnimIdx++;return e.cssAnims[n]=t,n}function RA(t){return Qr(t)?AA[t]?"cubic-bezier("+AA[t]+")":ks(t)?t:"":""}function NA(t,e,n,i){var r=t.animators,o=r.length,a=[];if(t instanceof Of){var s=function(t,e,n){var i,r,o=t.shape.paths,a={};if(jr(o,function(t){var e=CA(n.zrId);e.animation=!0,NA(t,{},e,!0);var o=e.cssAnims,s=e.cssNodes,l=Gr(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=EA(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 EA(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-"+TA();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-"+TA(),n.cssStyleCache[r]=o,n.cssNodes["."+o+":hover"]=t),e.class=e.class?e.class+" "+o:o}var OA=Math.round;function $A(t){return t&&Qr(t.src)}function HA(t){return t&&Kr(t.toDataURL)}function FA(t,e,n,i){vA(function(r,o){var a="fill"===r||"stroke"===r;a&&sl(o)?KA(e,t,r,i):a&&rl(o)?QA(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=Ks(i.shadowColor),f=p.opacity,g=p.color,m=h/2/l+" "+h/2/c;a=n.zrId+"-s"+n.shadowIdx++,n.defs[a]=wA("filter",a,{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},[wA("feDropShadow","",{dx:d/l,dy:u/c,stdDeviation:m,"flood-color":g,"flood-opacity":f})]),o[r]=a}e.filter=ll(a)}}(n,t,i)}function BA(t,e){var n=function(t){if("function"==typeof Rc)return Rc(t)}(e);n&&(n.each(function(e,n){null!=e&&(t[(bA+n).toLowerCase()]=e+"")}),e.isSilent()&&(t[bA+"silent"]="true"))}function VA(t){return Js(t[0]-1)&&Js(t[1])&&Js(t[2])&&Js(t[3]-1)}function jA(t,e,n){if(e&&(!function(t){return Js(t[4])&&Js(t[5])}(e)||!VA(e))){var i=1e4;t.transform=VA(e)?"translate("+OA(e[4]*i)/i+" "+OA(e[5]*i)/i+")":function(t){return"matrix("+tl(t[0])+","+tl(t[1])+","+tl(t[2])+","+tl(t[3])+","+el(t[4])+","+el(t[5])+")"}(e)}}function qA(t,e,n){for(var i=t.points,r=[],o=0;o=0&&a||o;s&&(r=Ys(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),wA(s,t.id+"",o)}function ZA(t,e){return t instanceof fh?YA(t,e):t instanceof yh?function(t,e){var n=t.style,i=n.image;if(i&&!Qr(i)&&($A(i)?i=i.src:HA(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),FA(a,n,t,e),BA(a,t),e.animation&&NA(t,a,e),wA("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||vr,o=n.x||0,a=function(t,e,n){return"top"===n?t+=e/2:"bottom"===n&&(t-=e/2),t}(n.y||0,vc(r),n.textBaseline),s={"dominant-baseline":"central","text-anchor":nl[n.textAlign]||n.textAlign};if(zh(n)){var l="",c=n.fontStyle,d=Rh(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),FA(s,n,t,e),BA(s,t),e.animation&&NA(t,s,e),wA("text",t.id+"",s,void 0,i)}}(t,e):void 0}function KA(t,e,n,i){var r,o=t[n],a={gradientUnits:o.global?"userSpaceOnUse":"objectBoundingBox"};if(ol(o))r="linearGradient",a.x1=o.x,a.y1=o.y,a.x2=o.x2,a.y2=o.y2;else{if(!al(o))return;r="radialGradient",a.cx=lo(o.x,.5),a.cy=lo(o.y,.5),a.r=lo(o.r,.5)}for(var s=o.colorStops,l=[],c=0,d=s.length;cl?pI(t,null==n[u+1]?null:n[u+1].elm,n,s,u):fI(t,e,a,l))}(n,i,r):cI(r)?(cI(t.text)&&aI(n,""),pI(n,null,r,0,r.length-1)):cI(i)?fI(n,i,0,i.length-1):cI(t.text)&&aI(n,""):t.text!==e.text&&(cI(i)&&fI(n,i,0,i.length-1),aI(n,e.text)))}var vI=0,_I=function(){function t(t,e,n){if(this.type="svg",this.refreshHover=function(){},this.configLayer=function(){},this.storage=e,this._opts=n=$r({},n),this.root=t,this._id="zr"+vI++,this._oldVNode=kA(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=xA("svg");gI(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(uI(t,e))mI(t,e);else{var n=t.elm,i=rI(n);hI(e),null!==i&&(eI(i,e.elm,oI(n)),fI(i,[t],0,0))}}(this._oldVNode,t),this._oldVNode=t}},t.prototype.renderOneToVNode=function(t){return ZA(t,CA(this._id))},t.prototype.renderToVNode=function(t){t=t||{};var e=this.storage.getDisplayList(!0),n=this._width,i=this._height,r=CA(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=wA("rect","bg",{width:t,height:e,x:"0",y:"0"}),sl(n))KA({fill:n},r.attrs,"fill",i);else if(rl(n))QA({style:{fill:n},dirty:Co,getBoundingRect:function(){return{width:t,height:e}}},r.attrs,"fill",i);else{var o=Ks(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=wA("g","main",{},[]);this._paintList(e,r,s?s.children:o),s&&o.push(s);var l=qr(Gr(r.defs),function(t){return r.defs[t]});if(l.length&&o.push(wA("defs","defs",{},l)),t.animation){var c=function(t,e,n){var i=(n=n||{}).newline?"\n":"",r=" {"+i,o=i+"}",a=qr(Gr(t),function(e){return e+r+qr(Gr(t[e]),function(n){return n+":"+t[e][n]+";"}).join(i)+o}).join(i),s=qr(Gr(e),function(t){return"@keyframes "+t+r+qr(Gr(e[t]),function(n){return n+r+qr(Gr(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=wA("style","stl",{},[],c);o.push(d)}}return kA(n,i,o,t.useViewBox)},t.prototype.renderToString=function(t){return t=t||{},SA(this.renderToVNode({animation:lo(t.cssAnimation,!0),emphasis:lo(t.cssEmphasis,!0),willUpdate:!1,compress:!0,useViewBox:lo(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;Qr(r)?p=Wk[r]:Kr(r)&&(p=r),p&&t.setData(i.downSample(i.mapDimension(l.dim),1/h,p,Uk))}}}}}("line"))},function(t){HC(aT),HC(HT)},function(t){HC(HT),t.registerComponentModel(FT),t.registerComponentView(iA),t.registerAction({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},Co),t.registerAction({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},Co)},function(t){t.registerPainter("svg",_I)}]);class yI 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=Uw(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)}}yI.styles=k` :host { display: block; width: 100%; @@ -233,7 +282,7 @@ var Xl={},Yl={};var Zl,Kl=function(){function t(t,e,n){var i=this;this._sleepAft width: 100%; height: 100%; } - `,_([Lt({attribute:!1})],NA.prototype,"options",void 0),_([Lt({attribute:!1})],NA.prototype,"data",void 0),_([Lt({type:String})],NA.prototype,"height",void 0);try{customElements.get("span-chart")||customElements.define("span-chart",NA)}catch{}function zA(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 OA(t){return null===t?Vn:function(t){return(Math.abs(t)/1e3).toFixed(1)}(t)}function $A(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):Vn,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:Ze(o),partial:!1}),a&&(a.textContent=OA(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):Vn,c&&(c.textContent="A")}else l.textContent=OA(Ze(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):Vn,u&&(u.textContent="A")}else d.textContent=OA(Ze(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):Vn,p&&(p.textContent="A")}else h.textContent=OA(Ze(i)),p&&(p.textContent="kW")}const f=t.querySelector(".stat-battery .stat-value");if(f){const t=n.panel_entities?.battery_level,i=Ze(t?e.states[t]:void 0);f.textContent=null===i?Vn:`${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:Vn}}function HA(t,e,n,i,r,o,a){if(!t||!n||!e)return;const s=yi(i),l=be(n),c=[];for(const{circuit:t}of l){if(!t.entities?.power||fn(t)||on(t))continue;const n=hn(t,e);c.push(null===n?null:Math.abs(n))}!function(t,e,n,i,r){const o=t.querySelector(".panel-stats");o&&$A(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,powerHistory:r,horizonMap:o,defaultDurationMs:s,chartMetric:Qn(i),monitoringStatus:a};for(const e of l)for(const n of ve(e)){const i=t.querySelector(`.circuit-slot[data-uuid="${li(n.uuid)}"]`);if(!i)continue;const r=n.uuid===e.uuid?e.circuit:ye(n.circuit,e);FA(i,n.uuid,r,d)}}function FA(t,e,n,i){const{hass:r,powerHistory:o,horizonMap:a,defaultDurationMs:s,chartMetric:l,monitoringStatus:c}=i,d=hn(n,r),u=gn(n,d),h=un(n,r),p=t.querySelector(".power-value");p&&(p.innerHTML="current"===l.entityRole?Xn(pn(n,r)):Gn(d)),ei(t,h,wn(n,r)),t.classList.toggle("circuit-off",!h),t.classList.toggle("circuit-producer",u),oi(t,kn(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)?bi(a.get(e)):s,h=fn(n),p=Re(c,n),g=Ut(n,p);zA(f,0,i,d,l,u,r,g?{ratingA:g,...ze(p)}:void 0,h)}}class BA{get errorStore(){return this._errorStore}set errorStore(t){this._errorStore=t,this._retry=t?new Ie(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 VA(t,e){if(!t)return o;const n=t.circuits?.[e];return n?.has_override?n.horizon:t.global_horizon??o}function jA(t,e){if(!t)return o;const n=t.sub_devices?.[e];return n?.has_override?n.horizon:t.global_horizon??o}function WA(t,e,n){return{members:t?ve(t):[{uuid:e,circuit:n}],capacityA:t&&t.members.length>1?t.circuit.breaker_rating_a??null:null}}class qA{constructor(){this.powerHistory=new Map,this.horizonMap=new Map,this.subDeviceHorizonMap=new Map,this.monitoringCache=new De,this.monitoringMultiCache=new Le,this.graphSettingsCache=new BA,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,VA(t,e));if(t&&this._topology?.sub_devices)for(const e of Object.keys(this._topology.sub_devices))this.subDeviceHorizonMap.set(e,jA(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,VA(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,jA(i,r))}}async loadHistory(){await Ii(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=Jn(n,this._config);if(!r)continue;const s=Ze(this._hass.states[r]);if(null===s)continue;const l=bi(i),c=xi(l),d=wi(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 Ai(this._topology))i.has(e)&&r.add(t);const o=new Map;try{await Ii(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&&(HA(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=yi(i);for(const[i,s]of Object.entries(n.sub_devices)){const n=t.querySelector(`[data-subdev="${li(i)}"]`);if(!n)continue;const l=Ke(s);if(l.headlineEid){const t=n.querySelector(".sub-power-value");t&&(t.innerHTML=Un(tn(e,l.headlineEid)))}if(l.siteTotalEid){const t=tn(e,l.siteTotalEid),i=n.querySelector(".sub-site-total-value");i&&(i.innerHTML=Un(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");zA(t,0,n,o?.has(i)?bi(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="${li(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=Ze(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 ci(n)){const n=t.querySelector(`.meter-tile[data-meter-uuid="${li(r)}"] .meter-readings`);n&&(n.innerHTML=ui(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 i=t.target,r=i?.closest(".toggle-pill");if(!r)return;const o=e.querySelector(".slide-confirm");if(!o||!o.classList.contains("confirmed"))return;t.stopPropagation(),t.preventDefault();const a=r.closest("[data-uuid]");if(!a||!this._topology||!this._hass)return;const s=a.dataset.uuid;if(!s)return;const l=this._topology.circuits[s];if(!l)return;const c=l.entities?.switch;if(!c)return;if("operable"!==wn(l,this._hass))return;const d="on"===this._hass.states[c]?.state?"turn_off":"turn_on";this._hass.callService("switch",d,{},{entity_id:c}).catch(t=>{console.warn("SPAN Panel: switch service call failed",t),this._errorStore?.add({key:"service:relay",level:"error",message:n("error.relay_failed"),persistent:!1})})}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=Re(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,...WA(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};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:Je(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?_e(be(n)).get(e.targetId):this._topology?_e(be(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=_e(be(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=Re(l,a);r.refreshRating({...WA(s,o.uuid,a),monitoringInfo:c,monitoringGlobals:l?.global_settings??null})}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 Ie(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 Ie(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 Pe(o?.response)}catch(t){return console.warn("SPAN Panel: fresh monitoring status fetch failed",t),null}}bindSlideConfirm(t,e){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 UA(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 GA='\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 .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 .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\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 XA{constructor(){this._ctrl=new qA,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 Hn(e,i);if(a=t.topology,s=an(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 sn(t.last)-sn(t.first)+1}(s),c=this._ctrl.monitoringCache.status,d=Kn(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?[Oe(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 be(t)){if(on(n))continue;const t=n.tabs;if(!t||0===t.length)continue;const r=Math.min(...t),s=1===t.length?"single":cn(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=sn(Math.max(...n));0===ln(t)?s.add(i):l.add(i)}function c(t){return{monInfo:Re(r,t.circuit),sheddingPriority:kn(t.circuit,n)}}const d=t=>t>=e.first&&t<=e.last,u=sn(e.first),h=sn(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}=c(f);p+=ai(f.uuid,f.circuit,e,"2 / 5","row-span",n,i,t,r,f.members),p+=v;continue}if(!s.has(t))if(!f||"col-span"!==f.layout&&"single"!==f.layout)!a.has(r)&&d(r)&&(p+=si(e,"2"));else{const{monInfo:t,sheddingPriority:r}=c(f);p+=ai(f.uuid,f.circuit,e,"2",f.layout,n,i,t,r,f.members)}if(!l.has(t))if(!g||"col-span"!==g.layout&&"single"!==g.layout)!a.has(h)&&d(h)&&(p+=si(e,"4"));else{const{monInfo:t,sheddingPriority:r}=c(g);p+=ai(g.uuid,g.circuit,e,"4",g.layout,n,i,t,r,g.members)}p+=v}return p}(a,s,e,r,c),p=pi(a,e,r,{showFavorites:this._ctrl.showFavorites}),f=hi(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=UA(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)}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 YA="\n display:flex;align-items:center;gap:8px;margin-bottom:8px;\n",ZA="var(--divider-color)",KA=`\n background:var(--secondary-background-color,#333);\n border:1px solid ${ZA};\n color:var(--primary-text-color);\n border-radius:4px;padding:6px 10px;width:80px;font-size:0.85em;\n`,QA="\n min-width:130px;font-size:0.85em;color:var(--secondary-text-color);\n",JA="\n min-width:160px;font-size:0.85em;color:var(--secondary-text-color);\n",tI="\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",eI=`\n background:var(--secondary-background-color,#333);\n border:1px solid ${ZA};\n color:var(--primary-text-color);\n border-radius:3px;padding:3px 6px;width:50px;font-size:0.8em;\n text-align:center;\n`,nI="var(--error-color,#f44336)",iI="\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 rI=0;function oI(t){return rI+=1,`span-monitoring-${t}-${rI}`}const aI=[["continuous_threshold_pct","#g-continuous"],["spike_threshold_pct","#g-spike"],["window_duration_m","#g-window"],["cooldown_duration_m","#g-cooldown"]];function sI(t){const e=document.createElement("div");e.id=oI("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?nI:ZA}}const lI=["reset-btn","circuit-toggle","mains-toggle","rating-clear","rating-turn-off"],cI="other_breaker",dI=["[id]",".threshold-input",".rating-input",...lI.map(t=>`.${t}`)].join(", "),uI={"reset-btn":t=>pI(t,"continuous_threshold_pct"),"rating-clear":t=>pI(t,cI),"rating-turn-off":t=>fI("circuit-toggle",t)};function hI(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?pI(e,n):null;if(t.classList.contains("rating-input"))return pI(e,cI);const i=gI(t);return i?fI(i,e):null}function pI(t,e){return`${t}\0${e}`}function fI(t,e){return`${t}\0${e}`}function gI(t){return lI.find(e=>t.classList.contains(e))}const mI=["one_space","two_spaces"],vI=["applies","pending","averaged_legs"];function _I(t,e){return null===t||e.some(e=>e===t)}function yI(t){const{package_ratings_form:e,package_ratings_state:n,...i}=t,r=i;return _I(e,mI)&&(r.package_ratings_form=e),_I(n,vI)&&(r.package_ratings_state=n),r}function bI(t){if(!t||"object"!=typeof t)return;const e={};for(const[n,i]of Object.entries(t))i&&"object"==typeof i&&(e[n]=yI(i));return e}const xI={continuous_threshold_pct:"monitoring.continuous",spike_threshold_pct:"monitoring.spike",window_duration_m:"monitoring.window",cooldown_duration_m:"monitoring.cooldown"};function wI(t,e,r,o,a,s){const{min:l,max:c}=de[r];return`\n ${a}\n `}function SI(t,e){const i=Yt(t);return`${Kt({...i,userSet:!e&&i.userSet})||`${Ft(n("monitoringRating.none"))}`}`}function CI(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 kI(t){return t.ratings?.[1]??null}function MI(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 TI(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 AI="event_bus",II=[{type:"device"},{type:"entity"}];function PI(t){return t.length?t.map(t=>t===AI?n("notification.event_bus_target"):t).join(", "):n("notification.none_selected")}function DI(t){return i("notification.targets_button",{targets:t})}class LI{static of(t){let e=LI._watches.get(t);return e||(e=new LI(t),LI._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()}}LI._watches=new WeakMap;class EI{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 RI=Promise.resolve(new Map);function NI(t,e,n){return n.get(t)||e.name||t}class zI{constructor(){this.errorStore=null,this._pendingSaves=new Map,this._circuitLabels=RI,this._epoch=0,this._renderSeq=0,this._drawn=null,this._configEntryId=null,this._notifyCloseHandler=null,this._headerHTML=""}stop(){this._epoch+=1,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;void 0!==r&&(this._configEntryId=r),void 0!==o?this._circuitLabels=function(t){return Promise.resolve(t).then(Ne,t=>(console.warn("SPAN Panel: no topology to label the Monitoring tab's circuits by:",Jt(t)),new Map))}(o):l||(this._circuitLabels=RI);const c=this._circuitLabels;this._headerHTML=a,this._notifyCloseHandler&&(document.removeEventListener("click",this._notifyCloseHandler),this._notifyCloseHandler=null);const d=this._epoch,u=++this._renderSeq;let h;await this._flushPendingSaves().catch(()=>{});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=bI(e.circuits);i&&(n.circuits=i);const r=bI(e.mains);return r&&(n.mains=r),n}(n?.response)}catch(t){console.warn("SPAN Panel: monitoring status fetch failed",t),h=null}const p=await c;if(d!==this._epoch||u!==this._renderSeq)return;if(await LI.of(t).settled(),d!==this._epoch||u!==this._renderSeq)return;const f=h?.global_settings??{},g=!0===h?.enabled,m=h?.circuits??{},v=h?.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(AI);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,NI(t,e,p)])),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])=>qt(t)),E=D.some(([,t])=>qt(t)),R=!0===h?.monitoring_rating_offered,N=new Map;for(const[t,e]of I){const n=CI(e,R);n&&N.set(t,n)}const z=new Map,O=new Map,$=I.map(([t,e])=>{const r=A(t),o=Ft(r),a=qt(e),s=!0===e.has_override,l=a?"":"opacity:0.4;",c=Ft(t),d=N.get(t)??null,u=d?Xt(e,e):null,h=u?{warning:u,textId:oI("warning")}:null;u&&(z.set(t,u),O.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?Wt(n):null,s=i("monitoringRating.panel_plus",{panel:String(r.panelA)}),l=oI("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):SI(e,!1)}\n ${wI(c,r,"continuous_threshold_pct",e.continuous_threshold_pct,"%","circuit")}\n ${wI(c,r,"spike_threshold_pct",e.spike_threshold_pct,"%","circuit")}\n ${wI(c,r,"window_duration_m",e.window_duration_m,"m","circuit")}\n ${wI(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(MI(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=qt(e),s=!0===e.has_override,l=a?"":"opacity:0.4;",c=Ft(t);return`\n \n \n \n \n ${SI(e,!0)}\n ${wI(c,r,"continuous_threshold_pct",e.continuous_threshold_pct,"%","mains")}\n ${wI(c,r,"spike_threshold_pct",e.spike_threshold_pct,"%","mains")}\n ${wI(c,r,"window_duration_m",e.window_duration_m,"m","mains")}\n ${wI(c,r,"cooldown_duration_m",e.cooldown_duration_m,"m","mains")}\n \n ${s?``:""}\n \n \n `}).join(""),F=l?function(t){const e=se(t),n=e?hI(e):null;if(!e||null===n)return null;const i=e.dataset.entity,r=gI(e),o=void 0!==r&&void 0!==i?uI[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 ${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===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_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 ${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=t.querySelector("#toggle-all-circuits");j&&!L&&E&&(j.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),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(dI)];for(const t of e.keys){const i=n.find(e=>hI(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&&l,z,O)}_drawingIn(t){const e=this._drawn;if(e?.container===t&&2===t.childNodes.length&&t.firstChild===e.content&&t.lastChild===e.announcer)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:MI(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}_callService(t,e,n){return t.callWS({type:"call_service",domain:s,service:e,service_data:this._serviceData({...n})})}_callSetGlobal(t,e){return this._callService(t,"set_global_monitoring",e)}_saveOnPause(t,e,i){const r=this._serviceData({[e]:i});let o=this._pendingSaves.get(e);o||(o=new EI,this._pendingSaves.set(e,o)),o.schedule(async()=>{try{await t.callWS({type:"call_service",domain:s,service:"set_global_monitoring",service_data:r})}catch(t){throw console.warn(`SPAN Panel: ${e} save failed`,t),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1}),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,i)=>{if(!t)return;const r=null===e?i:Jt(e);t.textContent=`${n("error.prefix")} ${r}`,t.style.color="var(--error-color, #f44336)"},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 aI){const i=t.querySelector(n);i&&l.set(e,fe(i,e,{report:sI(i),save:t=>{s({[e]:t})}}))}const c=t=>{r&&(r.style.opacity=t?"":"0.4",r.style.pointerEvents=t?"":"none")};i&&i.addEventListener("change",async()=>{const r=this._epoch,s=i.checked,d=()=>{i.checked=!s,c(!s)};c(s);try{if(s){const t=(()=>{const t={};let e=!0;for(const[n]of aI){const i=l.get(n)?.check()??null;null===i?e=!1:t[n]=i}return e?t:null})();if(!t)return d(),void a(o,null,n("monitoring.enable_invalid"));await this._callSetGlobal(e,t)}else await this._callSetGlobal(e,{enabled:!1})}catch(t){return d(),void a(o,t,n("error.failed"))}await this._redraw(t,e,r)})}_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=PI(i);r&&(r.textContent=o),n.setAttribute("aria-label",DI(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){const i=t.querySelector("#g-priority"),r=t.querySelector("#g-title-template"),o=t.querySelector("#g-message-template");i&&i.addEventListener("change",async()=>{const r=this._epoch;try{await this._callSetGlobal(e,{notification_priority:i.value}),await this._redraw(t,e,r)}catch(t){console.warn("SPAN Panel: notification priority change failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1})}}),r&&r.addEventListener("input",()=>{this._saveOnPause(e,"notification_title_template",r.value)}),o&&o.addEventListener("input",()=>{this._saveOnPause(e,"notification_message_template",o.value)});const a=t.querySelector("#test-notification-btn"),l=t.querySelector("#test-notification-status");a&&a.addEventListener("click",async()=>{a.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();const r={};this._configEntryId&&(r.config_entry_id=this._configEntryId),await e.callWS({type:"call_service",domain:s,service:"test_notification",service_data:r}),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{a.disabled=!1}})}_bindToggleAll(t,e,i,r){const o=t.querySelector("#toggle-all-circuits");o&&o.addEventListener("change",async()=>{const a=this._epoch,l=o.checked,c=[...Object.keys(i).map(t=>e.callWS({type:"call_service",domain:s,service:"set_circuit_threshold",service_data:this._serviceData({circuit_id:t,monitoring_enabled:l})}).catch(t=>{console.warn("SPAN Panel: circuit monitoring toggle failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1})})),...Object.keys(r).map(t=>e.callWS({type:"call_service",domain:s,service:"set_mains_threshold",service_data:this._serviceData({leg:t,monitoring_enabled:l})}).catch(t=>{console.warn("SPAN Panel: mains monitoring toggle failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1})}))];await Promise.all(c),await this._redraw(t,e,a)})}_bindMainsToggles(t,e){for(const i of t.querySelectorAll(".mains-toggle"))i.addEventListener("change",async()=>{const r=this._epoch,o=i.dataset.entity,a=i.checked;try{await e.callWS({type:"call_service",domain:s,service:"set_mains_threshold",service_data:this._serviceData({leg:o,monitoring_enabled:a})})}catch(t){return console.warn("SPAN Panel: mains threshold toggle failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1}),void(i.checked=!a)}await this._redraw(t,e,r)})}_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;await this._setCircuitMonitoring(t,e,i,r)||(n.checked=!r)})}}_bindTurnOffButtons(t,e){for(const n of t.querySelectorAll(".rating-turn-off")){const i=n.dataset.entity;void 0!==i&&TI(n,()=>this._setCircuitMonitoring(t,e,i,!1))}}async _setCircuitMonitoring(t,e,i,r){const o=this._epoch;try{await this._callService(e,"set_circuit_threshold",{circuit_id:i,monitoring_enabled:r})}catch(t){return console.warn("SPAN Panel: circuit threshold toggle failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1}),!1}return await this._redraw(t,e,o),!0}_bindThresholdInputs(t,e){for(const n of t.querySelectorAll(".threshold-input")){const i=n.dataset.field,r=n.dataset.entity;if(!he(i)||void 0===r)continue;const o="mains"===n.dataset.type;fe(n,i,{report:sI(n),save:a=>{const s=o?"set_mains_threshold":"set_circuit_threshold",l=o?{leg:r,[i]:a}:{circuit_id:r,[i]:a};this._saveThreshold(t,e,n,s,l)}})}}async _saveThreshold(t,e,i,r,o){const a=this._epoch;try{await e.callWS({type:"call_service",domain:s,service:r,service_data:this._serviceData(o)})}catch(t){return console.warn("SPAN Panel: threshold input save failed",t),this.errorStore?.add({key:"service:monitoring",level:"error",message:n("error.threshold_failed"),persistent:!1}),void(i.style.borderColor=nI)}await this._redraw(t,e,a)}_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=ge(i,{report:sI(i),stored:()=>kI(o),save:n=>{this._savePackageRatings(t,e,i,a,o,n)}}),s=i.closest("td")?.querySelector(".rating-clear");s&&TI(s,()=>(a.revert(),this._clearPackageRatings(t,e,o)))}}async _savePackageRatings(t,e,n,i,r,o){const a=this._epoch;try{await this._callService(e,"set_circuit_package_ratings",{circuit_id:r.circuitId,package_ratings_a:[r.panelA,o]})}catch(t){return me(e,this.errorStore,t),void(i.answerRefusal(o)&&n.isConnected&&le()&&n.focus())}await this._redraw(t,e,a)}async _clearPackageRatings(t,e,n){const i=this._epoch;try{await this._callService(e,"clear_circuit_package_ratings",{circuit_id:n.circuitId})}catch(t){return me(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;TI(i,async()=>{const i=this._epoch,a=o?"clear_mains_threshold":"clear_circuit_threshold",l=this._serviceData(o?{leg:r}:{circuit_id:r});try{await e.callService(s,a,l)}catch(t){return console.warn("SPAN Panel: threshold reset failed",t),ie(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 OI(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function $I(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)=>$I(t,e[n]));if(!OI(t)||!OI(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=>$I(t[n],e[n]))}function HI(t,e){return null!==t&&t.toLowerCase().includes(e)}function FI(t,e){const n=t[e];return"string"==typeof n?n:""}function BI(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 VI(t,e){const n=Number(e);return{unit_of_measurement:t||null,display_precision:""!==e&&Number.isFinite(n)?n:null}}function jI(t,e,n){return""!==t&&e.includes(t)&&n.length>0}function WI(t){if(!t)return"";const e=t.replace(/_/g," ");return e.charAt(0).toUpperCase()+e.slice(1)}const qI=["0","1","2","3","4","5","6"],UI="var(--secondary-text-color,#999)",GI="var(--primary-color,#4dd9af)",XI="var(--warning-color,#ff9800)",YI="var(--card-background-color,#1c1c1c)",ZI="var(--secondary-background-color,#232323)",KI="var(--divider-color,#333)",QI=`background:${ZI};border:1px solid ${KI};color:var(--primary-text-color);border-radius:4px;padding:4px 8px;font-size:0.85em;`,JI=`${QI}min-width:0;`,tP="display:flex;align-items:center;gap:12px;flex-wrap:wrap;",eP=`font-size:0.85em;color:${UI};min-width:130px;`,nP=`color:${UI};font-size:0.75em;`,iP=`background:none;border:1px solid ${KI};color:var(--primary-text-color);border-radius:6px;padding:6px 12px;font-size:0.8em;cursor:pointer;`;function rP(t,e){const n=e?GI:UI;return`${Ft(t)}`}function oP(t,e,n){const i=e.map(t=>``).join("");return``}function aP(t){return"total_increasing"===t?n("adopted.warn_total_increasing"):"statistics_removed"===t?n("adopted.warn_statistics_removed"):t}class sP{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||!$I(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:FI(e,"name"),unit:FI(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(HI(e.name,n)){i.push(e);continue}const t=e.rows.filter(t=>HI(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?rP(n("adopted.adopted_device"),!1):rP(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:${ZI};border:1px solid ${KI};border-bottom-color:transparent;border-radius:8px 8px 0 0;cursor:pointer;`:`display:flex;align-items:center;padding:12px 16px;gap:10px;background:${YI};border:1px solid ${KI};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?rP(n("adopted.curated"),!0):""}\n ${t.stale_fields.length>0?rP(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&&jI(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?GI:UI;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:WI(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 ${oP("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:WI(t)}))];return`\n
    \n ${n("adopted.statistics_class")}\n ${oP("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")},...qI.map(t=>({value:t,label:t}))];return`\n
    \n ${n("adopted.display_unit")}\n ${oP("unit",i,e.unit)}\n ${n("adopted.precision")}\n ${oP("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:WI(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:BI(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=BI(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&&jI(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:VI(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(aP):[]]}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 lP(t=""){const e=t?` value="${Ft(t)}"`:"",i=t?"":"display:none;";return`\n
    \n \n \n
    \n `}function cP(t,e,i,r,o,a,s,l){const c=un(e,i),d=wn(e,i),u=we([e]),h=Ft(e.name||n("grid.unknown")),p="current"===Qn(r).entityRole;let f;f=c?p?Xn(pn(e,i)):Gn(hn(e,i)):"";const g=ri(a||"unknown");let m="";const v=mn(l,i,o);null!==v&&(m=`${Math.round(v)}%`);const _=``,y=on(e)?"":"none"===d?`${c?"ON":"OFF"}`:ti(c,d);return`\n
    \n ${u?`${u}`:""}\n ${m}\n ${h}\n ${g}\n ${y}\n \n ${f}\n \n ${_}\n \n
    \n `}function dP(t,e,n,i,r){const o=gn(e,hn(e,n)),a=dn(0,r,un(e,n),o),s=Ft(t);return`\n
    \n
    \n
    \n
    \n
    \n `}function uP(t){return`
    ${Ft(t)}
    `}function hP(t,e,n){return{isOn:un(t,e),value:"current"===(n.chart_metric||"power")?pn(t,e):hn(t,e)}}function pP(t,e,n,i){const r=hP(t,n,i),o=hP(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 fP(t,e,n){return t.sort((t,i)=>pP(t[1],i[1],e,n))}class gP{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=fP(Object.entries(n.circuits),e,i),s=_e(be(n));let l=o+lP(this._searchQuery);l+=`
    `;for(const[t,n]of a){const o=Re(r,n),a=kn(n,e),c=this._expandedUuids.has(t);l+=`
    `,l+=cP(t,n,e,i,o,a,c,ye(n,s.get(t))),c&&(l+=dP(t,n,e,0,o)),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=_e(be(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+lP(this._searchQuery);u+=`
    `;for(const t of d){const n=c.get(t);if(!n)continue;const i=fP(n,e,r);u+=uP(t);for(const[t,n]of i){const i=Re(o,n),a=kn(n,e),s=this._expandedUuids.has(t);u+=`
    `,u+=cP(t,n,e,r,i,a,s,ye(n,l.get(t))),s&&(u+=dP(t,n,e,0,i)),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"===Qn(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}=hP(a,e,i),c=t.querySelector(".list-power-value");c&&(c.innerHTML=s?r?Xn(l):Gn(l):""),ei(t,s,wn(a,e)),oi(t,kn(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)=>pP(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=UA(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=li(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=Re(this._monitoringStatus,e),o=dP(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 mP=["name","name_by_user"];function vP(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))}const _P="loaded";function yP(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 bP(t,e,n){const i=t.connection;return i?i.subscribeEvents(t=>{(function(t){const e=yP(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=yP(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"):()=>{}}const xP=["relay_state","relay_state_target","priority","priority_target"];function wP(t){const e={...t};for(const t of xP)delete e[t];return e}function SP(t){const e=Object.fromEntries(Object.entries(t.circuits).map(([t,e])=>[t,wP(e)]));return{...t,circuits:e}}function CP(t,e){return`${t}|${e}`}class kP{async build(t,e,n,i){const r=new Map;for(const t of n)r.set(t.id,t);const o=i?new Ie(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 Hn(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=CP(t,e),s=l&&o?`${o} · ${n.name}`:n.name,u=n.shared_meter_group,p=u?CP(t,u):u,f=u?i.shared_meter_groups?.[u]:void 0;p&&f&&(d[p]={...f,members:f.members.map(e=>CP(t,e))}),c[a]={...n,name:s,shared_meter_group:p},h[a]={panelDeviceId:t,kind:"circuit",targetId:e,configEntryId:r}}for(const e of g){const n=i.sub_devices?.[e];if(!n)continue;const a=CP(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 MP="span_panel_favorites_view_state";function TP(t){try{localStorage.setItem(MP,JSON.stringify(t))}catch{}}function AP(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 IP(t){let e=!1;return()=>{e||(e=!0,Promise.resolve().then(()=>{e=!1,t()}))}}var PP;const DP="favorites";function LP(t){return"dashboard"===t||"adopted"===t}let EP=PP=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 XA,this._monitoringTab=new zI,this._adoptedTab=new sP,this._listDashCtrl=new qA,this._listCtrl=new gP(this._listDashCtrl),this._favCache=new Be,this._favCtrl=new kP,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=AP(()=>this._refreshPanels()),this._requestPanelsRefresh=IP(()=>{this._panelsRefresh()}),this._requestTabRender=IP(()=>{this._scheduleTabRender()}),this._onFavoritesChanged=null,this._deviceRegistryUnsub=null,this._renamedPanelIds=new Set,this._renameRefresh=AP(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=AP(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(He,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(He,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")||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&&LP(this._activeTab))return void(this._activeTab="activity");this._scheduleTabRender()}if(t.has("_selectedPanelId")&&(this._selectedPanelId!==DP&&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)}}}setConfig(t){}render(){var i,r,o;if(i=this.hass?.language,t=i&&e[i]?i:"en",!this.hass)return ct` + `,_([Lt({attribute:!1})],yI.prototype,"options",void 0),_([Lt({attribute:!1})],yI.prototype,"data",void 0),_([Lt({type:String})],yI.prototype,"height",void 0);try{customElements.get("span-chart")||customElements.define("span-chart",yI)}catch{}function bI(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 xI(t){return null===t?Ci:function(t){return(Math.abs(t)/1e3).toFixed(1)}(t)}function wI(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):Ci,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=xI(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):Ci,c&&(c.textContent="A")}else l.textContent=xI(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):Ci,u&&(u.textContent="A")}else d.textContent=xI(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):Ci,p&&(p.textContent="A")}else h.textContent=xI(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?Ci:`${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:Ci}}function SI(t,e,n,i,r,o,a){if(!t||!n||!e)return;const s=ir(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&&wI(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:Ni(i),monitoringStatus:a};for(const e of l)for(const n of ye(e)){const i=t.querySelector(`.circuit-slot[data-uuid="${Ui(n.uuid)}"]`);if(!i)continue;const r=n.uuid===e.uuid?e.circuit:xe(n.circuit,e);CI(i,n.uuid,r,d)}}function CI(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?Pi(Un(n,r)):Ii(d)),Hi(t,h,ei(n,r),on(i.topology,e)),t.classList.toggle("circuit-off",!h),t.classList.toggle("circuit-producer",u),ji(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)?rr(a.get(e)):s,h=Gn(n),p=ze(c,n),g=Ut(n,p);bI(f,0,i,d,l,u,r,g?{ratingA:g,...$e(p)}:void 0,h)}}class kI{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 MI(t,e){if(!t)return o;const n=t.circuits?.[e];return n?.has_override?n.horizon:t.global_horizon??o}function TI(t,e){if(!t)return o;const n=t.sub_devices?.[e];return n?.has_override?n.horizon:t.global_horizon??o}function AI(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 II{constructor(){this.powerHistory=new Map,this.horizonMap=new Map,this.subDeviceHorizonMap=new Map,this.monitoringCache=new Ee,this.monitoringMultiCache=new Re,this.graphSettingsCache=new kI,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,MI(t,e));if(t&&this._topology?.sub_devices)for(const e of Object.keys(this._topology.sub_devices))this.subDeviceHorizonMap.set(e,TI(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,MI(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,TI(i,r))}}async loadHistory(){await pr(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=rr(i),c=or(l),d=ar(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 hr(this._topology))i.has(e)&&r.add(t);const o=new Map;try{await pr(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&&(SI(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=ir(i);for(const[i,s]of Object.entries(n.sub_devices)){const n=t.querySelector(`[data-subdev="${Ui(i)}"]`);if(!n)continue;const l=Dn(s);if(l.headlineEid){const t=n.querySelector(".sub-power-value");t&&(t.innerHTML=Ai(Rn(e,l.headlineEid)))}if(l.siteTotalEid){const t=Rn(e,l.siteTotalEid),i=n.querySelector(".sub-site-total-value");i&&(i.innerHTML=Ai(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");bI(t,0,n,o?.has(i)?rr(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="${Ui(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 Gi(n)){const n=t.querySelector(`.meter-tile[data-meter-uuid="${Ui(r)}"] .meter-readings`);n&&(n.innerHTML=Yi(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=ze(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,...AI(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=ze(l,a);r.refreshRating({...AI(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 PI(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 DI='\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 LI{constructor(){this._ctrl=new II,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 xi(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=Ri(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:ze(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+=qi(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+=Wi(e,"2"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(f);p+=qi(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+=Wi(e,"4"));else{const{monInfo:t,sheddingPriority:r,access:o}=c(g);p+=qi(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=Ki(a,e,r,{showFavorites:this._ctrl.showFavorites}),f=Zi(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=PI(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 EI="\n display:flex;align-items:center;gap:8px;margin-bottom:8px;\n",RI="var(--divider-color)",NI=`\n background:var(--secondary-background-color,#333);\n border:1px solid ${RI};\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",OI="\n min-width:160px;font-size:0.85em;color:var(--secondary-text-color);\n",$I="\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",HI=`\n background:var(--secondary-background-color,#333);\n border:1px solid ${RI};\n color:var(--primary-text-color);\n border-radius:3px;padding:3px 6px;width:50px;font-size:0.8em;\n text-align:center;\n`,FI="var(--error-color,#f44336)",BI="\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 VI=0;function jI(t){return VI+=1,`span-monitoring-${t}-${VI}`}const qI=[["continuous_threshold_pct","#g-continuous"],["spike_threshold_pct","#g-spike"],["window_duration_m","#g-window"],["cooldown_duration_m","#g-cooldown"]];function WI(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?FI:RI}}const UI=["reset-btn","circuit-toggle","mains-toggle","rating-clear","rating-turn-off"],GI="other_breaker",XI=["[id]",".threshold-input",".rating-input",...UI.map(t=>`.${t}`)].join(", "),YI={"reset-btn":t=>KI(t,"continuous_threshold_pct"),"rating-clear":t=>KI(t,GI),"rating-turn-off":t=>QI("circuit-toggle",t)};function ZI(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?KI(e,n):null;if(t.classList.contains("rating-input"))return KI(e,GI);const i=JI(t);return i?QI(i,e):null}function KI(t,e){return`${t}\0${e}`}function QI(t,e){return`${t}\0${e}`}function JI(t){return UI.find(e=>t.classList.contains(e))}const tP=["one_space","two_spaces"],eP=["applies","pending","averaged_legs"];function nP(t,e){return null===t||e.some(e=>e===t)}function iP(t){const{package_ratings_form:e,package_ratings_state:n,...i}=t,r=i;return nP(e,tP)&&(r.package_ratings_form=e),nP(n,eP)&&(r.package_ratings_state=n),r}function rP(t){if(!t||"object"!=typeof t)return;const e={};for(const[n,i]of Object.entries(t))i&&"object"==typeof i&&(e[n]=iP(i));return e}const oP={continuous_threshold_pct:"monitoring.continuous",spike_threshold_pct:"monitoring.spike",window_duration_m:"monitoring.window",cooldown_duration_m:"monitoring.cooldown"};function aP(t,e,r,o,a,s){const{min:l,max:c}=he[r];return`\n ${a}\n `}function sP(t,e){const i=Yt(t);return`${Kt({...i,userSet:!e&&i.userSet})||`${Ft(n("monitoringRating.none"))}`}`}function lP(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 cP(t){return t.ratings?.[1]??null}function dP(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 uP(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 hP="event_bus",pP=[{type:"device"},{type:"entity"}];function fP(t){return t.length?t.map(t=>t===hP?n("notification.event_bus_target"):t).join(", "):n("notification.none_selected")}function gP(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 vP="0.4";function _P(t,e,n){t.isConnected&&(e&&t.toggleAttribute("checked",n),t.checked=t.hasAttribute("checked"))}function yP(t,e,n){if(!t.isConnected)return;_P(t,e,n);const i=t.closest("tr");i&&(i.style.opacity=t.checked?"":vP)}function bP(t,e,n){return t.querySelector(`.${e}[data-entity="${Ui(n)}"]`)}function xP(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 wP(t,e,n,i){if(!e.isConnected)return;yP(e,n,i);const r=t.querySelector("#toggle-all-circuits");r&&xP(r,t)}class SP{static of(t){let e=SP._watches.get(t);return e||(e=new SP(t),SP._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()}}SP._watches=new WeakMap;class CP{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 kP=Promise.resolve(new Map);function MP(t,e,n){return n.get(t)||e.name||t}class TP{constructor(){this.errorStore=null,this._pendingSaves=new Map,this._circuitLabels=kP,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(Oe,t=>(console.warn("SPAN Panel: no topology to label the Monitoring tab's circuits by:",Jt(t)),new Map))}(o):l||(this._circuitLabels=kP);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=rP(e.circuits);i&&(n.circuits=i);const r=rP(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 SP.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(hP);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,MP(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,z=new Map;for(const[t,e]of P){const n=lP(e,N);n&&z.set(t,n)}const O=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:${vP};`,c=Ft(t),d=z.get(t)??null,u=d?Xt(e,e):null,h=u?{warning:u,textId:jI("warning")}:null;u&&(O.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=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):sP(e,!1)}\n ${aP(c,r,"continuous_threshold_pct",e.continuous_threshold_pct,"%","circuit")}\n ${aP(c,r,"spike_threshold_pct",e.spike_threshold_pct,"%","circuit")}\n ${aP(c,r,"window_duration_m",e.window_duration_m,"m","circuit")}\n ${aP(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(dP(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:${vP};`,c=Ft(t);return`\n \n \n \n \n ${sP(e,!0)}\n ${aP(c,r,"continuous_threshold_pct",e.continuous_threshold_pct,"%","mains")}\n ${aP(c,r,"spike_threshold_pct",e.spike_threshold_pct,"%","mains")}\n ${aP(c,r,"window_duration_m",e.window_duration_m,"m","mains")}\n ${aP(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?ZI(e):null;if(!e||null===n)return null;const i=e.dataset.entity,r=JI(e),o=void 0!==r&&void 0!==i?YI[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,z),this._bindTurnOffButtons(t,e),this._bindResetButtons(t,e),this._bindRatingMarks(t),function(t,e){if(!e)return;const n=[...t.querySelectorAll(XI)];for(const t of e.keys){const i=n.find(e=>ZI(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,O,$),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,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:dP(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 CP,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&&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 qI){const i=t.querySelector(n);i&&l.set(e,me(i,e,{report:WI(i),save:t=>{s({[e]:t})}}))}const c=t=>{r&&(r.style.opacity=t?"":vP,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 qI){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),_P(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=fP(i);r&&(r.textContent=o),n.setAttribute("aria-label",gP(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:bP(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:bP(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&&yP(t,e,a);xP(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),wP(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;wP(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&&uP(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=bP(t,"circuit-toggle",n);i&&wP(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:WI(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=FI)}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:WI(i),stored:()=>cP(o),save:n=>{this._savePackageRatings(t,e,i,a,o,n)}}),s=i.closest("td")?.querySelector(".rating-clear");s&&uP(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;uP(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 AP(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function IP(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)=>IP(t,e[n]));if(!AP(t)||!AP(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=>IP(t[n],e[n]))}function PP(t,e){return null!==t&&t.toLowerCase().includes(e)}function DP(t,e){const n=t[e];return"string"==typeof n?n:""}function LP(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 EP(t,e){const n=Number(e);return{unit_of_measurement:t||null,display_precision:""!==e&&Number.isFinite(n)?n:null}}function RP(t,e,n){return""!==t&&e.includes(t)&&n.length>0}function NP(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"],OP="var(--secondary-text-color,#999)",$P="var(--primary-color,#4dd9af)",HP="var(--warning-color,#ff9800)",FP="var(--card-background-color,#1c1c1c)",BP="var(--secondary-background-color,#232323)",VP="var(--divider-color,#333)",jP=`background:${BP};border:1px solid ${VP};color:var(--primary-text-color);border-radius:4px;padding:4px 8px;font-size:0.85em;`,qP=`${jP}min-width:0;`,WP="display:flex;align-items:center;gap:12px;flex-wrap:wrap;",UP=`font-size:0.85em;color:${OP};min-width:130px;`,GP=`color:${OP};font-size:0.75em;`,XP=`background:none;border:1px solid ${VP};color:var(--primary-text-color);border-radius:6px;padding:6px 12px;font-size:0.8em;cursor:pointer;`;function YP(t,e){const n=e?$P:OP;return`${Ft(t)}`}function ZP(t,e,n){const i=e.map(t=>``).join("");return``}function KP(t){return"total_increasing"===t?n("adopted.warn_total_increasing"):"statistics_removed"===t?n("adopted.warn_statistics_removed"):t}class QP{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||!IP(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:DP(e,"name"),unit:DP(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(PP(e.name,n)){i.push(e);continue}const t=e.rows.filter(t=>PP(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?YP(n("adopted.adopted_device"),!1):YP(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:${BP};border:1px solid ${VP};border-bottom-color:transparent;border-radius:8px 8px 0 0;cursor:pointer;`:`display:flex;align-items:center;padding:12px 16px;gap:10px;background:${FP};border:1px solid ${VP};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?YP(n("adopted.curated"),!0):""}\n ${t.stale_fields.length>0?YP(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&&RP(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?$P:OP;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:NP(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 ${ZP("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:NP(t)}))];return`\n
    \n ${n("adopted.statistics_class")}\n ${ZP("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 ${ZP("unit",i,e.unit)}\n ${n("adopted.precision")}\n ${ZP("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:NP(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:LP(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=LP(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&&RP(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:EP(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(KP):[]]}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 JP(t=""){const e=t?` value="${Ft(t)}"`:"",i=t?"":"display:none;";return`\n
    \n \n \n
    \n `}function tD(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"===Ni(r).entityRole;let g;g=d?f?Pi(Un(e,i)):Ii(Wn(e,i)):"";const m=Vi(a||"unknown");let v="";const _=Yn(l,i,o);null!==_&&(v=`${Math.round(_)}%`);const y=``,b=$n(e)?"":"none"===u?`${d?"ON":"OFF"}`:$i(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 eD(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 nD(t){return`
    ${Ft(t)}
    `}function iD(t,e,n){return{isOn:qn(t,e),value:"current"===(n.chart_metric||"power")?Un(t,e):Wn(t,e)}}function rD(t,e,n,i){const r=iD(t,n,i),o=iD(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 oD(t,e,n){return t.sort((t,i)=>rD(t[1],i[1],e,n))}class aD{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=oD(Object.entries(n.circuits),e,i),s=be(we(n));let l=o+JP(this._searchQuery);l+=`
    `;for(const[t,o]of a){const a=ze(r,o),c=ri(o,e),d=this._expandedUuids.has(t);l+=`
    `,l+=tD(t,o,e,i,a,c,d,xe(o,s.get(t)),on(n,t)),d&&(l+=eD(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+JP(this._searchQuery);u+=`
    `;for(const t of d){const n=c.get(t);if(!n)continue;const a=oD(n,e,r);u+=nD(t);for(const[t,n]of a){const a=ze(o,n),s=ri(n,e),c=this._expandedUuids.has(t);u+=`
    `,u+=tD(t,n,e,r,a,s,c,xe(n,l.get(t)),on(i,t)),c&&(u+=eD(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"===Ni(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}=iD(a,e,i),c=t.querySelector(".list-power-value");c&&(c.innerHTML=s?r?Pi(l):Ii(l):""),Hi(t,s,ei(a,e),on(n,o)),ji(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)=>rD(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=PI(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=Ui(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=eD(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 sD=["name","name_by_user"];function lD(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))}const cD="loaded";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 xi(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 LI,this._monitoringTab=new TP,this._adoptedTab=new QP,this._listDashCtrl=new II,this._listCtrl=new aD(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
    @@ -284,7 +333,7 @@ var Xl={},Yl={};var Zl,Kl=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&&LP(this._activeTab)&&(this._activeTab="activity"),this._unsubscribeAreaTab(),this._areaTopology=null}get _isFavoritesView(){return this._selectedPanelId===DP}_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&&!LP(n)&&(this._favoritesViewState.activeTab=n,TP(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,TP(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:mP.some(t=>t in n)?e.device_id:null}(t);if(e){for(const[t,n]of this._renderedTopologies)vP(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===_P&&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===_P&&t!==_P&&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||!1===t.user?.is_admin)return;const e=new Set;for(const t of this._panels)t.id!==DP&&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,bP(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!==DP&&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=AP(()=>{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}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!==DP&&e.config_entry_id===t);this._isFavoritesView||e&&e.id===this._selectedPanelId?e?(!this._isFavoritesView||this._renderedTopologies.has(e.id)||je(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 Hn(this.hass,t,null))}catch(t){return void console.warn("SPAN Panel: topology refresh failed; keeping the current view:",Jt(t))}var r,o;this._renderedTopologies.get(t)===n&&(i&&e&&(await e(i),this._renderedTopologies.get(t)!==n)||i&&(r=i,null!==(o=n)&&$I(SP(r),SP(o)))||this._requestTabRender())}async _fetchBaselineTopology(){if(!this.hass||!this._selectedPanelId)return null;try{return(await Hn(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 zn(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(Nn.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 this.hass.callWS({type:"config/device_registry/list"})).filter(On),e=this._panels.filter(t=>t.id!==DP),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===DP)return;if(this._watchedPanelId===this._selectedPanelId)return;const t=this._selectedPanelId;this._watchedPanelId=t;try{const e=new Ie(this._errorStore),n=await Hn(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{const e=new Ie(this._errorStore);t=(await e.callWS(this.hass,{type:"config/device_registry/list"},{errorId:"fetch:topology"})).filter(On)}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(MP);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===DP){const t=this._favoritesViewState.activeTab;"activity"===t||"area"===t||"monitoring"===t?this._activeTab=t:LP(this._activeTab)&&(this._activeTab="activity")}this._chartMetric=localStorage.getItem("span_panel_metric")||"power"}finally{this._discovering=!1}}}_buildPanelList(t,e){if(!Ve(e))return t;return[{id:DP,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===DP;this._favorites=e;const i=this._panels.filter(t=>t.id!==DP);if(this._panels=this._buildPanelList(i,e),n&&!Ve(e)){!function(){try{localStorage.removeItem(MP)}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(){return function(t){return`\n
    \n \n
    \n ${Ft(n("header.enable_switches"))}\n
    \n \n
    \n
    \n
    \n ${Yn()}\n
    \n \n \n
    \n
    \n
    \n `}("current"===(this._chartMetric||"power"))}_buildFavoritesPanelStatsGridHTML(t,e){if(0===t.length)return"";return`
    ${t.map(t=>`\n
    \n
    ${Ft(t.panelName||t.topology.device_name||"")}
    \n ${Zn(t.topology,e,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="${li(n.panelDeviceId)}"]`);i&&$A(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 Ie(this._errorStore),r=await Hn(this.hass,this._selectedPanelId??void 0,n);if(t())return;const o=this._buildDashboardConfig();if(this._listDashCtrl.init(r.topology,o,this.hass,i),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,i),t())return;if(await this._listDashCtrl.fetchAndBuildHorizonMaps(),t())return;const a=r.topology?Kn(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 Ie(this._errorStore),r=await Hn(this.hass,this._selectedPanelId??void 0,n);if(t())return;const o=this._buildDashboardConfig();if(this._listDashCtrl.init(r.topology,o,this.hass,i),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,i),t())return;if(await this._listDashCtrl.fetchAndBuildHorizonMaps(),t())return;const a=r.topology?Kn(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!==DP),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(),i=this._buildFavoritesPanelStatsGridHTML(a.perPanelStats,m),r=n+i+(h?`
    \n
    ${pi(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 zI;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)}};EP._shellStyles=k` + `}_onPanelChange(t){const e=t.target;this._selectedPanelId=e.value,localStorage.setItem("span_panel_selected",e.value),this._isFavoritesView&&SD(this._activeTab)&&(this._activeTab="activity"),this._unsubscribeAreaTab(),this._areaTopology=null}get _isFavoritesView(){return this._selectedPanelId===wD}_onTabClick(t){const e=t.target.closest(".shared-tab");if(!e)return;const n=e.dataset.tab;n&&n!==this._activeTab&&(this._activeTab=n,this._isFavoritesView&&!SD(n)&&(this._favoritesViewState.activeTab=n,_D(this._favoritesViewState)))}_onTabContentClick(t){const e=t.target.closest(".unit-btn");if(e){const t=e.dataset.unit;if(!t||t===this._chartMetric)return;return this._chartMetric=t,void localStorage.setItem("span_panel_metric",t)}}_onSidePanelClosed(){if("dashboard"===this._activeTab){const t=this._dashboardTab._ctrl;t.monitoringCache.invalidate(),t.graphSettingsCache.invalidate()}this._listDashCtrl.monitoringMultiCache.invalidate(),this._pendingTabRender&&(this._pendingTabRender=!1,this._scheduleTabRender())}_onUnitChanged(t){const e=t.detail;e&&e!==this._chartMetric&&(this._chartMetric=e,localStorage.setItem("span_panel_metric",e))}_onListColumnsChanged(t){const e=t.detail;"number"!=typeof e||1!==e&&2!==e&&3!==e||e===this._listColumns||(this._listColumns=e,jt(e))}_onGraphSettingsChanged(){if("dashboard"===this._activeTab){const t=this._root.getElementById("tab-content");if(t){this._dashboardTab._ctrl.onGraphSettingsChanged(t)}}}_onNavigateTab(t){const e=t.detail;e&&(this._activeTab=e)}_onFavoritesViewStateChangedEvent(t){if(!this._isFavoritesView)return;const e=t.detail;if(!e)return;const n=this._favoritesViewState;n.activeTab=e.view;const i=this._listDashCtrl.topology,r=i?.circuits;r&&Object.keys(r).length>0?n.expanded[e.view]=e.expanded.filter(t=>t in r):n.expanded[e.view]=e.expanded,n.searchQuery=e.searchQuery,this._persistFavoritesViewStateTimer&&clearTimeout(this._persistFavoritesViewStateTimer),this._persistFavoritesViewStateTimer=setTimeout(()=>{this._persistFavoritesViewStateTimer=null,_D(n)},250)}_subscribeDeviceRegistry(){!this._deviceRegistryUnsub&&this.hass?.connection&&(this._deviceRegistryUnsub=this.hass.connection.subscribeEvents(t=>this._onDeviceRegistryUpdated(t),"device_registry_updated"))}_onDeviceRegistryUpdated(t){this._refreshPanels();const e=function(t){if("object"!=typeof t||null===t||!("data"in t))return null;const{data:e}=t;if("object"!=typeof e||null===e)return null;if(!("action"in e)||"update"!==e.action)return null;if(!("device_id"in e)||"string"!=typeof e.device_id)return null;if(!("changes"in e))return null;const{changes:n}=e;return"object"!=typeof n||null===n?null:sD.some(t=>t in n)?e.device_id:null}(t);if(e){for(const[t,n]of this._renderedTopologies)lD(n,e)&&this._renamedPanelIds.add(t);this._renamedPanelIds.size>0&&this._renameRefresh()}}_unsubscribeDeviceRegistry(){this._deviceRegistryUnsub&&(this._deviceRegistryUnsub.then(t=>t()),this._deviceRegistryUnsub=null)}_subscribeEntryReloads(){!this._reloadSub&&this.hass?.connection&&(this._reloadSub=async function(t,e,n,{initialIsReseed:i}){const r=t.connection;if(!r)return async()=>{};const o=new Map;let a=!1;return r.subscribeMessage(t=>{if(t.every(t=>null===t.type)){const r=a||i;a=!0,o.clear();for(const{entry:i}of t)e(i)&&(o.set(i.entry_id,i.state),r&&i.state===cD&&n(i.entry_id));return}for(const{type:i,entry:r}of t){if(!e(r))continue;if("removed"===i){o.delete(r.entry_id);continue}const t=o.get(r.entry_id);o.set(r.entry_id,r.state),"updated"===i&&r.state===cD&&t!==cD&&n(r.entry_id)}},{type:"config_entries/subscribe",type_filter:["device"]})}(this.hass,t=>t.domain===s,t=>this._onEntryLoaded(t),{initialIsReseed:this._discovered}).catch(t=>(console.warn("SPAN Panel: config entry subscription failed",t),async()=>{})))}_unsubscribeEntryReloads(){const t=this._reloadSub;this._reloadSub=null,t?.then(t=>t())}_syncRatingSubscriptions(){const t=this.hass;if(!this.isConnected||!t?.connection)return;if(!function(t){return!0===t?.user?.is_admin}(t))return void this._unsubscribeRatingChanges();const e=new Set;for(const t of this._panels)t.id!==wD&&t.config_entry_id&&e.add(t.config_entry_id);for(const[t,n]of this._ratingSubs)e.has(t)||(this._ratingSubs.delete(t),n.then(t=>t()));for(const n of e)this._ratingSubs.has(n)||this._ratingSubs.set(n,hD(t,n,t=>this._onRatingChanged(n,t)).catch(t=>(console.warn("SPAN Panel: monitoring rating subscription failed",t),()=>{})))}_unsubscribeRatingChanges(){const t=[...this._ratingSubs.values()];this._ratingSubs.clear();for(const e of t)e.then(t=>t())}_onRatingChanged(t,e){const n=this._panels.find(e=>e.id!==wD&&e.config_entry_id===t);if(!n)return;this._dashboardTab.invalidateMonitoring(),this._listDashCtrl.monitoringCache.invalidate(),this._listDashCtrl.monitoringMultiCache.invalidate();if(!(this._isFavoritesView?this._renderedTopologies.has(n.id):n.id===this._selectedPanelId)||!this._isFavoritesView&&"adopted"===this._activeTab)return;const i=this._ratingChangedIds.has(n.id)?this._ratingChangedIds.get(n.id)??null:new Set;this._ratingChangedIds.set(n.id,function(t,e){return null===t||null===e?null:new Set([...t,...e])}(i,e));let r=this._ratingRefreshes.get(n.id);if(!r){const e=n.id;r=yD(()=>{const n=this._takeRatingChangedIds(e);return this._renderIfRestructured(e,e=>this._refreshOpenSidePanel(t,e,n))}),this._ratingRefreshes.set(e,r)}r()}_takeRatingChangedIds(t){const e=this._ratingChangedIds.has(t)?this._ratingChangedIds.get(t)??null:null;return this._ratingChangedIds.delete(t),e}_refreshOpenSidePanelAccess(t,e){const n=this._root.getElementById("tab-content"),i=this._panels.find(e=>e.id===t)?.config_entry_id;n&&i&&("dashboard"!==this._activeTab||this._isFavoritesView?this._listDashCtrl.refreshCircuitControlAccess(n,i,e):this._dashboardTab.refreshSidePanelControlAccess(i,e))}async _refreshOpenSidePanel(t,e,n){const i=this._root.getElementById("tab-content");i&&("dashboard"!==this._activeTab||this._isFavoritesView?await this._listDashCtrl.refreshCircuitSidePanel(i,t,e,n):await this._dashboardTab.refreshSidePanel(t,e,n))}_onEntryLoaded(t){const e=this._panels.find(e=>e.id!==wD&&e.config_entry_id===t);this._isFavoritesView||e&&e.id===this._selectedPanelId?e?(!this._isFavoritesView||this._renderedTopologies.has(e.id)||Sn(this._favorites,e.id))&&(this._isFavoritesView||"adopted"!==this._activeTab?this._renderIfRestructured(e.id):this._adoptedTab.refresh()):this._requestTabRender():this._requestPanelsRefresh()}async _renderIfRestructured(t,e){const n=this._renderedTopologies.get(t);if(!n||!this.hass)return void this._requestTabRender();let i;try{({topology:i}=await xi(this.hass,t,null))}catch(t){return void console.warn("SPAN Panel: topology refresh failed; keeping the current view:",Jt(t))}var r,o;this._renderedTopologies.get(t)===n&&(i&&this._refreshOpenSidePanelAccess(t,i),i&&e&&(await e(i),this._renderedTopologies.get(t)!==n)||i&&(r=i,null!==(o=n)&&IP(fD(r),fD(o)))||this._requestTabRender())}async _fetchBaselineTopology(){if(!this.hass||!this._selectedPanelId)return null;try{return(await xi(this.hass,this._selectedPanelId,null)).topology}catch(t){return console.warn("SPAN Panel: no topology baseline for this view:",Jt(t)),null}}_recordRenderedTopology(t){t&&this._selectedPanelId&&this._renderedTopologies.set(this._selectedPanelId,t)}_reapplyPanelStatusWatch(){if(this._isFavoritesView)return this._errorStore.watchPanelStatuses(this._favoritesWatchEntries),void(this.hass&&this._errorStore.updateHass(this.hass));this._updatePanelStatusWatch()}_subscribeAreaTab(){!this._areaSub&&this.hass&&(this._areaSub=async function(t,e,i,r){const o=t.connection;if(!o)return()=>{};const a=async()=>{const o=e();if(o)try{const e=new Map;for(const[t,n]of Object.entries(o.circuits))e.set(t,n.area);await yi(t,o);for(const[t,n]of Object.entries(o.circuits))if(n.area!==e.get(t))return void i()}catch(t){console.warn("[span-panel] area registry update failed:",t),r?.add({key:"fetch:areas",level:"warning",message:n("error.areas_failed"),persistent:!1})}},s=await Promise.all(_i.map(t=>o.subscribeEvents(a,t)));return()=>{for(const t of s)t()}}(this.hass,()=>this._areaTopology,()=>{"area"===this._activeTab&&this._scheduleTabRender()},this._errorStore).catch(t=>(console.warn("SPAN Panel: area subscription failed",t),this._errorStore.add({key:"subscribe:area",level:"warning",message:n("error.areas_failed"),persistent:!1}),()=>{})))}_unsubscribeAreaTab(){const t=this._areaSub;this._areaSub=null,t?.then(t=>t())}async _refreshPanels(){if(!this.hass||!this._discovered)return;const t=await dD(this.hass),e=this._panels.filter(t=>t.id!==wD),n=new Map(e.map(t=>[t.id,t])),i=new Set(t.map(t=>t.id)),r=n.size!==i.size||[...n.keys()].some(t=>!i.has(t)),o=!r&&t.some(t=>{const e=n.get(t.id);return!!e&&(e.name!==t.name||e.name_by_user!==t.name_by_user)});if((r||o)&&(this._panels=this._buildPanelList(t,this._favorites),!this._panels.some(t=>t.id===this._selectedPanelId)&&this._panels.length>0)){const e=t[0];e&&(this._selectedPanelId=e.id,localStorage.setItem("span_panel_selected",this._selectedPanelId))}}async _updatePanelStatusWatch(){if(!this.hass||!this._selectedPanelId)return;if(this._selectedPanelId===wD)return;if(this._watchedPanelId===this._selectedPanelId)return;const t=this._selectedPanelId;this._watchedPanelId=t;try{const e=new De(this._errorStore),n=await xi(this.hass,t,e);if(this._selectedPanelId!==t)return;const i=n.topology?.panel_entities?.panel_status;i&&(this._errorStore.watchPanelStatus(i),this._errorStore.updateHass(this.hass))}catch(e){console.warn("SPAN Panel: unable to fetch topology for panel status watching",e),this._watchedPanelId===t&&(this._watchedPanelId=null)}}async _discoverPanels(){if(!this._discovering&&this.hass){this._discovering=!0;try{let t;try{t=await dD(this.hass,new De(this._errorStore))}catch(t){return console.error("SPAN Panel: device discovery failed",t),void this._errorStore.add({key:"discovery-failed",level:"error",message:n("error.discovery_failed"),persistent:!0,retryFn:()=>{this._errorStore.remove("discovery-failed"),this._discoverPanels()}})}this._favorites=await this._loadFavorites(),this._panels=this._buildPanelList(t,this._favorites),this._favoritesViewState=function(){try{const t=localStorage.getItem(vD);if(!t)return{expanded:{activity:[],area:[]}};const e=JSON.parse(t);if(!e||"object"!=typeof e)return{expanded:{activity:[],area:[]}};const n=e.expanded??{activity:[],area:[]};return{activeTab:e.activeTab,expanded:{activity:Array.isArray(n.activity)?n.activity:[],area:Array.isArray(n.area)?n.area:[]},searchQuery:"string"==typeof e.searchQuery?e.searchQuery:void 0}}catch{return{expanded:{activity:[],area:[]}}}}(),this._discovered=!0;const e=localStorage.getItem("span_panel_selected");if(e&&this._panels.some(t=>t.id===e)?this._selectedPanelId=e:t.length>0&&(this._selectedPanelId=t[0].id),this._selectedPanelId===wD){const t=this._favoritesViewState.activeTab;"activity"===t||"area"===t||"monitoring"===t?this._activeTab=t:SD(this._activeTab)&&(this._activeTab="activity")}this._chartMetric=localStorage.getItem("span_panel_metric")||"power"}finally{this._discovering=!1}}}_buildPanelList(t,e){if(!wn(e))return t;return[{id:wD,name:n("panel.favorites"),model:"__favorites__"},...t]}async _loadFavorites(){return this.hass?this._favCache.fetch(this.hass):{}}async _refreshFavorites(){const t=++this._refreshSeq;this._favCache.invalidate();const e=await this._loadFavorites();if(t!==this._refreshSeq)return;const n=this._selectedPanelId===wD;this._favorites=e;const i=this._panels.filter(t=>t.id!==wD);if(this._panels=this._buildPanelList(i,e),n&&!wn(e)){!function(){try{localStorage.removeItem(vD)}catch{}}(),this._favoritesViewState={expanded:{activity:[],area:[]}};const t=i[0];t?(this._selectedPanelId=t.id,localStorage.setItem("span_panel_selected",t.id)):this._selectedPanelId=null}else this._isFavoritesView?this._scheduleTabRender():this._applyPanelFavorites()}_buildTabList(){const t=[];return this._isFavoritesView||t.push({id:"dashboard",label:n("tab.by_panel"),icon:"mdi:view-dashboard"}),t.push({id:"activity",label:n("tab.by_activity"),icon:"mdi:sort-descending"},{id:"area",label:n("tab.by_area"),icon:"mdi:home-group"},{id:"monitoring",label:n("tab.monitoring"),icon:"mdi:monitor-eye"}),this._isFavoritesView||!0!==this.hass?.user?.is_admin||t.push({id:"adopted",label:n("tab.adopted"),icon:"mdi:tune"}),t}_buildFavoritesSummaryHTML(t){return function(t,e){return`\n
    \n \n ${Di(e,{note:!1})}\n
    \n ${Li()}\n
    \n \n \n
    \n
    \n
    \n `}("current"===(this._chartMetric||"power"),an(t))}_buildFavoritesPanelStatsGridHTML(t,e,n){if(0===t.length)return"";const i=cn(e,ln);return`
    ${t.map(t=>`\n
    \n
    ${Ft(t.panelName||t.topology.device_name||"")}
    \n ${(t=>{const e=i.get(t);return e?_n(e):""})(t.panelDeviceId)}\n ${Ei(t.topology,n,t.panelDeviceId)}\n
    \n `).join("")}
    `}_updateFavoritesPanelStats(t,e){if(this.hass&&0!==this._favoritesPanelStats.length)for(const n of this._favoritesPanelStats){const i=t.querySelector(`.panel-stats[data-stats-panel-id="${Ui(n.panelDeviceId)}"]`);i&&wI(i,this.hass,n.topology,e,null)}}_buildDashboardConfig(){return{chart_metric:this._chartMetric,history_minutes:5,show_panel:!0,show_battery:!0,show_evse:!0,show_solar:!0}}async _scheduleTabRender(){await this.updateComplete,this._sidePanelOpen()?this._pendingTabRender=!0:await this._tabRenderScheduler()}_sidePanelOpen(){const t=this.shadowRoot?.getElementById("tab-content");return!!t?.querySelector("span-side-panel[open]")}async _renderTab(){const t=this._beginRender(),e=this._root.getElementById("tab-content"),n=this._renderedView,i={tab:this._activeTab,panelId:this._selectedPanelId},r=null!==e&&null!==n&&n.tab===i.tab&&n.panelId===i.panelId;if(this._dashboardTab.stop(),r||(this._monitoringTab.stop(),this._dropFavoritesMonitoring()),this._adoptedTab.stop(),this._listCtrl.stop(),this._listDashCtrl.stopIntervals(),this._favoritesPanelStats=[],this._renderedTopologies.clear(),e)if(this._renderedView=i,this._isFavoritesView)await this._renderFavoritesTab(e,t,r);else switch(this._listDashCtrl.clearFavoriteRefs(),this._listCtrl.setViewName(null),this._applyPanelFavorites(),this._activeTab){case"dashboard":{e.innerHTML="";const n=this._buildDashboardConfig(),i=this._panels.find(t=>t.id===this._selectedPanelId),r=i?.config_entry_id??null,o=await this._dashboardTab.render(e,this.hass,this._selectedPanelId??"",n,r);t()||this._recordRenderedTopology(o);break}case"activity":{e.innerHTML="";const n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null;try{const n=new De(this._errorStore),r=await xi(this.hass,this._selectedPanelId??void 0,n);if(t())return;const o=this._buildDashboardConfig();if(this._listDashCtrl.init(r.topology,o,this.hass,i),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,i),t())return;if(await this._listDashCtrl.fetchAndBuildHorizonMaps(),t())return;const a=r.topology?Ri(r.topology,o):"";if(this._listCtrl.setColumns(this._listColumns),this._listCtrl.renderActivityView(e,this.hass,r.topology,o,this._listDashCtrl.monitoringCache.status,a),await this._listDashCtrl.loadHistory(),t())return;this._listDashCtrl.updateDOM(e),this._listDashCtrl.startIntervals(e),this._recordRenderedTopology(r.topology)}catch(n){if(t())return;const i=document.createElement("p");i.style.color="var(--error-color)",i.textContent=Jt(n),e.appendChild(i)}break}case"area":{e.innerHTML="";const n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null;try{const n=new De(this._errorStore),r=await xi(this.hass,this._selectedPanelId??void 0,n);if(t())return;const o=this._buildDashboardConfig();if(this._listDashCtrl.init(r.topology,o,this.hass,i),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.monitoringCache.fetch(this.hass,i),t())return;if(await this._listDashCtrl.fetchAndBuildHorizonMaps(),t())return;const a=r.topology?Ri(r.topology,o):"";if(this._listCtrl.setColumns(this._listColumns),this._listCtrl.renderAreaView(e,this.hass,r.topology,o,this._listDashCtrl.monitoringCache.status,a),await this._listDashCtrl.loadHistory(),t())return;this._listDashCtrl.updateDOM(e),this._listDashCtrl.startIntervals(e),this._recordRenderedTopology(r.topology),this._areaTopology=r.topology,this.isConnected&&this._subscribeAreaTab()}catch(t){const n=document.createElement("p");n.style.color="var(--error-color)",n.textContent=Jt(t),e.appendChild(n)}break}case"monitoring":{r||(e.innerHTML="");const n=this._panels.find(t=>t.id===this._selectedPanelId),i=n?.config_entry_id??null,o=this._fetchBaselineTopology(),[,a]=await Promise.all([this._monitoringTab.render(e,this.hass,i??void 0,o),o]);t()||this._recordRenderedTopology(a);break}case"adopted":e.innerHTML="",await this._adoptedTab.render(e,this.hass,this._selectedPanelId??"")}}async _renderFavoritesTab(t,e,i){const r=i?this._shownFavoritesMonitoring(t):null;if(r||(this._dropFavoritesMonitoring(),t.innerHTML=""),!this.hass)return;const o=this._panels.filter(t=>t.id!==wD),a=await this._favCtrl.build(this.hass,this._favorites,o,this._errorStore);if(e())return;for(const t of a.perPanelStats)this._renderedTopologies.set(t.panelDeviceId,t.topology);const s=a.perPanelStats.map(t=>{const e=t.topology.panel_entities?.panel_status;return"string"==typeof e?{entityId:e,panelName:t.panelName}:null}).filter(t=>null!==t);this._favoritesWatchEntries=s,this._errorStore.watchPanelStatuses(s),this._errorStore.updateHass(this.hass);const l=new Map;for(const t of a.perPanelStats){const e=o.find(e=>e.id===t.panelDeviceId);l.set(t.panelDeviceId,{panelName:t.panelName,topology:t.topology,configEntryId:e?.config_entry_id??null})}this._listDashCtrl.setFavoritesPerPanelInfo(l);const c=a.topology,d=a.entryIds[0]??null,u=Object.keys(c.circuits).length>0,h=Object.keys(c.sub_devices??{}).length>0;if(!u&&!h){this._dropFavoritesMonitoring(),t.innerHTML="";const e=document.createElement("p");return e.style.color="var(--secondary-text-color)",e.style.padding="24px",e.textContent=n("list.no_results"),void t.appendChild(e)}if(this._listDashCtrl.setFavoriteRefs(c._favoriteRefs),this._listDashCtrl.setPanelFavorites(null),"monitoring"===this._activeTab){this._listCtrl.setViewName(null);const e=new Map;for(const t of l.values())t.configEntryId&&e.set(t.configEntryId,t.topology);return void await this._renderFavoritesMonitoring(t,a.entryIds,o,r,e)}const p=this._activeTab,f=new Set(Object.keys(c.circuits)),g=this._favoritesViewState.expanded[p].filter(t=>f.has(t));this._listCtrl.setViewName(p),this._listCtrl.setInitialExpansion(g),this._listCtrl.setInitialSearchQuery(this._favoritesViewState.searchQuery??""),this._listCtrl.setColumns(this._listColumns);const m=this._buildDashboardConfig();if(this._listDashCtrl.init(c,m,this.hass,d),this._listDashCtrl.powerHistory.clear(),await this._listDashCtrl.fetchAndBuildHorizonMaps(),e())return;const v=await this._listDashCtrl.fetchMergedMonitoringStatus(a.entryIds);if(!e()){this._favoritesPanelStats=a.perPanelStats;try{if(await this._listDashCtrl.loadHistory(),e())return;const n=this._buildFavoritesSummaryHTML(c),i=this._buildFavoritesPanelStatsGridHTML(a.perPanelStats,c,m),r=n+i+(h?`
    \n
    ${Ki(c,this.hass,m,{showFavorites:this._listDashCtrl.showFavorites})}
    \n
    `:"");"activity"===p?this._listCtrl.renderActivityView(t,this.hass,c,m,v,r):this._listCtrl.renderAreaView(t,this.hass,c,m,v,r),this._updateFavoritesPanelStats(t,m),this._listDashCtrl.setupResizeObserver(t,t),this._listDashCtrl.startIntervals(t,()=>{this._updateFavoritesPanelStats(t,m)})}catch(n){if(e())return;const i=document.createElement("p");i.style.color="var(--error-color)",i.textContent=Jt(n),t.appendChild(i)}}}async _renderFavoritesMonitoring(t,e,n,i,r){const o=this.hass;if(!o)return;const a=i??this._newFavoritesMonitoringStack(t);this._favoritesMonitoring=a;const s=new Map;for(const t of n){const e=t.config_entry_id;e&&s.set(e,t)}for(const[t,n]of a.blocks)e.includes(t)||(n.tab.stop(),n.block.remove(),a.blocks.delete(t));const l=this._detaches;for(const[t,n]of e.entries()){if(!this.isConnected)break;if(this._favoritesMonitoring!==a)return;const e=s.get(n),i=e?.name_by_user??e?.name??n,l=a.blocks.get(n)??this._newFavoritesMonitoringBlock();a.blocks.set(n,l),l.heading.textContent!==i&&(l.heading.textContent=i);const c=a.wrapper.children.item(t);c!==l.block&&a.wrapper.insertBefore(l.block,c);try{await l.tab.render(l.body,o,n,r.get(n)??null)}catch(t){console.warn("SPAN Panel: favorites monitoring render failed",n,t);const e=document.createElement("p");e.style.color="var(--error-color)",e.textContent=Jt(t),l.body.appendChild(e)}}this.isConnected&&this._detaches===l||this._renderWhenAttached()}_renderWhenAttached(){this.isConnected?this._requestTabRender():this._renderOnAttach=!0}_newFavoritesMonitoringStack(t){const e=document.createElement("div");return e.className="favorites-monitoring-stack",t.appendChild(e),{wrapper:e,blocks:new Map}}_newFavoritesMonitoringBlock(){const t=document.createElement("div");t.className="favorites-monitoring-block",t.style.marginBottom="24px";const e=document.createElement("h2");e.style.margin="8px 0 12px",e.style.fontSize="1em",t.appendChild(e);const n=document.createElement("div");t.appendChild(n);const i=new TP;return i.errorStore=this._errorStore,{tab:i,block:t,heading:e,body:n}}_shownFavoritesMonitoring(t){const e=this._favoritesMonitoring;return null!==e&&e.wrapper.parentElement===t?e:null}_stopFavoritesMonitoring(){for(const{tab:t}of this._favoritesMonitoring?.blocks.values()??[])t.stop()}_dropFavoritesMonitoring(){this._stopFavoritesMonitoring(),this._favoritesMonitoring=null}_applyPanelFavorites(){if(!this._selectedPanelId||this._isFavoritesView)return this._listDashCtrl.setPanelFavorites(null),void this._dashboardTab.setPanelFavorites(null);const t=this._favorites[this._selectedPanelId],e={panelDeviceId:this._selectedPanelId,circuitUuids:new Set(t?.circuits??[]),subDeviceIds:new Set(t?.sub_devices??[])};this._listDashCtrl.setPanelFavorites(e),this._dashboardTab.setPanelFavorites(e)}};CD._shellStyles=k` :host { color: var(--primary-text-color); } @@ -381,4 +430,4 @@ var Xl={},Yl={};var Zl,Kl=function(){function t(t,e,n){var i=this;this._sleepAft opacity: 1; border-bottom-color: var(--app-header-text-color, white); } - `,EP.styles=[PP._shellStyles,C(GA)],_([Lt({attribute:!1})],EP.prototype,"hass",void 0),_([Lt({type:Boolean,reflect:!0})],EP.prototype,"narrow",void 0),_([Et()],EP.prototype,"_panels",void 0),_([Et()],EP.prototype,"_selectedPanelId",void 0),_([Et()],EP.prototype,"_activeTab",void 0),_([Et()],EP.prototype,"_discovered",void 0),_([Et()],EP.prototype,"_chartMetric",void 0),_([Et()],EP.prototype,"_listColumns",void 0),_([Et()],EP.prototype,"_favorites",void 0),EP=PP=_([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})("span-panel")],EP),console.warn("%c SPAN-PANEL %c v0.11.0 ","background: var(--primary-color, #4dd9af); color: #000; font-weight: 700; padding: 2px 6px; border-radius: 4px 0 0 4px;","background: var(--secondary-background-color, #333); color: var(--primary-text-color, #fff); padding: 2px 6px; border-radius: 0 4px 4px 0;"); + `,CD.styles=[xD._shellStyles,C(DI)],_([Lt({attribute:!1})],CD.prototype,"hass",void 0),_([Lt({type:Boolean,reflect:!0})],CD.prototype,"narrow",void 0),_([Et()],CD.prototype,"_panels",void 0),_([Et()],CD.prototype,"_selectedPanelId",void 0),_([Et()],CD.prototype,"_activeTab",void 0),_([Et()],CD.prototype,"_discovered",void 0),_([Et()],CD.prototype,"_chartMetric",void 0),_([Et()],CD.prototype,"_listColumns",void 0),_([Et()],CD.prototype,"_favorites",void 0),CD=xD=_([(t=>(e,n)=>{void 0!==n?n.addInitializer(()=>{customElements.define(t,e)}):customElements.define(t,e)})("span-panel")],CD),console.warn("%c SPAN-PANEL %c v0.12.0 ","background: var(--primary-color, #4dd9af); color: #000; font-weight: 700; padding: 2px 6px; border-radius: 4px 0 0 4px;","background: var(--secondary-background-color, #333); color: var(--primary-text-color, #fff); padding: 2px 6px; border-radius: 0 4px 4px 0;");