mirror of
https://github.com/home-assistant/frontend.git
synced 2026-12-02 17:50:19 +00:00
Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
088640642c | ||
|
|
0819c80044 | ||
|
|
bb0c3bcd80 | ||
|
|
0f24280606 | ||
|
|
164cddaeb2 | ||
|
|
3fbd704245 | ||
|
|
f50a0a0e6c | ||
|
|
24ea197e34 | ||
|
|
84ecc939fa | ||
|
|
df40f11a14 | ||
|
|
14034dda2d | ||
|
|
47582923aa | ||
|
|
75555390a1 | ||
|
|
9e39b72de4 | ||
|
|
2ae815f1fd | ||
|
|
92045529e2 | ||
|
|
baaf5d1503 | ||
|
|
39b5f62cdb | ||
|
|
77f2230f9b | ||
|
|
2cab493aaa | ||
|
|
c024b4594a | ||
|
|
b76650cb55 | ||
|
|
eae1d81471 | ||
|
|
99b9f2593c | ||
|
|
43b6d8a0ea | ||
|
|
caccbf3c59 | ||
|
|
e5f408fca0 | ||
|
|
1c70897226 | ||
|
|
3a27de8e0a | ||
|
|
bc21f2903d | ||
|
|
b067ce5515 | ||
|
|
c95ed9f16c | ||
|
|
95eb2641e2 | ||
|
|
4cb23b772a | ||
|
|
0bf5da2e09 | ||
|
|
c12ad32797 | ||
|
|
2c03c2d74a | ||
|
|
2705e6da51 | ||
|
|
e3871d47de | ||
|
|
ead8c01926 | ||
|
|
258cb6f8b9 | ||
|
|
72057cf504 |
No files matched your search
@@ -1,43 +0,0 @@
|
||||
---
|
||||
name: ha-frontend-browser-checks
|
||||
description: Check a Home Assistant frontend change in a browser and show it in a pull request. Use when checking how a change looks or behaves at different screen sizes, in light and dark mode, right to left (RTL) or with long translations, or when taking before and after screenshots or recording a demo of a feature for a pull request.
|
||||
---
|
||||
|
||||
# HA Frontend Browser Checks
|
||||
|
||||
Use this skill to check a visible change in a browser and to show it in a pull request. Any browser tool you already have works if it can open a page, set its size, run a script in it, take screenshots and record video. Load `ha-frontend-testing` for the dev servers, and `ha-frontend-loading` for loading states.
|
||||
|
||||
Screenshots and recordings help reviewers see what changed, but they don't make a large change easy to review. [Keep pull requests small](https://contributors.home-assistant.io/start/pull-requests/#keep-it-small), and make sure you have reviewed and understood the change and can explain it, as the [AI policy](https://contributors.home-assistant.io/start/ai-policy/) asks.
|
||||
|
||||
## Check Real Devices
|
||||
|
||||
Check the sizes the change affects rather than one fixed size, such as a phone, a tablet in both orientations, a laptop and a large desktop monitor. Include a small phone. Take each device's viewport in CSS pixels, its pixel ratio and touch support from the device presets your tools have, rather than from memory, and check the page really has that size once it's set.
|
||||
|
||||
## Check Light And Dark
|
||||
|
||||
When the change can look different in light and dark mode, such as a colour, border, background or image, check it in both. Switch the colour scheme in your browser tool, with the profile's theme following it, or pick light and dark in the profile. A fix for one mode only needs that mode.
|
||||
|
||||
## Check Right To Left (RTL)
|
||||
|
||||
Check layout, alignment, icons and anything with a direction in RTL. In the app, set your profile language to one written right to left, then set it back: many components take their direction from the language, so setting the page to RTL in your browser tool leaves them left to right. The gallery's RTL toggle checks styling only.
|
||||
|
||||
## Check Long Text
|
||||
|
||||
When a change adds or changes text, check it in a language with long words or long translations too, so labels, descriptions and buttons don't overflow or wrap badly. When the new string isn't translated yet, try a rough translation to check its length.
|
||||
|
||||
## Show It In The Pull Request
|
||||
|
||||
- When the change alters something that exists already, capture the same screen on `dev` and on your branch, in the same state, and put them side by side. Only a new screen, with nothing before it, needs just the after.
|
||||
- Keep the size of every capture fixed, screenshots as well as videos. Set the page size before you capture and don't change it in between, and capture the same area each time, so the subject sits in the same place in before and after. For a card or other part of the page, work out a fixed area around it for each size you test, and use that same area on both branches.
|
||||
- Say which device, size or mode each capture shows.
|
||||
- Make the change easy to see: capture the part of the screen it affects rather than a whole page where it's a few pixels.
|
||||
- Save captures outside the repository, so they can't be committed by accident.
|
||||
- Keep personal details out: use demo data, such as the demo or the Demo integration, and mask anything else before you capture, such as names, addresses, IP and MAC addresses, hostnames, serial numbers and tokens. Check each capture before you attach it.
|
||||
|
||||
Record a video when it shows the change better than a still, such as an animation, a drag, a loading sequence (hold the loading state as "Checking It" in `ha-frontend-loading` shows) or a flow across several screens. Keep each video short and small: GitHub limits upload sizes, and reviewers have to watch it. You can record it yourself with the tools you have; it doesn't need a person.
|
||||
|
||||
- Use the recording tools at hand: your browser tool's recorder for a page, or a desktop screen recorder for a window, such as a phone emulator, so the device frame shows.
|
||||
- Don't resize, zoom or take screenshots while recording, which redraw the page at another size and make the video jump.
|
||||
- Check the whole recording before you attach it. For a short clip, look at a frame every second or half second, not only the first and last, since the page can jump to another size partway through. Record again if it does. Take stills from the same frames, so they match the video.
|
||||
- Keep the window drawn on a screen. A hidden or minimised window records only a frame every few seconds.
|
||||
- Label each video, such as **Before** and **After**, and say what it shows and how you set it up. Say what you didn't record and why.
|
||||
@@ -20,7 +20,7 @@ When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the body
|
||||
- Do not omit, reorder, or rewrite template sections.
|
||||
- Check the appropriate "Type of change" box based on the actual change.
|
||||
- Do not check checklist items on behalf of the user.
|
||||
- If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
|
||||
- If the PR includes UI changes, remind the user to add screenshots or a short video.
|
||||
- Explain what the change does for users, not only implementation details.
|
||||
- Use Markdown.
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ workflows:
|
||||
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
|
||||
'.github/workflows/codeql-analysis.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'github/codeql-action@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea'
|
||||
- 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066'
|
||||
'.github/workflows/copilot-setup-steps.yml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
@@ -29,7 +29,7 @@ workflows:
|
||||
- 'actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1'
|
||||
'.github/workflows/dependency-review.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec'
|
||||
- 'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294'
|
||||
- 'actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'
|
||||
'.github/workflows/design_deployment.yaml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
@@ -101,9 +101,9 @@ dependencies:
|
||||
commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
owner_id: 44036562
|
||||
repo_id: 197814629
|
||||
'actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec':
|
||||
ref: 'v5.0.1'
|
||||
commit: 'sha1-bbc44d14a204704ccc493733616cd1e93a0321ec'
|
||||
'actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294':
|
||||
ref: 'v5.0.0'
|
||||
commit: 'sha1-a1d282b36b6f3519aa1f3fc636f609c47dddb294'
|
||||
owner_id: 44036562
|
||||
repo_id: 476372928
|
||||
'actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333':
|
||||
@@ -151,9 +151,9 @@ dependencies:
|
||||
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
|
||||
owner_id: 7513068
|
||||
repo_id: 113918130
|
||||
'github/codeql-action@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea':
|
||||
ref: 'v4.39.4'
|
||||
commit: 'sha1-1bd86f2fdb4b86187fa4059f16f31a3202acc9ea'
|
||||
'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066':
|
||||
ref: 'v4.39.3'
|
||||
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
|
||||
owner_id: 9919
|
||||
repo_id: 259445878
|
||||
'home-assistant/[email protected]':
|
||||
|
||||
@@ -32,12 +32,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4
|
||||
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
languages: javascript-typescript
|
||||
build-mode: none
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@1bd86f2fdb4b86187fa4059f16f31a3202acc9ea # v4.39.4
|
||||
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
category: "/language:javascript-typescript"
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
contents: read # To compare the dependency graph between base and head
|
||||
steps:
|
||||
- name: Dependency review
|
||||
uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec # v5.0.1
|
||||
uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
|
||||
with:
|
||||
license-check: false # Covered by pnpm lint:licenses
|
||||
fail-on-severity: high
|
||||
|
||||
@@ -53,11 +53,10 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
|
||||
- `ha-frontend-ux-readiness`: UI/UX routing that complements frontend review for new user experiences.
|
||||
- `ha-frontend-gallery`: gallery pages, demos, sidebar structure, content, and verification.
|
||||
- `ha-frontend-demo`: standalone demo structure, configurations, navigation, shared stubs, and verification.
|
||||
- `ha-frontend-browser-checks`: checking a change in a browser at real device sizes, in light and dark mode, right to left (RTL) and with long translations, and screenshots and recorded demos for pull requests.
|
||||
|
||||
## Pull Requests
|
||||
|
||||
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
|
||||
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, remind the user to add screenshots or a short video.
|
||||
|
||||
## AI policy
|
||||
|
||||
|
||||
@@ -198,7 +198,10 @@ async function fetchTranslations(currentArtifact: Artifact | null) {
|
||||
console.log("Unpacking downloaded translations...");
|
||||
const zip = await jszip.loadAsync(downloadResponse.data as ArrayBuffer);
|
||||
await deleteCurrent;
|
||||
await extract({ input: await zip.file(/.*/)[0].async("uint8array") });
|
||||
const extractStream = zip.file(/.*/)[0].nodeStream().pipe(extract());
|
||||
await new Promise((resolve, reject) => {
|
||||
extractStream.on("close", resolve).on("error", reject);
|
||||
});
|
||||
|
||||
// Record the artifact only after successful extraction, so a failed fetch
|
||||
// is retried by the next build instead of being considered current.
|
||||
|
||||
@@ -69,6 +69,10 @@ async function copyMapPanel(staticDir) {
|
||||
npmPath("leaflet/dist/leaflet.css"),
|
||||
staticPath("images/leaflet/")
|
||||
);
|
||||
copyFileDir(
|
||||
npmPath("leaflet.markercluster/dist/MarkerCluster.css"),
|
||||
staticPath("images/leaflet/")
|
||||
);
|
||||
fs.copySync(
|
||||
npmPath("leaflet/dist/images"),
|
||||
staticPath("images/leaflet/images/")
|
||||
|
||||
@@ -25,7 +25,13 @@ const NOTICE_FILES = [path.join(NODE_MODULES, "echarts/NOTICE")];
|
||||
// that the new version's license still matches. The build will fail if
|
||||
// the pinned version is no longer installed.
|
||||
const LICENSE_OVERRIDES = [
|
||||
// No entries currently needed.
|
||||
{
|
||||
// type-fest ships two license files (MIT for code, CC0 for types).
|
||||
// We use the MIT license since that covers the bundled code.
|
||||
packageName: "type-fest",
|
||||
version: "5.10.0",
|
||||
licenseFile: "license-mit",
|
||||
},
|
||||
];
|
||||
|
||||
// Locate the directory of an installed package matching an exact version.
|
||||
|
||||
@@ -73,8 +73,7 @@ class HcLovelace extends LitElement {
|
||||
|
||||
if (index !== undefined) {
|
||||
const title = getPanelTitleFromUrlPath(
|
||||
this.hass.localize,
|
||||
this.hass.panels,
|
||||
this.hass,
|
||||
this.urlPath || "lovelace"
|
||||
);
|
||||
|
||||
|
||||
@@ -355,8 +355,7 @@ export class HcMain extends HassElement {
|
||||
|
||||
private _handleNewLovelaceConfig(lovelaceConfig: LovelaceConfig) {
|
||||
const title = getPanelTitleFromUrlPath(
|
||||
this.hass!.localize,
|
||||
this.hass!.panels,
|
||||
this.hass!,
|
||||
this._urlPath || "lovelace"
|
||||
);
|
||||
castContext.setApplicationState(title || "");
|
||||
|
||||
@@ -207,7 +207,6 @@ export class HaEmbedProvider extends LitElement {
|
||||
}));
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
fixed_cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
this._applyColorScheme();
|
||||
|
||||
@@ -120,12 +120,10 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_consumption: "sensor.gas_heat_pump",
|
||||
},
|
||||
],
|
||||
fixed_costs: [],
|
||||
};
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
fixed_cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
hass.mockWS("energy/validate", () => ({
|
||||
@@ -133,7 +131,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
device_consumption: prefs.device_consumption.map(() => []),
|
||||
device_consumption_water: prefs.device_consumption_water.map(() => []),
|
||||
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
|
||||
fixed_costs: prefs.fixed_costs.map(() => []),
|
||||
}));
|
||||
hass.mockWS(
|
||||
"energy/fossil_energy_consumption",
|
||||
|
||||
@@ -22,14 +22,6 @@ const baseRepository = {
|
||||
status: "default" as const,
|
||||
};
|
||||
|
||||
// The names of the connectivity of the demo repositories. Home Assistant
|
||||
// translates them, the mocked hass has no backend translations.
|
||||
export const marketplaceBackendTranslations = {
|
||||
"component.homeassistant.integration_connectivity.mqtt.name": "MQTT",
|
||||
"component.homeassistant.integration_connectivity.network.name":
|
||||
"Local network",
|
||||
};
|
||||
|
||||
const repositories: RepositoryBase[] = [
|
||||
{
|
||||
...baseRepository,
|
||||
@@ -40,7 +32,6 @@ const repositories: RepositoryBase[] = [
|
||||
description: "Watch camera streams with low latency through WebRTC.",
|
||||
authors: ["@AlexxIT"],
|
||||
domain: "webrtc",
|
||||
connectivity: ["network"],
|
||||
config_flow: true,
|
||||
available_version: "v3.6.1",
|
||||
downloads: 98000,
|
||||
@@ -77,7 +68,6 @@ const repositories: RepositoryBase[] = [
|
||||
description: "Use the cameras and events of a Frigate NVR.",
|
||||
authors: ["@blakeblackshear", "@dermotduffy", "@NickM-27"],
|
||||
domain: "frigate",
|
||||
connectivity: ["network", "mqtt"],
|
||||
config_flow: true,
|
||||
available_version: "v5.9.0",
|
||||
installed: true,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { LocalizeFunc } from "../../../src/common/translations/localize";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
import { connectivityBackendTranslations } from "./connectivity/fixtures";
|
||||
import { marketplaceBackendTranslations } from "./marketplace";
|
||||
|
||||
export const mockTranslations = (
|
||||
hass: MockHomeAssistant,
|
||||
@@ -21,11 +20,7 @@ export const mockTranslations = (
|
||||
// this merges on top of them.
|
||||
(localizePromise ?? Promise.resolve()).then(() =>
|
||||
hass.addTranslations(
|
||||
Object.assign(
|
||||
{},
|
||||
...Object.values(connectivityBackendTranslations),
|
||||
marketplaceBackendTranslations
|
||||
)
|
||||
Object.assign({}, ...Object.values(connectivityBackendTranslations))
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -1,8 +1,6 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { html, css, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import "../../../src/components/ha-switch";
|
||||
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
|
||||
import type { HomeAssistant } from "../../../src/types";
|
||||
import "./demo-card";
|
||||
import type { DemoCardConfig } from "./demo-card";
|
||||
@@ -16,16 +14,6 @@ class DemoCards extends LitElement {
|
||||
|
||||
@state() private _showConfig = false;
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
// Handles card actions like the app's action mixin
|
||||
this.addEventListener("hass-action", (ev) => {
|
||||
ev.stopPropagation();
|
||||
const node = (ev.composedPath()[0] as HTMLElement | undefined) ?? this;
|
||||
handleAction(node, this.hass, ev.detail.config, ev.detail.action);
|
||||
});
|
||||
}
|
||||
|
||||
render() {
|
||||
return html`
|
||||
<ha-demo-options>
|
||||
|
||||
@@ -22,27 +22,20 @@ export class DemoHaCircularSlider extends LitElement {
|
||||
@state()
|
||||
private changingHigh?: number;
|
||||
|
||||
// A handle that passes the other one pushes it along, like the slider does
|
||||
private _lowChanged(ev) {
|
||||
this.low = ev.detail.value;
|
||||
this.high = Math.max(this.high, this.low);
|
||||
}
|
||||
|
||||
private _lowChanging(ev) {
|
||||
const value = ev.detail.value;
|
||||
this.changingLow = value;
|
||||
this.changingHigh = value != null && value > this.high ? value : undefined;
|
||||
this.changingLow = ev.detail.value;
|
||||
}
|
||||
|
||||
private _highChanged(ev) {
|
||||
this.high = ev.detail.value;
|
||||
this.low = Math.min(this.low, this.high);
|
||||
}
|
||||
|
||||
private _highChanging(ev) {
|
||||
const value = ev.detail.value;
|
||||
this.changingHigh = value;
|
||||
this.changingLow = value != null && value < this.low ? value : undefined;
|
||||
this.changingHigh = ev.detail.value;
|
||||
}
|
||||
|
||||
private _currentChanged(ev) {
|
||||
|
||||
@@ -462,14 +462,6 @@ const SCHEMAS: {
|
||||
},
|
||||
},
|
||||
},
|
||||
select_search: {
|
||||
name: "Select (more than 12 options)",
|
||||
selector: {
|
||||
select: {
|
||||
options: Array.from({ length: 20 }, (_, i) => `Option ${i + 1}`),
|
||||
},
|
||||
},
|
||||
},
|
||||
select_disabled_list: {
|
||||
name: "Select disabled option",
|
||||
selector: {
|
||||
@@ -640,10 +632,6 @@ const SCHEMAS: {
|
||||
},
|
||||
language: { name: "Language", selector: { language: {} } },
|
||||
navigation: { name: "Navigation", selector: { navigation: {} } },
|
||||
ui_condition: {
|
||||
name: "Dashboard conditions",
|
||||
selector: { ui_condition: {} },
|
||||
},
|
||||
numeric_threshold: {
|
||||
name: "Numeric threshold",
|
||||
selector: { numeric_threshold: {} },
|
||||
|
||||
@@ -22,13 +22,6 @@ const ENTITIES = [
|
||||
friendly_name: "Bed Light",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "light.living_room_ceiling_accent_lights",
|
||||
state: "on",
|
||||
attributes: {
|
||||
friendly_name: "Living Room Ceiling Accent Lights",
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "person.paulus",
|
||||
state: "home",
|
||||
@@ -80,14 +73,6 @@ const CONFIGS = [
|
||||
entity: "person.paulus",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Long name",
|
||||
config: {
|
||||
type: "picture-entity",
|
||||
image: "/images/living_room.png",
|
||||
entity: "light.living_room_ceiling_accent_lights",
|
||||
},
|
||||
},
|
||||
{
|
||||
heading: "Hidden name",
|
||||
config: {
|
||||
|
||||
+40
-39
@@ -40,31 +40,31 @@
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "8.1.4",
|
||||
"@babel/runtime": "8.1.3",
|
||||
"@braintree/sanitize-url": "7.1.2",
|
||||
"@codemirror/autocomplete": "6.20.4",
|
||||
"@codemirror/commands": "6.11.2",
|
||||
"@codemirror/commands": "6.11.1",
|
||||
"@codemirror/lang-jinja": "6.0.1",
|
||||
"@codemirror/lang-python": "6.2.1",
|
||||
"@codemirror/lang-yaml": "6.1.3",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/lint": "6.9.8",
|
||||
"@codemirror/search": "6.7.3",
|
||||
"@codemirror/search": "6.7.2",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.44.2",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@date-fns/tz": "1.5.0",
|
||||
"@egjs/hammerjs": "2.0.17",
|
||||
"@formatjs/intl-datetimeformat": "8.2.2",
|
||||
"@formatjs/intl-displaynames": "8.0.5",
|
||||
"@formatjs/intl-durationformat": "0.13.2",
|
||||
"@formatjs/intl-getcanonicallocales": "3.4.2",
|
||||
"@formatjs/intl-listformat": "9.1.2",
|
||||
"@formatjs/intl-locale": "5.5.2",
|
||||
"@formatjs/intl-numberformat": "10.1.2",
|
||||
"@formatjs/intl-pluralrules": "7.1.2",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.5",
|
||||
"@formatjs/intl-datetimeformat": "8.0.3",
|
||||
"@formatjs/intl-displaynames": "8.0.3",
|
||||
"@formatjs/intl-durationformat": "0.13.0",
|
||||
"@formatjs/intl-getcanonicallocales": "3.4.0",
|
||||
"@formatjs/intl-listformat": "9.1.0",
|
||||
"@formatjs/intl-locale": "5.5.0",
|
||||
"@formatjs/intl-numberformat": "10.1.0",
|
||||
"@formatjs/intl-pluralrules": "7.1.0",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.3",
|
||||
"@home-assistant/webawesome": "3.14.0-ha.2",
|
||||
"@lezer/common": "1.5.7",
|
||||
"@lezer/common": "1.5.6",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
"@lit-labs/motion": "1.1.0",
|
||||
"@lit-labs/observers": "2.1.0",
|
||||
@@ -79,12 +79,12 @@
|
||||
"@swc/helpers": "0.5.24",
|
||||
"@tsparticles/engine": "4.5.4",
|
||||
"@tsparticles/preset-links": "4.5.4",
|
||||
"@versatiles/style": "9.1.3",
|
||||
"@versatiles/style": "9.1.0",
|
||||
"@vibrant/color": "4.0.4",
|
||||
"@vvo/tzdb": "6.208.0",
|
||||
"@vvo/tzdb": "6.204.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.11",
|
||||
"barcode-detector": "3.2.5",
|
||||
"cally": "0.10.1",
|
||||
"barcode-detector": "3.2.4",
|
||||
"cally": "0.9.2",
|
||||
"color-name": "2.1.1",
|
||||
"comlink": "4.4.2",
|
||||
"core-js": "3.51.0",
|
||||
@@ -102,15 +102,15 @@
|
||||
"hls.js": "1.7.4",
|
||||
"home-assistant-js-websocket": "9.9.0",
|
||||
"idb-keyval": "6.3.0",
|
||||
"intl-messageformat": "12.2.1",
|
||||
"intl-messageformat": "12.2.0",
|
||||
"js-yaml": "5.5.0",
|
||||
"leaflet": "1.9.4",
|
||||
"leaflet.markercluster": "2.0.0",
|
||||
"leaflet.markercluster": "1.5.3",
|
||||
"lit": "3.3.3",
|
||||
"lit-html": "3.3.3",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"marked": "18.3.0",
|
||||
"memoize-one": "7.0.0",
|
||||
"maplibre-gl": "6.19.0",
|
||||
"marked": "18.2.1",
|
||||
"memoize-one": "6.0.0",
|
||||
"nanoid": "6.0.2",
|
||||
"node-vibrant": "4.0.4",
|
||||
"object-hash": "3.0.0",
|
||||
@@ -136,25 +136,25 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ampproject/remapping": "2.3.0",
|
||||
"@babel/core": "8.1.4",
|
||||
"@babel/core": "8.1.3",
|
||||
"@babel/helper-compilation-targets": "8.0.7",
|
||||
"@babel/helper-define-polyfill-provider": "1.0.0",
|
||||
"@babel/plugin-transform-class-properties": "8.0.1",
|
||||
"@babel/plugin-transform-private-methods": "8.0.1",
|
||||
"@babel/plugin-transform-runtime": "8.1.2",
|
||||
"@babel/preset-env": "8.1.4",
|
||||
"@babel/preset-env": "8.0.7",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.23.1",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@gfx/zopfli": "1.0.15",
|
||||
"@home-assistant/components": "workspace:*",
|
||||
"@html-eslint/eslint-plugin": "0.69.0",
|
||||
"@html-eslint/eslint-plugin": "0.68.0",
|
||||
"@lokalise/node-api": "17.0.1",
|
||||
"@octokit/auth-oauth-device": "8.0.5",
|
||||
"@octokit/rest": "22.0.1",
|
||||
"@playwright/test": "1.65.1",
|
||||
"@rsdoctor/rspack-plugin": "1.6.5",
|
||||
"@rspack/core": "2.3.4",
|
||||
"@rspack/dev-server": "2.2.3",
|
||||
"@rspack/core": "2.3.3",
|
||||
"@rspack/dev-server": "2.2.2",
|
||||
"@types/babel__plugin-transform-runtime": "7.9.5",
|
||||
"@types/chromecast-caf-receiver": "7.0.1",
|
||||
"@types/chromecast-caf-sender": "1.0.11",
|
||||
@@ -162,22 +162,23 @@
|
||||
"@types/culori": "4.0.1",
|
||||
"@types/geojson": "7946.0.16",
|
||||
"@types/html-minifier-terser": "7.0.2",
|
||||
"@types/leaflet": "1.9.23",
|
||||
"@types/leaflet": "1.9.22",
|
||||
"@types/leaflet.markercluster": "1.5.6",
|
||||
"@types/lodash.merge": "4.6.9",
|
||||
"@types/node": "24.19.4",
|
||||
"@types/node": "24.19.2",
|
||||
"@types/qrcode": "1.5.6",
|
||||
"@types/sortablejs": "1.15.9",
|
||||
"@types/tar": "7.0.87",
|
||||
"@typescript/native": "npm:[email protected]",
|
||||
"@vitest/coverage-v8": "5.1.2",
|
||||
"@vitest/coverage-v8": "5.1.1",
|
||||
"babel-loader": "10.1.1",
|
||||
"babel-plugin-polyfill-corejs3": "1.0.0",
|
||||
"browserslist": "4.29.6",
|
||||
"browserslist-useragent-regexp": "4.1.4",
|
||||
"core-js-compat": "3.51.0",
|
||||
"del": "9.0.1",
|
||||
"eslint": "10.16.0",
|
||||
"eslint-config-prettier": "10.1.9",
|
||||
"eslint": "10.15.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-import-resolver-webpack": "0.13.11",
|
||||
"eslint-plugin-import-x": "4.18.1",
|
||||
"eslint-plugin-lit": "2.3.1",
|
||||
@@ -198,7 +199,7 @@
|
||||
"jszip": "3.10.2",
|
||||
"license-checker-rseidelsohn": "5.0.1",
|
||||
"lightningcss": "1.33.0",
|
||||
"lint-staged": "17.6.3",
|
||||
"lint-staged": "17.6.2",
|
||||
"lit-analyzer": "2.0.3",
|
||||
"lodash.merge": "4.6.2",
|
||||
"lodash.template": "4.18.1",
|
||||
@@ -209,19 +210,19 @@
|
||||
"rspack-manifest-plugin": "5.2.2",
|
||||
"serve": "14.2.8",
|
||||
"sinon": "22.1.0",
|
||||
"tar": "8.0.2",
|
||||
"tar": "7.5.23",
|
||||
"terser-webpack-plugin": "5.6.1",
|
||||
"ts-lit-plugin": "2.0.2",
|
||||
"typescript": "6.0.3",
|
||||
"typescript-eslint": "8.74.0",
|
||||
"vite": "8.4.0",
|
||||
"typescript-eslint": "8.73.0",
|
||||
"vite": "8.3.8",
|
||||
"vite-tsconfig-paths": "6.1.1",
|
||||
"vitest": "5.1.2",
|
||||
"vitest": "5.1.1",
|
||||
"webpack-stats-plugin": "1.1.3",
|
||||
"webpackbar": "7.0.0",
|
||||
"workbox-build": "7.4.1"
|
||||
},
|
||||
"packageManager": "[email protected]4.0",
|
||||
"packageManager": "[email protected]3.0",
|
||||
"volta": {
|
||||
"node": "24.22.3"
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@custom-elements-manifest/analyzer": "0.11.0",
|
||||
"@rslib/core": "1.1.0",
|
||||
"@rslib/core": "1.0.7",
|
||||
"lit": "3.3.3",
|
||||
"typescript": "6.0.3"
|
||||
}
|
||||
|
||||
Generated
+1232
-1304
File diff suppressed because it is too large.
Load diff
@@ -18,8 +18,6 @@ trustPolicyExclude:
|
||||
- [email protected]
|
||||
# Pre-release published without provenance, used by workbox-build
|
||||
- "@trickfilm400/[email protected]"
|
||||
# Published without the trusted-publisher record; provenance still from vvo/tzdb release.yml
|
||||
- "@vvo/[email protected]"
|
||||
|
||||
# Dependency build scripts are denied unless listed here with true
|
||||
allowBuilds:
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "home-assistant-frontend"
|
||||
version = "20261125.0"
|
||||
version = "20261125.4"
|
||||
license = "Apache-2.0"
|
||||
license-files = ["LICENSE*"]
|
||||
description = "The Home Assistant frontend"
|
||||
|
||||
+2
-2
@@ -126,9 +126,9 @@
|
||||
"matchPackageNames": ["echarts", "zrender"]
|
||||
},
|
||||
{
|
||||
"description": "Group formatjs monorepo packages",
|
||||
"description": "Group formatjs monorepo package",
|
||||
"groupName": "formatjs",
|
||||
"matchPackageNames": ["@formatjs/**", "intl-messageformat"]
|
||||
"matchPackageNames": ["@formatjs/**"]
|
||||
},
|
||||
{
|
||||
"description": "Group Playwright package and CI container updates",
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
|
||||
import type {
|
||||
ConditionContext,
|
||||
VisibilityCondition,
|
||||
} from "../../panels/lovelace/common/validate-condition";
|
||||
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
|
||||
import { ConditionEvaluatorController } from "../controllers/condition-evaluator-controller";
|
||||
import { dropInvalidConditions } from "./sanitize";
|
||||
|
||||
export interface VisibilitySubscription {
|
||||
/** Pass each new hass object so client-side conditions check again. */
|
||||
update(hass: HomeAssistant): void;
|
||||
/** Close the subscriptions. `onChange` is not called again. */
|
||||
unsubscribe(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live visibility of a list of dashboard visibility conditions, for code
|
||||
* without a Lit host, such as custom cards and plugins. Conditions core
|
||||
* evaluates are subscribed to; the rest are checked locally. Reports
|
||||
* `unknown` until core replies.
|
||||
*/
|
||||
export const subscribeVisibility = (
|
||||
hass: HomeAssistant,
|
||||
conditions: VisibilityCondition[],
|
||||
onChange: (result: ConditionEvaluation, error?: string) => void,
|
||||
context: ConditionContext = {}
|
||||
): VisibilitySubscription => {
|
||||
// The controller only needs a host to register with and to re-render.
|
||||
const host: ReactiveControllerHost = {
|
||||
addController: () => undefined,
|
||||
removeController: () => undefined,
|
||||
requestUpdate: () => undefined,
|
||||
updateComplete: Promise.resolve(true),
|
||||
};
|
||||
|
||||
let active = true;
|
||||
|
||||
const controller = new ConditionEvaluatorController(host, {
|
||||
resubscribeDelay: 0,
|
||||
onResult: (result, error) => {
|
||||
if (active) {
|
||||
onChange(result, error);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const sanitized = dropInvalidConditions(conditions);
|
||||
const { entity_id: entityId } = context;
|
||||
|
||||
// Core-evaluated conditions never see the context, so fold its entity in
|
||||
// first, as the dashboard mixin does.
|
||||
const validConditions = entityId
|
||||
? sanitized.map((condition) => addEntityToCondition(condition, entityId))
|
||||
: sanitized;
|
||||
const getContext = () => context;
|
||||
|
||||
controller.hostConnected();
|
||||
controller.observe(validConditions, hass, getContext);
|
||||
|
||||
return {
|
||||
update: (newHass) => {
|
||||
if (active) {
|
||||
controller.observe(validConditions, newHass, getContext);
|
||||
}
|
||||
},
|
||||
unsubscribe: () => {
|
||||
active = false;
|
||||
controller.hostDisconnected();
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -209,16 +209,6 @@ const formatDurationMinuteMem = memoizeOne((locale: FrontendLocaleData) =>
|
||||
})
|
||||
);
|
||||
|
||||
// Splits a value into whole units and whole sub-units, e.g. 1.15 h into 1 h
|
||||
// and 9 min. The value is converted to sub-units and rounded before flooring,
|
||||
// as floating point math puts many of them just below a whole number:
|
||||
// (1.15 - 1) * 60 is 8.999999999999995.
|
||||
const splitDuration = (value: number, subUnits: number): [number, number] => {
|
||||
const total = Math.floor(round(value * subUnits, 6));
|
||||
const units = Math.floor(total / subUnits);
|
||||
return [units, total - units * subUnits];
|
||||
};
|
||||
|
||||
export const formatDuration = (
|
||||
locale: FrontendLocaleData,
|
||||
duration: string,
|
||||
@@ -232,7 +222,8 @@ export const formatDuration = (
|
||||
|
||||
switch (unit) {
|
||||
case "d": {
|
||||
const [days, hours] = splitDuration(value, 24);
|
||||
const days = Math.floor(value);
|
||||
const hours = Math.floor((value - days) * 24);
|
||||
const input = {
|
||||
days,
|
||||
hours,
|
||||
@@ -240,7 +231,8 @@ export const formatDuration = (
|
||||
return formatDurationDayMem(locale)(input);
|
||||
}
|
||||
case "h": {
|
||||
const [hours, minutes] = splitDuration(value, 60);
|
||||
const hours = Math.floor(value);
|
||||
const minutes = Math.floor((value - hours) * 60);
|
||||
const input = {
|
||||
hours,
|
||||
minutes,
|
||||
@@ -248,7 +240,8 @@ export const formatDuration = (
|
||||
return formatDurationHourMem(locale)(input);
|
||||
}
|
||||
case "min": {
|
||||
const [minutes, seconds] = splitDuration(value, 60);
|
||||
const minutes = Math.floor(value);
|
||||
const seconds = Math.floor((value - minutes) * 60);
|
||||
const input = {
|
||||
minutes,
|
||||
seconds,
|
||||
|
||||
@@ -31,6 +31,8 @@ export const setupLeafletMap = async (
|
||||
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
|
||||
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
|
||||
|
||||
await import("leaflet.markercluster");
|
||||
|
||||
const map = Leaflet.map(mapElement, {
|
||||
minZoom: MAP_MIN_ZOOM,
|
||||
maxZoom: MAP_MAX_ZOOM,
|
||||
@@ -41,6 +43,14 @@ export const setupLeafletMap = async (
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
mapElement.parentNode.appendChild(style);
|
||||
|
||||
const markerClusterStyle = document.createElement("link");
|
||||
markerClusterStyle.setAttribute(
|
||||
"href",
|
||||
"/static/images/leaflet/MarkerCluster.css"
|
||||
);
|
||||
markerClusterStyle.setAttribute("rel", "stylesheet");
|
||||
mapElement.parentNode.appendChild(markerClusterStyle);
|
||||
|
||||
if (initialView) {
|
||||
map.setView(
|
||||
[initialView.latitude, initialView.longitude],
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { parseISO } from "date-fns";
|
||||
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
|
||||
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
|
||||
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
|
||||
@@ -15,7 +14,6 @@ import {
|
||||
getNumberFormatOptions,
|
||||
isNumericFromAttributes,
|
||||
} from "../number/format_number";
|
||||
import { isDate } from "../string/is_date";
|
||||
import { blankBeforeUnit } from "../translations/blank_before_unit";
|
||||
import type { LocalizeFunc } from "../translations/localize";
|
||||
import { computeDomain } from "./compute_domain";
|
||||
@@ -198,9 +196,7 @@ const computeStateToPartsFromEntityAttributes = (
|
||||
return [{ type: "value", value: value }];
|
||||
}
|
||||
|
||||
const isDateSensor = isSensorDomain && attributes.device_class === "date";
|
||||
|
||||
if (DATE_TIME_DOMAINS.has(domain) || isDateSensor) {
|
||||
if (DATE_TIME_DOMAINS.has(domain)) {
|
||||
// If trying to display an explicit state, need to parse the explicit state to `Date` then format.
|
||||
// Attributes aren't available, we have to use `state`.
|
||||
|
||||
@@ -221,15 +217,15 @@ const computeStateToPartsFromEntityAttributes = (
|
||||
];
|
||||
}
|
||||
if (components.length === 1) {
|
||||
if (isDate(state)) {
|
||||
// Parse and format date-only values in UTC to preserve the calendar day.
|
||||
if (state.includes("-")) {
|
||||
// Date only.
|
||||
return [
|
||||
{
|
||||
type: "value",
|
||||
value: formatDate(
|
||||
parseISO(`${state}T00:00:00Z`),
|
||||
{ ...locale, time_zone: TimeZone.server },
|
||||
{ ...config, time_zone: "UTC" }
|
||||
new Date(`${state}T00:00`),
|
||||
{ ...locale, time_zone: TimeZone.local },
|
||||
config
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import memoizeOne from "memoize-one";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { ensureArray } from "../array/ensure-array";
|
||||
import { computeDomain } from "./compute_domain";
|
||||
import { getEntityContext } from "./context/get_entity_context";
|
||||
import { getEntityIds } from "./get_entity_ids";
|
||||
|
||||
type EntityCategory = "none" | "config" | "diagnostic";
|
||||
|
||||
@@ -181,66 +179,3 @@ export const findFilteredEntities = (
|
||||
);
|
||||
return findEntities(Object.keys(sources.states), filterFuncs);
|
||||
};
|
||||
|
||||
export type EntityFinder = (
|
||||
states: HomeAssistant["states"],
|
||||
entities: HomeAssistant["entities"],
|
||||
devices: HomeAssistant["devices"],
|
||||
areas: HomeAssistant["areas"],
|
||||
floors: HomeAssistant["floors"]
|
||||
) => string[];
|
||||
|
||||
/**
|
||||
* Finds the same entities as `findFilteredEntities`, for repeated calls.
|
||||
* Of a state, the filters only read its device class, so everything else is
|
||||
* matched again only when the entity ids or the registries change.
|
||||
*/
|
||||
export const createEntityFinder = (filters: EntityFilter[]): EntityFinder => {
|
||||
const registryFilters = filters.map(
|
||||
({ device_class: _deviceClass, ...filter }) => filter
|
||||
);
|
||||
const deviceClasses = filters.map((filter) =>
|
||||
filter.device_class ? new Set(ensureArray(filter.device_class)) : undefined
|
||||
);
|
||||
let candidatesKey: unknown[] = [];
|
||||
let candidates: string[][] = [];
|
||||
|
||||
return memoizeOne<EntityFinder>(
|
||||
(states, entities, devices, areas, floors) => {
|
||||
const entityIds = getEntityIds(states);
|
||||
const key = [entityIds, entities, devices, areas, floors];
|
||||
if (key.some((value, i) => value !== candidatesKey[i])) {
|
||||
candidatesKey = key;
|
||||
candidates = registryFilters.map((filter) =>
|
||||
entityIds.filter(
|
||||
generateEntityFilter(
|
||||
states,
|
||||
entities,
|
||||
devices,
|
||||
areas,
|
||||
floors,
|
||||
filter
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const seen = new Set<string>();
|
||||
const results: string[] = [];
|
||||
candidates.forEach((candidateIds, i) => {
|
||||
const classes = deviceClasses[i];
|
||||
for (const entityId of candidateIds) {
|
||||
if (
|
||||
!seen.has(entityId) &&
|
||||
(!classes ||
|
||||
classes.has(states[entityId].attributes.device_class || "none"))
|
||||
) {
|
||||
seen.add(entityId);
|
||||
results.push(entityId);
|
||||
}
|
||||
}
|
||||
});
|
||||
return results;
|
||||
}
|
||||
);
|
||||
};
|
||||
@@ -1,22 +0,0 @@
|
||||
import type { HomeAssistant } from "../../types";
|
||||
|
||||
let lastStates: HomeAssistant["states"] | undefined;
|
||||
let lastEntityIds: string[] = [];
|
||||
|
||||
/**
|
||||
* Returns the ids of `states`, as the same array for as long as they stay the
|
||||
* same, so callers can memoize on it.
|
||||
*/
|
||||
export const getEntityIds = (states: HomeAssistant["states"]): string[] => {
|
||||
if (states !== lastStates) {
|
||||
lastStates = states;
|
||||
const entityIds = Object.keys(states);
|
||||
if (
|
||||
entityIds.length !== lastEntityIds.length ||
|
||||
entityIds.some((entityId, i) => entityId !== lastEntityIds[i])
|
||||
) {
|
||||
lastEntityIds = entityIds;
|
||||
}
|
||||
}
|
||||
return lastEntityIds;
|
||||
};
|
||||
@@ -1,12 +1,9 @@
|
||||
/// <reference types="leaflet.markercluster" />
|
||||
import type {
|
||||
CircleMarker,
|
||||
Control,
|
||||
DivIcon,
|
||||
Map,
|
||||
MarkerCluster,
|
||||
MarkerClusterGroup,
|
||||
MarkerClusterGroupOptions,
|
||||
Polyline,
|
||||
} from "leaflet";
|
||||
import type { LeafletModuleType } from "../../dom/setup-leaflet-map";
|
||||
@@ -39,18 +36,8 @@ interface HandledMarker extends DecoratedMarker {
|
||||
|
||||
interface LeafletMarkerHandle extends MapMarkerHandle {
|
||||
marker: HandledMarker;
|
||||
title?: string;
|
||||
}
|
||||
|
||||
// v2 option the 1.x types don't know yet
|
||||
interface ClusterGroupOptions extends MarkerClusterGroupOptions {
|
||||
clusterLabel?(cluster: MarkerCluster): string;
|
||||
}
|
||||
|
||||
// Stands in for getAnimations on browsers without it (Chrome before 84),
|
||||
// which markercluster calls whenever the map zooms
|
||||
const noAnimations = (): Animation[] => [];
|
||||
|
||||
/** The Leaflet engine: raster viewing fallback without WebGL2, no editing */
|
||||
export class LeafletMapEngine implements MapEngine {
|
||||
/** For the ha-map jsdom tests only */
|
||||
@@ -62,14 +49,10 @@ export class LeafletMapEngine implements MapEngine {
|
||||
|
||||
private _clusterable: HandledMarker[] = [];
|
||||
|
||||
private _MarkerClusterGroup?: typeof MarkerClusterGroup;
|
||||
|
||||
private _cluster?: MarkerClusterGroup;
|
||||
|
||||
private _clusterOptions: MapClusterOptions | null = null;
|
||||
|
||||
private _animateClusters = true;
|
||||
|
||||
private _scaleControl?: Control.Scale;
|
||||
|
||||
public async init(
|
||||
@@ -83,26 +66,22 @@ export class LeafletMapEngine implements MapEngine {
|
||||
// eslint-disable-next-line
|
||||
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
|
||||
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
|
||||
// The package's own types are for Leaflet 2; on our Leaflet 1.9,
|
||||
// @types/leaflet.markercluster describes it
|
||||
this._MarkerClusterGroup = (await import("leaflet.markercluster"))
|
||||
.MarkerClusterGroup as unknown as typeof MarkerClusterGroup;
|
||||
// Without a native getAnimations, markercluster can't cancel the
|
||||
// animations a zoom interrupts, so clusters don't animate there
|
||||
this._animateClusters =
|
||||
"getAnimations" in Element.prototype &&
|
||||
Element.prototype.getAnimations !== noAnimations;
|
||||
Element.prototype.getAnimations ??= noAnimations;
|
||||
await import("leaflet.markercluster");
|
||||
|
||||
const map = Leaflet.map(container, {
|
||||
minZoom: MAP_MIN_ZOOM,
|
||||
maxZoom: MAP_MAX_ZOOM,
|
||||
});
|
||||
map.attributionControl.setPrefix("");
|
||||
const style = document.createElement("link");
|
||||
style.setAttribute("href", "/static/images/leaflet/leaflet.css");
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
root.appendChild(style);
|
||||
for (const href of [
|
||||
"/static/images/leaflet/leaflet.css",
|
||||
"/static/images/leaflet/MarkerCluster.css",
|
||||
]) {
|
||||
const style = document.createElement("link");
|
||||
style.setAttribute("href", href);
|
||||
style.setAttribute("rel", "stylesheet");
|
||||
root.appendChild(style);
|
||||
}
|
||||
map.setView(options.center, options.zoom);
|
||||
|
||||
// The base layer adds itself; a vector layer may still fall back to raster
|
||||
@@ -278,7 +257,6 @@ export class LeafletMapEngine implements MapEngine {
|
||||
const handle: LeafletMarkerHandle = {
|
||||
marker,
|
||||
location,
|
||||
title: options.title,
|
||||
clusterData: options.clusterData,
|
||||
remove: () => {
|
||||
this._cluster?.removeLayer(marker);
|
||||
@@ -367,27 +345,18 @@ export class LeafletMapEngine implements MapEngine {
|
||||
this._cluster = undefined;
|
||||
}
|
||||
this._clusterOptions = options;
|
||||
|
||||
if (!this.leafletMap || !this.Leaflet || !this._MarkerClusterGroup) {
|
||||
if (!this.leafletMap || !this.Leaflet) {
|
||||
return;
|
||||
}
|
||||
if (!options) {
|
||||
this._clusterable.forEach((marker) => marker.addTo(this.leafletMap!));
|
||||
return;
|
||||
}
|
||||
|
||||
// markercluster groups by proximity only; groupKey is not supported here
|
||||
const clusterOptions: ClusterGroupOptions = {
|
||||
this._cluster = this.Leaflet.markerClusterGroup({
|
||||
showCoverageOnHover: false,
|
||||
removeOutsideVisibleBounds: false,
|
||||
animate: this._animateClusters,
|
||||
maxClusterRadius: options.radius,
|
||||
// The members' names, as the MapLibre engine labels its clusters
|
||||
clusterLabel: (cluster) =>
|
||||
(cluster.getAllChildMarkers() as HandledMarker[])
|
||||
.map((marker) => marker.engineHandle?.title)
|
||||
.filter(Boolean)
|
||||
.join(", "),
|
||||
iconCreateFunction: (cluster) => {
|
||||
const build = () => {
|
||||
const members = (cluster.getAllChildMarkers() as HandledMarker[]).map(
|
||||
@@ -428,9 +397,7 @@ export class LeafletMapEngine implements MapEngine {
|
||||
createShadow: () => null,
|
||||
} as unknown as DivIcon;
|
||||
},
|
||||
};
|
||||
|
||||
this._cluster = new this._MarkerClusterGroup(clusterOptions);
|
||||
});
|
||||
this._cluster.addLayers(this._clusterable);
|
||||
this.leafletMap!.addLayer(this._cluster!);
|
||||
}
|
||||
|
||||
@@ -849,9 +849,6 @@ export class MapLibreMapEngine implements MapEngine {
|
||||
if (!interactive) {
|
||||
// Leaflet lets input through non-interactive markers; MapLibre does not
|
||||
element.style.pointerEvents = "none";
|
||||
} else {
|
||||
// Leaflet points at what takes a click; MapLibre leaves the map's grab
|
||||
element.style.cursor = "pointer";
|
||||
}
|
||||
setMarkerAccessibility(element, options.title, focusable);
|
||||
element.style.zIndex = options.raised ? "1" : "";
|
||||
@@ -1049,8 +1046,6 @@ export class MapLibreMapEngine implements MapEngine {
|
||||
setMarkerAccessibility(centerEl, options.title, !!options.onClick);
|
||||
if (options.moveable) {
|
||||
centerEl.style.cursor = "move";
|
||||
} else if (options.onClick) {
|
||||
centerEl.style.cursor = "pointer";
|
||||
}
|
||||
this._placedElements.add(centerEl);
|
||||
const centerMarker = new maplibre.Marker({
|
||||
@@ -1655,7 +1650,6 @@ export class MapLibreMapEngine implements MapEngine {
|
||||
this._hideEmerging(members);
|
||||
};
|
||||
setMarkerAccessibility(icon.element, this._groupTitle(group), true);
|
||||
icon.element.style.cursor = "pointer";
|
||||
icon.element.addEventListener("click", (ev) => {
|
||||
ev.stopPropagation();
|
||||
zoomToMembers();
|
||||
|
||||
@@ -108,32 +108,9 @@ const addAtmosphere = (style: StyleSpecification): StyleSpecification => ({
|
||||
sky: { ...style.sky, "atmosphere-blend": ATMOSPHERE_BLEND },
|
||||
});
|
||||
|
||||
// MapLibre keeps the globe until it blends into mercator between zoom 11 and
|
||||
// 12, but unbuffered ocean polygons leave hairline gaps between tiles on it
|
||||
// from about zoom 6. Flatten it earlier, between zoom 5 and 6.
|
||||
const GLOBE_FLATTEN_ZOOM = 5;
|
||||
|
||||
const flattenGlobeEarly = (style: StyleSpecification): StyleSpecification =>
|
||||
style.projection?.type === "globe"
|
||||
? {
|
||||
...style,
|
||||
projection: {
|
||||
type: [
|
||||
"interpolate",
|
||||
["linear"],
|
||||
["zoom"],
|
||||
GLOBE_FLATTEN_ZOOM,
|
||||
"vertical-perspective",
|
||||
GLOBE_FLATTEN_ZOOM + 1,
|
||||
"mercator",
|
||||
],
|
||||
},
|
||||
}
|
||||
: style;
|
||||
|
||||
/** Everything a freshly built style needs before it is handed to MapLibre */
|
||||
export const finalizeMapStyle = (
|
||||
name: string,
|
||||
style: StyleSpecification
|
||||
): StyleSpecification =>
|
||||
flattenGlobeEarly(addAtmosphere(addLatinLabels(useTileJson(name, style))));
|
||||
addAtmosphere(addLatinLabels(useTileJson(name, style)));
|
||||
@@ -5,7 +5,6 @@ import type {
|
||||
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
|
||||
import type { FrontendLocaleData } from "../../data/translation";
|
||||
import { NumberFormat } from "../../data/translation";
|
||||
import { getLocaleDataVersion } from "../../resources/polyfills/locale-data-polyfill";
|
||||
import { blankBeforeUnit } from "../translations/blank_before_unit";
|
||||
|
||||
/**
|
||||
@@ -43,20 +42,11 @@ export const numberFormatToLocale = (
|
||||
// (locale, options) combinations is small and bounded in practice, so cache the
|
||||
// instances instead of rebuilding them on every call.
|
||||
const numberFormatCache = new Map<string, Intl.NumberFormat>();
|
||||
let numberFormatCacheVersion = getLocaleDataVersion();
|
||||
|
||||
const getNumberFormatter = (
|
||||
locale: string | string[] | undefined,
|
||||
options: Intl.NumberFormatOptions
|
||||
): Intl.NumberFormat => {
|
||||
// The Intl polyfill falls back to another locale while the data for the
|
||||
// requested one is still loading, e.g. right after a language change.
|
||||
// Start over when locale data is added, so the cache doesn't keep those.
|
||||
const version = getLocaleDataVersion();
|
||||
if (version !== numberFormatCacheVersion) {
|
||||
numberFormatCache.clear();
|
||||
numberFormatCacheVersion = version;
|
||||
}
|
||||
const key = JSON.stringify([locale, options]);
|
||||
let formatter = numberFormatCache.get(key);
|
||||
if (!formatter) {
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
// The filters of the Marketplace tables. Search, sorting and grouping are kept
|
||||
// by the data table, see data-table-query-params.
|
||||
export const marketplaceFilterQueryParamConfig = {
|
||||
list: ["status", "type", "source", "integration_category", "connectivity"],
|
||||
list: ["status", "type", "source", "integration_category"],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type MarketplaceFilterQueryParams = QueryParamValues<
|
||||
|
||||
@@ -37,29 +37,3 @@ export const preserveUnchangedRecord = <T>(
|
||||
}
|
||||
return changed ? next : previous;
|
||||
};
|
||||
|
||||
/**
|
||||
* List variant of {@link preserveUnchangedRecord}: replaces each item in `next`
|
||||
* with the equal `previous` item that has the same key, in place.
|
||||
*/
|
||||
export const preserveUnchangedItems = <T>(
|
||||
previous: readonly T[] | undefined,
|
||||
next: T[],
|
||||
getKey: (item: T) => string,
|
||||
equal: (a: T, b: T) => boolean
|
||||
): T[] => {
|
||||
if (!previous?.length) {
|
||||
return next;
|
||||
}
|
||||
const previousByKey = new Map<string, T>();
|
||||
for (const item of previous) {
|
||||
previousByKey.set(getKey(item), item);
|
||||
}
|
||||
for (let i = 0; i < next.length; i++) {
|
||||
const previousItem = previousByKey.get(getKey(next[i]));
|
||||
if (previousItem !== undefined && equal(previousItem, next[i])) {
|
||||
next[i] = previousItem;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
};
|
||||
@@ -273,7 +273,7 @@ export class HaCameraPlayer extends LitElement {
|
||||
const aspectRatio = this._aspectRatio();
|
||||
if (aspectRatio !== this._firedAspectRatio) {
|
||||
this._firedAspectRatio = aspectRatio;
|
||||
fireEvent(this, "media-size-changed", { aspectRatio });
|
||||
fireEvent(this, "camera-aspect-ratio-changed", { aspectRatio });
|
||||
}
|
||||
if (changedProps.has("keepAwake")) {
|
||||
if (this.keepAwake) {
|
||||
@@ -1338,7 +1338,6 @@ declare global {
|
||||
"ha-camera-player": HaCameraPlayer;
|
||||
}
|
||||
interface HASSDomEvents {
|
||||
/** The natural width limits the picture's width when it is set */
|
||||
"media-size-changed": { aspectRatio: number; naturalWidth?: number };
|
||||
"camera-aspect-ratio-changed": { aspectRatio: number };
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
import { differenceInMinutes } from "date-fns";
|
||||
import type {
|
||||
DataZoomComponentOption,
|
||||
GridComponentOption,
|
||||
MarkAreaComponentOption,
|
||||
} from "echarts/components";
|
||||
import type { EChartsType } from "echarts/core";
|
||||
@@ -28,7 +27,6 @@ import {
|
||||
eventOptions,
|
||||
property,
|
||||
query,
|
||||
queryAll,
|
||||
state,
|
||||
} from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
@@ -152,9 +150,6 @@ const processSeriesTooltipFormatter = (s: HaECSeriesItem): RawSeriesOption => {
|
||||
|
||||
export type CustomLegendOption = ECOption["legend"] & {
|
||||
type: "custom";
|
||||
// "y-axis" lists the items beside the chart, each one next to its category,
|
||||
// in place of the y-axis labels.
|
||||
position?: "bottom" | "y-axis";
|
||||
data?: {
|
||||
id?: string;
|
||||
secondaryIds?: string[]; // Other dataset IDs that should be controlled by this legend item.
|
||||
@@ -253,9 +248,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
@query(".chart") private _chartContainer?: HTMLDivElement;
|
||||
|
||||
@queryAll(".chart-legend button[data-id]")
|
||||
private _legendButtons!: NodeListOf<HTMLElement>;
|
||||
|
||||
@query(".sonification-output")
|
||||
private _sonificationOutput?: HTMLDivElement;
|
||||
|
||||
@@ -327,25 +319,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
},
|
||||
});
|
||||
|
||||
// The axis legend takes width from the chart without resizing the host
|
||||
private _chartResizeController = new ResizeController(this, {
|
||||
target: null,
|
||||
callback: (entries) => {
|
||||
const contentRect = entries[entries.length - 1]?.contentRect;
|
||||
if (
|
||||
this.chart &&
|
||||
contentRect &&
|
||||
(Math.round(contentRect.width) !== this.chart.getWidth() ||
|
||||
Math.round(contentRect.height) !== this.chart.getHeight())
|
||||
) {
|
||||
this._shouldResizeChart = true;
|
||||
this._resizeChartIfNeeded();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
private _focusedLegendButton?: { id: string; toggle: boolean };
|
||||
|
||||
private _loading = false;
|
||||
|
||||
private _reducedMotion = false;
|
||||
@@ -468,7 +441,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
if (!this.isConnected) {
|
||||
return;
|
||||
}
|
||||
this._chartResizeController.observe(this._chartContainer!);
|
||||
// The only measurement taken here: neither observer has reported yet, and a
|
||||
// chart first rendered inside a hidden container has to defer its setup
|
||||
// rather than build against a guessed width.
|
||||
@@ -517,16 +489,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
|
||||
public willUpdate(changedProps: PropertyValues): void {
|
||||
const focused = this.shadowRoot?.activeElement as HTMLElement | null;
|
||||
this._focusedLegendButton =
|
||||
focused?.dataset.id &&
|
||||
focused.closest(".chart-legend") &&
|
||||
focused.matches(":focus-visible")
|
||||
? {
|
||||
id: focused.dataset.id,
|
||||
toggle: focused.classList.contains("legend-toggle"),
|
||||
}
|
||||
: undefined;
|
||||
if (!this.chart) {
|
||||
return;
|
||||
}
|
||||
@@ -634,7 +596,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
this._resizeChartIfNeeded();
|
||||
}
|
||||
this._renderedLegendFit = this._legendFit.fit;
|
||||
this._restoreLegendFocus();
|
||||
if (changedProps.has("options") || changedProps.has("data")) {
|
||||
// New values keep the widest widths, but other items are fitted afresh
|
||||
const legendItemsKey = JSON.stringify(
|
||||
@@ -649,30 +610,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
}
|
||||
|
||||
// The legend reuses its buttons when items move, which would leave focus on
|
||||
// whichever item now sits where the focused one was
|
||||
private _restoreLegendFocus() {
|
||||
const focused = this._focusedLegendButton;
|
||||
const active = this.shadowRoot?.activeElement as HTMLElement | null;
|
||||
if (!focused || active?.dataset.id === focused.id) {
|
||||
return;
|
||||
}
|
||||
const className = focused.toggle ? "legend-toggle" : "label";
|
||||
Array.from(this._legendButtons)
|
||||
.find(
|
||||
(button) =>
|
||||
button.dataset.id === focused.id &&
|
||||
button.classList.contains(className)
|
||||
)
|
||||
?.focus();
|
||||
}
|
||||
|
||||
protected render() {
|
||||
const sonifiable =
|
||||
!this._sonificationUnavailable &&
|
||||
canSonifyChart(this.data, this._hiddenDatasets);
|
||||
const showZoomSlider = this._showZoomSlider();
|
||||
const axisLegend = this._hasAxisLegend();
|
||||
return html`
|
||||
<div
|
||||
class="container ${classMap({ "has-height": !!this.height })}"
|
||||
@@ -684,14 +626,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
})}
|
||||
>
|
||||
<div
|
||||
class="chart-container ${classMap({
|
||||
"has-axis-legend": axisLegend,
|
||||
})}"
|
||||
class="chart-container"
|
||||
style=${styleMap({
|
||||
height: this.height ? undefined : `${this._getDefaultHeight()}px`,
|
||||
})}
|
||||
>
|
||||
${axisLegend ? this._renderAxisLegend() : nothing}
|
||||
<div
|
||||
class="chart ${classMap({
|
||||
"touch-scrub": this._isTouchDevice && this._hasZoomableXAxis(),
|
||||
@@ -717,7 +656,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
${showZoomSlider ? this._renderZoomSlider() : nothing}
|
||||
</div>
|
||||
<div class="sonification-output"></div>
|
||||
${axisLegend ? nothing : this._renderLegend()}
|
||||
${this._renderLegend()}
|
||||
<div class="top-controls ${classMap({ small: this.smallControls })}">
|
||||
<slot name="search"></slot>
|
||||
<div
|
||||
@@ -744,22 +683,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
`;
|
||||
}
|
||||
|
||||
private _getCustomLegend() {
|
||||
if (!this.options?.legend) {
|
||||
private _getLegendItems() {
|
||||
if (!this.options?.legend || !this.data) {
|
||||
return undefined;
|
||||
}
|
||||
return ensureArray(this.options.legend).find(
|
||||
const legend = ensureArray(this.options.legend).find(
|
||||
(l) => l.show && l.type === "custom"
|
||||
) as CustomLegendOption | undefined;
|
||||
}
|
||||
|
||||
private _hasAxisLegend() {
|
||||
return this._getCustomLegend()?.position === "y-axis";
|
||||
}
|
||||
|
||||
private _getLegendItems() {
|
||||
const legend = this._getCustomLegend();
|
||||
if (!legend || !this.data) {
|
||||
if (!legend) {
|
||||
return undefined;
|
||||
}
|
||||
const datasets = ensureArray(this.data);
|
||||
@@ -776,6 +707,20 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
if (!items) {
|
||||
return nothing;
|
||||
}
|
||||
const datasets = ensureArray(this.data!);
|
||||
// Index datasets by id and name so each legend item is an O(1) lookup
|
||||
// instead of scanning every dataset twice. Charts can have many series.
|
||||
const datasetById = new Map<unknown, (typeof datasets)[number]>();
|
||||
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
|
||||
for (const dataset of datasets) {
|
||||
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
|
||||
datasetById.set(dataset.id, dataset);
|
||||
}
|
||||
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
|
||||
datasetByName.set(dataset.name, dataset);
|
||||
}
|
||||
}
|
||||
|
||||
const fit = this._legendFit.fit ?? items.length;
|
||||
return html`<div
|
||||
class=${classMap({
|
||||
@@ -784,7 +729,73 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
})}
|
||||
>
|
||||
<ul ${this._legendFit.target()}>
|
||||
${this._renderLegendItems(items, fit)}
|
||||
${items.map((item, index) => {
|
||||
let itemStyle: Record<string, any> = {};
|
||||
let value = "";
|
||||
let noLabelClick = false;
|
||||
const name = typeof item === "string" ? item : (item.name ?? "");
|
||||
let id: string;
|
||||
if (typeof item === "string") {
|
||||
id = item;
|
||||
} else {
|
||||
id = item.id ?? name;
|
||||
value = item.value ?? "";
|
||||
itemStyle = item.itemStyle ?? {};
|
||||
noLabelClick = item.noLabelClick ?? false;
|
||||
}
|
||||
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
|
||||
const dataset = datasetById.get(id) ?? datasetByName.get(id);
|
||||
itemStyle = {
|
||||
color: dataset?.color as string,
|
||||
...(dataset?.itemStyle as { borderColor?: string }),
|
||||
...itemStyle,
|
||||
};
|
||||
const color = itemStyle?.color as string;
|
||||
return html`<li
|
||||
.id=${id}
|
||||
@pointerdown=${this._legendPointerDown}
|
||||
@pointerup=${this._legendPointerCancel}
|
||||
@pointerleave=${this._legendPointerCancel}
|
||||
@pointercancel=${this._legendPointerCancel}
|
||||
@contextmenu=${this._legendContextMenu}
|
||||
class=${classMap({
|
||||
hidden: this._hiddenDatasets.has(id),
|
||||
overflow: !this.expandLegend && index >= fit,
|
||||
})}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="legend-toggle"
|
||||
data-id=${id}
|
||||
aria-pressed=${!this._hiddenDatasets.has(id)}
|
||||
.title=${this._i18n.localize(
|
||||
"ui.components.history_charts.toggle_visibility"
|
||||
)}
|
||||
@click=${this._toggleDataset}
|
||||
>
|
||||
<ha-svg-icon
|
||||
.path=${
|
||||
this._hiddenDatasets.has(id)
|
||||
? mdiCircleOutline
|
||||
: mdiCheckCircle
|
||||
}
|
||||
style=${styleMap({
|
||||
color: this._hiddenDatasets.has(id) ? undefined : color,
|
||||
})}
|
||||
></ha-svg-icon>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class=${classMap({ label: true, clickable: labelClickable })}
|
||||
data-id=${id}
|
||||
.title=${name}
|
||||
@click=${this._labelClick}
|
||||
>
|
||||
${name}
|
||||
</button>
|
||||
${value ? html`<div class="value">${value}</div>` : nothing}
|
||||
</li>`;
|
||||
})}
|
||||
${
|
||||
items.length
|
||||
? html`<li
|
||||
@@ -818,107 +829,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _renderAxisLegend() {
|
||||
const items = this._getLegendItems() ?? [];
|
||||
const grid = ensureArray(this._getGridOption()!)[0];
|
||||
return html`<div class="chart-legend axis-legend">
|
||||
<ul
|
||||
@pointerover=${this._axisLegendPointerOver}
|
||||
@pointerleave=${this._axisLegendPointerLeave}
|
||||
style=${styleMap({
|
||||
paddingTop: `${grid.top}px`,
|
||||
paddingBottom: `${grid.bottom}px`,
|
||||
})}
|
||||
>
|
||||
${this._renderLegendItems(items, items.length)}
|
||||
</ul>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _renderLegendItems(
|
||||
items: NonNullable<ReturnType<HaChartBase["_getLegendItems"]>>,
|
||||
fit: number
|
||||
) {
|
||||
const datasets = ensureArray(this.data!);
|
||||
// Index datasets by id and name so each legend item is an O(1) lookup
|
||||
// instead of scanning every dataset twice. Charts can have many series.
|
||||
const datasetById = new Map<unknown, (typeof datasets)[number]>();
|
||||
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
|
||||
for (const dataset of datasets) {
|
||||
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
|
||||
datasetById.set(dataset.id, dataset);
|
||||
}
|
||||
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
|
||||
datasetByName.set(dataset.name, dataset);
|
||||
}
|
||||
}
|
||||
return items.map((item, index) => {
|
||||
let itemStyle: Record<string, any> = {};
|
||||
let value = "";
|
||||
let noLabelClick = false;
|
||||
const name = typeof item === "string" ? item : (item.name ?? "");
|
||||
let id: string;
|
||||
if (typeof item === "string") {
|
||||
id = item;
|
||||
} else {
|
||||
id = item.id ?? name;
|
||||
value = item.value ?? "";
|
||||
itemStyle = item.itemStyle ?? {};
|
||||
noLabelClick = item.noLabelClick ?? false;
|
||||
}
|
||||
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
|
||||
const dataset = datasetById.get(id) ?? datasetByName.get(id);
|
||||
itemStyle = {
|
||||
color: dataset?.color as string,
|
||||
...(dataset?.itemStyle as { borderColor?: string }),
|
||||
...itemStyle,
|
||||
};
|
||||
const color = itemStyle?.color as string;
|
||||
return html`<li
|
||||
.id=${id}
|
||||
@pointerdown=${this._legendPointerDown}
|
||||
@pointerup=${this._legendPointerCancel}
|
||||
@pointerleave=${this._legendPointerCancel}
|
||||
@pointercancel=${this._legendPointerCancel}
|
||||
@contextmenu=${this._legendContextMenu}
|
||||
class=${classMap({
|
||||
hidden: this._hiddenDatasets.has(id),
|
||||
overflow: !this.expandLegend && index >= fit,
|
||||
})}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="legend-toggle"
|
||||
data-id=${id}
|
||||
aria-pressed=${!this._hiddenDatasets.has(id)}
|
||||
.title=${this._i18n.localize(
|
||||
"ui.components.history_charts.toggle_visibility"
|
||||
)}
|
||||
@click=${this._toggleDataset}
|
||||
>
|
||||
<ha-svg-icon
|
||||
.path=${
|
||||
this._hiddenDatasets.has(id) ? mdiCircleOutline : mdiCheckCircle
|
||||
}
|
||||
style=${styleMap({
|
||||
color: this._hiddenDatasets.has(id) ? undefined : color,
|
||||
})}
|
||||
></ha-svg-icon>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class=${classMap({ label: true, clickable: labelClickable })}
|
||||
data-id=${id}
|
||||
.title=${name}
|
||||
@click=${this._labelClick}
|
||||
>
|
||||
${name}
|
||||
</button>
|
||||
${value ? html`<div class="value">${value}</div>` : nothing}
|
||||
</li>`;
|
||||
});
|
||||
}
|
||||
|
||||
// Chart2Music adds ~45 kB gzipped, so it is only fetched once someone actually
|
||||
// moves keyboard focus into a chart.
|
||||
private async _handleChartFocus() {
|
||||
@@ -1399,28 +1309,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
private _getGridOption() {
|
||||
const grid = this.options?.grid;
|
||||
const axisLegend = this._hasAxisLegend();
|
||||
if (!axisLegend && (!grid || !this._zoomSliderRoom)) {
|
||||
if (!grid || !this._zoomSliderRoom) {
|
||||
return grid;
|
||||
}
|
||||
const [first, ...rest] = ensureArray(grid ?? {});
|
||||
const result: GridComponentOption = { ...first };
|
||||
if (axisLegend) {
|
||||
// The legend rows are laid out from these, so labels must not move them
|
||||
result.top = this._getGridTop();
|
||||
result.bottom = this._getGridBottom();
|
||||
result.containLabel = false;
|
||||
result.outerBoundsMode = "none";
|
||||
}
|
||||
if (this._zoomSliderRoom) {
|
||||
result.bottom = this._getGridBottom() + this._getZoomSliderSpace();
|
||||
}
|
||||
return [result, ...rest];
|
||||
}
|
||||
|
||||
private _getGridTop() {
|
||||
const top = this.options?.grid && ensureArray(this.options.grid)[0].top;
|
||||
return typeof top === "number" ? top : 0;
|
||||
const [first, ...rest] = ensureArray(grid);
|
||||
return [
|
||||
{ ...first, bottom: this._getGridBottom() + this._getZoomSliderSpace() },
|
||||
...rest,
|
||||
];
|
||||
}
|
||||
|
||||
private _getGridBottom() {
|
||||
@@ -1493,22 +1389,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
} as XAXisOption;
|
||||
});
|
||||
}
|
||||
let yAxis = this.options?.yAxis;
|
||||
if (this._hasAxisLegend()) {
|
||||
const [first, ...rest] = ensureArray(yAxis ?? {});
|
||||
yAxis = [
|
||||
{
|
||||
...first,
|
||||
type: "category",
|
||||
inverse: true,
|
||||
data: this._getLegendItems()?.map((item) =>
|
||||
typeof item === "string" ? item : (item.id ?? item.name)
|
||||
),
|
||||
axisLabel: { ...first.axisLabel, show: false },
|
||||
} as YAXisOption,
|
||||
...rest,
|
||||
];
|
||||
}
|
||||
let legend = this.options?.legend;
|
||||
if (legend) {
|
||||
legend = ensureArray(legend).map((l) =>
|
||||
@@ -1538,7 +1418,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
grid: this._getGridOption(),
|
||||
legend,
|
||||
xAxis,
|
||||
yAxis,
|
||||
};
|
||||
|
||||
if (options.tooltip) {
|
||||
@@ -2002,7 +1881,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
series.option.center = null;
|
||||
series.option.zoom = 1;
|
||||
});
|
||||
fireEvent(this, "chart-zoom-reset");
|
||||
}
|
||||
|
||||
private _getGraphRoams(): {
|
||||
@@ -2140,24 +2018,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
};
|
||||
|
||||
private _axisLegendPointerOver(ev: PointerEvent) {
|
||||
if (ev.pointerType !== "mouse" || !this.chart) {
|
||||
return;
|
||||
}
|
||||
const id = (ev.target as HTMLElement).closest("li")?.id;
|
||||
if (!id || this._hiddenDatasets.has(id)) {
|
||||
this._hideTooltip();
|
||||
return;
|
||||
}
|
||||
this.chart.dispatchAction({ type: "showTip", seriesIndex: 0, name: id });
|
||||
}
|
||||
|
||||
private _axisLegendPointerLeave(ev: PointerEvent) {
|
||||
if (ev.pointerType === "mouse") {
|
||||
this._hideTooltip();
|
||||
}
|
||||
}
|
||||
|
||||
private _hideTooltip() {
|
||||
this.chart?.dispatchAction({ type: "hideTip" });
|
||||
this.chart?.dispatchAction({
|
||||
@@ -2462,15 +2322,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
.has-height .chart-container {
|
||||
flex: 1;
|
||||
}
|
||||
.chart-container.has-axis-legend {
|
||||
display: flex;
|
||||
/* The chart is not mirrored in RTL, so its legend stays on the left */
|
||||
direction: ltr;
|
||||
}
|
||||
.has-axis-legend .chart {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.chart {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
@@ -2571,29 +2422,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
position: absolute;
|
||||
visibility: hidden;
|
||||
}
|
||||
.chart-legend.axis-legend {
|
||||
flex: none;
|
||||
max-width: min(200px, 40%);
|
||||
max-height: none;
|
||||
padding: 0;
|
||||
overflow: visible;
|
||||
direction: var(--direction);
|
||||
}
|
||||
.chart-legend.axis-legend ul {
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
flex-direction: column;
|
||||
flex-wrap: nowrap;
|
||||
align-items: stretch;
|
||||
gap: 0;
|
||||
}
|
||||
.chart-legend.axis-legend li,
|
||||
.chart-legend.axis-legend li:has(.legend-toggle) {
|
||||
flex: 1 1 0;
|
||||
height: auto;
|
||||
min-height: 0;
|
||||
max-width: none;
|
||||
}
|
||||
.chart-legend .hidden {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
@@ -2698,7 +2526,5 @@ declare global {
|
||||
};
|
||||
"chart-sankeyroam": { zoom: number };
|
||||
"chart-setup": undefined;
|
||||
// The user reset the zoom
|
||||
"chart-zoom-reset": undefined;
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,6 @@ import type {
|
||||
import { mdiFormatTextVariant, mdiGoogleCirclesGroup } from "@mdi/js";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import type { HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import { consumeLocalize } from "../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import { reducedMotionContext } from "../../data/context";
|
||||
@@ -130,25 +128,6 @@ export class HaNetworkGraph extends LitElement {
|
||||
*/
|
||||
@property({ attribute: false }) public selectedNode?: string;
|
||||
|
||||
/**
|
||||
* Highlight the neighbors of a node on hover and fade the rest.
|
||||
*/
|
||||
@property({ attribute: false }) public hoverFocus = true;
|
||||
|
||||
/**
|
||||
* Distance in pixels from the center of a node within which a click next to
|
||||
* it still clicks the node, so small nodes are easier to hit. 0 is off.
|
||||
* Such a click fires a `chart-click` with only `dataType` and `data.id`.
|
||||
*/
|
||||
@property({ attribute: false }) public nodeClickRadius = 0;
|
||||
|
||||
/**
|
||||
* Names of the legend categories that are switched off. Keep it up to date
|
||||
* with `network-legend-changed`, or leave it out to let the legend keep its
|
||||
* own selection.
|
||||
*/
|
||||
@property({ attribute: false }) public hiddenCategories?: string[];
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state() private _highlightedNodes?: Set<string>;
|
||||
@@ -183,8 +162,6 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
private _followedChart?: EChartsType;
|
||||
|
||||
private _cancelSettledHide?: () => void;
|
||||
|
||||
@query("ha-chart-base") private _baseChart?: HaChartBase;
|
||||
|
||||
constructor() {
|
||||
@@ -203,10 +180,6 @@ export class HaNetworkGraph extends LitElement {
|
||||
this._physicsEnabled =
|
||||
this.data.nodes.length <= PHYSICS_DISABLE_THRESHOLD;
|
||||
}
|
||||
// Before the first render, which counts the visible nodes
|
||||
if (changedProperties.has("hiddenCategories") && this.hiddenCategories) {
|
||||
this._hiddenCategories = this.hiddenCategories;
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
@@ -230,19 +203,14 @@ export class HaNetworkGraph extends LitElement {
|
||||
isMobile,
|
||||
hasHighlightedNodes,
|
||||
this.selectedNode,
|
||||
this.hoverFocus,
|
||||
this._nodePositions,
|
||||
this._pinnedNodes,
|
||||
this._fewVisibleNodes()
|
||||
)}
|
||||
.options=${this._createOptions(
|
||||
this.data?.categories,
|
||||
this.hiddenCategories
|
||||
)}
|
||||
.options=${this._createOptions(this.data?.categories)}
|
||||
height="100%"
|
||||
.extraComponents=${[GraphChart]}
|
||||
@chart-setup=${this._handleChartSetup}
|
||||
@chart-click=${this._handleBaseChartClick}
|
||||
>
|
||||
<slot name="search" slot="search"></slot>
|
||||
<slot name="button" slot="button"></slot>
|
||||
@@ -266,10 +234,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
|
||||
private _createOptions = memoizeOne(
|
||||
(
|
||||
categories?: NetworkData["categories"],
|
||||
hiddenCategories?: string[]
|
||||
): HaECOption => ({
|
||||
(categories?: NetworkData["categories"]): HaECOption => ({
|
||||
tooltip: {
|
||||
trigger: "item",
|
||||
confine: true,
|
||||
@@ -281,15 +246,6 @@ export class HaNetworkGraph extends LitElement {
|
||||
...category,
|
||||
icon: category.symbol,
|
||||
})),
|
||||
// Every category, as a category left out keeps its last selection
|
||||
...(hiddenCategories && {
|
||||
selected: Object.fromEntries(
|
||||
(categories ?? []).map((category) => [
|
||||
category.name,
|
||||
!hiddenCategories.includes(category.name),
|
||||
])
|
||||
),
|
||||
}),
|
||||
bottom: 8,
|
||||
},
|
||||
dataZoom: {
|
||||
@@ -355,7 +311,6 @@ export class HaNetworkGraph extends LitElement {
|
||||
isMobile: boolean,
|
||||
hasHighlightedNodes?: boolean,
|
||||
selectedNode?: string,
|
||||
hoverFocus = true,
|
||||
nodePositions: Record<string, { x: number; y: number }> = {},
|
||||
pinnedNodes: string[] = [],
|
||||
fewVisibleNodes = true
|
||||
@@ -390,11 +345,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
},
|
||||
},
|
||||
emphasis: {
|
||||
focus: hasHighlightedNodes
|
||||
? "self"
|
||||
: isMobile || !hoverFocus
|
||||
? "none"
|
||||
: "adjacency",
|
||||
focus: hasHighlightedNodes ? "self" : isMobile ? "none" : "adjacency",
|
||||
},
|
||||
force: {
|
||||
repulsion: [400, 600],
|
||||
@@ -619,23 +570,12 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
// Fired for every drawn frame, so the page can place things next to nodes
|
||||
// while the graph moves, and stays idle when it does not
|
||||
private _handleRendered = () => {
|
||||
fireEvent(this, "network-graph-rendered", undefined, {
|
||||
bubbles: false,
|
||||
composed: false,
|
||||
});
|
||||
};
|
||||
|
||||
private _handleChartSetup() {
|
||||
const chart = this._baseChart?.chart;
|
||||
chart?.getZr().on("click", this._handleEmptyClick);
|
||||
chart?.on("mousedown", this._handleNodeMouseDown);
|
||||
chart?.getZr().on("dragstart", this._handleDragStart);
|
||||
chart?.getZr().on("drag", this._handleDrag);
|
||||
chart?.getZr().on("dragend", this._handleDragEnd);
|
||||
chart?.on("rendered", this._handleRendered);
|
||||
for (const event of LEGEND_SELECT_EVENTS) {
|
||||
chart?.on(event, this._handleLegendChange);
|
||||
}
|
||||
@@ -648,22 +588,18 @@ export class HaNetworkGraph extends LitElement {
|
||||
// last render
|
||||
this.requestUpdate();
|
||||
this._updateFollowing();
|
||||
// The base chart drew the first frame before the listener was added
|
||||
this._handleRendered();
|
||||
}
|
||||
|
||||
private _handleLegendChange = (params: unknown) => {
|
||||
const { selected } = params as { selected: Record<string, boolean> };
|
||||
const fewVisibleNodes = this._fewVisibleNodes();
|
||||
this._setHiddenCategories(selected);
|
||||
this._setHiddenCategories(
|
||||
(params as { selected: Record<string, boolean> }).selected
|
||||
);
|
||||
if (this._fewVisibleNodes() !== fewVisibleNodes) {
|
||||
// The new series option lays out again from where the nodes are now
|
||||
this._saveNodePositions();
|
||||
this.requestUpdate();
|
||||
}
|
||||
fireEvent(this, "network-legend-changed", {
|
||||
hidden: this._hiddenCategories,
|
||||
});
|
||||
};
|
||||
|
||||
private _setHiddenCategories(selected: Record<string, boolean>) {
|
||||
@@ -672,65 +608,6 @@ export class HaNetworkGraph extends LitElement {
|
||||
);
|
||||
}
|
||||
|
||||
// A click next to a small node hits nothing, or a link that runs to its
|
||||
// center, so it clicks the nearest node within nodeClickRadius instead
|
||||
private _handleEmptyClick = (ev: {
|
||||
target?: unknown;
|
||||
offsetX: number;
|
||||
offsetY: number;
|
||||
}) => {
|
||||
if (!ev.target) {
|
||||
this._clickNearestNode(ev.offsetX, ev.offsetY);
|
||||
}
|
||||
};
|
||||
|
||||
// The base chart forwards a click on a link, which is replaced by the node
|
||||
// click, so the page gets one click
|
||||
private _handleBaseChartClick = (
|
||||
ev: HASSDomEvent<HASSDomEvents["chart-click"]>
|
||||
) => {
|
||||
const { dataType, event } = ev.detail;
|
||||
if (
|
||||
dataType === "edge" &&
|
||||
event &&
|
||||
this._clickNearestNode(event.offsetX, event.offsetY)
|
||||
) {
|
||||
ev.stopPropagation();
|
||||
}
|
||||
};
|
||||
|
||||
// Returns whether a node was clicked
|
||||
private _clickNearestNode(offsetX: number, offsetY: number): boolean {
|
||||
const chart = this._baseChart?.chart;
|
||||
if (!this.nodeClickRadius || !chart || chart.isDisposed()) {
|
||||
return false;
|
||||
}
|
||||
const series = this._getGraphSeries(chart);
|
||||
let nearest: { id: string; distance: number } | undefined;
|
||||
series?.getGraph().eachNode((node: any) => {
|
||||
const layout: number[] | undefined = node.getLayout();
|
||||
if (!layout) {
|
||||
return;
|
||||
}
|
||||
const [x, y] = chart.convertToPixel({ seriesId: "network" }, layout);
|
||||
const distance = Math.hypot(x - offsetX, y - offsetY);
|
||||
if (
|
||||
distance <= this.nodeClickRadius &&
|
||||
(!nearest || distance < nearest.distance)
|
||||
) {
|
||||
nearest = { id: node.id, distance };
|
||||
}
|
||||
});
|
||||
if (!nearest) {
|
||||
return false;
|
||||
}
|
||||
fireEvent(this, "chart-click", {
|
||||
dataType: "node",
|
||||
data: { id: nearest.id },
|
||||
} as unknown as HASSDomEvents["chart-click"]);
|
||||
return true;
|
||||
}
|
||||
|
||||
private _handleNodeMouseDown = (params: {
|
||||
dataType?: string;
|
||||
data?: unknown;
|
||||
@@ -858,62 +735,6 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The position of a node in pixels within the graph, or undefined when the
|
||||
* node is not drawn.
|
||||
*/
|
||||
public getNodePosition(id: string): { x: number; y: number } | undefined {
|
||||
const chart = this._baseChart?.chart;
|
||||
if (!chart || chart.isDisposed()) {
|
||||
return undefined;
|
||||
}
|
||||
const series = this._getGraphSeries(chart);
|
||||
const node = series?.getGraph().getNodeById(id);
|
||||
if (!node) {
|
||||
return undefined;
|
||||
}
|
||||
// The layout already holds where a moving node ends up, the drawn symbol
|
||||
// where it is now
|
||||
const transform: number[] | null | undefined = series
|
||||
.getData()
|
||||
.getItemGraphicEl(node.dataIndex)
|
||||
?.getComputedTransform();
|
||||
if (transform) {
|
||||
return { x: transform[4], y: transform[5] };
|
||||
}
|
||||
const position: number[] | undefined = node.getLayout();
|
||||
if (!position) {
|
||||
return undefined;
|
||||
}
|
||||
const [x, y] = chart.convertToPixel({ seriesId: "network" }, position);
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
public hideTooltip(): void {
|
||||
const chart = this._baseChart?.chart;
|
||||
if (!chart || chart.isDisposed()) {
|
||||
return;
|
||||
}
|
||||
chart.dispatchAction({ type: "hideTip" });
|
||||
this._cancelSettledHide?.();
|
||||
// A resize waits for running animations and shows the tooltip again, so
|
||||
// it is hidden once more when the chart has settled. Without a resize it
|
||||
// would hide the next tooltip, so moving the pointer cancels it.
|
||||
const zr = chart.getZr();
|
||||
const hideWhenSettled = () => {
|
||||
this._cancelSettledHide?.();
|
||||
chart.dispatchAction({ type: "hideTip" });
|
||||
};
|
||||
const cancel = () => {
|
||||
chart.off("finished", hideWhenSettled);
|
||||
zr.off("mousemove", cancel);
|
||||
this._cancelSettledHide = undefined;
|
||||
};
|
||||
chart.on("finished", hideWhenSettled);
|
||||
zr.on("mousemove", cancel);
|
||||
this._cancelSettledHide = cancel;
|
||||
}
|
||||
|
||||
private _centerOnSelectedNode = () => {
|
||||
const chart = this._followedChart;
|
||||
if (!chart) {
|
||||
@@ -1040,8 +861,5 @@ declare global {
|
||||
}
|
||||
interface HASSDomEvents {
|
||||
"node-selected": { id: string };
|
||||
// The names of the legend categories that are switched off
|
||||
"network-legend-changed": { hidden: string[] };
|
||||
"network-graph-rendered": undefined;
|
||||
}
|
||||
}
|
||||
@@ -328,11 +328,6 @@ export function generateStatisticsChartData(
|
||||
: undefined,
|
||||
color: chartType === "bar" ? backgroundColor : borderColor,
|
||||
};
|
||||
if (chartType === "bar") {
|
||||
// echarts sizes bars from the smallest gap between points, so sparse
|
||||
// data (one point, or points far apart) gets huge bars without a cap
|
||||
(series as BarSeriesOption).barMaxWidth = 50;
|
||||
}
|
||||
if (chartStacked) {
|
||||
series.stack = `band-stacked`;
|
||||
series.stackStrategy = "samesign";
|
||||
|
||||
@@ -327,7 +327,7 @@ export class HaCodeEditor extends ReactiveElement {
|
||||
transactions.push({
|
||||
effects: [
|
||||
this._loadedCodeMirror!.readonlyCompartment!.reconfigure(
|
||||
this._readOnlyExtensions()
|
||||
this._loadedCodeMirror!.EditorView!.editable.of(!this.readOnly)
|
||||
),
|
||||
this._loadedCodeMirror!.yamlLintCompartment!.reconfigure(
|
||||
this.lint && !this.readOnly
|
||||
@@ -452,7 +452,9 @@ export class HaCodeEditor extends ReactiveElement {
|
||||
this._loadedCodeMirror.haSyntaxHighlighting,
|
||||
this._loadedCodeMirror.yamlScalarHighlighter,
|
||||
this._loadedCodeMirror.yamlScalarHighlightStyle,
|
||||
this._loadedCodeMirror.readonlyCompartment.of(this._readOnlyExtensions()),
|
||||
this._loadedCodeMirror.readonlyCompartment.of(
|
||||
this._loadedCodeMirror.EditorView.editable.of(!this.readOnly)
|
||||
),
|
||||
this._loadedCodeMirror.linewrapCompartment.of(
|
||||
this.linewrap ? this._loadedCodeMirror.EditorView.lineWrapping : []
|
||||
),
|
||||
@@ -521,20 +523,6 @@ export class HaCodeEditor extends ReactiveElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _readOnlyExtensions(): Extension {
|
||||
const cm = this._loadedCodeMirror!;
|
||||
if (!this.readOnly) {
|
||||
return cm.EditorView.editable.of(true);
|
||||
}
|
||||
return [
|
||||
cm.EditorView.editable.of(false),
|
||||
// Keeps commands like Tab from changing the content once it has focus
|
||||
cm.EditorState.readOnly.of(true),
|
||||
// Focusable, so the content can be scrolled with the keyboard
|
||||
cm.EditorView.contentAttributes.of({ tabindex: "0" }),
|
||||
];
|
||||
}
|
||||
|
||||
private _fullscreenLabel(): string {
|
||||
if (this._isFullscreen) {
|
||||
return (
|
||||
@@ -1951,10 +1939,6 @@ export class HaCodeEditor extends ReactiveElement {
|
||||
padding-top: var(--code-editor-toolbar-height);
|
||||
}
|
||||
|
||||
:host(.fullscreen) {
|
||||
--code-mirror-min-height: 100%;
|
||||
}
|
||||
|
||||
:host(.fullscreen) .cm-editor {
|
||||
height: 100% !important;
|
||||
max-height: 100% !important;
|
||||
|
||||
@@ -111,11 +111,6 @@ export class HaControlCircularSlider extends LitElement {
|
||||
|
||||
@state() public _lastSlider?: ActiveSlider;
|
||||
|
||||
// Position of the other handle before the active one started pushing it
|
||||
private _lowBeforePush?: number;
|
||||
|
||||
private _highBeforePush?: number;
|
||||
|
||||
private _valueToPercentage(value: number) {
|
||||
return (
|
||||
(clamp(value, this.min, this.max) - this.min) / (this.max - this.min)
|
||||
@@ -127,31 +122,31 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _steppedValue(value: number) {
|
||||
// Rounding to the step can overshoot min/max when they aren't multiples of it
|
||||
return clamp(Math.round(value / this.step) * this.step, this.min, this.max);
|
||||
return Math.round(value / this.step) * this.step;
|
||||
}
|
||||
|
||||
private _boundedValue(value: number) {
|
||||
return Math.min(Math.max(value, this.min), this.max);
|
||||
const min =
|
||||
this._activeSlider === "high"
|
||||
? Math.min(this._localLow ?? this.max)
|
||||
: this.min;
|
||||
const max =
|
||||
this._activeSlider === "low"
|
||||
? Math.max(this._localHigh ?? this.min)
|
||||
: this.max;
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues): void {
|
||||
super.updated(changedProps);
|
||||
const activeValue = this._getActiveValue();
|
||||
if (
|
||||
this._activeSlider &&
|
||||
activeValue != null &&
|
||||
changedProps.has(this._activeSlider) &&
|
||||
this[this._activeSlider] !== this._lastChanging
|
||||
) {
|
||||
this._lastChanging = this._steppedValue(activeValue);
|
||||
fireEvent(this, `${this._activeSlider}-changing`, {
|
||||
value: this._lastChanging,
|
||||
});
|
||||
this._lastChanging = undefined;
|
||||
}
|
||||
if (!this._activeSlider) {
|
||||
this._lowBeforePush = undefined;
|
||||
this._highBeforePush = undefined;
|
||||
if (changedProps.has("value")) {
|
||||
this._localValue = this.value;
|
||||
}
|
||||
@@ -184,10 +179,6 @@ export class HaControlCircularSlider extends LitElement {
|
||||
|
||||
disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
this._destroyListeners();
|
||||
if (this._activeSlider) {
|
||||
this._cancelInteraction();
|
||||
}
|
||||
}
|
||||
|
||||
private _managers: HammerManager[] = [];
|
||||
@@ -235,19 +226,9 @@ export class HaControlCircularSlider extends LitElement {
|
||||
switch (this._activeSlider) {
|
||||
case "high":
|
||||
this._localHigh = value;
|
||||
// Push the low handle along instead of stopping at it, and let it
|
||||
// return to where it was if the drag comes back
|
||||
if (this._localLow != null) {
|
||||
this._lowBeforePush ??= this._localLow;
|
||||
this._localLow = Math.min(this._lowBeforePush, value);
|
||||
}
|
||||
break;
|
||||
case "low":
|
||||
this._localLow = value;
|
||||
if (this._localHigh != null) {
|
||||
this._highBeforePush ??= this._localHigh;
|
||||
this._localHigh = Math.max(this._highBeforePush, value);
|
||||
}
|
||||
break;
|
||||
case "value":
|
||||
this._localValue = value;
|
||||
@@ -267,18 +248,6 @@ export class HaControlCircularSlider extends LitElement {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private _cancelInteraction() {
|
||||
if (this._activeSlider) {
|
||||
fireEvent(this, `${this._activeSlider}-changing`, {
|
||||
value: undefined,
|
||||
});
|
||||
}
|
||||
this._activeSlider = undefined;
|
||||
this._localValue = this.value;
|
||||
this._localLow = this.low;
|
||||
this._localHigh = this.high;
|
||||
}
|
||||
|
||||
private _setupListeners() {
|
||||
if (this._interactions && this._managers.length === 0) {
|
||||
this._interactions.forEach((interaction) => {
|
||||
@@ -310,7 +279,15 @@ export class HaControlCircularSlider extends LitElement {
|
||||
mc.add(new Tap({ event: "singletap" }));
|
||||
|
||||
const cancelInteraction = () => {
|
||||
this._cancelInteraction();
|
||||
if (this._activeSlider) {
|
||||
fireEvent(this, `${this._activeSlider}-changing`, {
|
||||
value: undefined,
|
||||
});
|
||||
}
|
||||
this._activeSlider = undefined;
|
||||
this._localValue = this.value;
|
||||
this._localLow = this.low;
|
||||
this._localHigh = this.high;
|
||||
if (pressToActivate) {
|
||||
panRecognizer.set({ enable: false });
|
||||
}
|
||||
|
||||
@@ -73,15 +73,6 @@ export class HaDropdown extends Dropdown {
|
||||
// @ts-ignore
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
private override async showMenu() {
|
||||
// Flip away from the safe areas instead of opening into them, where the
|
||||
// max-height below would squeeze the menu.
|
||||
const styles = getComputedStyle(this);
|
||||
// @ts-ignore flipPadding is typed as a number, floating-ui accepts sides
|
||||
this.popup.flipPadding = {
|
||||
top: parseFloat(styles.getPropertyValue("--safe-area-inset-top")) || 0,
|
||||
bottom:
|
||||
parseFloat(styles.getPropertyValue("--safe-area-inset-bottom")) || 0,
|
||||
};
|
||||
// @ts-ignore
|
||||
await super.showMenu();
|
||||
const triggerElement = this.getTrigger();
|
||||
|
||||
@@ -83,7 +83,6 @@ const SELECTOR_FALLBACK_VALUES = {
|
||||
ui_action: undefined,
|
||||
ui_clock_date_format: undefined,
|
||||
ui_color: undefined,
|
||||
ui_condition: undefined,
|
||||
ui_state_content: undefined,
|
||||
ui_time_format: undefined,
|
||||
unit_of_measurement: undefined,
|
||||
|
||||
@@ -118,7 +118,6 @@ const SELECTOR_INITIAL_VALUES = {
|
||||
ui_action: undefined,
|
||||
ui_clock_date_format: undefined,
|
||||
ui_color: undefined,
|
||||
ui_condition: () => [],
|
||||
ui_state_content: undefined,
|
||||
ui_time_format: undefined,
|
||||
unit_of_measurement: undefined,
|
||||
|
||||
@@ -45,7 +45,7 @@ function adjustRgb(
|
||||
if (wv != null) {
|
||||
return rgbw2rgb([...rgb, wv] as [number, number, number, number]);
|
||||
}
|
||||
if (cw != null && ww != null) {
|
||||
if (cw != null && ww !== null) {
|
||||
return rgbww2rgb(
|
||||
[...rgb, cw, ww] as [number, number, number, number, number],
|
||||
minKelvin,
|
||||
|
||||
@@ -1,23 +1,17 @@
|
||||
import { mdiDelete, mdiPlayBox, mdiPlus } from "@mdi/js";
|
||||
import type { HassEntities } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { transform } from "../common/decorators/transform";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { statesContext } from "../data/context";
|
||||
import type { MediaPickedEvent } from "../data/media-player";
|
||||
import {
|
||||
MediaClassBrowserSettings,
|
||||
MediaPlayerEntityFeature,
|
||||
} from "../data/media-player";
|
||||
import type { MediaSelector, MediaSelectorValue } from "../data/selector";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import "./ha-alert";
|
||||
import "./ha-form/ha-form";
|
||||
import type { SchemaUnion } from "./ha-form/types";
|
||||
@@ -37,6 +31,8 @@ const EMPTY_FORM = {};
|
||||
|
||||
@customElement("ha-media-item-picker")
|
||||
export class HaMediaItemPicker extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public selector!: MediaSelector;
|
||||
|
||||
@property({ attribute: false }) public value?: MediaSelectorValue;
|
||||
@@ -55,26 +51,6 @@ export class HaMediaItemPicker extends LitElement {
|
||||
filter_entity?: string | string[];
|
||||
};
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
@transform<HassEntities | null, boolean>({
|
||||
transformer: function (this: HaMediaItemPicker, states) {
|
||||
const entityId = this._getActiveEntityId();
|
||||
if (!entityId) {
|
||||
return true;
|
||||
}
|
||||
const stateObj = states?.[entityId];
|
||||
return (
|
||||
!!stateObj &&
|
||||
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA)
|
||||
);
|
||||
},
|
||||
watch: ["value", "context"],
|
||||
})
|
||||
private _supportsBrowse?: boolean;
|
||||
|
||||
private _contextEntities: string[] | undefined;
|
||||
|
||||
private get _hasAccept(): boolean {
|
||||
@@ -92,6 +68,13 @@ export class HaMediaItemPicker extends LitElement {
|
||||
protected render() {
|
||||
const entityId = this._getActiveEntityId();
|
||||
|
||||
const stateObj = entityId ? this.hass.states[entityId] : undefined;
|
||||
|
||||
const supportsBrowse =
|
||||
!entityId ||
|
||||
(stateObj &&
|
||||
supportsFeature(stateObj, MediaPlayerEntityFeature.BROWSE_MEDIA));
|
||||
|
||||
if (this.selector.media?.image_upload && !this.value) {
|
||||
return html`${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
<ha-picture-upload
|
||||
@@ -115,7 +98,7 @@ export class HaMediaItemPicker extends LitElement {
|
||||
.value=${entityId}
|
||||
.label=${
|
||||
this.label ||
|
||||
this._localize(
|
||||
this.hass.localize(
|
||||
"ui.components.selectors.media.pick_media_player"
|
||||
)
|
||||
}
|
||||
@@ -131,19 +114,20 @@ export class HaMediaItemPicker extends LitElement {
|
||||
`
|
||||
}
|
||||
${
|
||||
this._supportsBrowse === false
|
||||
!supportsBrowse
|
||||
? html`
|
||||
${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
<ha-alert>
|
||||
${this._localize(
|
||||
${this.hass.localize(
|
||||
"ui.components.selectors.media.browse_not_supported"
|
||||
)}
|
||||
</ha-alert>
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.data=${this.value || EMPTY_FORM}
|
||||
.schema=${MANUAL_SCHEMA}
|
||||
.computeLabel=${this._computeLabel(this._localize)}
|
||||
.computeHelper=${this._computeHelper(this._localize)}
|
||||
.computeLabel=${this._computeLabelCallback}
|
||||
.computeHelper=${this._computeHelperCallback}
|
||||
></ha-form>
|
||||
`
|
||||
: html`${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
@@ -153,7 +137,9 @@ export class HaMediaItemPicker extends LitElement {
|
||||
role="button"
|
||||
aria-label=${
|
||||
!this.value?.media_content_id
|
||||
? this._localize("ui.components.selectors.media.pick_media")
|
||||
? this.hass.localize(
|
||||
"ui.components.selectors.media.pick_media"
|
||||
)
|
||||
: this.value.metadata?.title || this.value.media_content_id
|
||||
}
|
||||
@click=${this._pickMedia}
|
||||
@@ -210,7 +196,7 @@ export class HaMediaItemPicker extends LitElement {
|
||||
<div class="title">
|
||||
${
|
||||
!this.value?.media_content_id
|
||||
? this._localize(
|
||||
? this.hass.localize(
|
||||
"ui.components.selectors.media.pick_media"
|
||||
)
|
||||
: this.value.metadata?.title ||
|
||||
@@ -223,7 +209,7 @@ export class HaMediaItemPicker extends LitElement {
|
||||
: html`
|
||||
<div class="delete">
|
||||
<ha-icon-button
|
||||
.label=${this._localize("ui.common.delete")}
|
||||
.label=${this.hass.localize("ui.common.delete")}
|
||||
.path=${mdiDelete}
|
||||
@click=${this._clearValue}
|
||||
></ha-icon-button>
|
||||
@@ -241,7 +227,7 @@ export class HaMediaItemPicker extends LitElement {
|
||||
variant="danger"
|
||||
@click=${this._clearValue}
|
||||
>
|
||||
${this._localize(
|
||||
${this.hass.localize(
|
||||
"ui.components.picture-upload.clear_picture"
|
||||
)}
|
||||
</ha-button>
|
||||
@@ -257,17 +243,15 @@ export class HaMediaItemPicker extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _computeLabel = memoizeOne(
|
||||
(localize: LocalizeFunc) =>
|
||||
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
|
||||
localize(`ui.components.selectors.media.${schema.name}`)
|
||||
);
|
||||
private _computeLabelCallback = (
|
||||
schema: SchemaUnion<typeof MANUAL_SCHEMA>
|
||||
): string =>
|
||||
this.hass.localize(`ui.components.selectors.media.${schema.name}`);
|
||||
|
||||
private _computeHelper = memoizeOne(
|
||||
(localize: LocalizeFunc) =>
|
||||
(schema: SchemaUnion<typeof MANUAL_SCHEMA>): string =>
|
||||
localize(`ui.components.selectors.media.${schema.name}_detail`)
|
||||
);
|
||||
private _computeHelperCallback = (
|
||||
schema: SchemaUnion<typeof MANUAL_SCHEMA>
|
||||
): string =>
|
||||
this.hass.localize(`ui.components.selectors.media.${schema.name}_detail`);
|
||||
|
||||
private _entityChanged(ev: CustomEvent) {
|
||||
ev.stopPropagation();
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import { mdiMagnify, mdiMapSearchOutline } from "@mdi/js";
|
||||
import type { HassConfig } from "home-assistant-js-websocket";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { transform } from "../../common/decorators/transform";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../common/translations/localize";
|
||||
import { configContext, internationalizationContext } from "../../data/context";
|
||||
import type {
|
||||
LocationSelector,
|
||||
LocationSelectorValue,
|
||||
@@ -18,10 +14,7 @@ import {
|
||||
formatOpenStreetMapPlace,
|
||||
searchPlaces,
|
||||
} from "../../data/openstreetmap";
|
||||
import type {
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantInternationalization,
|
||||
} from "../../types";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { SchemaUnion } from "../ha-form/types";
|
||||
import type { HaListItemButton } from "../item/ha-list-item-button";
|
||||
import { searchResultsStatus } from "../list/search-results-status";
|
||||
@@ -35,7 +28,6 @@ import "../ha-alert";
|
||||
import "../ha-icon-button";
|
||||
import "../item/ha-list-item-button";
|
||||
import "../list/ha-list-base";
|
||||
import "../animation/ha-fade-in";
|
||||
import "../ha-spinner";
|
||||
import "../ha-svg-icon";
|
||||
import "../input/ha-input";
|
||||
@@ -47,6 +39,8 @@ import {
|
||||
|
||||
@customElement("ha-selector-location")
|
||||
export class HaLocationSelector extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public selector!: LocationSelector;
|
||||
|
||||
@property({ type: Object }) public value?: LocationSelectorValue;
|
||||
@@ -57,17 +51,6 @@ export class HaLocationSelector extends LitElement {
|
||||
|
||||
@property({ type: Boolean, reflect: true }) public disabled = false;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: HomeAssistantInternationalization;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, HassConfig | undefined>({
|
||||
transformer: ({ config }) => config ?? undefined,
|
||||
})
|
||||
private _hassConfig?: HassConfig;
|
||||
|
||||
@state() private _working = false;
|
||||
|
||||
@state() private _places?: OpenStreetMapPlace[] | null;
|
||||
@@ -123,10 +106,10 @@ export class HaLocationSelector extends LitElement {
|
||||
);
|
||||
|
||||
protected willUpdate() {
|
||||
if (!this.value && this._hassConfig) {
|
||||
if (!this.value) {
|
||||
this.value = {
|
||||
latitude: this._hassConfig.latitude,
|
||||
longitude: this._hassConfig.longitude,
|
||||
latitude: this.hass.config.latitude,
|
||||
longitude: this.hass.config.longitude,
|
||||
radius: this.selector.location?.radius ? DEFAULT_RADIUS : undefined,
|
||||
};
|
||||
}
|
||||
@@ -138,7 +121,7 @@ export class HaLocationSelector extends LitElement {
|
||||
|
||||
<div class="location-search" @keydown=${this._searchKeyDown}>
|
||||
<ha-input
|
||||
label=${this._i18n.localize(
|
||||
label=${this.hass.localize(
|
||||
"ui.components.selectors.location.address_label"
|
||||
)}
|
||||
.disabled=${this.disabled}
|
||||
@@ -154,7 +137,7 @@ export class HaLocationSelector extends LitElement {
|
||||
: html`<ha-icon-button
|
||||
slot="end"
|
||||
.path=${mdiMapSearchOutline}
|
||||
.label=${this._i18n.localize("ui.common.search")}
|
||||
.label=${this.hass.localize("ui.common.search")}
|
||||
.disabled=${this.disabled}
|
||||
@click=${this._searchButtonClicked}
|
||||
></ha-icon-button>`
|
||||
@@ -164,7 +147,7 @@ export class HaLocationSelector extends LitElement {
|
||||
${
|
||||
this._searchError
|
||||
? html`<ha-alert alert-type="error">
|
||||
${this._i18n.localize(
|
||||
${this.hass.localize(
|
||||
"ui.components.selectors.location.search_error"
|
||||
)}
|
||||
</ha-alert>`
|
||||
@@ -182,7 +165,7 @@ export class HaLocationSelector extends LitElement {
|
||||
Array.isArray(this._places) && this._places.length
|
||||
? html`
|
||||
<ha-list-base
|
||||
aria-label=${this._i18n.localize(
|
||||
aria-label=${this.hass.localize(
|
||||
"ui.components.selectors.location.search_results_label"
|
||||
)}
|
||||
>
|
||||
@@ -191,13 +174,13 @@ export class HaLocationSelector extends LitElement {
|
||||
`
|
||||
: this._places?.length === 0
|
||||
? html`<p class="search-no-results">
|
||||
${this._i18n.localize("ui.components.combo-box.no_match")}
|
||||
${this.hass.localize("ui.components.combo-box.no_match")}
|
||||
</p>`
|
||||
: nothing
|
||||
}
|
||||
|
||||
<p class="attribution">
|
||||
${this._i18n.localize(
|
||||
${this.hass.localize(
|
||||
"ui.components.selectors.location.search_disclosure",
|
||||
{
|
||||
openstreetmap: html`<a
|
||||
@@ -210,7 +193,7 @@ export class HaLocationSelector extends LitElement {
|
||||
href="https://wiki.osmfoundation.org/wiki/Privacy_Policy"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>${this._i18n.localize(
|
||||
>${this.hass.localize(
|
||||
"ui.components.selectors.location.osm_privacy_policy"
|
||||
)}</a
|
||||
>`,
|
||||
@@ -219,27 +202,18 @@ export class HaLocationSelector extends LitElement {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
${
|
||||
this._hassConfig
|
||||
? html`<ha-locations-editor
|
||||
class="flex"
|
||||
.helper=${this.helper}
|
||||
.locations=${this._location(
|
||||
this.selector,
|
||||
this._hassConfig,
|
||||
this.value
|
||||
)}
|
||||
@location-updated=${this._locationChanged}
|
||||
@radius-updated=${this._radiusChanged}
|
||||
pin-on-click
|
||||
></ha-locations-editor>`
|
||||
: html`<ha-fade-in .delay=${500}
|
||||
><ha-spinner></ha-spinner
|
||||
></ha-fade-in>`
|
||||
}
|
||||
<ha-locations-editor
|
||||
class="flex"
|
||||
.helper=${this.helper}
|
||||
.locations=${this._location(this.selector, this.value)}
|
||||
@location-updated=${this._locationChanged}
|
||||
@radius-updated=${this._radiusChanged}
|
||||
pin-on-click
|
||||
></ha-locations-editor>
|
||||
<ha-form
|
||||
.hass=${this.hass}
|
||||
.schema=${this._schema(
|
||||
this._i18n.localize,
|
||||
this.hass.localize,
|
||||
this.selector.location?.radius,
|
||||
this.selector.location?.radius_readonly
|
||||
)}
|
||||
@@ -254,7 +228,6 @@ export class HaLocationSelector extends LitElement {
|
||||
private _location = memoizeOne(
|
||||
(
|
||||
selector: LocationSelector,
|
||||
hassConfig: HassConfig,
|
||||
value?: LocationSelectorValue
|
||||
): MarkerLocation[] => {
|
||||
const computedStyles = getComputedStyle(this);
|
||||
@@ -267,11 +240,11 @@ export class HaLocationSelector extends LitElement {
|
||||
id: "location",
|
||||
latitude:
|
||||
!value || isNaN(value.latitude)
|
||||
? hassConfig.latitude
|
||||
? this.hass.config.latitude
|
||||
: value.latitude,
|
||||
longitude:
|
||||
!value || isNaN(value.longitude)
|
||||
? hassConfig.longitude
|
||||
? this.hass.config.longitude
|
||||
: value.longitude,
|
||||
radius: selector.location?.radius
|
||||
? value?.radius || DEFAULT_RADIUS
|
||||
@@ -313,7 +286,7 @@ export class HaLocationSelector extends LitElement {
|
||||
entry: SchemaUnion<ReturnType<typeof this._schema>>
|
||||
): string => {
|
||||
if (entry.name) {
|
||||
return this._i18n.localize(
|
||||
return this.hass.localize(
|
||||
`ui.components.selectors.location.${entry.name}`
|
||||
);
|
||||
}
|
||||
@@ -364,17 +337,12 @@ export class HaLocationSelector extends LitElement {
|
||||
this._status = undefined;
|
||||
|
||||
try {
|
||||
this._places = await searchPlaces(
|
||||
searchTerm,
|
||||
this._i18n.locale.language,
|
||||
true,
|
||||
3
|
||||
);
|
||||
this._places = await searchPlaces(searchTerm, this.hass, true, 3);
|
||||
this._status = searchResultsStatus(
|
||||
searchTerm,
|
||||
this._places,
|
||||
() => true,
|
||||
this._i18n.localize
|
||||
this.hass.localize
|
||||
);
|
||||
} catch (_err) {
|
||||
this._places = undefined;
|
||||
@@ -430,7 +398,7 @@ export class HaLocationSelector extends LitElement {
|
||||
this._input?.focus({ preventScroll: true });
|
||||
}
|
||||
this._places = undefined;
|
||||
this._status = this._i18n.localize(
|
||||
this._status = this.hass.localize(
|
||||
"ui.components.selectors.location.selected_location",
|
||||
{ location: place.display_name }
|
||||
);
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { html, LitElement, type TemplateResult } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import type { MediaSelector, MediaSelectorValue } from "../../data/selector";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import "../ha-media-item-picker";
|
||||
import { ensureArray } from "../../common/array/ensure-array";
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
|
||||
@customElement("ha-selector-media")
|
||||
export class HaMediaSelector extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public selector!: MediaSelector;
|
||||
|
||||
@property({ attribute: false }) public value?:
|
||||
@@ -31,6 +34,7 @@ export class HaMediaSelector extends LitElement {
|
||||
changeCallback?
|
||||
): TemplateResult {
|
||||
return html`<ha-media-item-picker
|
||||
.hass=${this.hass}
|
||||
.context=${this.context}
|
||||
.selector=${this.selector}
|
||||
.value=${value}
|
||||
|
||||
@@ -26,20 +26,6 @@ import "../ha-svg-icon";
|
||||
import "../radio/ha-radio-group";
|
||||
import "../radio/ha-radio-option";
|
||||
|
||||
const SEARCH_MIN_OPTIONS = 12;
|
||||
|
||||
const SEARCH_KEYS = [{ name: "primary", weight: 1 }];
|
||||
|
||||
// Every value gets the prefix, so "" has a non-empty ID and no value can
|
||||
// collide with another value's ID.
|
||||
const PICKER_ID_PREFIX = "option:";
|
||||
|
||||
export const toPickerId = (value: string | number) =>
|
||||
`${PICKER_ID_PREFIX}${value}`;
|
||||
|
||||
export const findPickerOption = (options: SelectOption[], id?: string) =>
|
||||
options.find((option) => toPickerId(option.value) === id);
|
||||
|
||||
@customElement("ha-selector-select")
|
||||
export class HaSelectSelector extends LitElement {
|
||||
@state()
|
||||
@@ -270,23 +256,6 @@ export class HaSelectSelector extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
if (options.length > SEARCH_MIN_OPTIONS) {
|
||||
return html`
|
||||
<ha-generic-picker
|
||||
no-sort
|
||||
.label=${this.label}
|
||||
.helper=${this.helper}
|
||||
.disabled=${this.disabled}
|
||||
.required=${this.required}
|
||||
.getItems=${this._getSearchItems(options)}
|
||||
.value=${this._pickerValue(options)}
|
||||
.valueRenderer=${this._valueRenderer(options)}
|
||||
.searchKeys=${SEARCH_KEYS}
|
||||
@value-changed=${this._searchPickerChanged}
|
||||
></ha-generic-picker>
|
||||
`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-select
|
||||
.label=${this.label ?? ""}
|
||||
@@ -341,37 +310,6 @@ export class HaSelectSelector extends LitElement {
|
||||
}
|
||||
);
|
||||
|
||||
private _getSearchItems = memoizeOne(
|
||||
(options: SelectOption[]) => () =>
|
||||
options.map((option) => ({
|
||||
id: toPickerId(option.value),
|
||||
primary: option.label,
|
||||
sorting_label: option.label,
|
||||
disabled: option.disabled,
|
||||
}))
|
||||
);
|
||||
|
||||
private _pickerValue(options: SelectOption[]): string | undefined {
|
||||
const value = this.value as string | number | undefined;
|
||||
if (typeof value !== "string" && typeof value !== "number") {
|
||||
return undefined;
|
||||
}
|
||||
if (value === "" && !options.some((option) => option.value === "")) {
|
||||
return undefined;
|
||||
}
|
||||
return toPickerId(value);
|
||||
}
|
||||
|
||||
private _valueRenderer = memoizeOne(
|
||||
(options: SelectOption[]) => (id: string) =>
|
||||
html`<span slot="headline"
|
||||
>${
|
||||
findPickerOption(options, id)?.label ??
|
||||
id.slice(PICKER_ID_PREFIX.length)
|
||||
}</span
|
||||
>`
|
||||
);
|
||||
|
||||
private get _mode(): "list" | "dropdown" | "box" {
|
||||
return (
|
||||
this.selector.select?.mode ||
|
||||
@@ -446,36 +384,6 @@ export class HaSelectSelector extends LitElement {
|
||||
});
|
||||
}
|
||||
|
||||
private _searchPickerChanged(ev: CustomEvent): void {
|
||||
ev.stopPropagation();
|
||||
|
||||
if (this.disabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const id: string | undefined = ev.detail.value;
|
||||
|
||||
if (id === undefined) {
|
||||
if (this.value !== undefined) {
|
||||
fireEvent(this, "value-changed", { value: undefined });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Look the pick up in the current options: the open list can be older.
|
||||
const option = findPickerOption(this._getOptions(this.selector), id);
|
||||
|
||||
if (
|
||||
!option ||
|
||||
option.disabled ||
|
||||
(this.value != null && String(option.value) === String(this.value))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
fireEvent(this, "value-changed", { value: option.value });
|
||||
}
|
||||
|
||||
private _comboBoxValueChanged(ev: CustomEvent): void {
|
||||
ev.stopPropagation();
|
||||
const newValue = ev.detail.value;
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import type { UiConditionSelector } from "../../data/selector";
|
||||
import "../../panels/lovelace/editor/conditions/ha-card-conditions-editor";
|
||||
import type { VisibilityCondition } from "../../panels/lovelace/common/validate-condition";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
|
||||
@customElement("ha-selector-ui_condition")
|
||||
export class HaUiConditionSelector extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false })
|
||||
public selector!: UiConditionSelector;
|
||||
|
||||
@property({ attribute: false }) public value?: VisibilityCondition[];
|
||||
|
||||
@property() public label?: string;
|
||||
|
||||
@property({ type: Boolean }) public disabled = false;
|
||||
|
||||
protected firstUpdated() {
|
||||
// The editor's labels come from the dashboard translations, which only
|
||||
// load with a dashboard; this selector can show anywhere.
|
||||
this.hass.loadFragmentTranslation("lovelace");
|
||||
}
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
${this.label ? html`<label>${this.label}</label>` : nothing}
|
||||
<ha-card-conditions-editor
|
||||
.hass=${this.hass}
|
||||
.conditions=${this.value ?? []}
|
||||
.disabled=${this.disabled}
|
||||
></ha-card-conditions-editor>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: var(--ha-space-1);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-selector-ui_condition": HaUiConditionSelector;
|
||||
}
|
||||
}
|
||||
@@ -69,7 +69,6 @@ const LOAD_ELEMENTS = {
|
||||
ui_action: () => import("./ha-selector-ui-action"),
|
||||
ui_clock_date_format: () => import("./ha-selector-ui-clock-date-format"),
|
||||
ui_color: () => import("./ha-selector-ui-color"),
|
||||
ui_condition: () => import("./ha-selector-ui-condition"),
|
||||
ui_state_content: () => import("./ha-selector-ui-state-content"),
|
||||
ui_time_format: () => import("./ha-selector-ui-time-format"),
|
||||
unit_of_measurement: () => import("./ha-selector-unit-of-measurement"),
|
||||
|
||||
@@ -23,7 +23,6 @@ import {
|
||||
getPanelIcon,
|
||||
getPanelIconPath,
|
||||
getPanelTitle,
|
||||
getSelectedPanelUrlPath,
|
||||
} from "../data/panel";
|
||||
import type { PersistentNotification } from "../data/persistent_notification";
|
||||
import { subscribeNotifications } from "../data/persistent_notification";
|
||||
@@ -232,36 +231,12 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const selectedPanel = this.hass.panelUrl;
|
||||
|
||||
// prettier-ignore
|
||||
return html`
|
||||
${this._renderHeader()}
|
||||
${this._renderAllPanels()}`;
|
||||
}
|
||||
|
||||
private _computeSidebarPanels(): [PanelInfo[], PanelInfo[]] | undefined {
|
||||
if (!this._panelOrder || !this._hiddenPanels) {
|
||||
return undefined;
|
||||
}
|
||||
return computePanels(
|
||||
this.hass.panels,
|
||||
getDefaultPanelUrlPath(this.hass),
|
||||
this._panelOrder,
|
||||
this._hiddenPanels,
|
||||
this.hass.locale
|
||||
);
|
||||
}
|
||||
|
||||
private _computeSelectedPanel(
|
||||
sidebarPanels: [PanelInfo[], PanelInfo[]] | undefined,
|
||||
route: Route | undefined
|
||||
): string {
|
||||
if (!route) {
|
||||
return this.hass.panelUrl;
|
||||
}
|
||||
const urlPaths = (sidebarPanels ?? [[], []])
|
||||
.flat()
|
||||
.map((panel) => panel.url_path);
|
||||
return getSelectedPanelUrlPath(urlPaths, route.path);
|
||||
${this._renderAllPanels(selectedPanel)}`;
|
||||
}
|
||||
|
||||
protected shouldUpdate(changedProps: PropertyValues): boolean {
|
||||
@@ -279,20 +254,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (!this.hass) {
|
||||
return false;
|
||||
}
|
||||
if (changedProps.has("route")) {
|
||||
const sidebarPanels = this._computeSidebarPanels();
|
||||
const oldRoute = changedProps.get("route") as Route | undefined;
|
||||
if (
|
||||
this._computeSelectedPanel(sidebarPanels, oldRoute) !==
|
||||
this._computeSelectedPanel(sidebarPanels, this.route)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (!changedProps.has("hass")) {
|
||||
if (!this.hass || !changedProps.has("hass")) {
|
||||
return false;
|
||||
}
|
||||
const oldHass = changedProps.get("hass") as HomeAssistant;
|
||||
@@ -393,9 +355,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _renderAllPanels() {
|
||||
const sidebarPanels = this._computeSidebarPanels();
|
||||
const selectedPanel = this._computeSelectedPanel(sidebarPanels, this.route);
|
||||
private _renderAllPanels(selectedPanel: string) {
|
||||
const renderList = (content, cls: string, scrollable: boolean) =>
|
||||
html`<ha-list-nav
|
||||
class=${classMap({
|
||||
@@ -405,7 +365,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
>${content}</ha-list-nav
|
||||
>`;
|
||||
|
||||
if (!sidebarPanels) {
|
||||
if (!this._panelOrder || !this._hiddenPanels) {
|
||||
return html`<div class="panels-list">
|
||||
<div class="wrapper">
|
||||
${renderList(
|
||||
@@ -430,7 +390,15 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
</div>`;
|
||||
}
|
||||
|
||||
const [beforeSpacer, afterSpacer] = sidebarPanels;
|
||||
const defaultPanel = getDefaultPanelUrlPath(this.hass);
|
||||
|
||||
const [beforeSpacer, afterSpacer] = computePanels(
|
||||
this.hass.panels,
|
||||
defaultPanel,
|
||||
this._panelOrder,
|
||||
this._hiddenPanels,
|
||||
this.hass.locale
|
||||
);
|
||||
|
||||
// prettier-ignore
|
||||
return html`<div class="panels-list">
|
||||
@@ -474,7 +442,7 @@ class HaSidebar extends SubscribeMixin(ScrollableFadeMixin(LitElement)) {
|
||||
}
|
||||
|
||||
private _renderPanel(panel: PanelInfo, isSelected: boolean) {
|
||||
const title = getPanelTitle(this.hass.localize, panel);
|
||||
const title = getPanelTitle(this.hass, panel);
|
||||
const urlPath = panel.url_path;
|
||||
const icon = getPanelIcon(panel);
|
||||
const iconPath = getPanelIconPath(panel);
|
||||
|
||||
@@ -200,7 +200,6 @@ class HaEntityMarker extends LitElement {
|
||||
}
|
||||
.entity-picture {
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@@ -1812,20 +1812,6 @@ export class HaMap extends ReactiveElement {
|
||||
#map.clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
/* Bubble avatars open their entity; the expanded bubble around them
|
||||
takes no click of its own */
|
||||
.maplibregl-marker ha-entity-marker {
|
||||
cursor: pointer;
|
||||
}
|
||||
/* A drag that starts on a marker pans the map like anywhere else;
|
||||
markers that drag themselves keep their own cursor */
|
||||
.maplibregl-canvas-container.maplibregl-interactive:active
|
||||
.maplibregl-marker:not(.maplibregl-marker-draggable),
|
||||
.maplibregl-canvas-container.maplibregl-interactive:active
|
||||
.maplibregl-marker:not(.maplibregl-marker-draggable)
|
||||
ha-entity-marker {
|
||||
cursor: grabbing !important;
|
||||
}
|
||||
.maplibregl-marker {
|
||||
transition:
|
||||
opacity var(--ha-animation-duration-fast),
|
||||
|
||||
@@ -11,7 +11,6 @@ import type {
|
||||
HassEntityBase,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { showEnterCodeDialog } from "../dialogs/enter-code/show-enter-code-dialog";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import { getExtendedEntityRegistryEntry } from "./entity/entity_registry";
|
||||
@@ -109,9 +108,7 @@ export const supportedAlarmModes = (stateObj: AlarmControlPanelEntity) =>
|
||||
|
||||
export const setProtectedAlarmControlPanelMode = async (
|
||||
element: HTMLElement,
|
||||
callService: HomeAssistant["callService"],
|
||||
callWS: HomeAssistant["callWS"],
|
||||
localize: LocalizeFunc,
|
||||
hass: Pick<HomeAssistant, "callService" | "localize" | "callWS">,
|
||||
stateObj: AlarmControlPanelEntity,
|
||||
mode: AlarmMode
|
||||
) => {
|
||||
@@ -126,7 +123,7 @@ export const setProtectedAlarmControlPanelMode = async (
|
||||
(mode === "disarmed" && stateObj.attributes.code_format)
|
||||
) {
|
||||
const entry = await getExtendedEntityRegistryEntry(
|
||||
callWS,
|
||||
hass.callWS,
|
||||
stateObj.entity_id
|
||||
).catch(() => undefined);
|
||||
const defaultCode = entry?.options?.alarm_control_panel?.default_code;
|
||||
@@ -136,10 +133,10 @@ export const setProtectedAlarmControlPanelMode = async (
|
||||
|
||||
const response = await showEnterCodeDialog(element, {
|
||||
codeFormat: stateObj.attributes.code_format,
|
||||
title: localize(
|
||||
title: hass.localize(
|
||||
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
|
||||
),
|
||||
submitText: localize(
|
||||
submitText: hass.localize(
|
||||
`ui.card.alarm_control_panel.${disarm ? "disarm" : "arm"}`
|
||||
),
|
||||
});
|
||||
@@ -150,7 +147,7 @@ export const setProtectedAlarmControlPanelMode = async (
|
||||
}
|
||||
}
|
||||
|
||||
await callService("alarm_control_panel", service, {
|
||||
await hass.callService("alarm_control_panel", service, {
|
||||
entity_id: stateObj.entity_id,
|
||||
code,
|
||||
});
|
||||
|
||||
@@ -103,23 +103,3 @@ export const CLIMATE_HVAC_MODE_ICONS: Record<HvacMode, string> = {
|
||||
|
||||
export const climateHvacModeIcon = (mode: string) =>
|
||||
CLIMATE_HVAC_MODE_ICONS[mode] || mdiThermostat;
|
||||
|
||||
export type ClimateTarget = "value" | "low" | "high";
|
||||
|
||||
/**
|
||||
* The targets to change when one target is set. A low or high target that
|
||||
* passes the other one pushes it along, so the range never ends up inverted.
|
||||
*/
|
||||
export const pushTargetTemperature = (
|
||||
current: Partial<Record<ClimateTarget, number>>,
|
||||
target: ClimateTarget,
|
||||
value: number
|
||||
): Partial<Record<ClimateTarget, number>> => {
|
||||
if (target === "low" && current.high != null && value > current.high) {
|
||||
return { low: value, high: value };
|
||||
}
|
||||
if (target === "high" && current.low != null && value < current.low) {
|
||||
return { low: value, high: value };
|
||||
}
|
||||
return { [target]: value };
|
||||
};
|
||||
@@ -158,12 +158,7 @@ export const computeNavigationPathInfo = (
|
||||
const isDashboard = panel?.component_name === "lovelace";
|
||||
|
||||
const panelInfo: NavigationPathInfo = {
|
||||
label:
|
||||
getPanelTitleFromUrlPath(
|
||||
options.localize,
|
||||
options.panels,
|
||||
panelUrlPath
|
||||
) || panelUrlPath,
|
||||
label: getPanelTitleFromUrlPath(options, panelUrlPath) || panelUrlPath,
|
||||
icon: panelIcon || (isDashboard ? "mdi:view-dashboard" : undefined),
|
||||
iconPath: panelIconPath || mdiLink,
|
||||
};
|
||||
|
||||
@@ -32,7 +32,6 @@ import type { EntityNameItem } from "../common/entity/entity_name_config";
|
||||
import { formatNumberWithUnit } from "../common/number/format_number";
|
||||
import { normalizeValueBySIPrefix } from "../common/number/normalize-by-si-prefix";
|
||||
import { groupBy } from "../common/util/group-by";
|
||||
import { generateUuidV4 } from "../common/util/uuid";
|
||||
import type { HomeAssistant, HomeAssistantRegistries } from "../types";
|
||||
import { fileDownload } from "../util/file_download";
|
||||
import type {
|
||||
@@ -344,31 +343,6 @@ export interface WaterSourceTypeEnergyPreference {
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export type FixedCostType = "grid" | "gas" | "water";
|
||||
|
||||
export type FixedCostPeriod = "day" | "month" | "year";
|
||||
|
||||
export interface FixedCostEnergyPreference {
|
||||
id: string;
|
||||
type: FixedCostType;
|
||||
name: string;
|
||||
// Charged at the start of each period, exactly one of these is set
|
||||
number_amount: number | null;
|
||||
entity_amount: string | null;
|
||||
period: FixedCostPeriod;
|
||||
}
|
||||
|
||||
export const emptyFixedCostEnergyPreference = (
|
||||
type: FixedCostType
|
||||
): FixedCostEnergyPreference => ({
|
||||
id: generateUuidV4(),
|
||||
type,
|
||||
name: "",
|
||||
number_amount: null,
|
||||
entity_amount: null,
|
||||
period: "day",
|
||||
});
|
||||
|
||||
export type EnergySource =
|
||||
| SolarSourceTypeEnergyPreference
|
||||
| HomeSourceTypeEnergyPreference
|
||||
@@ -382,7 +356,6 @@ export interface EnergyPreferences {
|
||||
device_consumption: DeviceConsumptionEnergyPreference[];
|
||||
device_consumption_water: DeviceConsumptionEnergyPreference[];
|
||||
device_consumption_gas: DeviceConsumptionEnergyPreference[];
|
||||
fixed_costs: FixedCostEnergyPreference[];
|
||||
}
|
||||
|
||||
export const EMPTY_PREFERENCES: EnergyPreferences = {
|
||||
@@ -390,13 +363,10 @@ export const EMPTY_PREFERENCES: EnergyPreferences = {
|
||||
device_consumption: [],
|
||||
device_consumption_water: [],
|
||||
device_consumption_gas: [],
|
||||
fixed_costs: [],
|
||||
};
|
||||
|
||||
export interface EnergyInfo {
|
||||
cost_sensors: Record<string, string>;
|
||||
// Fixed cost id to the entity ID of its cost sensor
|
||||
fixed_cost_sensors: Record<string, string>;
|
||||
solar_forecast_domains: string[];
|
||||
}
|
||||
|
||||
@@ -411,7 +381,6 @@ export interface EnergyPreferencesValidation {
|
||||
device_consumption: EnergyValidationIssue[][];
|
||||
device_consumption_water: EnergyValidationIssue[][];
|
||||
device_consumption_gas: EnergyValidationIssue[][];
|
||||
fixed_costs: EnergyValidationIssue[][];
|
||||
}
|
||||
|
||||
export const getEnergyInfo = (callWS: HomeAssistant["callWS"]) =>
|
||||
@@ -474,30 +443,6 @@ export interface EnergySourceByType {
|
||||
export const energySourcesByType = (prefs: EnergyPreferences) =>
|
||||
groupBy(prefs.energy_sources, (item) => item.type) as EnergySourceByType;
|
||||
|
||||
export type FixedCostsByType = Partial<
|
||||
Record<FixedCostType, FixedCostEnergyPreference[]>
|
||||
>;
|
||||
|
||||
export const fixedCostsByType = (prefs: EnergyPreferences) =>
|
||||
groupBy(prefs.fixed_costs, (item) => item.type) as FixedCostsByType;
|
||||
|
||||
/** Sum of the fixed costs, or undefined without cost data. */
|
||||
export const calculateFixedCostTotal = (
|
||||
fixedCosts: FixedCostEnergyPreference[],
|
||||
info: EnergyInfo,
|
||||
stats: Statistics
|
||||
): number | undefined => {
|
||||
let total: number | undefined;
|
||||
for (const fixedCost of fixedCosts) {
|
||||
const statId = info.fixed_cost_sensors[fixedCost.id];
|
||||
const cost = statId ? calculateStatisticSumGrowth(stats[statId]) : null;
|
||||
if (cost !== null) {
|
||||
total = (total ?? 0) + cost;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
};
|
||||
|
||||
/** Import cost minus export compensation, or undefined without cost data. */
|
||||
export const calculateGridNetCost = (
|
||||
sources: GridSourceTypeEnergyPreference[],
|
||||
@@ -813,15 +758,6 @@ export const getReferencedStatisticIds = (
|
||||
...prefs.device_consumption_gas.map((d) => d.stat_consumption)
|
||||
);
|
||||
}
|
||||
for (const fixedCost of prefs.fixed_costs) {
|
||||
if (includeTypes && !includeTypes.includes(fixedCost.type)) {
|
||||
continue;
|
||||
}
|
||||
const costStatId = info.fixed_cost_sensors[fixedCost.id];
|
||||
if (costStatId) {
|
||||
statIDs.push(costStatId);
|
||||
}
|
||||
}
|
||||
|
||||
return statIDs;
|
||||
};
|
||||
@@ -2655,9 +2591,6 @@ export const formatFlowRateShort = (
|
||||
|
||||
export type WaterGasResource = "water" | "gas";
|
||||
|
||||
/** The device categories the device graphs can show. */
|
||||
export type DeviceConsumptionResource = "electricity" | "gas";
|
||||
|
||||
export const getWaterGasDevicesKey = (resource: WaterGasResource) =>
|
||||
`device_consumption_${resource}` as const;
|
||||
|
||||
@@ -3005,13 +2938,6 @@ export const downloadEnergyData = (
|
||||
printCategory("device_consumption_gas", gasDevices, state.gasUnit);
|
||||
}
|
||||
|
||||
energyData.prefs.fixed_costs.forEach((fixedCost) => {
|
||||
const costId = state.info.fixed_cost_sensors[fixedCost.id];
|
||||
if (costId) {
|
||||
processStat(costId, `${fixedCost.type}_fixed_cost`, currency);
|
||||
}
|
||||
});
|
||||
|
||||
const { summedData } = getSummedData(state);
|
||||
const { consumption } = computeConsumptionData(summedData, undefined);
|
||||
|
||||
|
||||
@@ -77,10 +77,6 @@ export const filterGroupsWithListedMembers = (
|
||||
): string[] => {
|
||||
const listed = new Set(entityIds);
|
||||
const hasListedDescendant = (groupId: string): boolean => {
|
||||
const groupObj = states[groupId];
|
||||
if (!groupObj || !computeGroupMemberIds(groupObj)) {
|
||||
return false;
|
||||
}
|
||||
const seen = new Set([groupId]);
|
||||
const queue = [groupId];
|
||||
while (queue.length) {
|
||||
|
||||
+2
-30
@@ -250,16 +250,13 @@ export type IconCategory =
|
||||
| "services"
|
||||
| "triggers"
|
||||
| "conditions"
|
||||
| "integration_category"
|
||||
| "integration_connectivity";
|
||||
| "integration_category";
|
||||
|
||||
export type IntegrationCategoryIcons = Record<
|
||||
string,
|
||||
{ default: string; subcategory?: Record<string, { default: string }> }
|
||||
>;
|
||||
|
||||
export type IntegrationConnectivityIcons = Record<string, { default: string }>;
|
||||
|
||||
interface CategoryType {
|
||||
entity: PlatformIcons;
|
||||
entity_component: ComponentIcons;
|
||||
@@ -267,7 +264,6 @@ interface CategoryType {
|
||||
triggers: TriggerIcons;
|
||||
conditions: ConditionIcons;
|
||||
integration_category: IntegrationCategoryIcons;
|
||||
integration_connectivity: IntegrationConnectivityIcons;
|
||||
}
|
||||
|
||||
export const getHassIcons = async <T extends IconCategory>(
|
||||
@@ -338,10 +334,7 @@ export const getComponentIcons = async (
|
||||
export const getCategoryIcons = async <
|
||||
T extends Exclude<
|
||||
IconCategory,
|
||||
| "entity"
|
||||
| "entity_component"
|
||||
| "integration_category"
|
||||
| "integration_connectivity"
|
||||
"entity" | "entity_component" | "integration_category"
|
||||
>,
|
||||
>(
|
||||
connection: Connection,
|
||||
@@ -782,24 +775,3 @@ export const getIntegrationCategoryIcons = async (
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
let integrationConnectivityIcons:
|
||||
ReturnType<typeof getHassIcons<"integration_connectivity">> | undefined;
|
||||
|
||||
export const getIntegrationConnectivityIcons = async (
|
||||
connection: Connection
|
||||
): Promise<IntegrationConnectivityIcons | undefined> => {
|
||||
// Cache the request itself, so callers while it loads share it
|
||||
integrationConnectivityIcons ??= getHassIcons(
|
||||
connection,
|
||||
"integration_connectivity",
|
||||
"homeassistant"
|
||||
);
|
||||
try {
|
||||
const result = await integrationConnectivityIcons;
|
||||
return result.resources.homeassistant;
|
||||
} catch (_err) {
|
||||
integrationConnectivityIcons = undefined;
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
@@ -1,15 +0,0 @@
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import type { IntegrationConnectivityIcons } from "./icons";
|
||||
|
||||
// The name of a connectivity, like `zigbee`. Empty for one this Home Assistant
|
||||
// doesn't know.
|
||||
export const integrationConnectivityName = (
|
||||
localize: LocalizeFunc,
|
||||
slug: string
|
||||
): string =>
|
||||
localize(`component.homeassistant.integration_connectivity.${slug}.name`);
|
||||
|
||||
export const integrationConnectivityIcon = (
|
||||
icons: IntegrationConnectivityIcons | undefined,
|
||||
slug: string
|
||||
): string | undefined => icons?.[slug]?.default;
|
||||
@@ -10,9 +10,6 @@ export interface RepositoryBase {
|
||||
can_install: boolean;
|
||||
category: RepositoryType;
|
||||
config_flow: boolean;
|
||||
// How an integration connects, like `zigbee` or `cloud`. Empty for other
|
||||
// repositories and for integrations that don't set it.
|
||||
connectivity?: string[];
|
||||
custom: boolean;
|
||||
description: string;
|
||||
domain: string | null;
|
||||
|
||||
@@ -62,14 +62,14 @@ export const formatOpenStreetMapPlace = (
|
||||
|
||||
export const searchPlaces = (
|
||||
address: string,
|
||||
language: string,
|
||||
hass: HomeAssistant,
|
||||
addressdetails?: boolean,
|
||||
limit?: number
|
||||
): Promise<OpenStreetMapPlace[]> => {
|
||||
const params = new URLSearchParams({
|
||||
q: address,
|
||||
format: "jsonv2",
|
||||
"accept-language": language,
|
||||
"accept-language": hass.locale.language,
|
||||
email: "[email protected]",
|
||||
});
|
||||
if (limit) {
|
||||
|
||||
+8
-27
@@ -8,12 +8,9 @@ import {
|
||||
mdiMap,
|
||||
mdiPlayBoxMultiple,
|
||||
} from "@mdi/js";
|
||||
import type {
|
||||
LocalizeFunc,
|
||||
LocalizeKeys,
|
||||
} from "../common/translations/localize";
|
||||
import type { LocalizeKeys } from "../common/translations/localize";
|
||||
import type { PageNavigation } from "../layouts/hass-tabs-subpage";
|
||||
import type { HomeAssistant, PanelInfo, Panels } from "../types";
|
||||
import type { HomeAssistant, PanelInfo } from "../types";
|
||||
import { MARKETPLACE_NAME } from "../common/translations/name-placeholders";
|
||||
|
||||
export const APP_PANEL = "app";
|
||||
@@ -69,7 +66,7 @@ export const getPanelNameTranslationKey = (panel: PanelInfo) => {
|
||||
};
|
||||
|
||||
export const getPanelTitle = (
|
||||
localize: LocalizeFunc,
|
||||
hass: Pick<HomeAssistant, "localize">,
|
||||
panel: PanelInfo
|
||||
): string | undefined => {
|
||||
if (panel.url_path === "marketplace") {
|
||||
@@ -78,19 +75,18 @@ export const getPanelTitle = (
|
||||
|
||||
const translationKey = getPanelNameTranslationKey(panel);
|
||||
|
||||
return localize(translationKey) || panel.title || undefined;
|
||||
return hass.localize(translationKey) || panel.title || undefined;
|
||||
};
|
||||
|
||||
export const getPanelTitleFromUrlPath = (
|
||||
localize: LocalizeFunc,
|
||||
panels: Panels,
|
||||
hass: Pick<HomeAssistant, "localize" | "panels">,
|
||||
urlPath: string
|
||||
): string | undefined => {
|
||||
if (!panels) {
|
||||
if (!hass.panels) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const panel = Object.values(panels).find(
|
||||
const panel = Object.values(hass.panels).find(
|
||||
(p: PanelInfo): boolean => p.url_path === urlPath
|
||||
);
|
||||
|
||||
@@ -98,7 +94,7 @@ export const getPanelTitleFromUrlPath = (
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return getPanelTitle(localize, panel);
|
||||
return getPanelTitle(hass, panel);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -200,21 +196,6 @@ export const getPanelIconPath = (panel: PanelInfo): string | undefined => {
|
||||
|
||||
export const FIXED_PANELS = [PROFILE_PANEL, "config", NOT_FOUND_PANEL];
|
||||
|
||||
// A panel's url_path can span several segments (e.g. "config/logs"), so the
|
||||
// most specific url_path matching the path wins over its first segment.
|
||||
export const getSelectedPanelUrlPath = (
|
||||
urlPaths: string[],
|
||||
path: string
|
||||
): string =>
|
||||
urlPaths.reduce(
|
||||
(selected, urlPath) =>
|
||||
urlPath.length > selected.length &&
|
||||
(path === `/${urlPath}` || path.startsWith(`/${urlPath}/`))
|
||||
? urlPath
|
||||
: selected,
|
||||
path.split("/")[1] ?? ""
|
||||
);
|
||||
|
||||
export interface PanelMutableParams {
|
||||
title?: string | null;
|
||||
icon?: string | null;
|
||||
|
||||
@@ -57,7 +57,7 @@ const generateNavigationPanelCommands = (
|
||||
.map(([_panelKey, panel]) => {
|
||||
const icon = getPanelIcon(panel) || "mdi:view-dashboard";
|
||||
|
||||
const primary = getPanelTitle(localize, panel) || panel.url_path;
|
||||
const primary = getPanelTitle({ localize }, panel) || panel.url_path;
|
||||
|
||||
const panelApp = apps?.find(({ slug }) => slug === panel.url_path);
|
||||
|
||||
|
||||
@@ -89,7 +89,6 @@ export type Selector =
|
||||
| UiActionSelector
|
||||
| UiClockDateFormatSelector
|
||||
| UiColorSelector
|
||||
| UiConditionSelector
|
||||
| UiStateContentSelector
|
||||
| UiTimeFormatSelector
|
||||
| UnitOfMeasurementSelector
|
||||
@@ -204,11 +203,6 @@ export interface ConditionSelector {
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** Dashboard conditions, edited like a card's visibility tab. */
|
||||
export interface UiConditionSelector {
|
||||
ui_condition: {} | null;
|
||||
}
|
||||
|
||||
export interface ConversationAgentSelector {
|
||||
conversation_agent: { language?: string } | null;
|
||||
}
|
||||
|
||||
@@ -223,7 +223,6 @@ export const SENSOR_DEVICE_CLASS_UNITS: Record<string, (string | null)[]> = {
|
||||
voltage: ["kV", "MV", "mV", "V", "μV"],
|
||||
volume: ["CCF", "fl. oz.", "ft³", "gal", "L", "MCF", "mL", "m³"],
|
||||
volume_flow_rate: [
|
||||
"ft³/h",
|
||||
"ft³/min",
|
||||
"gal/d",
|
||||
"gal/h",
|
||||
@@ -400,7 +399,6 @@ export const SENSOR_DEVICE_CLASS_CONVERTIBLE_UNITS: Record<
|
||||
voltage: ["kV", "MV", "mV", "V", "μV"],
|
||||
volume: ["CCF", "fl. oz.", "ft³", "gal", "L", "MCF", "mL", "m³"],
|
||||
volume_flow_rate: [
|
||||
"ft³/h",
|
||||
"ft³/min",
|
||||
"gal/d",
|
||||
"gal/h",
|
||||
|
||||
@@ -77,8 +77,7 @@ export type TranslationCategory =
|
||||
| "services"
|
||||
| "triggers"
|
||||
| "conditions"
|
||||
| "integration_category"
|
||||
| "integration_connectivity";
|
||||
| "integration_category";
|
||||
|
||||
export const subscribeTranslationPreferences = (
|
||||
hass: HomeAssistant,
|
||||
|
||||
@@ -4,11 +4,9 @@ import type {
|
||||
HassEntityBase,
|
||||
HassEvent,
|
||||
} from "home-assistant-js-websocket";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { BINARY_STATE_OFF, BINARY_STATE_ON } from "../common/const";
|
||||
import { computeDomain } from "../common/entity/compute_domain";
|
||||
import { computeStateDomain } from "../common/entity/compute_state_domain";
|
||||
import { getEntityIds } from "../common/entity/get_entity_ids";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import { formatNumber } from "../common/number/format_number";
|
||||
import { caseInsensitiveStringCompare } from "../common/string/compare";
|
||||
@@ -154,15 +152,6 @@ export const filterUpdateEntities = (
|
||||
);
|
||||
});
|
||||
|
||||
const findUpdateEntityIds = memoizeOne((entityIds: string[]) =>
|
||||
entityIds.filter((entityId) => computeDomain(entityId) === "update")
|
||||
);
|
||||
|
||||
export const countInstallableUpdates = (states: HassEntities): number =>
|
||||
findUpdateEntityIds(getEntityIds(states)).filter((entityId) =>
|
||||
updateCanInstall(states[entityId] as UpdateEntity)
|
||||
).length;
|
||||
|
||||
export const filterUpdateEntitiesParameterized = (
|
||||
entities: HassEntities,
|
||||
formatEntityName: HomeAssistant["formatEntityName"],
|
||||
|
||||
@@ -31,9 +31,11 @@ class MoreInfoAlarmControlPanel extends LitElement {
|
||||
private async _disarm() {
|
||||
setProtectedAlarmControlPanelMode(
|
||||
this,
|
||||
this._api.callService,
|
||||
this._api.callWS,
|
||||
this._localize,
|
||||
{
|
||||
callService: this._api.callService,
|
||||
callWS: this._api.callWS,
|
||||
localize: this._localize,
|
||||
},
|
||||
this.stateObj!,
|
||||
"disarmed"
|
||||
);
|
||||
|
||||
@@ -2,8 +2,6 @@ import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import { connectionContext, formattersContext } from "../../../data/context";
|
||||
import type { ImageEntity } from "../../../data/image";
|
||||
import { computeImageUrl } from "../../../data/image";
|
||||
@@ -30,17 +28,6 @@ class MoreInfoImage extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public stateObj?: ImageEntity;
|
||||
|
||||
private _size?: HASSDomEvents["media-size-changed"];
|
||||
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
// A cached view that was detached while the picture loaded couldn't send
|
||||
// its size, and the picture doesn't load again when it's shown
|
||||
if (this._size) {
|
||||
fireEvent(this, "media-size-changed", this._size);
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this._connection || !this.stateObj) {
|
||||
return nothing;
|
||||
@@ -52,28 +39,16 @@ class MoreInfoImage extends LitElement {
|
||||
return html`<img
|
||||
alt=${this._formatEntityName?.(this.stateObj) || this.stateObj.entity_id}
|
||||
src=${this._connection.hassUrl(imageUrl)}
|
||||
@load=${this._imageLoaded}
|
||||
/> `;
|
||||
}
|
||||
|
||||
private _imageLoaded(ev: HASSDomCurrentTargetEvent<HTMLImageElement>) {
|
||||
const { naturalWidth, naturalHeight } = ev.currentTarget;
|
||||
if (!naturalWidth || !naturalHeight) {
|
||||
return;
|
||||
}
|
||||
this._size = { aspectRatio: naturalWidth / naturalHeight, naturalWidth };
|
||||
fireEvent(this, "media-size-changed", this._size);
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
text-align: center;
|
||||
}
|
||||
img {
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
max-width: 100%;
|
||||
max-height: var(--more-info-media-max-height, none);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassConfig, UnsubscribeFunc } from "home-assistant-js-websocket";
|
||||
import { ERR_CONNECTION_LOST } from "home-assistant-js-websocket";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
@@ -457,11 +456,6 @@ class MoreInfoUpdate extends LitElement {
|
||||
false
|
||||
);
|
||||
} catch (err: any) {
|
||||
// The update keeps running when the connection drops during a long install.
|
||||
if (err?.error?.code === ERR_CONNECTION_LOST) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = await this._localizeInstallError(err);
|
||||
|
||||
if (this._isShown()) {
|
||||
|
||||
@@ -620,14 +620,15 @@ class MoreInfoWeather extends LitElement {
|
||||
}
|
||||
|
||||
.temp-attribute .temp {
|
||||
position: relative;
|
||||
margin-right: var(--ha-space-6);
|
||||
direction: ltr;
|
||||
}
|
||||
|
||||
.temp-attribute .temp span {
|
||||
position: relative;
|
||||
position: absolute;
|
||||
font-size: var(--ha-font-size-2xl);
|
||||
top: 1px;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.state,
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
mdiCogOutline,
|
||||
mdiContentDuplicate,
|
||||
mdiDevices,
|
||||
mdiDirections,
|
||||
mdiDotsVertical,
|
||||
mdiDownload,
|
||||
mdiInformationOutline,
|
||||
@@ -38,8 +37,6 @@ import {
|
||||
computeEntityNameParts,
|
||||
type EntityNameType,
|
||||
} from "../../common/entity/compute_entity_name_display";
|
||||
import { getEntityLocation } from "../../common/entity/get_entity_location";
|
||||
import { navigationUrl } from "../../common/map/navigation-url";
|
||||
import {
|
||||
getHistoryState,
|
||||
navigate,
|
||||
@@ -152,12 +149,10 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
|
||||
@property({ type: Boolean, reflect: true }) public large = false;
|
||||
|
||||
// The dialog grows with the camera's or image's picture, as high as there
|
||||
// is room for
|
||||
@state() private _mediaAspectRatio?: number;
|
||||
@state() private _fill = false;
|
||||
|
||||
// An image is not shown larger than it is
|
||||
@state() private _mediaNaturalWidth?: number;
|
||||
// The dialog grows with the camera's picture, as high as there is room for
|
||||
@state() private _cameraAspectRatio?: number;
|
||||
|
||||
// Height of the controls the camera's info shows below the picture
|
||||
@state() private _cameraControlsHeight?: string;
|
||||
@@ -201,6 +196,12 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
}
|
||||
|
||||
public showDialog(params: MoreInfoDialogParams) {
|
||||
// The camera player keeps running for the same entity and doesn't send
|
||||
// its size again
|
||||
if (params.entityId !== this._entityId) {
|
||||
this._cameraAspectRatio = undefined;
|
||||
this._cameraControlsHeight = undefined;
|
||||
}
|
||||
this._entityId = params.entityId;
|
||||
if (!this._entityId) {
|
||||
this.closeDialog();
|
||||
@@ -218,6 +219,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
this._detailsYamlMode = false;
|
||||
|
||||
this.large = params.large ?? false;
|
||||
this._fill = false;
|
||||
this._open = true;
|
||||
this._loadEntityRegistryEntry();
|
||||
}
|
||||
@@ -263,6 +265,8 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
this._currView = DEFAULT_VIEW;
|
||||
this._childViewStack = [];
|
||||
this._returnUrl = undefined;
|
||||
this._cameraAspectRatio = undefined;
|
||||
this._cameraControlsHeight = undefined;
|
||||
this._isEscapeEnabled = true;
|
||||
window.removeEventListener("dialog-closed", this._enableEscapeKeyClose);
|
||||
window.removeEventListener("show-dialog", this._disableEscapeKeyClose);
|
||||
@@ -507,29 +511,11 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
case "download_snapshot":
|
||||
this._downloadSnapshot();
|
||||
break;
|
||||
case "directions":
|
||||
this._openDirections();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private _openDirections() {
|
||||
const stateObj = this._entityId
|
||||
? (this.hass.states[this._entityId] as HassEntity | undefined)
|
||||
: undefined;
|
||||
const location = stateObj && getEntityLocation(stateObj, this.hass.states);
|
||||
if (!location) {
|
||||
return;
|
||||
}
|
||||
window.open(
|
||||
navigationUrl(location.latitude, location.longitude),
|
||||
"_blank",
|
||||
"noreferrer"
|
||||
);
|
||||
}
|
||||
|
||||
private async _resetFavorites() {
|
||||
const favoritesContext = this._getFavoritesContext();
|
||||
|
||||
@@ -653,16 +639,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
</ha-dropdown-item>
|
||||
`
|
||||
: nothing;
|
||||
const hasLocation =
|
||||
!!stateObj && !!getEntityLocation(stateObj, this.hass.states);
|
||||
const directionsMenuItem = hasLocation
|
||||
? html`
|
||||
<ha-dropdown-item value="directions">
|
||||
<ha-svg-icon slot="icon" .path=${mdiDirections}></ha-svg-icon>
|
||||
${this.hass.localize("ui.dialogs.more_info_control.directions")}
|
||||
</ha-dropdown-item>
|
||||
`
|
||||
: nothing;
|
||||
const viewTitle = this._computeViewTitle();
|
||||
const defaultTitle = breadcrumb[breadcrumb.length - 1] || entityId;
|
||||
if (!viewTitle) {
|
||||
@@ -715,32 +691,30 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
`
|
||||
: nothing;
|
||||
|
||||
// Also when it was opened from a smaller entity's related view
|
||||
const mediaAspectRatio =
|
||||
(domain === "camera" || domain === "image") && isDefaultView
|
||||
? this._mediaAspectRatio
|
||||
// Also when the camera was opened from a smaller entity's related view
|
||||
const cameraAspectRatio =
|
||||
domain === "camera" && isDefaultView
|
||||
? this._cameraAspectRatio
|
||||
: undefined;
|
||||
// As wide as the picture is when it's as high as there is room for
|
||||
const fullHeightWidth = `var(--more-info-media-max-height) * ${mediaAspectRatio}`;
|
||||
const mediaPictureWidth = this._mediaNaturalWidth
|
||||
? `min(${fullHeightWidth}, ${this._mediaNaturalWidth}px)`
|
||||
: fullHeightWidth;
|
||||
|
||||
return html`
|
||||
<ha-adaptive-dialog
|
||||
.open=${this._open}
|
||||
.width=${this.large || mediaAspectRatio ? "large" : "medium"}
|
||||
class=${classMap({
|
||||
camera: domain === "camera",
|
||||
image: domain === "image",
|
||||
})}
|
||||
.width=${
|
||||
this._fill
|
||||
? "full"
|
||||
: this.large || cameraAspectRatio
|
||||
? "large"
|
||||
: "medium"
|
||||
}
|
||||
class=${classMap({ camera: domain === "camera" })}
|
||||
style=${styleMap({
|
||||
"--more-info-camera-controls-height": this._cameraControlsHeight,
|
||||
"--ha-dialog-width-lg": mediaAspectRatio
|
||||
? `clamp(var(--ha-dialog-width-md, 580px), calc(${mediaPictureWidth} + var(--more-info-media-inline-padding, 0px)), 1920px)`
|
||||
"--ha-dialog-width-lg": cameraAspectRatio
|
||||
? `clamp(var(--ha-dialog-width-md, 580px), calc(var(--video-max-height) * ${cameraAspectRatio}), 1920px)`
|
||||
: undefined,
|
||||
})}
|
||||
@media-size-changed=${this._mediaSizeChanged}
|
||||
@camera-aspect-ratio-changed=${this._cameraAspectRatioChanged}
|
||||
@camera-controls-height-changed=${this._cameraControlsHeightChanged}
|
||||
.accessibleLabel=${title}
|
||||
@closed=${this._dialogClosed}
|
||||
@@ -773,7 +747,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
></ha-icon-button-prev>
|
||||
`
|
||||
}
|
||||
<span slot="headerTitle" class="title">
|
||||
<span slot="headerTitle" @click=${this._enlarge} class="title">
|
||||
${
|
||||
breadcrumb.length > 0
|
||||
? !__DEMO__ && isAdmin
|
||||
@@ -832,10 +806,9 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
></ha-icon-button>
|
||||
|
||||
${
|
||||
domain === "camera" || hasLocation
|
||||
domain === "camera"
|
||||
? html`
|
||||
${downloadSnapshotMenuItem}
|
||||
${directionsMenuItem}
|
||||
<wa-divider></wa-divider>
|
||||
`
|
||||
: nothing
|
||||
@@ -972,7 +945,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
domain === "camera" || hasLocation
|
||||
domain === "camera"
|
||||
? html`
|
||||
<ha-dropdown
|
||||
slot="headerActionItems"
|
||||
@@ -988,7 +961,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
.path=${mdiDotsVertical}
|
||||
></ha-icon-button>
|
||||
${downloadSnapshotMenuItem}
|
||||
${directionsMenuItem}
|
||||
</ha-dropdown>
|
||||
`
|
||||
: nothing
|
||||
@@ -1099,17 +1071,6 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
`;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues) {
|
||||
super.willUpdate(changedProps);
|
||||
// Also when going to a related entity or back. The camera player or image
|
||||
// of the same entity keeps running and doesn't send its size again.
|
||||
if (changedProps.has("_entityId")) {
|
||||
this._mediaAspectRatio = undefined;
|
||||
this._mediaNaturalWidth = undefined;
|
||||
this._cameraControlsHeight = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
this.addEventListener("close-dialog", () => this.closeDialog());
|
||||
@@ -1179,11 +1140,10 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
this._entry = ev.detail;
|
||||
}
|
||||
|
||||
private _mediaSizeChanged(
|
||||
ev: HASSDomEvent<HASSDomEvents["media-size-changed"]>
|
||||
private _cameraAspectRatioChanged(
|
||||
ev: HASSDomEvent<HASSDomEvents["camera-aspect-ratio-changed"]>
|
||||
) {
|
||||
this._mediaAspectRatio = ev.detail.aspectRatio;
|
||||
this._mediaNaturalWidth = ev.detail.naturalWidth;
|
||||
this._cameraAspectRatio = ev.detail.aspectRatio;
|
||||
}
|
||||
|
||||
private _cameraControlsHeightChanged(
|
||||
@@ -1192,6 +1152,12 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
this._cameraControlsHeight = ev.detail.height;
|
||||
}
|
||||
|
||||
private _enlarge() {
|
||||
withViewTransition(() => {
|
||||
this._fill = !this._fill;
|
||||
});
|
||||
}
|
||||
|
||||
private _handleOpened() {
|
||||
window.addEventListener("dialog-closed", this._enableEscapeKeyClose);
|
||||
window.addEventListener("show-dialog", this._disableEscapeKeyClose);
|
||||
@@ -1250,14 +1216,12 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
--dialog-content-padding: 0;
|
||||
}
|
||||
|
||||
/* The dialog's margin, the safe area like the dialog's height limit,
|
||||
its header of about 68px and what the info shows besides the
|
||||
picture */
|
||||
ha-adaptive-dialog.camera,
|
||||
ha-adaptive-dialog.image {
|
||||
--more-info-media-max-height: calc(
|
||||
100vh - var(--ha-space-20) - var(--safe-area-inset-y, 0px) -
|
||||
68px - var(--more-info-media-reserved-height, 0px)
|
||||
/* The dialog's margin, its header of about 68px and the controls
|
||||
below the picture */
|
||||
ha-adaptive-dialog.camera {
|
||||
--video-max-height: calc(
|
||||
100vh - var(--ha-space-20) -
|
||||
68px - var(--more-info-camera-controls-height, 0px)
|
||||
);
|
||||
/* Along with the height of the picture */
|
||||
--ha-dialog-width-transition:
|
||||
@@ -1268,33 +1232,14 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
/* A custom property takes any value, so it can't fall back to the
|
||||
declaration before it. svh like the height limit of the dialog. */
|
||||
@supports (height: 1svh) {
|
||||
ha-adaptive-dialog.camera,
|
||||
ha-adaptive-dialog.image {
|
||||
--more-info-media-max-height: calc(
|
||||
100svh - var(--ha-space-20) - var(--safe-area-inset-y, 0px) -
|
||||
68px - var(--more-info-media-reserved-height, 0px)
|
||||
ha-adaptive-dialog.camera {
|
||||
--video-max-height: calc(
|
||||
100svh - var(--ha-space-20) -
|
||||
68px - var(--more-info-camera-controls-height, 0px)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ha-adaptive-dialog.camera {
|
||||
--more-info-media-reserved-height: var(
|
||||
--more-info-camera-controls-height,
|
||||
0px
|
||||
);
|
||||
--video-max-height: var(--more-info-media-max-height);
|
||||
}
|
||||
|
||||
/* The info's padding around the picture and the entity's row of 40px
|
||||
above it, with 16px between them */
|
||||
ha-adaptive-dialog.image {
|
||||
--more-info-media-reserved-height: calc(
|
||||
var(--ha-space-6) +
|
||||
max(var(--safe-area-inset-bottom, 0px), var(--ha-space-6)) + 56px
|
||||
);
|
||||
--more-info-media-inline-padding: calc(var(--ha-space-6) * 2);
|
||||
}
|
||||
|
||||
.content-wrapper {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
|
||||
@@ -13,6 +13,7 @@ import { fireEvent } from "../../common/dom/fire_event";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../common/dom/fire_event";
|
||||
import "../../components/animation/ha-fade-in";
|
||||
import "../../components/ha-adaptive-dialog";
|
||||
import "../../components/ha-alert";
|
||||
import "../../components/ha-expansion-panel";
|
||||
import "../../components/ha-icon-next";
|
||||
import "../../components/ha-spinner";
|
||||
@@ -20,6 +21,10 @@ import "../../components/item/ha-list-item-button";
|
||||
import type { HaListItemButton } from "../../components/item/ha-list-item-button";
|
||||
import "../../components/list/ha-list-base";
|
||||
import "../../components/progress/ha-progress-bar";
|
||||
import {
|
||||
getBackupState,
|
||||
type BackupManagerState,
|
||||
} from "../../data/backup_manager";
|
||||
import {
|
||||
extractApiErrorMessage,
|
||||
ignoreSupervisorError,
|
||||
@@ -31,14 +36,14 @@ import {
|
||||
shutdownHost,
|
||||
} from "../../data/hassio/host";
|
||||
import { haStyle, haStyleDialog } from "../../resources/styles";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import type { HomeAssistant, ServiceCallRequest } from "../../types";
|
||||
import { HOST_ACTION_TOAST_ID, showToast } from "../../util/toast";
|
||||
import { showAlertDialog } from "../generic/show-dialog-box";
|
||||
import {
|
||||
confirmRestartAction,
|
||||
showRestartConfirmation,
|
||||
type RestartAction,
|
||||
} from "./show-restart-confirmation";
|
||||
showAlertDialog,
|
||||
showConfirmationDialog,
|
||||
} from "../generic/show-dialog-box";
|
||||
import { showRestartWaitDialog } from "./show-dialog-restart";
|
||||
import "./automation-restart-status";
|
||||
|
||||
@customElement("dialog-restart")
|
||||
class DialogRestart extends LitElement {
|
||||
@@ -69,6 +74,15 @@ class DialogRestart extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private async _loadBackupState() {
|
||||
try {
|
||||
return await getBackupState(this.hass);
|
||||
} catch (_err) {
|
||||
// Do nothing
|
||||
return "idle";
|
||||
}
|
||||
}
|
||||
|
||||
private async _loadHostInfo() {
|
||||
this._loadingHostInfo = true;
|
||||
try {
|
||||
@@ -259,16 +273,45 @@ class DialogRestart extends LitElement {
|
||||
duration: 1000,
|
||||
});
|
||||
|
||||
try {
|
||||
await this.hass.callService("homeassistant", "reload_all");
|
||||
} catch (err: any) {
|
||||
showAlertDialog(this, {
|
||||
title: this.hass.localize("ui.dialogs.restart.reload.failed"),
|
||||
text: err.message,
|
||||
});
|
||||
this._restartAction(
|
||||
"homeassistant",
|
||||
"reload_all",
|
||||
this.hass.localize("ui.dialogs.restart.reload.failed")
|
||||
)();
|
||||
}
|
||||
|
||||
private _getBackupProgressMessage(backupState: BackupManagerState) {
|
||||
switch (backupState) {
|
||||
case "create_backup":
|
||||
return this.hass.localize("ui.dialogs.restart.backup_in_progress");
|
||||
case "receive_backup":
|
||||
return this.hass.localize("ui.dialogs.restart.upload_in_progress");
|
||||
case "restore_backup":
|
||||
return this.hass.localize("ui.dialogs.restart.restore_in_progress");
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private _restartAction =
|
||||
(
|
||||
domain: ServiceCallRequest["domain"],
|
||||
service: ServiceCallRequest["service"],
|
||||
errorTitle: string,
|
||||
|
||||
serviceData?: ServiceCallRequest["serviceData"]
|
||||
) =>
|
||||
async () => {
|
||||
try {
|
||||
await this.hass.callService(domain, service, serviceData);
|
||||
} catch (err: any) {
|
||||
showAlertDialog(this, {
|
||||
title: errorTitle,
|
||||
text: err.message,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
private _hostAction =
|
||||
(toastMessage: string, action: "reboot" | "shutdown") => async () => {
|
||||
showToast(this, {
|
||||
@@ -300,32 +343,75 @@ class DialogRestart extends LitElement {
|
||||
};
|
||||
|
||||
private async _handleAction(
|
||||
ev: HASSDomCurrentTargetEvent<HaListItemButton & { action: RestartAction }>
|
||||
ev: HASSDomCurrentTargetEvent<
|
||||
HaListItemButton & {
|
||||
action: "restart" | "reboot" | "shutdown" | "restart-safe-mode";
|
||||
}
|
||||
>
|
||||
) {
|
||||
if (this._loadingBackupInfo) {
|
||||
return;
|
||||
}
|
||||
this._loadingBackupInfo = true;
|
||||
const action = ev.currentTarget.action;
|
||||
try {
|
||||
const confirmed =
|
||||
action === "restart" || action === "restart-safe-mode"
|
||||
? await showRestartConfirmation(this, this.hass, action)
|
||||
: await confirmRestartAction(
|
||||
this,
|
||||
this.hass,
|
||||
action,
|
||||
this._hostAction(
|
||||
this.hass.localize(`ui.dialogs.restart.${action}.action_toast`),
|
||||
action
|
||||
)
|
||||
);
|
||||
if (confirmed) {
|
||||
this._dialogOpen = false;
|
||||
}
|
||||
} finally {
|
||||
this._loadingBackupInfo = false;
|
||||
|
||||
const backupState = await this._loadBackupState();
|
||||
|
||||
const backupProgressMessage = this._getBackupProgressMessage(backupState);
|
||||
|
||||
this._loadingBackupInfo = false;
|
||||
|
||||
const confirmed = await showConfirmationDialog(this, {
|
||||
title: this.hass.localize(`ui.dialogs.restart.${action}.confirm_title`),
|
||||
text: html`${this.hass.localize(
|
||||
`ui.dialogs.restart.${action}.confirm_description`
|
||||
)}${
|
||||
backupProgressMessage
|
||||
? html`<br /><br /><ha-alert>${backupProgressMessage}</ha-alert>`
|
||||
: nothing
|
||||
} <br /><br /><automation-restart-status></automation-restart-status>`,
|
||||
confirmText: this.hass.localize(
|
||||
`ui.dialogs.restart.${action}.confirm_action${backupState === "idle" ? "" : "_backup"}`
|
||||
),
|
||||
destructive: true,
|
||||
});
|
||||
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._dialogOpen = false;
|
||||
|
||||
let actionFunc: () => Promise<void>;
|
||||
|
||||
if (["restart", "restart-safe-mode"].includes(action)) {
|
||||
const serviceData =
|
||||
action === "restart-safe-mode" ? { safe_mode: true } : undefined;
|
||||
actionFunc = this._restartAction(
|
||||
"homeassistant",
|
||||
"restart",
|
||||
this.hass.localize(`ui.dialogs.restart.${action}.failed`),
|
||||
serviceData
|
||||
);
|
||||
} else {
|
||||
actionFunc = this._hostAction(
|
||||
this.hass.localize(
|
||||
`ui.dialogs.restart.${action as "reboot" | "shutdown"}.action_toast`
|
||||
),
|
||||
action as "reboot" | "shutdown"
|
||||
);
|
||||
}
|
||||
|
||||
if (backupState !== "idle") {
|
||||
showRestartWaitDialog(this, {
|
||||
title: this.hass.localize(`ui.dialogs.restart.${action}.title`),
|
||||
initialBackupState: backupState,
|
||||
action: actionFunc,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
actionFunc();
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
import { html, nothing } from "lit";
|
||||
import "../../components/ha-alert";
|
||||
import {
|
||||
getBackupState,
|
||||
type BackupManagerState,
|
||||
} from "../../data/backup_manager";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import {
|
||||
showAlertDialog,
|
||||
showConfirmationDialog,
|
||||
} from "../generic/show-dialog-box";
|
||||
import "./automation-restart-status";
|
||||
import { showRestartWaitDialog } from "./show-dialog-restart";
|
||||
|
||||
export type RestartAction =
|
||||
"restart" | "reboot" | "shutdown" | "restart-safe-mode";
|
||||
type ConfirmationContext = Pick<HomeAssistant, "connection" | "localize">;
|
||||
|
||||
function getBackupProgressMessage(
|
||||
localize: HomeAssistant["localize"],
|
||||
backupState: BackupManagerState
|
||||
) {
|
||||
switch (backupState) {
|
||||
case "create_backup":
|
||||
return localize("ui.dialogs.restart.backup_in_progress");
|
||||
case "receive_backup":
|
||||
return localize("ui.dialogs.restart.upload_in_progress");
|
||||
case "restore_backup":
|
||||
return localize("ui.dialogs.restart.restore_in_progress");
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export async function confirmRestartAction(
|
||||
element: HTMLElement,
|
||||
hass: ConfirmationContext,
|
||||
action: RestartAction,
|
||||
run: () => Promise<void>
|
||||
) {
|
||||
const backupState = await getBackupState(hass).catch(() => "idle" as const);
|
||||
const backupProgressMessage = getBackupProgressMessage(
|
||||
hass.localize,
|
||||
backupState
|
||||
);
|
||||
const confirmed = await showConfirmationDialog(element, {
|
||||
title: hass.localize(`ui.dialogs.restart.${action}.confirm_title`),
|
||||
text: html`${hass.localize(
|
||||
`ui.dialogs.restart.${action}.confirm_description`
|
||||
)}${
|
||||
backupProgressMessage
|
||||
? html`<br /><br /><ha-alert>${backupProgressMessage}</ha-alert>`
|
||||
: nothing
|
||||
} <br /><br /><automation-restart-status></automation-restart-status>`,
|
||||
confirmText: hass.localize(
|
||||
`ui.dialogs.restart.${action}.confirm_action${backupState === "idle" ? "" : "_backup"}`
|
||||
),
|
||||
destructive: true,
|
||||
});
|
||||
|
||||
if (!confirmed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (backupState !== "idle") {
|
||||
showRestartWaitDialog(element, {
|
||||
title: hass.localize(`ui.dialogs.restart.${action}.title`),
|
||||
initialBackupState: backupState,
|
||||
action: run,
|
||||
});
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function showRestartConfirmation(
|
||||
element: HTMLElement,
|
||||
hass: ConfirmationContext & Pick<HomeAssistant, "callService">,
|
||||
action: "restart" | "restart-safe-mode" = "restart"
|
||||
) {
|
||||
return confirmRestartAction(element, hass, action, async () => {
|
||||
try {
|
||||
await hass.callService(
|
||||
"homeassistant",
|
||||
"restart",
|
||||
action === "restart-safe-mode" ? { safe_mode: true } : undefined
|
||||
);
|
||||
} catch (err: any) {
|
||||
showAlertDialog(element, {
|
||||
title: hass.localize(`ui.dialogs.restart.${action}.failed`),
|
||||
text: err.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -158,7 +158,7 @@ class DialogEditSidebar extends DirtyStateProviderMixin<SidebarState>()(
|
||||
].map<DisplayItem>((panel) => ({
|
||||
value: panel.url_path,
|
||||
label:
|
||||
(getPanelTitle(this.hass.localize, panel) || panel.url_path) +
|
||||
(getPanelTitle(this.hass, panel) || panel.url_path) +
|
||||
`${defaultPanel === panel.url_path ? ` (${this.hass.localize("ui.sidebar.default")})` : ""}`,
|
||||
icon: getPanelIcon(panel),
|
||||
iconPath: getPanelIconPath(panel),
|
||||
|
||||
@@ -145,9 +145,7 @@ export class HaVoiceAssistantSetupDialog extends LitElement {
|
||||
return html`
|
||||
<ha-dialog
|
||||
.open=${this._open}
|
||||
header-title=${this.hass.localize(
|
||||
"ui.panel.config.voice_assistants.satellite_wizard.title"
|
||||
)}
|
||||
header-title="Voice Satellite setup"
|
||||
prevent-scrim-close
|
||||
@closed=${this._dialogClosed}
|
||||
>
|
||||
|
||||
@@ -2,10 +2,4 @@ import "@webcomponents/scoped-custom-element-registry/scoped-custom-element-regi
|
||||
import "../resources/scoped-registry-ready";
|
||||
import "../layouts/home-assistant";
|
||||
|
||||
// Custom cards and plugins can reach the helpers on any page, not only once a
|
||||
// dashboard has loaded.
|
||||
Object.assign(window, {
|
||||
loadCardHelpers: () => import("../panels/lovelace/custom-card-helpers"),
|
||||
});
|
||||
|
||||
import("../resources/append-ha-style");
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import { loadTokens, saveTokens } from "../common/auth/token_storage";
|
||||
import { hassUrl } from "../data/auth";
|
||||
import { isExternal } from "../data/external";
|
||||
import { subscribeFrontendUserData } from "../data/frontend";
|
||||
import { fetchConfig } from "../data/lovelace/config/types";
|
||||
import { fetchResources } from "../data/lovelace/resource";
|
||||
import { MAIN_WINDOW_NAME } from "../data/main_window";
|
||||
@@ -177,7 +178,7 @@ window.hassConnection.then(({ conn }) => {
|
||||
const noop = () => {
|
||||
// do nothing
|
||||
};
|
||||
subscribeEntities(conn, noop, { batchUpdates: true });
|
||||
subscribeEntities(conn, noop);
|
||||
subscribeEntityRegistryDisplay(conn, noop);
|
||||
subscribeDeviceRegistry(conn, noop);
|
||||
subscribeAreaRegistry(conn, noop);
|
||||
@@ -187,6 +188,7 @@ window.hassConnection.then(({ conn }) => {
|
||||
subscribePanels(conn, noop);
|
||||
subscribeThemes(conn, noop);
|
||||
subscribeUser(conn, noop);
|
||||
subscribeFrontendUserData(conn, "core", noop);
|
||||
subscribeRepairsIssueRegistry(conn, noop);
|
||||
|
||||
const preloadWindow = window as WindowWithPreloads;
|
||||
|
||||
@@ -1,9 +1,21 @@
|
||||
import { supportsFeatureFromAttributes } from "../../common/entity/supports-feature";
|
||||
import { ClimateEntityFeature } from "../../data/climate";
|
||||
import {
|
||||
CLIMATE_HVAC_ACTION_TO_MODE,
|
||||
ClimateEntityFeature,
|
||||
} from "../../data/climate";
|
||||
import type { HvacAction } from "../../data/climate";
|
||||
import { MockBaseEntity } from "./base-entity";
|
||||
import type { EntityAttributes } from "./types";
|
||||
|
||||
// Reverse mapping: mode → action (e.g. "cool" → "cooling")
|
||||
const HVAC_MODE_TO_ACTION: Partial<Record<string, HvacAction>> =
|
||||
Object.fromEntries(
|
||||
Object.entries(CLIMATE_HVAC_ACTION_TO_MODE).map(([action, mode]) => [
|
||||
mode,
|
||||
action as HvacAction,
|
||||
])
|
||||
);
|
||||
|
||||
export class MockClimateEntity extends MockBaseEntity {
|
||||
public async handleService(
|
||||
domain: string,
|
||||
@@ -231,13 +243,10 @@ export class MockClimateEntity extends MockBaseEntity {
|
||||
return "off";
|
||||
}
|
||||
|
||||
// Heat and cool get their action from the temperatures below
|
||||
if (state === "dry") {
|
||||
return "drying";
|
||||
}
|
||||
|
||||
if (state === "fan_only") {
|
||||
return "fan";
|
||||
// Use the reverse mapping for direct mode → action (e.g. "fan_only" → "fan", "dry" → "drying")
|
||||
const directAction = HVAC_MODE_TO_ACTION[state];
|
||||
if (directAction && directAction !== "idle" && directAction !== "off") {
|
||||
return directAction;
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -267,17 +276,13 @@ export class MockClimateEntity extends MockBaseEntity {
|
||||
const current = attrs.current_temperature;
|
||||
const lowTarget = attrs.target_temp_low;
|
||||
const highTarget = attrs.target_temp_high;
|
||||
// Heat mode can only heat and cool mode only cool, while auto and
|
||||
// heat_cool use both ends of the range
|
||||
if (current != null) {
|
||||
if (state !== "cool" && lowTarget != null && lowTarget > current) {
|
||||
if (lowTarget != null && lowTarget > current) {
|
||||
return "heating";
|
||||
}
|
||||
|
||||
if (state !== "heat" && highTarget != null && highTarget < current) {
|
||||
if (highTarget != null && highTarget < current) {
|
||||
return "cooling";
|
||||
}
|
||||
|
||||
return "idle";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -607,22 +607,6 @@ export const ENTITY_COMPONENT_ICONS: Record<string, ComponentIcons> = {
|
||||
atmospheric_pressure: {
|
||||
default: "mdi:thermometer-lines",
|
||||
},
|
||||
battery: {
|
||||
default: "mdi:battery-unknown",
|
||||
range: {
|
||||
"0": "mdi:battery-alert",
|
||||
"10": "mdi:battery-10",
|
||||
"20": "mdi:battery-20",
|
||||
"30": "mdi:battery-30",
|
||||
"40": "mdi:battery-40",
|
||||
"50": "mdi:battery-50",
|
||||
"60": "mdi:battery-60",
|
||||
"70": "mdi:battery-70",
|
||||
"80": "mdi:battery-80",
|
||||
"90": "mdi:battery-90",
|
||||
"100": "mdi:battery",
|
||||
},
|
||||
},
|
||||
carbon_dioxide: {
|
||||
default: "mdi:molecule-co2",
|
||||
},
|
||||
|
||||
@@ -27,12 +27,6 @@ import {
|
||||
import { updateHassGroups } from "../data/context/updateContext";
|
||||
import type { IconCategory } from "../data/icons";
|
||||
import type { EntityRegistryDisplayEntry } from "../data/entity/entity_registry";
|
||||
import { evaluateConditionsLocally } from "../common/condition/evaluate-locally";
|
||||
import {
|
||||
isLogicalCondition,
|
||||
logicalChildren,
|
||||
} from "../common/condition/translate";
|
||||
import type { VisibilityCondition } from "../panels/lovelace/common/validate-condition";
|
||||
import {
|
||||
DateFormat,
|
||||
FirstWeekday,
|
||||
@@ -59,24 +53,6 @@ import type { EntityInput } from "./entities/types";
|
||||
const ensureArray = <T>(val: T | T[]): T[] =>
|
||||
Array.isArray(val) ? val : [val];
|
||||
|
||||
// Core's `not` passes when none of its conditions pass, and the frontend's
|
||||
// unless all of them pass, so each `not` gets one `or` of its conditions
|
||||
const withCoreNot = (condition: VisibilityCondition): VisibilityCondition => {
|
||||
if (!isLogicalCondition(condition) || condition.conditions === undefined) {
|
||||
return condition;
|
||||
}
|
||||
|
||||
const conditions = logicalChildren(condition).map(withCoreNot);
|
||||
|
||||
return {
|
||||
...condition,
|
||||
conditions:
|
||||
condition.condition === "not"
|
||||
? [{ condition: "or", conditions }]
|
||||
: conditions,
|
||||
};
|
||||
};
|
||||
|
||||
type MockServiceCallback = (
|
||||
data: Record<string, any> | undefined,
|
||||
target: Record<string, any> | undefined,
|
||||
@@ -245,8 +221,6 @@ export const provideHass = (
|
||||
return lazyLoaderPromise;
|
||||
};
|
||||
const eventListeners: Record<string, ((event) => void)[]> = {};
|
||||
// Checks each subscribed condition again, for when the states change.
|
||||
const conditionChecks = new Set<() => void>();
|
||||
const entities = {};
|
||||
let localResources: Resources = {};
|
||||
|
||||
@@ -690,51 +664,6 @@ export const provideHass = (
|
||||
resources: category === "entity_component" ? ENTITY_COMPONENT_ICONS : {},
|
||||
}));
|
||||
|
||||
// Core answers the visibility conditions of cards and rows that depend on
|
||||
// states. Here they are checked against the mock states, as the frontend
|
||||
// does itself before Core answers, and again each time the states change.
|
||||
// A condition only Core can check, such as a template, gets an error, so
|
||||
// a `not` around it can't show the card.
|
||||
hassObj.mockWS(
|
||||
"subscribe_condition",
|
||||
({ condition }: { condition: VisibilityCondition }, _hass, onChange) => {
|
||||
const check = () => {
|
||||
const result = evaluateConditionsLocally(
|
||||
[withCoreNot(condition)],
|
||||
hass(),
|
||||
{}
|
||||
);
|
||||
|
||||
onChange?.(
|
||||
result === undefined
|
||||
? {
|
||||
error: {
|
||||
code: "not_supported",
|
||||
message: "The demo can't check this condition",
|
||||
},
|
||||
}
|
||||
: { result }
|
||||
);
|
||||
};
|
||||
|
||||
conditionChecks.add(check);
|
||||
check();
|
||||
|
||||
return () => conditionChecks.delete(check);
|
||||
}
|
||||
);
|
||||
|
||||
// Check the conditions again after each state update, also when the host
|
||||
// passed its own updateHass, as the demo does
|
||||
const applyUpdate = hassObj.updateHass;
|
||||
hassObj.updateHass = (obj: Partial<MockHomeAssistant>) => {
|
||||
applyUpdate(obj);
|
||||
|
||||
if (obj.states) {
|
||||
conditionChecks.forEach((check) => check());
|
||||
}
|
||||
};
|
||||
|
||||
// Set hass if required
|
||||
if (setHassProperty) {
|
||||
elements.forEach((el) => {
|
||||
|
||||
@@ -352,12 +352,7 @@ class OnboardingLocation extends LitElement {
|
||||
}
|
||||
);
|
||||
try {
|
||||
this._places = await searchPlaces(
|
||||
address,
|
||||
this.hass.locale.language,
|
||||
true,
|
||||
3
|
||||
);
|
||||
this._places = await searchPlaces(address, this.hass, true, 3);
|
||||
if (this._places?.length) {
|
||||
this._highlightedMarker = this._places[0].place_id;
|
||||
this._location = [
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-code-editor";
|
||||
import "../../../components/ha-dialog";
|
||||
import { DialogMixin } from "../../../dialogs/dialog-mixin";
|
||||
import type { BlueprintContentDialogParams } from "./show-dialog-blueprint-content";
|
||||
|
||||
@customElement("dialog-blueprint-content")
|
||||
class DialogBlueprintContent extends DialogMixin<BlueprintContentDialogParams>(
|
||||
LitElement
|
||||
) {
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
protected render() {
|
||||
if (!this.params) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<ha-dialog
|
||||
open
|
||||
width="full"
|
||||
flexcontent
|
||||
header-title=${this._localize(
|
||||
"ui.panel.config.blueprint.add.raw_blueprint"
|
||||
)}
|
||||
header-subtitle=${this.params.name}
|
||||
>
|
||||
<ha-code-editor
|
||||
mode="yaml"
|
||||
.value=${this.params.content}
|
||||
read-only
|
||||
in-dialog
|
||||
dir="ltr"
|
||||
></ha-code-editor>
|
||||
</ha-dialog>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
ha-dialog {
|
||||
--dialog-content-padding: 0;
|
||||
}
|
||||
/* A grid, so that the editor fills the height and scrolls inside */
|
||||
ha-code-editor {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"dialog-blueprint-content": DialogBlueprintContent;
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
import "@home-assistant/components/card";
|
||||
import { mdiClose, mdiCodeBraces, mdiOpenInNew } from "@mdi/js";
|
||||
import { mdiClose, mdiOpenInNew } from "@mdi/js";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { withViewTransition } from "../../../common/util/view-transition";
|
||||
import "../../../components/ha-alert";
|
||||
import "../../../components/ha-button";
|
||||
import "../../../components/ha-code-editor";
|
||||
import "../../../components/ha-dialog";
|
||||
import "../../../components/ha-dialog-footer";
|
||||
import "../../../components/ha-dialog-header";
|
||||
import "../../../components/ha-expansion-panel";
|
||||
import "../../../components/ha-markdown";
|
||||
import "../../../components/ha-spinner";
|
||||
import "../../../components/input/ha-input";
|
||||
@@ -19,7 +21,6 @@ import { DirtyStateProviderMixin } from "../../../mixins/dirty-state-provider-mi
|
||||
import { haStyleDialog } from "../../../resources/styles";
|
||||
import type { HomeAssistant } from "../../../types";
|
||||
import { documentationUrl } from "../../../util/documentation-url";
|
||||
import { showBlueprintContentDialog } from "./show-dialog-blueprint-content";
|
||||
|
||||
interface BlueprintImportState {
|
||||
value: string;
|
||||
@@ -32,6 +33,8 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
) {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ type: Boolean, reflect: true }) public large = false;
|
||||
|
||||
@state() private _params?;
|
||||
|
||||
@state() private _open = false;
|
||||
@@ -55,6 +58,7 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
this._error = undefined;
|
||||
this._url = this._params.url;
|
||||
this._sourceUrlWarning = !this._isTrustedBlueprintUrl(this._url);
|
||||
this.large = false;
|
||||
this._open = true;
|
||||
this._initDirtyTracking(
|
||||
{ type: "shallow" },
|
||||
@@ -84,6 +88,7 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
<ha-dialog
|
||||
.open=${this._open}
|
||||
.accessibleLabel=${heading}
|
||||
width=${this.large ? "full" : "medium"}
|
||||
.preventScrimClose=${this.isDirtyState}
|
||||
@closed=${this._dialogClosed}
|
||||
>
|
||||
@@ -94,7 +99,9 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
.label=${this.hass.localize("ui.common.close")}
|
||||
.path=${mdiClose}
|
||||
></ha-icon-button>
|
||||
<span slot="title">${heading}</span>
|
||||
<span slot="title" class="title-enlargeable" @click=${this._enlarge}>
|
||||
${heading}
|
||||
</span>
|
||||
</ha-dialog-header>
|
||||
<div>
|
||||
${
|
||||
@@ -157,37 +164,18 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
></ha-input>
|
||||
`
|
||||
}
|
||||
<hac-card class="content-card">
|
||||
<div class="content-row">
|
||||
<div class="content-text">
|
||||
<span>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.raw_blueprint"
|
||||
)}
|
||||
</span>
|
||||
<span class="content-description">
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.raw_blueprint_description"
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<ha-button
|
||||
appearance="filled"
|
||||
.accessibleLabel=${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.view_raw_blueprint_label"
|
||||
)}
|
||||
@click=${this._showContent}
|
||||
>
|
||||
<ha-svg-icon
|
||||
slot="start"
|
||||
.path=${mdiCodeBraces}
|
||||
></ha-svg-icon>
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.view_raw_blueprint"
|
||||
)}
|
||||
</ha-button>
|
||||
</div>
|
||||
</hac-card>
|
||||
<ha-expansion-panel
|
||||
.header=${this.hass.localize(
|
||||
"ui.panel.config.blueprint.add.raw_blueprint"
|
||||
)}
|
||||
>
|
||||
<ha-code-editor
|
||||
mode="yaml"
|
||||
.value=${this._result.raw_data}
|
||||
read-only
|
||||
dir="ltr"
|
||||
></ha-code-editor>
|
||||
</ha-expansion-panel>
|
||||
${
|
||||
this._result?.exists
|
||||
? html`
|
||||
@@ -287,10 +275,9 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
`;
|
||||
}
|
||||
|
||||
private _showContent() {
|
||||
showBlueprintContentDialog(this, {
|
||||
name: this._result!.blueprint.metadata.name,
|
||||
content: this._result!.raw_data,
|
||||
private _enlarge() {
|
||||
withViewTransition(() => {
|
||||
this.large = !this.large;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -397,23 +384,11 @@ class DialogImportBlueprint extends DirtyStateProviderMixin<BlueprintImportState
|
||||
a ha-svg-icon {
|
||||
--mdc-icon-size: 16px;
|
||||
}
|
||||
.content-card {
|
||||
margin: var(--ha-space-6) 0 var(--ha-space-2);
|
||||
ha-expansion-panel {
|
||||
--expansion-panel-content-padding: 0px;
|
||||
}
|
||||
.content-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-4);
|
||||
}
|
||||
.content-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.content-description {
|
||||
font-size: var(--ha-font-size-s);
|
||||
color: var(--secondary-text-color);
|
||||
.title-enlargeable {
|
||||
display: block;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
|
||||
export interface BlueprintContentDialogParams {
|
||||
name: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export const loadBlueprintContentDialog = () =>
|
||||
import("./dialog-blueprint-content");
|
||||
|
||||
export const showBlueprintContentDialog = (
|
||||
element: HTMLElement,
|
||||
dialogParams: BlueprintContentDialogParams
|
||||
): void => {
|
||||
fireEvent(element, "show-dialog", {
|
||||
dialogTag: "dialog-blueprint-content",
|
||||
dialogImport: loadBlueprintContentDialog,
|
||||
dialogParams,
|
||||
});
|
||||
};
|
||||
@@ -86,7 +86,6 @@ export class HaCategoryPicker extends LitElement {
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._unsubscribeCategories();
|
||||
this._categories = undefined;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProperties: PropertyValues) {
|
||||
|
||||
@@ -1,386 +0,0 @@
|
||||
import { mdiCashClock, mdiDelete, mdiPlus } from "@mdi/js";
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { HassEntities } from "home-assistant-js-websocket";
|
||||
import type { CSSResultGroup, TemplateResult } from "lit";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import { preserveUnchangedEntityStatesRecord } from "../../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../../common/decorators/transform";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { stopPropagation } from "../../../../common/dom/stop_propagation";
|
||||
import { formatNumber } from "../../../../common/number/format_number";
|
||||
import "../../../../components/automation/ha-automation-row";
|
||||
import "../../../../components/ha-button";
|
||||
import "../../../../components/ha-card";
|
||||
import "../../../../components/ha-icon-button";
|
||||
import "../../../../components/ha-svg-icon";
|
||||
import {
|
||||
configContext,
|
||||
formattersContext,
|
||||
internationalizationContext,
|
||||
statesContext,
|
||||
} from "../../../../data/context";
|
||||
import type {
|
||||
EnergyPreferences,
|
||||
EnergyPreferencesValidation,
|
||||
EnergyValidationIssue,
|
||||
FixedCostEnergyPreference,
|
||||
FixedCostType,
|
||||
} from "../../../../data/energy";
|
||||
import { saveEnergyPreferences } from "../../../../data/energy";
|
||||
import { getStatisticLabel } from "../../../../data/recorder";
|
||||
import {
|
||||
showAlertDialog,
|
||||
showConfirmationDialog,
|
||||
} from "../../../../dialogs/generic/show-dialog-box";
|
||||
import { haStyle } from "../../../../resources/styles";
|
||||
import type {
|
||||
HomeAssistant,
|
||||
HomeAssistantConfig,
|
||||
HomeAssistantFormatters,
|
||||
} from "../../../../types";
|
||||
import { showEnergySettingsDialog } from "../dialogs/show-dialogs-energy";
|
||||
import type { EnergyEditorConfig } from "../editors/energy-editor";
|
||||
import "../ha-energy-editor-page";
|
||||
import type { EnergyEditorPageConfig } from "../ha-energy-editor-page";
|
||||
import "./ha-energy-validation-result";
|
||||
import { energyCardStyles } from "./styles";
|
||||
|
||||
type CostElement = HTMLElement & { cost: FixedCostEnergyPreference };
|
||||
|
||||
@customElement("ha-energy-fixed-cost-settings")
|
||||
export class EnergyFixedCostSettings extends LitElement {
|
||||
@property({ attribute: false }) public hass!: HomeAssistant;
|
||||
|
||||
@property({ attribute: false }) public type!: FixedCostType;
|
||||
|
||||
@property({ attribute: false })
|
||||
public preferences!: EnergyPreferences;
|
||||
|
||||
@property({ attribute: false })
|
||||
public validationResult?: EnergyPreferencesValidation;
|
||||
|
||||
/** Path of the list page, editors open on pages under it instead of dialogs */
|
||||
@property({ attribute: false }) public listPath?: string;
|
||||
|
||||
/** Shows the editor page of the item with this key, or `new` to add one */
|
||||
@property({ attribute: false }) public editKey?: string;
|
||||
|
||||
@property({ type: Boolean }) public narrow = false;
|
||||
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, string>({
|
||||
transformer: ({ config }) => config.currency,
|
||||
})
|
||||
private _currency!: string;
|
||||
|
||||
@state()
|
||||
@consume({ context: formattersContext, subscribe: true })
|
||||
@transform<
|
||||
HomeAssistantFormatters,
|
||||
HomeAssistantFormatters["formatEntityName"]
|
||||
>({
|
||||
transformer: ({ formatEntityName }) => formatEntityName,
|
||||
})
|
||||
private _formatEntityName!: HomeAssistantFormatters["formatEntityName"];
|
||||
|
||||
// Only the amount entities, so other state changes don't render
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
@transform<HassEntities, HassEntities>({
|
||||
transformer: function (this: EnergyFixedCostSettings, states) {
|
||||
const amountStates: HassEntities = {};
|
||||
for (const cost of this._costs()) {
|
||||
const entityId = cost.entity_amount;
|
||||
if (entityId && states?.[entityId]) {
|
||||
amountStates[entityId] = states[entityId];
|
||||
}
|
||||
}
|
||||
return preserveUnchangedEntityStatesRecord(
|
||||
this._amountStates,
|
||||
amountStates
|
||||
);
|
||||
},
|
||||
watch: ["preferences", "type"],
|
||||
})
|
||||
private _amountStates?: HassEntities;
|
||||
|
||||
protected render(): TemplateResult {
|
||||
if (this.listPath && this.editKey !== undefined) {
|
||||
return html`<ha-energy-editor-page
|
||||
.hass=${this.hass}
|
||||
.narrow=${this.narrow}
|
||||
.backPath=${this.listPath}
|
||||
.config=${this._editorPage(this.editKey, this.type)}
|
||||
></ha-energy-editor-page>`;
|
||||
}
|
||||
|
||||
const costs: FixedCostEnergyPreference[] = [];
|
||||
const validation: EnergyValidationIssue[][] = [];
|
||||
|
||||
this.preferences.fixed_costs.forEach((cost, idx) => {
|
||||
if (cost.type !== this.type) {
|
||||
return;
|
||||
}
|
||||
costs.push(cost);
|
||||
|
||||
const issues = this.validationResult?.fixed_costs[idx];
|
||||
if (issues) {
|
||||
validation.push(issues);
|
||||
}
|
||||
});
|
||||
|
||||
return html`
|
||||
<ha-card>
|
||||
<h1 class="card-header">
|
||||
<ha-svg-icon .path=${mdiCashClock}></ha-svg-icon>
|
||||
${this._i18n.localize("ui.panel.config.energy.fixed_costs.title")}
|
||||
</h1>
|
||||
|
||||
<div class="card-content">
|
||||
<p>
|
||||
${this._i18n.localize("ui.panel.config.energy.fixed_costs.sub")}
|
||||
</p>
|
||||
${validation.map(
|
||||
(issues) => html`
|
||||
<ha-energy-validation-result
|
||||
.hass=${this.hass}
|
||||
.issues=${issues}
|
||||
></ha-energy-validation-result>
|
||||
`
|
||||
)}
|
||||
${
|
||||
costs.length > 0
|
||||
? html`
|
||||
<div class="items">
|
||||
${costs.map(
|
||||
(cost) => html`
|
||||
<ha-card outlined>
|
||||
<ha-automation-row
|
||||
.cost=${cost}
|
||||
.href=${this._editorHref(cost)}
|
||||
@click=${this.listPath ? nothing : this._editCost}
|
||||
>
|
||||
<ha-svg-icon
|
||||
slot="leading-icon"
|
||||
.path=${mdiCashClock}
|
||||
></ha-svg-icon>
|
||||
<div slot="header" class="row-header">
|
||||
<span class="label">${cost.name}</span>
|
||||
<span class="label secondary"
|
||||
>${this._amountPerPeriod(cost)}</span
|
||||
>
|
||||
</div>
|
||||
<ha-icon-button
|
||||
slot="icons"
|
||||
.label=${this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.delete_fixed_cost"
|
||||
)}
|
||||
.path=${mdiDelete}
|
||||
.cost=${cost}
|
||||
@click=${this._deleteCostClicked}
|
||||
@keydown=${stopPropagation}
|
||||
></ha-icon-button>
|
||||
</ha-automation-row>
|
||||
</ha-card>
|
||||
`
|
||||
)}
|
||||
</div>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
<ha-button
|
||||
.href=${this._editorHref()}
|
||||
@click=${this.listPath ? nothing : this._addCost}
|
||||
appearance="filled"
|
||||
size="s"
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiPlus}></ha-svg-icon>
|
||||
${this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.add_fixed_cost"
|
||||
)}
|
||||
</ha-button>
|
||||
</div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
private _costs(): FixedCostEnergyPreference[] {
|
||||
return (this.preferences?.fixed_costs ?? []).filter(
|
||||
(cost) => cost.type === this.type
|
||||
);
|
||||
}
|
||||
|
||||
private _amountPerPeriod(cost: FixedCostEnergyPreference): string {
|
||||
const amount = cost.entity_amount
|
||||
? getStatisticLabel(
|
||||
this._amountStates ?? {},
|
||||
this._formatEntityName,
|
||||
cost.entity_amount,
|
||||
undefined
|
||||
)
|
||||
: formatNumber(cost.number_amount ?? 0, this._i18n.locale, {
|
||||
style: "currency",
|
||||
currency: this._currency,
|
||||
});
|
||||
return this._i18n.localize(
|
||||
`ui.panel.config.energy.fixed_costs.amount_per_period.${cost.period}`,
|
||||
{ amount }
|
||||
);
|
||||
}
|
||||
|
||||
private _addCost() {
|
||||
this._openEditor();
|
||||
}
|
||||
|
||||
private _editCost(ev: HASSDomCurrentTargetEvent<CostElement>) {
|
||||
this._openEditor(ev.currentTarget.cost);
|
||||
}
|
||||
|
||||
private _openEditor(cost?: FixedCostEnergyPreference) {
|
||||
showEnergySettingsDialog(this, {
|
||||
editor: this._editorConfig(this.type, cost),
|
||||
});
|
||||
}
|
||||
|
||||
private _editorHref(cost?: FixedCostEnergyPreference) {
|
||||
return this.listPath
|
||||
? `${this.listPath}/fixed_cost/${cost ? encodeURIComponent(cost.id) : "new"}`
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private _editorConfig(
|
||||
type: FixedCostType,
|
||||
cost?: FixedCostEnergyPreference
|
||||
): EnergyEditorConfig {
|
||||
return {
|
||||
kind: "fixed_cost",
|
||||
params: {
|
||||
cost: cost ? { ...cost } : undefined,
|
||||
type,
|
||||
saveCallback: (newCost) => this._saveCost(newCost),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private _costIndex(cost: FixedCostEnergyPreference) {
|
||||
return this.preferences.fixed_costs.findIndex(
|
||||
(item) => item.id === cost.id
|
||||
);
|
||||
}
|
||||
|
||||
// Kept per item: a save replaces the preferences right before the page leaves
|
||||
private _editorPage = memoizeOne(
|
||||
(key: string, type: FixedCostType): EnergyEditorPageConfig | undefined => {
|
||||
if (key === "new") {
|
||||
return this._pageConfig(this._editorConfig(type));
|
||||
}
|
||||
const cost = this._costs().find((item) => item.id === key);
|
||||
return cost && this._pageConfig(this._editorConfig(type, cost), cost);
|
||||
}
|
||||
);
|
||||
|
||||
private _pageConfig(
|
||||
editor: EnergyEditorConfig,
|
||||
cost?: FixedCostEnergyPreference
|
||||
): EnergyEditorPageConfig {
|
||||
if (!cost) {
|
||||
return {
|
||||
editor,
|
||||
title: this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.add_fixed_cost"
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
editor,
|
||||
title: cost.name,
|
||||
delete: {
|
||||
label: this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.delete_fixed_cost"
|
||||
),
|
||||
action: () => this._deleteCost(cost),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async _saveCost(cost: FixedCostEnergyPreference) {
|
||||
const costs = [...this.preferences.fixed_costs];
|
||||
const index = this._costIndex(cost);
|
||||
if (index === -1) {
|
||||
costs.push(cost);
|
||||
} else {
|
||||
costs[index] = cost;
|
||||
}
|
||||
await this._savePreferences({ ...this.preferences, fixed_costs: costs });
|
||||
}
|
||||
|
||||
private _deleteCostClicked(ev: HASSDomCurrentTargetEvent<CostElement>) {
|
||||
ev.stopPropagation();
|
||||
this._deleteCost(ev.currentTarget.cost);
|
||||
}
|
||||
|
||||
private async _deleteCost(cost: FixedCostEnergyPreference): Promise<boolean> {
|
||||
if (
|
||||
!(await showConfirmationDialog(this, {
|
||||
title: this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.delete_confirm_title"
|
||||
),
|
||||
text: this._i18n.localize(
|
||||
"ui.panel.config.energy.fixed_costs.delete_confirm_text",
|
||||
{ name: cost.name }
|
||||
),
|
||||
confirmText: this._i18n.localize("ui.common.delete"),
|
||||
destructive: true,
|
||||
}))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const index = this._costIndex(cost);
|
||||
if (index === -1) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await this._savePreferences({
|
||||
...this.preferences,
|
||||
fixed_costs: this.preferences.fixed_costs.filter(
|
||||
(_cost, idx) => idx !== index
|
||||
),
|
||||
});
|
||||
} catch (err: any) {
|
||||
showAlertDialog(this, {
|
||||
title: this._i18n.localize(
|
||||
"ui.panel.config.energy.save_config_failed",
|
||||
{ error: err.message }
|
||||
),
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private async _savePreferences(preferences: EnergyPreferences) {
|
||||
const result = await saveEnergyPreferences(this.hass, preferences);
|
||||
fireEvent(this, "value-changed", { value: result });
|
||||
return result;
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return [haStyle, energyCardStyles];
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-energy-fixed-cost-settings": EnergyFixedCostSettings;
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,6 @@ const HEADERS = {
|
||||
water: "ui.panel.config.energy.device_consumption_water.dialog.header",
|
||||
gas: "ui.panel.config.energy.device_consumption_gas.dialog.header",
|
||||
},
|
||||
fixed_cost: "ui.panel.config.energy.fixed_costs.dialog.header",
|
||||
} as const;
|
||||
|
||||
@customElement("dialog-energy-settings")
|
||||
|
||||
@@ -9,8 +9,6 @@ import type {
|
||||
DeviceConsumptionEnergyPreference,
|
||||
EnergyGasUnitClass,
|
||||
EnergyInfo,
|
||||
FixedCostEnergyPreference,
|
||||
FixedCostType,
|
||||
GasSourceTypeEnergyPreference,
|
||||
GridSourceTypeEnergyPreference,
|
||||
HomeSourceTypeEnergyPreference,
|
||||
@@ -79,12 +77,6 @@ export interface EnergyWaterGasDeviceEditorParams extends EnergyDeviceEditorPara
|
||||
allowedUnitClass?: EnergyGasUnitClass;
|
||||
}
|
||||
|
||||
export interface EnergyFixedCostEditorParams {
|
||||
cost?: FixedCostEnergyPreference;
|
||||
type: FixedCostType;
|
||||
saveCallback: (cost: FixedCostEnergyPreference) => Promise<void>;
|
||||
}
|
||||
|
||||
export type EnergyEditorConfig =
|
||||
| { kind: "grid"; params: EnergyGridSourceEditorParams }
|
||||
| { kind: "solar"; params: EnergySolarSourceEditorParams }
|
||||
@@ -93,8 +85,7 @@ export type EnergyEditorConfig =
|
||||
| { kind: "device"; params: EnergyDeviceEditorParams }
|
||||
| { kind: "gas"; params: EnergyGasSourceEditorParams }
|
||||
| { kind: "water"; params: EnergyWaterSourceEditorParams }
|
||||
| { kind: "water_gas_device"; params: EnergyWaterGasDeviceEditorParams }
|
||||
| { kind: "fixed_cost"; params: EnergyFixedCostEditorParams };
|
||||
| { kind: "water_gas_device"; params: EnergyWaterGasDeviceEditorParams };
|
||||
|
||||
type PreselectedStatistic =
|
||||
(typeof energyEditorQueryParamConfig)["string"][number];
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consume } from "../../../../common/decorators/consume";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../../common/decorators/transform";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/entity/ha-entity-picker";
|
||||
import "../../../../components/ha-alert";
|
||||
import "../../../../components/ha-markdown";
|
||||
import "../../../../components/ha-select";
|
||||
import type {
|
||||
HaSelectOption,
|
||||
HaSelectSelectEvent,
|
||||
} from "../../../../components/ha-select";
|
||||
import "../../../../components/input/ha-input";
|
||||
import type { HaInput } from "../../../../components/input/ha-input";
|
||||
import { configContext } from "../../../../data/context";
|
||||
import type {
|
||||
FixedCostEnergyPreference,
|
||||
FixedCostPeriod,
|
||||
} from "../../../../data/energy";
|
||||
import { emptyFixedCostEnergyPreference } from "../../../../data/energy";
|
||||
import { DirtyStateProviderMixin } from "../../../../mixins/dirty-state-provider-mixin";
|
||||
import type { HomeAssistantConfig, ValueChangedEvent } from "../../../../types";
|
||||
import type {
|
||||
EnergyEditorStatus,
|
||||
EnergyFixedCostEditorParams,
|
||||
} from "./energy-editor";
|
||||
import { EnergyEditorMixin, energyEditorStyles } from "./energy-editor";
|
||||
|
||||
type AmountType = "number" | "entity";
|
||||
|
||||
interface FixedCostFormState {
|
||||
cost: FixedCostEnergyPreference;
|
||||
amountType: AmountType;
|
||||
}
|
||||
|
||||
const PERIODS: FixedCostPeriod[] = ["day", "month", "year"];
|
||||
|
||||
@customElement("ha-energy-fixed-cost-editor")
|
||||
export class HaEnergyFixedCostEditor extends EnergyEditorMixin(
|
||||
DirtyStateProviderMixin<FixedCostFormState>()(LitElement)
|
||||
) {
|
||||
@property({ attribute: false })
|
||||
public params!: EnergyFixedCostEditorParams;
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
@transform<HomeAssistantConfig, string>({
|
||||
transformer: ({ config }) => config.currency,
|
||||
})
|
||||
private _currency!: string;
|
||||
|
||||
@state() private _cost?: FixedCostEnergyPreference;
|
||||
|
||||
@state() private _amountType: AmountType = "number";
|
||||
|
||||
@state() private _numberAmountText = "";
|
||||
|
||||
@state() private _error?: string;
|
||||
|
||||
@state() private _saving = false;
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>) {
|
||||
super.willUpdate(changedProps);
|
||||
if (changedProps.has("params")) {
|
||||
this._init();
|
||||
}
|
||||
}
|
||||
|
||||
private _init() {
|
||||
const params = this.params;
|
||||
this._error = undefined;
|
||||
this._saving = false;
|
||||
this._cost = params.cost
|
||||
? { ...params.cost }
|
||||
: emptyFixedCostEnergyPreference(params.type);
|
||||
this._amountType = this._cost.entity_amount ? "entity" : "number";
|
||||
this._numberAmountText =
|
||||
typeof this._cost.number_amount === "number"
|
||||
? String(this._cost.number_amount)
|
||||
: "";
|
||||
this._initDirtyTracking(
|
||||
{ type: "deep" },
|
||||
{ cost: this._cost, amountType: this._amountType }
|
||||
);
|
||||
}
|
||||
|
||||
protected get editorStatus(): EnergyEditorStatus {
|
||||
const cost = this._cost;
|
||||
return {
|
||||
dirty: this.isDirtyState,
|
||||
valid:
|
||||
!!cost?.name.trim() &&
|
||||
(this._amountType === "number"
|
||||
? Number.isFinite(cost.number_amount)
|
||||
: !!cost.entity_amount),
|
||||
saving: this._saving,
|
||||
};
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this._cost) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
${
|
||||
this._error
|
||||
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
|
||||
: nothing
|
||||
}
|
||||
<ha-input
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.name"
|
||||
)}
|
||||
type="text"
|
||||
required
|
||||
.disabled=${this._saving}
|
||||
.value=${this._cost.name}
|
||||
@input=${this._nameChanged}
|
||||
></ha-input>
|
||||
<div class="group">
|
||||
<ha-select
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_type"
|
||||
)}
|
||||
.value=${this._amountType}
|
||||
.options=${this._amountTypeOptions()}
|
||||
.disabled=${this._saving}
|
||||
@selected=${this._amountTypeChanged}
|
||||
></ha-select>
|
||||
${this._renderAmount()}
|
||||
</div>
|
||||
<ha-select
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.period"
|
||||
)}
|
||||
.helper=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.period_helper"
|
||||
)}
|
||||
.value=${this._cost.period}
|
||||
.options=${this._periodOptions()}
|
||||
.disabled=${this._saving}
|
||||
@selected=${this._periodChanged}
|
||||
></ha-select>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderAmount() {
|
||||
if (this._amountType === "entity") {
|
||||
return html`<ha-entity-picker
|
||||
.disabled=${this._saving}
|
||||
include-domains='["sensor", "input_number"]'
|
||||
.value=${this._cost!.entity_amount ?? undefined}
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_entity_label"
|
||||
)}
|
||||
.helper=${html`<ha-markdown
|
||||
.content=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_entity_helper",
|
||||
{ currency: this._currency, period: this._cost!.period }
|
||||
)}
|
||||
></ha-markdown>`}
|
||||
@value-changed=${this._amountEntityChanged}
|
||||
></ha-entity-picker>`;
|
||||
}
|
||||
return html`<ha-input
|
||||
.disabled=${this._saving}
|
||||
.label=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_number_label"
|
||||
)}
|
||||
.hint=${this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_number_helper"
|
||||
)}
|
||||
step="any"
|
||||
type="number"
|
||||
required
|
||||
auto-validate
|
||||
.value=${this._numberAmountText}
|
||||
@input=${this._numberAmountChanged}
|
||||
>
|
||||
<span slot="end">${this._currency}</span>
|
||||
</ha-input>`;
|
||||
}
|
||||
|
||||
private _amountTypeOptions(): HaSelectOption[] {
|
||||
return [
|
||||
{
|
||||
value: "number",
|
||||
label: this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_number"
|
||||
),
|
||||
},
|
||||
{
|
||||
value: "entity",
|
||||
label: this._localize(
|
||||
"ui.panel.config.energy.fixed_costs.dialog.amount_entity"
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
private _periodOptions(): HaSelectOption[] {
|
||||
return PERIODS.map((period) => ({
|
||||
value: period,
|
||||
label: this._localize(
|
||||
`ui.panel.config.energy.fixed_costs.dialog.period_${period}`
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
private _nameChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
|
||||
this._cost = { ...this._cost!, name: ev.currentTarget.value ?? "" };
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _amountTypeChanged(ev: HaSelectSelectEvent) {
|
||||
this._amountType = ev.detail.value as AmountType;
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _numberAmountChanged(ev: HASSDomCurrentTargetEvent<HaInput>) {
|
||||
// Render the typed text so partial input such as "-" is not rewritten
|
||||
this._numberAmountText = ev.currentTarget.value ?? "";
|
||||
const amount = parseFloat(this._numberAmountText);
|
||||
this._cost = {
|
||||
...this._cost!,
|
||||
number_amount: Number.isFinite(amount) ? amount : null,
|
||||
};
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _amountEntityChanged(ev: ValueChangedEvent<string>) {
|
||||
this._cost = { ...this._cost!, entity_amount: ev.detail.value || null };
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _periodChanged(ev: HaSelectSelectEvent) {
|
||||
this._cost = {
|
||||
...this._cost!,
|
||||
period: ev.detail.value as FixedCostPeriod,
|
||||
};
|
||||
this._updateFormDirtyState();
|
||||
}
|
||||
|
||||
private _updateFormDirtyState(): void {
|
||||
this._updateDirtyState({ cost: this._cost!, amountType: this._amountType });
|
||||
}
|
||||
|
||||
public async save(): Promise<boolean> {
|
||||
const params = this.params;
|
||||
const cost = this._cost!;
|
||||
const isNumber = this._amountType === "number";
|
||||
const isCurrent = () => this.params === params && this.isConnected;
|
||||
this._error = undefined;
|
||||
this._saving = true;
|
||||
try {
|
||||
await params.saveCallback({
|
||||
...cost,
|
||||
name: cost.name.trim(),
|
||||
number_amount: isNumber ? cost.number_amount : null,
|
||||
entity_amount: isNumber ? null : cost.entity_amount,
|
||||
});
|
||||
if (isCurrent()) {
|
||||
this._markDirtyStateClean();
|
||||
}
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
if (isCurrent()) {
|
||||
this._error = err.message;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (isCurrent()) {
|
||||
this._saving = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return energyEditorStyles;
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-energy-fixed-cost-editor": HaEnergyFixedCostEditor;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { html, nothing } from "lit";
|
||||
import type { EnergyEditorConfig } from "./energy-editor";
|
||||
import "./ha-energy-battery-source-editor";
|
||||
import "./ha-energy-device-editor";
|
||||
import "./ha-energy-fixed-cost-editor";
|
||||
import "./ha-energy-gas-source-editor";
|
||||
import "./ha-energy-grid-source-editor";
|
||||
import "./ha-energy-home-source-editor";
|
||||
@@ -52,11 +51,6 @@ export const renderEnergyEditor = (config: EnergyEditorConfig) => {
|
||||
class="energy-editor"
|
||||
.params=${config.params}
|
||||
></ha-energy-water-gas-device-editor>`;
|
||||
case "fixed_cost":
|
||||
return html`<ha-energy-fixed-cost-editor
|
||||
class="energy-editor"
|
||||
.params=${config.params}
|
||||
></ha-energy-fixed-cost-editor>`;
|
||||
default:
|
||||
return nothing;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ import type {
|
||||
EnergyPreferencesValidation,
|
||||
EnergyInfo,
|
||||
EnergyPreferences,
|
||||
FixedCostType,
|
||||
} from "../../../data/energy";
|
||||
import {
|
||||
getEnergyPreferenceValidation,
|
||||
@@ -36,7 +35,6 @@ import type { HomeAssistant, Route } from "../../../types";
|
||||
import "../../../components/ha-alert";
|
||||
import "./components/ha-energy-device-settings";
|
||||
import "./components/ha-energy-device-settings-water-gas";
|
||||
import "./components/ha-energy-fixed-cost-settings";
|
||||
import "./components/ha-energy-grid-settings";
|
||||
import "./components/ha-energy-solar-settings";
|
||||
import "./components/ha-energy-home-settings";
|
||||
@@ -57,7 +55,6 @@ const INITIAL_CONFIG: EnergyPreferences = {
|
||||
device_consumption: [],
|
||||
device_consumption_water: [],
|
||||
device_consumption_gas: [],
|
||||
fixed_costs: [],
|
||||
};
|
||||
|
||||
const TABS: PageNavigation[] = [
|
||||
@@ -83,15 +80,9 @@ const TABS: PageNavigation[] = [
|
||||
|
||||
// Editor pages are at <tab>/<kind>/<key>, with `new` as the key of a new item
|
||||
const EDITOR_KINDS: Record<string, string[]> = {
|
||||
electricity: ["grid", "solar", "home", "battery", "device", "fixed_cost"],
|
||||
gas: ["gas", "device", "fixed_cost"],
|
||||
water: ["water", "device", "fixed_cost"],
|
||||
};
|
||||
|
||||
const FIXED_COST_TYPES: Record<string, FixedCostType> = {
|
||||
electricity: "grid",
|
||||
gas: "gas",
|
||||
water: "water",
|
||||
electricity: ["grid", "solar", "home", "battery", "device"],
|
||||
gas: ["gas", "device"],
|
||||
water: ["water", "device"],
|
||||
};
|
||||
|
||||
@customElement("ha-config-energy")
|
||||
@@ -260,7 +251,6 @@ class HaConfigEnergy extends LitElement {
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-grid-settings>
|
||||
${this._renderFixedCostSettings("grid", listPath)}
|
||||
<ha-energy-solar-settings
|
||||
.hass=${this.hass}
|
||||
.preferences=${this._preferences!}
|
||||
@@ -304,7 +294,6 @@ class HaConfigEnergy extends LitElement {
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-gas-settings>
|
||||
${this._renderFixedCostSettings("gas", listPath)}
|
||||
<ha-energy-device-settings-water-gas
|
||||
.hass=${this.hass}
|
||||
.resource=${"gas"}
|
||||
@@ -325,7 +314,6 @@ class HaConfigEnergy extends LitElement {
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-water-settings>
|
||||
${this._renderFixedCostSettings("water", listPath)}
|
||||
<ha-energy-device-settings-water-gas
|
||||
.hass=${this.hass}
|
||||
.resource=${"water"}
|
||||
@@ -341,26 +329,6 @@ class HaConfigEnergy extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _renderFixedCostSettings(type: FixedCostType, listPath: string) {
|
||||
const prefs = this._preferences!;
|
||||
// The dashboard only shows fixed costs next to a source of their type,
|
||||
// without one the card stays so existing costs can be deleted
|
||||
if (
|
||||
!prefs.energy_sources.some((source) => source.type === type) &&
|
||||
!prefs.fixed_costs.some((cost) => cost.type === type)
|
||||
) {
|
||||
return nothing;
|
||||
}
|
||||
return html`<ha-energy-fixed-cost-settings
|
||||
.hass=${this.hass}
|
||||
.type=${type}
|
||||
.preferences=${prefs}
|
||||
.listPath=${listPath}
|
||||
.validationResult=${this._validationResult}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-fixed-cost-settings>`;
|
||||
}
|
||||
|
||||
private _renderEditorPage(kind: string, key: string) {
|
||||
const listPath = `${this.route.prefix}/${this._currTab}`;
|
||||
switch (`${this._currTab}/${kind}`) {
|
||||
@@ -465,19 +433,6 @@ class HaConfigEnergy extends LitElement {
|
||||
.editKey=${key}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-device-settings-water-gas>`;
|
||||
case "electricity/fixed_cost":
|
||||
case "gas/fixed_cost":
|
||||
case "water/fixed_cost":
|
||||
return html`<ha-energy-fixed-cost-settings
|
||||
class="editor-page"
|
||||
.hass=${this.hass}
|
||||
.narrow=${this.narrow}
|
||||
.type=${FIXED_COST_TYPES[this._currTab]}
|
||||
.preferences=${this._preferences!}
|
||||
.listPath=${listPath}
|
||||
.editKey=${key}
|
||||
@value-changed=${this._prefsChanged}
|
||||
></ha-energy-fixed-cost-settings>`;
|
||||
default:
|
||||
return nothing;
|
||||
}
|
||||
@@ -619,8 +574,7 @@ class HaConfigEnergy extends LitElement {
|
||||
ha-energy-gas-settings,
|
||||
ha-energy-water-settings,
|
||||
ha-energy-device-settings,
|
||||
ha-energy-device-settings-water-gas,
|
||||
ha-energy-fixed-cost-settings {
|
||||
ha-energy-device-settings-water-gas {
|
||||
display: block;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { navigate } from "../../../common/navigate";
|
||||
import { formatListWithAnds } from "../../../common/string/format-list";
|
||||
import { copyToClipboard } from "../../../common/util/copy-clipboard";
|
||||
import "../../../components/ha-dropdown";
|
||||
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
|
||||
@@ -96,9 +95,6 @@ export class HaConfigEntryRow extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public data!: ConfigEntryData;
|
||||
|
||||
/** The loaded integrations that lose this integration with this entry. */
|
||||
@property({ attribute: false }) public dependents?: IntegrationManifest[];
|
||||
|
||||
@state() private _expanded = true;
|
||||
|
||||
@state() private _devicesExpanded = true;
|
||||
@@ -816,33 +812,14 @@ export class HaConfigEntryRow extends LitElement {
|
||||
const applicationCredentialsId =
|
||||
await this._applicationCredentialForRemove(entryId);
|
||||
|
||||
const text = this.hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.delete_confirm_text"
|
||||
);
|
||||
const confirmed = await showConfirmationDialog(this, {
|
||||
title: this.hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.delete_confirm_title",
|
||||
{ title: this.data.entry.title }
|
||||
),
|
||||
text: this.dependents?.length
|
||||
? html`${text}<br /><br />${this.hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.delete_confirm_dependents",
|
||||
{
|
||||
count: this.dependents.length,
|
||||
integrations: formatListWithAnds(
|
||||
this.hass.locale,
|
||||
this.dependents.map((manifest) =>
|
||||
domainToName(this.hass.localize, manifest.domain, manifest)
|
||||
)
|
||||
),
|
||||
name: domainToName(
|
||||
this.hass.localize,
|
||||
this.data.entry.domain,
|
||||
this.manifest
|
||||
),
|
||||
}
|
||||
)}`
|
||||
: text,
|
||||
text: this.hass.localize(
|
||||
"ui.panel.config.integrations.config_entry.delete_confirm_text"
|
||||
),
|
||||
confirmText: this.hass!.localize("ui.common.delete"),
|
||||
dismissText: this.hass!.localize("ui.common.cancel"),
|
||||
destructive: true,
|
||||
|
||||
@@ -21,7 +21,7 @@ import memoizeOne from "memoize-one";
|
||||
import { ensureArray } from "../../../common/array/ensure-array";
|
||||
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
|
||||
import { QueryParamsController } from "../../../common/controllers/query-params-controller";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { ContextSubscriptionController } from "../../../common/decorators/consume";
|
||||
import type { HASSDomTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { computeDeviceNameDisplay } from "../../../common/entity/compute_device_name";
|
||||
import {
|
||||
@@ -176,9 +176,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
@state() private _manifest?: IntegrationManifest;
|
||||
|
||||
/** The manifests of all loaded integrations, to find the dependents. */
|
||||
@consume({ context: manifestsContext, subscribe: true })
|
||||
@state()
|
||||
private _loadedManifests?: DomainManifestLookup;
|
||||
@state() private _loadedManifests?: DomainManifestLookup;
|
||||
|
||||
private _manifestsConsumer?: ContextSubscriptionController<DomainManifestLookup>;
|
||||
|
||||
@state() private _extraConfigEntries?: ConfigEntry[];
|
||||
|
||||
@@ -432,23 +432,17 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
this.domain
|
||||
);
|
||||
|
||||
const dependents = this._getDependents(
|
||||
this.domain,
|
||||
this._loadedManifests,
|
||||
this.hass.localize,
|
||||
this.hass.locale.language
|
||||
);
|
||||
// Without the dependents, a dependency looks like a YAML integration.
|
||||
const dependencyOnly =
|
||||
normalEntries.length === 0 &&
|
||||
dependents.length > 0 &&
|
||||
!this._manifest?.config_flow;
|
||||
// Deleting the last entry in use leaves the dependents without it.
|
||||
const entriesInUse = configEntries.filter(
|
||||
(entry) => entry.source !== "ignore" && !entry.disabled_by
|
||||
);
|
||||
const lastEntryId =
|
||||
entriesInUse.length === 1 ? entriesInUse[0].entry_id : undefined;
|
||||
const dependents =
|
||||
this._manifest && !this._manifest.config_flow
|
||||
? this._getDependents(
|
||||
this.domain,
|
||||
this._loadedManifests,
|
||||
this.hass.localize,
|
||||
this.hass.locale.language
|
||||
)
|
||||
: [];
|
||||
const showDependents = normalEntries.length === 0 && dependents.length > 0;
|
||||
// Hold back the YAML texts and "Add entry" until the manifest and the
|
||||
// dependents are known. Entries do not wait, so a failed request cannot
|
||||
// hide them.
|
||||
@@ -467,7 +461,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
|
||||
const showAddEntry =
|
||||
this._manifest?.integration_type !== "hardware" &&
|
||||
!dependencyOnly &&
|
||||
!showDependents &&
|
||||
!dependentsLoading &&
|
||||
!setUpInPanel &&
|
||||
(!this._manifest?.single_config_entry ||
|
||||
@@ -659,7 +653,7 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
${
|
||||
normalEntries.length === 0 &&
|
||||
!dependencyOnly &&
|
||||
!showDependents &&
|
||||
!dependentsLoading &&
|
||||
!setUpInPanel &&
|
||||
this._manifest &&
|
||||
@@ -1016,11 +1010,6 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
.diagnosticHandler=${this._diagnosticHandler}
|
||||
.entities=${this._entities}
|
||||
.data=${data}
|
||||
.dependents=${
|
||||
data.entry.entry_id === lastEntryId
|
||||
? dependents
|
||||
: undefined
|
||||
}
|
||||
data-entry-id=${data.entry.entry_id}
|
||||
></ha-config-entry-row>`
|
||||
)}
|
||||
@@ -1029,7 +1018,19 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
dependencyOnly ||
|
||||
showDependents
|
||||
? html`<div class="section">
|
||||
<h3 class="section-header">
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.integrations.integration_page.used_by"
|
||||
)}
|
||||
</h3>
|
||||
${this._renderDependents(dependents)}
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
showDependents ||
|
||||
dependentsLoading ||
|
||||
(setUpInPanel && normalEntries.length === 0)
|
||||
? nothing
|
||||
@@ -1076,11 +1077,6 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
.diagnosticHandler=${this._diagnosticHandler}
|
||||
.entities=${this._entities}
|
||||
.data=${data}
|
||||
.dependents=${
|
||||
data.entry.entry_id === lastEntryId
|
||||
? dependents
|
||||
: undefined
|
||||
}
|
||||
data-entry-id=${data.entry.entry_id}
|
||||
></ha-config-entry-row>`
|
||||
)}
|
||||
@@ -1088,23 +1084,26 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
}
|
||||
</div>`
|
||||
}
|
||||
${
|
||||
dependents.length
|
||||
? html`<div class="section">
|
||||
<h3 class="section-header">
|
||||
${this.hass.localize(
|
||||
"ui.panel.config.integrations.integration_page.used_by"
|
||||
)}
|
||||
</h3>
|
||||
${this._renderDependents(dependents)}
|
||||
</div>`
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
</hass-subpage>
|
||||
`;
|
||||
}
|
||||
|
||||
// Only an integration without a config flow needs the loaded manifests, so
|
||||
// other integration pages do not make the context fetch them.
|
||||
private _watchLoadedManifests(): void {
|
||||
if (this._manifestsConsumer) {
|
||||
return;
|
||||
}
|
||||
this._manifestsConsumer = new ContextSubscriptionController(
|
||||
this,
|
||||
manifestsContext,
|
||||
(manifests) => {
|
||||
this._loadedManifests = manifests;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private _getDependents = memoizeOne(
|
||||
(
|
||||
domain: string,
|
||||
@@ -1200,6 +1199,9 @@ class HaConfigIntegrationPage extends SubscribeMixin(LitElement) {
|
||||
return;
|
||||
}
|
||||
this._manifest = await fetchIntegrationManifest(this.hass, this.domain);
|
||||
if (!this._manifest.config_flow) {
|
||||
this._watchLoadedManifests();
|
||||
}
|
||||
if (
|
||||
this._manifest.integration_type &&
|
||||
!["device", "hub", "service"].includes(this._manifest.integration_type)
|
||||
|
||||
@@ -363,8 +363,7 @@ export class HaConfigLovelaceDashboards extends LitElement {
|
||||
}
|
||||
const item: DataTableItem = {
|
||||
icon: getPanelIcon(panelInfo),
|
||||
title:
|
||||
getPanelTitle(this.hass.localize, panelInfo) || panelInfo.url_path,
|
||||
title: getPanelTitle(this.hass, panelInfo) || panelInfo.url_path,
|
||||
show_in_sidebar: panelInfo.show_in_sidebar || false,
|
||||
mode: "storage",
|
||||
url_path: panelInfo.url_path,
|
||||
@@ -548,7 +547,7 @@ export class HaConfigLovelaceDashboards extends LitElement {
|
||||
const defaultPanel = this.hass.systemData?.default_panel || DEFAULT_PANEL;
|
||||
showPanelDetailDialog(this, {
|
||||
urlPath: panelInfo.url_path,
|
||||
title: getPanelTitle(this.hass.localize, panelInfo) || panelInfo.url_path,
|
||||
title: getPanelTitle(this.hass, panelInfo) || panelInfo.url_path,
|
||||
icon: getPanelIcon(panelInfo),
|
||||
requireAdmin: panelInfo.require_admin || false,
|
||||
showInSidebar: panelInfo.show_in_sidebar || false,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { mdiArrowDown, mdiArrowUp, mdiMenuDown } from "@mdi/js";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
@@ -9,10 +8,7 @@ import { formatDateTime } from "../../../common/datetime/format_date_time";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { consumeLocalize } from "../../../common/decorators/consume-context-entry";
|
||||
import { transform } from "../../../common/decorators/transform";
|
||||
import type {
|
||||
HASSDomCurrentTargetEvent,
|
||||
HASSDomEvent,
|
||||
} from "../../../common/dom/fire_event";
|
||||
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../common/dom/fire_event";
|
||||
import { computeStateName } from "../../../common/entity/compute_state_name";
|
||||
import { formatNumber } from "../../../common/number/format_number";
|
||||
@@ -21,20 +17,13 @@ import "../../../components/data-table/ha-data-table";
|
||||
import type {
|
||||
DataTableColumnContainer,
|
||||
DataTableRowData,
|
||||
SortingChangedEvent,
|
||||
SortingDirection,
|
||||
} from "../../../components/data-table/ha-data-table";
|
||||
import "../../../components/chips/ha-assist-chip";
|
||||
import "../../../components/ha-alert";
|
||||
import "../../../components/ha-button";
|
||||
import "../../../components/ha-card";
|
||||
import "../../../components/ha-dropdown";
|
||||
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
|
||||
import "../../../components/ha-dropdown-item";
|
||||
import "../../../components/ha-segmented-bar";
|
||||
import type { Segment } from "../../../components/ha-segmented-bar";
|
||||
import "../../../components/ha-spinner";
|
||||
import "../../../components/ha-svg-icon";
|
||||
import {
|
||||
configContext,
|
||||
fullEntitiesContext,
|
||||
@@ -178,10 +167,6 @@ export class StorageDatabaseCard extends LitElement {
|
||||
@consume({ context: fullEntitiesContext, subscribe: true })
|
||||
private _entityRegistry: EntityRegistryEntry[] = [];
|
||||
|
||||
@state() private _sortColumn?: string;
|
||||
|
||||
@state() private _sortDirection: SortingDirection = null;
|
||||
|
||||
protected render(): TemplateResult {
|
||||
const usage = this.usage;
|
||||
return html`
|
||||
@@ -219,7 +204,6 @@ export class StorageDatabaseCard extends LitElement {
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
${usage ? this._renderTable(usage) : nothing}
|
||||
<div class="card-actions">
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
@@ -286,25 +270,15 @@ export class StorageDatabaseCard extends LitElement {
|
||||
></ha-segmented-bar>`
|
||||
: nothing
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderTable(usage: RecorderDatabaseUsage) {
|
||||
const columns = this._columns(
|
||||
this._localize,
|
||||
this._locale,
|
||||
this.narrow,
|
||||
usage.tables !== null,
|
||||
this._sortColumn
|
||||
);
|
||||
return html`
|
||||
<div class="table">
|
||||
<ha-data-table
|
||||
.narrow=${this.narrow}
|
||||
.columns=${columns}
|
||||
.sortColumn=${this._sortColumn}
|
||||
.sortDirection=${this._sortDirection}
|
||||
@sorting-changed=${this._sortingChanged}
|
||||
.columns=${this._columns(
|
||||
this._localize,
|
||||
this._locale,
|
||||
this.narrow,
|
||||
usage.tables !== null
|
||||
)}
|
||||
.data=${this._rows(usage, this._entityRegistry, this._localize)}
|
||||
.searchLabel=${this._localize(
|
||||
"ui.panel.config.storage.database.search"
|
||||
@@ -312,9 +286,7 @@ export class StorageDatabaseCard extends LitElement {
|
||||
.noDataText=${this._localize(
|
||||
"ui.panel.config.storage.database.no_entities"
|
||||
)}
|
||||
>
|
||||
${this.narrow ? this._renderSortMenu(columns) : nothing}
|
||||
</ha-data-table>
|
||||
></ha-data-table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
@@ -399,157 +371,84 @@ export class StorageDatabaseCard extends LitElement {
|
||||
localize: LocalizeFunc,
|
||||
locale: FrontendLocaleData,
|
||||
narrow: boolean,
|
||||
hasSizes: boolean,
|
||||
sortColumn: string | undefined
|
||||
): DataTableColumnContainer<EntityUsageRow> => {
|
||||
// Narrow screens show one number beside the name: the sorted one.
|
||||
const narrowColumn =
|
||||
sortColumn && sortColumn !== "name"
|
||||
? sortColumn
|
||||
: hasSizes
|
||||
? "bytes"
|
||||
: "states";
|
||||
return {
|
||||
name: {
|
||||
title: localize("ui.panel.config.storage.database.columns.entity"),
|
||||
main: true,
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
flex: 3,
|
||||
template: (row) => {
|
||||
const content = html`${row.name}
|
||||
${
|
||||
row.id !== UNKNOWN_ROW_ID && row.name !== row.id
|
||||
? html`<div class="secondary">${row.id}</div>`
|
||||
: nothing
|
||||
}`;
|
||||
// Rendered inside the data table, which styles .row-button.
|
||||
return row.hasSettings
|
||||
? html`<button
|
||||
type="button"
|
||||
class="row-button"
|
||||
data-entity-id=${row.id}
|
||||
@click=${this._openSettings}
|
||||
>
|
||||
${content}
|
||||
</button>`
|
||||
: content;
|
||||
},
|
||||
},
|
||||
id: {
|
||||
title: localize("ui.panel.config.storage.database.columns.entity_id"),
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
},
|
||||
states: {
|
||||
title: localize("ui.panel.config.storage.database.columns.states"),
|
||||
type: "numeric",
|
||||
minWidth: "100px",
|
||||
maxWidth: "100px",
|
||||
sortable: true,
|
||||
// Without sizes the rows are sorted by states instead.
|
||||
direction: hasSizes ? undefined : "desc",
|
||||
showNarrow: narrow && narrowColumn === "states",
|
||||
template: (row) => formatNumber(row.states, locale),
|
||||
},
|
||||
statistics: {
|
||||
title: localize(
|
||||
"ui.panel.config.storage.database.columns.statistics"
|
||||
),
|
||||
type: "numeric",
|
||||
minWidth: "100px",
|
||||
maxWidth: "100px",
|
||||
sortable: true,
|
||||
showNarrow: narrow && narrowColumn === "statistics",
|
||||
template: (row) => formatNumber(row.statistics, locale),
|
||||
},
|
||||
statistics_short_term: {
|
||||
title: localize(
|
||||
"ui.panel.config.storage.database.columns.statistics_short_term"
|
||||
),
|
||||
type: "numeric",
|
||||
minWidth: "130px",
|
||||
maxWidth: "130px",
|
||||
sortable: true,
|
||||
showNarrow: narrow && narrowColumn === "statistics_short_term",
|
||||
template: (row) => formatNumber(row.statistics_short_term, locale),
|
||||
},
|
||||
bytes: {
|
||||
title: localize("ui.panel.config.storage.database.columns.size"),
|
||||
type: "numeric",
|
||||
minWidth: "100px",
|
||||
maxWidth: "100px",
|
||||
sortable: true,
|
||||
direction: hasSizes ? "desc" : undefined,
|
||||
hidden: !hasSizes,
|
||||
showNarrow: narrow && narrowColumn === "bytes",
|
||||
template: (row) => bytesToString(row.bytes ?? 0),
|
||||
},
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
// Replaces the column headers on narrow screens, like the list pages do.
|
||||
private _renderSortMenu(columns: DataTableColumnContainer<EntityUsageRow>) {
|
||||
const sortColumn = this._sortColumn ? columns[this._sortColumn] : undefined;
|
||||
return html`
|
||||
<div slot="header-row" class="narrow-header-row">
|
||||
<ha-dropdown @wa-select=${this._handleSortBy}>
|
||||
<ha-assist-chip
|
||||
slot="trigger"
|
||||
.label=${this._localize(
|
||||
"ui.components.subpage-data-table.sort_by",
|
||||
{
|
||||
sortColumn: sortColumn ? ` ${sortColumn.title}` : "",
|
||||
}
|
||||
)}
|
||||
>
|
||||
<ha-svg-icon
|
||||
slot="trailing-icon"
|
||||
.path=${mdiMenuDown}
|
||||
></ha-svg-icon>
|
||||
</ha-assist-chip>
|
||||
${Object.entries(columns).map(([id, column]) =>
|
||||
column.sortable && !column.hidden
|
||||
? html`<ha-dropdown-item
|
||||
.value=${id}
|
||||
.selected=${id === this._sortColumn}
|
||||
>
|
||||
${
|
||||
id === this._sortColumn
|
||||
? html`<ha-svg-icon
|
||||
slot="details"
|
||||
.path=${
|
||||
this._sortDirection === "desc"
|
||||
? mdiArrowDown
|
||||
: mdiArrowUp
|
||||
}
|
||||
></ha-svg-icon>`
|
||||
: nothing
|
||||
}
|
||||
${column.title}
|
||||
</ha-dropdown-item>`
|
||||
hasSizes: boolean
|
||||
): DataTableColumnContainer<EntityUsageRow> => ({
|
||||
name: {
|
||||
title: localize("ui.panel.config.storage.database.columns.entity"),
|
||||
main: true,
|
||||
sortable: true,
|
||||
filterable: true,
|
||||
flex: 3,
|
||||
template: (row) => {
|
||||
const content = html`${row.name}
|
||||
${
|
||||
row.id !== UNKNOWN_ROW_ID && row.name !== row.id
|
||||
? html`<div class="secondary">${row.id}</div>`
|
||||
: nothing
|
||||
)}
|
||||
</ha-dropdown>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _sortingChanged(ev: HASSDomEvent<SortingChangedEvent>) {
|
||||
this._sortDirection = ev.detail.direction;
|
||||
this._sortColumn = ev.detail.direction ? ev.detail.column : undefined;
|
||||
}
|
||||
|
||||
private _handleSortBy(ev: HaDropdownSelectEvent) {
|
||||
ev.preventDefault(); // keep the dropdown open
|
||||
const column = ev.detail.item.value;
|
||||
this._sortDirection =
|
||||
column === this._sortColumn && this._sortDirection === "asc"
|
||||
? "desc"
|
||||
: "asc";
|
||||
this._sortColumn = column;
|
||||
}
|
||||
}`;
|
||||
// Rendered inside the data table, which styles .row-button.
|
||||
return row.hasSettings
|
||||
? html`<button
|
||||
type="button"
|
||||
class="row-button"
|
||||
data-entity-id=${row.id}
|
||||
@click=${this._openSettings}
|
||||
>
|
||||
${content}
|
||||
</button>`
|
||||
: content;
|
||||
},
|
||||
},
|
||||
id: {
|
||||
title: localize("ui.panel.config.storage.database.columns.entity_id"),
|
||||
filterable: true,
|
||||
hidden: true,
|
||||
},
|
||||
states: {
|
||||
title: localize("ui.panel.config.storage.database.columns.states"),
|
||||
type: "numeric",
|
||||
minWidth: "100px",
|
||||
maxWidth: "100px",
|
||||
sortable: true,
|
||||
// Without sizes the rows are sorted by states instead.
|
||||
direction: hasSizes ? undefined : "desc",
|
||||
hidden: narrow && hasSizes,
|
||||
showNarrow: !hasSizes,
|
||||
template: (row) => formatNumber(row.states, locale),
|
||||
},
|
||||
statistics: {
|
||||
title: localize("ui.panel.config.storage.database.columns.statistics"),
|
||||
type: "numeric",
|
||||
minWidth: "100px",
|
||||
maxWidth: "100px",
|
||||
sortable: true,
|
||||
hidden: narrow,
|
||||
template: (row) => formatNumber(row.statistics, locale),
|
||||
},
|
||||
statistics_short_term: {
|
||||
title: localize(
|
||||
"ui.panel.config.storage.database.columns.statistics_short_term"
|
||||
),
|
||||
type: "numeric",
|
||||
minWidth: "130px",
|
||||
maxWidth: "130px",
|
||||
sortable: true,
|
||||
hidden: narrow,
|
||||
template: (row) => formatNumber(row.statistics_short_term, locale),
|
||||
},
|
||||
bytes: {
|
||||
title: localize("ui.panel.config.storage.database.columns.size"),
|
||||
type: "numeric",
|
||||
minWidth: "100px",
|
||||
maxWidth: "100px",
|
||||
sortable: true,
|
||||
direction: hasSizes ? "desc" : undefined,
|
||||
hidden: !hasSizes,
|
||||
showNarrow: hasSizes,
|
||||
template: (row) => bytesToString(row.bytes ?? 0),
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
private _analyze() {
|
||||
fireEvent(this, "database-analyze");
|
||||
@@ -609,17 +508,6 @@ export class StorageDatabaseCard extends LitElement {
|
||||
--data-table-row-height: 44px;
|
||||
height: 100%;
|
||||
}
|
||||
.narrow-header-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 100%;
|
||||
padding-inline: var(--ha-space-4);
|
||||
}
|
||||
ha-assist-chip {
|
||||
--ha-assist-chip-container-shape: 10px;
|
||||
--ha-assist-chip-container-color: var(--card-background-color);
|
||||
--ha-assist-chip-trailing-space: 8px;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user