mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-18 19:02:19 +00:00
Compare commits
94
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a194ef1e6 | ||
|
|
04ab43929e | ||
|
|
10b7f5ffb6 | ||
|
|
cce6a720f3 | ||
|
|
c8f6a9ef77 | ||
|
|
94bd98d78d | ||
|
|
0904c2a547 | ||
|
|
2fd66939e7 | ||
|
|
5e340cb4e5 | ||
|
|
8b2dc28d0f | ||
|
|
8d933e85d4 | ||
|
|
b93869e668 | ||
|
|
bfd511deaf | ||
|
|
eeec2d4662 | ||
|
|
500249d996 | ||
|
|
a4157a490d | ||
|
|
d24ec6d34f | ||
|
|
bef72ec5da | ||
|
|
87add82ad0 | ||
|
|
eb70761886 | ||
|
|
74a2d3636b | ||
|
|
f03740c446 | ||
|
|
4873df0df6 | ||
|
|
d08b734afd | ||
|
|
4d1fc1225d | ||
|
|
18bcddaa20 | ||
|
|
ca576fadf5 | ||
|
|
aea1ac4ac8 | ||
|
|
6e1fe2846e | ||
|
|
17202283b4 | ||
|
|
0c8323c4f6 | ||
|
|
a2a523d5e5 | ||
|
|
b379c0d311 | ||
|
|
4dc975ec23 | ||
|
|
84294d7a8f | ||
|
|
e5838446c8 | ||
|
|
53f000e492 | ||
|
|
c452e8e4ff | ||
|
|
e80b07893d | ||
|
|
c801a52e67 | ||
|
|
8ac2712e31 | ||
|
|
f7f15ae4a8 | ||
|
|
e66733186e | ||
|
|
1e7bdbbcc8 | ||
|
|
7292db76bf | ||
|
|
9d997fbe4c | ||
|
|
05d11c25c2 | ||
|
|
ec14a9fe39 | ||
|
|
fc640e236d | ||
|
|
c2db01285c | ||
|
|
f2d0da08ed | ||
|
|
502dcdc1a6 | ||
|
|
0d31ae5624 | ||
|
|
f57384a265 | ||
|
|
4fe20d7712 | ||
|
|
14a4c05130 | ||
|
|
2d6ebd26d9 | ||
|
|
5ba1190cdd | ||
|
|
81cf8050e4 | ||
|
|
1a10982a5e | ||
|
|
fb8ac756ce | ||
|
|
2c072ab254 | ||
|
|
31ca8c298b | ||
|
|
1a5d8884ad | ||
|
|
9a95c9dea9 | ||
|
|
5db5f9075d | ||
|
|
6ce043a8e4 | ||
|
|
d81a9f29b2 | ||
|
|
c39734f350 | ||
|
|
e65584e724 | ||
|
|
6641a43e43 | ||
|
|
2706bd89a1 | ||
|
|
bd434eeb0d | ||
|
|
16f01e1081 | ||
|
|
050251db23 | ||
|
|
13128609de | ||
|
|
0f70813ada | ||
|
|
5762da9d22 | ||
|
|
33f709cd21 | ||
|
|
1f77e4cd59 | ||
|
|
77170b447f | ||
|
|
e2bb744202 | ||
|
|
0eec83448a | ||
|
|
1864f6f802 | ||
|
|
9a19cc3bf6 | ||
|
|
ec51fb4f8d | ||
|
|
6a1a9bfb1b | ||
|
|
16807d2765 | ||
|
|
9caad65c91 | ||
|
|
af523f1087 | ||
|
|
349d5f7125 | ||
|
|
de64bd3c59 | ||
|
|
5253eef284 | ||
|
|
b1164739c3 |
No files matched your search
@@ -18,7 +18,7 @@ workflows:
|
||||
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
|
||||
'.github/workflows/codeql-analysis.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
- 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066'
|
||||
'.github/workflows/copilot-setup-steps.yml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
@@ -151,9 +151,9 @@ dependencies:
|
||||
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
|
||||
owner_id: 7513068
|
||||
repo_id: 113918130
|
||||
'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370':
|
||||
ref: 'v4.39.1'
|
||||
commit: 'sha1-9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066':
|
||||
ref: 'v4.39.3'
|
||||
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
|
||||
owner_id: 9919
|
||||
repo_id: 259445878
|
||||
'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361':
|
||||
|
||||
@@ -32,12 +32,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
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@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
with:
|
||||
category: "/language:javascript-typescript"
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
name: Prepare container dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
options: --user 1001
|
||||
defaults:
|
||||
run:
|
||||
@@ -155,7 +155,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
@@ -207,7 +207,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
@@ -261,7 +261,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.65.1-noble@sha256:1507cbfc550a63a6b7396791ca4f00df17beb56342d2447b3f106c306f525579
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
|
||||
@@ -157,6 +157,99 @@ async function pollProcess(lokaliseApi, projectId, processId) {
|
||||
}
|
||||
/* eslint-enable no-await-in-loop */
|
||||
|
||||
const DRAFTS_ACCEPTED_KEYS = [
|
||||
// Written per language rather than translated from English, so an English edit doesn't make them outdated
|
||||
"ui.components.rooms.keywords",
|
||||
];
|
||||
|
||||
async function exportTranslations(lokaliseApi, projectId) {
|
||||
const exportProcess = await lokaliseApi.files().async_download(projectId, {
|
||||
format: "json",
|
||||
original_filenames: false,
|
||||
replace_breaks: false,
|
||||
json_unescaped_slashes: true,
|
||||
export_empty_as: "skip",
|
||||
filter_data: ["verified"],
|
||||
});
|
||||
|
||||
const finishedProcess = await pollProcess(
|
||||
lokaliseApi,
|
||||
projectId,
|
||||
exportProcess.process_id
|
||||
);
|
||||
|
||||
const bundleUrl = finishedProcess.details.download_url;
|
||||
|
||||
console.log(`Downloading translations from: ${bundleUrl}`);
|
||||
|
||||
const response = await fetch(bundleUrl);
|
||||
|
||||
if (response.status !== 200 && response.status !== 0) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
|
||||
console.log(`Extracting translations...`);
|
||||
|
||||
const contents = await JSZip.loadAsync(await response.arrayBuffer());
|
||||
|
||||
const files = {};
|
||||
await Promise.all(
|
||||
Object.keys(contents.files).map(async (filename) => {
|
||||
const file = contents.file(filename);
|
||||
if (!file) {
|
||||
// no file, probably a directory
|
||||
return;
|
||||
}
|
||||
files[filename.split("/").splice(-1)[0]] = await file.async("string");
|
||||
})
|
||||
);
|
||||
return files;
|
||||
}
|
||||
|
||||
async function fetchDrafts(lokaliseApi, projectId) {
|
||||
const english = JSON.parse(
|
||||
await fs.readFile("src/translations/en.json", { encoding })
|
||||
);
|
||||
const keyNames = DRAFTS_ACCEPTED_KEYS.flatMap((key) => {
|
||||
const keys = key.split(".");
|
||||
const drafts = keys.reduce((obj, part) => obj?.[part], english) ?? {};
|
||||
return Object.keys(drafts).map((name) => [...keys, name].join("::"));
|
||||
});
|
||||
if (!keyNames.length) {
|
||||
return [];
|
||||
}
|
||||
const { items } = await lokaliseApi.keys().list({
|
||||
project_id: projectId,
|
||||
filter_keys: keyNames.join(","),
|
||||
include_translations: 1,
|
||||
limit: keyNames.length,
|
||||
});
|
||||
return items.flatMap((key) =>
|
||||
key.translations
|
||||
.filter(({ translation }) => translation)
|
||||
.map(({ language_iso, translation }) => ({
|
||||
filename: `${language_iso}.json`,
|
||||
path: key.key_name.web.split("::"),
|
||||
translation,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
function acceptDrafts(files, drafts) {
|
||||
const data = {};
|
||||
drafts.forEach(({ filename, path: keyPath, translation }) => {
|
||||
data[filename] ??= files[filename] ? JSON.parse(files[filename]) : {};
|
||||
const parent = keyPath.slice(0, -1).reduce((obj, part) => {
|
||||
obj[part] ??= {};
|
||||
return obj[part];
|
||||
}, data[filename]);
|
||||
parent[keyPath.at(-1)] = translation;
|
||||
});
|
||||
Object.entries(data).forEach(([filename, content]) => {
|
||||
files[filename] = JSON.stringify(content, null, 2);
|
||||
});
|
||||
}
|
||||
|
||||
gulp.task("fetch-lokalise", async function () {
|
||||
let apiKey;
|
||||
try {
|
||||
@@ -193,52 +286,24 @@ gulp.task("fetch-lokalise", async function () {
|
||||
await Promise.all(
|
||||
projects.map(async ([project, projectId]) => {
|
||||
try {
|
||||
const exportProcess = await lokaliseApi
|
||||
.files()
|
||||
.async_download(projectId, {
|
||||
format: "json",
|
||||
original_filenames: false,
|
||||
replace_breaks: false,
|
||||
json_unescaped_slashes: true,
|
||||
export_empty_as: "skip",
|
||||
filter_data: ["verified"],
|
||||
});
|
||||
|
||||
const finishedProcess = await pollProcess(
|
||||
lokaliseApi,
|
||||
projectId,
|
||||
exportProcess.process_id
|
||||
);
|
||||
|
||||
const bundleUrl = finishedProcess.details.download_url;
|
||||
|
||||
console.log(`Downloading translations from: ${bundleUrl}`);
|
||||
|
||||
const response = await fetch(bundleUrl);
|
||||
|
||||
if (response.status !== 200 && response.status !== 0) {
|
||||
throw new Error(response.statusText);
|
||||
const [files, drafts] = await Promise.all([
|
||||
exportTranslations(lokaliseApi, projectId),
|
||||
project === "frontend"
|
||||
? fetchDrafts(lokaliseApi, projectId)
|
||||
: undefined,
|
||||
]);
|
||||
if (drafts) {
|
||||
acceptDrafts(files, drafts);
|
||||
}
|
||||
|
||||
console.log(`Extracting translations...`);
|
||||
|
||||
const contents = await JSZip.loadAsync(await response.arrayBuffer());
|
||||
|
||||
await mkdirPromise;
|
||||
await Promise.all(
|
||||
Object.keys(contents.files).map(async (filename) => {
|
||||
const file = contents.file(filename);
|
||||
if (!file) {
|
||||
// no file, probably a directory
|
||||
return;
|
||||
}
|
||||
const content = await file.async("nodebuffer");
|
||||
await fs.writeFile(
|
||||
path.join(inDir, project, filename.split("/").splice(-1)[0]),
|
||||
content,
|
||||
{ flag: "w", encoding }
|
||||
);
|
||||
})
|
||||
Object.entries(files).map(([filename, content]) =>
|
||||
fs.writeFile(path.join(inDir, project, filename), content, {
|
||||
flag: "w",
|
||||
encoding,
|
||||
})
|
||||
)
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
@@ -50,7 +50,9 @@ const convertToJSON = async (
|
||||
const encodedData = localeData.match(
|
||||
/JSON\.parse\((?<data>"(?:[^"\\]|\\.)*")\)/
|
||||
)?.groups?.data;
|
||||
localeData = firstBlock.match(dataRegex)?.groups?.data;
|
||||
localeData =
|
||||
localeData.match(/\}\)\((?<data>\{.*\})\)\s*;?\s*$/s)?.groups?.data ??
|
||||
firstBlock.match(dataRegex)?.groups?.data;
|
||||
if (!localeData && !encodedData) {
|
||||
throw Error(`Failed to extract data for language ${lang} from ${pkg}`);
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ class HcLaunchScreen extends LitElement {
|
||||
:host {
|
||||
display: block;
|
||||
height: 100vh;
|
||||
background-color: #f2f4f9;
|
||||
background-color: var(--primary-background-color, #f2f4f9);
|
||||
font-size: var(--ha-font-size-2xl);
|
||||
}
|
||||
.container {
|
||||
@@ -44,7 +44,7 @@ class HcLaunchScreen extends LitElement {
|
||||
object-fit: cover;
|
||||
}
|
||||
.status {
|
||||
color: #1d2126;
|
||||
color: var(--primary-text-color, #1d2126);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => ({
|
||||
const prefs: EnergyPreferences = {
|
||||
energy_sources: [
|
||||
{
|
||||
type: "grid",
|
||||
@@ -21,7 +21,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
stat_rate: "sensor.power_grid",
|
||||
cost_adjustment_day: 0,
|
||||
},
|
||||
{
|
||||
type: "grid",
|
||||
@@ -34,7 +33,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
stat_rate: "sensor.power_grid_return",
|
||||
cost_adjustment_day: 0,
|
||||
},
|
||||
{
|
||||
type: "solar",
|
||||
@@ -48,6 +46,23 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_energy_to: "sensor.battery_input",
|
||||
stat_rate: "sensor.power_battery",
|
||||
},
|
||||
{
|
||||
type: "battery",
|
||||
name: "Powerwall",
|
||||
stat_energy_from_grid: "sensor.powerwall_from_grid",
|
||||
stat_energy_from_solar: "sensor.powerwall_from_solar",
|
||||
stat_energy_to_home: "sensor.powerwall_to_home",
|
||||
stat_energy_to_grid: "sensor.powerwall_to_grid",
|
||||
stat_rate: "sensor.powerwall_power",
|
||||
power_config: {
|
||||
stat_rate_from_grid: "sensor.powerwall_power_from_grid",
|
||||
stat_rate_from_solar: "sensor.powerwall_power_from_solar",
|
||||
stat_rate_to_home: "sensor.powerwall_power_to_home",
|
||||
stat_rate_to_grid: "sensor.powerwall_power_to_grid",
|
||||
},
|
||||
stat_soc: "sensor.powerwall_battery_level",
|
||||
capacity: 13.5,
|
||||
},
|
||||
{
|
||||
type: "gas",
|
||||
stat_energy_from: "sensor.energy_gas",
|
||||
@@ -105,16 +120,17 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_consumption: "sensor.gas_heat_pump",
|
||||
},
|
||||
],
|
||||
}));
|
||||
};
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
hass.mockWS("energy/validate", () => ({
|
||||
energy_sources: Array.from({ length: 6 }, () => []),
|
||||
device_consumption: Array.from({ length: 6 }, () => []),
|
||||
device_consumption_water: Array.from({ length: 2 }, () => []),
|
||||
device_consumption_gas: Array.from({ length: 2 }, () => []),
|
||||
energy_sources: prefs.energy_sources.map(() => []),
|
||||
device_consumption: prefs.device_consumption.map(() => []),
|
||||
device_consumption_water: prefs.device_consumption_water.map(() => []),
|
||||
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
|
||||
}));
|
||||
hass.mockWS(
|
||||
"energy/fossil_energy_consumption",
|
||||
|
||||
@@ -1,3 +1,30 @@
|
||||
// Live power of the battery measured per direction, in W
|
||||
const powerwallPower = {
|
||||
from_grid: 50,
|
||||
from_solar: 150,
|
||||
to_home: 0,
|
||||
to_grid: 0,
|
||||
};
|
||||
|
||||
const powerEntity = (entityId: string, power: number) => ({
|
||||
entity_id: entityId,
|
||||
state: String(power),
|
||||
attributes: {
|
||||
state_class: "measurement",
|
||||
unit_of_measurement: "W",
|
||||
},
|
||||
});
|
||||
|
||||
const powerwallEnergyEntity = (entityId: string, friendlyName: string) => ({
|
||||
entity_id: entityId,
|
||||
state: "2",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
friendly_name: friendlyName,
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
});
|
||||
|
||||
export const energyEntities = () =>
|
||||
Object.values({
|
||||
"sensor.grid_fossil_fuel_percentage": {
|
||||
@@ -34,6 +61,31 @@ export const energyEntities = () =>
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
},
|
||||
"sensor.powerwall_from_grid": powerwallEnergyEntity(
|
||||
"sensor.powerwall_from_grid",
|
||||
"Powerwall charged from grid"
|
||||
),
|
||||
"sensor.powerwall_from_solar": powerwallEnergyEntity(
|
||||
"sensor.powerwall_from_solar",
|
||||
"Powerwall charged from solar"
|
||||
),
|
||||
"sensor.powerwall_to_home": powerwallEnergyEntity(
|
||||
"sensor.powerwall_to_home",
|
||||
"Powerwall discharged to home"
|
||||
),
|
||||
"sensor.powerwall_to_grid": powerwallEnergyEntity(
|
||||
"sensor.powerwall_to_grid",
|
||||
"Powerwall discharged to grid"
|
||||
),
|
||||
"sensor.powerwall_battery_level": {
|
||||
entity_id: "sensor.powerwall_battery_level",
|
||||
state: "62",
|
||||
attributes: {
|
||||
device_class: "battery",
|
||||
friendly_name: "Powerwall battery level",
|
||||
unit_of_measurement: "%",
|
||||
},
|
||||
},
|
||||
"sensor.energy_consumption_tarif_1": {
|
||||
entity_id: "sensor.energy_consumption_tarif_1",
|
||||
state: "88.6",
|
||||
@@ -134,6 +186,29 @@ export const energyEntities = () =>
|
||||
unit_of_measurement: "W",
|
||||
},
|
||||
},
|
||||
"sensor.powerwall_power_from_grid": powerEntity(
|
||||
"sensor.powerwall_power_from_grid",
|
||||
powerwallPower.from_grid
|
||||
),
|
||||
"sensor.powerwall_power_from_solar": powerEntity(
|
||||
"sensor.powerwall_power_from_solar",
|
||||
powerwallPower.from_solar
|
||||
),
|
||||
"sensor.powerwall_power_to_home": powerEntity(
|
||||
"sensor.powerwall_power_to_home",
|
||||
powerwallPower.to_home
|
||||
),
|
||||
"sensor.powerwall_power_to_grid": powerEntity(
|
||||
"sensor.powerwall_power_to_grid",
|
||||
powerwallPower.to_grid
|
||||
),
|
||||
"sensor.powerwall_power": powerEntity(
|
||||
"sensor.powerwall_power",
|
||||
powerwallPower.to_home +
|
||||
powerwallPower.to_grid -
|
||||
powerwallPower.from_grid -
|
||||
powerwallPower.from_solar
|
||||
),
|
||||
"sensor.energy_gas_cost": {
|
||||
entity_id: "sensor.energy_gas_cost",
|
||||
state: "2",
|
||||
|
||||
@@ -351,6 +351,26 @@ const statisticsFunctions: Record<
|
||||
const derivedCosts: Record<string, { source: string; price: number }> = {
|
||||
"sensor.energy_water_cost": { source: "sensor.energy_water", price: 0.004 },
|
||||
};
|
||||
// Battery directions as a share of the meter the energy also passes, so they
|
||||
// never exceed it
|
||||
const derivedBatteryFlows: Record<string, { source: string; share: number }> = {
|
||||
"sensor.powerwall_from_grid": {
|
||||
source: "sensor.energy_consumption_tarif_1",
|
||||
share: 0.4,
|
||||
},
|
||||
"sensor.powerwall_from_solar": {
|
||||
source: "sensor.solar_production",
|
||||
share: 0.3,
|
||||
},
|
||||
"sensor.powerwall_to_home": {
|
||||
source: "sensor.energy_consumption_tarif_2",
|
||||
share: 0.5,
|
||||
},
|
||||
"sensor.powerwall_to_grid": {
|
||||
source: "sensor.energy_production_tarif_2",
|
||||
share: 0.3,
|
||||
},
|
||||
};
|
||||
|
||||
export const mockRecorder = (mockHass: MockHomeAssistant) => {
|
||||
mockHass.mockWS(
|
||||
@@ -375,15 +395,22 @@ export const mockRecorder = (mockHass: MockHomeAssistant) => {
|
||||
return cache[id];
|
||||
};
|
||||
|
||||
const scaleStats = (source: string, factor: number) => {
|
||||
let sum = 0;
|
||||
return getStats(source).map((statistic) => {
|
||||
const change = statistic.change! * factor;
|
||||
sum += change;
|
||||
return { ...statistic, change, state: sum, sum };
|
||||
});
|
||||
};
|
||||
|
||||
statistic_ids.forEach((id: string) => {
|
||||
if (id in derivedCosts) {
|
||||
const { source, price } = derivedCosts[id];
|
||||
let cost = 0;
|
||||
statistics[id] = getStats(source).map((statistic) => {
|
||||
const change = statistic.change! * price;
|
||||
cost += change;
|
||||
return { ...statistic, change, state: cost, sum: cost };
|
||||
});
|
||||
statistics[id] = scaleStats(source, price);
|
||||
} else if (id in derivedBatteryFlows) {
|
||||
const { source, share } = derivedBatteryFlows[id];
|
||||
statistics[id] = scaleStats(source, share);
|
||||
} else if (id in statisticsFunctions) {
|
||||
statistics[id] = getStats(id);
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { ReactiveElement } from "lit";
|
||||
import { ContextSubscriptionController } from "../../../src/common/decorators/consume";
|
||||
import { uiContext } from "../../../src/data/context";
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
// A demo that provides its own hass hides the gallery theme from its children,
|
||||
// so pass the gallery light or dark mode on to it.
|
||||
export const followGalleryTheme = (
|
||||
host: ReactiveElement,
|
||||
hass: MockHomeAssistant
|
||||
) =>
|
||||
new ContextSubscriptionController(host, uiContext, (ui) => {
|
||||
if (ui) {
|
||||
hass.updateHass({
|
||||
themes: ui.themes,
|
||||
selectedTheme: ui.selectedTheme,
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -117,11 +117,17 @@ shared slots/attributes below.
|
||||
|
||||
**Attributes**
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ----------------- | ------- | ------- | --------------------------------------- |
|
||||
| `headline` | String | — | Primary text. Overridden by the slot. |
|
||||
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
|
||||
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
|
||||
| Name | Type | Default | Description |
|
||||
| ---------------------- | ------- | ------- | -------------------------------------------------- |
|
||||
| `headline` | String | — | Primary text. Overridden by the slot. |
|
||||
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
|
||||
| `wrap-headline` | Boolean | `false` | Wrap the headline instead of truncating it. |
|
||||
| `wrap-supporting-text` | Boolean | `false` | Wrap the supporting text instead of truncating it. |
|
||||
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
|
||||
|
||||
The headline and the supporting text stay on one line and are truncated with an
|
||||
ellipsis by default. Set `wrap-headline` or `wrap-supporting-text` on rows whose
|
||||
text has to stay readable in full, like settings with a description.
|
||||
|
||||
**CSS parts**
|
||||
|
||||
|
||||
@@ -191,6 +191,20 @@ export class DemoHaList extends LitElement {
|
||||
<ha-list-item-base headline="Disabled row" disabled>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
<ha-list-item-base
|
||||
headline="Truncated by default, a long headline stays on one line and ends with an ellipsis"
|
||||
supporting-text="Long supporting text is truncated as well, so every row in the list keeps the same height"
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
<ha-list-item-base
|
||||
wrap-headline
|
||||
wrap-supporting-text
|
||||
headline="With wrap-headline, a long headline wraps onto as many lines as it needs"
|
||||
supporting-text="With wrap-supporting-text, long supporting text wraps too, which suits settings with a description"
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
</ha-list-base>
|
||||
</ha-card>
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
} from "../../../../src/data/history";
|
||||
import { provideHass } from "../../../../src/fake_data/provide_hass";
|
||||
import type { HomeAssistant } from "../../../../src/types";
|
||||
import { followGalleryTheme } from "../../data/follow-gallery-theme";
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
const HOURS = 48;
|
||||
@@ -166,6 +167,7 @@ export class DemoStateHistoryCharts extends LitElement {
|
||||
super.firstUpdated(changedProps);
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
followGalleryTheme(this, hass);
|
||||
hass.addEntities(ENTITIES);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import type { ChartSelectMode } from "../../../../src/components/chart/ha-chart-base";
|
||||
import "../../../../src/components/chart/statistics-chart";
|
||||
import "../../../../src/components/ha-button";
|
||||
import "../../../../src/components/ha-card";
|
||||
import type {
|
||||
Statistics,
|
||||
@@ -11,7 +13,9 @@ import type {
|
||||
} from "../../../../src/data/recorder";
|
||||
import { StatisticMeanType } from "../../../../src/data/recorder";
|
||||
import { provideHass } from "../../../../src/fake_data/provide_hass";
|
||||
import type { HASSDomEvent } from "../../../../src/common/dom/fire_event";
|
||||
import type { HomeAssistant } from "../../../../src/types";
|
||||
import { followGalleryTheme } from "../../data/follow-gallery-theme";
|
||||
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
const HOURS = 48;
|
||||
@@ -108,6 +112,64 @@ interface Example {
|
||||
height?: string;
|
||||
}
|
||||
|
||||
interface TimeRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
interface RangeExample {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
statistics: Statistics;
|
||||
statTypes: StatisticType[];
|
||||
chartType: "line" | "bar";
|
||||
unit: string;
|
||||
selectMode: ChartSelectMode;
|
||||
hint: string;
|
||||
}
|
||||
|
||||
const RANGE_EXAMPLES: RangeExample[] = [
|
||||
{
|
||||
id: "point",
|
||||
title: "Point selection",
|
||||
description:
|
||||
"With select-mode set to point, a click selects the hour that contains it, and everything outside fades. Dragging still zooms.",
|
||||
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP },
|
||||
statTypes: ["change"],
|
||||
chartType: "bar",
|
||||
unit: "kWh",
|
||||
selectMode: "point",
|
||||
hint: "Click on a bar to select its hour.",
|
||||
},
|
||||
{
|
||||
id: "range-bar",
|
||||
title: "Range selection on bars",
|
||||
description:
|
||||
"With select-mode set to range, dragging selects a time range instead of zooming, so several bars can be selected at once. A click still selects one bar.",
|
||||
statistics: { [HEAT_PUMP_ID]: HEAT_PUMP },
|
||||
statTypes: ["change"],
|
||||
chartType: "bar",
|
||||
unit: "kWh",
|
||||
selectMode: "range",
|
||||
hint: "Click or drag on the chart to select one or more bars.",
|
||||
},
|
||||
{
|
||||
id: "range",
|
||||
title: "Range selection on lines",
|
||||
description: "The same on a line chart.",
|
||||
statistics: { [LIVING_ROOM_ID]: LIVING_ROOM },
|
||||
statTypes: ["mean", "min", "max"],
|
||||
chartType: "line",
|
||||
unit: "°C",
|
||||
selectMode: "range",
|
||||
hint: "Click or drag on the chart to select a period.",
|
||||
},
|
||||
];
|
||||
|
||||
const formatRange = (range: TimeRange) =>
|
||||
`${new Date(range.start).toLocaleString()} to ${new Date(range.end).toLocaleString()}`;
|
||||
|
||||
const EXAMPLES: Example[] = [
|
||||
{
|
||||
title: "Sum as bars",
|
||||
@@ -159,17 +221,20 @@ const EXAMPLES: Example[] = [
|
||||
export class DemoStatisticsChart extends LitElement {
|
||||
@property({ attribute: false }) public hass?: HomeAssistant;
|
||||
|
||||
@state() private _selections: Record<string, TimeRange | undefined> = {};
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
const hass = provideHass(this);
|
||||
hass.updateTranslations(null, "en");
|
||||
followGalleryTheme(this, hass);
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.hass) {
|
||||
return nothing;
|
||||
}
|
||||
return EXAMPLES.map(
|
||||
return html`${EXAMPLES.map(
|
||||
(example) => html`
|
||||
<ha-card header=${example.title}>
|
||||
<div class="card-content">
|
||||
@@ -191,7 +256,66 @@ export class DemoStatisticsChart extends LitElement {
|
||||
</div>
|
||||
</ha-card>
|
||||
`
|
||||
);
|
||||
)}
|
||||
${RANGE_EXAMPLES.map((example) => this._renderRangeExample(example))}`;
|
||||
}
|
||||
|
||||
private _renderRangeExample(example: RangeExample) {
|
||||
const selection = this._selections[example.id];
|
||||
return html`
|
||||
<ha-card header=${example.title}>
|
||||
<div class="card-content">
|
||||
<p>${example.description}</p>
|
||||
<statistics-chart
|
||||
.statisticsData=${example.statistics}
|
||||
.metadata=${METADATA}
|
||||
.names=${NAMES}
|
||||
.statTypes=${example.statTypes}
|
||||
.chartType=${example.chartType}
|
||||
period="hour"
|
||||
.unit=${example.unit}
|
||||
.startTime=${START}
|
||||
.endTime=${END}
|
||||
.highlight=${selection}
|
||||
.clickForMoreInfo=${false}
|
||||
data-example=${example.id}
|
||||
.selectMode=${example.selectMode}
|
||||
hide-legend
|
||||
@chart-select=${this._rangeSelected}
|
||||
></statistics-chart>
|
||||
<div class="selection">
|
||||
${
|
||||
selection
|
||||
? html`
|
||||
<span>${formatRange(selection)}</span>
|
||||
<ha-button
|
||||
appearance="plain"
|
||||
size="s"
|
||||
data-example=${example.id}
|
||||
@click=${this._clearSelection}
|
||||
>
|
||||
Clear
|
||||
</ha-button>
|
||||
`
|
||||
: html`<span class="hint">${example.hint}</span>`
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</ha-card>
|
||||
`;
|
||||
}
|
||||
|
||||
private _rangeSelected(ev: HASSDomEvent<HASSDomEvents["chart-select"]>) {
|
||||
const id = (ev.currentTarget as HTMLElement).dataset.example!;
|
||||
this._selections = {
|
||||
...this._selections,
|
||||
[id]: ev.detail,
|
||||
};
|
||||
}
|
||||
|
||||
private _clearSelection(ev: Event) {
|
||||
const id = (ev.currentTarget as HTMLElement).dataset.example!;
|
||||
this._selections = { ...this._selections, [id]: undefined };
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
@@ -202,6 +326,20 @@ export class DemoStatisticsChart extends LitElement {
|
||||
p {
|
||||
margin-top: 0;
|
||||
}
|
||||
.selection {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--ha-space-2);
|
||||
min-height: 48px;
|
||||
margin-top: var(--ha-space-2);
|
||||
padding: 0 var(--ha-space-2) 0 var(--ha-space-4);
|
||||
border-radius: var(--ha-border-radius-lg);
|
||||
background-color: var(--secondary-background-color);
|
||||
}
|
||||
.hint {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -187,6 +187,139 @@ const ENTITIES = [
|
||||
current_tilt_position: 70,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.shade",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Shade",
|
||||
device_class: "shade",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 60,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.shutter",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Shutter",
|
||||
device_class: "shutter",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 40,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.awning",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Awning",
|
||||
device_class: "awning",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 70,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.curtain",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Curtain",
|
||||
device_class: "curtain",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 50,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.door",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Door",
|
||||
device_class: "door",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 30,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.gate",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Gate",
|
||||
device_class: "gate",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 30,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.window",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Window",
|
||||
device_class: "window",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 50,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.garage",
|
||||
state: "closed",
|
||||
attributes: {
|
||||
friendly_name: "Garage door",
|
||||
device_class: "garage",
|
||||
supported_features: CoverEntityFeature.OPEN + CoverEntityFeature.CLOSE,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.unknown",
|
||||
state: "unknown",
|
||||
attributes: {
|
||||
friendly_name: "Unknown position",
|
||||
device_class: "shade",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.unavailable",
|
||||
state: "unavailable",
|
||||
attributes: {
|
||||
friendly_name: "Unavailable",
|
||||
device_class: "shutter",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@customElement("demo-more-info-cover")
|
||||
|
||||
@@ -250,7 +250,16 @@ class DemoMoreInfoUpdate extends LitElement {
|
||||
"update/release_notes",
|
||||
(msg: { type: string; entity_id: string }) => {
|
||||
if (msg.entity_id === "update.update16") {
|
||||
return LONG_TEXT;
|
||||
return {
|
||||
release_notes: LONG_TEXT,
|
||||
messages: [
|
||||
{
|
||||
severity: "warning",
|
||||
message:
|
||||
"Do not restart, remove power from, or otherwise interrupt the device while the update is in progress.",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (msg.entity_id === "update.update17") {
|
||||
return Promise.reject({
|
||||
@@ -261,7 +270,7 @@ class DemoMoreInfoUpdate extends LitElement {
|
||||
if (msg.entity_id === "update.update18") {
|
||||
return undefined;
|
||||
}
|
||||
return null;
|
||||
return { release_notes: null, messages: [] };
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
+33
-33
@@ -40,7 +40,7 @@
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "8.1.0",
|
||||
"@babel/runtime": "8.1.2",
|
||||
"@braintree/sanitize-url": "7.1.2",
|
||||
"@codemirror/autocomplete": "6.20.4",
|
||||
"@codemirror/commands": "6.11.1",
|
||||
@@ -48,21 +48,21 @@
|
||||
"@codemirror/lang-python": "6.2.1",
|
||||
"@codemirror/lang-yaml": "6.1.3",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/lint": "6.9.7",
|
||||
"@codemirror/lint": "6.9.8",
|
||||
"@codemirror/search": "6.7.2",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@date-fns/tz": "1.5.0",
|
||||
"@egjs/hammerjs": "2.0.17",
|
||||
"@formatjs/intl-datetimeformat": "8.0.2",
|
||||
"@formatjs/intl-displaynames": "8.0.1",
|
||||
"@formatjs/intl-durationformat": "0.12.3",
|
||||
"@formatjs/intl-getcanonicallocales": "3.3.0",
|
||||
"@formatjs/intl-listformat": "9.0.1",
|
||||
"@formatjs/intl-locale": "5.4.2",
|
||||
"@formatjs/intl-numberformat": "10.0.2",
|
||||
"@formatjs/intl-pluralrules": "7.0.2",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.1",
|
||||
"@formatjs/intl-datetimeformat": "8.0.3",
|
||||
"@formatjs/intl-displaynames": "8.0.3",
|
||||
"@formatjs/intl-durationformat": "0.12.4",
|
||||
"@formatjs/intl-getcanonicallocales": "3.3.1",
|
||||
"@formatjs/intl-listformat": "9.0.3",
|
||||
"@formatjs/intl-locale": "5.4.3",
|
||||
"@formatjs/intl-numberformat": "10.0.4",
|
||||
"@formatjs/intl-pluralrules": "7.0.4",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.3",
|
||||
"@home-assistant/webawesome": "3.14.0-ha.2",
|
||||
"@lezer/common": "1.5.5",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
@@ -77,9 +77,9 @@
|
||||
"@mdi/svg": "7.4.47",
|
||||
"@replit/codemirror-indentation-markers": "6.5.3",
|
||||
"@swc/helpers": "0.5.24",
|
||||
"@tsparticles/engine": "4.5.3",
|
||||
"@tsparticles/preset-links": "4.5.3",
|
||||
"@versatiles/style": "9.0.0",
|
||||
"@tsparticles/engine": "4.5.4",
|
||||
"@tsparticles/preset-links": "4.5.4",
|
||||
"@versatiles/style": "9.1.0",
|
||||
"@vibrant/color": "4.0.4",
|
||||
"@vvo/tzdb": "6.204.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.10",
|
||||
@@ -97,19 +97,19 @@
|
||||
"echarts": "6.1.0",
|
||||
"echarts-extension-chart2music": "0.1.1",
|
||||
"element-internals-polyfill": "3.0.2",
|
||||
"fullcalendar": "7.1.4",
|
||||
"fullcalendar": "7.1.5",
|
||||
"fuse.js": "7.5.0",
|
||||
"hls.js": "1.7.4",
|
||||
"home-assistant-js-websocket": "9.8.1",
|
||||
"idb-keyval": "6.3.0",
|
||||
"intl-messageformat": "12.1.4",
|
||||
"intl-messageformat": "12.1.5",
|
||||
"js-yaml": "5.5.0",
|
||||
"leaflet": "1.9.4",
|
||||
"leaflet.markercluster": "1.5.3",
|
||||
"lit": "3.3.3",
|
||||
"lit-html": "3.3.3",
|
||||
"maplibre-gl": "6.17.0",
|
||||
"marked": "18.1.3",
|
||||
"maplibre-gl": "6.18.0",
|
||||
"marked": "18.2.0",
|
||||
"memoize-one": "6.0.0",
|
||||
"nanoid": "6.0.2",
|
||||
"node-vibrant": "4.0.4",
|
||||
@@ -136,12 +136,12 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ampproject/remapping": "2.3.0",
|
||||
"@babel/core": "8.1.0",
|
||||
"@babel/core": "8.1.2",
|
||||
"@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.0.6",
|
||||
"@babel/plugin-transform-runtime": "8.1.2",
|
||||
"@babel/preset-env": "8.0.7",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.23.1",
|
||||
"@eslint/js": "10.0.1",
|
||||
@@ -151,9 +151,9 @@
|
||||
"@lokalise/node-api": "17.0.1",
|
||||
"@octokit/auth-oauth-device": "8.0.5",
|
||||
"@octokit/rest": "22.0.1",
|
||||
"@playwright/test": "1.65.0",
|
||||
"@playwright/test": "1.65.1",
|
||||
"@rsdoctor/rspack-plugin": "1.6.5",
|
||||
"@rspack/core": "2.3.1",
|
||||
"@rspack/core": "2.3.2",
|
||||
"@rspack/dev-server": "2.2.2",
|
||||
"@types/babel__plugin-transform-runtime": "7.9.5",
|
||||
"@types/chromecast-caf-receiver": "7.0.1",
|
||||
@@ -177,10 +177,10 @@
|
||||
"browserslist-useragent-regexp": "4.1.4",
|
||||
"core-js-compat": "3.51.0",
|
||||
"del": "9.0.1",
|
||||
"eslint": "10.14.0",
|
||||
"eslint": "10.15.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-import-resolver-webpack": "0.13.11",
|
||||
"eslint-plugin-import-x": "4.18.0",
|
||||
"eslint-plugin-import-x": "4.18.1",
|
||||
"eslint-plugin-lit": "2.3.1",
|
||||
"eslint-plugin-lit-a11y": "5.1.3",
|
||||
"eslint-plugin-unused-imports": "4.4.1",
|
||||
@@ -188,14 +188,14 @@
|
||||
"fancy-log": "2.0.0",
|
||||
"fs-extra": "11.4.1",
|
||||
"generate-license-file": "4.2.5",
|
||||
"glob": "14.0.4",
|
||||
"glob": "14.0.6",
|
||||
"globals": "17.14.0",
|
||||
"gulp": "5.0.1",
|
||||
"gulp-json-transform": "0.5.0",
|
||||
"gulp-rename": "2.1.0",
|
||||
"html-minifier-terser": "7.2.0",
|
||||
"husky": "9.1.7",
|
||||
"jsdom": "31.0.0",
|
||||
"jsdom": "31.0.1",
|
||||
"jszip": "3.10.2",
|
||||
"license-checker-rseidelsohn": "5.0.1",
|
||||
"lightningcss": "1.33.0",
|
||||
@@ -206,24 +206,24 @@
|
||||
"map-stream": "0.0.7",
|
||||
"minify-literals": "2.2.0",
|
||||
"pinst": "3.0.0",
|
||||
"prettier": "3.9.10",
|
||||
"prettier": "3.10.1",
|
||||
"rspack-manifest-plugin": "5.2.2",
|
||||
"serve": "14.2.7",
|
||||
"serve": "14.2.8",
|
||||
"sinon": "22.1.0",
|
||||
"tar": "7.5.22",
|
||||
"tar": "7.5.23",
|
||||
"terser-webpack-plugin": "5.6.1",
|
||||
"ts-lit-plugin": "2.0.2",
|
||||
"typescript": "6.0.3",
|
||||
"typescript-eslint": "8.72.1",
|
||||
"vite": "8.3.6",
|
||||
"typescript-eslint": "8.72.2",
|
||||
"vite": "8.3.8",
|
||||
"vite-tsconfig-paths": "6.1.1",
|
||||
"vitest": "5.1.0",
|
||||
"webpack-stats-plugin": "1.1.3",
|
||||
"webpackbar": "7.0.0",
|
||||
"workbox-build": "7.4.1"
|
||||
},
|
||||
"packageManager": "[email protected]8.0",
|
||||
"packageManager": "pnpm@12.21.0",
|
||||
"volta": {
|
||||
"node": "24.22.2"
|
||||
"node": "24.22.3"
|
||||
}
|
||||
}
|
||||
@@ -53,7 +53,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@custom-elements-manifest/analyzer": "0.11.0",
|
||||
"@rslib/core": "1.0.6",
|
||||
"@rslib/core": "1.0.7",
|
||||
"lit": "3.3.3",
|
||||
"typescript": "6.0.3"
|
||||
}
|
||||
|
||||
Generated
+1081
-1078
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,55 @@
|
||||
interface EntityWithColorTemp {
|
||||
attributes?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const finiteRange = (
|
||||
min: unknown,
|
||||
max: unknown
|
||||
): { min: number; max: number } | undefined => {
|
||||
if (typeof min !== "number" || typeof max !== "number") {
|
||||
return undefined;
|
||||
}
|
||||
if (!Number.isFinite(min) || !Number.isFinite(max) || min > max) {
|
||||
return undefined;
|
||||
}
|
||||
return { min, max };
|
||||
};
|
||||
|
||||
/**
|
||||
* Kelvin bounds reported by the given entity states.
|
||||
*
|
||||
* Several lights use the overlap of their ranges, because one
|
||||
* `color_temp_kelvin` value is sent to every target. When the ranges do not
|
||||
* overlap, the result spans the widest range so it still has a valid min and
|
||||
* max. Entities without a finite range are ignored. Returns undefined when
|
||||
* nothing reports a range, so the caller keeps the selector min and max.
|
||||
*/
|
||||
export const kelvinRangeFromEntityStates = (
|
||||
states: Readonly<Record<string, EntityWithColorTemp | undefined>> | undefined
|
||||
): { min: number; max: number } | undefined => {
|
||||
if (!states) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const ranges: { min: number; max: number }[] = [];
|
||||
for (const state of Object.values(states)) {
|
||||
const range = finiteRange(
|
||||
state?.attributes?.min_color_temp_kelvin,
|
||||
state?.attributes?.max_color_temp_kelvin
|
||||
);
|
||||
if (range) {
|
||||
ranges.push(range);
|
||||
}
|
||||
}
|
||||
if (!ranges.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let min = Math.max(...ranges.map((range) => range.min));
|
||||
let max = Math.min(...ranges.map((range) => range.max));
|
||||
if (min > max) {
|
||||
min = Math.min(...ranges.map((range) => range.min));
|
||||
max = Math.max(...ranges.map((range) => range.max));
|
||||
}
|
||||
return { min, max };
|
||||
};
|
||||
@@ -89,10 +89,19 @@ export class LegendFitController {
|
||||
|
||||
private _fit() {
|
||||
const list = this._element;
|
||||
const rowWidth = list?.getBoundingClientRect().width;
|
||||
if (!list || !rowWidth) {
|
||||
if (!list) {
|
||||
return;
|
||||
}
|
||||
const style = getComputedStyle(list);
|
||||
const rowWidth = parseFloat(style.width);
|
||||
// Bounding rects include transforms, such as a dialog scaling in, which
|
||||
// never resize the list, so measure in layout pixels
|
||||
const scale = list.getBoundingClientRect().width / rowWidth;
|
||||
if (!rowWidth || !scale) {
|
||||
return;
|
||||
}
|
||||
const layoutWidth = (element: Element) =>
|
||||
element.getBoundingClientRect().width / scale;
|
||||
const children = Array.from(list.children);
|
||||
const more = children.find((child) =>
|
||||
child.classList.contains("legend-more")
|
||||
@@ -107,9 +116,7 @@ export class LegendFitController {
|
||||
}
|
||||
this._more = more;
|
||||
}
|
||||
const widths = children
|
||||
.filter((child) => child !== more)
|
||||
.map((child) => child.getBoundingClientRect().width);
|
||||
const widths = children.filter((child) => child !== more).map(layoutWidth);
|
||||
// Values resize the items on every state update. Fitting each item at its
|
||||
// widest since the last resize keeps the more button from flickering.
|
||||
if (rowWidth !== this._rowWidth || widths.length !== this._widths.length) {
|
||||
@@ -122,9 +129,9 @@ export class LegendFitController {
|
||||
}
|
||||
const fit = fitInRows(
|
||||
this._widths,
|
||||
more?.getBoundingClientRect().width ?? 0,
|
||||
more ? layoutWidth(more) : 0,
|
||||
rowWidth,
|
||||
parseFloat(getComputedStyle(list).columnGap) || 0,
|
||||
parseFloat(style.columnGap) || 0,
|
||||
rowWidth < NARROW_WIDTH ? NARROW_MAX_ROWS : MAX_ROWS
|
||||
);
|
||||
if (fit !== this.fit) {
|
||||
|
||||
@@ -3,6 +3,7 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
|
||||
"ha-slider",
|
||||
"ha-control-switch",
|
||||
"ha-control-circular-slider",
|
||||
"ha-state-control-cover",
|
||||
"ha-hs-color-picker",
|
||||
"ha-map",
|
||||
// Charts pan and pinch-zoom on touch
|
||||
|
||||
@@ -4,16 +4,23 @@ import {
|
||||
mdiArrowDown,
|
||||
mdiArrowExpandHorizontal,
|
||||
mdiArrowUp,
|
||||
mdiDoorClosed,
|
||||
mdiDoorOpen,
|
||||
mdiGate,
|
||||
mdiGateOpen,
|
||||
} from "@mdi/js";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
|
||||
export const computeOpenIcon = (stateObj: HassEntity): string => {
|
||||
switch (stateObj.attributes.device_class) {
|
||||
case "awning":
|
||||
case "door":
|
||||
return mdiDoorOpen;
|
||||
case "gate":
|
||||
return mdiGateOpen;
|
||||
case "curtain":
|
||||
return mdiArrowExpandHorizontal;
|
||||
case "awning":
|
||||
return mdiArrowDown;
|
||||
default:
|
||||
return mdiArrowUp;
|
||||
}
|
||||
@@ -21,11 +28,14 @@ export const computeOpenIcon = (stateObj: HassEntity): string => {
|
||||
|
||||
export const computeCloseIcon = (stateObj: HassEntity): string => {
|
||||
switch (stateObj.attributes.device_class) {
|
||||
case "awning":
|
||||
case "door":
|
||||
return mdiDoorClosed;
|
||||
case "gate":
|
||||
return mdiGate;
|
||||
case "curtain":
|
||||
return mdiArrowCollapseHorizontal;
|
||||
case "awning":
|
||||
return mdiArrowUp;
|
||||
default:
|
||||
return mdiArrowDown;
|
||||
}
|
||||
|
||||
@@ -163,21 +163,9 @@ export const findEntities = (
|
||||
return results;
|
||||
};
|
||||
|
||||
export const excludeEntities = (
|
||||
entityIds: string[],
|
||||
excludedEntityIds?: string[]
|
||||
): string[] => {
|
||||
if (!excludedEntityIds?.length) {
|
||||
return entityIds;
|
||||
}
|
||||
const excluded = new Set(excludedEntityIds);
|
||||
return entityIds.filter((entityId) => !excluded.has(entityId));
|
||||
};
|
||||
|
||||
export const findFilteredEntities = (
|
||||
sources: EntityFilterSources,
|
||||
filters: EntityFilter[],
|
||||
excludedEntityIds?: string[]
|
||||
filters: EntityFilter[]
|
||||
): string[] => {
|
||||
const filterFuncs = filters.map((filter) =>
|
||||
generateEntityFilter(
|
||||
@@ -189,8 +177,5 @@ export const findFilteredEntities = (
|
||||
filter
|
||||
)
|
||||
);
|
||||
return excludeEntities(
|
||||
findEntities(Object.keys(sources.states), filterFuncs),
|
||||
excludedEntityIds
|
||||
);
|
||||
return findEntities(Object.keys(sources.states), filterFuncs);
|
||||
};
|
||||
@@ -161,6 +161,9 @@ export const getNumberFormatOptions = (
|
||||
return undefined;
|
||||
};
|
||||
|
||||
// Intl.NumberFormat throws a RangeError for more fraction digits than this.
|
||||
const MAX_FRACTION_DIGITS = 100;
|
||||
|
||||
/**
|
||||
* Generates default options for Intl.NumberFormat
|
||||
* @param num The number to be formatted
|
||||
@@ -185,7 +188,10 @@ export const getDefaultFormatOptions = (
|
||||
(options.minimumFractionDigits === undefined &&
|
||||
options.maximumFractionDigits === undefined)
|
||||
) {
|
||||
const digits = num.indexOf(".") > -1 ? num.split(".")[1].length : 0;
|
||||
const digits = Math.min(
|
||||
num.indexOf(".") > -1 ? num.split(".")[1].length : 0,
|
||||
MAX_FRACTION_DIGITS
|
||||
);
|
||||
defaultOptions.minimumFractionDigits = digits;
|
||||
defaultOptions.maximumFractionDigits = digits;
|
||||
}
|
||||
|
||||
@@ -1,2 +1,10 @@
|
||||
export const capitalizeFirstLetter = (str: string) =>
|
||||
str.charAt(0).toUpperCase() + str.slice(1);
|
||||
export const capitalizeFirstLetter = (str: string) => {
|
||||
// Take the first code point, not code unit, so letters outside the BMP
|
||||
// (stored as a surrogate pair) are uppercased too.
|
||||
const first = str.codePointAt(0);
|
||||
if (first === undefined) {
|
||||
return str;
|
||||
}
|
||||
const firstLetter = String.fromCodePoint(first);
|
||||
return firstLetter.toUpperCase() + str.slice(firstLetter.length);
|
||||
};
|
||||
@@ -1,11 +1,27 @@
|
||||
// Unanchored regex fragments, shared as the single source of truth for both
|
||||
// the boolean validators below and the HTML `pattern` attribute (the browser
|
||||
// anchors a pattern as `^(?:…)$`).
|
||||
const IPV4 =
|
||||
"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
|
||||
|
||||
const IPV6 =
|
||||
"(?:([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|::(ffff(:0{1,4})?:)?((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))";
|
||||
// Decimal octet 0-255 without leading zeros.
|
||||
const DEC_OCTET = "(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])";
|
||||
|
||||
const IPV4 = `(?:${DEC_OCTET}\\.){3}${DEC_OCTET}`;
|
||||
|
||||
// IPv6 grammar from RFC 3986, section 3.2.2.
|
||||
const H16 = "[0-9a-fA-F]{1,4}";
|
||||
const LS32 = `(?:${H16}:${H16}|${IPV4})`;
|
||||
|
||||
const IPV6 = `(?:${[
|
||||
`(?:${H16}:){6}${LS32}`,
|
||||
`::(?:${H16}:){5}${LS32}`,
|
||||
`(?:${H16})?::(?:${H16}:){4}${LS32}`,
|
||||
`(?:(?:${H16}:){0,1}${H16})?::(?:${H16}:){3}${LS32}`,
|
||||
`(?:(?:${H16}:){0,2}${H16})?::(?:${H16}:){2}${LS32}`,
|
||||
`(?:(?:${H16}:){0,3}${H16})?::${H16}:${LS32}`,
|
||||
`(?:(?:${H16}:){0,4}${H16})?::${LS32}`,
|
||||
`(?:(?:${H16}:){0,5}${H16})?::${H16}`,
|
||||
`(?:(?:${H16}:){0,6}${H16})?::`,
|
||||
].join("|")})`;
|
||||
|
||||
// CIDR prefix lengths: 0-32 for IPv4, 0-128 for IPv6.
|
||||
const IPV4_PREFIX = "(?:3[0-2]|[12]?[0-9])";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// https://gist.github.com/hagemann/382adfc57adbd5af078dc93feef01fe1
|
||||
export const slugify = (value: string, delimiter = "_") => {
|
||||
const a =
|
||||
"àáâäæãåāăąабçćčđďдèéêëēėęěеёэфğǵгḧхîïíīįìıİийкłлḿмñńǹňнôöòóœøōõőоṕпŕřрßśšşșсťțтûüùúūǘůűųувẃẍÿýыžźżз·";
|
||||
const b = `aaaaaaaaaaabcccdddeeeeeeeeeeefggghhiiiiiiiiijkllmmnnnnnoooooooooopprrrsssssstttuuuuuuuuuuvwxyyyzzzz${delimiter}`;
|
||||
"àáâäæãåāăąабçćčđďдèéêëēėęěеёэфğǵгḧîïíīįìıİийкłлḿмñńǹňнôöòóœøōõőоṕпŕřрßśšşșсťțтûüùúūǘůűųувẃẍÿýыžźżз·";
|
||||
const b = `aaaaaaaaaaabcccdddeeeeeeeeeeefggghiiiiiiiiijkllmmnnnnnoooooooooopprrrsssssstttuuuuuuuuuuvwxyyyzzzz${delimiter}`;
|
||||
const p = new RegExp(a.split("").join("|"), "g");
|
||||
const complex_cyrillic = {
|
||||
ж: "zh",
|
||||
|
||||
@@ -82,7 +82,11 @@ export function decodeQueryParams(
|
||||
for (const key of config.date ?? []) {
|
||||
const value = getSearchParam(searchParams, key);
|
||||
if (value) {
|
||||
params[key] = new Date(value);
|
||||
const date = new Date(value);
|
||||
// Leave out dates that can't be parsed, like a missing value.
|
||||
if (!Number.isNaN(date.getTime())) {
|
||||
params[key] = date;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const { key, trueValue } of config.boolean ?? []) {
|
||||
|
||||
@@ -37,6 +37,7 @@ export const debounce = <T extends any[]>(
|
||||
|
||||
debouncedFunc.cancel = () => {
|
||||
clearTimeout(timeout);
|
||||
timeout = undefined;
|
||||
trailingArgs = undefined;
|
||||
};
|
||||
|
||||
|
||||
@@ -2,14 +2,17 @@ export const groupBy = <T>(
|
||||
list: T[],
|
||||
keySelector: (item: T) => string
|
||||
): Record<string, T[]> => {
|
||||
const result = {};
|
||||
// Group in a Map so keys like `constructor` or `__proto__` don't collide
|
||||
// with Object.prototype.
|
||||
const groups = new Map<string, T[]>();
|
||||
for (const item of list) {
|
||||
const key = keySelector(item);
|
||||
if (key in result) {
|
||||
result[key].push(item);
|
||||
const group = groups.get(key);
|
||||
if (group) {
|
||||
group.push(item);
|
||||
} else {
|
||||
result[key] = [item];
|
||||
groups.set(key, [item]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
return Object.fromEntries(groups);
|
||||
};
|
||||
@@ -11,7 +11,8 @@
|
||||
* parseAnimationDuration("invalid") // Returns 0
|
||||
*/
|
||||
export const parseAnimationDuration = (duration: string): number => {
|
||||
const trimmed = duration.trim();
|
||||
// CSS units are case-insensitive, e.g. "3S" is the same as "3s".
|
||||
const trimmed = duration.trim().toLowerCase();
|
||||
|
||||
let value: number;
|
||||
let multiplier: number;
|
||||
|
||||
@@ -19,6 +19,7 @@ interface MinMaxFrame {
|
||||
maxPoint: Point;
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
lastX: number;
|
||||
gapPoint: Point | undefined;
|
||||
}
|
||||
|
||||
@@ -68,6 +69,7 @@ function newFrame(
|
||||
maxPoint: point,
|
||||
maxX: x,
|
||||
maxY: y,
|
||||
lastX: x,
|
||||
gapPoint,
|
||||
};
|
||||
}
|
||||
@@ -174,6 +176,7 @@ export function downSampleLineData<
|
||||
if (!frame) {
|
||||
frames.set(frameIndex, newFrame(point, x, y, undefined));
|
||||
} else if (frame.hasValue) {
|
||||
frame.lastX = x;
|
||||
// Match the original strict-less / strict-greater comparisons so the
|
||||
// first occurrence wins on ties.
|
||||
if (y < frame.minY) {
|
||||
@@ -189,6 +192,7 @@ export function downSampleLineData<
|
||||
} else {
|
||||
// the frame held nothing but a marker so far
|
||||
frame.hasValue = true;
|
||||
frame.lastX = x;
|
||||
frame.minPoint = point;
|
||||
frame.minX = x;
|
||||
frame.minY = y;
|
||||
@@ -213,11 +217,8 @@ export function downSampleLineData<
|
||||
if (frame.gapPoint !== undefined) {
|
||||
// A marker followed by a value in its own frame is a gap that closed
|
||||
// within one frame, which is about one device pixel: too narrow to show.
|
||||
// The kept points are exactly min and max, so comparing against the
|
||||
// later of the two catches that without any work on the ingest path. A
|
||||
// marker-only frame compares against its own x and always passes.
|
||||
const lastValueX = frame.minX > frame.maxX ? frame.minX : frame.maxX;
|
||||
if (Number(getPointData(frame.gapPoint)[0]) >= lastValueX) {
|
||||
// That value may be neither min nor max, so check the frame's last x.
|
||||
if (Number(getPointData(frame.gapPoint)[0]) >= frame.lastX) {
|
||||
result.push(frame.gapPoint as T);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,10 @@ import {
|
||||
mdiRestart,
|
||||
} from "@mdi/js";
|
||||
import { differenceInMinutes } from "date-fns";
|
||||
import type { DataZoomComponentOption } from "echarts/components";
|
||||
import type {
|
||||
DataZoomComponentOption,
|
||||
MarkAreaComponentOption,
|
||||
} from "echarts/components";
|
||||
import type { EChartsType } from "echarts/core";
|
||||
import type {
|
||||
ECElementEvent,
|
||||
@@ -90,14 +93,29 @@ export const DEFAULT_CHART_WIDTH = 500;
|
||||
// is short enough for a whole screenful; on a desktop that would cover the page.
|
||||
const VISIBILITY_ROOT_MARGIN_NARROW = "100%";
|
||||
const VISIBILITY_ROOT_MARGIN = "300px";
|
||||
const CLICK_DRAG_TOLERANCE = 4;
|
||||
// The selection is shown by the mask, not by the brush
|
||||
const BRUSH_STYLE = {
|
||||
color: "rgba(0, 0, 0, 0)",
|
||||
borderColor: "rgba(0, 0, 0, 0)",
|
||||
};
|
||||
|
||||
export type ZoomSliderMode = "auto" | "always" | "never";
|
||||
|
||||
export type ChartSelectMode = "none" | "point" | "range";
|
||||
const DEFERRED_PROPS = [
|
||||
"options",
|
||||
"data",
|
||||
"_hiddenDatasets",
|
||||
"_isZoomed",
|
||||
"highlight",
|
||||
] as const;
|
||||
const MASK_OPACITY = 0.7;
|
||||
|
||||
export interface ChartTimeRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
type RawSeriesOption = Exclude<
|
||||
NonNullable<ECOption["series"]>,
|
||||
@@ -176,6 +194,18 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
@property({ attribute: "grow-for-zoom-slider", type: Boolean })
|
||||
public growForZoomSlider = false;
|
||||
|
||||
// "point" selects on click, "range" also selects on drag instead of zooming
|
||||
@property({ attribute: "select-mode" })
|
||||
public selectMode: ChartSelectMode = "none";
|
||||
|
||||
// Everything outside this time range fades
|
||||
@property({ attribute: false }) public highlight?: ChartTimeRange;
|
||||
|
||||
// Rounds a selection to the periods of the data, or drops it
|
||||
@property({ attribute: false }) public snapSelection?: (
|
||||
range: ChartTimeRange
|
||||
) => ChartTimeRange | undefined;
|
||||
|
||||
// extraComponents is not reactive and should not trigger updates
|
||||
public extraComponents?: any[];
|
||||
|
||||
@@ -201,6 +231,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
@state() private _isZoomed = false;
|
||||
|
||||
private _pointerDownX?: number;
|
||||
|
||||
private _selectingRange?: ChartTimeRange;
|
||||
|
||||
private _maskColor = "";
|
||||
|
||||
private _maskShown = false;
|
||||
|
||||
// Separate from _isZoomed, whose touch handling reruns graph layouts
|
||||
@state() private _isGraphRoamed = false;
|
||||
|
||||
@@ -454,6 +492,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
if (!this.chart) {
|
||||
return;
|
||||
}
|
||||
if (changedProps.has("selectMode")) {
|
||||
this._updateSelectMode();
|
||||
}
|
||||
const themeChanged = changedProps.has("_themes") && this.hasUpdated;
|
||||
if (!themeChanged && !DEFERRED_PROPS.some((p) => changedProps.has(p))) {
|
||||
return;
|
||||
@@ -499,6 +540,8 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
) {
|
||||
this._disposeSonification();
|
||||
}
|
||||
} else if (changedProps.has("highlight")) {
|
||||
this._updateMask();
|
||||
}
|
||||
if (changedProps.has("options")) {
|
||||
chartOptions = { ...chartOptions, ...this._createOptions() };
|
||||
@@ -888,6 +931,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
const style = getComputedStyle(this);
|
||||
echarts.registerTheme("custom", this._createTheme(style));
|
||||
this._maskColor =
|
||||
style.getPropertyValue("--card-background-color").trim() ||
|
||||
style.getPropertyValue("--primary-background-color").trim();
|
||||
|
||||
this.chart = echarts.init(this._chartContainer!, "custom");
|
||||
this._dragToZoom = false;
|
||||
@@ -970,6 +1016,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
this._legendItemCount = this._getLegendItems()?.length;
|
||||
this._updateSankeyRoam();
|
||||
this._updateDragToZoom();
|
||||
if (this.selectMode !== "none") {
|
||||
this._updateSelectMode();
|
||||
}
|
||||
if (zoomStart !== 0 || zoomEnd !== 100) {
|
||||
this.zoom(zoomStart, zoomEnd, true);
|
||||
}
|
||||
@@ -1021,7 +1070,10 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
|
||||
// A chart can switch type (e.g. pie and bar) without being rebuilt
|
||||
private _updateDragToZoom() {
|
||||
const active = !this._touchInput && this._hasZoomableXAxis();
|
||||
const active =
|
||||
!this._touchInput &&
|
||||
this._hasZoomableXAxis() &&
|
||||
this.selectMode !== "range";
|
||||
if (!this.chart || active === this._dragToZoom) {
|
||||
return;
|
||||
}
|
||||
@@ -1033,6 +1085,130 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
});
|
||||
}
|
||||
|
||||
private _snapRange(range: ChartTimeRange) {
|
||||
return this.snapSelection ? this.snapSelection(range) : range;
|
||||
}
|
||||
|
||||
private _getMaskArea(): MarkAreaComponentOption | undefined {
|
||||
const range = this._selectingRange ?? this.highlight;
|
||||
if (!range) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
silent: true,
|
||||
z: 10,
|
||||
itemStyle: {
|
||||
color: this._maskColor,
|
||||
opacity: MASK_OPACITY,
|
||||
},
|
||||
data: [
|
||||
[{ xAxis: -Infinity }, { xAxis: range.start }],
|
||||
[{ xAxis: range.end }, { xAxis: Infinity }],
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
// Only the first series carries the mask, merged in without resending data
|
||||
private _updateMask() {
|
||||
const maskArea = this._getMaskArea();
|
||||
if (maskArea) {
|
||||
this._maskShown = true;
|
||||
}
|
||||
this.chart?.setOption({
|
||||
series: [{ markArea: maskArea ?? { data: [] } }],
|
||||
});
|
||||
}
|
||||
|
||||
private _handleSelectPointerDown = (e: ECElementEvent) => {
|
||||
this._pointerDownX = e.offsetX;
|
||||
};
|
||||
|
||||
private _handleSelectClick = (e: ECElementEvent) => {
|
||||
const point = [e.offsetX, e.offsetY];
|
||||
// A drag that ends on the plot is not a click
|
||||
const dragged =
|
||||
this._pointerDownX !== undefined &&
|
||||
Math.abs(e.offsetX - this._pointerDownX) > CLICK_DRAG_TOLERANCE;
|
||||
if (dragged || !this.chart?.containPixel("grid", point)) {
|
||||
return;
|
||||
}
|
||||
const [x] = this.chart.convertFromPixel("grid", point) as number[];
|
||||
const selection = this._snapRange({ start: x, end: x });
|
||||
if (selection) {
|
||||
fireEvent(this, "chart-select", selection);
|
||||
}
|
||||
};
|
||||
|
||||
private _handleBrush = (e: any) => {
|
||||
const range = e.areas?.[0]?.coordRange as number[] | undefined;
|
||||
if (range) {
|
||||
this._selectingRange = this._snapRange({
|
||||
start: range[0],
|
||||
end: range[1],
|
||||
});
|
||||
this._updateMask();
|
||||
}
|
||||
};
|
||||
|
||||
private _handleBrushEnd = (e: any) => {
|
||||
const range = e.areas?.[0]?.coordRange as number[] | undefined;
|
||||
this.chart?.dispatchAction({ type: "brush", areas: [] });
|
||||
this._selectingRange = undefined;
|
||||
this._updateMask();
|
||||
const selection =
|
||||
range && this._snapRange({ start: range[0], end: range[1] });
|
||||
if (selection) {
|
||||
fireEvent(this, "chart-select", selection);
|
||||
}
|
||||
};
|
||||
|
||||
private _updateSelectMode() {
|
||||
if (!this.chart) {
|
||||
return;
|
||||
}
|
||||
const zr = this.chart.getZr();
|
||||
zr.off("mousedown", this._handleSelectPointerDown);
|
||||
zr.off("click", this._handleSelectClick);
|
||||
this.chart.off("brush", this._handleBrush);
|
||||
this.chart.off("brushEnd", this._handleBrushEnd);
|
||||
if (this.selectMode !== "none") {
|
||||
zr.on("mousedown", this._handleSelectPointerDown);
|
||||
zr.on("click", this._handleSelectClick);
|
||||
}
|
||||
const selectRange = this.selectMode === "range";
|
||||
if (selectRange) {
|
||||
this.chart.on("brush", this._handleBrush);
|
||||
this.chart.on("brushEnd", this._handleBrushEnd);
|
||||
this.chart.setOption({
|
||||
brush: {
|
||||
xAxisIndex: 0,
|
||||
// Only measures the range, the mask fades what is outside
|
||||
seriesIndex: [],
|
||||
transformable: false,
|
||||
brushStyle: BRUSH_STYLE,
|
||||
},
|
||||
});
|
||||
}
|
||||
const brushCursor = {
|
||||
type: "takeGlobalCursor",
|
||||
key: "brush",
|
||||
brushOption: {
|
||||
brushType: selectRange ? "lineX" : false,
|
||||
brushMode: "single",
|
||||
brushStyle: BRUSH_STYLE,
|
||||
},
|
||||
};
|
||||
// Brush and drag to zoom share the global cursor, the last one taken wins
|
||||
if (selectRange) {
|
||||
this._updateDragToZoom();
|
||||
this.chart.dispatchAction(brushCursor);
|
||||
} else {
|
||||
this.chart.dispatchAction(brushCursor);
|
||||
this._dragToZoom = false;
|
||||
this._updateDragToZoom();
|
||||
}
|
||||
}
|
||||
|
||||
private _hasZoomableXAxis() {
|
||||
const xAxis = ensureArray(this.options?.xAxis)?.[0] as
|
||||
XAXisOption | undefined;
|
||||
@@ -1475,7 +1651,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
private _getSeries() {
|
||||
const xAxis = (this.options?.xAxis?.[0] ?? this.options?.xAxis) as
|
||||
XAXisOption | undefined;
|
||||
const series = ensureArray(this.data).map((s) => {
|
||||
const maskArea = this._getMaskArea();
|
||||
if (maskArea) {
|
||||
this._maskShown = true;
|
||||
}
|
||||
const series = ensureArray(this.data).map((s, index) => {
|
||||
const data = this._hiddenDatasets.has(String(s.id ?? s.name))
|
||||
? undefined
|
||||
: s.data;
|
||||
@@ -1513,6 +1693,16 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
} as HaECSeriesItem;
|
||||
}
|
||||
}
|
||||
// ECharts merges series by id and would keep a mask left out here
|
||||
if (this._maskShown && (s.type === "line" || s.type === "bar")) {
|
||||
result = {
|
||||
...result,
|
||||
markArea:
|
||||
index === 0 && maskArea
|
||||
? maskArea
|
||||
: ((s as LineSeriesOption).markArea ?? { data: [] }),
|
||||
} as HaECSeriesItem;
|
||||
}
|
||||
return processSeriesTooltipFormatter(result);
|
||||
});
|
||||
return series as ECOption["series"];
|
||||
@@ -1762,7 +1952,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
|
||||
// it, so a quick drag out would lose the release and its selection
|
||||
if (
|
||||
ev.type === "pointerdown" &&
|
||||
this._dragToZoom &&
|
||||
(this._dragToZoom || this.selectMode === "range") &&
|
||||
this._isZoomPress(ev)
|
||||
) {
|
||||
this.chart
|
||||
@@ -2337,6 +2527,7 @@ declare global {
|
||||
"dataset-hidden": { id: string };
|
||||
"dataset-unhidden": { id: string };
|
||||
"chart-click": ECElementEvent;
|
||||
"chart-select": ChartTimeRange;
|
||||
"legend-label-click": { id: string };
|
||||
"chart-zoom": {
|
||||
start: number;
|
||||
|
||||
@@ -76,6 +76,18 @@ export interface NetworkData {
|
||||
|
||||
const PHYSICS_DISABLE_THRESHOLD = 512;
|
||||
|
||||
const LAYOUT_ANIMATION_THRESHOLD = 100;
|
||||
|
||||
// Every event of a change of the legend selection, each with the whole
|
||||
// selection
|
||||
const LEGEND_SELECT_EVENTS = [
|
||||
"legendselectchanged",
|
||||
"legendselected",
|
||||
"legendunselected",
|
||||
"legendselectall",
|
||||
"legendinverseselect",
|
||||
];
|
||||
|
||||
const SELECTED_NODE_MAX_ZOOM = 2;
|
||||
|
||||
// Keeps neighbors clear of the search field, buttons and legend
|
||||
@@ -124,8 +136,22 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
@state() private _showLabels = true;
|
||||
|
||||
// Not reactive: a new series option starts the layout again, so a drop only
|
||||
// reaches the option with the next render
|
||||
private _nodePositions: Record<string, { x: number; y: number }> = {};
|
||||
|
||||
// Dragged nodes stay where they are dropped, the force layout moves the others
|
||||
private _pinnedNodes: string[] = [];
|
||||
|
||||
// Names of the legend categories that are switched off. Not reactive: the
|
||||
// legend lays the graph out itself, only the layout animation threshold
|
||||
// needs a render
|
||||
private _hiddenCategories: string[] = [];
|
||||
|
||||
private _dragNode?: string;
|
||||
|
||||
private _dragMoved = false;
|
||||
|
||||
private _followSelectedNode = false;
|
||||
|
||||
private _followedChart?: EChartsType;
|
||||
@@ -170,12 +196,15 @@ export class HaNetworkGraph extends LitElement {
|
||||
this._showLabels,
|
||||
isMobile,
|
||||
hasHighlightedNodes,
|
||||
this.selectedNode
|
||||
this.selectedNode,
|
||||
this._nodePositions,
|
||||
this._pinnedNodes,
|
||||
this._fewVisibleNodes()
|
||||
)}
|
||||
.options=${this._createOptions(this.data?.categories)}
|
||||
height="100%"
|
||||
.extraComponents=${[GraphChart]}
|
||||
@chart-setup=${this._updateFollowing}
|
||||
@chart-setup=${this._handleChartSetup}
|
||||
>
|
||||
<slot name="search" slot="search"></slot>
|
||||
<slot name="button" slot="button"></slot>
|
||||
@@ -273,7 +302,10 @@ export class HaNetworkGraph extends LitElement {
|
||||
showLabels: boolean,
|
||||
isMobile: boolean,
|
||||
hasHighlightedNodes?: boolean,
|
||||
selectedNode?: string
|
||||
selectedNode?: string,
|
||||
nodePositions: Record<string, { x: number; y: number }> = {},
|
||||
pinnedNodes: string[] = [],
|
||||
fewVisibleNodes = true
|
||||
) => ({
|
||||
id: "network",
|
||||
type: "graph",
|
||||
@@ -311,14 +343,15 @@ export class HaNetworkGraph extends LitElement {
|
||||
repulsion: [400, 600],
|
||||
edgeLength: [200, 350],
|
||||
gravity: 0.05,
|
||||
layoutAnimation: !reducedMotion && data.nodes.length < 100,
|
||||
layoutAnimation: !reducedMotion && fewVisibleNodes,
|
||||
},
|
||||
edgeSymbol: ["none", "arrow"],
|
||||
edgeSymbolSize: 10,
|
||||
data: this._getSeriesData(
|
||||
data.nodes,
|
||||
data.links,
|
||||
this._nodePositions,
|
||||
nodePositions,
|
||||
pinnedNodes,
|
||||
selectedNode
|
||||
),
|
||||
links: data.links.map((link) => ({
|
||||
@@ -334,11 +367,25 @@ export class HaNetworkGraph extends LitElement {
|
||||
deepEqual
|
||||
);
|
||||
|
||||
// The legend leaves the nodes of hidden categories out of the layout
|
||||
private _fewVisibleNodes() {
|
||||
const hidden = this._hiddenCategories;
|
||||
const visibleNodes = hidden.length
|
||||
? this.data.nodes.filter(
|
||||
(node) =>
|
||||
node.category === undefined ||
|
||||
!hidden.includes(this.data.categories?.[node.category]?.name ?? "")
|
||||
).length
|
||||
: this.data.nodes.length;
|
||||
return visibleNodes < LAYOUT_ANIMATION_THRESHOLD;
|
||||
}
|
||||
|
||||
private _getSeriesData = memoizeOne(
|
||||
(
|
||||
nodes: NetworkNode[],
|
||||
links: NetworkLink[],
|
||||
nodePositions: Record<string, { x: number; y: number }>,
|
||||
pinnedNodes: string[],
|
||||
selectedNode?: string
|
||||
) =>
|
||||
this._getPositionedNodes(nodes, links, nodePositions).map((node) => {
|
||||
@@ -355,7 +402,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
? { ...node.itemStyle, borderWidth: 3 }
|
||||
: node.itemStyle || {},
|
||||
label: selected ? { ...node.label, fontWeight: "bold" } : node.label,
|
||||
fixed: node.fixed,
|
||||
fixed: node.fixed || pinnedNodes.includes(node.id),
|
||||
x: node.x,
|
||||
y: node.y,
|
||||
} as NonNullable<GraphSeriesOption["data"]>[number];
|
||||
@@ -515,6 +562,90 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _handleChartSetup() {
|
||||
const chart = this._baseChart?.chart;
|
||||
chart?.on("mousedown", this._handleNodeMouseDown);
|
||||
chart?.getZr().on("drag", this._handleDrag);
|
||||
chart?.getZr().on("dragend", this._handleDragEnd);
|
||||
for (const event of LEGEND_SELECT_EVENTS) {
|
||||
chart?.on(event, this._handleLegendChange);
|
||||
}
|
||||
const legend = (
|
||||
chart?.getOption() as
|
||||
{ legend?: { selected?: Record<string, boolean> }[] } | undefined
|
||||
)?.legend?.[0];
|
||||
this._setHiddenCategories(legend?.selected ?? {});
|
||||
// A recreated chart, e.g. after a theme change, lacks the drops since the
|
||||
// last render
|
||||
this.requestUpdate();
|
||||
this._updateFollowing();
|
||||
}
|
||||
|
||||
private _handleLegendChange = (params: unknown) => {
|
||||
const fewVisibleNodes = this._fewVisibleNodes();
|
||||
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();
|
||||
}
|
||||
};
|
||||
|
||||
private _setHiddenCategories(selected: Record<string, boolean>) {
|
||||
this._hiddenCategories = Object.keys(selected).filter(
|
||||
(name) => !selected[name]
|
||||
);
|
||||
}
|
||||
|
||||
private _handleNodeMouseDown = (params: {
|
||||
dataType?: string;
|
||||
data?: unknown;
|
||||
}) => {
|
||||
this._dragNode =
|
||||
params.dataType === "node" ? (params.data as NetworkNode).id : undefined;
|
||||
this._dragMoved = false;
|
||||
};
|
||||
|
||||
private _handleDrag = () => {
|
||||
this._dragMoved = true;
|
||||
};
|
||||
|
||||
private _handleDragEnd = () => {
|
||||
const id = this._dragNode;
|
||||
const moved = this._dragMoved;
|
||||
this._dragNode = undefined;
|
||||
this._dragMoved = false;
|
||||
// A click also ends a drag, which releases a pinned node in ECharts
|
||||
if (!id || (!moved && !this._pinnedNodes.includes(id))) {
|
||||
return;
|
||||
}
|
||||
this._pinNodeInChart(id);
|
||||
if (!this._pinnedNodes.includes(id)) {
|
||||
this._pinnedNodes = [...this._pinnedNodes, id];
|
||||
}
|
||||
this._saveNodePositions();
|
||||
};
|
||||
|
||||
// A new series option would start the layout again, so the pin goes into
|
||||
// the running force layout, and into the item option that ECharts lays out
|
||||
// from again, e.g. on a legend change
|
||||
private _pinNodeInChart(id: string) {
|
||||
const series = this._getGraphSeries();
|
||||
const node = series?.getGraph().getNodeById(id);
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
series.forceLayout?.setFixed(node.dataIndex);
|
||||
const [x, y] = node.getLayout();
|
||||
Object.assign(series.getData().getRawDataItem(node.dataIndex), {
|
||||
fixed: true,
|
||||
x,
|
||||
y,
|
||||
});
|
||||
}
|
||||
|
||||
private _updateFollowing() {
|
||||
const chart = this._followSelectedNode ? this._baseChart?.chart : undefined;
|
||||
if (chart !== this._followedChart) {
|
||||
@@ -550,10 +681,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
if (!chart) {
|
||||
return;
|
||||
}
|
||||
const series: any = chart
|
||||
// @ts-ignore private method but no other way to get the graph positions
|
||||
.getModel()
|
||||
.getSeriesByIndex(0);
|
||||
const series = this._getGraphSeries(chart);
|
||||
const node = series?.getGraph().getNodeById(this.selectedNode);
|
||||
const position: number[] | undefined = node?.getLayout();
|
||||
if (!position) {
|
||||
@@ -614,6 +742,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
private _togglePhysics() {
|
||||
this._saveNodePositions();
|
||||
this._pinnedNodes = [];
|
||||
this._physicsEnabled = !this._physicsEnabled;
|
||||
}
|
||||
|
||||
@@ -622,26 +751,30 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
|
||||
private _saveNodePositions() {
|
||||
const positions = {};
|
||||
if (this._baseChart?.chart) {
|
||||
this._baseChart.chart
|
||||
// @ts-ignore private method but no other way to get the graph positions
|
||||
.getModel()
|
||||
.getSeriesByIndex(0)
|
||||
.getGraph()
|
||||
.eachNode((node: any) => {
|
||||
const layout = node.getLayout();
|
||||
if (layout) {
|
||||
positions[node.id] = {
|
||||
x: layout[0],
|
||||
y: layout[1],
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
// Nodes that are not drawn keep their earlier position
|
||||
const positions = { ...this._nodePositions };
|
||||
this._getGraphSeries()
|
||||
?.getGraph()
|
||||
.eachNode((node: any) => {
|
||||
const layout = node.getLayout();
|
||||
if (layout) {
|
||||
positions[node.id] = {
|
||||
x: layout[0],
|
||||
y: layout[1],
|
||||
};
|
||||
}
|
||||
});
|
||||
this._nodePositions = positions;
|
||||
}
|
||||
|
||||
private _getGraphSeries(chart = this._baseChart?.chart): any {
|
||||
if (!chart || chart.isDisposed()) {
|
||||
return undefined;
|
||||
}
|
||||
// @ts-ignore private method but no other way to get the graph
|
||||
return chart.getModel().getSeriesByIndex(0);
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
import type { HassConfig, HassEntities } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { isComponentLoaded } from "../../common/config/is_component_loaded";
|
||||
@@ -49,7 +49,13 @@ import type {
|
||||
HomeAssistantUI,
|
||||
} from "../../types";
|
||||
import { getPeriodicAxisLabelConfig } from "./axis-label";
|
||||
import type { CustomLegendOption } from "./ha-chart-base";
|
||||
import type {
|
||||
ChartSelectMode,
|
||||
ChartTimeRange,
|
||||
CustomLegendOption,
|
||||
HaChartBase,
|
||||
ZoomSliderMode,
|
||||
} from "./ha-chart-base";
|
||||
import "./ha-chart-base";
|
||||
import { sideTooltipPosition } from "./chart-tooltip-position";
|
||||
import "./ha-chart-tooltip-marker";
|
||||
@@ -128,6 +134,16 @@ export class StatisticsChart extends LitElement {
|
||||
@property({ attribute: "expand-legend", type: Boolean })
|
||||
public expandLegend?: boolean;
|
||||
|
||||
@property({ attribute: "select-mode" })
|
||||
public selectMode: ChartSelectMode = "none";
|
||||
|
||||
@property({ attribute: "zoom-slider" })
|
||||
public zoomSlider: ZoomSliderMode = "auto";
|
||||
|
||||
@property({ attribute: false }) public highlight?: ChartTimeRange;
|
||||
|
||||
@query("ha-chart-base") private _chartBase?: HaChartBase;
|
||||
|
||||
@state() private _chartData: (LineSeriesOption | BarSeriesOption)[] = [];
|
||||
|
||||
@state() private _legendData: CustomLegendOption["data"];
|
||||
@@ -244,8 +260,12 @@ export class StatisticsChart extends LitElement {
|
||||
return html`
|
||||
<ha-chart-base
|
||||
.data=${this._chartData}
|
||||
.highlight=${this.highlight}
|
||||
.snapSelection=${this._snapSelection}
|
||||
.options=${this._chartOptions}
|
||||
.height=${this.height}
|
||||
.selectMode=${this.selectMode}
|
||||
.zoomSlider=${this.zoomSlider}
|
||||
style=${styleMap({ height: this.height })}
|
||||
@dataset-hidden=${this._datasetHidden}
|
||||
@dataset-unhidden=${this._datasetUnhidden}
|
||||
@@ -259,6 +279,39 @@ export class StatisticsChart extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
public resetZoom() {
|
||||
this._chartBase?.zoom(0, 100);
|
||||
}
|
||||
|
||||
// A click selects the period that contains it, a drag every period it
|
||||
// touches
|
||||
private _snapSelection = (
|
||||
range: ChartTimeRange
|
||||
): ChartTimeRange | undefined => {
|
||||
let start: number | undefined;
|
||||
let end: number | undefined;
|
||||
Object.entries(this.statisticsData ?? {}).forEach(
|
||||
([statisticId, values]) => {
|
||||
if (this._hiddenStats.has(statisticId)) {
|
||||
return;
|
||||
}
|
||||
values.forEach((value) => {
|
||||
const touched =
|
||||
range.start === range.end
|
||||
? value.start <= range.start && range.start < value.end
|
||||
: value.start < range.end && value.end > range.start;
|
||||
if (touched) {
|
||||
start = Math.min(start ?? value.start, value.start);
|
||||
end = Math.max(end ?? value.end, value.end);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
return start === undefined || end === undefined
|
||||
? undefined
|
||||
: { start, end };
|
||||
};
|
||||
|
||||
private _datasetHidden(ev: HASSDomEvent<HASSDomEvents["dataset-hidden"]>) {
|
||||
this._hiddenStats.add(ev.detail.id);
|
||||
this.requestUpdate("_hiddenStats");
|
||||
|
||||
@@ -35,24 +35,27 @@ function computeTimelineStateColor(
|
||||
|
||||
const domain = computeDomain(stateObj.entity_id);
|
||||
|
||||
// Zone states for person/device_tracker don't have specific CSS color variables,
|
||||
// so they all fall back to the same --state-person-active-color.
|
||||
// Only use a custom CSS variable if explicitly defined (e.g. --state-person-kitchen-color),
|
||||
// otherwise return undefined to get unique colors from the generic color handler.
|
||||
if (
|
||||
// Zone states would all share --state-person-active-color, so only an
|
||||
// exact state variable may color them, like states of uncolored domains.
|
||||
const isZoneState =
|
||||
(domain === "person" || domain === "device_tracker") &&
|
||||
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state)
|
||||
) {
|
||||
return computeCssValue(
|
||||
`--state-${domain}-${slugify(state, "_")}-color`,
|
||||
computedStyles
|
||||
);
|
||||
}
|
||||
|
||||
const properties = stateColorProperties(stateObj, state);
|
||||
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state);
|
||||
const properties = isZoneState
|
||||
? undefined
|
||||
: stateColorProperties(stateObj, state);
|
||||
|
||||
if (!properties) {
|
||||
return undefined;
|
||||
const stateKey = slugify(state, "_");
|
||||
const deviceClass = stateObj.attributes.device_class;
|
||||
return computeCssValue(
|
||||
[
|
||||
...(deviceClass
|
||||
? [`--state-${domain}-${deviceClass}-${stateKey}-color`]
|
||||
: []),
|
||||
`--state-${domain}-${stateKey}-color`,
|
||||
],
|
||||
computedStyles
|
||||
);
|
||||
}
|
||||
|
||||
const rgb = computeCssValue(properties, computedStyles);
|
||||
|
||||
@@ -1663,7 +1663,8 @@ export class HaDataTable extends LitElement {
|
||||
}
|
||||
|
||||
.mdc-data-table__row ~ .mdc-data-table__row {
|
||||
border-top: 1px solid var(--divider-color);
|
||||
border-top: var(--data-table-row-border-width, 1px) solid
|
||||
var(--divider-color);
|
||||
}
|
||||
|
||||
.mdc-data-table__row.clickable:not(
|
||||
|
||||
@@ -52,7 +52,7 @@ class StateInfo extends LitElement {
|
||||
${
|
||||
this.inDialog
|
||||
? html`<div class="time-ago">
|
||||
<ha-tooltip for="relative-time">
|
||||
<ha-tooltip for="relative-time" trigger="hover focus click">
|
||||
<div class="row">
|
||||
<span class="column-name">
|
||||
${this._localize(
|
||||
|
||||
@@ -6,7 +6,7 @@ import { repeat } from "lit/directives/repeat";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { fireEvent, type HASSDomEvent } from "../common/dom/fire_event";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import {
|
||||
CameraEntityFeature,
|
||||
@@ -17,8 +17,14 @@ import {
|
||||
STREAM_TYPE_WEB_RTC,
|
||||
type CameraCapabilities,
|
||||
type CameraEntity,
|
||||
type StreamType,
|
||||
} from "../data/camera";
|
||||
import {
|
||||
MJPEG_STREAM,
|
||||
selectCameraStreams,
|
||||
type CameraStream,
|
||||
type CameraStreamTracks,
|
||||
type CameraStreamType,
|
||||
} from "../data/camera-streams";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
@@ -29,14 +35,7 @@ import "./ha-hls-player";
|
||||
import "./ha-web-rtc-player";
|
||||
import type { HaWebRtcPlayer } from "./ha-web-rtc-player";
|
||||
|
||||
const MJPEG_STREAM = "mjpeg";
|
||||
|
||||
export type CameraStreamType = StreamType | typeof MJPEG_STREAM;
|
||||
|
||||
interface Stream {
|
||||
type: CameraStreamType;
|
||||
visible: boolean;
|
||||
}
|
||||
export type { CameraStreamType } from "../data/camera-streams";
|
||||
|
||||
@customElement("ha-camera-stream")
|
||||
export class HaCameraStream extends LitElement {
|
||||
@@ -78,13 +77,15 @@ export class HaCameraStream extends LitElement {
|
||||
|
||||
@state() private _capabilities?: CameraCapabilities;
|
||||
|
||||
@state() private _hlsStreams?: { hasAudio: boolean; hasVideo: boolean };
|
||||
@state() private _hlsStreams?: CameraStreamTracks;
|
||||
|
||||
@state() private _webRtcStreams?: { hasAudio: boolean; hasVideo: boolean };
|
||||
@state() private _webRtcStreams?: CameraStreamTracks;
|
||||
|
||||
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
|
||||
|
||||
private _visibleStreamType?: Stream["type"];
|
||||
private _visibleStreamType?: CameraStreamType;
|
||||
|
||||
private _capabilitiesRequest = 0;
|
||||
|
||||
private _thumbnailApi = memoizeOne(
|
||||
(
|
||||
@@ -132,6 +133,10 @@ export class HaCameraStream extends LitElement {
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._connected = true;
|
||||
if (this.hasUpdated) {
|
||||
// The players start again when reattached, so their results do as well
|
||||
this._resetStreams();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
@@ -146,9 +151,8 @@ export class HaCameraStream extends LitElement {
|
||||
capabilities: this._capabilities,
|
||||
});
|
||||
}
|
||||
const visibleStreamType = this._currentStreams().find(
|
||||
(stream) => stream.visible
|
||||
)?.type;
|
||||
const streams = this._currentStreams();
|
||||
const visibleStreamType = streams.find((stream) => stream.visible)?.type;
|
||||
if (visibleStreamType !== this._visibleStreamType) {
|
||||
this._visibleStreamType = visibleStreamType;
|
||||
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
|
||||
@@ -167,7 +171,7 @@ export class HaCameraStream extends LitElement {
|
||||
)}`;
|
||||
}
|
||||
|
||||
private _renderStream(stream: Stream) {
|
||||
private _renderStream(stream: CameraStream) {
|
||||
if (!this.stateObj) {
|
||||
return nothing;
|
||||
}
|
||||
@@ -229,15 +233,14 @@ export class HaCameraStream extends LitElement {
|
||||
return this._streams(
|
||||
this._capabilities?.frontend_stream_types,
|
||||
this._hlsStreams,
|
||||
this._webRtcStreams,
|
||||
this.muted
|
||||
this._webRtcStreams
|
||||
);
|
||||
}
|
||||
|
||||
private async _getCapabilities() {
|
||||
this._capabilities = undefined;
|
||||
this._hlsStreams = undefined;
|
||||
this._webRtcStreams = undefined;
|
||||
this._resetStreams();
|
||||
const request = ++this._capabilitiesRequest;
|
||||
if (!supportsFeature(this.stateObj!, CameraEntityFeature.STREAM)) {
|
||||
this._capabilities = {
|
||||
frontend_stream_types: [],
|
||||
@@ -245,10 +248,19 @@ export class HaCameraStream extends LitElement {
|
||||
};
|
||||
return;
|
||||
}
|
||||
this._capabilities = await fetchCameraCapabilities(
|
||||
const capabilities = await fetchCameraCapabilities(
|
||||
this._api,
|
||||
this.stateObj!.entity_id
|
||||
);
|
||||
if (request !== this._capabilitiesRequest) {
|
||||
return;
|
||||
}
|
||||
this._capabilities = capabilities;
|
||||
}
|
||||
|
||||
private _resetStreams() {
|
||||
this._hlsStreams = undefined;
|
||||
this._webRtcStreams = undefined;
|
||||
}
|
||||
|
||||
private async _getPosterUrl(): Promise<void> {
|
||||
@@ -269,89 +281,38 @@ export class HaCameraStream extends LitElement {
|
||||
fireEvent(this, "load");
|
||||
}
|
||||
|
||||
private _handleHlsStreams(ev: CustomEvent) {
|
||||
private _handleHlsStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
|
||||
this._hlsStreams = ev.detail;
|
||||
}
|
||||
|
||||
private _handleWebRtcStreams(ev: CustomEvent) {
|
||||
private _handleWebRtcStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
|
||||
if (
|
||||
!ev.detail.hasVideo &&
|
||||
!ev.detail.hasAudio &&
|
||||
this._capabilities?.frontend_stream_types.length === 1 &&
|
||||
typeof RTCPeerConnection !== "undefined"
|
||||
) {
|
||||
// Without another stream type, keep the player to show why it failed.
|
||||
// Only a browser without WebRTC falls back to MJPEG.
|
||||
return;
|
||||
}
|
||||
this._webRtcStreams = ev.detail;
|
||||
}
|
||||
|
||||
private _streams = memoizeOne(
|
||||
(
|
||||
supportedTypes?: StreamType[],
|
||||
hlsStreams?: { hasAudio: boolean; hasVideo: boolean },
|
||||
webRtcStreams?: { hasAudio: boolean; hasVideo: boolean },
|
||||
muted?: boolean
|
||||
): Stream[] => {
|
||||
supportedTypes?: CameraCapabilities["frontend_stream_types"],
|
||||
hlsStreams?: CameraStreamTracks,
|
||||
webRtcStreams?: CameraStreamTracks
|
||||
): CameraStream[] => {
|
||||
if (__DEMO__) {
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
if (!supportedTypes) {
|
||||
return [];
|
||||
}
|
||||
if (supportedTypes.length === 0) {
|
||||
// doesn't support any stream type, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
if (supportedTypes.length === 1) {
|
||||
// only 1 stream type, no need to choose
|
||||
if (
|
||||
(supportedTypes[0] === STREAM_TYPE_HLS &&
|
||||
hlsStreams?.hasVideo === false) ||
|
||||
(supportedTypes[0] === STREAM_TYPE_WEB_RTC &&
|
||||
webRtcStreams?.hasVideo === false)
|
||||
) {
|
||||
// stream failed to load, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
return [{ type: supportedTypes[0], visible: true }];
|
||||
}
|
||||
if (hlsStreams && webRtcStreams) {
|
||||
// fully loaded
|
||||
if (
|
||||
hlsStreams.hasVideo &&
|
||||
hlsStreams.hasAudio &&
|
||||
!webRtcStreams.hasAudio &&
|
||||
!muted
|
||||
) {
|
||||
// webRTC stream is missing audio and audio is not muted, use HLS
|
||||
return [{ type: STREAM_TYPE_HLS, visible: true }];
|
||||
}
|
||||
if (webRtcStreams.hasVideo) {
|
||||
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
|
||||
}
|
||||
// both streams failed to load, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
|
||||
if (hlsStreams?.hasVideo !== webRtcStreams?.hasVideo) {
|
||||
// one of the two streams is loaded, or errored
|
||||
// choose the one that has video or is still loading
|
||||
if (hlsStreams?.hasVideo) {
|
||||
return [
|
||||
{ type: STREAM_TYPE_HLS, visible: true },
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: false },
|
||||
];
|
||||
}
|
||||
if (hlsStreams?.hasVideo === false) {
|
||||
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
|
||||
}
|
||||
if (webRtcStreams?.hasVideo) {
|
||||
return [
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: true },
|
||||
{ type: STREAM_TYPE_HLS, visible: false },
|
||||
];
|
||||
}
|
||||
if (webRtcStreams?.hasVideo === false) {
|
||||
return [{ type: STREAM_TYPE_HLS, visible: true }];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{ type: STREAM_TYPE_HLS, visible: true },
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: false },
|
||||
];
|
||||
return selectCameraStreams({
|
||||
supportedTypes,
|
||||
hlsStreams,
|
||||
webRtcStreams,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ class HaConfigNavigationList extends LitElement {
|
||||
return html`
|
||||
<ha-list-item-button
|
||||
.href=${externalApp ? undefined : page.path}
|
||||
.headline=${page.name}
|
||||
.supportingText=${this.hasSecondary ? page.description : undefined}
|
||||
@click=${externalApp ? this._handleExternalApp : undefined}
|
||||
>
|
||||
<ha-svg-icon
|
||||
@@ -43,14 +45,6 @@ class HaConfigNavigationList extends LitElement {
|
||||
.secondaryPath=${page.iconSecondaryPath}
|
||||
.viewBox=${page.iconViewBox}
|
||||
></ha-svg-icon>
|
||||
<span slot="headline">${page.name}</span>
|
||||
${
|
||||
this.hasSecondary
|
||||
? html`<span slot="supporting-text"
|
||||
>${page.description}</span
|
||||
>`
|
||||
: ""
|
||||
}
|
||||
${
|
||||
!this.narrow
|
||||
? html`<ha-icon-next slot="end"></ha-icon-next>`
|
||||
|
||||
@@ -387,7 +387,7 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _handleKeyDown(e: KeyboardEvent) {
|
||||
if (!A11Y_KEY_CODES.has(e.code)) return;
|
||||
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
|
||||
e.preventDefault();
|
||||
if (this._lastSlider) {
|
||||
this.shadowRoot?.getElementById(this._lastSlider)?.focus();
|
||||
@@ -439,7 +439,7 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _handleKeyUp(e: KeyboardEvent) {
|
||||
if (!A11Y_KEY_CODES.has(e.code)) return;
|
||||
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
|
||||
this._activeSlider = (e.currentTarget as any).id as ActiveSlider;
|
||||
e.preventDefault();
|
||||
fireEvent(this, `${this._activeSlider}-changing`, {
|
||||
|
||||
@@ -87,11 +87,12 @@ export class HaFilterCategories extends LitElement {
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._unsubscribeCategories();
|
||||
this._categories = [];
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues) {
|
||||
super.willUpdate(changedProps);
|
||||
if (changedProps.get("scope") !== undefined) {
|
||||
if (changedProps.has("scope") && this.scope !== this._categoriesScope) {
|
||||
this._categories = [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +112,9 @@ export class HaGenericPicker extends PickerMixin(LitElement) {
|
||||
|
||||
@property({ type: Boolean, attribute: "no-sort" }) public noSort = false;
|
||||
|
||||
@property({ attribute: "pin-block" })
|
||||
public pinBlock?: "start" | "center" | "end" | "nearest";
|
||||
|
||||
// Skip the "unknown value" highlight and note for a value that is not in the
|
||||
// list but that the value renderer presents on its own.
|
||||
@property({ type: Boolean, attribute: "no-unknown-state" })
|
||||
@@ -347,6 +350,7 @@ export class HaGenericPicker extends PickerMixin(LitElement) {
|
||||
.searchKeys=${this.searchKeys}
|
||||
.customValueLabel=${this.customValueLabel}
|
||||
.noSort=${this.noSort}
|
||||
.pinBlock=${this.pinBlock}
|
||||
></ha-picker-combo-box>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -26,7 +26,11 @@ export class HaHelpTooltip extends LitElement {
|
||||
protected render(): TemplateResult {
|
||||
return html`
|
||||
<ha-svg-icon id="svg-icon" .path=${mdiHelpCircleOutline}></ha-svg-icon>
|
||||
<ha-tooltip for="svg-icon" .placement=${this.position}>
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="svg-icon"
|
||||
.placement=${this.position}
|
||||
>
|
||||
${this.label}
|
||||
</ha-tooltip>
|
||||
`;
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { nextRender } from "../common/util/render-status";
|
||||
import { fetchStreamUrl } from "../data/camera";
|
||||
import { apiContext, configContext, connectionContext } from "../data/context";
|
||||
import { isExternal } from "../data/external";
|
||||
import "./ha-alert";
|
||||
|
||||
type HlsLite = Omit<
|
||||
@@ -71,7 +72,7 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
@state() private _errorIsFatal = false;
|
||||
|
||||
@state() private _url!: string;
|
||||
private _url?: string;
|
||||
|
||||
private _hlsPolyfillInstance?: HlsLite;
|
||||
|
||||
@@ -81,12 +82,22 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
private _hiddenCleanupTimeout?: number;
|
||||
|
||||
// Increased on every clean up, so a start that is still waiting on the
|
||||
// network knows it is outdated
|
||||
private _cleanUpCount = 0;
|
||||
|
||||
private _handleVisibilityChange = () => {
|
||||
if (document.pictureInPictureElement) {
|
||||
// video is playing in picture-in-picture mode, don't do anything
|
||||
return;
|
||||
}
|
||||
if (document.hidden) {
|
||||
if (isExternal) {
|
||||
// The companion apps pause JavaScript timers while in the background,
|
||||
// so a delayed clean up would not run until the app is opened again
|
||||
this._cleanUp();
|
||||
return;
|
||||
}
|
||||
this._hiddenCleanupTimeout = window.setTimeout(() => {
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
this._cleanUp();
|
||||
@@ -96,8 +107,7 @@ class HaHLSPlayer extends LitElement {
|
||||
clearTimeout(this._hiddenCleanupTimeout);
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
} else {
|
||||
this._resetError();
|
||||
this._startHls();
|
||||
this._restartHls();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -105,8 +115,7 @@ class HaHLSPlayer extends LitElement {
|
||||
super.connectedCallback();
|
||||
HaHLSPlayer.streamCount += 1;
|
||||
if (this.hasUpdated) {
|
||||
this._resetError();
|
||||
this._startHls();
|
||||
this._restartHls();
|
||||
}
|
||||
document.addEventListener("visibilitychange", this._handleVisibilityChange);
|
||||
}
|
||||
@@ -171,24 +180,44 @@ class HaHLSPlayer extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts the stream again, replacing a start that is still pending. */
|
||||
private _restartHls() {
|
||||
if (this.entityid) {
|
||||
// The stream URL stops working once the stream has been idle for a while
|
||||
this._getStreamUrlFromEntityId();
|
||||
return;
|
||||
}
|
||||
this._cleanUp();
|
||||
this._resetError();
|
||||
this._startHls();
|
||||
}
|
||||
|
||||
private async _getStreamUrlFromEntityId(): Promise<void> {
|
||||
this._cleanUp();
|
||||
this._resetError();
|
||||
this._url = undefined;
|
||||
|
||||
if (!isComponentLoaded(this._config.config, "stream")) {
|
||||
this._setFatalError("Streaming component is not loaded.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.entityid) {
|
||||
const entityId = this.entityid;
|
||||
if (!entityId) {
|
||||
return;
|
||||
}
|
||||
const cleanUpCount = this._cleanUpCount;
|
||||
try {
|
||||
const { url } = await fetchStreamUrl(
|
||||
{ callWS: this._api.callWS, hassUrl: this._connection.hassUrl },
|
||||
this.entityid
|
||||
entityId
|
||||
);
|
||||
|
||||
if (cleanUpCount !== this._cleanUpCount) {
|
||||
// Removed, hidden or switched camera while fetching
|
||||
return;
|
||||
}
|
||||
|
||||
this._url = this._connection.hassUrl(url);
|
||||
this._cleanUp();
|
||||
this._resetError();
|
||||
@@ -198,18 +227,27 @@ class HaHLSPlayer extends LitElement {
|
||||
// eslint-disable-next-line
|
||||
console.error(err);
|
||||
|
||||
if (cleanUpCount !== this._cleanUpCount || entityId !== this.entityid) {
|
||||
// Removed, hidden or switched camera while fetching
|
||||
return;
|
||||
}
|
||||
fireEvent(this, "streams", { hasAudio: false, hasVideo: false });
|
||||
}
|
||||
}
|
||||
|
||||
private async _startHls(): Promise<void> {
|
||||
const masterPlaylistPromise = fetch(this._url);
|
||||
const url = this._url;
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
const cleanUpCount = this._cleanUpCount;
|
||||
const masterPlaylistPromise = fetch(url);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
const Hls: typeof HlsType = (await import("hls.js/dist/hls.light.mjs"))
|
||||
.default;
|
||||
|
||||
if (!this.isConnected) {
|
||||
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -231,7 +269,7 @@ class HaHLSPlayer extends LitElement {
|
||||
this.allowExoPlayer && this._config.auth.external?.config.hasExoPlayer;
|
||||
const masterPlaylist = await (await masterPlaylistPromise).text();
|
||||
|
||||
if (!this.isConnected) {
|
||||
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -247,9 +285,9 @@ class HaHLSPlayer extends LitElement {
|
||||
let playlist_url: string;
|
||||
if (match !== null && matchTwice === null) {
|
||||
// Only send the regular playlist url if we match exactly once
|
||||
playlist_url = new URL(match[3], this._url).href;
|
||||
playlist_url = new URL(match[3], url).href;
|
||||
} else {
|
||||
playlist_url = this._url;
|
||||
playlist_url = url;
|
||||
}
|
||||
|
||||
const codecs = match ? `${match[1]},${match[2]}` : undefined;
|
||||
@@ -387,12 +425,17 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
private async _renderHLSNative(videoEl: HTMLVideoElement, url: string) {
|
||||
videoEl.src = url;
|
||||
videoEl.addEventListener("loadedmetadata", () => {
|
||||
videoEl.play();
|
||||
});
|
||||
videoEl.addEventListener(
|
||||
"loadedmetadata",
|
||||
() => {
|
||||
videoEl.play();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
}
|
||||
|
||||
private _cleanUp() {
|
||||
this._cleanUpCount++;
|
||||
if (this._hlsPolyfillInstance) {
|
||||
this._hlsPolyfillInstance.destroy();
|
||||
this._hlsPolyfillInstance = undefined;
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
|
||||
import type { TemplateResult } from "lit";
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import { LitElement, css, html } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { caseInsensitiveStringCompare } from "../common/string/compare";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { customIcons } from "../data/custom_icons";
|
||||
import type { ValueChangedEvent } from "../types";
|
||||
import "./ha-combo-box-item";
|
||||
import "./ha-generic-picker";
|
||||
import type { HaGenericPicker } from "./ha-generic-picker";
|
||||
import "./ha-icon";
|
||||
import type { PickerComboBoxItem } from "./ha-picker-combo-box";
|
||||
|
||||
@@ -50,16 +54,17 @@ const createIconItem = (icon: IconData, prefix: string): PickerComboBoxItem => {
|
||||
const loadIcons = async () => {
|
||||
ICONS_LOADED = true;
|
||||
|
||||
const iconList = await import("../../build/mdi/iconList.json");
|
||||
ICONS = iconList.default.map((icon) => createIconItem(icon, "mdi"));
|
||||
const sortIcons = (icons: PickerComboBoxItem[]) =>
|
||||
icons.sort((a, b) => caseInsensitiveStringCompare(a.id, b.id));
|
||||
|
||||
const customIconLoads: Promise<PickerComboBoxItem[]>[] = [];
|
||||
Object.keys(customIcons).forEach((iconSet) => {
|
||||
customIconLoads.push(loadCustomIconItems(iconSet));
|
||||
});
|
||||
(await Promise.all(customIconLoads)).forEach((customIconItems) => {
|
||||
ICONS.push(...customIconItems);
|
||||
});
|
||||
const iconList = await import("../../build/mdi/iconList.json");
|
||||
const mdiIcons = iconList.default.map((icon) => createIconItem(icon, "mdi"));
|
||||
ICONS = sortIcons([...mdiIcons]);
|
||||
|
||||
const customIconItems = await Promise.all(
|
||||
Object.keys(customIcons).map(loadCustomIconItems)
|
||||
);
|
||||
ICONS = sortIcons([...mdiIcons, ...customIconItems.flat()]);
|
||||
};
|
||||
|
||||
const loadCustomIconItems = async (
|
||||
@@ -81,8 +86,8 @@ const loadCustomIconItems = async (
|
||||
|
||||
const rowRenderer: RenderItemFunction<PickerComboBoxItem> = (item) => html`
|
||||
<ha-combo-box-item>
|
||||
<ha-icon .icon=${item.id} slot="start"></ha-icon>
|
||||
${item.id}
|
||||
<ha-icon .icon=${item.icon ?? item.id} slot="start"></ha-icon>
|
||||
${item.icon ?? item.id}
|
||||
</ha-combo-box-item>
|
||||
`;
|
||||
|
||||
@@ -104,12 +109,32 @@ export class HaIconPicker extends LitElement {
|
||||
|
||||
@property({ type: Boolean }) public invalid = false;
|
||||
|
||||
private _getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
|
||||
@property({ attribute: false }) public suggestedIcons?: string[];
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@query("ha-generic-picker") private _picker?: HaGenericPicker;
|
||||
|
||||
private _getIconPickerItems = () =>
|
||||
this._itemsWithSuggestions(ICONS, this.suggestedIcons, this._localize);
|
||||
|
||||
protected updated(changedProps: PropertyValues) {
|
||||
super.updated(changedProps);
|
||||
if (changedProps.has("suggestedIcons") || changedProps.has("_localize")) {
|
||||
this._picker?.refreshItems();
|
||||
}
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
return html`
|
||||
<ha-generic-picker
|
||||
allow-custom-value
|
||||
no-sort
|
||||
.pinBlock=${
|
||||
this.value && this.suggestedIcons?.includes(this.value)
|
||||
? "end"
|
||||
: undefined
|
||||
}
|
||||
.getItems=${this._getIconPickerItems}
|
||||
.helper=${this.helper}
|
||||
.disabled=${this.disabled}
|
||||
@@ -128,15 +153,35 @@ export class HaIconPicker extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _itemsWithSuggestions = memoizeOne(
|
||||
(
|
||||
icons: PickerComboBoxItem[],
|
||||
suggestedIcons: string[] | undefined,
|
||||
localize: LocalizeFunc
|
||||
): (PickerComboBoxItem | string)[] => {
|
||||
if (!suggestedIcons?.length) {
|
||||
return icons;
|
||||
}
|
||||
const suggested = new Set(suggestedIcons);
|
||||
return [
|
||||
localize("ui.components.icon_picker.suggested"),
|
||||
...suggestedIcons.map((icon) => ({ id: icon, primary: icon, icon })),
|
||||
localize("ui.components.icon_picker.all_icons"),
|
||||
...icons.filter((item) => !suggested.has(item.id)),
|
||||
];
|
||||
}
|
||||
);
|
||||
|
||||
// Filter can take a significant chunk of frame (up to 3-5 ms)
|
||||
private _filterIcons = memoizeOne(
|
||||
(
|
||||
filter: string,
|
||||
filteredItems: PickerComboBoxItem[],
|
||||
allItems: PickerComboBoxItem[]
|
||||
_allItems: PickerComboBoxItem[]
|
||||
): PickerComboBoxItem[] => {
|
||||
const normalizedFilter = filter.toLowerCase().replace(/\s+/g, "-");
|
||||
const iconItems = allItems?.length ? allItems : filteredItems;
|
||||
// The full list also holds the suggestions and their section titles
|
||||
const iconItems = ICONS.length ? ICONS : filteredItems;
|
||||
|
||||
if (!normalizedFilter.length) {
|
||||
return iconItems;
|
||||
@@ -175,8 +220,7 @@ export class HaIconPicker extends LitElement {
|
||||
protected firstUpdated() {
|
||||
if (!ICONS_LOADED) {
|
||||
loadIcons().then(() => {
|
||||
this._getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
|
||||
this.requestUpdate();
|
||||
this._picker?.refreshItems();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,10 @@ export class HaMarqueeText extends LitElement {
|
||||
|
||||
private _pauseTimeout?: number;
|
||||
|
||||
private get _animationFactor() {
|
||||
return document.dir === "rtl" ? -1 : 1;
|
||||
}
|
||||
|
||||
protected firstUpdated(changedProps: PropertyValues<this>) {
|
||||
super.firstUpdated(changedProps);
|
||||
|
||||
@@ -117,7 +121,7 @@ export class HaMarqueeText extends LitElement {
|
||||
reachedEnd = true;
|
||||
}
|
||||
}
|
||||
this._textSpan.style.transform = `translateX(${this._position}px)`;
|
||||
this._textSpan.style.transform = `translateX(${this._position * this._animationFactor}px)`;
|
||||
if (reachedEnd) {
|
||||
this._pauseTimeout = window.setTimeout(() => {
|
||||
this._pauseTimeout = undefined;
|
||||
|
||||
@@ -201,6 +201,9 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
|
||||
|
||||
@property({ type: Boolean, attribute: "no-sort" }) public noSort = false;
|
||||
|
||||
@property({ attribute: "pin-block" })
|
||||
public pinBlock?: "start" | "center" | "end" | "nearest";
|
||||
|
||||
@query(".list") private _list?: HaListBase;
|
||||
|
||||
@query("ha-input-search") private _searchFieldElement?: HaInputSearch;
|
||||
@@ -453,6 +456,7 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
|
||||
this.value
|
||||
)}
|
||||
.pinIndex=${this.value ? this._getInitialSelectedIndex() : undefined}
|
||||
.pinBlock=${this.pinBlock ?? "center"}
|
||||
@mousedown=${this._preventBlur}
|
||||
@focus=${this._focusList}
|
||||
@blur=${this._resetSelectedItem}
|
||||
@@ -685,6 +689,11 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
|
||||
fireEvent(this, "index-selected", { index, item, newTab });
|
||||
}
|
||||
|
||||
// Fuse indexes every row as text when the first one is a section title
|
||||
private _searchableItems = memoizeOne((items: PickerComboBoxItem[]) =>
|
||||
items.filter((item) => typeof item !== "string")
|
||||
);
|
||||
|
||||
private _fuseIndex = memoizeOne(
|
||||
(states: PickerComboBoxItem[], searchKeys?: FuseWeightedKey[]) =>
|
||||
Fuse.createIndex(searchKeys || DEFAULT_SEARCH_KEYS, states)
|
||||
@@ -708,10 +717,11 @@ export class HaPickerComboBox extends ScrollableFadeMixin(LitElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
const index = this._fuseIndex(this._allItems, this.searchKeys);
|
||||
const searchableItems = this._searchableItems(this._allItems);
|
||||
const index = this._fuseIndex(searchableItems, this.searchKeys);
|
||||
|
||||
let filteredItems = multiTermSortedSearch<PickerComboBoxItem>(
|
||||
this._allItems,
|
||||
searchableItems,
|
||||
searchString,
|
||||
(item) => item.id,
|
||||
index
|
||||
|
||||
@@ -171,6 +171,16 @@ export class HaRipple extends LitElement {
|
||||
return;
|
||||
}
|
||||
|
||||
// A touch long press opens the context menu while the press continues,
|
||||
// e.g. for a hold action. touchend or pointercancel ends it instead.
|
||||
if (
|
||||
ev.type === "contextmenu" &&
|
||||
this._startEvent &&
|
||||
isTouch(this._startEvent)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ev.type === "contextmenu" || ev.type === "touchend") {
|
||||
this._endPress();
|
||||
|
||||
@@ -193,13 +203,25 @@ export class HaRipple extends LitElement {
|
||||
break;
|
||||
case "pointerenter":
|
||||
this._hovered = true;
|
||||
|
||||
if (this._state === "waiting-for-click") {
|
||||
if (ev.buttons === 1) {
|
||||
// Back on the control with the press still held
|
||||
this._pressed = true;
|
||||
} else {
|
||||
// The press was released off the control, so no click follows
|
||||
this._endPress();
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
case "pointerleave":
|
||||
this._hovered = false;
|
||||
|
||||
// Release a held mouse or pen press that moves off the control
|
||||
if (this._state !== "inactive") {
|
||||
this._endPress();
|
||||
// A mouse or pen press that moves off the control still clicks if it
|
||||
// is released back on it, so only hide the press until it returns
|
||||
if (this._state === "waiting-for-click") {
|
||||
this._pressed = false;
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import type { ColorTempSelector } from "../../data/selector";
|
||||
import "../ha-labeled-slider";
|
||||
import { generateColorTemperatureGradient } from "../../dialogs/more-info/components/lights/light-color-temp-picker";
|
||||
import { kelvinRangeFromEntityStates } from "../../common/color/color-temp-selector-range";
|
||||
import {
|
||||
DEFAULT_MAX_KELVIN,
|
||||
DEFAULT_MIN_KELVIN,
|
||||
mired2kelvin,
|
||||
} from "../../common/color/convert-light-color";
|
||||
import { consumeEntityStates } from "../../common/decorators/consume-context-entry";
|
||||
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
|
||||
import type { ColorTempSelector } from "../../data/selector";
|
||||
import { generateColorTemperatureGradient } from "../../dialogs/more-info/components/lights/light-color-temp-picker";
|
||||
import "../ha-labeled-slider";
|
||||
|
||||
@customElement("ha-selector-color_temp")
|
||||
export class HaColorTempSelector extends LitElement {
|
||||
@property({ attribute: false }) public selector!: ColorTempSelector;
|
||||
|
||||
@property() public value?: string;
|
||||
@property() public value?: string | number;
|
||||
|
||||
@property() public label?: string;
|
||||
|
||||
@@ -26,27 +29,16 @@ export class HaColorTempSelector extends LitElement {
|
||||
|
||||
@property({ type: Boolean }) public required = true;
|
||||
|
||||
protected render() {
|
||||
let min: number;
|
||||
let max: number;
|
||||
@property({ attribute: false }) public context?: {
|
||||
filter_entity?: string | string[];
|
||||
};
|
||||
|
||||
switch (this.selector.color_temp?.unit) {
|
||||
case "kelvin":
|
||||
min = this.selector.color_temp?.min ?? DEFAULT_MIN_KELVIN;
|
||||
max = this.selector.color_temp?.max ?? DEFAULT_MAX_KELVIN;
|
||||
break;
|
||||
case "mired":
|
||||
default:
|
||||
min =
|
||||
this.selector.color_temp?.min ??
|
||||
this.selector.color_temp?.min_mireds ??
|
||||
153;
|
||||
max =
|
||||
this.selector.color_temp?.max ??
|
||||
this.selector.color_temp?.max_mireds ??
|
||||
500;
|
||||
break;
|
||||
}
|
||||
@state()
|
||||
@consumeEntityStates({ entityIdPath: ["context", "filter_entity"] })
|
||||
private _filterEntityStates?: Record<string, HassEntity>;
|
||||
|
||||
protected render() {
|
||||
const { min, max } = this._bounds();
|
||||
const gradient = this._generateTemperatureGradient(
|
||||
this.selector.color_temp?.unit ?? "mired",
|
||||
min,
|
||||
@@ -72,6 +64,30 @@ export class HaColorTempSelector extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _bounds(): { min: number; max: number } {
|
||||
switch (this.selector.color_temp?.unit) {
|
||||
case "kelvin":
|
||||
return (
|
||||
kelvinRangeFromEntityStates(this._filterEntityStates) ?? {
|
||||
min: this.selector.color_temp?.min ?? DEFAULT_MIN_KELVIN,
|
||||
max: this.selector.color_temp?.max ?? DEFAULT_MAX_KELVIN,
|
||||
}
|
||||
);
|
||||
case "mired":
|
||||
default:
|
||||
return {
|
||||
min:
|
||||
this.selector.color_temp?.min ??
|
||||
this.selector.color_temp?.min_mireds ??
|
||||
153,
|
||||
max:
|
||||
this.selector.color_temp?.max ??
|
||||
this.selector.color_temp?.max_mireds ??
|
||||
500,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private _generateTemperatureGradient = memoizeOne(
|
||||
(unit: "kelvin" | "mired", min: number, max: number) => {
|
||||
let gradient;
|
||||
|
||||
@@ -465,10 +465,13 @@ export class HaServiceControl extends LitElement {
|
||||
serviceData?.flatFields.some((field) => showOptionalToggle(field))
|
||||
);
|
||||
|
||||
const targetEntities = this._getTargetedEntities(
|
||||
serviceData?.target,
|
||||
this._value
|
||||
);
|
||||
// Actions that can never have targets get null, like template targets
|
||||
const targetEntities =
|
||||
serviceData &&
|
||||
("target" in serviceData ||
|
||||
serviceData.flatFields.some((field) => field.key === "entity_id"))
|
||||
? this._getTargetedEntities(serviceData.target, this._value)
|
||||
: null;
|
||||
|
||||
const domain = this._value?.action
|
||||
? computeDomain(this._value.action)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { mdiClose, mdiInformationOutline } from "@mdi/js";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { showStartupProgressDialog } from "../dialogs/startup-progress/show-dialog-startup-progress";
|
||||
import "./ha-icon-button";
|
||||
|
||||
@customElement("ha-startup-progress")
|
||||
export class HaStartupProgress extends LitElement {
|
||||
// The launch screen render swap would remove a dialog opened before it.
|
||||
@property({ attribute: false }) public detailsAvailable = false;
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
// Fallbacks cover the first render, before the core translations have loaded.
|
||||
protected render() {
|
||||
const localize = this._localize;
|
||||
return html`
|
||||
<div class="card">
|
||||
<div class="text" role="status">
|
||||
<span class="title">
|
||||
${
|
||||
localize("ui.startup_progress.starting") ||
|
||||
"Home Assistant is starting"
|
||||
}
|
||||
</span>
|
||||
<span class="secondary">
|
||||
${
|
||||
localize("ui.startup_progress.starting_secondary") ||
|
||||
"Some features may not be available yet"
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
${
|
||||
this.detailsAvailable
|
||||
? html`<ha-icon-button
|
||||
.label=${
|
||||
localize("ui.startup_progress.details") || "Startup details"
|
||||
}
|
||||
.path=${mdiInformationOutline}
|
||||
@click=${this._showDetails}
|
||||
></ha-icon-button>`
|
||||
: nothing
|
||||
}
|
||||
<ha-icon-button
|
||||
.label=${localize("ui.notification_toast.dismiss") || "Dismiss"}
|
||||
.path=${mdiClose}
|
||||
@click=${this._dismiss}
|
||||
></ha-icon-button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _showDetails() {
|
||||
showStartupProgressDialog(this);
|
||||
}
|
||||
|
||||
private _dismiss() {
|
||||
fireEvent(this, "startup-progress-dismissed");
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
position: fixed;
|
||||
inset-inline-start: 50%;
|
||||
inset-block-end: calc(
|
||||
var(--safe-area-inset-bottom, 0px) + var(--ha-space-4)
|
||||
);
|
||||
transform: translateX(calc(-50% * var(--scale-direction, 1)));
|
||||
/* Above the launch screen, which can still be fading out. */
|
||||
z-index: 101;
|
||||
width: min(420px, calc(100vw - var(--ha-space-8)));
|
||||
}
|
||||
.card {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-2);
|
||||
padding: var(--ha-space-3) var(--ha-space-2) var(--ha-space-3)
|
||||
var(--ha-space-4);
|
||||
color: var(--ha-color-on-neutral-loud);
|
||||
background-color: var(--ha-color-neutral-10);
|
||||
border-radius: var(--ha-border-radius-sm);
|
||||
box-shadow: var(--wa-shadow-l);
|
||||
}
|
||||
.text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.title {
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
}
|
||||
.secondary {
|
||||
/* The card is dark in both themes, so the themed quiet color lacks contrast. */
|
||||
color: var(--ha-color-neutral-70);
|
||||
font-size: var(--ha-font-size-s);
|
||||
}
|
||||
ha-icon-button {
|
||||
--mdc-icon-button-size: 36px;
|
||||
color: var(--ha-color-on-neutral-loud);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-startup-progress": HaStartupProgress;
|
||||
}
|
||||
interface HASSDomEvents {
|
||||
"startup-progress-dismissed": undefined;
|
||||
}
|
||||
}
|
||||
@@ -18,14 +18,30 @@ import {
|
||||
type WebRtcOfferEvent,
|
||||
} from "../data/camera";
|
||||
import { apiContext, connectionContext } from "../data/context";
|
||||
import { isExternal } from "../data/external";
|
||||
import "./ha-alert";
|
||||
import "./ha-spinner";
|
||||
import { showToast } from "../util/toast";
|
||||
|
||||
const HIDDEN_CLEANUP_DELAY = 60000;
|
||||
|
||||
// How long the backend gets to answer the offer, it has to connect to the camera
|
||||
const ANSWER_TIMEOUT = 20000;
|
||||
|
||||
// How long finding a network path gets after the answer. Browsers can take
|
||||
// minutes to give up on their own, or never do.
|
||||
const ICE_TIMEOUT = 30000;
|
||||
|
||||
// How often a stream that lost its connection or got a backend error is
|
||||
// started again. A new connection that gets no answer or finds no path is not
|
||||
// retried, as a retry would most likely end the same way.
|
||||
const MAX_RETRIES = 1;
|
||||
|
||||
// Gives the backend time to tear down the failed session before the next one
|
||||
const RETRY_DELAY = 1000;
|
||||
|
||||
interface WebRtcPlayerError {
|
||||
type: "not_supported" | "start_failed" | "connect_failed";
|
||||
type: "not_supported" | "start_failed" | "connect_failed" | "no_connection";
|
||||
message?: string;
|
||||
}
|
||||
|
||||
@@ -99,7 +115,7 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
if (this._microphoneDenied) {
|
||||
return "denied";
|
||||
}
|
||||
if (this._microphoneConnecting) {
|
||||
if (this._microphoneConnecting || this._retryMicrophoneTrack) {
|
||||
return "connecting";
|
||||
}
|
||||
return this._localReturnAudioTrack ? "on" : "off";
|
||||
@@ -110,11 +126,17 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
}
|
||||
|
||||
public async toggleMicrophone() {
|
||||
if (this._localReturnAudioTrack || this._microphoneConnecting) {
|
||||
if (
|
||||
this._localReturnAudioTrack ||
|
||||
this._microphoneConnecting ||
|
||||
this._retryMicrophoneTrack
|
||||
) {
|
||||
// Stop (not disable) so the browser releases the microphone, also cancels connecting
|
||||
this._microphoneRequest++;
|
||||
this._localReturnAudioTrack?.stop();
|
||||
this._localReturnAudioTrack = undefined;
|
||||
this._retryMicrophoneTrack?.stop();
|
||||
this._retryMicrophoneTrack = undefined;
|
||||
this._microphoneConnecting = false;
|
||||
this._fireMicrophoneChanged();
|
||||
await this._microphoneSender?.replaceTrack(null).catch(() => undefined);
|
||||
@@ -197,12 +219,30 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
|
||||
private _cleanUpCount = 0;
|
||||
|
||||
private _connectTimeout?: number;
|
||||
|
||||
private _retryTimeout?: number;
|
||||
|
||||
private _retryMicrophoneTrack?: MediaStreamTrack;
|
||||
|
||||
private _retries = 0;
|
||||
|
||||
// The stream showed video since it was started, so a lost connection is
|
||||
// worth a retry
|
||||
private _hasPlayed = false;
|
||||
|
||||
private _handleVisibilityChange = () => {
|
||||
if (document.pictureInPictureElement) {
|
||||
// video is playing in picture-in-picture mode, don't do anything
|
||||
return;
|
||||
}
|
||||
if (document.hidden) {
|
||||
if (isExternal) {
|
||||
// The companion apps pause JavaScript timers while in the background,
|
||||
// so a delayed clean up would not run until the app is opened again
|
||||
this._cleanUp();
|
||||
return;
|
||||
}
|
||||
this._hiddenCleanupTimeout = window.setTimeout(() => {
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
this._cleanUp();
|
||||
@@ -212,7 +252,7 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
clearTimeout(this._hiddenCleanupTimeout);
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
} else {
|
||||
this._startWebRtc();
|
||||
this._restartWebRtc();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -253,7 +293,7 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
public override connectedCallback() {
|
||||
super.connectedCallback();
|
||||
if (this.hasUpdated && this.entityid) {
|
||||
this._startWebRtc();
|
||||
this._restartWebRtc();
|
||||
}
|
||||
document.addEventListener("visibilitychange", this._handleVisibilityChange);
|
||||
}
|
||||
@@ -274,6 +314,13 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
if (!changedProperties.has("entityid")) {
|
||||
return;
|
||||
}
|
||||
this._restartWebRtc();
|
||||
}
|
||||
|
||||
/** Starts a new stream, not a retry of the current one. */
|
||||
private _restartWebRtc() {
|
||||
this._retries = 0;
|
||||
this._hasPlayed = false;
|
||||
this._startWebRtc();
|
||||
}
|
||||
|
||||
@@ -415,7 +462,7 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
while (this._candidatesList.length) {
|
||||
const candidate = this._candidatesList.pop();
|
||||
if (candidate) {
|
||||
candidates += `a=${candidate}\r\n`;
|
||||
candidates += `a=${candidate.candidate}\r\n`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -423,6 +470,8 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
|
||||
this._logEvent("start webRtcOffer", offer_sdp);
|
||||
|
||||
this._startConnectTimeout(ANSWER_TIMEOUT);
|
||||
|
||||
this._unsub = webRtcOffer(
|
||||
this._connection,
|
||||
this.entityid,
|
||||
@@ -443,11 +492,61 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
"ice connection state change",
|
||||
this._peerConnection?.iceConnectionState
|
||||
);
|
||||
if (this._peerConnection?.iceConnectionState === "failed") {
|
||||
this._peerConnection.restartIce();
|
||||
const iceState = this._peerConnection?.iceConnectionState;
|
||||
if (iceState === "connected" || iceState === "completed") {
|
||||
clearTimeout(this._connectTimeout);
|
||||
this._connectTimeout = undefined;
|
||||
} else if (iceState === "failed") {
|
||||
// An ICE restart needs a new offer, which the backend answers from a new
|
||||
// peer that can't continue this connection, so start a new one instead.
|
||||
this._retryOrFail({ type: "no_connection" });
|
||||
}
|
||||
};
|
||||
|
||||
private _startConnectTimeout(timeout: number) {
|
||||
clearTimeout(this._connectTimeout);
|
||||
this._connectTimeout = window.setTimeout(() => {
|
||||
this._connectTimeout = undefined;
|
||||
this._logEvent("connect timeout");
|
||||
this._retryOrFail({ type: "no_connection" });
|
||||
}, timeout);
|
||||
}
|
||||
|
||||
private _retryOrFail(error: WebRtcPlayerError) {
|
||||
if (
|
||||
this._retries >= MAX_RETRIES ||
|
||||
// No answer or no path for a stream that never played, a retry would
|
||||
// most likely end the same way
|
||||
(error.type === "no_connection" && !this._hasPlayed) ||
|
||||
// A microphone connect the user started is handled by starting again
|
||||
// without the microphone. A retry keeps the microphone of the stream.
|
||||
(this._localReturnAudioTrack &&
|
||||
this._microphoneConnecting &&
|
||||
this._retries === 0)
|
||||
) {
|
||||
this._failStart(error);
|
||||
return;
|
||||
}
|
||||
this._retries++;
|
||||
this._logEvent("retry", this._retries, error);
|
||||
// Keep showing the last frame instead of the poster while starting again
|
||||
this._captureReconnectFrame();
|
||||
// Taken out before the clean up, so a running microphone is not stopped
|
||||
const microphoneTrack = this._localReturnAudioTrack;
|
||||
this._localReturnAudioTrack = undefined;
|
||||
this._cleanUp();
|
||||
if (microphoneTrack) {
|
||||
this._retryMicrophoneTrack = microphoneTrack;
|
||||
this._fireMicrophoneChanged();
|
||||
}
|
||||
this._retryTimeout = window.setTimeout(() => {
|
||||
this._retryTimeout = undefined;
|
||||
const track = this._retryMicrophoneTrack;
|
||||
this._retryMicrophoneTrack = undefined;
|
||||
this._startWebRtc(track);
|
||||
}, RETRY_DELAY);
|
||||
}
|
||||
|
||||
private async _handleOfferEvent(
|
||||
peerConnection: RTCPeerConnection,
|
||||
event: WebRtcOfferEvent
|
||||
@@ -470,6 +569,10 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
this._candidatesList = [];
|
||||
}
|
||||
if (event.type === "answer") {
|
||||
const iceState = peerConnection.iceConnectionState;
|
||||
if (iceState !== "connected" && iceState !== "completed") {
|
||||
this._startConnectTimeout(ICE_TIMEOUT);
|
||||
}
|
||||
this._logEvent("answer", event.answer);
|
||||
|
||||
this._handleAnswer(peerConnection, event);
|
||||
@@ -495,7 +598,8 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
}
|
||||
}
|
||||
if (event.type === "error") {
|
||||
this._failStart({ type: "start_failed", message: event.message });
|
||||
// Often temporary, like the backend still closing the previous session
|
||||
this._retryOrFail({ type: "start_failed", message: event.message });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -587,8 +691,13 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
}
|
||||
|
||||
private _failStart(error: WebRtcPlayerError) {
|
||||
// The camera can reject the microphone, keep the video running without it
|
||||
if (this._localReturnAudioTrack && this._microphoneConnecting) {
|
||||
// The camera can reject the microphone, keep the video running without it.
|
||||
// After retries it is the connection that failed, not the microphone.
|
||||
if (
|
||||
this._localReturnAudioTrack &&
|
||||
this._microphoneConnecting &&
|
||||
this._retries === 0
|
||||
) {
|
||||
showToast(this, {
|
||||
message: this._localize(
|
||||
"ui.components.web-rtc-player.microphone_connect_failed",
|
||||
@@ -599,12 +708,19 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
return;
|
||||
}
|
||||
this._error = error;
|
||||
this._reconnectPoster = undefined;
|
||||
this._cleanUp();
|
||||
// Tell the camera stream this player has no video, so it can fall back
|
||||
fireEvent(this, "streams", { hasAudio: false, hasVideo: false });
|
||||
}
|
||||
|
||||
private _cleanUp() {
|
||||
this._cleanUpCount++;
|
||||
this._microphoneRequest++;
|
||||
clearTimeout(this._connectTimeout);
|
||||
this._connectTimeout = undefined;
|
||||
clearTimeout(this._retryTimeout);
|
||||
this._retryTimeout = undefined;
|
||||
if (this._remoteStream) {
|
||||
this._remoteStream.getTracks().forEach((track) => {
|
||||
track.stop();
|
||||
@@ -612,9 +728,15 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
|
||||
this._remoteStream = undefined;
|
||||
}
|
||||
if (this._localReturnAudioTrack || this._microphoneConnecting) {
|
||||
if (
|
||||
this._localReturnAudioTrack ||
|
||||
this._microphoneConnecting ||
|
||||
this._retryMicrophoneTrack
|
||||
) {
|
||||
this._localReturnAudioTrack?.stop();
|
||||
this._localReturnAudioTrack = undefined;
|
||||
this._retryMicrophoneTrack?.stop();
|
||||
this._retryMicrophoneTrack = undefined;
|
||||
this._microphoneConnecting = false;
|
||||
this._fireMicrophoneChanged();
|
||||
}
|
||||
@@ -666,6 +788,8 @@ export class HaWebRtcPlayer extends LitElement {
|
||||
|
||||
this._logEvent("loadedData", data);
|
||||
this._stopTimer();
|
||||
this._retries = 0;
|
||||
this._hasPlayed = true;
|
||||
|
||||
// Without a track the microphone is still waiting for permission
|
||||
if (this._microphoneConnecting && this._localReturnAudioTrack) {
|
||||
|
||||
@@ -34,6 +34,8 @@ import type { HASSDomTargetEvent } from "../../common/dom/fire_event";
|
||||
*
|
||||
* @attr {string} headline - Primary text. Overridden by the `headline` slot.
|
||||
* @attr {string} supporting-text - Secondary text. Overridden by the `supporting-text` slot.
|
||||
* @attr {boolean} wrap-headline - Wraps the headline onto multiple lines instead of truncating it.
|
||||
* @attr {boolean} wrap-supporting-text - Wraps the supporting text onto multiple lines instead of truncating it.
|
||||
* @attr {boolean} disabled - Dims the row and blocks pointer events.
|
||||
*/
|
||||
@customElement("ha-row-item")
|
||||
@@ -43,6 +45,12 @@ export class HaRowItem extends LitElement {
|
||||
@property({ type: String, attribute: "supporting-text" })
|
||||
public supportingText?: string;
|
||||
|
||||
@property({ type: Boolean, reflect: true, attribute: "wrap-headline" })
|
||||
public wrapHeadline = false;
|
||||
|
||||
@property({ type: Boolean, reflect: true, attribute: "wrap-supporting-text" })
|
||||
public wrapSupportingText = false;
|
||||
|
||||
@property({ type: Boolean, reflect: true }) public disabled = false;
|
||||
|
||||
protected readonly _slotController = new HasSlotController(
|
||||
@@ -192,6 +200,10 @@ export class HaRowItem extends LitElement {
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
:host([wrap-headline]) .headline,
|
||||
:host([wrap-supporting-text]) .supporting {
|
||||
white-space: normal;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,11 +22,65 @@ const SMALL_THUMBNAIL_THRESHOLD = 16;
|
||||
const isSvgUrl = (url: string): boolean =>
|
||||
/\.svg(\?|#|$)/i.test(url) || url.startsWith("data:image/svg+xml");
|
||||
|
||||
// Local thumbnails can be slow to generate, for example when the integration
|
||||
// extracts them from a recording on a camera. Without a limit they take all of
|
||||
// the browser's connections to Home Assistant (6 for HTTP/1.1), and requests
|
||||
// such as starting media playback wait until all queued thumbnails are loaded.
|
||||
const MAX_PARALLEL_LOCAL_THUMBNAILS = 4;
|
||||
let activeLocalThumbnails = 0;
|
||||
const localThumbnailQueue: (() => void)[] = [];
|
||||
|
||||
const acquireLocalThumbnailSlot = (signal: AbortSignal): Promise<void> => {
|
||||
if (signal.aborted) {
|
||||
return Promise.reject(signal.reason);
|
||||
}
|
||||
if (activeLocalThumbnails < MAX_PARALLEL_LOCAL_THUMBNAILS) {
|
||||
activeLocalThumbnails++;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const start = () => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
activeLocalThumbnails++;
|
||||
resolve();
|
||||
};
|
||||
const onAbort = () => {
|
||||
const index = localThumbnailQueue.indexOf(start);
|
||||
if (index !== -1) {
|
||||
localThumbnailQueue.splice(index, 1);
|
||||
}
|
||||
reject(signal.reason);
|
||||
};
|
||||
localThumbnailQueue.push(start);
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
};
|
||||
|
||||
const releaseLocalThumbnailSlot = (): void => {
|
||||
activeLocalThumbnails--;
|
||||
localThumbnailQueue.shift()?.();
|
||||
};
|
||||
|
||||
const fetchLocalThumbnail = async (
|
||||
fetchWithAuth: HomeAssistantApi["fetchWithAuth"],
|
||||
thumbnailUrl: string,
|
||||
signal: AbortSignal
|
||||
): Promise<Blob> => {
|
||||
await acquireLocalThumbnailSlot(signal);
|
||||
try {
|
||||
const response = await fetchWithAuth(thumbnailUrl, { signal });
|
||||
return await response.blob();
|
||||
} finally {
|
||||
releaseLocalThumbnailSlot();
|
||||
}
|
||||
};
|
||||
|
||||
const resolveThumbnailURL = (
|
||||
thumbnailUrl: string,
|
||||
darkMode: boolean | undefined,
|
||||
hassUrl: string | undefined,
|
||||
fetchWithAuth: HomeAssistantApi["fetchWithAuth"]
|
||||
fetchWithAuth: HomeAssistantApi["fetchWithAuth"],
|
||||
signal: AbortSignal
|
||||
): Promise<string> => {
|
||||
if (isBrandUrl(thumbnailUrl)) {
|
||||
return Promise.resolve(
|
||||
@@ -42,18 +96,16 @@ const resolveThumbnailURL = (
|
||||
}
|
||||
if (thumbnailUrl.startsWith("/")) {
|
||||
// Local thumbnails require authentication; fetch and inline as base64.
|
||||
return fetchWithAuth(thumbnailUrl)
|
||||
.then((response) => response.blob())
|
||||
.then(
|
||||
(blob) =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () =>
|
||||
resolve(typeof reader.result === "string" ? reader.result : "");
|
||||
reader.onerror = (e) => reject(e);
|
||||
reader.readAsDataURL(blob);
|
||||
})
|
||||
);
|
||||
return fetchLocalThumbnail(fetchWithAuth, thumbnailUrl, signal).then(
|
||||
(blob) =>
|
||||
new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () =>
|
||||
resolve(typeof reader.result === "string" ? reader.result : "");
|
||||
reader.onerror = (e) => reject(e);
|
||||
reader.readAsDataURL(blob);
|
||||
})
|
||||
);
|
||||
}
|
||||
return Promise.resolve(thumbnailUrl);
|
||||
};
|
||||
@@ -85,6 +137,28 @@ export class HaMediaBrowserThumbnail extends LitElement {
|
||||
|
||||
@state() private _brand = false;
|
||||
|
||||
private _abortController?: AbortController;
|
||||
|
||||
public connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
// Resume a thumbnail which was aborted when this element was disconnected
|
||||
if (this.hasUpdated && this.url && !this._resolvedUrl) {
|
||||
this._resolve();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
// Do not keep loading thumbnails which are no longer shown
|
||||
if (this._abortController) {
|
||||
this._abortController.abort();
|
||||
this._abortController = undefined;
|
||||
// A shown image can belong to a previous url, clear it so
|
||||
// connectedCallback restarts loading the current url.
|
||||
this._resolvedUrl = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues): void {
|
||||
super.willUpdate(changedProps);
|
||||
if (
|
||||
@@ -97,6 +171,8 @@ export class HaMediaBrowserThumbnail extends LitElement {
|
||||
}
|
||||
|
||||
private async _resolve(): Promise<void> {
|
||||
this._abortController?.abort();
|
||||
this._abortController = undefined;
|
||||
this._small = false;
|
||||
this._brand = !!this.url && isBrandUrl(this.url);
|
||||
if (!this.url) {
|
||||
@@ -104,18 +180,28 @@ export class HaMediaBrowserThumbnail extends LitElement {
|
||||
return;
|
||||
}
|
||||
const requested = this.url;
|
||||
const abortController = new AbortController();
|
||||
this._abortController = abortController;
|
||||
try {
|
||||
const resolved = await resolveThumbnailURL(
|
||||
requested,
|
||||
this._darkMode,
|
||||
this._hassUrl,
|
||||
this._api.fetchWithAuth
|
||||
this._api.fetchWithAuth,
|
||||
abortController.signal
|
||||
);
|
||||
if (requested !== this.url) return;
|
||||
this._resolvedUrl = resolved;
|
||||
this._probeSize(resolved);
|
||||
} catch (_err) {
|
||||
// Aborted when the url changed or this element was disconnected,
|
||||
// which already restarted or reset the resolution.
|
||||
if (abortController.signal.aborted) return;
|
||||
if (requested === this.url) this._resolvedUrl = undefined;
|
||||
} finally {
|
||||
if (this._abortController === abortController) {
|
||||
this._abortController = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { CSSResultGroup, TemplateResult } from "lit";
|
||||
import { css, html, nothing } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { HaListItemButton } from "../item/ha-list-item-button";
|
||||
import "./ha-media-browser-thumbnail";
|
||||
|
||||
/**
|
||||
* @element ha-media-player-browse-list-item
|
||||
* @extends {HaListItemButton}
|
||||
*
|
||||
* @summary
|
||||
* Row of the media browser list. Always reserves a graphic next to the title
|
||||
* so titles line up, and shows a thumbnail with an optional play button over
|
||||
* it. Without `interactive` the row is plain text, used for the "not shown"
|
||||
* row. The row is rendered inside the shadow root of `ha-list-virtualized`, so
|
||||
* it carries its own styles.
|
||||
*
|
||||
* @slot start - Play or pick button, shown over the thumbnail.
|
||||
* @slot headline - Title of the row.
|
||||
*
|
||||
* @csspart start - The graphic container.
|
||||
*
|
||||
* @attr {string} thumbnail - URL of the thumbnail. Shown inside the graphic.
|
||||
*/
|
||||
@customElement("ha-media-player-browse-list-item")
|
||||
export class HaMediaPlayerBrowseListItem extends HaListItemButton {
|
||||
@property() public thumbnail?: string;
|
||||
|
||||
// The "not shown" row is plain text, not a button
|
||||
protected override _renderControl(content: TemplateResult): TemplateResult {
|
||||
if (!this.interactive) {
|
||||
return content;
|
||||
}
|
||||
return super._renderControl(content);
|
||||
}
|
||||
|
||||
// Always reserve the graphic, so titles line up across rows
|
||||
protected override _renderStart(): TemplateResult {
|
||||
return html`<div part="start" class="start">
|
||||
<div class="graphic">
|
||||
${
|
||||
this.thumbnail
|
||||
? html`<ha-media-browser-thumbnail
|
||||
.url=${this.thumbnail}
|
||||
></ha-media-browser-thumbnail>`
|
||||
: nothing
|
||||
}
|
||||
<slot name="start"></slot>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
static styles: CSSResultGroup = [
|
||||
HaListItemButton.styles,
|
||||
css`
|
||||
:host {
|
||||
direction: var(--direction);
|
||||
--ha-row-item-padding-block: 0;
|
||||
--ha-row-item-min-height: 48px;
|
||||
}
|
||||
|
||||
:host(.show-images) {
|
||||
--ha-row-item-padding-block: var(--ha-space-1);
|
||||
--ha-row-item-min-height: 64px;
|
||||
}
|
||||
|
||||
:host(.not-shown) {
|
||||
font-style: italic;
|
||||
color: var(--secondary-text-color);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
::slotted(ha-svg-icon) {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
|
||||
.graphic {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: var(--ha-border-radius-sm);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:host(.show-images) .graphic {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
}
|
||||
|
||||
ha-media-browser-thumbnail {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
::slotted(.play) {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
margin: auto;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
opacity: 0;
|
||||
transition: all 0.5s;
|
||||
background-color: rgba(var(--rgb-card-background-color), 0.5);
|
||||
border-radius: var(--ha-border-radius-circle);
|
||||
--ha-icon-button-size: 40px;
|
||||
}
|
||||
|
||||
:host(:hover) ::slotted(.play) {
|
||||
opacity: 1;
|
||||
color: var(--primary-text-color);
|
||||
}
|
||||
|
||||
::slotted(.play.show) {
|
||||
opacity: 1;
|
||||
background-color: transparent;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-media-player-browse-list-item": HaMediaPlayerBrowseListItem;
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,6 @@ import "../ha-svg-icon";
|
||||
import "../ha-tooltip";
|
||||
import "../input/ha-input-search";
|
||||
import type { HaInputSearch } from "../input/ha-input-search";
|
||||
import { HaListItemButton } from "../item/ha-list-item-button";
|
||||
import "../list/ha-list-virtualized";
|
||||
import type {
|
||||
HaListVirtualized,
|
||||
@@ -88,6 +87,7 @@ import type { ManualMediaPickedEvent } from "./ha-browse-media-manual";
|
||||
import "./ha-browse-media-tts";
|
||||
import type { TtsMediaPickedEvent } from "./ha-browse-media-tts";
|
||||
import "./ha-media-browser-thumbnail";
|
||||
import "./ha-media-player-browse-list-item";
|
||||
|
||||
declare global {
|
||||
interface HASSDomEvents {
|
||||
@@ -120,105 +120,6 @@ type MediaBrowseListRow =
|
||||
count: number;
|
||||
});
|
||||
|
||||
@customElement("ha-media-player-browse-list-item")
|
||||
export class HaMediaPlayerBrowseListItem extends HaListItemButton {
|
||||
@property() public thumbnail?: string;
|
||||
|
||||
// The "not shown" row is plain text, not a button
|
||||
protected override _renderControl(content: TemplateResult): TemplateResult {
|
||||
if (!this.interactive) {
|
||||
return content;
|
||||
}
|
||||
return super._renderControl(content);
|
||||
}
|
||||
|
||||
// Always reserve the graphic, so titles line up across rows
|
||||
protected override _renderStart(): TemplateResult {
|
||||
return html`<div part="start" class="start">
|
||||
<div class="graphic">
|
||||
${
|
||||
this.thumbnail
|
||||
? html`<ha-media-browser-thumbnail
|
||||
.url=${this.thumbnail}
|
||||
></ha-media-browser-thumbnail>`
|
||||
: nothing
|
||||
}
|
||||
<slot name="start"></slot>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
static styles: CSSResultGroup = [
|
||||
HaListItemButton.styles,
|
||||
css`
|
||||
:host {
|
||||
direction: var(--direction);
|
||||
--ha-row-item-padding-block: 0;
|
||||
--ha-row-item-min-height: 48px;
|
||||
}
|
||||
|
||||
:host(.show-images) {
|
||||
--ha-row-item-padding-block: var(--ha-space-1);
|
||||
--ha-row-item-min-height: 64px;
|
||||
}
|
||||
|
||||
:host(.not-shown) {
|
||||
font-style: italic;
|
||||
color: var(--secondary-text-color);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
::slotted(ha-svg-icon) {
|
||||
color: var(--secondary-text-color);
|
||||
}
|
||||
|
||||
.graphic {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: var(--ha-border-radius-sm);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:host(.show-images) .graphic {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
}
|
||||
|
||||
ha-media-browser-thumbnail {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
::slotted(.play) {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
margin: auto;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
opacity: 0;
|
||||
transition: all 0.5s;
|
||||
background-color: rgba(var(--rgb-card-background-color), 0.5);
|
||||
border-radius: var(--ha-border-radius-circle);
|
||||
--ha-icon-button-size: 40px;
|
||||
}
|
||||
|
||||
:host(:hover) ::slotted(.play) {
|
||||
opacity: 1;
|
||||
color: var(--primary-text-color);
|
||||
}
|
||||
|
||||
::slotted(.play.show) {
|
||||
opacity: 1;
|
||||
background-color: transparent;
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
/** Folders with at least this many items get a filter field when their source cannot search. */
|
||||
const FILTER_MIN_CHILDREN = 10;
|
||||
|
||||
@@ -1945,6 +1846,5 @@ export class HaMediaPlayerBrowse extends LitElement {
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-media-player-browse": HaMediaPlayerBrowse;
|
||||
"ha-media-player-browse-list-item": HaMediaPlayerBrowseListItem;
|
||||
}
|
||||
}
|
||||
@@ -112,7 +112,7 @@ export class HaTracePathDetails extends LitElement {
|
||||
initialValue: {
|
||||
options: [],
|
||||
showIndices: false,
|
||||
select: () => undefined,
|
||||
select: () => true,
|
||||
fixDuplicateIds: async () => undefined,
|
||||
updateTriggerId: () => false,
|
||||
},
|
||||
|
||||
@@ -123,7 +123,7 @@ export const setProtectedAlarmControlPanelMode = async (
|
||||
(mode === "disarmed" && stateObj.attributes.code_format)
|
||||
) {
|
||||
const entry = await getExtendedEntityRegistryEntry(
|
||||
hass,
|
||||
hass.callWS,
|
||||
stateObj.entity_id
|
||||
).catch(() => undefined);
|
||||
const defaultCode = entry?.options?.alarm_control_panel?.default_code;
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
|
||||
export const ROOM_ICONS = {
|
||||
living_room: [
|
||||
"mdi:sofa",
|
||||
"mdi:sofa-single",
|
||||
"mdi:television",
|
||||
"mdi:fireplace",
|
||||
"mdi:floor-lamp",
|
||||
],
|
||||
bedroom: ["mdi:bed", "mdi:bed-king", "mdi:bed-double", "mdi:lamp"],
|
||||
kids_room: ["mdi:teddy-bear", "mdi:toy-brick", "mdi:bunk-bed", "mdi:cradle"],
|
||||
kitchen: [
|
||||
"mdi:stove",
|
||||
"mdi:fridge",
|
||||
"mdi:countertop",
|
||||
"mdi:chef-hat",
|
||||
"mdi:pot-steam",
|
||||
"mdi:coffee-maker",
|
||||
],
|
||||
dining_room: [
|
||||
"mdi:silverware-fork-knife",
|
||||
"mdi:table-chair",
|
||||
"mdi:table-furniture",
|
||||
"mdi:glass-wine",
|
||||
],
|
||||
bathroom: [
|
||||
"mdi:shower",
|
||||
"mdi:bathtub",
|
||||
"mdi:shower-head",
|
||||
"mdi:toothbrush",
|
||||
"mdi:hair-dryer",
|
||||
],
|
||||
toilet: ["mdi:toilet", "mdi:paper-roll"],
|
||||
office: [
|
||||
"mdi:desk",
|
||||
"mdi:laptop",
|
||||
"mdi:monitor",
|
||||
"mdi:chair-rolling",
|
||||
"mdi:bookshelf",
|
||||
],
|
||||
laundry_room: [
|
||||
"mdi:washing-machine",
|
||||
"mdi:tumble-dryer",
|
||||
"mdi:iron",
|
||||
"mdi:hanger",
|
||||
],
|
||||
hallway: ["mdi:door", "mdi:door-open", "mdi:coat-rack", "mdi:key"],
|
||||
stairs: ["mdi:stairs", "mdi:stairs-up", "mdi:stairs-down"],
|
||||
garage: ["mdi:garage", "mdi:garage-variant", "mdi:car", "mdi:tools"],
|
||||
garden: [
|
||||
"mdi:flower",
|
||||
"mdi:tree",
|
||||
"mdi:grass",
|
||||
"mdi:sprout",
|
||||
"mdi:watering-can",
|
||||
"mdi:greenhouse",
|
||||
],
|
||||
terrace: [
|
||||
"mdi:balcony",
|
||||
"mdi:grill",
|
||||
"mdi:umbrella-outline",
|
||||
"mdi:coach-lamp",
|
||||
"mdi:patio-heater",
|
||||
],
|
||||
basement: [
|
||||
"mdi:home-floor-negative-1",
|
||||
"mdi:stairs-down",
|
||||
"mdi:water-boiler",
|
||||
],
|
||||
attic: ["mdi:home-roof", "mdi:package-variant-closed"],
|
||||
storage: ["mdi:archive", "mdi:package-variant-closed", "mdi:warehouse"],
|
||||
utility_room: [
|
||||
"mdi:water-boiler",
|
||||
"mdi:heat-pump",
|
||||
"mdi:server-network",
|
||||
"mdi:flash",
|
||||
],
|
||||
pool: ["mdi:pool", "mdi:swim"],
|
||||
media_room: [
|
||||
"mdi:theater",
|
||||
"mdi:projector",
|
||||
"mdi:television",
|
||||
"mdi:movie-open",
|
||||
],
|
||||
game_room: [
|
||||
"mdi:gamepad-variant",
|
||||
"mdi:billiards",
|
||||
"mdi:cards-playing",
|
||||
"mdi:dice-multiple",
|
||||
],
|
||||
music_room: ["mdi:piano", "mdi:guitar-acoustic", "mdi:music"],
|
||||
library: ["mdi:bookshelf", "mdi:book-open-variant", "mdi:library"],
|
||||
bar: [
|
||||
"mdi:glass-cocktail",
|
||||
"mdi:glass-mug-variant",
|
||||
"mdi:bottle-wine",
|
||||
"mdi:beer",
|
||||
],
|
||||
dressing_room: [
|
||||
"mdi:hanger",
|
||||
"mdi:wardrobe",
|
||||
"mdi:tshirt-crew",
|
||||
"mdi:shoe-heel",
|
||||
],
|
||||
workshop: ["mdi:tools", "mdi:hammer-wrench", "mdi:toolbox", "mdi:saw-blade"],
|
||||
server_room: ["mdi:server-network", "mdi:server", "mdi:router-network"],
|
||||
safe_room: ["mdi:shield-home", "mdi:shield-lock", "mdi:safe"],
|
||||
prayer_room: ["mdi:hands-pray", "mdi:meditation", "mdi:candle"],
|
||||
sauna: ["mdi:spa", "mdi:hot-tub", "mdi:thermometer-high"],
|
||||
outdoor_kitchen: ["mdi:grill", "mdi:grill-outline", "mdi:pizza"],
|
||||
driveway: ["mdi:road-variant", "mdi:car", "mdi:gate"],
|
||||
} as const satisfies Record<string, readonly string[]>;
|
||||
|
||||
export type RoomType = keyof typeof ROOM_ICONS;
|
||||
|
||||
type RoomKeywords = Partial<Record<RoomType, string[]>>;
|
||||
|
||||
export const ROOM_TYPES = Object.keys(ROOM_ICONS) as RoomType[];
|
||||
|
||||
export const isRoomType = (value: string): value is RoomType =>
|
||||
(ROOM_TYPES as string[]).includes(value);
|
||||
|
||||
// Languages written without spaces between words
|
||||
const NO_WORD_SPACING =
|
||||
/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}]/u;
|
||||
|
||||
const normalizeRoomText = (text: string): string =>
|
||||
text
|
||||
.normalize("NFD")
|
||||
.replace(/\p{M}/gu, "")
|
||||
.toLowerCase()
|
||||
.replace(/['’]/g, "")
|
||||
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
||||
.trim();
|
||||
|
||||
interface RoomMatch {
|
||||
room: RoomType;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
const findMatches = (name: string, keywords: RoomKeywords): RoomMatch[] => {
|
||||
const text = ` ${normalizeRoomText(name)} `;
|
||||
const candidates: RoomMatch[] = [];
|
||||
for (const room of ROOM_TYPES) {
|
||||
for (const keyword of keywords[room] ?? []) {
|
||||
const phrase = normalizeRoomText(keyword);
|
||||
if (!phrase) {
|
||||
continue;
|
||||
}
|
||||
const needle = NO_WORD_SPACING.test(phrase) ? phrase : ` ${phrase} `;
|
||||
const start = text.indexOf(needle);
|
||||
if (start !== -1) {
|
||||
candidates.push({ room, start, end: start + needle.length });
|
||||
}
|
||||
}
|
||||
}
|
||||
// The longest phrase wins, so "guest bedroom" is not also read as "bedroom"
|
||||
candidates.sort((a, b) => b.end - b.start - (a.end - a.start));
|
||||
const kept: RoomMatch[] = [];
|
||||
for (const match of candidates) {
|
||||
const overlaps = kept.some(
|
||||
(other) => match.start < other.end - 1 && other.start < match.end - 1
|
||||
);
|
||||
if (!overlaps) {
|
||||
kept.push(match);
|
||||
}
|
||||
}
|
||||
return kept.sort((a, b) => a.start - b.start);
|
||||
};
|
||||
|
||||
const matchRoomTypes = (
|
||||
names: string[],
|
||||
keywords: RoomKeywords
|
||||
): RoomType[] => {
|
||||
const rooms = new Set<RoomType>();
|
||||
for (const name of names) {
|
||||
for (const match of findMatches(name, keywords)) {
|
||||
rooms.add(match.room);
|
||||
}
|
||||
}
|
||||
return [...rooms];
|
||||
};
|
||||
|
||||
const roomIconSuggestions = (rooms: RoomType[]): string[] => [
|
||||
...new Set(rooms.flatMap((room) => ROOM_ICONS[room])),
|
||||
];
|
||||
|
||||
export const getAreaIconSuggestions = (
|
||||
names: string[],
|
||||
localize: LocalizeFunc
|
||||
): string[] => {
|
||||
const keywords: RoomKeywords = Object.fromEntries(
|
||||
ROOM_TYPES.map((room) => [
|
||||
room,
|
||||
localize(`ui.components.rooms.keywords.${room}`).split("|"),
|
||||
])
|
||||
);
|
||||
return roomIconSuggestions(matchRoomTypes(names, keywords));
|
||||
};
|
||||
@@ -1,18 +1,111 @@
|
||||
import type { HomeAssistant } from "../types";
|
||||
import type { Connection, UnsubscribeFunc } from "home-assistant-js-websocket";
|
||||
import {
|
||||
STATE_NOT_RUNNING,
|
||||
STATE_RUNNING,
|
||||
STATE_STARTING,
|
||||
} from "home-assistant-js-websocket";
|
||||
|
||||
export type BootstrapIntegrationsTimings = Record<string, number>;
|
||||
export type BootstrapPhase =
|
||||
"preparing" | "setup" | "wrap_up" | "starting" | "running";
|
||||
|
||||
export const subscribeBootstrapIntegrations = (
|
||||
hass: HomeAssistant,
|
||||
callback: (message: BootstrapIntegrationsTimings) => void
|
||||
) => {
|
||||
const unsubProm =
|
||||
hass.connection.subscribeMessage<BootstrapIntegrationsTimings>(
|
||||
(message) => callback(message),
|
||||
{
|
||||
type: "subscribe_bootstrap_integrations",
|
||||
}
|
||||
);
|
||||
export interface BootstrapProgress {
|
||||
phase: BootstrapPhase;
|
||||
// Seconds since integration setup started.
|
||||
elapsed: number;
|
||||
integrations: {
|
||||
// Integrations scheduled by bootstrap, including dependencies. Null while resolving.
|
||||
total: number | null;
|
||||
// Integrations whose setup attempt finished, successful or not.
|
||||
done: number;
|
||||
failed: string[];
|
||||
};
|
||||
// Domain to seconds since its oldest pending setup started.
|
||||
active: Record<string, number>;
|
||||
}
|
||||
|
||||
return unsubProm;
|
||||
export interface StartupProgressView {
|
||||
phase: BootstrapPhase;
|
||||
// Share of scheduled integrations that finished setup, not of startup time.
|
||||
// Undefined when the indicator must be indeterminate.
|
||||
percent?: number;
|
||||
done: number;
|
||||
total: number | null;
|
||||
elapsed?: number;
|
||||
active: [domain: string, seconds: number][];
|
||||
failed: string[];
|
||||
finished: boolean;
|
||||
}
|
||||
|
||||
export type StartupTransition = "show" | "finish" | "none";
|
||||
|
||||
export const subscribeBootstrapProgress = (
|
||||
connection: Connection,
|
||||
callback: (message: BootstrapProgress) => void
|
||||
): Promise<UnsubscribeFunc> =>
|
||||
connection.subscribeMessage<BootstrapProgress>(callback, {
|
||||
type: "subscribe_bootstrap_progress",
|
||||
});
|
||||
|
||||
const PHASE_ORDER: BootstrapPhase[] = [
|
||||
"preparing",
|
||||
"setup",
|
||||
"wrap_up",
|
||||
"starting",
|
||||
"running",
|
||||
];
|
||||
|
||||
export const computeStartupProgress = (
|
||||
progress: BootstrapProgress | undefined,
|
||||
coreState: string
|
||||
): StartupProgressView => {
|
||||
// The core state is authoritative; progress messages can lag behind it.
|
||||
const statePhase: BootstrapPhase | undefined =
|
||||
coreState === STATE_RUNNING
|
||||
? "running"
|
||||
: coreState === STATE_STARTING
|
||||
? "starting"
|
||||
: undefined;
|
||||
const messagePhase = progress?.phase ?? "preparing";
|
||||
const phase =
|
||||
statePhase &&
|
||||
PHASE_ORDER.indexOf(statePhase) > PHASE_ORDER.indexOf(messagePhase)
|
||||
? statePhase
|
||||
: messagePhase;
|
||||
const total = progress?.integrations.total ?? null;
|
||||
const done = progress?.integrations.done ?? 0;
|
||||
return {
|
||||
phase,
|
||||
percent:
|
||||
phase === "setup" && total
|
||||
? Math.min(100, Math.round((done / total) * 100))
|
||||
: undefined,
|
||||
done,
|
||||
total,
|
||||
elapsed: progress?.elapsed,
|
||||
active: Object.entries(progress?.active ?? {}).sort(
|
||||
([, a], [, b]) => b - a
|
||||
),
|
||||
failed: progress?.integrations.failed ?? [],
|
||||
finished: coreState === STATE_RUNNING,
|
||||
};
|
||||
};
|
||||
|
||||
export const startupTransition = (
|
||||
oldState: string | undefined,
|
||||
newState: string
|
||||
): StartupTransition => {
|
||||
if (oldState === newState) {
|
||||
return "none";
|
||||
}
|
||||
if (newState === STATE_NOT_RUNNING || newState === STATE_STARTING) {
|
||||
// Startup is not finished in STARTING, so keep the indicator from NOT_RUNNING.
|
||||
return oldState === STATE_NOT_RUNNING ? "none" : "show";
|
||||
}
|
||||
if (
|
||||
newState === STATE_RUNNING &&
|
||||
(oldState === STATE_NOT_RUNNING || oldState === STATE_STARTING)
|
||||
) {
|
||||
return "finish";
|
||||
}
|
||||
return "none";
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
export const STREAM_TYPE_HLS = "hls";
|
||||
export const STREAM_TYPE_WEB_RTC = "web_rtc";
|
||||
|
||||
export type StreamType = typeof STREAM_TYPE_HLS | typeof STREAM_TYPE_WEB_RTC;
|
||||
|
||||
export const MJPEG_STREAM = "mjpeg";
|
||||
|
||||
export type CameraStreamType = StreamType | typeof MJPEG_STREAM;
|
||||
|
||||
export interface CameraStream {
|
||||
type: CameraStreamType;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
/** What a player reported, `hasVideo: false` means it failed to load. */
|
||||
export interface CameraStreamTracks {
|
||||
hasAudio: boolean;
|
||||
hasVideo: boolean;
|
||||
}
|
||||
|
||||
export interface CameraStreamSelectionOptions {
|
||||
supportedTypes?: StreamType[];
|
||||
hlsStreams?: CameraStreamTracks;
|
||||
webRtcStreams?: CameraStreamTracks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides which players are rendered and which one is shown. Hidden players
|
||||
* are still loading in the background.
|
||||
*/
|
||||
export const selectCameraStreams = ({
|
||||
supportedTypes,
|
||||
hlsStreams,
|
||||
webRtcStreams,
|
||||
}: CameraStreamSelectionOptions): CameraStream[] => {
|
||||
if (!supportedTypes) {
|
||||
return [];
|
||||
}
|
||||
if (supportedTypes.length === 0) {
|
||||
// doesn't support any stream type, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
if (supportedTypes.length === 1) {
|
||||
// only 1 stream type, no need to choose
|
||||
if (
|
||||
(supportedTypes[0] === STREAM_TYPE_HLS &&
|
||||
hlsStreams?.hasVideo === false) ||
|
||||
(supportedTypes[0] === STREAM_TYPE_WEB_RTC &&
|
||||
webRtcStreams?.hasVideo === false)
|
||||
) {
|
||||
// stream failed to load, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
return [{ type: supportedTypes[0], visible: true }];
|
||||
}
|
||||
|
||||
const hlsFailed = hlsStreams?.hasVideo === false;
|
||||
|
||||
if (webRtcStreams?.hasVideo) {
|
||||
// WebRTC is preferred whenever it plays, it has the lowest latency
|
||||
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
|
||||
}
|
||||
|
||||
if (webRtcStreams?.hasVideo === false) {
|
||||
if (hlsFailed) {
|
||||
// both streams failed to load, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
return [{ type: STREAM_TYPE_HLS, visible: true }];
|
||||
}
|
||||
|
||||
// WebRTC is still loading
|
||||
if (hlsFailed) {
|
||||
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
|
||||
}
|
||||
return [
|
||||
{ type: STREAM_TYPE_HLS, visible: true },
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: false },
|
||||
];
|
||||
};
|
||||
+6
-4
@@ -7,13 +7,15 @@ import { timeCacheEntityPromiseFunc } from "../common/util/time-cache-entity-pro
|
||||
import type { HomeAssistant, HomeAssistantApi } from "../types";
|
||||
import { fileDownload } from "../util/file_download";
|
||||
import { getSignedPath } from "./auth";
|
||||
import type { StreamType } from "./camera-streams";
|
||||
|
||||
export const CAMERA_ORIENTATIONS = [1, 2, 3, 4, 6, 8];
|
||||
|
||||
export const STREAM_TYPE_HLS = "hls";
|
||||
export const STREAM_TYPE_WEB_RTC = "web_rtc";
|
||||
|
||||
export type StreamType = typeof STREAM_TYPE_HLS | typeof STREAM_TYPE_WEB_RTC;
|
||||
export {
|
||||
STREAM_TYPE_HLS,
|
||||
STREAM_TYPE_WEB_RTC,
|
||||
type StreamType,
|
||||
} from "./camera-streams";
|
||||
|
||||
export { CameraEntityFeature } from "./feature/camera_entity_feature";
|
||||
|
||||
|
||||
+123
-25
@@ -2,16 +2,37 @@ import type {
|
||||
HassEntityAttributeBase,
|
||||
HassEntityBase,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { stateActive } from "../common/entity/state_active";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import type { HomeAssistantFormatters } from "../types";
|
||||
import { UNAVAILABLE } from "./entity/entity";
|
||||
import { UNAVAILABLE, UNKNOWN } from "./entity/entity";
|
||||
import { CoverEntityFeature } from "./feature/cover_entity_feature";
|
||||
|
||||
export { CoverEntityFeature };
|
||||
|
||||
export const DEFAULT_COVER_FAVORITE_POSITIONS = [0, 25, 75, 100];
|
||||
|
||||
export type CoverControlMode = "position" | "tilt";
|
||||
|
||||
export type CoverAction = "open" | "close" | "stop";
|
||||
|
||||
export type CoverCommand =
|
||||
| { mode: CoverControlMode; action: CoverAction }
|
||||
| { mode: CoverControlMode; action: "set"; value: number };
|
||||
|
||||
export interface CoverRequest {
|
||||
mode: CoverControlMode;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface CoverSwipe {
|
||||
action: "open" | "close";
|
||||
passedHalfway: boolean;
|
||||
}
|
||||
|
||||
export interface CoverDrag {
|
||||
value: number;
|
||||
swipe?: CoverSwipe;
|
||||
}
|
||||
|
||||
export const coverSupportsPosition = (stateObj: CoverEntity) =>
|
||||
supportsFeature(stateObj, CoverEntityFeature.SET_POSITION);
|
||||
|
||||
@@ -21,11 +42,79 @@ export const coverSupportsTiltPosition = (stateObj: CoverEntity) =>
|
||||
export const coverSupportsAnyPosition = (stateObj: CoverEntity) =>
|
||||
coverSupportsPosition(stateObj) || coverSupportsTiltPosition(stateObj);
|
||||
|
||||
export function isFullyOpen(stateObj: CoverEntity) {
|
||||
if (stateObj.attributes.current_position !== undefined) {
|
||||
return stateObj.attributes.current_position === 100;
|
||||
export const coverSupportsSetValue = (
|
||||
stateObj: CoverEntity,
|
||||
mode: CoverControlMode
|
||||
) =>
|
||||
mode === "tilt"
|
||||
? coverSupportsTiltPosition(stateObj)
|
||||
: coverSupportsPosition(stateObj);
|
||||
|
||||
const POSITION_FEATURES = [
|
||||
CoverEntityFeature.OPEN,
|
||||
CoverEntityFeature.CLOSE,
|
||||
CoverEntityFeature.STOP,
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
];
|
||||
|
||||
const TILT_FEATURES = [
|
||||
CoverEntityFeature.OPEN_TILT,
|
||||
CoverEntityFeature.CLOSE_TILT,
|
||||
CoverEntityFeature.STOP_TILT,
|
||||
CoverEntityFeature.SET_TILT_POSITION,
|
||||
];
|
||||
|
||||
export const coverHasPositionControls = (stateObj: CoverEntity) =>
|
||||
POSITION_FEATURES.some((feature) => supportsFeature(stateObj, feature));
|
||||
|
||||
export const coverHasTiltControls = (stateObj: CoverEntity) =>
|
||||
TILT_FEATURES.some((feature) => supportsFeature(stateObj, feature));
|
||||
|
||||
export const defaultCoverMode = (stateObj: CoverEntity): CoverControlMode =>
|
||||
coverHasTiltControls(stateObj) && !coverHasPositionControls(stateObj)
|
||||
? "tilt"
|
||||
: "position";
|
||||
|
||||
export const coverModeAttribute = (mode: CoverControlMode) =>
|
||||
mode === "tilt" ? "current_tilt_position" : "current_position";
|
||||
|
||||
const COVER_SERVICES: Record<
|
||||
CoverControlMode,
|
||||
Record<CoverCommand["action"], string>
|
||||
> = {
|
||||
position: {
|
||||
open: "open_cover",
|
||||
close: "close_cover",
|
||||
stop: "stop_cover",
|
||||
set: "set_cover_position",
|
||||
},
|
||||
tilt: {
|
||||
open: "open_cover_tilt",
|
||||
close: "close_cover_tilt",
|
||||
stop: "stop_cover_tilt",
|
||||
set: "set_cover_tilt_position",
|
||||
},
|
||||
};
|
||||
|
||||
export const coverCommandService = ({ mode, action }: CoverCommand) =>
|
||||
COVER_SERVICES[mode][action];
|
||||
|
||||
export const coverCommandData = (
|
||||
stateObj: CoverEntity,
|
||||
command: CoverCommand
|
||||
): Record<string, unknown> => {
|
||||
const data = { entity_id: stateObj.entity_id };
|
||||
if (command.action !== "set") {
|
||||
return data;
|
||||
}
|
||||
return stateObj.state === "open";
|
||||
if (command.mode === "tilt") {
|
||||
return { ...data, tilt_position: command.value };
|
||||
}
|
||||
return { ...data, position: command.value };
|
||||
};
|
||||
|
||||
export function isFullyOpen(stateObj: CoverEntity) {
|
||||
return stateObj.attributes.current_position === 100;
|
||||
}
|
||||
|
||||
export function isFullyClosed(stateObj: CoverEntity) {
|
||||
@@ -51,6 +140,10 @@ export function isClosing(stateObj: CoverEntity) {
|
||||
return stateObj.state === "closing";
|
||||
}
|
||||
|
||||
export function isMoving(stateObj: CoverEntity) {
|
||||
return isOpening(stateObj) || isClosing(stateObj);
|
||||
}
|
||||
|
||||
export function isTiltOnly(stateObj: CoverEntity) {
|
||||
const supportsCover =
|
||||
supportsFeature(stateObj, CoverEntityFeature.OPEN) ||
|
||||
@@ -113,24 +206,29 @@ export interface CoverEntity extends HassEntityBase {
|
||||
attributes: CoverEntityAttributes;
|
||||
}
|
||||
|
||||
export function computeCoverPositionStateDisplay(
|
||||
export const coverCurrentValue = (
|
||||
stateObj: CoverEntity,
|
||||
formatEntityAttributeValue: HomeAssistantFormatters["formatEntityAttributeValue"],
|
||||
position?: number
|
||||
) {
|
||||
const statePosition = stateActive(stateObj)
|
||||
? (stateObj.attributes.current_position ??
|
||||
stateObj.attributes.current_tilt_position)
|
||||
: undefined;
|
||||
mode: CoverControlMode
|
||||
): number | undefined => {
|
||||
if (mode === "tilt") {
|
||||
return stateObj.attributes.current_tilt_position ?? undefined;
|
||||
}
|
||||
const position = stateObj.attributes.current_position;
|
||||
if (
|
||||
position != null ||
|
||||
supportsFeature(stateObj, CoverEntityFeature.SET_POSITION)
|
||||
) {
|
||||
return position ?? undefined;
|
||||
}
|
||||
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
|
||||
return undefined;
|
||||
}
|
||||
return stateObj.state === "closed" || stateObj.state === "opening" ? 0 : 100;
|
||||
};
|
||||
|
||||
const currentPosition = position ?? statePosition;
|
||||
|
||||
return currentPosition && currentPosition !== 100
|
||||
? formatEntityAttributeValue(
|
||||
stateObj,
|
||||
// Always use position as it's the same formatting as tilt position
|
||||
"current_position",
|
||||
Math.round(currentPosition)
|
||||
)
|
||||
: "";
|
||||
declare global {
|
||||
interface HASSDomEvents {
|
||||
"cover-command": CoverCommand;
|
||||
"cover-drag-changed": { drag?: CoverDrag };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { BatterySourceTypeEnergyPreference } from "./energy";
|
||||
|
||||
const capacityUnitFactors: Record<string, number> = {
|
||||
Wh: 0.001,
|
||||
kWh: 1,
|
||||
MWh: 1000,
|
||||
};
|
||||
|
||||
export const batteryCapacityUnits = Object.keys(capacityUnitFactors);
|
||||
|
||||
export const getBatteryCapacity = (
|
||||
source: BatterySourceTypeEnergyPreference,
|
||||
states: Record<string, HassEntity | undefined> | undefined
|
||||
): number | undefined => {
|
||||
let capacity = source.capacity;
|
||||
if (source.entity_capacity) {
|
||||
const entity = states?.[source.entity_capacity];
|
||||
const unit = entity?.attributes.unit_of_measurement;
|
||||
const factor =
|
||||
unit && Object.prototype.hasOwnProperty.call(capacityUnitFactors, unit)
|
||||
? capacityUnitFactors[unit]
|
||||
: undefined;
|
||||
capacity = entity && factor ? Number(entity.state) * factor : undefined;
|
||||
}
|
||||
return capacity != null && Number.isFinite(capacity) && capacity > 0
|
||||
? capacity
|
||||
: undefined;
|
||||
};
|
||||
+325
-50
@@ -81,7 +81,6 @@ export const emptyGridSourceEnergyPreference =
|
||||
number_energy_price: null,
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
cost_adjustment_day: 0,
|
||||
});
|
||||
|
||||
export const emptySolarEnergyPreference =
|
||||
@@ -97,13 +96,6 @@ export const emptyHomeEnergyPreference =
|
||||
stat_energy_to: "",
|
||||
});
|
||||
|
||||
export const emptyBatteryEnergyPreference =
|
||||
(): BatterySourceTypeEnergyPreference => ({
|
||||
type: "battery",
|
||||
stat_energy_from: "",
|
||||
stat_energy_to: "",
|
||||
});
|
||||
|
||||
export const emptyGasEnergyPreference = (): GasSourceTypeEnergyPreference => ({
|
||||
type: "gas",
|
||||
stat_energy_from: "",
|
||||
@@ -169,7 +161,6 @@ export interface GridSourceTypeEnergyPreference {
|
||||
stat_rate?: string; // always available if power_config is set
|
||||
power_config?: PowerConfig;
|
||||
|
||||
cost_adjustment_day: number;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
@@ -190,16 +181,127 @@ export interface HomeSourceTypeEnergyPreference {
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface BatterySourceTypeEnergyPreference {
|
||||
export interface BatteryTotalsSourceTypeEnergyPreference {
|
||||
type: "battery";
|
||||
stat_energy_from: string;
|
||||
stat_energy_to: string;
|
||||
stat_energy_from: string; // out of the battery
|
||||
stat_energy_to: string; // into the battery
|
||||
stat_rate?: string; // always available if power_config is set
|
||||
power_config?: PowerConfig;
|
||||
stat_soc?: string;
|
||||
capacity?: number; // usable capacity in kWh, used to weight the combined SOC
|
||||
entity_capacity?: string; // sensor reporting usable capacity in an energy unit
|
||||
name?: string;
|
||||
}
|
||||
|
||||
// Non-negative power sensors, any subset
|
||||
export interface BatteryDirectionsPowerConfig {
|
||||
stat_rate_from_grid?: string; // grid → battery
|
||||
stat_rate_from_solar?: string; // solar → battery
|
||||
stat_rate_to_home?: string; // battery → home
|
||||
stat_rate_to_grid?: string; // battery → grid
|
||||
}
|
||||
|
||||
// A missing direction is 0. At least one charge and one discharge direction is
|
||||
// required, so getBatteryEnergyStatIds never returns an empty list.
|
||||
export interface BatteryDirectionsSourceTypeEnergyPreference {
|
||||
type: "battery";
|
||||
stat_energy_from?: undefined;
|
||||
stat_energy_to?: undefined;
|
||||
stat_energy_from_grid?: string; // grid → battery
|
||||
stat_energy_from_solar?: string; // solar → battery
|
||||
stat_energy_to_home?: string; // battery → home
|
||||
stat_energy_to_grid?: string; // battery → grid
|
||||
// Net power generated from power_config, + discharge and − charge
|
||||
stat_rate?: string;
|
||||
power_config?: BatteryDirectionsPowerConfig;
|
||||
stat_soc?: string;
|
||||
capacity?: number;
|
||||
entity_capacity?: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export type BatterySourceTypeEnergyPreference =
|
||||
| BatteryTotalsSourceTypeEnergyPreference
|
||||
| BatteryDirectionsSourceTypeEnergyPreference;
|
||||
|
||||
export interface BatteryFlowStatIds {
|
||||
grid_to_battery?: string;
|
||||
solar_to_battery?: string;
|
||||
battery_to_home?: string;
|
||||
battery_to_grid?: string;
|
||||
}
|
||||
|
||||
export const BATTERY_FLOW_KEYS = [
|
||||
"grid_to_battery",
|
||||
"solar_to_battery",
|
||||
"battery_to_home",
|
||||
"battery_to_grid",
|
||||
] as const satisfies readonly (keyof BatteryFlowStatIds)[];
|
||||
|
||||
export const isBatteryDirections = (
|
||||
source: BatterySourceTypeEnergyPreference
|
||||
): source is BatteryDirectionsSourceTypeEnergyPreference => {
|
||||
const directions = source as BatteryDirectionsSourceTypeEnergyPreference;
|
||||
return !!(
|
||||
directions.stat_energy_from_grid ||
|
||||
directions.stat_energy_from_solar ||
|
||||
directions.stat_energy_to_home ||
|
||||
directions.stat_energy_to_grid
|
||||
);
|
||||
};
|
||||
|
||||
/** The direction statistics, or undefined for a battery configured with totals. */
|
||||
export const getBatteryFlowStatIds = (
|
||||
source: BatterySourceTypeEnergyPreference
|
||||
): BatteryFlowStatIds | undefined =>
|
||||
isBatteryDirections(source)
|
||||
? {
|
||||
grid_to_battery: source.stat_energy_from_grid || undefined,
|
||||
solar_to_battery: source.stat_energy_from_solar || undefined,
|
||||
battery_to_home: source.stat_energy_to_home || undefined,
|
||||
battery_to_grid: source.stat_energy_to_grid || undefined,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
/** The direction power sensors, or undefined for a battery configured with totals. */
|
||||
export const getBatteryFlowPowerIds = (
|
||||
source: BatterySourceTypeEnergyPreference
|
||||
): BatteryFlowStatIds | undefined =>
|
||||
isBatteryDirections(source)
|
||||
? {
|
||||
grid_to_battery: source.power_config?.stat_rate_from_grid || undefined,
|
||||
solar_to_battery:
|
||||
source.power_config?.stat_rate_from_solar || undefined,
|
||||
battery_to_home: source.power_config?.stat_rate_to_home || undefined,
|
||||
battery_to_grid: source.power_config?.stat_rate_to_grid || undefined,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
/** Statistics whose sum is the energy going into and coming out of the battery. */
|
||||
export const getBatteryEnergyStatIds = (
|
||||
source: BatterySourceTypeEnergyPreference
|
||||
): { charge: string[]; discharge: string[] } => {
|
||||
if (!isBatteryDirections(source)) {
|
||||
return {
|
||||
charge: [source.stat_energy_to],
|
||||
discharge: [source.stat_energy_from],
|
||||
};
|
||||
}
|
||||
const ids = (...stats: (string | undefined)[]) =>
|
||||
stats.filter((id): id is string => !!id);
|
||||
return {
|
||||
charge: ids(source.stat_energy_from_grid, source.stat_energy_from_solar),
|
||||
discharge: ids(source.stat_energy_to_home, source.stat_energy_to_grid),
|
||||
};
|
||||
};
|
||||
|
||||
/** Identifies a battery in page keys and lookups. */
|
||||
export const getBatteryPrimaryStat = (
|
||||
source: BatterySourceTypeEnergyPreference
|
||||
): string => {
|
||||
const { charge, discharge } = getBatteryEnergyStatIds(source);
|
||||
return discharge[0] ?? charge[0] ?? "";
|
||||
};
|
||||
export interface GasSourceTypeEnergyPreference {
|
||||
type: "gas";
|
||||
|
||||
@@ -392,6 +494,28 @@ export const computeEnergyLabel = (
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Name that cards show as "<name> charged" and "<name> discharged". Unnamed
|
||||
* batteries configured with totals are labelled by each statistic instead.
|
||||
*/
|
||||
export const getBatteryName = (
|
||||
states: HomeAssistant["states"],
|
||||
formatEntityName: HomeAssistant["formatEntityName"],
|
||||
source: BatterySourceTypeEnergyPreference,
|
||||
statsMetadata?: Record<string, StatisticsMetaData>
|
||||
): string | undefined => {
|
||||
if (source.name || !isBatteryDirections(source)) {
|
||||
return source.name;
|
||||
}
|
||||
const primary = getBatteryPrimaryStat(source);
|
||||
return computeEnergyLabel(
|
||||
states,
|
||||
formatEntityName,
|
||||
primary,
|
||||
statsMetadata?.[primary]
|
||||
);
|
||||
};
|
||||
|
||||
export const computeEnergyStatisticArea = (
|
||||
registries: HomeAssistantRegistries,
|
||||
statisticId: string
|
||||
@@ -552,8 +676,8 @@ export const getReferencedStatisticIds = (
|
||||
}
|
||||
|
||||
if (source.type === "battery") {
|
||||
statIDs.push(source.stat_energy_from);
|
||||
statIDs.push(source.stat_energy_to);
|
||||
const { charge, discharge } = getBatteryEnergyStatIds(source);
|
||||
statIDs.push(...discharge, ...charge);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1637,7 +1761,8 @@ const getEnergyGasUnit = (
|
||||
return [source.stat_energy_to];
|
||||
}
|
||||
if (source.type === "battery") {
|
||||
return [source.stat_energy_from, source.stat_energy_to];
|
||||
const { charge, discharge } = getBatteryEnergyStatIds(source);
|
||||
return [...discharge, ...charge];
|
||||
}
|
||||
if (source.type === "grid") {
|
||||
return [source.stat_energy_from, source.stat_energy_to].filter(
|
||||
@@ -1710,6 +1835,14 @@ export interface EnergySumData {
|
||||
from_battery?: Record<number, number>;
|
||||
solar?: Record<number, number>;
|
||||
home?: Record<number, number>;
|
||||
// Set together, only when a battery has direction statistics
|
||||
grid_to_battery?: Record<number, number>;
|
||||
solar_to_battery?: Record<number, number>;
|
||||
battery_to_home?: Record<number, number>;
|
||||
battery_to_grid?: Record<number, number>;
|
||||
// Charge and discharge of the batteries configured with totals
|
||||
to_battery_totals?: Record<number, number>;
|
||||
from_battery_totals?: Record<number, number>;
|
||||
total: {
|
||||
to_grid?: number;
|
||||
from_grid?: number;
|
||||
@@ -1717,6 +1850,12 @@ export interface EnergySumData {
|
||||
from_battery?: number;
|
||||
solar?: number;
|
||||
home?: number;
|
||||
grid_to_battery?: number;
|
||||
solar_to_battery?: number;
|
||||
battery_to_home?: number;
|
||||
battery_to_grid?: number;
|
||||
to_battery_totals?: number;
|
||||
from_battery_totals?: number;
|
||||
};
|
||||
timestamps: number[];
|
||||
}
|
||||
@@ -1758,14 +1897,10 @@ const getSummedDataPartial = (
|
||||
data: EnergyData,
|
||||
compare?: boolean
|
||||
): EnergySumData => {
|
||||
const statIds: {
|
||||
to_grid?: string[];
|
||||
from_grid?: string[];
|
||||
solar?: string[];
|
||||
to_battery?: string[];
|
||||
from_battery?: string[];
|
||||
home?: string[];
|
||||
} = {};
|
||||
const statIds: Partial<
|
||||
Record<Exclude<keyof EnergySumData, "total" | "timestamps">, string[]>
|
||||
> = {};
|
||||
const batteries: BatterySourceTypeEnergyPreference[] = [];
|
||||
|
||||
for (const source of data.prefs.energy_sources) {
|
||||
if (source.type === "solar") {
|
||||
@@ -1783,12 +1918,14 @@ const getSummedDataPartial = (
|
||||
}
|
||||
|
||||
if (source.type === "battery") {
|
||||
batteries.push(source);
|
||||
const { charge, discharge } = getBatteryEnergyStatIds(source);
|
||||
if (statIds.to_battery) {
|
||||
statIds.to_battery.push(source.stat_energy_to);
|
||||
statIds.from_battery!.push(source.stat_energy_from);
|
||||
statIds.to_battery.push(...charge);
|
||||
statIds.from_battery!.push(...discharge);
|
||||
} else {
|
||||
statIds.to_battery = [source.stat_energy_to];
|
||||
statIds.from_battery = [source.stat_energy_from];
|
||||
statIds.to_battery = [...charge];
|
||||
statIds.from_battery = [...discharge];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -1814,6 +1951,23 @@ const getSummedDataPartial = (
|
||||
}
|
||||
}
|
||||
|
||||
if (batteries.some(isBatteryDirections)) {
|
||||
for (const key of BATTERY_FLOW_KEYS) {
|
||||
statIds[key] = batteries.flatMap(
|
||||
(battery) => getBatteryFlowStatIds(battery)?.[key] ?? []
|
||||
);
|
||||
}
|
||||
const totalsBatteries = batteries.filter(
|
||||
(battery) => !isBatteryDirections(battery)
|
||||
);
|
||||
statIds.to_battery_totals = totalsBatteries.flatMap(
|
||||
(battery) => getBatteryEnergyStatIds(battery).charge
|
||||
);
|
||||
statIds.from_battery_totals = totalsBatteries.flatMap(
|
||||
(battery) => getBatteryEnergyStatIds(battery).discharge
|
||||
);
|
||||
}
|
||||
|
||||
const summedData: EnergySumData = { total: {}, timestamps: [] };
|
||||
const timestamps = new Set<number>();
|
||||
Object.entries(statIds).forEach(([key, subStatIds]) => {
|
||||
@@ -1884,11 +2038,12 @@ const computeConsumptionDataPartial = (
|
||||
},
|
||||
};
|
||||
|
||||
const measured = BATTERY_FLOW_KEYS.some((key) => data[key]);
|
||||
const fromGrid = data.from_grid;
|
||||
const toGrid = data.to_grid;
|
||||
const solarData = data.solar;
|
||||
const toBattery = data.to_battery;
|
||||
const fromBattery = data.from_battery;
|
||||
const toBattery = measured ? data.to_battery_totals : data.to_battery;
|
||||
const fromBattery = measured ? data.from_battery_totals : data.from_battery;
|
||||
const total = outData.total;
|
||||
|
||||
data.timestamps.forEach((t) => {
|
||||
@@ -1903,13 +2058,25 @@ const computeConsumptionDataPartial = (
|
||||
used_total,
|
||||
solar_to_battery,
|
||||
solar_to_grid,
|
||||
} = computeConsumptionSingle({
|
||||
from_grid: fromGrid && (fromGrid[t] ?? 0),
|
||||
to_grid: toGrid && (toGrid[t] ?? 0),
|
||||
solar: solarData && (solarData[t] ?? 0),
|
||||
to_battery: toBattery && (toBattery[t] ?? 0),
|
||||
from_battery: fromBattery && (fromBattery[t] ?? 0),
|
||||
});
|
||||
} = computeConsumptionSingle(
|
||||
{
|
||||
from_grid: fromGrid && (fromGrid[t] ?? 0),
|
||||
to_grid: toGrid && (toGrid[t] ?? 0),
|
||||
solar: solarData && (solarData[t] ?? 0),
|
||||
to_battery: toBattery && (toBattery[t] ?? 0),
|
||||
from_battery: fromBattery && (fromBattery[t] ?? 0),
|
||||
},
|
||||
measured
|
||||
? {
|
||||
measured: {
|
||||
grid_to_battery: data.grid_to_battery?.[t] ?? 0,
|
||||
solar_to_battery: data.solar_to_battery?.[t] ?? 0,
|
||||
battery_to_home: data.battery_to_home?.[t] ?? 0,
|
||||
battery_to_grid: data.battery_to_grid?.[t] ?? 0,
|
||||
},
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
|
||||
const usedTotal = hasHome ? Math.max(homeUsed, 0) : used_total;
|
||||
outData.used_total[t] = usedTotal;
|
||||
@@ -1933,13 +2100,15 @@ const computeConsumptionDataPartial = (
|
||||
return outData;
|
||||
};
|
||||
|
||||
export const computeConsumptionSingle = (data: {
|
||||
interface ConsumptionInput {
|
||||
from_grid: number | undefined;
|
||||
to_grid: number | undefined;
|
||||
solar: number | undefined;
|
||||
to_battery: number | undefined;
|
||||
from_battery: number | undefined;
|
||||
}): {
|
||||
}
|
||||
|
||||
interface ConsumptionResult {
|
||||
grid_to_battery: number;
|
||||
battery_to_grid: number;
|
||||
solar_to_battery: number;
|
||||
@@ -1948,7 +2117,12 @@ export const computeConsumptionSingle = (data: {
|
||||
used_grid: number;
|
||||
used_battery: number;
|
||||
used_total: number;
|
||||
} => {
|
||||
}
|
||||
|
||||
const inferConsumption = (
|
||||
data: ConsumptionInput,
|
||||
usedTotal?: number
|
||||
): ConsumptionResult => {
|
||||
let to_grid = Math.max(data.to_grid || 0, 0);
|
||||
let to_battery = Math.max(data.to_battery || 0, 0);
|
||||
let solar = Math.max(data.solar || 0, 0);
|
||||
@@ -1956,11 +2130,12 @@ export const computeConsumptionSingle = (data: {
|
||||
let from_battery = Math.max(data.from_battery || 0, 0);
|
||||
|
||||
const used_total =
|
||||
usedTotal ??
|
||||
(from_grid || 0) +
|
||||
(solar || 0) +
|
||||
(from_battery || 0) -
|
||||
(to_grid || 0) -
|
||||
(to_battery || 0);
|
||||
(solar || 0) +
|
||||
(from_battery || 0) -
|
||||
(to_grid || 0) -
|
||||
(to_battery || 0);
|
||||
|
||||
let grid_to_battery = 0;
|
||||
|
||||
@@ -2028,6 +2203,70 @@ export const computeConsumptionSingle = (data: {
|
||||
};
|
||||
};
|
||||
|
||||
export type MeasuredBatteryFlows = Record<
|
||||
(typeof BATTERY_FLOW_KEYS)[number],
|
||||
number | undefined
|
||||
>;
|
||||
|
||||
/**
|
||||
* Splits the energy or power of one period into flows. Batteries with
|
||||
* direction statistics pass them in `measured`, and `to_battery` and
|
||||
* `from_battery` then only hold the batteries configured with totals.
|
||||
* Measured flows are kept as they are; only the rest is estimated. Leave a
|
||||
* meter undefined when it isn't configured, rather than 0.
|
||||
*/
|
||||
export const computeConsumptionSingle = (
|
||||
data: ConsumptionInput,
|
||||
options?: { measured?: MeasuredBatteryFlows; used_total?: number }
|
||||
): ConsumptionResult => {
|
||||
const measured = options?.measured;
|
||||
if (!measured) {
|
||||
return inferConsumption(data, options?.used_total);
|
||||
}
|
||||
const clamp = (value: number | undefined) => Math.max(value || 0, 0);
|
||||
const gridToBattery = clamp(measured.grid_to_battery);
|
||||
const solarToBattery = clamp(measured.solar_to_battery);
|
||||
const batteryToHome = clamp(measured.battery_to_home);
|
||||
const batteryToGrid = clamp(measured.battery_to_grid);
|
||||
const fromGrid = clamp(data.from_grid);
|
||||
const toGrid = clamp(data.to_grid);
|
||||
const solar = clamp(data.solar);
|
||||
// A flow without a configured meter never passed one, so it stays out of
|
||||
// the home load
|
||||
const metered = (meter: number | undefined, flow: number) =>
|
||||
meter === undefined ? 0 : flow;
|
||||
const toBattery =
|
||||
clamp(data.to_battery) +
|
||||
metered(data.from_grid, gridToBattery) +
|
||||
metered(data.solar, solarToBattery);
|
||||
const fromBattery =
|
||||
clamp(data.from_battery) +
|
||||
batteryToHome +
|
||||
metered(data.to_grid, batteryToGrid);
|
||||
const usedTotal =
|
||||
options.used_total ?? fromGrid + solar + fromBattery - toGrid - toBattery;
|
||||
|
||||
// Only what the measured flows leave over is estimated
|
||||
const inferred = inferConsumption(
|
||||
{
|
||||
from_grid: Math.max(fromGrid - gridToBattery, 0),
|
||||
to_grid: Math.max(toGrid - batteryToGrid, 0),
|
||||
solar: Math.max(solar - solarToBattery, 0),
|
||||
to_battery: data.to_battery,
|
||||
from_battery: data.from_battery,
|
||||
},
|
||||
Math.max(usedTotal - batteryToHome, 0)
|
||||
);
|
||||
return {
|
||||
...inferred,
|
||||
grid_to_battery: inferred.grid_to_battery + gridToBattery,
|
||||
solar_to_battery: inferred.solar_to_battery + solarToBattery,
|
||||
battery_to_grid: inferred.battery_to_grid + batteryToGrid,
|
||||
used_battery: inferred.used_battery + batteryToHome,
|
||||
used_total: usedTotal,
|
||||
};
|
||||
};
|
||||
|
||||
export const formatConsumptionShort = (
|
||||
locale: HomeAssistant["locale"],
|
||||
consumption: number | null,
|
||||
@@ -2517,18 +2756,54 @@ export const downloadEnergyData = (
|
||||
grid_productions_cost
|
||||
);
|
||||
|
||||
const batteries = energy_sources.filter(
|
||||
(s): s is BatterySourceTypeEnergyPreference => s.type === "battery"
|
||||
);
|
||||
const battery_ins: string[] = [];
|
||||
const battery_outs: string[] = [];
|
||||
energy_sources
|
||||
.filter((s) => s.type === "battery")
|
||||
.forEach((source) => {
|
||||
source = source as BatterySourceTypeEnergyPreference;
|
||||
battery_ins.push(source.stat_energy_to);
|
||||
battery_outs.push(source.stat_energy_from);
|
||||
const battery_flows: Record<keyof BatteryFlowStatIds, string[]> = {
|
||||
grid_to_battery: [],
|
||||
solar_to_battery: [],
|
||||
battery_to_home: [],
|
||||
battery_to_grid: [],
|
||||
};
|
||||
batteries.forEach((source) => {
|
||||
const flows = getBatteryFlowStatIds(source);
|
||||
if (!flows) {
|
||||
const { charge, discharge } = getBatteryEnergyStatIds(source);
|
||||
battery_ins.push(...charge);
|
||||
battery_outs.push(...discharge);
|
||||
return;
|
||||
}
|
||||
BATTERY_FLOW_KEYS.forEach((key) => {
|
||||
if (flows[key]) {
|
||||
battery_flows[key].push(flows[key]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
printCategory("battery_in", battery_ins, electricUnit);
|
||||
printCategory("battery_out", battery_outs, electricUnit);
|
||||
printCategory(
|
||||
"battery_in_from_grid",
|
||||
battery_flows.grid_to_battery,
|
||||
electricUnit
|
||||
);
|
||||
printCategory(
|
||||
"battery_in_from_solar",
|
||||
battery_flows.solar_to_battery,
|
||||
electricUnit
|
||||
);
|
||||
printCategory(
|
||||
"battery_out_to_home",
|
||||
battery_flows.battery_to_home,
|
||||
electricUnit
|
||||
);
|
||||
printCategory(
|
||||
"battery_out_to_grid",
|
||||
battery_flows.battery_to_grid,
|
||||
electricUnit
|
||||
);
|
||||
|
||||
const solar_productions: string[] = [];
|
||||
energy_sources
|
||||
@@ -2645,7 +2920,7 @@ export const downloadEnergyData = (
|
||||
|
||||
const hasSolar = !!solar_productions.length;
|
||||
const hasHome = !!home_consumptions.length;
|
||||
const hasBattery = !!battery_ins.length;
|
||||
const hasBattery = batteries.length > 0;
|
||||
const hasGridReturn = !!grid_productions.length;
|
||||
const hasGridSource = !!grid_consumptions.length;
|
||||
|
||||
|
||||
@@ -266,10 +266,10 @@ export const computeEntityRegistryName = (
|
||||
};
|
||||
|
||||
export const getExtendedEntityRegistryEntry = (
|
||||
hass: Pick<HomeAssistant, "callWS">,
|
||||
callWS: HomeAssistant["callWS"],
|
||||
entityId: string
|
||||
): Promise<ExtEntityRegistryEntry> =>
|
||||
hass.callWS({
|
||||
callWS({
|
||||
type: "config/entity_registry/get",
|
||||
entity_id: entityId,
|
||||
});
|
||||
|
||||
@@ -51,10 +51,6 @@ export interface SecurityFrontendSystemData {
|
||||
favorite_entities?: string[];
|
||||
}
|
||||
|
||||
export interface MaintenanceFrontendSystemData {
|
||||
hidden_entities?: string[];
|
||||
}
|
||||
|
||||
export interface EnergyFrontendSystemData {
|
||||
// Stable "<view>.<card-type>" keys of energy dashboard cards the user has
|
||||
// hidden. An absent key or array means nothing is hidden (all cards visible),
|
||||
@@ -73,7 +69,6 @@ declare global {
|
||||
home: HomeFrontendSystemData;
|
||||
energy: EnergyFrontendSystemData;
|
||||
security: SecurityFrontendSystemData;
|
||||
maintenance: MaintenanceFrontendSystemData;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,32 +145,6 @@ export const saveFrontendSystemData = async <
|
||||
value,
|
||||
});
|
||||
|
||||
const pendingSystemDataSaves = new Map<ValidSystemDataKey, Promise<void>>();
|
||||
|
||||
export const queueFrontendSystemDataSave = <
|
||||
SystemDataKey extends ValidSystemDataKey,
|
||||
>(
|
||||
conn: Connection,
|
||||
key: SystemDataKey,
|
||||
value: FrontendSystemData[SystemDataKey]
|
||||
): Promise<void> => {
|
||||
const save = (pendingSystemDataSaves.get(key) ?? Promise.resolve())
|
||||
.catch(() => undefined)
|
||||
.then(() => saveFrontendSystemData(conn, key, value));
|
||||
pendingSystemDataSaves.set(key, save);
|
||||
return save;
|
||||
};
|
||||
|
||||
export const fetchFrontendSystemDataAfterSaves = async <
|
||||
SystemDataKey extends ValidSystemDataKey,
|
||||
>(
|
||||
conn: Connection,
|
||||
key: SystemDataKey
|
||||
): Promise<FrontendSystemData[SystemDataKey] | null> => {
|
||||
await pendingSystemDataSaves.get(key)?.catch(() => undefined);
|
||||
return fetchFrontendSystemData(conn, key);
|
||||
};
|
||||
|
||||
export const subscribeFrontendSystemData = <
|
||||
SystemDataKey extends ValidSystemDataKey,
|
||||
>(
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type {
|
||||
HassEntities,
|
||||
HassEntity,
|
||||
HassEntityAttributeBase,
|
||||
HassEntityBase,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { computeDomain } from "../common/entity/compute_domain";
|
||||
import type { ExtEntityRegistryEntry } from "./entity/entity_registry";
|
||||
|
||||
interface GroupEntityAttributes extends HassEntityAttributeBase {
|
||||
entity_id: string[];
|
||||
@@ -24,3 +27,55 @@ export const computeGroupDomain = (
|
||||
];
|
||||
return uniqueDomains.length === 1 ? uniqueDomains[0] : undefined;
|
||||
};
|
||||
|
||||
/** Member entity IDs of a group, or undefined if it is not a group. */
|
||||
export const computeGroupMemberIds = (
|
||||
stateObj: HassEntity,
|
||||
entry?: Pick<ExtEntityRegistryEntry, "capabilities"> | null
|
||||
): string[] | undefined => {
|
||||
const ids =
|
||||
entry?.capabilities?.group_entities ??
|
||||
stateObj.attributes.group_entities ??
|
||||
stateObj.attributes.entity_id;
|
||||
return Array.isArray(ids) ? ids : undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* Drops groups that have a member in `entityIds`, at any depth (a hidden
|
||||
* group in between still counts). A group with no listed member stays, so
|
||||
* hiding its bulbs doesn't read "All off".
|
||||
*/
|
||||
export const filterGroupsWithListedMembers = (
|
||||
entityIds: string[],
|
||||
states: HassEntities
|
||||
): string[] => {
|
||||
const listed = new Set(entityIds);
|
||||
const hasListedDescendant = (groupId: string): boolean => {
|
||||
const seen = new Set([groupId]);
|
||||
const queue = [groupId];
|
||||
while (queue.length) {
|
||||
const stateObj = states[queue.shift()!];
|
||||
for (const memberId of (stateObj && computeGroupMemberIds(stateObj)) ??
|
||||
[]) {
|
||||
if (seen.has(memberId)) {
|
||||
continue;
|
||||
}
|
||||
if (listed.has(memberId)) {
|
||||
return true;
|
||||
}
|
||||
seen.add(memberId);
|
||||
queue.push(memberId);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return entityIds.filter((entityId) => {
|
||||
if (!hasListedDescendant(entityId)) {
|
||||
return true;
|
||||
}
|
||||
// A dropped group no longer counts as listed, so of two groups that
|
||||
// contain each other one still stays.
|
||||
listed.delete(entityId);
|
||||
return false;
|
||||
});
|
||||
};
|
||||
@@ -60,3 +60,18 @@ export const validateHassioSession = async (
|
||||
): Promise<void> => {
|
||||
await hass.callWS({ type: "supervisor/ingress/validate_session", session });
|
||||
};
|
||||
|
||||
// Extends the session, or replaces it with a new one for the app if it has
|
||||
// expired. Returns the session to keep using.
|
||||
export const refreshHassioSession = async (
|
||||
hass: Pick<HomeAssistant, "callWS">,
|
||||
slug: string,
|
||||
session: string
|
||||
): Promise<string> => {
|
||||
try {
|
||||
await validateHassioSession(hass, session);
|
||||
return session;
|
||||
} catch (_err: any) {
|
||||
return createHassioSession(hass, slug);
|
||||
}
|
||||
};
|
||||
+5
-5
@@ -6,7 +6,7 @@ import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { showEnterCodeDialog } from "../dialogs/enter-code/show-enter-code-dialog";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import { UNAVAILABLE } from "./entity/entity";
|
||||
import type { ExtEntityRegistryEntry } from "./entity/entity_registry";
|
||||
import { getExtendedEntityRegistryEntry } from "./entity/entity_registry";
|
||||
|
||||
export enum LockEntityFeature {
|
||||
OPEN = 1,
|
||||
@@ -88,10 +88,10 @@ export const callProtectedLockService = async (
|
||||
service: ProtectedLockService
|
||||
) => {
|
||||
let code: string | undefined;
|
||||
const lockRegistryEntry = await callWS<ExtEntityRegistryEntry>({
|
||||
type: "config/entity_registry/get",
|
||||
entity_id: stateObj.entity_id,
|
||||
}).catch(() => undefined);
|
||||
const lockRegistryEntry = await getExtendedEntityRegistryEntry(
|
||||
callWS,
|
||||
stateObj.entity_id
|
||||
).catch(() => undefined);
|
||||
const defaultCode = lockRegistryEntry?.options?.lock?.default_code;
|
||||
|
||||
if (stateObj!.attributes.code_format && !defaultCode) {
|
||||
|
||||
+11
-7
@@ -209,7 +209,15 @@ export const watchForNewMatterDevice = (
|
||||
callback: (device: DeviceRegistryEntry) => void
|
||||
): UnsubscribeFunc => {
|
||||
let curMatterDevices: Set<string> | undefined;
|
||||
const unsubDeviceReg = subscribeDeviceRegistry(hass.connection, (entries) => {
|
||||
let unsubDeviceReg: UnsubscribeFunc | undefined;
|
||||
// Callers also unsubscribe after a find. The registry collection counts its
|
||||
// subscribers, so a second unsubscribe would stop its updates for everyone.
|
||||
const unsubscribe = () => {
|
||||
unsubDeviceReg?.();
|
||||
unsubDeviceReg = undefined;
|
||||
curMatterDevices = undefined;
|
||||
};
|
||||
unsubDeviceReg = subscribeDeviceRegistry(hass.connection, (entries) => {
|
||||
if (!curMatterDevices) {
|
||||
curMatterDevices = new Set(
|
||||
Object.values(entries)
|
||||
@@ -226,15 +234,11 @@ export const watchForNewMatterDevice = (
|
||||
!curMatterDevices!.has(device.id)
|
||||
);
|
||||
if (newMatterDevices.length) {
|
||||
unsubDeviceReg();
|
||||
curMatterDevices = undefined;
|
||||
unsubscribe();
|
||||
callback(newMatterDevices[0]);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
unsubDeviceReg();
|
||||
curMatterDevices = undefined;
|
||||
};
|
||||
return unsubscribe;
|
||||
};
|
||||
|
||||
export const redirectOnNewMatterDevice = (
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
registriesContext,
|
||||
uiContext,
|
||||
} from "./context";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import type { HomeAssistant, HomeAssistantRegistries } from "../types";
|
||||
|
||||
/**
|
||||
* Reactive controller that keeps `NavigationPathInfo` in sync with a
|
||||
@@ -45,19 +45,8 @@ export class NavigationPathInfoController extends ContextController {
|
||||
})
|
||||
private _panels?: HomeAssistant["panels"];
|
||||
|
||||
@consumeContext({
|
||||
context: registriesContext,
|
||||
subscribe: true,
|
||||
transform: ({ areas }) => areas,
|
||||
})
|
||||
private _areas?: HomeAssistant["areas"];
|
||||
|
||||
@consumeContext({
|
||||
context: registriesContext,
|
||||
subscribe: true,
|
||||
transform: ({ devices }) => devices,
|
||||
})
|
||||
private _devices?: HomeAssistant["devices"];
|
||||
@consumeContext({ context: registriesContext, subscribe: true })
|
||||
private _registries?: HomeAssistantRegistries | null;
|
||||
|
||||
@consumeContext({
|
||||
context: configContext,
|
||||
@@ -79,6 +68,8 @@ export class NavigationPathInfoController extends ContextController {
|
||||
|
||||
private _path?: string;
|
||||
|
||||
private _resolvedInputs?: unknown[];
|
||||
|
||||
get info(): NavigationPathInfo {
|
||||
return this._info;
|
||||
}
|
||||
@@ -97,13 +88,31 @@ export class NavigationPathInfoController extends ContextController {
|
||||
this._unsubscribe();
|
||||
}
|
||||
|
||||
// The resolved info depends on every consumed value, so re-resolve.
|
||||
protected contextUpdated(): void {
|
||||
const inputs = this._inputs();
|
||||
if (
|
||||
this._resolvedInputs &&
|
||||
inputs.every((value, i) => value === this._resolvedInputs![i])
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this._resolve();
|
||||
}
|
||||
|
||||
private _inputs(): unknown[] {
|
||||
return [
|
||||
this._localize,
|
||||
this._panels,
|
||||
this._registries?.areas,
|
||||
this._registries?.devices,
|
||||
this._config,
|
||||
this._connection,
|
||||
];
|
||||
}
|
||||
|
||||
private _resolve(): void {
|
||||
this._unsubscribe();
|
||||
this._resolvedInputs = this._inputs();
|
||||
|
||||
if (!this._path) {
|
||||
if (this._info !== DEFAULT_NAVIGATION_PATH_INFO) {
|
||||
@@ -116,8 +125,8 @@ export class NavigationPathInfoController extends ContextController {
|
||||
if (
|
||||
!this._localize ||
|
||||
!this._panels ||
|
||||
!this._areas ||
|
||||
!this._devices ||
|
||||
!this._registries?.areas ||
|
||||
!this._registries.devices ||
|
||||
!this._config ||
|
||||
!this._connection
|
||||
) {
|
||||
@@ -128,8 +137,8 @@ export class NavigationPathInfoController extends ContextController {
|
||||
{
|
||||
localize: this._localize,
|
||||
panels: this._panels,
|
||||
areas: this._areas,
|
||||
devices: this._devices,
|
||||
areas: this._registries.areas,
|
||||
devices: this._registries.devices,
|
||||
config: this._config,
|
||||
connection: this._connection,
|
||||
},
|
||||
|
||||
+47
-1
@@ -1,7 +1,7 @@
|
||||
import type { Connection } from "home-assistant-js-websocket";
|
||||
import { DEFAULT_ENTITY_NAME } from "../common/entity/entity_name_config";
|
||||
import type { HaDurationData } from "../components/ha-duration-input";
|
||||
import type { HomeAssistant } from "../types";
|
||||
import type { HomeAssistant, HomeAssistantApi } from "../types";
|
||||
import { firstWeekday } from "../common/datetime/first_weekday";
|
||||
|
||||
export interface RecorderInfo {
|
||||
@@ -163,6 +163,52 @@ export const getRecorderInfo = (conn: Connection) =>
|
||||
type: "recorder/info",
|
||||
});
|
||||
|
||||
export interface RecorderTableUsage {
|
||||
table: string;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
// Byte figures are null when the database cannot report table sizes.
|
||||
export interface RecorderEntityUsage {
|
||||
// null collects rows without a known entity
|
||||
entity_id: string | null;
|
||||
states: number;
|
||||
states_bytes: number | null;
|
||||
attributes_bytes: number | null;
|
||||
}
|
||||
|
||||
export interface RecorderStatisticUsage {
|
||||
// null collects rows without a known statistic
|
||||
statistic_id: string | null;
|
||||
source: string | null;
|
||||
statistics: number;
|
||||
statistics_short_term: number;
|
||||
statistics_bytes: number | null;
|
||||
statistics_short_term_bytes: number | null;
|
||||
}
|
||||
|
||||
export interface RecorderDatabaseUsage {
|
||||
generated_at: string;
|
||||
duration: number;
|
||||
total_bytes: number;
|
||||
free_bytes: number | null;
|
||||
// SQLite write-ahead log, not part of total_bytes
|
||||
wal_bytes: number | null;
|
||||
tables: RecorderTableUsage[] | null;
|
||||
entities: RecorderEntityUsage[];
|
||||
statistics: RecorderStatisticUsage[];
|
||||
}
|
||||
|
||||
// Without refresh this returns the last report of the past hour, or null.
|
||||
export const fetchRecorderDatabaseUsage = (
|
||||
api: Pick<HomeAssistantApi, "callWS">,
|
||||
refresh = false
|
||||
) =>
|
||||
api.callWS<RecorderDatabaseUsage | null>({
|
||||
type: "recorder/database_usage",
|
||||
refresh,
|
||||
});
|
||||
|
||||
export type EntityRecordingDisabler = "user";
|
||||
|
||||
export interface RecorderEntityOptions {
|
||||
|
||||
@@ -185,6 +185,11 @@ export interface ColorRGBSelector {
|
||||
export interface ColorTempSelector {
|
||||
color_temp: {
|
||||
unit?: "kelvin" | "mired";
|
||||
/**
|
||||
* Slider bounds. For `unit: "kelvin"` these apply only when no entity in
|
||||
* the selector context `filter_entity` reports `min_color_temp_kelvin`
|
||||
* and `max_color_temp_kelvin`.
|
||||
*/
|
||||
min?: number;
|
||||
max?: number;
|
||||
min_mireds?: number;
|
||||
|
||||
+14
-2
@@ -79,13 +79,25 @@ export const updateButtonIsDisabled = (entity: UpdateEntity): boolean =>
|
||||
export const updateIsInstalling = (entity: UpdateEntity): boolean =>
|
||||
!!entity.attributes.in_progress;
|
||||
|
||||
export interface UpdateReleaseNotesMessage {
|
||||
severity: "info" | "warning" | "error";
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface UpdateReleaseNotes {
|
||||
release_notes: string | null;
|
||||
messages: UpdateReleaseNotesMessage[];
|
||||
}
|
||||
|
||||
export const updateReleaseNotes = (
|
||||
hass: Pick<HomeAssistant, "callWS">,
|
||||
entityId: string
|
||||
entityId: string,
|
||||
language: string
|
||||
) =>
|
||||
hass.callWS<string | null>({
|
||||
hass.callWS<UpdateReleaseNotes>({
|
||||
type: "update/release_notes",
|
||||
entity_id: entityId,
|
||||
language,
|
||||
});
|
||||
|
||||
const HOME_ASSISTANT_CORE_TITLE = "Home Assistant Core";
|
||||
|
||||
+13
-7
@@ -364,19 +364,25 @@ const getWeatherExtrema = (
|
||||
if (new Date(fc.datetime).getDate() !== today) {
|
||||
break;
|
||||
}
|
||||
if (!tempHigh || fc.temperature > tempHigh) {
|
||||
if (fc.temperature == null) {
|
||||
continue;
|
||||
}
|
||||
if (tempHigh === undefined || fc.temperature > tempHigh) {
|
||||
tempHigh =
|
||||
temperatureFractionDigits === undefined
|
||||
? fc.temperature
|
||||
: round(fc.temperature, temperatureFractionDigits);
|
||||
}
|
||||
if (fc.templow !== undefined && (!tempLow || fc.templow < tempLow)) {
|
||||
if (fc.templow != null && (tempLow === undefined || fc.templow < tempLow)) {
|
||||
tempLow =
|
||||
temperatureFractionDigits === undefined
|
||||
? fc.templow
|
||||
: round(fc.templow, temperatureFractionDigits);
|
||||
}
|
||||
if (!fc.templow && (!tempLow || fc.temperature < tempLow)) {
|
||||
if (
|
||||
fc.templow == null &&
|
||||
(tempLow === undefined || fc.temperature < tempLow)
|
||||
) {
|
||||
tempLow =
|
||||
temperatureFractionDigits === undefined
|
||||
? fc.temperature
|
||||
@@ -384,19 +390,19 @@ const getWeatherExtrema = (
|
||||
}
|
||||
}
|
||||
|
||||
if (!tempLow && !tempHigh) {
|
||||
if (tempLow === undefined && tempHigh === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return html`
|
||||
${
|
||||
tempHigh
|
||||
tempHigh !== undefined
|
||||
? formatEntityAttributeValue(stateObj, "temperature", tempHigh)
|
||||
: ""
|
||||
}
|
||||
${tempLow && tempHigh ? " / " : ""}
|
||||
${tempLow !== undefined && tempHigh !== undefined ? " / " : ""}
|
||||
${
|
||||
tempLow
|
||||
tempLow !== undefined
|
||||
? formatEntityAttributeValue(stateObj, "temperature", tempLow)
|
||||
: ""
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export const fetchEntityConfigFlow = async (
|
||||
if (!entities || !(entityId in entities)) {
|
||||
return undefined;
|
||||
}
|
||||
const regEntry = await getExtendedEntityRegistryEntry(api, entityId);
|
||||
const regEntry = await getExtendedEntityRegistryEntry(api.callWS, entityId);
|
||||
if (!regEntry.config_entry_id) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { mdiArrowBottomLeft, mdiArrowTopRight, mdiStop } from "@mdi/js";
|
||||
import { LitElement, css, html, nothing } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { consumeLocalize } from "../../../../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import {
|
||||
computeCloseIcon,
|
||||
computeOpenIcon,
|
||||
} from "../../../../common/entity/cover_icon";
|
||||
import { supportsFeature } from "../../../../common/entity/supports-feature";
|
||||
import type {
|
||||
LocalizeFunc,
|
||||
LocalizeKeys,
|
||||
} from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-control-button";
|
||||
import "../../../../components/ha-svg-icon";
|
||||
import type {
|
||||
CoverAction,
|
||||
CoverControlMode,
|
||||
CoverEntity,
|
||||
} from "../../../../data/cover";
|
||||
import {
|
||||
CoverEntityFeature,
|
||||
canClose,
|
||||
canCloseTilt,
|
||||
canOpen,
|
||||
canOpenTilt,
|
||||
canStop,
|
||||
canStopTilt,
|
||||
} from "../../../../data/cover";
|
||||
|
||||
interface CoverButton {
|
||||
action: CoverAction;
|
||||
feature: CoverEntityFeature;
|
||||
icon: (stateObj: CoverEntity) => string;
|
||||
label: LocalizeKeys;
|
||||
enabled: (stateObj: CoverEntity) => boolean;
|
||||
}
|
||||
|
||||
const BUTTONS: Record<CoverControlMode, CoverButton[]> = {
|
||||
position: [
|
||||
{
|
||||
action: "open",
|
||||
feature: CoverEntityFeature.OPEN,
|
||||
icon: computeOpenIcon,
|
||||
label: "ui.card.cover.open_cover",
|
||||
enabled: canOpen,
|
||||
},
|
||||
{
|
||||
action: "stop",
|
||||
feature: CoverEntityFeature.STOP,
|
||||
icon: () => mdiStop,
|
||||
label: "ui.card.cover.stop_cover",
|
||||
enabled: canStop,
|
||||
},
|
||||
{
|
||||
action: "close",
|
||||
feature: CoverEntityFeature.CLOSE,
|
||||
icon: computeCloseIcon,
|
||||
label: "ui.card.cover.close_cover",
|
||||
enabled: canClose,
|
||||
},
|
||||
],
|
||||
tilt: [
|
||||
{
|
||||
action: "open",
|
||||
feature: CoverEntityFeature.OPEN_TILT,
|
||||
icon: () => mdiArrowTopRight,
|
||||
label: "ui.card.cover.open_tilt_cover",
|
||||
enabled: canOpenTilt,
|
||||
},
|
||||
{
|
||||
action: "stop",
|
||||
feature: CoverEntityFeature.STOP_TILT,
|
||||
icon: () => mdiStop,
|
||||
label: "ui.card.cover.stop_cover",
|
||||
enabled: canStopTilt,
|
||||
},
|
||||
{
|
||||
action: "close",
|
||||
feature: CoverEntityFeature.CLOSE_TILT,
|
||||
icon: () => mdiArrowBottomLeft,
|
||||
label: "ui.card.cover.close_tilt_cover",
|
||||
enabled: canCloseTilt,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@customElement("ha-more-info-cover-buttons")
|
||||
export class HaMoreInfoCoverButtons extends LitElement {
|
||||
@property({ attribute: false }) public stateObj!: CoverEntity;
|
||||
|
||||
@property({ attribute: false }) public mode: CoverControlMode = "position";
|
||||
|
||||
@state()
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
private _handleClick(ev: Event) {
|
||||
const action = (ev.currentTarget as HTMLElement).dataset
|
||||
.action as CoverAction;
|
||||
fireEvent(this, "cover-command", { mode: this.mode, action });
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.stateObj) {
|
||||
return nothing;
|
||||
}
|
||||
const stateObj = this.stateObj;
|
||||
const buttons = BUTTONS[this.mode].filter((button) =>
|
||||
supportsFeature(stateObj, button.feature)
|
||||
);
|
||||
if (!buttons.length) {
|
||||
return nothing;
|
||||
}
|
||||
return html`
|
||||
${buttons.map(
|
||||
(button) => html`
|
||||
<ha-control-button
|
||||
.label=${this._localize(button.label)}
|
||||
.disabled=${!button.enabled(stateObj)}
|
||||
data-action=${button.action}
|
||||
@click=${this._handleClick}
|
||||
>
|
||||
<div class="content">
|
||||
<ha-svg-icon .path=${button.icon(stateObj)}></ha-svg-icon>
|
||||
<span>
|
||||
${this._localize(
|
||||
`ui.dialogs.more_info_control.cover.${button.action}`
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</ha-control-button>
|
||||
`
|
||||
)}
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: var(--ha-space-3);
|
||||
width: 100%;
|
||||
}
|
||||
ha-control-button {
|
||||
flex: 1;
|
||||
max-width: 104px;
|
||||
height: 64px;
|
||||
--control-button-border-radius: var(--ha-border-radius-xl);
|
||||
--mdc-icon-size: 22px;
|
||||
}
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-1);
|
||||
font-size: var(--ha-font-size-s);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-more-info-cover-buttons": HaMoreInfoCoverButtons;
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,14 @@ import { consumeLocalize } from "../../../../common/decorators/consume-context-e
|
||||
import { transform } from "../../../../common/decorators/transform";
|
||||
import type { HASSDomEvent } from "../../../../common/dom/fire_event";
|
||||
import { fireEvent } from "../../../../common/dom/fire_event";
|
||||
import { clamp } from "../../../../common/number/clamp";
|
||||
import type { LocalizeFunc } from "../../../../common/translations/localize";
|
||||
import "../../../../components/ha-control-button";
|
||||
import { apiContext, configContext } from "../../../../data/context";
|
||||
import type { CoverEntity } from "../../../../data/cover";
|
||||
import type { CoverControlMode, CoverEntity } from "../../../../data/cover";
|
||||
import {
|
||||
DEFAULT_COVER_FAVORITE_POSITIONS,
|
||||
coverSupportsPosition,
|
||||
coverSupportsTiltPosition,
|
||||
coverCurrentValue,
|
||||
} from "../../../../data/cover";
|
||||
import { normalizeFavoritePositions } from "../../../../data/favorite_positions";
|
||||
import { UNAVAILABLE } from "../../../../data/entity/entity";
|
||||
@@ -37,8 +37,6 @@ import {
|
||||
import "../ha-more-info-favorites";
|
||||
import type { HaMoreInfoFavorites } from "../ha-more-info-favorites";
|
||||
|
||||
type FavoriteKind = "position" | "tilt";
|
||||
|
||||
type FavoriteLocalizeKey =
|
||||
| "set"
|
||||
| "edit"
|
||||
@@ -50,8 +48,10 @@ type FavoriteLocalizeKey =
|
||||
| "edit_title"
|
||||
| "add_title";
|
||||
|
||||
const favoriteKindFromEvent = (ev: Event): FavoriteKind =>
|
||||
(ev.currentTarget as HTMLElement).dataset.kind as FavoriteKind;
|
||||
const OPTION_KEYS = {
|
||||
position: "favorite_positions",
|
||||
tilt: "favorite_tilt_positions",
|
||||
} as const satisfies Record<CoverControlMode, keyof CoverEntityOptions>;
|
||||
|
||||
@customElement("ha-more-info-cover-favorite-positions")
|
||||
export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
@@ -76,145 +76,70 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public editMode?: boolean;
|
||||
|
||||
@state() private _favoritePositions: number[] = [];
|
||||
@property({ attribute: false }) public mode: CoverControlMode = "position";
|
||||
|
||||
@state() private _favoriteTiltPositions: number[] = [];
|
||||
@state() private _favorites: number[] = [];
|
||||
|
||||
protected updated(changedProps: PropertyValues<this>): void {
|
||||
if (
|
||||
(changedProps.has("entry") || changedProps.has("stateObj")) &&
|
||||
this.entry &&
|
||||
this.stateObj
|
||||
) {
|
||||
const options = this.entry.options?.cover;
|
||||
|
||||
this._favoritePositions = coverSupportsPosition(this.stateObj)
|
||||
? normalizeFavoritePositions(
|
||||
options?.favorite_positions ?? DEFAULT_COVER_FAVORITE_POSITIONS
|
||||
)
|
||||
: [];
|
||||
|
||||
this._favoriteTiltPositions = coverSupportsTiltPosition(this.stateObj)
|
||||
? normalizeFavoritePositions(
|
||||
options?.favorite_tilt_positions ?? DEFAULT_COVER_FAVORITE_POSITIONS
|
||||
)
|
||||
: [];
|
||||
protected willUpdate(changedProps: PropertyValues<this>): void {
|
||||
if (changedProps.has("entry") || changedProps.has("mode")) {
|
||||
this._favorites = normalizeFavoritePositions(
|
||||
this.entry?.options?.cover?.[OPTION_KEYS[this.mode]] ??
|
||||
DEFAULT_COVER_FAVORITE_POSITIONS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private _localizeFavorite(
|
||||
kind: FavoriteKind,
|
||||
key: FavoriteLocalizeKey,
|
||||
values?: Record<string, string | number>
|
||||
): string {
|
||||
return this._localize(
|
||||
`ui.dialogs.more_info_control.cover.${kind === "position" ? "favorite_position" : "favorite_tilt_position"}.${key}`,
|
||||
`ui.dialogs.more_info_control.cover.${this.mode === "position" ? "favorite_position" : "favorite_tilt_position"}.${key}`,
|
||||
values
|
||||
);
|
||||
}
|
||||
|
||||
private _getFavorites(kind: FavoriteKind): number[] {
|
||||
return kind === "position"
|
||||
? this._favoritePositions
|
||||
: this._favoriteTiltPositions;
|
||||
}
|
||||
|
||||
private _getCurrentValue(kind: FavoriteKind): number | undefined {
|
||||
const current =
|
||||
kind === "position"
|
||||
? this.stateObj.attributes.current_position
|
||||
: this.stateObj.attributes.current_tilt_position;
|
||||
|
||||
return current == null ? undefined : current;
|
||||
}
|
||||
|
||||
private async _save(options: CoverEntityOptions): Promise<void> {
|
||||
private async _setFavorites(favorites: number[]): Promise<void> {
|
||||
if (!this.entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentOptions: CoverEntityOptions = {
|
||||
...(this.entry.options?.cover ?? {}),
|
||||
};
|
||||
|
||||
if (coverSupportsPosition(this.stateObj)) {
|
||||
currentOptions.favorite_positions = this._favoritePositions;
|
||||
}
|
||||
|
||||
if (coverSupportsTiltPosition(this.stateObj)) {
|
||||
currentOptions.favorite_tilt_positions = this._favoriteTiltPositions;
|
||||
}
|
||||
|
||||
const normalized = normalizeFavoritePositions(favorites);
|
||||
this._favorites = normalized;
|
||||
const result = await updateEntityRegistryEntry(
|
||||
this._api.callWS,
|
||||
this.entry.entity_id,
|
||||
{
|
||||
options_domain: "cover",
|
||||
options: {
|
||||
...currentOptions,
|
||||
...options,
|
||||
...this.entry.options?.cover,
|
||||
[OPTION_KEYS[this.mode]]: normalized,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
fireEvent(this, "entity-entry-updated", result.entity_entry);
|
||||
}
|
||||
|
||||
private async _setFavorites(
|
||||
kind: FavoriteKind,
|
||||
favorites: number[]
|
||||
): Promise<void> {
|
||||
const normalized = normalizeFavoritePositions(favorites);
|
||||
|
||||
if (kind === "position") {
|
||||
this._favoritePositions = normalized;
|
||||
await this._save({ favorite_positions: normalized });
|
||||
return;
|
||||
}
|
||||
|
||||
this._favoriteTiltPositions = normalized;
|
||||
await this._save({ favorite_tilt_positions: normalized });
|
||||
}
|
||||
|
||||
private _move(kind: FavoriteKind, index: number, newIndex: number): void {
|
||||
const favorites = this._getFavorites(kind).concat();
|
||||
const moved = favorites.splice(index, 1)[0];
|
||||
favorites.splice(newIndex, 0, moved);
|
||||
this._setFavorites(kind, favorites);
|
||||
}
|
||||
|
||||
private _applyFavorite(kind: FavoriteKind, index: number): void {
|
||||
const favorite = this._getFavorites(kind)[index];
|
||||
|
||||
private _applyFavorite(index: number): void {
|
||||
const favorite = this._favorites[index];
|
||||
if (favorite === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (kind === "position") {
|
||||
this._api.callService("cover", "set_cover_position", {
|
||||
entity_id: this.stateObj.entity_id,
|
||||
position: favorite,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this._api.callService("cover", "set_cover_tilt_position", {
|
||||
entity_id: this.stateObj.entity_id,
|
||||
tilt_position: favorite,
|
||||
fireEvent(this, "cover-command", {
|
||||
mode: this.mode,
|
||||
action: "set",
|
||||
value: favorite,
|
||||
});
|
||||
}
|
||||
|
||||
private async _promptFavoriteValue(
|
||||
kind: FavoriteKind,
|
||||
value?: number
|
||||
): Promise<number | undefined> {
|
||||
const response = await showPromptDialog(this, {
|
||||
title: this._localizeFavorite(
|
||||
kind,
|
||||
value === undefined ? "add_title" : "edit_title"
|
||||
),
|
||||
inputLabel: this._localize(
|
||||
kind === "position"
|
||||
this.mode === "position"
|
||||
? "ui.card.cover.position"
|
||||
: "ui.card.cover.tilt_position"
|
||||
),
|
||||
@@ -235,76 +160,56 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return Math.max(0, Math.min(100, number));
|
||||
return clamp(number, 0, 100);
|
||||
}
|
||||
|
||||
private async _addFavorite(kind: FavoriteKind): Promise<void> {
|
||||
const value = await this._promptFavoriteValue(kind);
|
||||
|
||||
private async _addFavorite(): Promise<void> {
|
||||
const value = await this._promptFavoriteValue();
|
||||
if (value === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this._setFavorites(kind, [...this._getFavorites(kind), value]);
|
||||
await this._setFavorites([...this._favorites, value]);
|
||||
}
|
||||
|
||||
private async _editFavorite(
|
||||
kind: FavoriteKind,
|
||||
index: number
|
||||
): Promise<void> {
|
||||
const favorites = this._getFavorites(kind);
|
||||
const current = favorites[index];
|
||||
|
||||
private async _editFavorite(index: number): Promise<void> {
|
||||
const current = this._favorites[index];
|
||||
if (current === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const value = await this._promptFavoriteValue(kind, current);
|
||||
|
||||
const value = await this._promptFavoriteValue(current);
|
||||
if (value === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const updated = [...favorites];
|
||||
const updated = [...this._favorites];
|
||||
updated[index] = value;
|
||||
await this._setFavorites(kind, updated);
|
||||
await this._setFavorites(updated);
|
||||
}
|
||||
|
||||
private async _deleteFavorite(
|
||||
kind: FavoriteKind,
|
||||
index: number
|
||||
): Promise<void> {
|
||||
private async _deleteFavorite(index: number): Promise<void> {
|
||||
const confirmed = await showConfirmationDialog(this, {
|
||||
destructive: true,
|
||||
title: this._localizeFavorite(kind, "delete_confirm_title"),
|
||||
text: this._localizeFavorite(kind, "delete_confirm_text"),
|
||||
confirmText: this._localizeFavorite(kind, "delete_confirm_action"),
|
||||
title: this._localizeFavorite("delete_confirm_title"),
|
||||
text: this._localizeFavorite("delete_confirm_text"),
|
||||
confirmText: this._localizeFavorite("delete_confirm_action"),
|
||||
});
|
||||
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this._setFavorites(
|
||||
kind,
|
||||
this._getFavorites(kind).filter((_, itemIndex) => itemIndex !== index)
|
||||
this._favorites.filter((_, itemIndex) => itemIndex !== index)
|
||||
);
|
||||
}
|
||||
|
||||
private _renderFavoriteButton =
|
||||
(kind: FavoriteKind): HaMoreInfoFavorites["renderItem"] =>
|
||||
(favorite, _index, editMode) => {
|
||||
const currentValue = this._getCurrentValue(kind);
|
||||
const active = currentValue === favorite;
|
||||
const label = this._localizeFavorite(kind, editMode ? "edit" : "set", {
|
||||
private _favoriteButtonRenderer(): HaMoreInfoFavorites["renderItem"] {
|
||||
return (favorite, _index, editMode) => {
|
||||
const active = coverCurrentValue(this.stateObj, this.mode) === favorite;
|
||||
const label = this._localizeFavorite(editMode ? "edit" : "set", {
|
||||
value: `${favorite as number}%`,
|
||||
});
|
||||
|
||||
return html`
|
||||
<ha-control-button
|
||||
class=${classMap({
|
||||
active,
|
||||
})}
|
||||
class=${classMap({ active })}
|
||||
style=${styleMap({
|
||||
"--control-button-border-radius": "var(--ha-border-radius-pill)",
|
||||
width: "72px",
|
||||
@@ -317,20 +222,15 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
</ha-control-button>
|
||||
`;
|
||||
};
|
||||
}
|
||||
|
||||
private _deleteLabel =
|
||||
(kind: FavoriteKind): HaMoreInfoFavorites["deleteLabel"] =>
|
||||
(index) =>
|
||||
this._localizeFavorite(kind, "delete", {
|
||||
number: index + 1,
|
||||
});
|
||||
private _deleteLabel: HaMoreInfoFavorites["deleteLabel"] = (index) =>
|
||||
this._localizeFavorite("delete", { number: index + 1 });
|
||||
|
||||
private _handleFavoriteAction = (
|
||||
private _handleFavoriteAction(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-action"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
const kind = favoriteKindFromEvent(ev);
|
||||
|
||||
const { action, index } = ev.detail;
|
||||
|
||||
if (action === "hold" && this._user?.is_admin) {
|
||||
@@ -339,158 +239,87 @@ export class HaMoreInfoCoverFavoritePositions extends LitElement {
|
||||
}
|
||||
|
||||
if (this.editMode) {
|
||||
this._editFavorite(kind, index);
|
||||
this._editFavorite(index);
|
||||
return;
|
||||
}
|
||||
|
||||
this._applyFavorite(kind, index);
|
||||
};
|
||||
this._applyFavorite(index);
|
||||
}
|
||||
|
||||
private _handleFavoriteMoved = (
|
||||
private _handleFavoriteMoved(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-moved"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
const kind = favoriteKindFromEvent(ev);
|
||||
this._move(kind, ev.detail.oldIndex, ev.detail.newIndex);
|
||||
};
|
||||
const favorites = [...this._favorites];
|
||||
const [moved] = favorites.splice(ev.detail.oldIndex, 1);
|
||||
favorites.splice(ev.detail.newIndex, 0, moved);
|
||||
this._setFavorites(favorites);
|
||||
}
|
||||
|
||||
private _handleFavoriteDelete = (
|
||||
private _handleFavoriteDelete(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-delete"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
const kind = favoriteKindFromEvent(ev);
|
||||
this._deleteFavorite(kind, ev.detail.index);
|
||||
};
|
||||
this._deleteFavorite(ev.detail.index);
|
||||
}
|
||||
|
||||
private _handleFavoriteAdd = (
|
||||
private _handleFavoriteAdd(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-add"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
const kind = favoriteKindFromEvent(ev);
|
||||
this._addFavorite(kind);
|
||||
};
|
||||
this._addFavorite();
|
||||
}
|
||||
|
||||
private _handleFavoriteDone = (
|
||||
private _handleFavoriteDone(
|
||||
ev: HASSDomEvent<HASSDomEvents["favorite-item-done"]>
|
||||
): void => {
|
||||
): void {
|
||||
ev.stopPropagation();
|
||||
fireEvent(this, "toggle-edit-mode", false);
|
||||
};
|
||||
|
||||
private _renderKindSection(
|
||||
kind: FavoriteKind,
|
||||
label: string,
|
||||
favorites: number[],
|
||||
showDone: boolean,
|
||||
showLabel: boolean
|
||||
): TemplateResult | typeof nothing {
|
||||
if (!this.editMode && favorites.length === 0) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<section class="group">
|
||||
${showLabel ? html`<h4>${label}</h4>` : nothing}
|
||||
<ha-more-info-favorites
|
||||
data-kind=${kind}
|
||||
.items=${favorites}
|
||||
.renderItem=${this._renderFavoriteButton(kind)}
|
||||
.deleteLabel=${this._deleteLabel(kind)}
|
||||
.editMode=${this.editMode ?? false}
|
||||
.disabled=${this.stateObj.state === UNAVAILABLE}
|
||||
.isAdmin=${Boolean(this._user?.is_admin)}
|
||||
.showDone=${showDone}
|
||||
.addLabel=${this._localizeFavorite(kind, "add")}
|
||||
.doneLabel=${this._localize(
|
||||
"ui.dialogs.more_info_control.exit_edit_mode"
|
||||
)}
|
||||
@favorite-item-action=${this._handleFavoriteAction}
|
||||
@favorite-item-moved=${this._handleFavoriteMoved}
|
||||
@favorite-item-delete=${this._handleFavoriteDelete}
|
||||
@favorite-item-add=${this._handleFavoriteAdd}
|
||||
@favorite-item-done=${this._handleFavoriteDone}
|
||||
></ha-more-info-favorites>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
protected render(): TemplateResult | typeof nothing {
|
||||
if (!this.stateObj || !this.entry) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const supportsPosition = coverSupportsPosition(this.stateObj);
|
||||
const supportsTiltPosition = coverSupportsTiltPosition(this.stateObj);
|
||||
const showPositionSection = supportsPosition
|
||||
? this.editMode || this._favoritePositions.length > 0
|
||||
: false;
|
||||
const showTiltSection = supportsTiltPosition
|
||||
? this.editMode || this._favoriteTiltPositions.length > 0
|
||||
: false;
|
||||
const showLabels =
|
||||
[showPositionSection, showTiltSection].filter(Boolean).length > 1;
|
||||
|
||||
const showDoneOnPosition = supportsPosition && !supportsTiltPosition;
|
||||
if (!this.editMode && this._favorites.length === 0) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div class="groups">
|
||||
${
|
||||
supportsPosition
|
||||
? this._renderKindSection(
|
||||
"position",
|
||||
this._localize("ui.card.cover.position"),
|
||||
this._favoritePositions,
|
||||
showDoneOnPosition,
|
||||
showLabels
|
||||
)
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
supportsTiltPosition
|
||||
? this._renderKindSection(
|
||||
"tilt",
|
||||
this._localize("ui.card.cover.tilt_position"),
|
||||
this._favoriteTiltPositions,
|
||||
true,
|
||||
showLabels
|
||||
)
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
<ha-more-info-favorites
|
||||
.items=${this._favorites}
|
||||
.renderItem=${this._favoriteButtonRenderer()}
|
||||
.deleteLabel=${this._deleteLabel}
|
||||
.editMode=${this.editMode ?? false}
|
||||
.disabled=${this.stateObj.state === UNAVAILABLE}
|
||||
.isAdmin=${Boolean(this._user?.is_admin)}
|
||||
.showDone=${true}
|
||||
.addLabel=${this._localizeFavorite("add")}
|
||||
.doneLabel=${this._localize(
|
||||
"ui.dialogs.more_info_control.exit_edit_mode"
|
||||
)}
|
||||
@favorite-item-action=${this._handleFavoriteAction}
|
||||
@favorite-item-moved=${this._handleFavoriteMoved}
|
||||
@favorite-item-delete=${this._handleFavoriteDelete}
|
||||
@favorite-item-add=${this._handleFavoriteAdd}
|
||||
@favorite-item-done=${this._handleFavoriteDone}
|
||||
></ha-more-info-favorites>
|
||||
`;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.groups {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-3);
|
||||
}
|
||||
|
||||
.group {
|
||||
ha-more-info-favorites {
|
||||
width: 100%;
|
||||
max-width: 384px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.group ha-more-info-favorites {
|
||||
--favorite-items-max-width: 384px;
|
||||
--favorite-item-active-background-color: var(--state-cover-active-color);
|
||||
}
|
||||
|
||||
h4 {
|
||||
margin: 0 0 var(--ha-space-2);
|
||||
color: var(--secondary-text-color);
|
||||
font-size: var(--ha-font-size-s);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
text-align: center;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -167,16 +167,12 @@ export class HaMoreInfoFavorites extends LitElement {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: calc(var(--ha-space-2) * -1);
|
||||
gap: var(--ha-space-4);
|
||||
flex-wrap: wrap;
|
||||
max-width: var(--favorite-items-max-width, 250px);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.container > * {
|
||||
margin: var(--ha-space-2);
|
||||
}
|
||||
|
||||
.favorite {
|
||||
display: block;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property, state } from "lit/decorators";
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import "../../../components/ha-absolute-time";
|
||||
import "../../../components/ha-relative-time";
|
||||
@@ -19,6 +20,10 @@ export class HaMoreInfoStateHeader extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public changedOverride?: number;
|
||||
|
||||
@property({ attribute: false }) public changedTextOverride?: string;
|
||||
|
||||
@property({ attribute: false }) public stateAccent = false;
|
||||
|
||||
@state() private _absoluteTime = false;
|
||||
|
||||
@state()
|
||||
@@ -51,30 +56,41 @@ export class HaMoreInfoStateHeader extends LitElement {
|
||||
const stateDisplay = this.stateOverride ?? this._localizeState();
|
||||
|
||||
return html`
|
||||
<p class="state">${stateDisplay}</p>
|
||||
<p class=${classMap({ state: true, accent: this.stateAccent })}>
|
||||
${stateDisplay}
|
||||
</p>
|
||||
<div class="time-row">
|
||||
<p class="last-changed" @click=${this._toggleAbsolute}>
|
||||
${
|
||||
this._absoluteTime
|
||||
? html`
|
||||
<ha-absolute-time
|
||||
.datetime=${
|
||||
this.changedOverride ?? this.stateObj.last_changed
|
||||
}
|
||||
></ha-absolute-time>
|
||||
`
|
||||
: html`
|
||||
<ha-relative-time
|
||||
.datetime=${
|
||||
this.changedOverride ?? this.stateObj.last_changed
|
||||
}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
`
|
||||
}
|
||||
</p>
|
||||
${
|
||||
this.changedTextOverride
|
||||
? html`<p class="last-changed secondary" aria-hidden="true">
|
||||
${this.changedTextOverride}
|
||||
</p>`
|
||||
: html`<p class="last-changed" @click=${this._toggleAbsolute}>
|
||||
${
|
||||
this._absoluteTime
|
||||
? html`
|
||||
<ha-absolute-time
|
||||
.datetime=${
|
||||
this.changedOverride ?? this.stateObj.last_changed
|
||||
}
|
||||
></ha-absolute-time>
|
||||
`
|
||||
: html`
|
||||
<ha-relative-time
|
||||
.datetime=${
|
||||
this.changedOverride ?? this.stateObj.last_changed
|
||||
}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
`
|
||||
}
|
||||
</p>`
|
||||
}
|
||||
<slot name="after-time"></slot>
|
||||
</div>
|
||||
<span class="visually-hidden" aria-live="polite"
|
||||
>${this.changedTextOverride ?? ""}</span
|
||||
>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -113,6 +129,22 @@ export class HaMoreInfoStateHeader extends LitElement {
|
||||
user-select: none;
|
||||
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
|
||||
}
|
||||
.visually-hidden {
|
||||
position: absolute;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
height: 1px;
|
||||
width: 1px;
|
||||
margin: -1px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
.state.accent {
|
||||
color: var(--primary-color);
|
||||
}
|
||||
.last-changed.secondary {
|
||||
cursor: default;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ export class HaMoreInfoViewVacuumCleanAreasHeaderAction extends LitElement {
|
||||
if (!this.params.entityId || !this.hass.user?.is_admin) return;
|
||||
try {
|
||||
const entry = await getExtendedEntityRegistryEntry(
|
||||
this.hass,
|
||||
this.hass.callWS,
|
||||
this.params.entityId
|
||||
);
|
||||
const areaMapping = entry?.options?.vacuum?.area_mapping;
|
||||
|
||||
@@ -56,7 +56,10 @@ export class HaMoreInfoViewVacuumCleanAreas extends LitElement {
|
||||
|
||||
try {
|
||||
const entry: ExtEntityRegistryEntry =
|
||||
await getExtendedEntityRegistryEntry(this.hass, this.params.entityId);
|
||||
await getExtendedEntityRegistryEntry(
|
||||
this.hass.callWS,
|
||||
this.params.entityId
|
||||
);
|
||||
|
||||
const areaMapping = entry?.options?.vacuum?.area_mapping || {};
|
||||
const mappedAreaIds = new Set(Object.keys(areaMapping));
|
||||
|
||||
@@ -50,7 +50,7 @@ export class HaMoreInfoViewVacuumSegmentMapping extends LitElement {
|
||||
if (!this.params.entityId) return;
|
||||
|
||||
this._entry = await getExtendedEntityRegistryEntry(
|
||||
this.hass,
|
||||
this.hass.callWS,
|
||||
this.params.entityId
|
||||
);
|
||||
|
||||
|
||||
@@ -1,36 +1,46 @@
|
||||
import { mdiMenu, mdiSwapVertical } from "@mdi/js";
|
||||
import { mdiAngleAcute, mdiArrowUpDown } from "@mdi/js";
|
||||
import type { CSSResultGroup, PropertyValues } from "lit";
|
||||
import { LitElement, css, html, 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 { supportsFeature } from "../../../common/entity/supports-feature";
|
||||
import type { HASSDomEvent } from "../../../common/dom/fire_event";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import "../../../components/ha-icon-button-group";
|
||||
import "../../../components/ha-icon-button-toggle";
|
||||
import { formattersContext } from "../../../data/context";
|
||||
import {
|
||||
shouldShowFavoriteOptions,
|
||||
type ExtEntityRegistryEntry,
|
||||
} from "../../../data/entity/entity_registry";
|
||||
import type { CoverEntity } from "../../../data/cover";
|
||||
import {
|
||||
CoverEntityFeature,
|
||||
coverSupportsAnyPosition,
|
||||
coverSupportsPosition,
|
||||
coverSupportsTiltPosition,
|
||||
computeCoverPositionStateDisplay,
|
||||
import { apiContext, formattersContext } from "../../../data/context";
|
||||
import type {
|
||||
CoverCommand,
|
||||
CoverControlMode,
|
||||
CoverDrag,
|
||||
CoverEntity,
|
||||
} from "../../../data/cover";
|
||||
import "../../../state-control/cover/ha-state-control-cover-buttons";
|
||||
import "../../../state-control/cover/ha-state-control-cover-position";
|
||||
import "../../../state-control/cover/ha-state-control-cover-tilt-position";
|
||||
import "../../../state-control/cover/ha-state-control-cover-toggle";
|
||||
import type { HomeAssistantFormatters } from "../../../types";
|
||||
import {
|
||||
coverCommandData,
|
||||
coverCommandService,
|
||||
coverCurrentValue,
|
||||
coverHasPositionControls,
|
||||
coverHasTiltControls,
|
||||
coverModeAttribute,
|
||||
coverSupportsPosition,
|
||||
coverSupportsSetValue,
|
||||
defaultCoverMode,
|
||||
} from "../../../data/cover";
|
||||
import type { ExtEntityRegistryEntry } from "../../../data/entity/entity_registry";
|
||||
import { CoverRequestController } from "../../../state-control/cover/cover-request-controller";
|
||||
import "../../../state-control/cover/ha-state-control-cover";
|
||||
import type { HomeAssistantApi, HomeAssistantFormatters } from "../../../types";
|
||||
import "../components/covers/ha-more-info-cover-buttons";
|
||||
import "../components/covers/ha-more-info-cover-favorite-positions";
|
||||
import "../components/ha-more-info-state-header";
|
||||
import { moreInfoControlStyle } from "../components/more-info-control-style";
|
||||
|
||||
type Mode = "position" | "button";
|
||||
type CoverHintKey =
|
||||
| "requested"
|
||||
| "requested_open"
|
||||
| "requested_closed"
|
||||
| "currently"
|
||||
| "currently_unknown";
|
||||
|
||||
@customElement("more-info-cover")
|
||||
class MoreInfoCover extends LitElement {
|
||||
@@ -42,159 +52,176 @@ class MoreInfoCover extends LitElement {
|
||||
@consumeLocalize()
|
||||
private _localize!: LocalizeFunc;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: HomeAssistantApi;
|
||||
|
||||
@property({ attribute: false }) public stateObj?: CoverEntity;
|
||||
|
||||
@property({ attribute: false }) public entry?: ExtEntityRegistryEntry | null;
|
||||
|
||||
@property({ attribute: false }) public editMode?: boolean;
|
||||
|
||||
@state() private _mode?: Mode;
|
||||
@state() private _mode: CoverControlMode = "position";
|
||||
|
||||
private _setMode(ev) {
|
||||
this._mode = ev.currentTarget.mode;
|
||||
}
|
||||
@state() private _drag?: CoverDrag;
|
||||
|
||||
private _requests = new CoverRequestController(this);
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>): void {
|
||||
super.willUpdate(changedProps);
|
||||
if (changedProps.has("stateObj") && this.stateObj) {
|
||||
const entityId = this.stateObj.entity_id;
|
||||
const oldEntityId = changedProps.get("stateObj")?.entity_id;
|
||||
if (!this._mode || entityId !== oldEntityId) {
|
||||
this._mode = coverSupportsAnyPosition(this.stateObj)
|
||||
? "position"
|
||||
: "button";
|
||||
}
|
||||
if (!changedProps.has("stateObj") || !this.stateObj) {
|
||||
return;
|
||||
}
|
||||
if (changedProps.get("stateObj")?.entity_id !== this.stateObj.entity_id) {
|
||||
this._mode = defaultCoverMode(this.stateObj);
|
||||
this._requests.clear();
|
||||
this._drag = undefined;
|
||||
return;
|
||||
}
|
||||
this._requests.stateChanged(this.stateObj);
|
||||
}
|
||||
|
||||
private get _stateOverride() {
|
||||
const stateDisplay = this._formatters.formatEntityState(this.stateObj!);
|
||||
private _setMode(ev: Event) {
|
||||
this._mode = (ev.currentTarget as HTMLElement).dataset
|
||||
.mode as CoverControlMode;
|
||||
}
|
||||
|
||||
const positionStateDisplay = computeCoverPositionStateDisplay(
|
||||
private _handleCommand(ev: HASSDomEvent<CoverCommand>) {
|
||||
ev.stopPropagation();
|
||||
const stateObj = this.stateObj!;
|
||||
const command = ev.detail;
|
||||
this._api
|
||||
.callService(
|
||||
"cover",
|
||||
coverCommandService(command),
|
||||
coverCommandData(stateObj, command)
|
||||
)
|
||||
.catch(() => this._requests.clear());
|
||||
this._requests.commandSent(command, stateObj);
|
||||
}
|
||||
|
||||
private _handleDrag(ev: HASSDomEvent<HASSDomEvents["cover-drag-changed"]>) {
|
||||
ev.stopPropagation();
|
||||
this._drag = ev.detail.drag;
|
||||
}
|
||||
|
||||
private _formatValue(mode: CoverControlMode, value: number) {
|
||||
return this._formatters.formatEntityAttributeValue(
|
||||
this.stateObj!,
|
||||
this._formatters.formatEntityAttributeValue
|
||||
coverModeAttribute(mode),
|
||||
Math.round(value)
|
||||
);
|
||||
}
|
||||
|
||||
if (positionStateDisplay) {
|
||||
return `${stateDisplay} · ${positionStateDisplay}`;
|
||||
private _hint(key: CoverHintKey, values?: Record<string, string>) {
|
||||
return this._localize(`ui.dialogs.more_info_control.cover.${key}`, values);
|
||||
}
|
||||
|
||||
private _dragText(): string | undefined {
|
||||
const drag = this._drag;
|
||||
if (!drag) {
|
||||
return undefined;
|
||||
}
|
||||
return stateDisplay;
|
||||
if (!drag.swipe) {
|
||||
return this._formatValue(this._mode, drag.value);
|
||||
}
|
||||
if (!drag.swipe.passedHalfway) {
|
||||
return undefined;
|
||||
}
|
||||
return this._localize(
|
||||
drag.swipe.action === "close"
|
||||
? "ui.dialogs.more_info_control.cover.closes_on_release"
|
||||
: "ui.dialogs.more_info_control.cover.opens_on_release"
|
||||
);
|
||||
}
|
||||
|
||||
private _stateText(): string {
|
||||
const stateObj = this.stateObj!;
|
||||
const stateDisplay = this._formatters.formatEntityState(stateObj);
|
||||
const value = Math.round(
|
||||
stateObj.attributes[coverModeAttribute(this._mode)] ?? 0
|
||||
);
|
||||
if (value === 0) {
|
||||
return stateDisplay;
|
||||
}
|
||||
return `${stateDisplay} · ${this._formatValue(this._mode, value)}`;
|
||||
}
|
||||
|
||||
private _dragHint(): string | undefined {
|
||||
if (!this._drag || this._drag.swipe) {
|
||||
return undefined;
|
||||
}
|
||||
const current = coverCurrentValue(this.stateObj!, this._mode);
|
||||
return current === undefined
|
||||
? this._hint("currently_unknown")
|
||||
: this._hint("currently", {
|
||||
value: this._formatValue(this._mode, current),
|
||||
});
|
||||
}
|
||||
|
||||
private _requestHint(): string | undefined {
|
||||
const request = this._requests.request;
|
||||
if (!request || this._drag) {
|
||||
return undefined;
|
||||
}
|
||||
if (request.mode === "position" && !coverSupportsPosition(this.stateObj!)) {
|
||||
return this._hint(request.value ? "requested_open" : "requested_closed");
|
||||
}
|
||||
return this._hint("requested", {
|
||||
value: this._formatValue(request.mode, request.value),
|
||||
});
|
||||
}
|
||||
|
||||
private _showFavorites(stateObj: CoverEntity): boolean {
|
||||
if (!this.entry) {
|
||||
return false;
|
||||
}
|
||||
return coverSupportsSetValue(stateObj, this._mode);
|
||||
}
|
||||
|
||||
protected render() {
|
||||
if (!this.stateObj) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const supportsPosition = coverSupportsPosition(this.stateObj);
|
||||
|
||||
const supportsTiltPosition = coverSupportsTiltPosition(this.stateObj);
|
||||
|
||||
const showFavoriteControls = Boolean(
|
||||
this.entry &&
|
||||
(this.editMode ||
|
||||
(coverSupportsPosition(this.stateObj) &&
|
||||
shouldShowFavoriteOptions(
|
||||
this.entry.options?.cover?.favorite_positions
|
||||
)) ||
|
||||
(coverSupportsTiltPosition(this.stateObj) &&
|
||||
shouldShowFavoriteOptions(
|
||||
this.entry.options?.cover?.favorite_tilt_positions
|
||||
)))
|
||||
);
|
||||
|
||||
const supportsOpenClose =
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.OPEN) ||
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE) ||
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.STOP);
|
||||
|
||||
const supportsTilt =
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.OPEN_TILT) ||
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE_TILT) ||
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.STOP_TILT);
|
||||
|
||||
const supportsOpenCloseOnly =
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.OPEN) &&
|
||||
supportsFeature(this.stateObj, CoverEntityFeature.CLOSE) &&
|
||||
!supportsFeature(this.stateObj, CoverEntityFeature.STOP) &&
|
||||
!supportsTilt &&
|
||||
!supportsPosition &&
|
||||
!supportsTiltPosition;
|
||||
const stateObj = this.stateObj;
|
||||
const bothModes =
|
||||
coverHasPositionControls(stateObj) && coverHasTiltControls(stateObj);
|
||||
const dragText = this._dragText();
|
||||
|
||||
return html`
|
||||
<ha-more-info-state-header
|
||||
.stateObj=${this.stateObj}
|
||||
.stateOverride=${this._stateOverride}
|
||||
.stateObj=${stateObj}
|
||||
.stateOverride=${dragText ?? this._stateText()}
|
||||
.changedTextOverride=${this._dragHint() ?? this._requestHint()}
|
||||
.stateAccent=${dragText !== undefined}
|
||||
></ha-more-info-state-header>
|
||||
<div class="controls">
|
||||
<div
|
||||
class="controls"
|
||||
@cover-command=${this._handleCommand}
|
||||
@cover-drag-changed=${this._handleDrag}
|
||||
>
|
||||
<div class="main-control">
|
||||
<ha-state-control-cover
|
||||
.stateObj=${stateObj}
|
||||
.mode=${this._mode}
|
||||
.request=${this._requests.request}
|
||||
></ha-state-control-cover>
|
||||
${
|
||||
this._mode === "position"
|
||||
? html`
|
||||
${
|
||||
supportsPosition
|
||||
? html`
|
||||
<ha-state-control-cover-position
|
||||
.stateObj=${this.stateObj}
|
||||
></ha-state-control-cover-position>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
supportsTiltPosition
|
||||
? html`
|
||||
<ha-state-control-cover-tilt-position
|
||||
.stateObj=${this.stateObj}
|
||||
></ha-state-control-cover-tilt-position>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
${
|
||||
this._mode === "button"
|
||||
? html`
|
||||
${
|
||||
supportsOpenCloseOnly
|
||||
? html`
|
||||
<ha-state-control-cover-toggle
|
||||
.stateObj=${this.stateObj}
|
||||
></ha-state-control-cover-toggle>
|
||||
`
|
||||
: supportsOpenClose || supportsTilt
|
||||
? html`
|
||||
<ha-state-control-cover-buttons
|
||||
.stateObj=${this.stateObj}
|
||||
></ha-state-control-cover-buttons>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
${
|
||||
(supportsPosition || supportsTiltPosition) &&
|
||||
(supportsOpenClose || supportsTilt)
|
||||
bothModes
|
||||
? html`
|
||||
<ha-icon-button-group>
|
||||
<ha-icon-button-toggle
|
||||
.label=${this._localize(
|
||||
`ui.dialogs.more_info_control.cover.switch_mode.position`
|
||||
)}
|
||||
.label=${this._localize("ui.card.cover.position")}
|
||||
.selected=${this._mode === "position"}
|
||||
.path=${mdiMenu}
|
||||
.mode=${"position"}
|
||||
.path=${mdiArrowUpDown}
|
||||
data-mode="position"
|
||||
@click=${this._setMode}
|
||||
></ha-icon-button-toggle>
|
||||
<ha-icon-button-toggle
|
||||
.label=${this._localize(
|
||||
`ui.dialogs.more_info_control.cover.switch_mode.button`
|
||||
)}
|
||||
.selected=${this._mode === "button"}
|
||||
.path=${mdiSwapVertical}
|
||||
.mode=${"button"}
|
||||
.label=${this._localize("ui.card.cover.tilt_position")}
|
||||
.selected=${this._mode === "tilt"}
|
||||
.path=${mdiAngleAcute}
|
||||
data-mode="tilt"
|
||||
@click=${this._setMode}
|
||||
></ha-icon-button-toggle>
|
||||
</ha-icon-button-group>
|
||||
@@ -202,13 +229,18 @@ class MoreInfoCover extends LitElement {
|
||||
: nothing
|
||||
}
|
||||
</div>
|
||||
<ha-more-info-cover-buttons
|
||||
.stateObj=${stateObj}
|
||||
.mode=${this._mode}
|
||||
></ha-more-info-cover-buttons>
|
||||
${
|
||||
showFavoriteControls
|
||||
this._showFavorites(stateObj)
|
||||
? html`
|
||||
<ha-more-info-cover-favorite-positions
|
||||
.stateObj=${this.stateObj}
|
||||
.stateObj=${stateObj}
|
||||
.entry=${this.entry}
|
||||
.editMode=${this.editMode}
|
||||
.mode=${this._mode}
|
||||
></ha-more-info-cover-favorite-positions>
|
||||
`
|
||||
: nothing
|
||||
@@ -223,11 +255,12 @@ class MoreInfoCover extends LitElement {
|
||||
css`
|
||||
.main-control {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-4);
|
||||
}
|
||||
.main-control > * {
|
||||
margin: 0 var(--ha-space-2);
|
||||
ha-more-info-cover-buttons {
|
||||
max-width: 360px;
|
||||
}
|
||||
`,
|
||||
];
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ContextType } from "@lit/context";
|
||||
import type { HassConfig, UnsubscribeFunc } 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";
|
||||
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
|
||||
import { consume } from "../../../common/decorators/consume";
|
||||
import { BINARY_STATE_OFF } from "../../../common/const";
|
||||
@@ -13,6 +14,7 @@ import { transform } from "../../../common/decorators/transform";
|
||||
import { supportsFeature } from "../../../common/entity/supports-feature";
|
||||
import type { LocalizeFunc } from "../../../common/translations/localize";
|
||||
import { sanitizeHttpUrl } from "../../../common/url/sanitize-http-url";
|
||||
import { estimateDirection } from "../../../common/util/estimate-direction";
|
||||
import { closestWithProperty } from "../../../common/dom/ancestors-with-property";
|
||||
import "../../../components/ha-alert";
|
||||
import "../../../components/ha-button";
|
||||
@@ -31,7 +33,7 @@ import {
|
||||
} from "../../../data/context";
|
||||
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
|
||||
import type { EntityRegistryDisplayEntry } from "../../../data/entity/entity_registry";
|
||||
import type { UpdateEntity } from "../../../data/update";
|
||||
import type { UpdateEntity, UpdateReleaseNotes } from "../../../data/update";
|
||||
import {
|
||||
latestVersionIsSkipped,
|
||||
updateButtonIsDisabled,
|
||||
@@ -97,7 +99,7 @@ class MoreInfoUpdate extends LitElement {
|
||||
})
|
||||
private _user?: CurrentUser;
|
||||
|
||||
@state() private _releaseNotes?: string | null;
|
||||
@state() private _releaseNotes?: UpdateReleaseNotes;
|
||||
|
||||
@state() private _error?: string;
|
||||
|
||||
@@ -261,15 +263,41 @@ class MoreInfoUpdate extends LitElement {
|
||||
<hr />
|
||||
${this._markdownLoading ? this._renderLoader() : nothing}
|
||||
`
|
||||
: this._releaseNotes
|
||||
: this._releaseNotes.messages.length ||
|
||||
this._releaseNotes.release_notes
|
||||
? html`
|
||||
<hr />
|
||||
<ha-markdown
|
||||
@content-resize=${this._markdownLoaded}
|
||||
.content=${this._releaseNotes}
|
||||
class=${this._markdownLoading ? "hidden" : ""}
|
||||
></ha-markdown>
|
||||
${this._markdownLoading ? this._renderLoader() : nothing}
|
||||
${this._releaseNotes.messages.map(
|
||||
(message) => html`
|
||||
<ha-alert
|
||||
class="release-notes-message"
|
||||
alert-type=${message.severity}
|
||||
>
|
||||
<ha-markdown
|
||||
class=${classMap({
|
||||
rtl: estimateDirection(message.message) === "rtl",
|
||||
})}
|
||||
.content=${message.message}
|
||||
></ha-markdown>
|
||||
</ha-alert>
|
||||
`
|
||||
)}
|
||||
${
|
||||
this._releaseNotes.release_notes
|
||||
? html`
|
||||
<ha-markdown
|
||||
@content-resize=${this._markdownLoaded}
|
||||
.content=${this._releaseNotes.release_notes}
|
||||
class=${this._markdownLoading ? "hidden" : ""}
|
||||
></ha-markdown>
|
||||
${
|
||||
this._markdownLoading
|
||||
? this._renderLoader()
|
||||
: nothing
|
||||
}
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`
|
||||
: nothing
|
||||
: this.stateObj.attributes.release_summary
|
||||
@@ -393,7 +421,8 @@ class MoreInfoUpdate extends LitElement {
|
||||
try {
|
||||
this._releaseNotes = await updateReleaseNotes(
|
||||
this._api,
|
||||
this.stateObj!.entity_id
|
||||
this.stateObj!.entity_id,
|
||||
this._i18n.language
|
||||
);
|
||||
} catch (err: any) {
|
||||
this._error = err.message;
|
||||
@@ -583,6 +612,11 @@ class MoreInfoUpdate extends LitElement {
|
||||
margin-bottom: var(--ha-space-4);
|
||||
}
|
||||
|
||||
.release-notes-message {
|
||||
display: block;
|
||||
margin-bottom: var(--ha-space-4);
|
||||
}
|
||||
|
||||
.row {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
@@ -642,6 +676,12 @@ class MoreInfoUpdate extends LitElement {
|
||||
padding-bottom: var(--ha-space-4);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.release-notes-message ha-markdown {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
ha-markdown.rtl {
|
||||
direction: rtl;
|
||||
}
|
||||
ha-markdown.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@ -227,7 +227,7 @@ class MoreInfoWeather extends LitElement {
|
||||
.datetime=${this.stateObj.last_changed}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
<ha-tooltip for="relative-time">
|
||||
<ha-tooltip trigger="hover focus click" for="relative-time">
|
||||
<div class="row">
|
||||
<span class="column-name">
|
||||
${this._i18n.localize(
|
||||
|
||||
@@ -217,7 +217,7 @@ export class MoreInfoDialog extends DirtyStateProviderMixin<
|
||||
}
|
||||
try {
|
||||
this._entry = await getExtendedEntityRegistryEntry(
|
||||
this.hass,
|
||||
this.hass.callWS,
|
||||
this._entityId
|
||||
);
|
||||
} catch (_e) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { computeStateDomain } from "../../common/entity/compute_state_domain";
|
||||
import { getEntityContext } from "../../common/entity/context/get_entity_context";
|
||||
import "../../components/ha-badge";
|
||||
import type { ExtEntityRegistryEntry } from "../../data/entity/entity_registry";
|
||||
import { computeGroupMemberIds } from "../../data/group";
|
||||
import { supportsCoverPositionCardFeature } from "../../panels/lovelace/card-features/hui-cover-position-card-feature";
|
||||
import { supportsLightBrightnessCardFeature } from "../../panels/lovelace/card-features/hui-light-brightness-card-feature";
|
||||
import { supportsLightColorCardFeature } from "../../panels/lovelace/card-features/hui-light-color-card-feature";
|
||||
@@ -115,13 +116,9 @@ class MoreInfoContent extends LitElement {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const memberIds =
|
||||
(entry?.capabilities?.group_entities as string[] | undefined) ??
|
||||
(Array.isArray(stateObj.attributes.entity_id)
|
||||
? (stateObj.attributes.entity_id as string[])
|
||||
: undefined);
|
||||
|
||||
return memberIds?.filter((entityId) => !entities[entityId]?.hidden);
|
||||
return computeGroupMemberIds(stateObj, entry)?.filter(
|
||||
(entityId) => !entities[entityId]?.hidden
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -33,7 +33,11 @@ export class HuiPersistentNotificationItem extends LitElement {
|
||||
.datetime=${this.notification.created_at}
|
||||
capitalize
|
||||
></ha-relative-time>
|
||||
<ha-tooltip for="relative-time" placement="bottom">
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="relative-time"
|
||||
placement="bottom"
|
||||
>
|
||||
${this._computeTooltip(this.hass, this.notification)}
|
||||
</ha-tooltip>
|
||||
</span>
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
import { mdiAlertCircle } from "@mdi/js";
|
||||
import type { ContextType } from "@lit/context";
|
||||
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
|
||||
import { STATE_RUNNING } from "home-assistant-js-websocket";
|
||||
import type { PropertyValues } from "lit";
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
import { navigate } from "../../common/navigate";
|
||||
import "../../components/ha-alert";
|
||||
import "../../components/ha-button";
|
||||
import "../../components/ha-dialog";
|
||||
import "../../components/ha-dialog-footer";
|
||||
import "../../components/ha-domain-icon";
|
||||
import "../../components/ha-spinner";
|
||||
import "../../components/ha-svg-icon";
|
||||
import "../../components/item/ha-list-item-base";
|
||||
import "../../components/list/ha-list-base";
|
||||
import "../../components/progress/ha-progress-bar";
|
||||
import type {
|
||||
BootstrapProgress,
|
||||
StartupProgressView,
|
||||
} from "../../data/bootstrap_integrations";
|
||||
import {
|
||||
computeStartupProgress,
|
||||
subscribeBootstrapProgress,
|
||||
} from "../../data/bootstrap_integrations";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
connectionContext,
|
||||
internationalizationContext,
|
||||
} from "../../data/context";
|
||||
import type { IntegrationSetup } from "../../data/integration";
|
||||
import { domainToName, fetchIntegrationSetups } from "../../data/integration";
|
||||
import { haStyleDialog } from "../../resources/styles";
|
||||
import { DialogMixin } from "../dialog-mixin";
|
||||
|
||||
const MAX_SLOWEST = 10;
|
||||
|
||||
@customElement("dialog-startup-progress")
|
||||
class DialogStartupProgress extends DialogMixin(LitElement) {
|
||||
@state()
|
||||
@consume({ context: internationalizationContext, subscribe: true })
|
||||
private _i18n!: ContextType<typeof internationalizationContext>;
|
||||
|
||||
@consume({ context: connectionContext, subscribe: true })
|
||||
private _connection!: ContextType<typeof connectionContext>;
|
||||
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: ContextType<typeof apiContext>;
|
||||
|
||||
@state()
|
||||
@consume({ context: configContext, subscribe: true })
|
||||
private _config!: ContextType<typeof configContext>;
|
||||
|
||||
@state() private _progress?: BootstrapProgress;
|
||||
|
||||
@state() private _setups?: IntegrationSetup[];
|
||||
|
||||
private _unsubProgress?: Promise<UnsubscribeFunc>;
|
||||
|
||||
private _computeProgress = memoizeOne(computeStartupProgress);
|
||||
|
||||
connectedCallback() {
|
||||
super.connectedCallback();
|
||||
// Core sends the current progress on subscribe.
|
||||
this._unsubProgress = subscribeBootstrapProgress(
|
||||
this._connection.connection,
|
||||
(progress) => {
|
||||
this._progress = progress;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._unsubProgress?.then((unsub) => unsub());
|
||||
this._unsubProgress = undefined;
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues) {
|
||||
super.willUpdate(changedProps);
|
||||
if (
|
||||
!this._setups &&
|
||||
changedProps.has("_config") &&
|
||||
this._config.config.state === STATE_RUNNING
|
||||
) {
|
||||
this._setups = [];
|
||||
fetchIntegrationSetups(this._api.callWS).then((setups) => {
|
||||
this._setups = setups
|
||||
.filter((setup) => setup.seconds !== undefined)
|
||||
.sort((a, b) => b.seconds! - a.seconds!)
|
||||
.slice(0, MAX_SLOWEST);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
protected render() {
|
||||
const localize = this._i18n.localize;
|
||||
const progress = this._progress
|
||||
? this._computeProgress(this._progress, this._config.config.state)
|
||||
: undefined;
|
||||
const issues = progress?.failed.length ?? 0;
|
||||
return html`
|
||||
<ha-dialog open header-title=${localize("ui.startup_progress.details")}>
|
||||
${
|
||||
!progress
|
||||
? html`<ha-spinner></ha-spinner>`
|
||||
: progress.finished
|
||||
? this._renderSummary(progress.elapsed, issues)
|
||||
: this._renderLive(progress)
|
||||
}
|
||||
${progress ? this._renderFailed(progress.failed) : nothing}
|
||||
${progress?.finished ? this._renderSlowest() : nothing}
|
||||
<ha-dialog-footer slot="footer">
|
||||
${
|
||||
issues && this._config.user?.is_admin
|
||||
? html`<ha-button
|
||||
slot="secondaryAction"
|
||||
appearance="plain"
|
||||
@click=${this._openIntegrations}
|
||||
>
|
||||
${localize("ui.startup_progress.open_integrations")}
|
||||
</ha-button>`
|
||||
: nothing
|
||||
}
|
||||
<ha-button slot="primaryAction" @click=${this.closeDialog}>
|
||||
${localize("ui.common.close")}
|
||||
</ha-button>
|
||||
</ha-dialog-footer>
|
||||
</ha-dialog>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderLive(progress: StartupProgressView) {
|
||||
const localize = this._i18n.localize;
|
||||
const phase = localize(`ui.startup_progress.phase.${progress.phase}`);
|
||||
return html`
|
||||
<div class="status">
|
||||
<span class="phase">${phase}</span>
|
||||
<span class="secondary">
|
||||
${
|
||||
progress.total === null
|
||||
? localize("ui.startup_progress.integrations_unknown")
|
||||
: localize("ui.startup_progress.integrations", {
|
||||
done: progress.done,
|
||||
total: progress.total,
|
||||
})
|
||||
}
|
||||
${
|
||||
progress.elapsed
|
||||
? html` ·
|
||||
${localize("ui.startup_progress.elapsed", {
|
||||
seconds: Math.round(progress.elapsed),
|
||||
})}`
|
||||
: nothing
|
||||
}
|
||||
</span>
|
||||
<ha-progress-bar
|
||||
.value=${progress.percent ?? 0}
|
||||
.indeterminate=${progress.percent === undefined}
|
||||
.label=${phase}
|
||||
></ha-progress-bar>
|
||||
</div>
|
||||
${
|
||||
progress.active.length
|
||||
? html`
|
||||
<h3>${localize("ui.startup_progress.active")}</h3>
|
||||
<ha-list-base>
|
||||
${progress.active.map(([domain, seconds]) =>
|
||||
this._row(domain, seconds)
|
||||
)}
|
||||
</ha-list-base>
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderSummary(elapsed: number | undefined, issues: number) {
|
||||
const localize = this._i18n.localize;
|
||||
const seconds = Math.round(elapsed ?? 0);
|
||||
return html`
|
||||
<ha-alert .alertType=${issues ? "warning" : "success"}>
|
||||
${
|
||||
!elapsed
|
||||
? localize(`ui.startup_progress.phase.running`)
|
||||
: issues
|
||||
? localize("ui.startup_progress.started_with_issues", {
|
||||
seconds,
|
||||
count: issues,
|
||||
})
|
||||
: localize("ui.startup_progress.started", { seconds })
|
||||
}
|
||||
</ha-alert>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderSlowest() {
|
||||
if (!this._setups?.length) {
|
||||
return nothing;
|
||||
}
|
||||
return html`
|
||||
<h3>${this._i18n.localize("ui.startup_progress.slowest")}</h3>
|
||||
<ha-list-base>
|
||||
${this._setups.map((setup) => this._row(setup.domain, setup.seconds!))}
|
||||
</ha-list-base>
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderFailed(domains: string[]) {
|
||||
if (!domains.length) {
|
||||
return nothing;
|
||||
}
|
||||
return html`
|
||||
<h3>${this._i18n.localize("ui.startup_progress.failed")}</h3>
|
||||
<ha-list-base>
|
||||
${domains.map(
|
||||
(domain) => html`
|
||||
<ha-list-item-base>
|
||||
<ha-domain-icon
|
||||
slot="start"
|
||||
.domain=${domain}
|
||||
brand-fallback
|
||||
></ha-domain-icon>
|
||||
<span slot="headline">
|
||||
${domainToName(this._i18n.localize, domain)}
|
||||
</span>
|
||||
<ha-svg-icon slot="end" .path=${mdiAlertCircle}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
`
|
||||
)}
|
||||
</ha-list-base>
|
||||
`;
|
||||
}
|
||||
|
||||
private _row(domain: string, seconds: number) {
|
||||
return html`
|
||||
<ha-list-item-base>
|
||||
<ha-domain-icon
|
||||
slot="start"
|
||||
.domain=${domain}
|
||||
brand-fallback
|
||||
></ha-domain-icon>
|
||||
<span slot="headline">
|
||||
${domainToName(this._i18n.localize, domain)}
|
||||
</span>
|
||||
<span slot="end" class="secondary">
|
||||
${this._i18n.localize("ui.startup_progress.seconds", {
|
||||
seconds: seconds.toFixed(1),
|
||||
})}
|
||||
</span>
|
||||
</ha-list-item-base>
|
||||
`;
|
||||
}
|
||||
|
||||
private _openIntegrations() {
|
||||
navigate("/config/integrations/dashboard");
|
||||
this.closeDialog();
|
||||
}
|
||||
|
||||
static styles = [
|
||||
haStyleDialog,
|
||||
css`
|
||||
ha-spinner {
|
||||
display: block;
|
||||
margin: var(--ha-space-6) auto;
|
||||
}
|
||||
.status {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--ha-space-1);
|
||||
}
|
||||
.phase {
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
}
|
||||
.secondary {
|
||||
color: var(--secondary-text-color);
|
||||
font-size: var(--ha-font-size-s);
|
||||
}
|
||||
ha-progress-bar {
|
||||
margin-top: var(--ha-space-1);
|
||||
}
|
||||
h3 {
|
||||
margin: var(--ha-space-4) 0 0;
|
||||
font-size: var(--ha-font-size-m);
|
||||
font-weight: var(--ha-font-weight-medium);
|
||||
}
|
||||
ha-svg-icon {
|
||||
flex-shrink: 0;
|
||||
color: var(--error-color);
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"dialog-startup-progress": DialogStartupProgress;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { fireEvent } from "../../common/dom/fire_event";
|
||||
|
||||
export const showStartupProgressDialog = (element: HTMLElement): void => {
|
||||
fireEvent(element, "show-dialog", {
|
||||
dialogTag: "dialog-startup-progress",
|
||||
dialogImport: () => import("./dialog-startup-progress"),
|
||||
dialogParams: {},
|
||||
});
|
||||
};
|
||||
+45
-19
@@ -2,6 +2,7 @@ import type { Auth, Connection } from "home-assistant-js-websocket";
|
||||
import {
|
||||
createConnection,
|
||||
ERR_INVALID_AUTH,
|
||||
ERR_INVALID_AUTH_CALLBACK,
|
||||
getAuth,
|
||||
subscribeConfig,
|
||||
subscribeEntities,
|
||||
@@ -36,17 +37,30 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
const replaceUrlParams = (searchParams: URLSearchParams) => {
|
||||
const search = searchParams.toString();
|
||||
history.replaceState(
|
||||
null,
|
||||
"",
|
||||
`${location.pathname}${search ? `?${search}` : ""}`
|
||||
);
|
||||
};
|
||||
|
||||
const deleteAuthCallbackParams = (searchParams: URLSearchParams) => {
|
||||
// https://github.com/home-assistant/home-assistant-js-websocket/blob/master/lib/auth.ts
|
||||
// Remove all data from QueryCallbackData type
|
||||
searchParams.delete("auth_callback");
|
||||
searchParams.delete("code");
|
||||
searchParams.delete("state");
|
||||
searchParams.delete("storeToken");
|
||||
};
|
||||
|
||||
const clearUrlParams = () => {
|
||||
const searchParams = new URLSearchParams(location.search);
|
||||
let changed = false;
|
||||
// Clear auth data from url if we have been able to establish a connection
|
||||
if (location.search.includes("auth_callback=1")) {
|
||||
// https://github.com/home-assistant/home-assistant-js-websocket/blob/master/lib/auth.ts
|
||||
// Remove all data from QueryCallbackData type
|
||||
searchParams.delete("auth_callback");
|
||||
searchParams.delete("code");
|
||||
searchParams.delete("state");
|
||||
searchParams.delete("storeToken");
|
||||
deleteAuthCallbackParams(searchParams);
|
||||
changed = true;
|
||||
}
|
||||
// Remove the cache-busting param added by the stale-index recovery guard in
|
||||
@@ -57,12 +71,30 @@ const clearUrlParams = () => {
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
const search = searchParams.toString();
|
||||
history.replaceState(
|
||||
null,
|
||||
"",
|
||||
`${location.pathname}${search ? `?${search}` : ""}`
|
||||
);
|
||||
replaceUrlParams(searchParams);
|
||||
}
|
||||
};
|
||||
|
||||
const authOptions = {
|
||||
hassUrl,
|
||||
limitHassInstance: true,
|
||||
saveTokens,
|
||||
loadTokens: () => Promise.resolve(loadTokens()),
|
||||
};
|
||||
|
||||
const getAuthDroppingStaleCallback = async () => {
|
||||
try {
|
||||
return await getAuth(authOptions);
|
||||
} catch (err: unknown) {
|
||||
if (err !== ERR_INVALID_AUTH && err !== ERR_INVALID_AUTH_CALLBACK) {
|
||||
throw err;
|
||||
}
|
||||
// The auth callback in the URL was used or has expired. Drop it so a
|
||||
// reload does not replay it, and fall back to stored tokens or a new login.
|
||||
const searchParams = new URLSearchParams(location.search);
|
||||
deleteAuthCallbackParams(searchParams);
|
||||
replaceUrlParams(searchParams);
|
||||
return getAuth(authOptions);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -71,13 +103,7 @@ const authProm = isExternal
|
||||
import("../external_app/external_auth").then(({ createExternalAuth }) =>
|
||||
createExternalAuth(hassUrl)
|
||||
)
|
||||
: () =>
|
||||
getAuth({
|
||||
hassUrl,
|
||||
limitHassInstance: true,
|
||||
saveTokens,
|
||||
loadTokens: () => Promise.resolve(loadTokens()),
|
||||
});
|
||||
: getAuthDroppingStaleCallback;
|
||||
|
||||
const connProm = async (auth) => {
|
||||
try {
|
||||
|
||||
@@ -60,14 +60,25 @@
|
||||
/* Margins, not flex `gap` (Safari 14.1). */
|
||||
#ha-launch-screen .ha-launch-screen-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
margin: -4px 16px;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
margin: 0 16px;
|
||||
}
|
||||
#ha-launch-screen .ha-launch-screen-actions label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-top: 8px;
|
||||
padding: 8px 16px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
#ha-launch-screen .ha-launch-screen-actions input {
|
||||
margin: 0 8px 0 0;
|
||||
accent-color: #009ac7;
|
||||
}
|
||||
#ha-launch-screen .ha-launch-screen-actions button {
|
||||
margin: 4px;
|
||||
padding: 8px 16px;
|
||||
border: 1px solid transparent;
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 18px;
|
||||
background: none;
|
||||
color: #009ac7;
|
||||
@@ -76,9 +87,6 @@
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
}
|
||||
#ha-launch-screen .ha-launch-screen-actions .ha-launch-screen-continue {
|
||||
border-color: currentColor;
|
||||
}
|
||||
.ohf-logo {
|
||||
margin: 48px 0;
|
||||
display: flex;
|
||||
|
||||
@@ -116,30 +116,33 @@
|
||||
actions.className = "ha-launch-screen-actions";
|
||||
box.appendChild(actions);
|
||||
|
||||
function addButton(label, value) {
|
||||
var button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = label;
|
||||
button.addEventListener("click", function () {
|
||||
try {
|
||||
localStorage.setItem(ACCEPTED_KEY, value());
|
||||
} catch (_err) {
|
||||
// Continue this time only.
|
||||
}
|
||||
box.removeChild(actions);
|
||||
loadApp();
|
||||
});
|
||||
actions.appendChild(button);
|
||||
return button;
|
||||
}
|
||||
var always = null;
|
||||
var button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = "Continue anyway";
|
||||
button.addEventListener("click", function () {
|
||||
try {
|
||||
localStorage.setItem(
|
||||
ACCEPTED_KEY,
|
||||
always && always.checked ? "always" : String(Date.now())
|
||||
);
|
||||
} catch (_err) {
|
||||
// Continue this time only.
|
||||
}
|
||||
box.removeChild(actions);
|
||||
loadApp();
|
||||
});
|
||||
actions.appendChild(button);
|
||||
|
||||
addButton("Continue anyway", function () {
|
||||
return String(Date.now());
|
||||
}).className = "ha-launch-screen-continue";
|
||||
// From the first reminder on. A checkbox, so it is not chosen by
|
||||
// accident.
|
||||
if (acceptedAt) {
|
||||
addButton("Don't show again", function () {
|
||||
return "always";
|
||||
});
|
||||
var label = document.createElement("label");
|
||||
always = document.createElement("input");
|
||||
always.type = "checkbox";
|
||||
label.appendChild(always);
|
||||
label.appendChild(document.createTextNode("Don't show again"));
|
||||
actions.appendChild(label);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
@@ -292,7 +292,8 @@ class NotificationManager extends LitElement {
|
||||
inset-inline-end: auto;
|
||||
inset-block-end: calc(
|
||||
var(--safe-area-inset-bottom, 0px) + var(--ha-space-4) +
|
||||
var(--notification-stack-bottom-offset, 0px)
|
||||
var(--notification-stack-bottom-offset, 0px) +
|
||||
var(--ha-startup-progress-offset, 0px)
|
||||
);
|
||||
inset-inline-start: 50%;
|
||||
margin: 0;
|
||||
|
||||
@@ -16,7 +16,7 @@ import type { IngressAppInfo } from "../../data/hassio/ingress";
|
||||
import {
|
||||
createHassioSession,
|
||||
fetchIngressAppInfo,
|
||||
validateHassioSession,
|
||||
refreshHassioSession,
|
||||
} from "../../data/hassio/ingress";
|
||||
import {
|
||||
showAlertDialog,
|
||||
@@ -60,6 +60,10 @@ class HaPanelApp extends LitElement {
|
||||
|
||||
private _sessionKeepAlive?: number;
|
||||
|
||||
private _session?: { slug: string; session: string };
|
||||
|
||||
private _sessionRefresh?: Promise<void>;
|
||||
|
||||
private _fetchDataTimeout?: number;
|
||||
|
||||
private _autoRetryUntil?: number;
|
||||
@@ -92,17 +96,22 @@ class HaPanelApp extends LitElement {
|
||||
super.connectedCallback();
|
||||
window.addEventListener("message", this._handleIframeMessage);
|
||||
window.addEventListener("resize", this._handleResize);
|
||||
document.addEventListener("visibilitychange", this._handleVisibility);
|
||||
document.addEventListener("resume", this._handleVisibility);
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
window.removeEventListener("message", this._handleIframeMessage);
|
||||
window.removeEventListener("resize", this._handleResize);
|
||||
document.removeEventListener("visibilitychange", this._handleVisibility);
|
||||
document.removeEventListener("resume", this._handleVisibility);
|
||||
|
||||
if (this._sessionKeepAlive) {
|
||||
clearInterval(this._sessionKeepAlive);
|
||||
this._sessionKeepAlive = undefined;
|
||||
}
|
||||
this._session = undefined;
|
||||
if (this._fetchDataTimeout) {
|
||||
clearTimeout(this._fetchDataTimeout);
|
||||
this._fetchDataTimeout = undefined;
|
||||
@@ -342,17 +351,51 @@ class HaPanelApp extends LitElement {
|
||||
if (this._sessionKeepAlive) {
|
||||
clearInterval(this._sessionKeepAlive);
|
||||
}
|
||||
this._sessionKeepAlive = window.setInterval(async () => {
|
||||
try {
|
||||
await validateHassioSession(this.hass, session);
|
||||
} catch (_err: any) {
|
||||
session = await createHassioSession(this.hass, addonSlug);
|
||||
}
|
||||
}, 60000);
|
||||
this._session = { slug: addonSlug, session };
|
||||
this._sessionKeepAlive = window.setInterval(this._refreshSession, 60000);
|
||||
|
||||
this._addon = addon;
|
||||
}
|
||||
|
||||
// The keep-alive timer does not run while the device sleeps, so the session
|
||||
// may have expired by the time the page is visible again. Refresh it right
|
||||
// away instead of leaving the app unreachable until the next tick.
|
||||
// "resume" only fires in Chromium after a frozen page, other browsers rely
|
||||
// on "visibilitychange".
|
||||
private _handleVisibility = () => {
|
||||
if (!document.hidden) {
|
||||
this._refreshSession();
|
||||
}
|
||||
};
|
||||
|
||||
private _refreshSession = (): Promise<void> => {
|
||||
const current = this._session;
|
||||
if (!current) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
if (this._sessionRefresh) {
|
||||
return this._sessionRefresh;
|
||||
}
|
||||
this._sessionRefresh = refreshHassioSession(
|
||||
this.hass,
|
||||
current.slug,
|
||||
current.session
|
||||
)
|
||||
.then((session) => {
|
||||
// the panel may have switched to another app meanwhile
|
||||
if (this._session === current) {
|
||||
this._session = { slug: current.slug, session };
|
||||
}
|
||||
})
|
||||
.catch((_err: any) => {
|
||||
// Connection to Home Assistant is gone, the next refresh will retry
|
||||
})
|
||||
.finally(() => {
|
||||
this._sessionRefresh = undefined;
|
||||
});
|
||||
return this._sessionRefresh;
|
||||
};
|
||||
|
||||
private async _checkLoaded(ev: Event): Promise<void> {
|
||||
const iframe = ev.target as HTMLIFrameElement;
|
||||
|
||||
|
||||
Loaded 100 of 255 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user