Merge pull request #9915 from home-assistant/dev

This commit is contained in:
Bram Kragten 2021-08-30 22:35:41 +02:00 committed by GitHub
commit 49947f3337
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
254 changed files with 17771 additions and 12528 deletions

View File

@ -73,8 +73,8 @@ jobs:
matrix:
arch: ["aarch64", "armhf", "armv7", "amd64", "i386"]
tag:
- "3.8-alpine3.12"
- "3.9-alpine3.13"
- "3.9-alpine3.14"
steps:
- name: Download requirements.txt
uses: actions/download-artifact@v2

View File

@ -5,32 +5,32 @@ require("./translations");
gulp.task(
"clean",
gulp.parallel("clean-translations", function cleanOutputAndBuildDir() {
return del([paths.app_output_root, paths.build_dir]);
})
gulp.parallel("clean-translations", () =>
del([paths.app_output_root, paths.build_dir])
)
);
gulp.task(
"clean-demo",
gulp.parallel("clean-translations", function cleanOutputAndBuildDir() {
return del([paths.demo_output_root, paths.build_dir]);
})
gulp.parallel("clean-translations", () =>
del([paths.demo_output_root, paths.build_dir])
)
);
gulp.task(
"clean-cast",
gulp.parallel("clean-translations", function cleanOutputAndBuildDir() {
return del([paths.cast_output_root, paths.build_dir]);
})
gulp.parallel("clean-translations", () =>
del([paths.cast_output_root, paths.build_dir])
)
);
gulp.task("clean-hassio", function cleanOutputAndBuildDir() {
return del([paths.hassio_output_root, paths.build_dir]);
});
gulp.task("clean-hassio", () =>
del([paths.hassio_output_root, paths.build_dir])
);
gulp.task(
"clean-gallery",
gulp.parallel("clean-translations", function cleanOutputAndBuildDir() {
return del([paths.gallery_output_root, paths.build_dir]);
})
gulp.parallel("clean-translations", () =>
del([paths.gallery_output_root, paths.build_dir])
)
);

View File

@ -12,8 +12,10 @@ const polyPath = (...parts) => path.resolve(paths.polymer_dir, ...parts);
const copyFileDir = (fromFile, toDir) =>
fs.copySync(fromFile, path.join(toDir, path.basename(fromFile)));
const genStaticPath = (staticDir) => (...parts) =>
path.resolve(staticDir, ...parts);
const genStaticPath =
(staticDir) =>
(...parts) =>
path.resolve(staticDir, ...parts);
function copyTranslations(staticDir) {
const staticPath = genStaticPath(staticDir);

View File

@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const crypto = require("crypto");
const del = require("del");
const path = require("path");
@ -26,13 +28,6 @@ gulp.task("translations-enable-merge-backend", (done) => {
done();
});
String.prototype.rsplit = function (sep, maxsplit) {
var split = this.split(sep);
return maxsplit
? [split.slice(0, -maxsplit).join(sep)].concat(split.slice(-maxsplit))
: split;
};
// Panel translations which should be split from the core translations.
const TRANSLATION_FRAGMENTS = Object.keys(
require("../../src/translations/en.json").ui.panel
@ -40,7 +35,7 @@ const TRANSLATION_FRAGMENTS = Object.keys(
function recursiveFlatten(prefix, data) {
let output = {};
Object.keys(data).forEach(function (key) {
Object.keys(data).forEach((key) => {
if (typeof data[key] === "object") {
output = {
...output,
@ -101,15 +96,19 @@ function lokaliseTransform(data, original, file) {
if (value instanceof Object) {
output[key] = lokaliseTransform(value, original, file);
} else {
output[key] = value.replace(re_key_reference, (match, key) => {
const replace = key.split("::").reduce((tr, k) => {
output[key] = value.replace(re_key_reference, (_match, lokalise_key) => {
const replace = lokalise_key.split("::").reduce((tr, k) => {
if (!tr) {
throw Error(`Invalid key placeholder ${key} in ${file.path}`);
throw Error(
`Invalid key placeholder ${lokalise_key} in ${file.path}`
);
}
return tr[k];
}, original);
if (typeof replace !== "string") {
throw Error(`Invalid key placeholder ${key} in ${file.path}`);
throw Error(
`Invalid key placeholder ${lokalise_key} in ${file.path}`
);
}
return replace;
});
@ -118,9 +117,7 @@ function lokaliseTransform(data, original, file) {
return output;
}
gulp.task("clean-translations", function () {
return del([workDir]);
});
gulp.task("clean-translations", () => del([workDir]));
gulp.task("ensure-translations-build-dir", (done) => {
if (!fs.existsSync(workDir)) {
@ -129,7 +126,7 @@ gulp.task("ensure-translations-build-dir", (done) => {
done();
});
gulp.task("create-test-metadata", function (cb) {
gulp.task("create-test-metadata", (cb) => {
fs.writeFile(
workDir + "/testMetadata.json",
JSON.stringify({
@ -143,17 +140,13 @@ gulp.task("create-test-metadata", function (cb) {
gulp.task(
"create-test-translation",
gulp.series("create-test-metadata", function createTestTranslation() {
return gulp
gulp.series("create-test-metadata", () =>
gulp
.src(path.join(paths.translations_src, "en.json"))
.pipe(
transform(function (data, file) {
return recursiveEmpty(data);
})
)
.pipe(transform((data, _file) => recursiveEmpty(data)))
.pipe(rename("test.json"))
.pipe(gulp.dest(workDir));
})
.pipe(gulp.dest(workDir))
)
);
/**
@ -165,7 +158,7 @@ gulp.task(
* project is buildable immediately after merging new translation keys, since
* the Lokalise update to translations/en.json will not happen immediately.
*/
gulp.task("build-master-translation", function () {
gulp.task("build-master-translation", () => {
const src = [path.join(paths.translations_src, "en.json")];
if (mergeBackend) {
@ -174,11 +167,7 @@ gulp.task("build-master-translation", function () {
return gulp
.src(src)
.pipe(
transform(function (data, file) {
return lokaliseTransform(data, data, file);
})
)
.pipe(transform((data, file) => lokaliseTransform(data, data, file)))
.pipe(
merge({
fileName: "translationMaster.json",
@ -187,18 +176,14 @@ gulp.task("build-master-translation", function () {
.pipe(gulp.dest(workDir));
});
gulp.task("build-merged-translations", function () {
return gulp
gulp.task("build-merged-translations", () =>
gulp
.src([inFrontendDir + "/*.json", workDir + "/test.json"], {
allowEmpty: true,
})
.pipe(transform((data, file) => lokaliseTransform(data, data, file)))
.pipe(
transform(function (data, file) {
return lokaliseTransform(data, data, file);
})
)
.pipe(
foreach(function (stream, file) {
foreach((stream, file) => {
// For each language generate a merged json file. It begins with the master
// translation as a failsafe for untranslated strings, and merges all parent
// tags into one file for each specific subtag
@ -230,17 +215,17 @@ gulp.task("build-merged-translations", function () {
)
.pipe(gulp.dest(fullDir));
})
);
});
)
);
var taskName;
let taskName;
const splitTasks = [];
TRANSLATION_FRAGMENTS.forEach((fragment) => {
taskName = "build-translation-fragment-" + fragment;
gulp.task(taskName, function () {
gulp.task(taskName, () =>
// Return only the translations for this fragment.
return gulp
gulp
.src(fullDir + "/*.json")
.pipe(
transform((data) => ({
@ -251,18 +236,18 @@ TRANSLATION_FRAGMENTS.forEach((fragment) => {
},
}))
)
.pipe(gulp.dest(workDir + "/" + fragment));
});
.pipe(gulp.dest(workDir + "/" + fragment))
);
splitTasks.push(taskName);
});
taskName = "build-translation-core";
gulp.task(taskName, function () {
gulp.task(taskName, () =>
// Remove the fragment translations from the core translation.
return gulp
gulp
.src(fullDir + "/*.json")
.pipe(
transform((data, file) => {
transform((data, _file) => {
TRANSLATION_FRAGMENTS.forEach((fragment) => {
delete data.ui.panel[fragment];
});
@ -270,14 +255,14 @@ gulp.task(taskName, function () {
return data;
})
)
.pipe(gulp.dest(coreDir));
});
.pipe(gulp.dest(coreDir))
);
splitTasks.push(taskName);
gulp.task("build-flattened-translations", function () {
gulp.task("build-flattened-translations", () =>
// Flatten the split versions of our translations, and move them into outDir
return gulp
gulp
.src(
TRANSLATION_FRAGMENTS.map(
(fragment) => workDir + "/" + fragment + "/*.json"
@ -285,41 +270,45 @@ gulp.task("build-flattened-translations", function () {
{ base: workDir }
)
.pipe(
transform(function (data) {
transform((data) =>
// Polymer.AppLocalizeBehavior requires flattened json
return flatten(data);
})
flatten(data)
)
)
.pipe(
rename((filePath) => {
if (filePath.dirname === "core") {
filePath.dirname = "";
}
// In dev we create the file with the fake hash in the filename
if (!env.isProdBuild()) {
filePath.basename += "-dev";
}
})
)
.pipe(gulp.dest(outDir));
});
.pipe(gulp.dest(outDir))
);
const fingerprints = {};
gulp.task(
"build-translation-fingerprints",
function fingerprintTranslationFiles() {
// Fingerprint full file of each language
const files = fs.readdirSync(fullDir);
gulp.task("build-translation-fingerprints", () => {
// Fingerprint full file of each language
const files = fs.readdirSync(fullDir);
for (let i = 0; i < files.length; i++) {
fingerprints[files[i].split(".")[0]] = {
// In dev we create fake hashes
hash: env.isProdBuild()
? crypto
.createHash("md5")
.update(fs.readFileSync(path.join(fullDir, files[i]), "utf-8"))
.digest("hex")
: "dev",
};
}
for (let i = 0; i < files.length; i++) {
fingerprints[files[i].split(".")[0]] = {
// In dev we create fake hashes
hash: env.isProdBuild()
? crypto
.createHash("md5")
.update(fs.readFileSync(path.join(fullDir, files[i]), "utf-8"))
.digest("hex")
: "dev",
};
}
// In dev we create the file with the fake hash in the filename
if (env.isProdBuild()) {
mapFiles(outDir, ".json", (filename) => {
const parsed = path.parse(filename);
@ -335,35 +324,35 @@ gulp.task(
}`
);
});
const stream = source("translationFingerprints.json");
stream.write(JSON.stringify(fingerprints));
process.nextTick(() => stream.end());
return stream.pipe(vinylBuffer()).pipe(gulp.dest(workDir));
}
);
gulp.task("build-translation-fragment-supervisor", function () {
return gulp
const stream = source("translationFingerprints.json");
stream.write(JSON.stringify(fingerprints));
process.nextTick(() => stream.end());
return stream.pipe(vinylBuffer()).pipe(gulp.dest(workDir));
});
gulp.task("build-translation-fragment-supervisor", () =>
gulp
.src(fullDir + "/*.json")
.pipe(transform((data) => data.supervisor))
.pipe(gulp.dest(workDir + "/supervisor"));
});
.pipe(gulp.dest(workDir + "/supervisor"))
);
gulp.task("build-translation-flatten-supervisor", function () {
return gulp
gulp.task("build-translation-flatten-supervisor", () =>
gulp
.src(workDir + "/supervisor/*.json")
.pipe(
transform(function (data) {
transform((data) =>
// Polymer.AppLocalizeBehavior requires flattened json
return flatten(data);
})
flatten(data)
)
)
.pipe(gulp.dest(outDir));
});
.pipe(gulp.dest(outDir))
);
gulp.task("build-translation-write-metadata", function writeMetadata() {
return gulp
gulp.task("build-translation-write-metadata", () =>
gulp
.src(
[
path.join(paths.translations_src, "translationMetadata.json"),
@ -374,13 +363,14 @@ gulp.task("build-translation-write-metadata", function writeMetadata() {
)
.pipe(merge({}))
.pipe(
transform(function (data) {
transform((data) => {
const newData = {};
Object.entries(data).forEach(([key, value]) => {
// Filter out translations without native name.
if (value.nativeName) {
newData[key] = value;
} else {
// eslint-disable-next-line no-console
console.warn(
`Skipping language ${key}. Native name was not translated.`
);
@ -396,19 +386,26 @@ gulp.task("build-translation-write-metadata", function writeMetadata() {
}))
)
.pipe(rename("translationMetadata.json"))
.pipe(gulp.dest(workDir));
});
.pipe(gulp.dest(workDir))
);
gulp.task(
"create-translations",
gulp.series(
env.isProdBuild() ? (done) => done() : "create-test-translation",
"build-master-translation",
"build-merged-translations",
gulp.parallel(...splitTasks),
"build-flattened-translations"
)
);
gulp.task(
"build-translations",
gulp.series(
"clean-translations",
"ensure-translations-build-dir",
env.isProdBuild() ? (done) => done() : "create-test-translation",
"build-master-translation",
"build-merged-translations",
gulp.parallel(...splitTasks),
"build-flattened-translations",
"create-translations",
"build-translation-fingerprints",
"build-translation-write-metadata"
)

View File

@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-var-requires */
// Tasks to run webpack.
const fs = require("fs");
const gulp = require("gulp");
@ -44,7 +45,7 @@ const runDevServer = ({
open: true,
watchContentBase: true,
contentBase,
}).listen(port, listenHost, function (err) {
}).listen(port, listenHost, (err) => {
if (err) {
throw err;
}
@ -65,6 +66,7 @@ const doneHandler = (done) => (err, stats) => {
}
if (stats.hasErrors() || stats.hasWarnings()) {
// eslint-disable-next-line no-console
console.log(stats.toString("minimal"));
}
@ -90,16 +92,10 @@ gulp.task("webpack-watch-app", () => {
process.env.ES5
? bothBuilds(createAppConfig, { isProdBuild: false })
: createAppConfig({ isProdBuild: false, latestBuild: true })
).watch(
{
ignored: /build-translations/,
poll: isWsl,
},
doneHandler()
);
).watch({ poll: isWsl }, doneHandler());
gulp.watch(
path.join(paths.translations_src, "en.json"),
gulp.series("build-translations", "copy-translations-app")
gulp.series("create-translations", "copy-translations-app")
);
});

View File

@ -23,7 +23,6 @@ import { mockTranslations } from "./stubs/translations";
import { mockEnergy } from "./stubs/energy";
import { mockConfig } from "./stubs/config";
import { energyEntities } from "./stubs/entities";
import { mockForecastSolar } from "./stubs/forecast_solar";
class HaDemo extends HomeAssistantAppEl {
protected async _initializeHass() {
@ -52,7 +51,6 @@ class HaDemo extends HomeAssistantAppEl {
mockMediaPlayer(hass);
mockFrontend(hass);
mockEnergy(hass);
mockForecastSolar(hass);
mockConfig(hass);
mockPersistentNotification(hass);

View File

@ -1,3 +1,5 @@
import { format, startOfToday, startOfTomorrow } from "date-fns";
import { EnergySolarForecasts } from "../../../src/data/energy";
import { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export const mockEnergy = (hass: MockHomeAssistant) => {
@ -44,6 +46,19 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_energy_from: "sensor.solar_production",
config_entry_solar_forecast: ["solar_forecast"],
},
/* {
type: "battery",
stat_energy_from: "sensor.battery_output",
stat_energy_to: "sensor.battery_input",
}, */
{
type: "gas",
stat_energy_from: "sensor.energy_gas",
stat_cost: "sensor.energy_gas_cost",
entity_energy_from: "sensor.energy_gas",
entity_energy_price: null,
number_energy_price: null,
},
],
device_consumption: [
{
@ -67,4 +82,53 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
],
}));
hass.mockWS("energy/info", () => ({ cost_sensors: [] }));
const todayString = format(startOfToday(), "yyyy-MM-dd");
const tomorrowString = format(startOfTomorrow(), "yyyy-MM-dd");
hass.mockWS(
"energy/solar_forecast",
(): EnergySolarForecasts => ({
solar_forecast: {
wh_hours: {
[`${todayString}T06:00:00`]: 0,
[`${todayString}T06:23:00`]: 6,
[`${todayString}T06:45:00`]: 39,
[`${todayString}T07:00:00`]: 28,
[`${todayString}T08:00:00`]: 208,
[`${todayString}T09:00:00`]: 352,
[`${todayString}T10:00:00`]: 544,
[`${todayString}T11:00:00`]: 748,
[`${todayString}T12:00:00`]: 1259,
[`${todayString}T13:00:00`]: 1361,
[`${todayString}T14:00:00`]: 1373,
[`${todayString}T15:00:00`]: 1370,
[`${todayString}T16:00:00`]: 1186,
[`${todayString}T17:00:00`]: 937,
[`${todayString}T18:00:00`]: 652,
[`${todayString}T19:00:00`]: 370,
[`${todayString}T20:00:00`]: 155,
[`${todayString}T21:48:00`]: 24,
[`${todayString}T22:36:00`]: 0,
[`${tomorrowString}T06:01:00`]: 0,
[`${tomorrowString}T06:23:00`]: 9,
[`${tomorrowString}T06:45:00`]: 47,
[`${tomorrowString}T07:00:00`]: 48,
[`${tomorrowString}T08:00:00`]: 473,
[`${tomorrowString}T09:00:00`]: 827,
[`${tomorrowString}T10:00:00`]: 1153,
[`${tomorrowString}T11:00:00`]: 1413,
[`${tomorrowString}T12:00:00`]: 1590,
[`${tomorrowString}T13:00:00`]: 1652,
[`${tomorrowString}T14:00:00`]: 1612,
[`${tomorrowString}T15:00:00`]: 1438,
[`${tomorrowString}T16:00:00`]: 1149,
[`${tomorrowString}T17:00:00`]: 830,
[`${tomorrowString}T18:00:00`]: 542,
[`${tomorrowString}T19:00:00`]: 311,
[`${tomorrowString}T20:00:00`]: 140,
[`${tomorrowString}T21:47:00`]: 22,
[`${tomorrowString}T22:34:00`]: 0,
},
},
})
);
};

View File

@ -18,6 +18,24 @@ export const energyEntities = () =>
unit_of_measurement: "kWh",
},
},
"sensor.battery_input": {
entity_id: "sensor.battery_input",
state: "4",
attributes: {
last_reset: "1970-01-01T00:00:00:00+00",
friendly_name: "Battery Input",
unit_of_measurement: "kWh",
},
},
"sensor.battery_output": {
entity_id: "sensor.battery_output",
state: "3",
attributes: {
last_reset: "1970-01-01T00:00:00:00+00",
friendly_name: "Battery Output",
unit_of_measurement: "kWh",
},
},
"sensor.energy_consumption_tarif_1": {
entity_id: "sensor.energy_consumption_tarif_1 ",
state: "88.6",
@ -86,6 +104,23 @@ export const energyEntities = () =>
unit_of_measurement: "EUR",
},
},
"sensor.energy_gas_cost": {
entity_id: "sensor.energy_gas_cost",
state: "2",
attributes: {
last_reset: "1970-01-01T00:00:00:00+00",
unit_of_measurement: "EUR",
},
},
"sensor.energy_gas": {
entity_id: "sensor.energy_gas",
state: "4",
attributes: {
last_reset: "1970-01-01T00:00:00:00+00",
friendly_name: "Gas",
unit_of_measurement: "m³",
},
},
"sensor.energy_car": {
entity_id: "sensor.energy_car",
state: "4",

View File

@ -1,55 +0,0 @@
import { format, startOfToday, startOfTomorrow } from "date-fns";
import { ForecastSolarForecast } from "../../../src/data/forecast_solar";
import { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
export const mockForecastSolar = (hass: MockHomeAssistant) => {
const todayString = format(startOfToday(), "yyyy-MM-dd");
const tomorrowString = format(startOfTomorrow(), "yyyy-MM-dd");
hass.mockWS(
"forecast_solar/forecasts",
(): Record<string, ForecastSolarForecast> => ({
solar_forecast: {
wh_hours: {
[`${todayString}T06:00:00`]: 0,
[`${todayString}T06:23:00`]: 6,
[`${todayString}T06:45:00`]: 39,
[`${todayString}T07:00:00`]: 28,
[`${todayString}T08:00:00`]: 208,
[`${todayString}T09:00:00`]: 352,
[`${todayString}T10:00:00`]: 544,
[`${todayString}T11:00:00`]: 748,
[`${todayString}T12:00:00`]: 1259,
[`${todayString}T13:00:00`]: 1361,
[`${todayString}T14:00:00`]: 1373,
[`${todayString}T15:00:00`]: 1370,
[`${todayString}T16:00:00`]: 1186,
[`${todayString}T17:00:00`]: 937,
[`${todayString}T18:00:00`]: 652,
[`${todayString}T19:00:00`]: 370,
[`${todayString}T20:00:00`]: 155,
[`${todayString}T21:48:00`]: 24,
[`${todayString}T22:36:00`]: 0,
[`${tomorrowString}T06:01:00`]: 0,
[`${tomorrowString}T06:23:00`]: 9,
[`${tomorrowString}T06:45:00`]: 47,
[`${tomorrowString}T07:00:00`]: 48,
[`${tomorrowString}T08:00:00`]: 473,
[`${tomorrowString}T09:00:00`]: 827,
[`${tomorrowString}T10:00:00`]: 1153,
[`${tomorrowString}T11:00:00`]: 1413,
[`${tomorrowString}T12:00:00`]: 1590,
[`${tomorrowString}T13:00:00`]: 1652,
[`${tomorrowString}T14:00:00`]: 1612,
[`${tomorrowString}T15:00:00`]: 1438,
[`${tomorrowString}T16:00:00`]: 1149,
[`${tomorrowString}T17:00:00`]: 830,
[`${tomorrowString}T18:00:00`]: 542,
[`${tomorrowString}T19:00:00`]: 311,
[`${tomorrowString}T20:00:00`]: 140,
[`${tomorrowString}T21:47:00`]: 22,
[`${tomorrowString}T22:34:00`]: 0,
},
},
})
);
};

View File

@ -1,4 +1,4 @@
import { addHours, differenceInHours } from "date-fns";
import { addHours, differenceInHours, endOfDay } from "date-fns";
import { HassEntity } from "home-assistant-js-websocket";
import { StatisticValue } from "../../../src/data/history";
import { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
@ -222,6 +222,7 @@ const statisticsFunctions: Record<
"sensor.energy_production_tarif_2": (id, start, end) => {
const productionStart = new Date(start.getTime() + 9 * 60 * 60 * 1000);
const productionEnd = new Date(start.getTime() + 21 * 60 * 60 * 1000);
const dayEnd = new Date(endOfDay(productionEnd));
const production = generateCurvedStatistics(
id,
productionStart,
@ -237,15 +238,17 @@ const statisticsFunctions: Record<
const evening = generateSumStatistics(
id,
productionEnd,
end,
dayEnd,
productionFinalVal,
0
);
return [...morning, ...production, ...evening];
const rest = generateSumStatistics(id, dayEnd, end, productionFinalVal, 1);
return [...morning, ...production, ...evening, ...rest];
},
"sensor.solar_production": (id, start, end) => {
const productionStart = new Date(start.getTime() + 7 * 60 * 60 * 1000);
const productionEnd = new Date(start.getTime() + 23 * 60 * 60 * 1000);
const dayEnd = new Date(endOfDay(productionEnd));
const production = generateCurvedStatistics(
id,
productionStart,
@ -261,11 +264,12 @@ const statisticsFunctions: Record<
const evening = generateSumStatistics(
id,
productionEnd,
end,
dayEnd,
productionFinalVal,
0
);
return [...morning, ...production, ...evening];
const rest = generateSumStatistics(id, dayEnd, end, productionFinalVal, 2);
return [...morning, ...production, ...evening, ...rest];
},
"sensor.grid_fossil_fuel_percentage": (id, start, end) =>
generateMeanStatistics(id, start, end, 35, 1.3),

View File

@ -0,0 +1,150 @@
import { html, css, LitElement, TemplateResult } from "lit";
import { customElement } from "lit/decorators";
import "../../../src/components/ha-alert";
import "../../../src/components/ha-card";
const alerts: {
title?: string;
description: string | TemplateResult;
type: "info" | "warning" | "error" | "success";
dismissable?: boolean;
action?: string;
rtl?: boolean;
}[] = [
{
title: "Test info alert",
description: "This is a test info alert with a title and description",
type: "info",
},
{
title: "Test warning alert",
description: "This is a test warning alert with a title and description",
type: "warning",
},
{
title: "Test error alert",
description: "This is a test error alert with a title and description",
type: "error",
},
{
title: "Test warning with long string",
description:
"sensor.lorem_ipsum_lorem_ipsum_lorem_ipsum_lorem_ipsum_lorem_ipsum_lorem_ipsum_lorem_ipsum_lorem_ipsum_lorem_ipsum_lorem_ipsum_lorem_ipsum_lorem_ipsum",
type: "warning",
},
{
title: "Test success alert",
description: "This is a test success alert with a title and description",
type: "success",
},
{
description: "This is a test info alert with description only",
type: "info",
},
{
description:
"This is a test warning alert with a rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really rally really really long description only",
type: "warning",
},
{
title: "Error with description and list",
description: html`<p>
This is a test error alert with a title, description and a list
</p>
<ul>
<li>List item #1</li>
<li>List item #2</li>
<li>List item #3</li>
</ul>`,
type: "error",
},
{
title: "Test dismissable alert",
description: "This is a test success alert that can be dismissable",
type: "success",
dismissable: true,
},
{
description: "Dismissable information",
type: "info",
dismissable: true,
},
{
title: "Error with action",
description: "This is a test error alert with action",
type: "error",
action: "restart",
},
{
title: "Unsaved data",
description: "You have unsaved data",
type: "warning",
action: "save",
},
{
description: "Dismissable information (RTL)",
type: "info",
dismissable: true,
rtl: true,
},
{
title: "Error with action",
description: "This is a test error alert with action (RTL)",
type: "error",
action: "restart",
rtl: true,
},
{
title: "Test success alert (RTL)",
description: "This is a test success alert with a title and description",
type: "success",
rtl: true,
},
];
@customElement("demo-ha-alert")
export class DemoHaAlert extends LitElement {
protected render(): TemplateResult {
return html`
<ha-card header="ha-alert demo">
${alerts.map(
(alert) => html`
<ha-alert
.title=${alert.title || ""}
.alertType=${alert.type}
.dismissable=${alert.dismissable || false}
.actionText=${alert.action || ""}
.rtl=${alert.rtl || false}
>
${alert.description}
</ha-alert>
`
)}
</ha-card>
`;
}
static get styles() {
return css`
ha-card {
max-width: 600px;
margin: 24px auto;
}
.condition {
padding: 16px;
display: flex;
align-items: center;
justify-content: space-between;
}
span {
margin-right: 16px;
}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"demo-ha-alert": DemoHaAlert;
}
}

View File

@ -172,6 +172,14 @@ class HaGallery extends PolymerElement {
this.$.notifications.showDialog({ message: ev.detail.message })
);
this.addEventListener("alert-dismissed-clicked", () =>
this.$.notifications.showDialog({ message: "Alert dismissed clicked" })
);
this.addEventListener("alert-action-clicked", () =>
this.$.notifications.showDialog({ message: "Alert action clicked" })
);
this.addEventListener("hass-more-info", (ev) => {
if (ev.detail.entityId) {
this.$.notifications.showDialog({

View File

@ -13,6 +13,7 @@ import {
import { customElement, property, state } from "lit/decorators";
import "web-animations-js/web-animations-next-lite.min";
import "../../../../src/components/buttons/ha-progress-button";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-card";
import {
HassioAddonDetails,
@ -53,7 +54,9 @@ class HassioAddonAudio extends LitElement {
.header=${this.supervisor.localize("addon.configuration.audio.header")}
>
<div class="card-content">
${this._error ? html` <div class="errors">${this._error}</div> ` : ""}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
<paper-dropdown-menu
.label=${this.supervisor.localize(
@ -117,10 +120,6 @@ class HassioAddonAudio extends LitElement {
paper-dropdown-menu {
display: block;
}
.errors {
color: var(--error-color);
margin-bottom: 16px;
}
paper-item {
width: 450px;
}

View File

@ -17,6 +17,7 @@ import { fireEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/buttons/ha-progress-button";
import "../../../../src/components/ha-button-menu";
import "../../../../src/components/ha-card";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-form/ha-form";
import type { HaFormSchema } from "../../../../src/components/ha-form/ha-form";
import "../../../../src/components/ha-formfield";
@ -135,17 +136,19 @@ class HassioAddonConfig extends LitElement {
@value-changed=${this._configChanged}
.yamlSchema=${ADDON_YAML_SCHEMA}
></ha-yaml-editor>`}
${this._error ? html` <div class="errors">${this._error}</div> ` : ""}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
${!this._yamlMode ||
(this._canShowSchema && this.addon.schema) ||
this._valid
? ""
: html`
<div class="errors">
<ha-alert alert-type="error">
${this.supervisor.localize(
"addon.configuration.options.invalid_yaml"
)}
</div>
</ha-alert>
`}
</div>
${hasHiddenOptions
@ -324,13 +327,7 @@ class HassioAddonConfig extends LitElement {
display: flex;
justify-content: space-between;
}
.errors {
color: var(--error-color);
margin-top: 16px;
}
.syntaxerror {
color: var(--error-color);
}
.card-menu {
float: right;
z-index: 3;

View File

@ -10,6 +10,7 @@ import {
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/buttons/ha-progress-button";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-card";
import {
HassioAddonDetails,
@ -62,7 +63,9 @@ class HassioAddonNetwork extends LitElement {
)}
>
<div class="card-content">
${this._error ? html` <div class="errors">${this._error}</div> ` : ""}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
<table>
<tbody>
@ -225,10 +228,6 @@ class HassioAddonNetwork extends LitElement {
ha-card {
display: block;
}
.errors {
color: var(--error-color);
margin-bottom: 16px;
}
.card-actions {
display: flex;
justify-content: space-between;

View File

@ -1,5 +1,6 @@
import "../../../../src/components/ha-card";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-circular-progress";
import "../../../../src/components/ha-markdown";
import { customElement, property, state } from "lit/decorators";
@ -38,7 +39,9 @@ class HassioAddonDocumentationDashboard extends LitElement {
return html`
<div class="content">
<ha-card>
${this._error ? html` <div class="errors">${this._error}</div> ` : ""}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
<div class="card-content">
${this._content
? html`<ha-markdown .content=${this._content}></ha-markdown>`

View File

@ -23,6 +23,7 @@ import { fireEvent } from "../../../../src/common/dom/fire_event";
import { navigate } from "../../../../src/common/navigate";
import "../../../../src/components/buttons/ha-call-api-button";
import "../../../../src/components/buttons/ha-progress-button";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-card";
import "../../../../src/components/ha-label-badge";
import "../../../../src/components/ha-markdown";
@ -143,14 +144,14 @@ class HassioAddonInfo extends LitElement {
this.addon.arch
)
? html`
<p class="warning">
<ha-alert alert-type="warning">
${this.supervisor.localize(
"addon.dashboard.not_available_arch"
)}
</p>
</ha-alert>
`
: html`
<p class="warning">
<ha-alert alert-type="warning">
${this.supervisor.localize(
"addon.dashboard.not_available_arch",
"core_version_installed",
@ -158,7 +159,7 @@ class HassioAddonInfo extends LitElement {
"core_version_needed",
addonStoreInfo.homeassistant
)}
</p>
</ha-alert>
`
: ""}
</div>
@ -569,21 +570,23 @@ class HassioAddonInfo extends LitElement {
: ""}
</div>
</div>
${this._error ? html` <div class="errors">${this._error}</div> ` : ""}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
${!this.addon.version && addonStoreInfo && !this.addon.available
? !addonArchIsSupported(
this.supervisor.info.supported_arch,
this.addon.arch
)
? html`
<p class="warning">
<ha-alert alert-type="warning">
${this.supervisor.localize(
"addon.dashboard.not_available_arch"
)}
</p>
</ha-alert>
`
: html`
<p class="warning">
<ha-alert alert-type="warning">
${this.supervisor.localize(
"addon.dashboard.not_available_version",
"core_version_installed",
@ -591,7 +594,7 @@ class HassioAddonInfo extends LitElement {
"core_version_needed",
addonStoreInfo!.homeassistant
)}
</p>
</ha-alert>
`
: ""}
</div>
@ -987,7 +990,7 @@ class HassioAddonInfo extends LitElement {
supervisor: this.supervisor,
name: this.addon.name,
version: this.addon.version_latest,
snapshotParams: {
backupParams: {
name: `addon_${this.addon.slug}_${this.addon.version}`,
addons: [this.addon.slug],
homeassistant: false,
@ -1149,6 +1152,7 @@ class HassioAddonInfo extends LitElement {
margin-bottom: 16px;
}
img.logo {
max-width: 100%;
max-height: 60px;
margin: 16px 0;
display: block;
@ -1158,10 +1162,10 @@ class HassioAddonInfo extends LitElement {
display: flex;
}
ha-svg-icon.running {
color: var(--paper-green-400);
color: var(--success-color);
}
ha-svg-icon.stopped {
color: var(--google-red-300);
color: var(--error-color);
}
ha-call-api-button {
font-weight: 500;

View File

@ -1,6 +1,7 @@
import "@material/mwc-button";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-card";
import {
fetchHassioAddonLogs,
@ -34,7 +35,9 @@ class HassioAddonLogs extends LitElement {
return html`
<h1>${this.addon.name}</h1>
<ha-card>
${this._error ? html` <div class="errors">${this._error}</div> ` : ""}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
<div class="card-content">
${this._content
? html`<hassio-ansi-to-html
@ -60,10 +63,6 @@ class HassioAddonLogs extends LitElement {
ha-card {
display: block;
}
.errors {
color: var(--error-color);
margin-bottom: 16px;
}
`,
];
}

View File

@ -25,12 +25,12 @@ import "../../../src/components/ha-button-menu";
import "../../../src/components/ha-fab";
import { extractApiErrorMessage } from "../../../src/data/hassio/common";
import {
fetchHassioSnapshots,
fetchHassioBackups,
friendlyFolderName,
HassioSnapshot,
reloadHassioSnapshots,
removeSnapshot,
} from "../../../src/data/hassio/snapshot";
HassioBackup,
reloadHassioBackups,
removeBackup,
} from "../../../src/data/hassio/backup";
import { Supervisor } from "../../../src/data/supervisor/supervisor";
import {
showAlertDialog,
@ -40,14 +40,14 @@ import "../../../src/layouts/hass-tabs-subpage-data-table";
import type { HaTabsSubpageDataTable } from "../../../src/layouts/hass-tabs-subpage-data-table";
import { haStyle } from "../../../src/resources/styles";
import { HomeAssistant, Route } from "../../../src/types";
import { showHassioCreateSnapshotDialog } from "../dialogs/snapshot/show-dialog-hassio-create-snapshot";
import { showHassioSnapshotDialog } from "../dialogs/snapshot/show-dialog-hassio-snapshot";
import { showSnapshotUploadDialog } from "../dialogs/snapshot/show-dialog-snapshot-upload";
import { showHassioCreateBackupDialog } from "../dialogs/backup/show-dialog-hassio-create-backup";
import { showHassioBackupDialog } from "../dialogs/backup/show-dialog-hassio-backup";
import { showBackupUploadDialog } from "../dialogs/backup/show-dialog-backup-upload";
import { supervisorTabs } from "../hassio-tabs";
import { hassioStyle } from "../resources/hassio-style";
@customElement("hassio-snapshots")
export class HassioSnapshots extends LitElement {
@customElement("hassio-backups")
export class HassioBackups extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public supervisor!: Supervisor;
@ -58,9 +58,9 @@ export class HassioSnapshots extends LitElement {
@property({ type: Boolean }) public isWide!: boolean;
@state() private _selectedSnapshots: string[] = [];
@state() private _selectedBackups: string[] = [];
@state() private _snapshots?: HassioSnapshot[] = [];
@state() private _backups?: HassioBackup[] = [];
@query("hass-tabs-subpage-data-table", true)
private _dataTable!: HaTabsSubpageDataTable;
@ -75,26 +75,26 @@ export class HassioSnapshots extends LitElement {
}
public async refreshData() {
await reloadHassioSnapshots(this.hass);
await this.fetchSnapshots();
await reloadHassioBackups(this.hass);
await this.fetchBackups();
}
private _computeSnapshotContent = (snapshot: HassioSnapshot): string => {
if (snapshot.type === "full") {
return this.supervisor.localize("snapshot.full_snapshot");
private _computeBackupContent = (backup: HassioBackup): string => {
if (backup.type === "full") {
return this.supervisor.localize("backup.full_backup");
}
const content: string[] = [];
if (snapshot.content.homeassistant) {
if (backup.content.homeassistant) {
content.push("Home Assistant");
}
if (snapshot.content.folders.length !== 0) {
for (const folder of snapshot.content.folders) {
if (backup.content.folders.length !== 0) {
for (const folder of backup.content.folders) {
content.push(friendlyFolderName[folder] || folder);
}
}
if (snapshot.content.addons.length !== 0) {
for (const addon of snapshot.content.addons) {
if (backup.content.addons.length !== 0) {
for (const addon of backup.content.addons) {
content.push(
this.supervisor.supervisor.addons.find(
(entry) => entry.slug === addon
@ -117,16 +117,16 @@ export class HassioSnapshots extends LitElement {
private _columns = memoizeOne(
(narrow: boolean): DataTableColumnContainer => ({
name: {
title: this.supervisor?.localize("snapshot.name") || "",
title: this.supervisor?.localize("backup.name") || "",
sortable: true,
filterable: true,
grows: true,
template: (entry: string, snapshot: any) =>
html`${entry || snapshot.slug}
<div class="secondary">${snapshot.secondary}</div>`,
template: (entry: string, backup: any) =>
html`${entry || backup.slug}
<div class="secondary">${backup.secondary}</div>`,
},
date: {
title: this.supervisor?.localize("snapshot.created") || "",
title: this.supervisor?.localize("backup.created") || "",
width: "15%",
direction: "desc",
hidden: narrow,
@ -143,10 +143,10 @@ export class HassioSnapshots extends LitElement {
})
);
private _snapshotData = memoizeOne((snapshots: HassioSnapshot[]) =>
snapshots.map((snapshot) => ({
...snapshot,
secondary: this._computeSnapshotContent(snapshot),
private _backupData = memoizeOne((backups: HassioBackup[]) =>
backups.map((backup) => ({
...backup,
secondary: this._computeBackupContent(backup),
}))
);
@ -160,11 +160,11 @@ export class HassioSnapshots extends LitElement {
.hass=${this.hass}
.localizeFunc=${this.supervisor.localize}
.searchLabel=${this.supervisor.localize("search")}
.noDataText=${this.supervisor.localize("snapshot.no_snapshots")}
.noDataText=${this.supervisor.localize("backup.no_backups")}
.narrow=${this.narrow}
.route=${this.route}
.columns=${this._columns(this.narrow)}
.data=${this._snapshotData(this._snapshots || [])}
.data=${this._backupData(this._backups || [])}
id="slug"
@row-click=${this._handleRowClicked}
@selection-changed=${this._handleSelectionChanged}
@ -187,12 +187,12 @@ export class HassioSnapshots extends LitElement {
</mwc-list-item>
${atLeastVersion(this.hass.config.version, 0, 116)
? html`<mwc-list-item>
${this.supervisor?.localize("snapshot.upload_snapshot")}
${this.supervisor?.localize("backup.upload_backup")}
</mwc-list-item>`
: ""}
</ha-button-menu>
${this._selectedSnapshots.length
${this._selectedBackups.length
? html`<div
class=${classMap({
"header-toolbar": this.narrow,
@ -201,8 +201,8 @@ export class HassioSnapshots extends LitElement {
slot="header"
>
<p class="selected-txt">
${this.supervisor.localize("snapshot.selected", {
number: this._selectedSnapshots.length,
${this.supervisor.localize("backup.selected", {
number: this._selectedBackups.length,
})}
</p>
<div class="header-btns">
@ -212,7 +212,7 @@ export class HassioSnapshots extends LitElement {
@click=${this._deleteSelected}
class="warning"
>
${this.supervisor.localize("snapshot.delete_selected")}
${this.supervisor.localize("backup.delete_selected")}
</mwc-button>
`
: html`
@ -224,7 +224,7 @@ export class HassioSnapshots extends LitElement {
<ha-svg-icon .path=${mdiDelete}></ha-svg-icon>
</mwc-icon-button>
<paper-tooltip animation-delay="0" for="delete-btn">
${this.supervisor.localize("snapshot.delete_selected")}
${this.supervisor.localize("backup.delete_selected")}
</paper-tooltip>
`}
</div>
@ -233,8 +233,8 @@ export class HassioSnapshots extends LitElement {
<ha-fab
slot="fab"
@click=${this._createSnapshot}
.label=${this.supervisor.localize("snapshot.create_snapshot")}
@click=${this._createBackup}
.label=${this.supervisor.localize("backup.create_backup")}
extended
>
<ha-svg-icon slot="icon" .path=${mdiPlus}></ha-svg-icon>
@ -249,7 +249,7 @@ export class HassioSnapshots extends LitElement {
this.refreshData();
break;
case 1:
this._showUploadSnapshotDialog();
this._showUploadBackupDialog();
break;
}
}
@ -257,33 +257,33 @@ export class HassioSnapshots extends LitElement {
private _handleSelectionChanged(
ev: HASSDomEvent<SelectionChangedEvent>
): void {
this._selectedSnapshots = ev.detail.value;
this._selectedBackups = ev.detail.value;
}
private _showUploadSnapshotDialog() {
showSnapshotUploadDialog(this, {
showSnapshot: (slug: string) =>
showHassioSnapshotDialog(this, {
private _showUploadBackupDialog() {
showBackupUploadDialog(this, {
showBackup: (slug: string) =>
showHassioBackupDialog(this, {
slug,
supervisor: this.supervisor,
onDelete: () => this.fetchSnapshots(),
onDelete: () => this.fetchBackups(),
}),
reloadSnapshot: () => this.refreshData(),
reloadBackup: () => this.refreshData(),
});
}
private async fetchSnapshots() {
await reloadHassioSnapshots(this.hass);
this._snapshots = await fetchHassioSnapshots(this.hass);
private async fetchBackups() {
await reloadHassioBackups(this.hass);
this._backups = await fetchHassioBackups(this.hass);
}
private async _deleteSelected() {
const confirm = await showConfirmationDialog(this, {
title: this.supervisor.localize("snapshot.delete_snapshot_title"),
text: this.supervisor.localize("snapshot.delete_snapshot_text", {
number: this._selectedSnapshots.length,
title: this.supervisor.localize("backup.delete_backup_title"),
text: this.supervisor.localize("backup.delete_backup_text", {
number: this._selectedBackups.length,
}),
confirmText: this.supervisor.localize("snapshot.delete_snapshot_confirm"),
confirmText: this.supervisor.localize("backup.delete_backup_confirm"),
});
if (!confirm) {
@ -292,44 +292,44 @@ export class HassioSnapshots extends LitElement {
try {
await Promise.all(
this._selectedSnapshots.map((slug) => removeSnapshot(this.hass, slug))
this._selectedBackups.map((slug) => removeBackup(this.hass, slug))
);
} catch (err) {
showAlertDialog(this, {
title: this.supervisor.localize("snapshot.failed_to_delete"),
title: this.supervisor.localize("backup.failed_to_delete"),
text: extractApiErrorMessage(err),
});
return;
}
await reloadHassioSnapshots(this.hass);
this._snapshots = await fetchHassioSnapshots(this.hass);
await reloadHassioBackups(this.hass);
this._backups = await fetchHassioBackups(this.hass);
this._dataTable.clearSelection();
}
private _handleRowClicked(ev: HASSDomEvent<RowClickedEvent>) {
const slug = ev.detail.id;
showHassioSnapshotDialog(this, {
showHassioBackupDialog(this, {
slug,
supervisor: this.supervisor,
onDelete: () => this.fetchSnapshots(),
onDelete: () => this.fetchBackups(),
});
}
private _createSnapshot() {
private _createBackup() {
if (this.supervisor!.info.state !== "running") {
showAlertDialog(this, {
title: this.supervisor!.localize("snapshot.could_not_create"),
title: this.supervisor!.localize("backup.could_not_create"),
text: this.supervisor!.localize(
"snapshot.create_blocked_not_running",
"backup.create_blocked_not_running",
"state",
this.supervisor!.info.state
),
});
return;
}
showHassioCreateSnapshotDialog(this, {
showHassioCreateBackupDialog(this, {
supervisor: this.supervisor!,
onCreate: () => this.fetchSnapshots(),
onCreate: () => this.fetchBackups(),
});
}
@ -378,6 +378,6 @@ export class HassioSnapshots extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"hassio-snapshots": HassioSnapshots;
"hassio-backups": HassioBackups;
}
}

View File

@ -41,16 +41,16 @@ class HassioAnsiToHtml extends LitElement {
text-decoration: underline line-through;
}
.fg-red {
color: rgb(222, 56, 43);
color: var(--error-color);
}
.fg-green {
color: rgb(57, 181, 74);
color: var(--success-color);
}
.fg-yellow {
color: rgb(255, 199, 6);
color: var(--warning-color);
}
.fg-blue {
color: rgb(0, 111, 184);
color: var(--info-color);
}
.fg-magenta {
color: rgb(118, 38, 113);
@ -65,16 +65,16 @@ class HassioAnsiToHtml extends LitElement {
background-color: rgb(0, 0, 0);
}
.bg-red {
background-color: rgb(222, 56, 43);
background-color: var(--error-color);
}
.bg-green {
background-color: rgb(57, 181, 74);
background-color: var(--success-color);
}
.bg-yellow {
background-color: rgb(255, 199, 6);
background-color: var(--warning-color);
}
.bg-blue {
background-color: rgb(0, 111, 184);
background-color: var(--info-color);
}
.bg-magenta {
background-color: rgb(118, 38, 113);

View File

@ -80,14 +80,14 @@ class HassioCardContent extends LitElement {
color: var(--secondary-text-color);
}
ha-svg-icon.update {
color: var(--paper-orange-400);
color: var(--warning-color);
}
ha-svg-icon.running,
ha-svg-icon.installed {
color: var(--paper-green-400);
color: var(--success-color);
}
ha-svg-icon.hassupdate,
ha-svg-icon.snapshot {
ha-svg-icon.backup {
color: var(--paper-item-icon-color);
}
ha-svg-icon.not_available {
@ -122,7 +122,7 @@ class HassioCardContent extends LitElement {
}
.dot {
position: absolute;
background-color: var(--paper-orange-400);
background-color: var(--warning-color);
width: 12px;
height: 12px;
top: 8px;

View File

@ -8,23 +8,20 @@ import "../../../src/components/ha-circular-progress";
import "../../../src/components/ha-file-upload";
import "../../../src/components/ha-svg-icon";
import { extractApiErrorMessage } from "../../../src/data/hassio/common";
import {
HassioSnapshot,
uploadSnapshot,
} from "../../../src/data/hassio/snapshot";
import { HassioBackup, uploadBackup } from "../../../src/data/hassio/backup";
import { showAlertDialog } from "../../../src/dialogs/generic/show-dialog-box";
import { HomeAssistant } from "../../../src/types";
declare global {
interface HASSDomEvents {
"snapshot-uploaded": { snapshot: HassioSnapshot };
"backup-uploaded": { backup: HassioBackup };
}
}
const MAX_FILE_SIZE = 1 * 1024 * 1024 * 1024; // 1GB
@customElement("hassio-upload-snapshot")
export class HassioUploadSnapshot extends LitElement {
@customElement("hassio-upload-backup")
export class HassioUploadBackup extends LitElement {
public hass!: HomeAssistant;
@state() public value: string | null = null;
@ -37,7 +34,7 @@ export class HassioUploadSnapshot extends LitElement {
.uploading=${this._uploading}
.icon=${mdiFolderUpload}
accept="application/x-tar"
label="Upload snapshot"
label="Upload backup"
@file-picked=${this._uploadFile}
auto-open-file-dialog
></ha-file-upload>
@ -49,10 +46,10 @@ export class HassioUploadSnapshot extends LitElement {
if (file.size > MAX_FILE_SIZE) {
showAlertDialog(this, {
title: "Snapshot file is too big",
title: "Backup file is too big",
text: html`The maximum allowed filesize is 1GB.<br />
<a
href="https://www.home-assistant.io/hassio/haos_common_tasks/#restoring-a-snapshot-on-a-new-install"
href="https://www.home-assistant.io/hassio/haos_common_tasks/#restoring-a-backup-on-a-new-install"
target="_blank"
>Have a look here on how to restore it.</a
>`,
@ -64,15 +61,15 @@ export class HassioUploadSnapshot extends LitElement {
if (!["application/x-tar"].includes(file.type)) {
showAlertDialog(this, {
title: "Unsupported file format",
text: "Please choose a Home Assistant snapshot file (.tar)",
text: "Please choose a Home Assistant backup file (.tar)",
confirmText: "ok",
});
return;
}
this._uploading = true;
try {
const snapshot = await uploadSnapshot(this.hass, file);
fireEvent(this, "snapshot-uploaded", { snapshot: snapshot.data });
const backup = await uploadBackup(this.hass, file);
fireEvent(this, "backup-uploaded", { backup: backup.data });
} catch (err) {
showAlertDialog(this, {
title: "Upload failed",
@ -87,6 +84,6 @@ export class HassioUploadSnapshot extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"hassio-upload-snapshot": HassioUploadSnapshot;
"hassio-upload-backup": HassioUploadBackup;
}
}

View File

@ -11,10 +11,10 @@ import "../../../src/components/ha-formfield";
import "../../../src/components/ha-radio";
import type { HaRadio } from "../../../src/components/ha-radio";
import {
HassioFullSnapshotCreateParams,
HassioPartialSnapshotCreateParams,
HassioSnapshotDetail,
} from "../../../src/data/hassio/snapshot";
HassioFullBackupCreateParams,
HassioPartialBackupCreateParams,
HassioBackupDetail,
} from "../../../src/data/hassio/backup";
import { Supervisor } from "../../../src/data/supervisor/supervisor";
import { PolymerChangedEvent } from "../../../src/polymer-types";
import { HomeAssistant } from "../../../src/types";
@ -64,17 +64,17 @@ const _computeAddons = (addons): AddonCheckboxItem[] =>
}))
.sort((a, b) => (a.name > b.name ? 1 : -1));
@customElement("supervisor-snapshot-content")
export class SupervisorSnapshotContent extends LitElement {
@customElement("supervisor-backup-content")
export class SupervisorBackupContent extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property() public localize?: LocalizeFunc;
@property({ attribute: false }) public supervisor?: Supervisor;
@property({ attribute: false }) public snapshot?: HassioSnapshotDetail;
@property({ attribute: false }) public backup?: HassioBackupDetail;
@property() public snapshotType: HassioSnapshotDetail["type"] = "full";
@property() public backupType: HassioBackupDetail["type"] = "full";
@property({ attribute: false }) public folders?: CheckboxItem[];
@ -82,37 +82,35 @@ export class SupervisorSnapshotContent extends LitElement {
@property({ type: Boolean }) public homeAssistant = false;
@property({ type: Boolean }) public snapshotHasPassword = false;
@property({ type: Boolean }) public backupHasPassword = false;
@property({ type: Boolean }) public onboarding = false;
@property() public snapshotName = "";
@property() public backupName = "";
@property() public snapshotPassword = "";
@property() public backupPassword = "";
@property() public confirmSnapshotPassword = "";
@property() public confirmBackupPassword = "";
public willUpdate(changedProps) {
super.willUpdate(changedProps);
if (!this.hasUpdated) {
this.folders = _computeFolders(
this.snapshot
? this.snapshot.folders
this.backup
? this.backup.folders
: ["homeassistant", "ssl", "share", "media", "addons/local"]
);
this.addons = _computeAddons(
this.snapshot
? this.snapshot.addons
: this.supervisor?.supervisor.addons
this.backup ? this.backup.addons : this.supervisor?.supervisor.addons
);
this.snapshotType = this.snapshot?.type || "full";
this.snapshotName = this.snapshot?.name || "";
this.snapshotHasPassword = this.snapshot?.protected || false;
this.backupType = this.backup?.type || "full";
this.backupName = this.backup?.name || "";
this.backupHasPassword = this.backup?.protected || false;
}
}
private _localize = (string: string) =>
this.supervisor?.localize(`snapshot.${string}`) ||
this.supervisor?.localize(`backup.${string}`) ||
this.localize!(`ui.panel.page-onboarding.restore.${string}`);
protected render(): TemplateResult {
@ -120,64 +118,64 @@ export class SupervisorSnapshotContent extends LitElement {
return html``;
}
const foldersSection =
this.snapshotType === "partial" ? this._getSection("folders") : undefined;
this.backupType === "partial" ? this._getSection("folders") : undefined;
const addonsSection =
this.snapshotType === "partial" ? this._getSection("addons") : undefined;
this.backupType === "partial" ? this._getSection("addons") : undefined;
return html`
${this.snapshot
${this.backup
? html`<div class="details">
${this.snapshot.type === "full"
? this._localize("full_snapshot")
: this._localize("partial_snapshot")}
(${Math.ceil(this.snapshot.size * 10) / 10 + " MB"})<br />
${this.backup.type === "full"
? this._localize("full_backup")
: this._localize("partial_backup")}
(${Math.ceil(this.backup.size * 10) / 10 + " MB"})<br />
${this.hass
? formatDateTime(new Date(this.snapshot.date), this.hass.locale)
: this.snapshot.date}
? formatDateTime(new Date(this.backup.date), this.hass.locale)
: this.backup.date}
</div>`
: html`<paper-input
name="snapshotName"
.label=${this.supervisor?.localize("snapshot.name") || "Name"}
.value=${this.snapshotName}
name="backupName"
.label=${this._localize("name")}
.value=${this.backupName}
@value-changed=${this._handleTextValueChanged}
>
</paper-input>`}
${!this.snapshot || this.snapshot.type === "full"
${!this.backup || this.backup.type === "full"
? html`<div class="sub-header">
${!this.snapshot
${!this.backup
? this._localize("type")
: this._localize("select_type")}
</div>
<div class="snapshot-types">
<ha-formfield .label=${this._localize("full_snapshot")}>
<div class="backup-types">
<ha-formfield .label=${this._localize("full_backup")}>
<ha-radio
@change=${this._handleRadioValueChanged}
value="full"
name="snapshotType"
.checked=${this.snapshotType === "full"}
name="backupType"
.checked=${this.backupType === "full"}
>
</ha-radio>
</ha-formfield>
<ha-formfield .label=${this._localize("partial_snapshot")}>
<ha-formfield .label=${this._localize("partial_backup")}>
<ha-radio
@change=${this._handleRadioValueChanged}
value="partial"
name="snapshotType"
.checked=${this.snapshotType === "partial"}
name="backupType"
.checked=${this.backupType === "partial"}
>
</ha-radio>
</ha-formfield>
</div>`
: ""}
${this.snapshotType === "partial"
${this.backupType === "partial"
? html`<div class="partial-picker">
${this.snapshot && this.snapshot.homeassistant
${this.backup && this.backup.homeassistant
? html`
<ha-formfield
.label=${html`<supervisor-formfield-label
label="Home Assistant"
.iconPath=${mdiHomeAssistant}
.version=${this.snapshot.homeassistant}
.version=${this.backup.homeassistant}
>
</supervisor-formfield-label>`}
>
@ -233,38 +231,38 @@ export class SupervisorSnapshotContent extends LitElement {
: ""}
</div> `
: ""}
${this.snapshotType === "partial" &&
(!this.snapshot || this.snapshotHasPassword)
${this.backupType === "partial" &&
(!this.backup || this.backupHasPassword)
? html`<hr />`
: ""}
${!this.snapshot
${!this.backup
? html`<ha-formfield
class="password"
.label=${this._localize("password_protection")}
>
<ha-checkbox
.checked=${this.snapshotHasPassword}
.checked=${this.backupHasPassword}
@change=${this._toggleHasPassword}
>
</ha-checkbox>
</ha-formfield>`
: ""}
${this.snapshotHasPassword
${this.backupHasPassword
? html`
<paper-input
.label=${this._localize("password")}
type="password"
name="snapshotPassword"
.value=${this.snapshotPassword}
name="backupPassword"
.value=${this.backupPassword}
@value-changed=${this._handleTextValueChanged}
>
</paper-input>
${!this.snapshot
${!this.backup
? html` <paper-input
.label=${this.supervisor?.localize("confirm_password")}
.label=${this._localize("confirm_password")}
type="password"
name="confirmSnapshotPassword"
.value=${this.confirmSnapshotPassword}
name="confirmBackupPassword"
.value=${this.confirmBackupPassword}
@value-changed=${this._handleTextValueChanged}
>
</paper-input>`
@ -307,7 +305,7 @@ export class SupervisorSnapshotContent extends LitElement {
display: block;
margin: 0 -14px -16px;
}
.snapshot-types {
.backup-types {
display: flex;
margin-left: -13px;
}
@ -317,23 +315,23 @@ export class SupervisorSnapshotContent extends LitElement {
`;
}
public snapshotDetails():
| HassioPartialSnapshotCreateParams
| HassioFullSnapshotCreateParams {
public backupDetails():
| HassioPartialBackupCreateParams
| HassioFullBackupCreateParams {
const data: any = {};
if (!this.snapshot) {
data.name = this.snapshotName || formatDate(new Date(), this.hass.locale);
if (!this.backup) {
data.name = this.backupName || formatDate(new Date(), this.hass.locale);
}
if (this.snapshotHasPassword) {
data.password = this.snapshotPassword;
if (!this.snapshot) {
data.confirm_password = this.confirmSnapshotPassword;
if (this.backupHasPassword) {
data.password = this.backupPassword;
if (!this.backup) {
data.confirm_password = this.confirmBackupPassword;
}
}
if (this.snapshotType === "full") {
if (this.backupType === "full") {
return data;
}
@ -415,7 +413,7 @@ export class SupervisorSnapshotContent extends LitElement {
}
private _toggleHasPassword(): void {
this.snapshotHasPassword = !this.snapshotHasPassword;
this.backupHasPassword = !this.backupHasPassword;
}
private _toggleSection(ev): void {
@ -445,6 +443,6 @@ export class SupervisorSnapshotContent extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"supervisor-snapshot-content": SupervisorSnapshotContent;
"supervisor-backup-content": SupervisorBackupContent;
}
}

View File

@ -162,7 +162,7 @@ export class HassioUpdate extends LitElement {
supervisor: this.supervisor,
name: "Home Assistant Core",
version: this.supervisor.core.version_latest,
snapshotParams: {
backupParams: {
name: `core_${this.supervisor.core.version}`,
folders: ["homeassistant"],
homeassistant: true,

View File

@ -6,20 +6,20 @@ import "../../../../src/components/ha-header-bar";
import { HassDialog } from "../../../../src/dialogs/make-dialog-manager";
import { haStyleDialog } from "../../../../src/resources/styles";
import type { HomeAssistant } from "../../../../src/types";
import "../../components/hassio-upload-snapshot";
import { HassioSnapshotUploadDialogParams } from "./show-dialog-snapshot-upload";
import "../../components/hassio-upload-backup";
import { HassioBackupUploadDialogParams } from "./show-dialog-backup-upload";
@customElement("dialog-hassio-snapshot-upload")
export class DialogHassioSnapshotUpload
@customElement("dialog-hassio-backup-upload")
export class DialogHassioBackupUpload
extends LitElement
implements HassDialog<HassioSnapshotUploadDialogParams>
implements HassDialog<HassioBackupUploadDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _params?: HassioSnapshotUploadDialogParams;
@state() private _params?: HassioBackupUploadDialogParams;
public async showDialog(
params: HassioSnapshotUploadDialogParams
params: HassioBackupUploadDialogParams
): Promise<void> {
this._params = params;
await this.updateComplete;
@ -27,8 +27,8 @@ export class DialogHassioSnapshotUpload
public closeDialog(): void {
if (this._params && !this._params.onboarding) {
if (this._params.reloadSnapshot) {
this._params.reloadSnapshot();
if (this._params.reloadBackup) {
this._params.reloadBackup();
}
}
this._params = undefined;
@ -51,23 +51,23 @@ export class DialogHassioSnapshotUpload
>
<div slot="heading">
<ha-header-bar>
<span slot="title"> Upload snapshot </span>
<span slot="title"> Upload backup </span>
<mwc-icon-button slot="actionItems" dialogAction="cancel">
<ha-svg-icon .path=${mdiClose}></ha-svg-icon>
</mwc-icon-button>
</ha-header-bar>
</div>
<hassio-upload-snapshot
@snapshot-uploaded=${this._snapshotUploaded}
<hassio-upload-backup
@backup-uploaded=${this._backupUploaded}
.hass=${this.hass}
></hassio-upload-snapshot>
></hassio-upload-backup>
</ha-dialog>
`;
}
private _snapshotUploaded(ev) {
const snapshot = ev.detail.snapshot;
this._params?.showSnapshot(snapshot.slug);
private _backupUploaded(ev) {
const backup = ev.detail.backup;
this._params?.showBackup(backup.slug);
this.closeDialog();
}
@ -94,6 +94,6 @@ export class DialogHassioSnapshotUpload
declare global {
interface HTMLElementTagNameMap {
"dialog-hassio-snapshot-upload": DialogHassioSnapshotUpload;
"dialog-hassio-backup-upload": DialogHassioBackupUpload;
}
}

View File

@ -6,15 +6,16 @@ import { customElement, property, query, state } from "lit/decorators";
import { fireEvent } from "../../../../src/common/dom/fire_event";
import { slugify } from "../../../../src/common/string/slugify";
import "../../../../src/components/buttons/ha-progress-button";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-button-menu";
import "../../../../src/components/ha-header-bar";
import "../../../../src/components/ha-svg-icon";
import { getSignedPath } from "../../../../src/data/auth";
import { extractApiErrorMessage } from "../../../../src/data/hassio/common";
import {
fetchHassioSnapshotInfo,
HassioSnapshotDetail,
} from "../../../../src/data/hassio/snapshot";
fetchHassioBackupInfo,
HassioBackupDetail,
} from "../../../../src/data/hassio/backup";
import {
showAlertDialog,
showConfirmationDialog,
@ -23,44 +24,45 @@ import { HassDialog } from "../../../../src/dialogs/make-dialog-manager";
import { haStyle, haStyleDialog } from "../../../../src/resources/styles";
import { HomeAssistant } from "../../../../src/types";
import { fileDownload } from "../../../../src/util/file_download";
import "../../components/supervisor-snapshot-content";
import type { SupervisorSnapshotContent } from "../../components/supervisor-snapshot-content";
import { HassioSnapshotDialogParams } from "./show-dialog-hassio-snapshot";
import "../../components/supervisor-backup-content";
import type { SupervisorBackupContent } from "../../components/supervisor-backup-content";
import { HassioBackupDialogParams } from "./show-dialog-hassio-backup";
import { atLeastVersion } from "../../../../src/common/config/version";
@customElement("dialog-hassio-snapshot")
class HassioSnapshotDialog
@customElement("dialog-hassio-backup")
class HassioBackupDialog
extends LitElement
implements HassDialog<HassioSnapshotDialogParams>
implements HassDialog<HassioBackupDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _error?: string;
@state() private _snapshot?: HassioSnapshotDetail;
@state() private _backup?: HassioBackupDetail;
@state() private _dialogParams?: HassioSnapshotDialogParams;
@state() private _dialogParams?: HassioBackupDialogParams;
@state() private _restoringSnapshot = false;
@state() private _restoringBackup = false;
@query("supervisor-snapshot-content")
private _snapshotContent!: SupervisorSnapshotContent;
@query("supervisor-backup-content")
private _backupContent!: SupervisorBackupContent;
public async showDialog(params: HassioSnapshotDialogParams) {
this._snapshot = await fetchHassioSnapshotInfo(this.hass, params.slug);
public async showDialog(params: HassioBackupDialogParams) {
this._backup = await fetchHassioBackupInfo(this.hass, params.slug);
this._dialogParams = params;
this._restoringSnapshot = false;
this._restoringBackup = false;
}
public closeDialog() {
this._snapshot = undefined;
this._backup = undefined;
this._dialogParams = undefined;
this._restoringSnapshot = false;
this._restoringBackup = false;
this._error = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
protected render(): TemplateResult {
if (!this._dialogParams || !this._snapshot) {
if (!this._dialogParams || !this._backup) {
return html``;
}
return html`
@ -72,26 +74,28 @@ class HassioSnapshotDialog
>
<div slot="heading">
<ha-header-bar>
<span slot="title">${this._snapshot.name}</span>
<span slot="title">${this._backup.name}</span>
<mwc-icon-button slot="actionItems" dialogAction="cancel">
<ha-svg-icon .path=${mdiClose}></ha-svg-icon>
</mwc-icon-button>
</ha-header-bar>
</div>
${this._restoringSnapshot
${this._restoringBackup
? html` <ha-circular-progress active></ha-circular-progress>`
: html`<supervisor-snapshot-content
: html`<supervisor-backup-content
.hass=${this.hass}
.supervisor=${this._dialogParams.supervisor}
.snapshot=${this._snapshot}
.backup=${this._backup}
.onboarding=${this._dialogParams.onboarding || false}
.localize=${this._dialogParams.localize}
>
</supervisor-snapshot-content>`}
${this._error ? html`<p class="error">Error: ${this._error}</p>` : ""}
</supervisor-backup-content>`}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
<mwc-button
.disabled=${this._restoringSnapshot}
.disabled=${this._restoringBackup}
slot="secondaryAction"
@click=${this._restoreClicked}
>
@ -108,8 +112,8 @@ class HassioSnapshotDialog
<mwc-icon-button slot="trigger" alt="menu">
<ha-svg-icon .path=${mdiDotsVertical}></ha-svg-icon>
</mwc-icon-button>
<mwc-list-item>Download Snapshot</mwc-list-item>
<mwc-list-item class="error">Delete Snapshot</mwc-list-item>
<mwc-list-item>Download Backup</mwc-list-item>
<mwc-list-item class="error">Delete Backup</mwc-list-item>
</ha-button-menu>`
: ""}
</ha-dialog>
@ -150,30 +154,30 @@ class HassioSnapshotDialog
}
private async _restoreClicked() {
const snapshotDetails = this._snapshotContent.snapshotDetails();
this._restoringSnapshot = true;
if (this._snapshotContent.snapshotType === "full") {
await this._fullRestoreClicked(snapshotDetails);
const backupDetails = this._backupContent.backupDetails();
this._restoringBackup = true;
if (this._backupContent.backupType === "full") {
await this._fullRestoreClicked(backupDetails);
} else {
await this._partialRestoreClicked(snapshotDetails);
await this._partialRestoreClicked(backupDetails);
}
this._restoringSnapshot = false;
this._restoringBackup = false;
}
private async _partialRestoreClicked(snapshotDetails) {
private async _partialRestoreClicked(backupDetails) {
if (
this._dialogParams?.supervisor !== undefined &&
this._dialogParams?.supervisor.info.state !== "running"
) {
await showAlertDialog(this, {
title: "Could not restore snapshot",
text: `Restoring a snapshot is not possible right now because the system is in ${this._dialogParams?.supervisor.info.state} state.`,
title: "Could not restore backup",
text: `Restoring a backup is not possible right now because the system is in ${this._dialogParams?.supervisor.info.state} state.`,
});
return;
}
if (
!(await showConfirmationDialog(this, {
title: "Are you sure you want partially to restore this snapshot?",
title: "Are you sure you want partially to restore this backup?",
confirmText: "restore",
dismissText: "cancel",
}))
@ -186,8 +190,12 @@ class HassioSnapshotDialog
.callApi(
"POST",
`hassio/snapshots/${this._snapshot!.slug}/restore/partial`,
snapshotDetails
`hassio/${
atLeastVersion(this.hass.config.version, 2021, 9)
? "backups"
: "snapshots"
}/${this._backup!.slug}/restore/partial`,
backupDetails
)
.then(
() => {
@ -199,29 +207,29 @@ class HassioSnapshotDialog
);
} else {
fireEvent(this, "restoring");
fetch(`/api/hassio/snapshots/${this._snapshot!.slug}/restore/partial`, {
fetch(`/api/hassio/backups/${this._backup!.slug}/restore/partial`, {
method: "POST",
body: JSON.stringify(snapshotDetails),
body: JSON.stringify(backupDetails),
});
this.closeDialog();
}
}
private async _fullRestoreClicked(snapshotDetails) {
private async _fullRestoreClicked(backupDetails) {
if (
this._dialogParams?.supervisor !== undefined &&
this._dialogParams?.supervisor.info.state !== "running"
) {
await showAlertDialog(this, {
title: "Could not restore snapshot",
text: `Restoring a snapshot is not possible right now because the system is in ${this._dialogParams?.supervisor.info.state} state.`,
title: "Could not restore backup",
text: `Restoring a backup is not possible right now because the system is in ${this._dialogParams?.supervisor.info.state} state.`,
});
return;
}
if (
!(await showConfirmationDialog(this, {
title:
"Are you sure you want to wipe your system and restore this snapshot?",
"Are you sure you want to wipe your system and restore this backup?",
confirmText: "restore",
dismissText: "cancel",
}))
@ -233,8 +241,12 @@ class HassioSnapshotDialog
this.hass
.callApi(
"POST",
`hassio/snapshots/${this._snapshot!.slug}/restore/full`,
snapshotDetails
`hassio/${
atLeastVersion(this.hass.config.version, 2021, 9)
? "backups"
: "snapshots"
}/${this._backup!.slug}/restore/full`,
backupDetails
)
.then(
() => {
@ -246,9 +258,9 @@ class HassioSnapshotDialog
);
} else {
fireEvent(this, "restoring");
fetch(`/api/hassio/snapshots/${this._snapshot!.slug}/restore/full`, {
fetch(`/api/hassio/backups/${this._backup!.slug}/restore/full`, {
method: "POST",
body: JSON.stringify(snapshotDetails),
body: JSON.stringify(backupDetails),
});
this.closeDialog();
}
@ -257,7 +269,7 @@ class HassioSnapshotDialog
private async _deleteClicked() {
if (
!(await showConfirmationDialog(this, {
title: "Are you sure you want to delete this snapshot?",
title: "Are you sure you want to delete this backup?",
confirmText: "delete",
dismissText: "cancel",
}))
@ -267,7 +279,14 @@ class HassioSnapshotDialog
this.hass
.callApi("POST", `hassio/snapshots/${this._snapshot!.slug}/remove`)
.callApi(
atLeastVersion(this.hass.config.version, 2021, 9) ? "DELETE" : "POST",
`hassio/${
atLeastVersion(this.hass.config.version, 2021, 9)
? `backups/${this._backup!.slug}`
: `snapshots/${this._backup!.slug}/remove`
}`
)
.then(
() => {
if (this._dialogParams!.onDelete) {
@ -286,7 +305,11 @@ class HassioSnapshotDialog
try {
signedPath = await getSignedPath(
this.hass,
`/api/hassio/snapshots/${this._snapshot!.slug}/download`
`/api/hassio/${
atLeastVersion(this.hass.config.version, 2021, 9)
? "backups"
: "snapshots"
}/${this._backup!.slug}/download`
);
} catch (err) {
await showAlertDialog(this, {
@ -298,7 +321,7 @@ class HassioSnapshotDialog
if (window.location.href.includes("ui.nabu.casa")) {
const confirm = await showConfirmationDialog(this, {
title: "Potential slow download",
text: "Downloading snapshots over the Nabu Casa URL will take some time, it is recomended to use your local URL instead, do you want to continue?",
text: "Downloading backups over the Nabu Casa URL will take some time, it is recomended to use your local URL instead, do you want to continue?",
confirmText: "continue",
dismissText: "cancel",
});
@ -310,19 +333,19 @@ class HassioSnapshotDialog
fileDownload(
this,
signedPath.path,
`home_assistant_snapshot_${slugify(this._computeName)}.tar`
`home_assistant_backup_${slugify(this._computeName)}.tar`
);
}
private get _computeName() {
return this._snapshot
? this._snapshot.name || this._snapshot.slug
: "Unnamed snapshot";
return this._backup
? this._backup.name || this._backup.slug
: "Unnamed backup";
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-hassio-snapshot": HassioSnapshotDialog;
"dialog-hassio-backup": HassioBackupDialog;
}
}

View File

@ -2,41 +2,42 @@ import "@material/mwc-button";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/ha-alert";
import "../../../../src/components/buttons/ha-progress-button";
import { createCloseHeading } from "../../../../src/components/ha-dialog";
import { extractApiErrorMessage } from "../../../../src/data/hassio/common";
import {
createHassioFullSnapshot,
createHassioPartialSnapshot,
} from "../../../../src/data/hassio/snapshot";
createHassioFullBackup,
createHassioPartialBackup,
} from "../../../../src/data/hassio/backup";
import { showAlertDialog } from "../../../../src/dialogs/generic/show-dialog-box";
import { haStyle, haStyleDialog } from "../../../../src/resources/styles";
import { HomeAssistant } from "../../../../src/types";
import "../../components/supervisor-snapshot-content";
import type { SupervisorSnapshotContent } from "../../components/supervisor-snapshot-content";
import { HassioCreateSnapshotDialogParams } from "./show-dialog-hassio-create-snapshot";
import "../../components/supervisor-backup-content";
import type { SupervisorBackupContent } from "../../components/supervisor-backup-content";
import { HassioCreateBackupDialogParams } from "./show-dialog-hassio-create-backup";
@customElement("dialog-hassio-create-snapshot")
class HassioCreateSnapshotDialog extends LitElement {
@customElement("dialog-hassio-create-backup")
class HassioCreateBackupDialog extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _dialogParams?: HassioCreateSnapshotDialogParams;
@state() private _dialogParams?: HassioCreateBackupDialogParams;
@state() private _error?: string;
@state() private _creatingSnapshot = false;
@state() private _creatingBackup = false;
@query("supervisor-snapshot-content")
private _snapshotContent!: SupervisorSnapshotContent;
@query("supervisor-backup-content")
private _backupContent!: SupervisorBackupContent;
public showDialog(params: HassioCreateSnapshotDialogParams) {
public showDialog(params: HassioCreateBackupDialogParams) {
this._dialogParams = params;
this._creatingSnapshot = false;
this._creatingBackup = false;
}
public closeDialog() {
this._dialogParams = undefined;
this._creatingSnapshot = false;
this._creatingBackup = false;
this._error = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
}
@ -52,74 +53,76 @@ class HassioCreateSnapshotDialog extends LitElement {
@closed=${this.closeDialog}
.heading=${createCloseHeading(
this.hass,
this._dialogParams.supervisor.localize("snapshot.create_snapshot")
this._dialogParams.supervisor.localize("backup.create_backup")
)}
>
${this._creatingSnapshot
${this._creatingBackup
? html` <ha-circular-progress active></ha-circular-progress>`
: html`<supervisor-snapshot-content
: html`<supervisor-backup-content
.hass=${this.hass}
.supervisor=${this._dialogParams.supervisor}
>
</supervisor-snapshot-content>`}
${this._error ? html`<p class="error">Error: ${this._error}</p>` : ""}
</supervisor-backup-content>`}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
<mwc-button slot="secondaryAction" @click=${this.closeDialog}>
${this._dialogParams.supervisor.localize("common.close")}
</mwc-button>
<mwc-button
.disabled=${this._creatingSnapshot}
.disabled=${this._creatingBackup}
slot="primaryAction"
@click=${this._createSnapshot}
@click=${this._createBackup}
>
${this._dialogParams.supervisor.localize("snapshot.create")}
${this._dialogParams.supervisor.localize("backup.create")}
</mwc-button>
</ha-dialog>
`;
}
private async _createSnapshot(): Promise<void> {
private async _createBackup(): Promise<void> {
if (this._dialogParams!.supervisor.info.state !== "running") {
showAlertDialog(this, {
title: this._dialogParams!.supervisor.localize(
"snapshot.could_not_create"
"backup.could_not_create"
),
text: this._dialogParams!.supervisor.localize(
"snapshot.create_blocked_not_running",
"backup.create_blocked_not_running",
"state",
this._dialogParams!.supervisor.info.state
),
});
return;
}
const snapshotDetails = this._snapshotContent.snapshotDetails();
this._creatingSnapshot = true;
const backupDetails = this._backupContent.backupDetails();
this._creatingBackup = true;
this._error = "";
if (snapshotDetails.password && !snapshotDetails.password.length) {
if (backupDetails.password && !backupDetails.password.length) {
this._error = this._dialogParams!.supervisor.localize(
"snapshot.enter_password"
"backup.enter_password"
);
this._creatingSnapshot = false;
this._creatingBackup = false;
return;
}
if (
snapshotDetails.password &&
snapshotDetails.password !== snapshotDetails.confirm_password
backupDetails.password &&
backupDetails.password !== backupDetails.confirm_password
) {
this._error = this._dialogParams!.supervisor.localize(
"snapshot.passwords_not_matching"
"backup.passwords_not_matching"
);
this._creatingSnapshot = false;
this._creatingBackup = false;
return;
}
delete snapshotDetails.confirm_password;
delete backupDetails.confirm_password;
try {
if (this._snapshotContent.snapshotType === "full") {
await createHassioFullSnapshot(this.hass, snapshotDetails);
if (this._backupContent.backupType === "full") {
await createHassioFullBackup(this.hass, backupDetails);
} else {
await createHassioPartialSnapshot(this.hass, snapshotDetails);
await createHassioPartialBackup(this.hass, backupDetails);
}
this._dialogParams!.onCreate();
@ -127,7 +130,7 @@ class HassioCreateSnapshotDialog extends LitElement {
} catch (err) {
this._error = extractApiErrorMessage(err);
}
this._creatingSnapshot = false;
this._creatingBackup = false;
}
static get styles(): CSSResultGroup {
@ -146,6 +149,6 @@ class HassioCreateSnapshotDialog extends LitElement {
declare global {
interface HTMLElementTagNameMap {
"dialog-hassio-create-snapshot": HassioCreateSnapshotDialog;
"dialog-hassio-create-backup": HassioCreateBackupDialog;
}
}

View File

@ -0,0 +1,19 @@
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "./dialog-hassio-backup-upload";
export interface HassioBackupUploadDialogParams {
showBackup: (slug: string) => void;
reloadBackup?: () => Promise<void>;
onboarding?: boolean;
}
export const showBackupUploadDialog = (
element: HTMLElement,
dialogParams: HassioBackupUploadDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-hassio-backup-upload",
dialogImport: () => import("./dialog-hassio-backup-upload"),
dialogParams,
});
};

View File

@ -2,7 +2,7 @@ import { fireEvent } from "../../../../src/common/dom/fire_event";
import { LocalizeFunc } from "../../../../src/common/translations/localize";
import { Supervisor } from "../../../../src/data/supervisor/supervisor";
export interface HassioSnapshotDialogParams {
export interface HassioBackupDialogParams {
slug: string;
onDelete?: () => void;
onboarding?: boolean;
@ -10,13 +10,13 @@ export interface HassioSnapshotDialogParams {
localize?: LocalizeFunc;
}
export const showHassioSnapshotDialog = (
export const showHassioBackupDialog = (
element: HTMLElement,
dialogParams: HassioSnapshotDialogParams
dialogParams: HassioBackupDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-hassio-snapshot",
dialogImport: () => import("./dialog-hassio-snapshot"),
dialogTag: "dialog-hassio-backup",
dialogImport: () => import("./dialog-hassio-backup"),
dialogParams,
});
};

View File

@ -1,18 +1,18 @@
import { fireEvent } from "../../../../src/common/dom/fire_event";
import { Supervisor } from "../../../../src/data/supervisor/supervisor";
export interface HassioCreateSnapshotDialogParams {
export interface HassioCreateBackupDialogParams {
supervisor: Supervisor;
onCreate: () => void;
}
export const showHassioCreateSnapshotDialog = (
export const showHassioCreateBackupDialog = (
element: HTMLElement,
dialogParams: HassioCreateSnapshotDialogParams
dialogParams: HassioCreateBackupDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-hassio-create-snapshot",
dialogImport: () => import("./dialog-hassio-create-snapshot"),
dialogTag: "dialog-hassio-create-backup",
dialogImport: () => import("./dialog-hassio-create-backup"),
dialogParams,
});
};

View File

@ -10,6 +10,7 @@ import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { cache } from "lit/directives/cache";
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-circular-progress";
import "../../../../src/components/ha-dialog";
import "../../../../src/components/ha-expansion-panel";
@ -251,9 +252,9 @@ export class DialogHassioNetwork
`
: ""}
${this._dirty
? html`<div class="warning">
? html`<ha-alert alert-type="warning">
${this.supervisor.localize("dialog.network.warning")}
</div>`
</ha-alert>`
: ""}
</div>
<div class="buttons">

View File

@ -9,6 +9,7 @@ import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, query, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-circular-progress";
import { createCloseHeading } from "../../../../src/components/ha-dialog";
import "../../../../src/components/ha-svg-icon";
@ -75,7 +76,9 @@ class HassioRepositoriesDialog extends LitElement {
this._dialogParams!.supervisor.localize("dialog.repositories.title")
)}
>
${this._error ? html`<div class="error">${this._error}</div>` : ""}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
<div class="form">
${repositories.length
? repositories.map(

View File

@ -1,19 +0,0 @@
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "./dialog-hassio-snapshot-upload";
export interface HassioSnapshotUploadDialogParams {
showSnapshot: (slug: string) => void;
reloadSnapshot?: () => Promise<void>;
onboarding?: boolean;
}
export const showSnapshotUploadDialog = (
element: HTMLElement,
dialogParams: HassioSnapshotUploadDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-hassio-snapshot-upload",
dialogImport: () => import("./dialog-hassio-snapshot-upload"),
dialogParams,
});
};

View File

@ -2,6 +2,7 @@ import "@material/mwc-button/mwc-button";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, state } from "lit/decorators";
import { fireEvent } from "../../../../src/common/dom/fire_event";
import "../../../../src/components/ha-alert";
import "../../../../src/components/ha-circular-progress";
import "../../../../src/components/ha-dialog";
import "../../../../src/components/ha-settings-row";
@ -11,7 +12,7 @@ import {
extractApiErrorMessage,
ignoreSupervisorError,
} from "../../../../src/data/hassio/common";
import { createHassioPartialSnapshot } from "../../../../src/data/hassio/snapshot";
import { createHassioPartialBackup } from "../../../../src/data/hassio/backup";
import { haStyle, haStyleDialog } from "../../../../src/resources/styles";
import type { HomeAssistant } from "../../../../src/types";
import { SupervisorDialogSupervisorUpdateParams } from "./show-dialog-update";
@ -22,9 +23,9 @@ class DialogSupervisorUpdate extends LitElement {
@state() private _opened = false;
@state() private _createSnapshot = true;
@state() private _createBackup = true;
@state() private _action: "snapshot" | "update" | null = null;
@state() private _action: "backup" | "update" | null = null;
@state() private _error?: string;
@ -41,7 +42,7 @@ class DialogSupervisorUpdate extends LitElement {
public closeDialog(): void {
this._action = null;
this._createSnapshot = true;
this._createBackup = true;
this._error = undefined;
this._dialogParams = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
@ -84,20 +85,20 @@ class DialogSupervisorUpdate extends LitElement {
<ha-settings-row>
<span slot="heading">
${this._dialogParams.supervisor.localize(
"dialog.update.snapshot"
"dialog.update.backup"
)}
</span>
<span slot="description">
${this._dialogParams.supervisor.localize(
"dialog.update.create_snapshot",
"dialog.update.create_backup",
"name",
this._dialogParams.name
)}
</span>
<ha-switch
.checked=${this._createSnapshot}
.checked=${this._createBackup}
haptic
@click=${this._toggleSnapshot}
@click=${this._toggleBackup}
>
</ha-switch>
</ha-settings-row>
@ -123,27 +124,29 @@ class DialogSupervisorUpdate extends LitElement {
this._dialogParams.version
)
: this._dialogParams.supervisor.localize(
"dialog.update.snapshotting",
"dialog.update.creating_backup",
"name",
this._dialogParams.name
)}
</p>`}
${this._error ? html`<p class="error">${this._error}</p>` : ""}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
</ha-dialog>
`;
}
private _toggleSnapshot() {
this._createSnapshot = !this._createSnapshot;
private _toggleBackup() {
this._createBackup = !this._createBackup;
}
private async _update() {
if (this._createSnapshot) {
this._action = "snapshot";
if (this._createBackup) {
this._action = "backup";
try {
await createHassioPartialSnapshot(
await createHassioPartialBackup(
this.hass,
this._dialogParams!.snapshotParams
this._dialogParams!.backupParams
);
} catch (err) {
this._error = extractApiErrorMessage(err);

View File

@ -5,7 +5,7 @@ export interface SupervisorDialogSupervisorUpdateParams {
supervisor: Supervisor;
name: string;
version: string;
snapshotParams: any;
backupParams: any;
updateHandler: () => Promise<void>;
}

View File

@ -26,7 +26,10 @@ const REDIRECTS: Redirects = {
redirect: "/hassio/system",
},
supervisor_snapshots: {
redirect: "/hassio/snapshots",
redirect: "/hassio/backups",
},
supervisor_backups: {
redirect: "/hassio/backups",
},
supervisor_store: {
redirect: "/hassio/store",

View File

@ -9,7 +9,7 @@ import "./addon-store/hassio-addon-store";
// Don't codesplit it, that way the dashboard always loads fast.
import "./dashboard/hassio-dashboard";
// Don't codesplit the others, because it breaks the UI when pushed to a Pi
import "./snapshots/hassio-snapshots";
import "./backups/hassio-backups";
import "./system/hassio-system";
@customElement("hassio-panel-router")
@ -23,6 +23,8 @@ class HassioPanelRouter extends HassRouterPage {
@property({ type: Boolean }) public narrow!: boolean;
protected routerOptions: RouterOptions = {
beforeRender: (page: string) =>
page === "snapshots" ? "backups" : undefined,
routes: {
dashboard: {
tag: "hassio-dashboard",
@ -30,8 +32,8 @@ class HassioPanelRouter extends HassRouterPage {
store: {
tag: "hassio-addon-store",
},
snapshots: {
tag: "hassio-snapshots",
backups: {
tag: "hassio-backups",
},
system: {
tag: "hassio-system",

View File

@ -23,6 +23,8 @@ class HassioRouter extends HassRouterPage {
protected routerOptions: RouterOptions = {
// Hass.io has a page with tabs, so we route all non-matching routes to it.
defaultPage: "dashboard",
beforeRender: (page: string) =>
page === "snapshots" ? "backups" : undefined,
initialLoad: () => this._redirectIngress(),
showLoading: true,
routes: {
@ -30,7 +32,7 @@ class HassioRouter extends HassRouterPage {
tag: "hassio-panel",
cache: true,
},
snapshots: "dashboard",
backups: "dashboard",
store: "dashboard",
system: "dashboard",
addon: {

View File

@ -13,8 +13,8 @@ export const supervisorTabs: PageNavigation[] = [
iconPath: mdiStore,
},
{
translationKey: "panel.snapshots",
path: `/hassio/snapshots`,
translationKey: "panel.backups",
path: `/hassio/backups`,
iconPath: mdiBackupRestore,
},
{

View File

@ -165,7 +165,7 @@ class HassioCoreInfo extends LitElement {
supervisor: this.supervisor,
name: "Home Assistant Core",
version: this.supervisor.core.version_latest,
snapshotParams: {
backupParams: {
name: `core_${this.supervisor.core.version}`,
folders: ["homeassistant"],
homeassistant: true,

View File

@ -3,6 +3,7 @@ import { customElement, property, state } from "lit/decorators";
import { atLeastVersion } from "../../../src/common/config/version";
import { fireEvent } from "../../../src/common/dom/fire_event";
import "../../../src/components/buttons/ha-progress-button";
import "../../../src/components/ha-alert";
import "../../../src/components/ha-card";
import "../../../src/components/ha-settings-row";
import "../../../src/components/ha-switch";
@ -170,31 +171,25 @@ class HassioSupervisorInfo extends LitElement {
></ha-switch>
</ha-settings-row>`
: ""
: html`<div class="error">
: html`<ha-alert
alert-type="warning"
.actionText=${this.supervisor.localize("common.learn_more")}
@alert-action-clicked=${this._unsupportedDialog}
>
${this.supervisor.localize(
"system.supervisor.unsupported_title"
)}
<button
class="link"
.title=${this.supervisor.localize("common.learn_more")}
@click=${this._unsupportedDialog}
>
Learn more
</button>
</div>`}
</ha-alert>`}
${!this.supervisor.supervisor.healthy
? html`<div class="error">
? html`<ha-alert
alert-type="error"
.actionText=${this.supervisor.localize("common.learn_more")}
@alert-action-clicked=${this._unhealthyDialog}
>
${this.supervisor.localize(
"system.supervisor.unhealthy_title"
)}
<button
class="link"
.title=${this.supervisor.localize("common.learn_more")}
@click=${this._unhealthyDialog}
>
Learn more
</button>
</div>`
</ha-alert>`
: ""}
</div>
<div class="metrics-block">

View File

@ -5,6 +5,7 @@ import "@polymer/paper-listbox/paper-listbox";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../../src/components/buttons/ha-progress-button";
import "../../../src/components/ha-alert";
import "../../../src/components/ha-card";
import { extractApiErrorMessage } from "../../../src/data/hassio/common";
import { fetchHassioLogs } from "../../../src/data/hassio/supervisor";
@ -67,7 +68,9 @@ class HassioSupervisorLog extends LitElement {
protected render(): TemplateResult | void {
return html`
<ha-card>
${this._error ? html` <div class="errors">${this._error}</div> ` : ""}
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: ""}
${this.hass.userData?.showAdvanced
? html`
<paper-dropdown-menu
@ -154,10 +157,6 @@ class HassioSupervisorLog extends LitElement {
padding: 0 2%;
width: 96%;
}
.errors {
color: var(--error-color);
margin-bottom: 16px;
}
`,
];
}

View File

@ -17,7 +17,7 @@
"lint": "yarn run lint:eslint && yarn run lint:prettier && yarn run lint:types",
"format": "yarn run format:eslint && yarn run format:prettier",
"mocha": "ts-mocha -p test-mocha/tsconfig.test.json \"test-mocha/**/*.ts\"",
"test": "yarn run lint && yarn run mocha"
"test": "yarn run mocha"
},
"author": "Paulus Schoutsen <Paulus@PaulusSchoutsen.nl> (http://paulusschoutsen.nl)",
"license": "Apache-2.0",
@ -113,7 +113,7 @@
"js-yaml": "^4.1.0",
"leaflet": "^1.7.1",
"leaflet-draw": "^1.0.4",
"lit": "^2.0.0-rc.2",
"lit": "^2.0.0-rc.3",
"lit-vaadin-helpers": "^0.1.3",
"marked": "^2.0.5",
"mdn-polyfills": "^5.16.0",
@ -233,8 +233,10 @@
"resolutions": {
"@polymer/polymer": "patch:@polymer/polymer@3.4.1#./.yarn/patches/@polymer/polymer/pr-5569.patch",
"@webcomponents/webcomponentsjs": "^2.2.10",
"lit-html": "2.0.0-rc.3",
"lit-element": "3.0.0-rc.2"
"lit": "^2.0.0-rc.3",
"lit-html": "2.0.0-rc.4",
"lit-element": "3.0.0-rc.3",
"@lit/reactive-element": "1.0.0-rc.3"
},
"main": "src/home-assistant.js",
"husky": {

View File

@ -2,7 +2,7 @@ from setuptools import setup, find_packages
setup(
name="home-assistant-frontend",
version="20210809.0",
version="20210830.0",
description="The Home Assistant frontend",
url="https://github.com/home-assistant/frontend",
author="The Home Assistant Authors",

View File

@ -1,5 +1,5 @@
export const COLORS = [
"#377eb8",
"#44739e",
"#984ea3",
"#00d2d5",
"#ff7f00",

View File

@ -56,19 +56,30 @@ export const FIXED_DOMAIN_ICONS = {
};
export const FIXED_DEVICE_CLASS_ICONS = {
aqi: "hass:air-filter",
current: "hass:current-ac",
carbon_dioxide: "mdi:molecule-co2",
carbon_monoxide: "mdi:molecule-co",
energy: "hass:lightning-bolt",
gas: "hass:gas-cylinder",
humidity: "hass:water-percent",
illuminance: "hass:brightness-5",
nitrogen_dioxide: "mdi:molecule",
nitrogen_monoxide: "mdi:molecule",
nitrous_oxide: "mdi:molecule",
ozone: "mdi:molecule",
temperature: "hass:thermometer",
monetary: "mdi:cash",
pm25: "mdi:molecule",
pm1: "mdi:molecule",
pm10: "mdi:molecule",
pressure: "hass:gauge",
power: "hass:flash",
power_factor: "hass:angle-acute",
signal_strength: "hass:wifi",
sulphur_dioxide: "mdi:molecule",
timestamp: "hass:clock",
volatile_organic_compounds: "mdi:molecule",
voltage: "hass:sine-wave",
};
@ -157,66 +168,3 @@ export const UNIT_F = "°F";
/** Entity ID of the default view. */
export const DEFAULT_VIEW_ENTITY_ID = "group.default_view";
/** HA Color Pallete. */
export const HA_COLOR_PALETTE = [
"ff0029",
"66a61e",
"377eb8",
"984ea3",
"00d2d5",
"ff7f00",
"af8d00",
"7f80cd",
"b3e900",
"c42e60",
"a65628",
"f781bf",
"8dd3c7",
"bebada",
"fb8072",
"80b1d3",
"fdb462",
"fccde5",
"bc80bd",
"ffed6f",
"c4eaff",
"cf8c00",
"1b9e77",
"d95f02",
"e7298a",
"e6ab02",
"a6761d",
"0097ff",
"00d067",
"f43600",
"4ba93b",
"5779bb",
"927acc",
"97ee3f",
"bf3947",
"9f5b00",
"f48758",
"8caed6",
"f2b94f",
"eff26e",
"e43872",
"d9b100",
"9d7a00",
"698cff",
"d9d9d9",
"00d27e",
"d06800",
"009f82",
"c49200",
"cbe8ff",
"fecddf",
"c27eb6",
"8cd2ce",
"c4b8d9",
"f883b0",
"a49100",
"f48800",
"27d0df",
"a04a9b",
];

View File

@ -0,0 +1,31 @@
import { HaDurationData } from "../../components/ha-duration-input";
import { ForDict } from "../../data/automation";
export const createDurationData = (
duration: string | number | ForDict | undefined
): HaDurationData => {
if (duration === undefined) {
return {};
}
if (typeof duration !== "object") {
if (typeof duration === "string" || isNaN(duration)) {
const parts = duration?.toString().split(":") || [];
return {
hours: Number(parts[0]) || 0,
minutes: Number(parts[1]) || 0,
seconds: Number(parts[2]) || 0,
milliseconds: Number(parts[3]) || 0,
};
}
return { seconds: duration };
}
const { days, minutes, seconds, milliseconds } = duration;
let hours = duration.hours || 0;
hours = (hours || 0) + (days || 0) * 24;
return {
hours,
minutes,
seconds,
milliseconds,
};
};

View File

@ -3,33 +3,11 @@ import memoizeOne from "memoize-one";
import { FrontendLocaleData } from "../../data/translation";
import { toLocaleDateStringSupportsOptions } from "./check_options_support";
const formatDateMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
year: "numeric",
month: "long",
day: "numeric",
})
);
export const formatDate = toLocaleDateStringSupportsOptions
// Tuesday, August 10
export const formatDateWeekday = toLocaleDateStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "longDate");
const formatDateShortMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
day: "numeric",
month: "short",
})
);
export const formatDateShort = toLocaleDateStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateShortMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "shortDate");
formatDateWeekdayMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "dddd, MMMM D");
const formatDateWeekdayMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
@ -39,7 +17,80 @@ const formatDateWeekdayMem = memoizeOne(
})
);
export const formatDateWeekday = toLocaleDateStringSupportsOptions
// August 10, 2021
export const formatDate = toLocaleDateStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateWeekdayMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "dddd, MMM D");
formatDateMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "MMMM D, YYYY");
const formatDateMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
year: "numeric",
month: "long",
day: "numeric",
})
);
// 10/08/2021
export const formatDateNumeric = toLocaleDateStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateNumericMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "M/D/YYYY");
const formatDateNumericMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
year: "numeric",
month: "numeric",
day: "numeric",
})
);
// Aug 10
export const formatDateShort = toLocaleDateStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateShortMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "MMM D");
const formatDateShortMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
day: "numeric",
month: "short",
})
);
// August 2021
export const formatDateMonthYear = toLocaleDateStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateMonthYearMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "MMMM YYYY");
const formatDateMonthYearMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
month: "long",
year: "numeric",
})
);
// August
export const formatDateMonth = toLocaleDateStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateMonthMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "MMMM");
const formatDateMonthMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
month: "long",
})
);
// 2021
export const formatDateYear = toLocaleDateStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateYearMem(locale).format(dateObj)
: (dateObj: Date) => format(dateObj, "YYYY");
const formatDateYearMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
year: "numeric",
})
);

View File

@ -4,6 +4,12 @@ import { FrontendLocaleData } from "../../data/translation";
import { toLocaleStringSupportsOptions } from "./check_options_support";
import { useAmPm } from "./use_am_pm";
// August 9, 2021, 8:23 AM
export const formatDateTime = toLocaleStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateTimeMem(locale).format(dateObj)
: (dateObj: Date, locale: FrontendLocaleData) =>
format(dateObj, "MMMM D, YYYY, HH:mm" + useAmPm(locale) ? " A" : "");
const formatDateTimeMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
@ -16,12 +22,12 @@ const formatDateTimeMem = memoizeOne(
})
);
export const formatDateTime = toLocaleStringSupportsOptions
// August 9, 2021, 8:23:15 AM
export const formatDateTimeWithSeconds = toLocaleStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateTimeMem(locale).format(dateObj)
formatDateTimeWithSecondsMem(locale).format(dateObj)
: (dateObj: Date, locale: FrontendLocaleData) =>
format(dateObj, "MMMM D, YYYY, HH:mm" + useAmPm(locale) ? " A" : "");
format(dateObj, "MMMM D, YYYY, HH:mm:ss" + useAmPm(locale) ? " A" : "");
const formatDateTimeWithSecondsMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
@ -35,8 +41,20 @@ const formatDateTimeWithSecondsMem = memoizeOne(
})
);
export const formatDateTimeWithSeconds = toLocaleStringSupportsOptions
// 9/8/2021, 8:23 AM
export const formatDateTimeNumeric = toLocaleStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatDateTimeWithSecondsMem(locale).format(dateObj)
formatDateTimeNumericMem(locale).format(dateObj)
: (dateObj: Date, locale: FrontendLocaleData) =>
format(dateObj, "MMMM D, YYYY, HH:mm:ss" + useAmPm(locale) ? " A" : "");
format(dateObj, "M/D/YYYY, HH:mm" + useAmPm(locale) ? " A" : "");
const formatDateTimeNumericMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "2-digit",
hour12: useAmPm(locale),
})
);

View File

@ -4,6 +4,12 @@ import { FrontendLocaleData } from "../../data/translation";
import { toLocaleTimeStringSupportsOptions } from "./check_options_support";
import { useAmPm } from "./use_am_pm";
// 9:15 PM || 21:15
export const formatTime = toLocaleTimeStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatTimeMem(locale).format(dateObj)
: (dateObj: Date, locale: FrontendLocaleData) =>
format(dateObj, "shortTime" + useAmPm(locale) ? " A" : "");
const formatTimeMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
@ -13,12 +19,12 @@ const formatTimeMem = memoizeOne(
})
);
export const formatTime = toLocaleTimeStringSupportsOptions
// 9:15:24 PM || 21:15:24
export const formatTimeWithSeconds = toLocaleTimeStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatTimeMem(locale).format(dateObj)
formatTimeWithSecondsMem(locale).format(dateObj)
: (dateObj: Date, locale: FrontendLocaleData) =>
format(dateObj, "shortTime" + useAmPm(locale) ? " A" : "");
format(dateObj, "mediumTime" + useAmPm(locale) ? " A" : "");
const formatTimeWithSecondsMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
@ -29,12 +35,12 @@ const formatTimeWithSecondsMem = memoizeOne(
})
);
export const formatTimeWithSeconds = toLocaleTimeStringSupportsOptions
// Tuesday 7:00 PM || Tuesday 19:00
export const formatTimeWeekday = toLocaleTimeStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatTimeWithSecondsMem(locale).format(dateObj)
formatTimeWeekdayMem(locale).format(dateObj)
: (dateObj: Date, locale: FrontendLocaleData) =>
format(dateObj, "mediumTime" + useAmPm(locale) ? " A" : "");
format(dateObj, "dddd, HH:mm" + useAmPm(locale) ? " A" : "");
const formatTimeWeekdayMem = memoizeOne(
(locale: FrontendLocaleData) =>
new Intl.DateTimeFormat(locale.language, {
@ -44,9 +50,3 @@ const formatTimeWeekdayMem = memoizeOne(
hour12: useAmPm(locale),
})
);
export const formatTimeWeekday = toLocaleTimeStringSupportsOptions
? (dateObj: Date, locale: FrontendLocaleData) =>
formatTimeWeekdayMem(locale).format(dateObj)
: (dateObj: Date, locale: FrontendLocaleData) =>
format(dateObj, "dddd, HH:mm" + useAmPm(locale) ? " A" : "");

View File

@ -1,6 +1,7 @@
import memoizeOne from "memoize-one";
import { FrontendLocaleData, TimeFormat } from "../../data/translation";
export const useAmPm = (locale: FrontendLocaleData): boolean => {
export const useAmPm = memoizeOne((locale: FrontendLocaleData): boolean => {
if (
locale.time_format === TimeFormat.language ||
locale.time_format === TimeFormat.system
@ -12,4 +13,4 @@ export const useAmPm = (locale: FrontendLocaleData): boolean => {
}
return locale.time_format === TimeFormat.am_pm;
};
});

View File

@ -44,6 +44,8 @@ export const binarySensorIcon = (state?: string, stateObj?: HassEntity) => {
return is_off ? "hass:home-outline" : "hass:home";
case "sound":
return is_off ? "hass:music-note-off" : "hass:music-note";
case "update":
return is_off ? "mdi:package" : "mdi:package-up";
case "vibration":
return is_off ? "hass:crop-portrait" : "hass:vibrate";
case "window":

View File

@ -0,0 +1,15 @@
export const groupBy = <T>(
list: T[],
keySelector: (item: T) => string
): { [key: string]: T[] } => {
const result = {};
for (const item of list) {
const key = keySelector(item);
if (key in result) {
result[key].push(item);
} else {
result[key] = [item];
}
}
return result;
};

View File

@ -7,14 +7,10 @@ interface ResultCache<T> {
export const timeCachePromiseFunc = async <T>(
cacheKey: string,
cacheTime: number,
func: (
hass: HomeAssistant,
entityId: string,
...args: unknown[]
) => Promise<T>,
func: (hass: HomeAssistant, entityId: string, ...args: any[]) => Promise<T>,
hass: HomeAssistant,
entityId: string,
...args: unknown[]
...args: any[]
): Promise<T> => {
let cache: ResultCache<T> | undefined = (hass as any)[cacheKey];

View File

@ -35,7 +35,14 @@ import {
endOfQuarter,
endOfYear,
} from "date-fns";
import { formatDate, formatDateShort } from "../../common/datetime/format_date";
import {
formatDate,
formatDateMonth,
formatDateMonthYear,
formatDateShort,
formatDateWeekday,
formatDateYear,
} from "../../common/datetime/format_date";
import {
formatDateTime,
formatDateTimeWithSeconds,
@ -53,8 +60,11 @@ const FORMATS = {
minute: "minute",
hour: "hour",
day: "day",
date: "date",
weekday: "weekday",
week: "week",
month: "month",
monthyear: "monthyear",
quarter: "quarter",
year: "year",
};
@ -81,16 +91,22 @@ _adapters._date.override({
return formatTime(new Date(time), this.options.locale);
case "hour":
return formatTime(new Date(time), this.options.locale);
case "weekday":
return formatDateWeekday(new Date(time), this.options.locale);
case "date":
return formatDate(new Date(time), this.options.locale);
case "day":
return formatDateShort(new Date(time), this.options.locale);
case "week":
return formatDate(new Date(time), this.options.locale);
case "month":
return formatDate(new Date(time), this.options.locale);
return formatDateMonth(new Date(time), this.options.locale);
case "monthyear":
return formatDateMonthYear(new Date(time), this.options.locale);
case "quarter":
return formatDate(new Date(time), this.options.locale);
case "year":
return formatDate(new Date(time), this.options.locale);
return formatDateYear(new Date(time), this.options.locale);
default:
return "";
}

View File

@ -61,6 +61,11 @@ export default class HaChartBase extends LitElement {
this.chart.config.type = this.chartType;
}
if (changedProps.has("data")) {
if (this._hiddenDatasets.size) {
this.data.datasets.forEach((dataset, index) => {
dataset.hidden = this._hiddenDatasets.has(index);
});
}
this.chart.data = this.data;
}
if (changedProps.has("options")) {
@ -238,9 +243,19 @@ export default class HaChartBase extends LitElement {
};
}
public updateChart = (): void => {
public updateChart = (
mode:
| "resize"
| "reset"
| "none"
| "hide"
| "show"
| "normal"
| "active"
| undefined
): void => {
if (this.chart) {
this.chart.update();
this.chart.update(mode);
}
};

View File

@ -25,6 +25,7 @@ export const createCurrencyListEl = () => {
"BSD",
"BTN",
"BWP",
"BYN",
"BYR",
"BZD",
"CAD",

View File

@ -62,6 +62,7 @@ export interface DataTableSortColumnData {
sortable?: boolean;
filterable?: boolean;
filterKey?: string;
valueColumn?: string;
direction?: SortingDirection;
}
@ -76,7 +77,7 @@ export interface DataTableColumnData extends DataTableSortColumnData {
hidden?: boolean;
}
type ClonedDataTableColumnData = Omit<DataTableColumnData, "title"> & {
export type ClonedDataTableColumnData = Omit<DataTableColumnData, "title"> & {
title?: TemplateResult | string;
};
@ -455,7 +456,7 @@ export class HaDataTable extends LitElement {
const prom = this._sortColumn
? sortData(
filteredData,
this._sortColumns,
this._sortColumns[this._sortColumn],
this._sortDirection,
this._sortColumn
)

View File

@ -2,8 +2,8 @@
import { expose } from "comlink";
import "proxy-polyfill";
import type {
ClonedDataTableColumnData,
DataTableRowData,
DataTableSortColumnData,
SortableColumnContainer,
SortingDirection,
} from "./ha-data-table";
@ -19,7 +19,11 @@ const filterData = (
const [key, column] = columnEntry;
if (column.filterable) {
if (
String(column.filterKey ? row[key][column.filterKey] : row[key])
String(
column.filterKey
? row[column.valueColumn || key][column.filterKey]
: row[column.valueColumn || key]
)
.toUpperCase()
.includes(filter)
) {
@ -33,7 +37,7 @@ const filterData = (
const sortData = (
data: DataTableRowData[],
column: DataTableSortColumnData,
column: ClonedDataTableColumnData,
direction: SortingDirection,
sortColumn: string
) =>
@ -44,12 +48,12 @@ const sortData = (
}
let valA = column.filterKey
? a[sortColumn][column.filterKey]
: a[sortColumn];
? a[column.valueColumn || sortColumn][column.filterKey]
: a[column.valueColumn || sortColumn];
let valB = column.filterKey
? b[sortColumn][column.filterKey]
: b[sortColumn];
? b[column.valueColumn || sortColumn][column.filterKey]
: b[column.valueColumn || sortColumn];
if (typeof valA === "string") {
valA = valA.toUpperCase();

View File

@ -257,7 +257,7 @@ export class HaStateLabelBadge extends LitElement {
}
.warning {
--ha-label-badge-color: var(--label-badge-yellow, #fce588);
--ha-label-badge-color: var(--label-badge-yellow, #f4b400);
}
`;
}

180
src/components/ha-alert.ts Normal file
View File

@ -0,0 +1,180 @@
import "@material/mwc-button/mwc-button";
import "@material/mwc-icon-button/mwc-icon-button";
import {
mdiAlertCircleOutline,
mdiAlertOutline,
mdiCheckboxMarkedCircleOutline,
mdiClose,
} from "@mdi/js";
import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { fireEvent } from "../common/dom/fire_event";
import "./ha-svg-icon";
const ALERT_ICONS = {
info: mdiAlertCircleOutline,
warning: mdiAlertOutline,
error: mdiAlertCircleOutline,
success: mdiCheckboxMarkedCircleOutline,
};
declare global {
interface HASSDomEvents {
"alert-dismissed-clicked": undefined;
"alert-action-clicked": undefined;
}
}
@customElement("ha-alert")
class HaAlert extends LitElement {
@property() public title = "";
@property({ attribute: "alert-type" }) public alertType:
| "info"
| "warning"
| "error"
| "success" = "info";
@property({ attribute: "action-text" }) public actionText = "";
@property({ type: Boolean }) public dismissable = false;
@property({ type: Boolean }) public rtl = false;
public render() {
return html`
<div
class="issue-type ${classMap({
rtl: this.rtl,
[this.alertType]: true,
})}"
>
<div class="icon">
<ha-svg-icon .path=${ALERT_ICONS[this.alertType]}></ha-svg-icon>
</div>
<div class="content">
<div
class="main-content ${classMap({
"no-title": !this.title,
})}"
>
${this.title ? html`<div class="title">${this.title}</div>` : ""}
<slot></slot>
</div>
<div class="action">
${this.actionText
? html`<mwc-button
@click=${this._action_clicked}
.label=${this.actionText}
></mwc-button>`
: this.dismissable
? html`<mwc-icon-button
@click=${this._dismiss_clicked}
aria-label="Dismiss alert"
>
<ha-svg-icon .path=${mdiClose}> </ha-svg-icon>
</mwc-icon-button> `
: ""}
</div>
</div>
</div>
`;
}
private _dismiss_clicked() {
fireEvent(this, "alert-dismissed-clicked");
}
private _action_clicked() {
fireEvent(this, "alert-action-clicked");
}
static styles = css`
.issue-type {
position: relative;
padding: 4px;
display: flex;
margin: 4px 0;
}
.issue-type.rtl {
flex-direction: row-reverse;
}
.issue-type::before {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
opacity: 0.12;
pointer-events: none;
content: "";
border-radius: 4px;
}
.icon {
margin: 4px 8px;
width: 24px;
}
.main-content.no-title {
margin-top: 6px;
}
.issue-type.rtl > .content {
flex-direction: row-reverse;
text-align: right;
}
.content {
display: flex;
justify-content: space-between;
width: 100%;
}
.main-content {
overflow-wrap: anywhere;
}
.title {
font-weight: bold;
margin-top: 6px;
}
mwc-button {
--mdc-theme-primary: var(--primary-text-color);
}
.action {
align-self: center;
}
.issue-type.info > .icon {
color: var(--info-color);
}
.issue-type.info::before {
background-color: var(--info-color);
}
.issue-type.warning > .icon {
color: var(--warning-color);
}
.issue-type.warning::before {
background-color: var(--warning-color);
}
.issue-type.error > .icon {
color: var(--error-color);
}
.issue-type.error::before {
background-color: var(--error-color);
}
.issue-type.success > .icon {
color: var(--success-color);
}
.issue-type.success::before {
background-color: var(--success-color);
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-alert": HaAlert;
}
}

View File

@ -1,7 +1,8 @@
import "@material/mwc-button/mwc-button";
import type { Button } from "@material/mwc-button/mwc-button";
import "@material/mwc-icon-button/mwc-icon-button";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, queryAll } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import { fireEvent } from "../common/dom/fire_event";
import type { ToggleButton } from "../types";
@ -15,6 +16,10 @@ export class HaButtonToggleGroup extends LitElement {
@property({ type: Boolean }) public fullWidth = false;
@property({ type: Boolean }) public dense = false;
@queryAll("mwc-button") private _buttons?: Button[];
protected render(): TemplateResult {
return html`
<div>
@ -34,6 +39,8 @@ export class HaButtonToggleGroup extends LitElement {
? `${100 / this.buttons.length}%`
: "initial",
})}
outlined
.dense=${this.dense}
.value=${button.value}
?active=${this.active === button.value}
@click=${this._handleClick}
@ -44,6 +51,16 @@ export class HaButtonToggleGroup extends LitElement {
`;
}
protected updated() {
// Work around Safari default margin that is not reset in mwc-button as of aug 2021
this._buttons?.forEach(async (button) => {
await button.updateComplete;
(
button.shadowRoot!.querySelector("button") as HTMLButtonElement
).style.margin = "0";
});
}
private _handleClick(ev): void {
this.active = ev.currentTarget.value;
fireEvent(this, "value-changed", { value: this.active });
@ -56,10 +73,16 @@ export class HaButtonToggleGroup extends LitElement {
--mdc-icon-button-size: var(--button-toggle-size, 36px);
--mdc-icon-size: var(--button-toggle-icon-size, 20px);
}
mwc-icon-button,
mwc-button {
--mdc-shape-small: 0;
--mdc-button-outline-width: 1px 0 1px 1px;
}
mwc-icon-button {
border: 1px solid var(--primary-color);
border-right-width: 0px;
}
mwc-icon-button,
mwc-button {
position: relative;
cursor: pointer;
}
@ -82,16 +105,19 @@ export class HaButtonToggleGroup extends LitElement {
}
mwc-icon-button:first-child,
mwc-button:first-child {
--mdc-shape-small: 4px 0 0 4px;
border-radius: 4px 0 0 4px;
}
mwc-icon-button:last-child,
mwc-button:last-child {
border-radius: 0 4px 4px 0;
border-right-width: 1px;
--mdc-shape-small: 0 4px 4px 0;
--mdc-button-outline-width: 1px;
}
mwc-icon-button:only-child,
mwc-button:only-child {
border-radius: 4px;
--mdc-shape-small: 4px;
border-right-width: 1px;
}
`;

View File

@ -8,7 +8,6 @@ import {
} from "lit";
import { customElement, property, state } from "lit/decorators";
import { isComponentLoaded } from "../common/config/is_component_loaded";
import { fireEvent } from "../common/dom/fire_event";
import { computeStateName } from "../common/entity/compute_state_name";
import { supportsFeature } from "../common/entity/supports-feature";
import {
@ -41,6 +40,32 @@ class HaCameraStream extends LitElement {
@state() private _url?: string;
@state() private _connected = false;
public willUpdate(changedProps: PropertyValues): void {
if (
changedProps.has("stateObj") &&
!this._shouldRenderMJPEG &&
this.stateObj &&
(changedProps.get("stateObj") as CameraEntity | undefined)?.entity_id !==
this.stateObj.entity_id
) {
this._forceMJPEG = undefined;
this._url = undefined;
this._getStreamUrl();
}
}
public connectedCallback() {
super.connectedCallback();
this._connected = true;
}
public disconnectedCallback() {
super.disconnectedCallback();
this._connected = false;
}
protected render(): TemplateResult {
if (!this.stateObj) {
return html``;
@ -50,10 +75,11 @@ class HaCameraStream extends LitElement {
${__DEMO__ || this._shouldRenderMJPEG
? html`
<img
@load=${this._elementResized}
.src=${__DEMO__
? this.stateObj!.attributes.entity_picture
: computeMJPEGStreamUrl(this.stateObj)}
? this.stateObj!.attributes.entity_picture!
: this._connected
? computeMJPEGStreamUrl(this.stateObj)
: ""}
.alt=${`Preview of the ${computeStateName(
this.stateObj
)} camera.`}
@ -75,13 +101,6 @@ class HaCameraStream extends LitElement {
`;
}
protected updated(changedProps: PropertyValues): void {
if (changedProps.has("stateObj") && !this._shouldRenderMJPEG) {
this._forceMJPEG = undefined;
this._getStreamUrl();
}
}
private get _shouldRenderMJPEG() {
return (
this._forceMJPEG === this.stateObj!.entity_id ||
@ -107,10 +126,6 @@ class HaCameraStream extends LitElement {
}
}
private _elementResized() {
fireEvent(this, "iron-resize");
}
static get styles(): CSSResultGroup {
return css`
:host,

View File

@ -0,0 +1,140 @@
import { html, LitElement, TemplateResult } from "lit";
import { customElement, property, query } from "lit/decorators";
import { fireEvent } from "../common/dom/fire_event";
import "./paper-time-input";
export interface HaDurationData {
hours?: number;
minutes?: number;
seconds?: number;
milliseconds?: number;
}
@customElement("ha-duration-input")
class HaDurationInput extends LitElement {
@property({ attribute: false }) public data!: HaDurationData;
@property() public label?: string;
@property() public suffix?: string;
@property({ type: Boolean }) public required?: boolean;
@property({ type: Boolean }) public enableMillisecond?: boolean;
@query("paper-time-input", true) private _input?: HTMLElement;
public focus() {
if (this._input) {
this._input.focus();
}
}
protected render(): TemplateResult {
return html`
<paper-time-input
.label=${this.label}
.required=${this.required}
.autoValidate=${this.required}
error-message="Required"
enable-second
.enableMillisecond=${this.enableMillisecond}
format="24"
.hour=${this._parseDuration(this._hours)}
.min=${this._parseDuration(this._minutes)}
.sec=${this._parseDuration(this._seconds)}
.millisec=${this._parseDurationMillisec(this._milliseconds)}
@hour-changed=${this._hourChanged}
@min-changed=${this._minChanged}
@sec-changed=${this._secChanged}
@millisec-changed=${this._millisecChanged}
float-input-labels
no-hours-limit
always-float-input-labels
hour-label="hh"
min-label="mm"
sec-label="ss"
millisec-label="ms"
></paper-time-input>
`;
}
private get _hours() {
return this.data && this.data.hours ? Number(this.data.hours) : 0;
}
private get _minutes() {
return this.data && this.data.minutes ? Number(this.data.minutes) : 0;
}
private get _seconds() {
return this.data && this.data.seconds ? Number(this.data.seconds) : 0;
}
private get _milliseconds() {
return this.data && this.data.milliseconds
? Number(this.data.milliseconds)
: 0;
}
private _parseDuration(value) {
return value.toString().padStart(2, "0");
}
private _parseDurationMillisec(value) {
return value.toString().padStart(3, "0");
}
private _hourChanged(ev) {
this._durationChanged(ev, "hours");
}
private _minChanged(ev) {
this._durationChanged(ev, "minutes");
}
private _secChanged(ev) {
this._durationChanged(ev, "seconds");
}
private _millisecChanged(ev) {
this._durationChanged(ev, "milliseconds");
}
private _durationChanged(ev, unit) {
let value = Number(ev.detail.value);
if (value === this[`_${unit}`]) {
return;
}
let hours = this._hours;
let minutes = this._minutes;
if (unit === "seconds" && value > 59) {
minutes += Math.floor(value / 60);
value %= 60;
}
if (unit === "minutes" && value > 59) {
hours += Math.floor(value / 60);
value %= 60;
}
fireEvent(this, "value-changed", {
value: {
hours,
minutes,
seconds: this._seconds,
milliseconds: this._milliseconds,
...{ [unit]: value },
},
});
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-duration-input": HaDurationInput;
}
}

View File

@ -1,6 +1,6 @@
import { html, LitElement, TemplateResult } from "lit";
import { customElement, property, query } from "lit/decorators";
import "../ha-time-input";
import "../ha-duration-input";
import { HaFormElement, HaFormTimeData, HaFormTimeSchema } from "./ha-form";
@customElement("ha-form-positive_time_period_dict")
@ -23,11 +23,11 @@ export class HaFormTimePeriod extends LitElement implements HaFormElement {
protected render(): TemplateResult {
return html`
<ha-time-input
<ha-duration-input
.label=${this.label}
.required=${this.schema.required}
.data=${this.data}
></ha-time-input>
></ha-duration-input>
`;
}
}

View File

@ -2,7 +2,7 @@ import { css, CSSResultGroup, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { dynamicElement } from "../../common/dom/dynamic-element-directive";
import { fireEvent } from "../../common/dom/fire_event";
import { HaTimeData } from "../ha-time-input";
import { HaDurationData } from "../ha-duration-input";
import "./ha-form-boolean";
import "./ha-form-constant";
import "./ha-form-float";
@ -88,7 +88,7 @@ export type HaFormFloatData = number;
export type HaFormBooleanData = boolean;
export type HaFormSelectData = string;
export type HaFormMultiSelectData = string[];
export type HaFormTimeData = HaTimeData;
export type HaFormTimeData = HaDurationData;
export interface HaFormElement extends LitElement {
schema: HaFormSchema | HaFormSchema[];

View File

@ -1,4 +1,4 @@
import { css, LitElement, PropertyValues, svg } from "lit";
import { css, LitElement, PropertyValues, svg, TemplateResult } from "lit";
import { customElement, property, state } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import { styleMap } from "lit/directives/style-map";
@ -75,9 +75,22 @@ export class Gauge extends LitElement {
this.levels
? this.levels
.sort((a, b) => a.level - b.level)
.map((level) => {
.map((level, idx) => {
let firstPath: TemplateResult | undefined;
if (idx === 0 && level.level !== this.min) {
const angle = getAngle(this.min, this.min, this.max);
firstPath = svg`<path
stroke="var(--info-color)"
class="level"
d="M
${50 - 40 * Math.cos((angle * Math.PI) / 180)}
${50 - 40 * Math.sin((angle * Math.PI) / 180)}
A 40 40 0 0 1 90 50
"
></path>`;
}
const angle = getAngle(level.level, this.min, this.max);
return svg`<path
return svg`${firstPath}<path
stroke="${level.stroke}"
class="level"
d="M

View File

@ -98,6 +98,11 @@ class HaHLSPlayer extends LitElement {
const Hls: typeof HlsType = (await import("hls.js/dist/hls.light.min"))
.default;
if (!this.isConnected) {
return;
}
let hlsSupported = Hls.isSupported();
if (!hlsSupported) {
@ -115,6 +120,10 @@ class HaHLSPlayer extends LitElement {
const useExoPlayer = await useExoPlayerPromise;
const masterPlaylist = await (await masterPlaylistPromise).text();
if (!this.isConnected) {
return;
}
// Parse playlist assuming it is a master playlist. Match group 1 is whether hevc, match group 2 is regular playlist url
// See https://tools.ietf.org/html/rfc8216 for HLS spec details
const playlistRegexp =

View File

@ -1,12 +1,8 @@
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import memoizeOne from "memoize-one";
import { useAmPm } from "../../common/datetime/use_am_pm";
import { fireEvent } from "../../common/dom/fire_event";
import { TimeSelector } from "../../data/selector";
import { FrontendLocaleData } from "../../data/translation";
import { HomeAssistant } from "../../types";
import "../paper-time-input";
import "../ha-time-input";
@customElement("ha-selector-time")
export class HaTimeSelector extends LitElement {
@ -20,51 +16,17 @@ export class HaTimeSelector extends LitElement {
@property({ type: Boolean }) public disabled = false;
private _useAmPmMem = memoizeOne((locale: FrontendLocaleData): boolean =>
useAmPm(locale)
);
protected render() {
const useAMPM = this._useAmPmMem(this.hass.locale);
const parts = this.value?.split(":") || [];
const hours = parts[0];
return html`
<paper-time-input
.label=${this.label}
.hour=${hours &&
(useAMPM && Number(hours) > 12 ? Number(hours) - 12 : hours)}
.min=${parts[1]}
.sec=${parts[2]}
.format=${useAMPM ? 12 : 24}
.amPm=${useAMPM && (Number(hours) > 12 ? "PM" : "AM")}
<ha-time-input
.value=${this.value}
.locale=${this.hass.locale}
.disabled=${this.disabled}
@change=${this._timeChanged}
@am-pm-changed=${this._timeChanged}
hide-label
enable-second
></paper-time-input>
></ha-time-input>
`;
}
private _timeChanged(ev) {
let value = ev.target.value;
const useAMPM = this._useAmPmMem(this.hass.locale);
let hours = Number(ev.target.hour || 0);
if (value && useAMPM) {
if (ev.target.amPm === "PM") {
hours += 12;
}
value = `${hours}:${ev.target.min || "00"}:${ev.target.sec || "00"}`;
}
if (value === this.value) {
return;
}
fireEvent(this, "value-changed", {
value,
});
}
}
declare global {

View File

@ -19,14 +19,14 @@ class HaSlider extends PaperSliderClass {
}
.pin > .slider-knob > .slider-knob-inner {
font-size: var(--ha-slider-pin-font-size, 10px);
font-size: var(--ha-slider-pin-font-size, 15px);
line-height: normal;
cursor: pointer;
}
.disabled.ring > .slider-knob > .slider-knob-inner {
background-color: var(--paper-slider-disabled-knob-color, var(--paper-grey-400));
border: 2px solid var(--paper-slider-disabled-knob-color, var(--paper-grey-400));
background-color: var(--paper-slider-disabled-knob-color, var(--disabled-text-color));
border: 2px solid var(--paper-slider-disabled-knob-color, var(--disabled-text-color));
}
.pin > .slider-knob > .slider-knob-inner::before {

View File

@ -1,134 +1,78 @@
import { html, LitElement, TemplateResult } from "lit";
import { customElement, property, query } from "lit/decorators";
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
import { useAmPm } from "../common/datetime/use_am_pm";
import { fireEvent } from "../common/dom/fire_event";
import "./paper-time-input";
export interface HaTimeData {
hours?: number;
minutes?: number;
seconds?: number;
milliseconds?: number;
}
import { FrontendLocaleData } from "../data/translation";
@customElement("ha-time-input")
class HaTimeInput extends LitElement {
@property() public data!: HaTimeData;
export class HaTimeInput extends LitElement {
@property() public locale!: FrontendLocaleData;
@property() public value?: string;
@property() public label?: string;
@property() public suffix?: string;
@property({ type: Boolean }) public disabled = false;
@property({ type: Boolean }) public required?: boolean;
@property({ type: Boolean, attribute: "hide-label" }) public hideLabel =
false;
@property({ type: Boolean }) public enableMillisecond?: boolean;
@property({ type: Boolean, attribute: "enable-second" })
public enableSecond = false;
@query("paper-time-input", true) private _input?: HTMLElement;
protected render() {
const useAMPM = useAmPm(this.locale);
public focus() {
if (this._input) {
this._input.focus();
const parts = this.value?.split(":") || [];
let hours = parts[0];
const numberHours = Number(parts[0]);
if (numberHours && useAMPM && numberHours > 12) {
hours = String(numberHours - 12).padStart(2, "0");
}
if (useAMPM && numberHours === 0) {
hours = "12";
}
}
protected render(): TemplateResult {
return html`
<paper-time-input
.label=${this.label}
.required=${this.required}
.autoValidate=${this.required}
error-message="Required"
enable-second
.enableMillisecond=${this.enableMillisecond}
format="24"
.hour=${this._parseDuration(this._hours)}
.min=${this._parseDuration(this._minutes)}
.sec=${this._parseDuration(this._seconds)}
.millisec=${this._parseDurationMillisec(this._milliseconds)}
@hour-changed=${this._hourChanged}
@min-changed=${this._minChanged}
@sec-changed=${this._secChanged}
@millisec-changed=${this._millisecChanged}
float-input-labels
no-hours-limit
always-float-input-labels
hour-label="hh"
min-label="mm"
sec-label="ss"
millisec-label="ms"
.hour=${hours}
.min=${parts[1]}
.sec=${parts[2]}
.format=${useAMPM ? 12 : 24}
.amPm=${useAMPM && (numberHours >= 12 ? "PM" : "AM")}
.disabled=${this.disabled}
@change=${this._timeChanged}
@am-pm-changed=${this._timeChanged}
.hideLabel=${this.hideLabel}
.enableSecond=${this.enableSecond}
></paper-time-input>
`;
}
private get _hours() {
return this.data && this.data.hours ? Number(this.data.hours) : 0;
}
private get _minutes() {
return this.data && this.data.minutes ? Number(this.data.minutes) : 0;
}
private get _seconds() {
return this.data && this.data.seconds ? Number(this.data.seconds) : 0;
}
private get _milliseconds() {
return this.data && this.data.milliseconds
? Number(this.data.milliseconds)
: 0;
}
private _parseDuration(value) {
return value.toString().padStart(2, "0");
}
private _parseDurationMillisec(value) {
return value.toString().padStart(3, "0");
}
private _hourChanged(ev) {
this._durationChanged(ev, "hours");
}
private _minChanged(ev) {
this._durationChanged(ev, "minutes");
}
private _secChanged(ev) {
this._durationChanged(ev, "seconds");
}
private _millisecChanged(ev) {
this._durationChanged(ev, "milliseconds");
}
private _durationChanged(ev, unit) {
let value = Number(ev.detail.value);
if (value === this[`_${unit}`]) {
private _timeChanged(ev) {
let value = ev.target.value;
const useAMPM = useAmPm(this.locale);
let hours = Number(ev.target.hour || 0);
if (value && useAMPM) {
if (ev.target.amPm === "PM" && hours < 12) {
hours += 12;
}
if (ev.target.amPm === "AM" && hours === 12) {
hours = 0;
}
value = `${hours.toString().padStart(2, "0")}:${ev.target.min || "00"}:${
ev.target.sec || "00"
}`;
}
if (value === this.value) {
return;
}
let hours = this._hours;
let minutes = this._minutes;
if (unit === "seconds" && value > 59) {
minutes += Math.floor(value / 60);
value %= 60;
}
if (unit === "minutes" && value > 59) {
hours += Math.floor(value / 60);
value %= 60;
}
this.value = value;
fireEvent(this, "change");
fireEvent(this, "value-changed", {
value: {
hours,
minutes,
seconds: this._seconds,
milliseconds: this._milliseconds,
...{ [unit]: value },
},
value,
});
}
}

View File

@ -5,7 +5,6 @@ import { classMap } from "lit/directives/class-map";
import { formatDateTimeWithSeconds } from "../../common/datetime/format_date_time";
import "../ha-code-editor";
import "../ha-icon-button";
import type { NodeInfo } from "./hat-graph";
import "./hat-logbook-note";
import { LogbookEntry } from "../../data/logbook";
import {
@ -17,6 +16,7 @@ import {
import "../../panels/logbook/ha-logbook";
import { traceTabStyles } from "./trace-tab-styles";
import { HomeAssistant } from "../../types";
import type { NodeInfo } from "./hat-script-graph";
@customElement("ha-trace-path-details")
export class HaTracePathDetails extends LitElement {
@ -30,7 +30,7 @@ export class HaTracePathDetails extends LitElement {
@property({ attribute: false }) public selected!: NodeInfo;
@property() renderedNodes: Record<string, any> = {};
@property() public renderedNodes: Record<string, any> = {};
@property() public trackedNodes!: Record<string, any>;

View File

@ -1,11 +1,11 @@
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import type { NodeInfo } from "./hat-graph";
import "./hat-logbook-note";
import "./hat-trace-timeline";
import type { LogbookEntry } from "../../data/logbook";
import type { TraceExtended } from "../../data/trace";
import type { HomeAssistant } from "../../types";
import type { NodeInfo } from "./hat-script-graph";
@customElement("ha-trace-timeline")
export class HaTraceTimeline extends LitElement {
@ -15,7 +15,7 @@ export class HaTraceTimeline extends LitElement {
@property({ attribute: false }) public logbookEntries!: LogbookEntry[];
@property() public selected!: NodeInfo;
@property({ attribute: false }) public selected!: NodeInfo;
protected render(): TemplateResult {
return html`

View File

@ -0,0 +1,186 @@
import { css, html, LitElement, svg } from "lit";
import { customElement, property, state } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { BRANCH_HEIGHT, SPACING } from "./hat-graph-const";
interface BranchConfig {
x: number;
height: number;
start: boolean;
end: boolean;
track: boolean;
}
/**
* @attribute active
* @attribute track
*/
@customElement("hat-graph-branch")
export class HatGraphBranch extends LitElement {
@property({ reflect: true, type: Boolean }) disabled?: boolean;
@property({ type: Boolean }) selected?: boolean;
@property({ type: Boolean }) start = false;
@property({ type: Boolean }) short = false;
@state() _branches: BranchConfig[] = [];
private _totalWidth = 0;
private _maxHeight = 0;
private _updateBranches(ev: Event) {
let total_width = 0;
const heights: number[] = [];
const branches: BranchConfig[] = [];
(ev.target as HTMLSlotElement).assignedElements().forEach((c) => {
const width = c.clientWidth;
const height = c.clientHeight;
branches.push({
x: width / 2 + total_width,
height,
start: c.hasAttribute("graphStart"),
end: c.hasAttribute("graphEnd"),
track: c.hasAttribute("track"),
});
total_width += width;
heights.push(height);
});
this._totalWidth = total_width;
this._maxHeight = Math.max(...heights);
this._branches = branches.sort((a, b) => {
if (a.track && !b.track) {
return 1;
}
if (a.track && b.track) {
return 0;
}
return -1;
});
}
render() {
return html`
<slot name="head"></slot>
${!this.start
? svg`
<svg
id="top"
width="${this._totalWidth}"
>
${this._branches.map((branch) =>
branch.start
? ""
: svg`
<path
class=${classMap({
track: branch.track,
})}
d="
M ${this._totalWidth / 2} 0
L ${branch.x} ${BRANCH_HEIGHT}
"/>
`
)}
</svg>
`
: ""}
<div id="branches">
<svg id="lines" width="${this._totalWidth}" height="${this._maxHeight}">
${this._branches.map((branch) => {
if (branch.end) return "";
return svg`
<path
class=${classMap({
track: branch.track,
})}
d="
M ${branch.x} ${branch.height}
v ${this._maxHeight - branch.height}
"/>
`;
})}
</svg>
<slot @slotchange=${this._updateBranches}></slot>
</div>
${!this.short
? svg`
<svg
id="bottom"
width="${this._totalWidth}"
>
${this._branches.map((branch) => {
if (branch.end) return "";
return svg`
<path
class=${classMap({
track: branch.track,
})}
d="
M ${branch.x} 0
V ${SPACING}
L ${this._totalWidth / 2} ${BRANCH_HEIGHT + SPACING}
"/>
`;
})}
</svg>
`
: ""}
`;
}
static get styles() {
return css`
:host {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
}
:host(:focus) {
outline: none;
}
#branches {
position: relative;
display: flex;
flex-direction: row;
align-items: start;
}
::slotted(*) {
z-index: 1;
}
::slotted([slot="head"]) {
margin-bottom: calc(var(--hat-graph-branch-height) / -2);
}
#lines {
position: absolute;
}
#top {
height: var(--hat-graph-branch-height);
}
#bottom {
height: calc(var(--hat-graph-branch-height) + var(--hat-graph-spacing));
}
path {
stroke: var(--stroke-clr);
stroke-width: 2;
fill: none;
}
path.track {
stroke: var(--track-clr);
}
:host([disabled]) path {
stroke: var(--disabled-clr);
}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"hat-graph-branch": HatGraphBranch;
}
}

View File

@ -0,0 +1,3 @@
export const SPACING = 10;
export const NODE_SIZE = 30;
export const BRANCH_HEIGHT = 20;

View File

@ -1,7 +1,18 @@
import { css, LitElement, svg } from "lit";
import {
css,
LitElement,
PropertyValues,
html,
TemplateResult,
svg,
} from "lit";
import { customElement, property } from "lit/decorators";
import { NODE_SIZE, SPACING } from "./hat-graph";
import { NODE_SIZE, SPACING } from "./hat-graph-const";
/**
* @attribute active
* @attribute track
*/
@customElement("hat-graph-node")
export class HatGraphNode extends LitElement {
@property() iconPath?: string;
@ -10,31 +21,30 @@ export class HatGraphNode extends LitElement {
@property({ reflect: true, type: Boolean }) graphStart?: boolean;
@property({ reflect: true, type: Boolean }) nofocus?: boolean;
@property({ type: Boolean, attribute: "nofocus" }) noFocus = false;
@property({ reflect: true, type: Number }) badge?: number;
connectedCallback() {
super.connectedCallback();
if (!this.hasAttribute("tabindex") && !this.nofocus)
this.setAttribute("tabindex", "0");
protected updated(changedProps: PropertyValues) {
if (changedProps.has("noFocus")) {
if (!this.hasAttribute("tabindex") && !this.noFocus) {
this.setAttribute("tabindex", "0");
} else if (changedProps.get("noFocus") !== undefined && this.noFocus) {
this.removeAttribute("tabindex");
}
}
}
render() {
protected render(): TemplateResult {
const height = NODE_SIZE + (this.graphStart ? 2 : SPACING + 1);
const width = SPACING + NODE_SIZE;
return svg`
<svg
width="${width}px"
height="${height}px"
viewBox="-${Math.ceil(width / 2)} -${
this.graphStart
? Math.ceil(height / 2)
: Math.ceil((NODE_SIZE + SPACING * 2) / 2)
} ${width} ${height}"
>
${
this.graphStart
return html`
<svg
viewBox="-${Math.ceil(width / 2)} -${this.graphStart
? Math.ceil(height / 2)
: Math.ceil((NODE_SIZE + SPACING * 2) / 2)} ${width} ${height}"
>
${this.graphStart
? ``
: svg`
<path
@ -45,41 +55,31 @@ export class HatGraphNode extends LitElement {
"
line-caps="round"
/>
`
}
<g class="node">
<circle
cx="0"
cy="0"
r="${NODE_SIZE / 2}"
/>
}
${
this.badge
? svg`
`}
<g class="node">
<circle cx="0" cy="0" r=${NODE_SIZE / 2} />
}
${this.badge
? svg`
<g class="number">
<circle
cx="8"
cy="${-NODE_SIZE / 2}"
cy=${-NODE_SIZE / 2}
r="8"
></circle>
<text
x="8"
y="${-NODE_SIZE / 2}"
y=${-NODE_SIZE / 2}
text-anchor="middle"
alignment-baseline="middle"
>${this.badge > 9 ? "9+" : this.badge}</text>
</g>
`
: ""
}
<g
style="pointer-events: none"
transform="translate(${-12} ${-12})"
>
${this.iconPath ? svg`<path class="icon" d="${this.iconPath}"/>` : ""}
</g>
</g>
: ""}
<g style="pointer-events: none" transform="translate(${-12} ${-12})">
${this.iconPath ? svg`<path class="icon" d=${this.iconPath}/>` : ""}
</g>
</g>
</svg>
`;
}
@ -89,12 +89,19 @@ export class HatGraphNode extends LitElement {
:host {
display: flex;
flex-direction: column;
width: calc(var(--hat-graph-node-size) + var(--hat-graph-spacing));
height: calc(
var(--hat-graph-node-size) + var(--hat-graph-spacing) + 1px
);
}
:host(.track) {
:host([graphStart]) {
height: calc(var(--hat-graph-node-size) + 2px);
}
:host([track]) {
--stroke-clr: var(--track-clr);
--icon-clr: var(--default-icon-clr);
}
:host(.active) circle {
:host([active]) circle {
--stroke-clr: var(--active-clr);
--icon-clr: var(--default-icon-clr);
}
@ -108,13 +115,9 @@ export class HatGraphNode extends LitElement {
:host([disabled]) circle {
stroke: var(--disabled-clr);
}
:host-context([disabled]) {
--stroke-clr: var(--disabled-clr);
}
:host([nofocus]):host-context(.active),
:host([nofocus]):host-context(:focus) {
--circle-clr: var(--active-clr);
--icon-clr: var(--default-icon-clr);
svg {
width: 100%;
height: 100%;
}
circle,
path.connector {
@ -137,24 +140,6 @@ export class HatGraphNode extends LitElement {
path.icon {
fill: var(--icon-clr);
}
:host(.triggered) svg {
overflow: visible;
}
:host(.triggered) circle {
animation: glow 10s;
}
@keyframes glow {
0% {
filter: drop-shadow(0px 0px 5px rgba(var(--rgb-trigger-color), 0));
}
10% {
filter: drop-shadow(0px 0px 10px rgba(var(--rgb-trigger-color), 1));
}
100% {
filter: drop-shadow(0px 0px 5px rgba(var(--rgb-trigger-color), 0));
}
}
`;
}
}

View File

@ -1,27 +1,26 @@
import { css, LitElement, svg } from "lit";
import { css, LitElement, html } from "lit";
import { customElement, property } from "lit/decorators";
import { NODE_SIZE, SPACING } from "./hat-graph";
import { SPACING, NODE_SIZE } from "./hat-graph-const";
/**
* @attribute active
* @attribute track
*/
@customElement("hat-graph-spacer")
export class HatGraphSpacer extends LitElement {
@property({ reflect: true, type: Boolean }) disabled?: boolean;
render() {
return svg`
<svg
width="${SPACING}px"
height="${SPACING + NODE_SIZE + 1}px"
viewBox="-${SPACING / 2} 0 10 ${SPACING + NODE_SIZE + 1}"
>
<path
class="connector"
d="
return html`
<svg viewBox="-${SPACING / 2} 0 10 ${SPACING + NODE_SIZE + 1}">
<path
d="
M 0 ${SPACING + NODE_SIZE + 1}
L 0 0
V 0
"
line-caps="round"
/>
}
line-caps="round"
/>
}
</svg>
`;
}
@ -31,15 +30,21 @@ export class HatGraphSpacer extends LitElement {
:host {
display: flex;
flex-direction: column;
align-items: center;
}
:host(.track) {
svg {
width: var(--hat-graph-spacing);
height: calc(
var(--hat-graph-spacing) + var(--hat-graph-node-size) + 1px
);
}
:host([track]) {
--stroke-clr: var(--track-clr);
--icon-clr: var(--default-icon-clr);
}
:host-context([disabled]) {
--stroke-clr: var(--disabled-clr);
}
path.connector {
path {
stroke: var(--stroke-clr);
stroke-width: 2;
fill: none;

View File

@ -1,219 +0,0 @@
import { css, html, LitElement, svg } from "lit";
import { customElement, property } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
export const BRANCH_HEIGHT = 20;
export const SPACING = 10;
export const NODE_SIZE = 30;
const track_converter = {
fromAttribute: (value) => value.split(",").map((v) => parseInt(v)),
toAttribute: (value) =>
value instanceof Array ? value.join(",") : `${value}`,
};
export interface NodeInfo {
path: string;
config: any;
}
interface BranchConfig {
x: number;
height: number;
start: boolean;
end: boolean;
}
@customElement("hat-graph")
export class HatGraph extends LitElement {
@property({ type: Number }) _num_items = 0;
@property({ reflect: true, type: Boolean }) branching?: boolean;
@property({ converter: track_converter })
track_start?: number[];
@property({ converter: track_converter }) track_end?: number[];
@property({ reflect: true, type: Boolean }) disabled?: boolean;
@property({ type: Boolean }) selected?: boolean;
@property({ type: Boolean }) short = false;
async updateChildren() {
this._num_items = this.children.length;
}
render() {
const branches: BranchConfig[] = [];
let total_width = 0;
let max_height = 0;
let min_height = Number.POSITIVE_INFINITY;
if (this.branching) {
for (const c of Array.from(this.children)) {
if (c.slot === "head") continue;
const rect = c.getBoundingClientRect();
branches.push({
x: rect.width / 2 + total_width,
height: rect.height,
start: c.getAttribute("graphStart") != null,
end: c.getAttribute("graphEnd") != null,
});
total_width += rect.width;
max_height = Math.max(max_height, rect.height);
min_height = Math.min(min_height, rect.height);
}
}
return html`
<slot name="head" @slotchange=${this.updateChildren}> </slot>
${this.branching && branches.some((branch) => !branch.start)
? svg`
<svg
id="top"
width="${total_width}"
height="${BRANCH_HEIGHT}"
>
${branches.map((branch, i) => {
if (branch.start) return "";
return svg`
<path
class="${classMap({
line: true,
track: this.track_start?.includes(i) ?? false,
})}"
id="${this.track_start?.includes(i) ? "track-start" : ""}"
index=${i}
d="
M ${total_width / 2} 0
L ${branch.x} ${BRANCH_HEIGHT}
"/>
`;
})}
<use xlink:href="#track-start" />
</svg>
`
: ""}
<div id="branches">
${this.branching
? svg`
<svg
id="lines"
width="${total_width}"
height="${max_height}"
>
${branches.map((branch, i) => {
if (branch.end) return "";
return svg`
<path
class="${classMap({
line: true,
track: this.track_end?.includes(i) ?? false,
})}"
index=${i}
d="
M ${branch.x} ${branch.height}
l 0 ${max_height - branch.height}
"/>
`;
})}
</svg>
`
: ""}
<slot @slotchange=${this.updateChildren}></slot>
</div>
${this.branching && !this.short
? svg`
<svg
id="bottom"
width="${total_width}"
height="${BRANCH_HEIGHT + SPACING}"
>
${branches.map((branch, i) => {
if (branch.end) return "";
return svg`
<path
class="${classMap({
line: true,
track: this.track_end?.includes(i) ?? false,
})}"
id="${this.track_end?.includes(i) ? "track-end" : ""}"
index=${i}
d="
M ${branch.x} 0
L ${branch.x} ${SPACING}
L ${total_width / 2} ${BRANCH_HEIGHT + SPACING}
"/>
`;
})}
<use xlink:href="#track-end" />
</svg>
`
: ""}
`;
}
static get styles() {
return css`
:host {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
--stroke-clr: var(--stroke-color, var(--secondary-text-color));
--active-clr: var(--active-color, var(--primary-color));
--track-clr: var(--track-color, var(--accent-color));
--hover-clr: var(--hover-color, var(--primary-color));
--disabled-clr: var(--disabled-color, var(--disabled-text-color));
--default-trigger-color: 3, 169, 244;
--rgb-trigger-color: var(--trigger-color, var(--default-trigger-color));
--background-clr: var(--background-color, white);
--default-icon-clr: var(--icon-color, black);
--icon-clr: var(--stroke-clr);
}
:host(:focus) {
outline: none;
}
#branches {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
}
:host([branching]) #branches {
flex-direction: row;
align-items: start;
}
:host([branching]) ::slotted(*) {
z-index: 1;
}
:host([branching]) ::slotted([slot="head"]) {
margin-bottom: ${-BRANCH_HEIGHT / 2}px;
}
#lines {
position: absolute;
}
path.line {
stroke: var(--stroke-clr);
stroke-width: 2;
fill: none;
}
path.line.track {
stroke: var(--track-clr);
}
:host([disabled]) path.line {
stroke: var(--disabled-clr);
}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"hat-graph": HatGraph;
}
}

View File

@ -19,7 +19,6 @@ import {
} from "@mdi/js";
import { css, html, LitElement, PropertyValues } from "lit";
import { customElement, property } from "lit/decorators";
import { classMap } from "lit/directives/class-map";
import { fireEvent } from "../../common/dom/fire_event";
import { ensureArray } from "../../common/ensure-array";
import { Condition, Trigger } from "../../data/automation";
@ -41,9 +40,15 @@ import {
TraceExtended,
} from "../../data/trace";
import "../ha-svg-icon";
import { NodeInfo, NODE_SIZE, SPACING } from "./hat-graph";
import "./hat-graph-node";
import "./hat-graph-spacer";
import "./hat-graph-branch";
import { NODE_SIZE, SPACING, BRANCH_HEIGHT } from "./hat-graph-const";
export interface NodeInfo {
path: string;
config: any;
}
declare global {
interface HASSDomEvents {
@ -52,14 +57,14 @@ declare global {
}
@customElement("hat-script-graph")
class HatScriptGraph extends LitElement {
export class HatScriptGraph extends LitElement {
@property({ attribute: false }) public trace!: TraceExtended;
@property({ attribute: false }) public selected;
@property({ attribute: false }) public selected?: string;
@property() renderedNodes: Record<string, any> = {};
public renderedNodes: Record<string, NodeInfo> = {};
@property() trackedNodes: Record<string, any> = {};
public trackedNodes: Record<string, NodeInfo> = {};
private selectNode(config, path) {
return () => {
@ -69,72 +74,54 @@ class HatScriptGraph extends LitElement {
private render_trigger(config: Trigger, i: number) {
const path = `trigger/${i}`;
const tracked = this.trace && path in this.trace.trace;
const track = this.trace && path in this.trace.trace;
this.renderedNodes[path] = { config, path };
if (tracked) {
if (track) {
this.trackedNodes[path] = this.renderedNodes[path];
}
return html`
<hat-graph-node
graphStart
?track=${track}
@focus=${this.selectNode(config, path)}
class=${classMap({
track: tracked,
active: this.selected === path,
})}
?active=${this.selected === path}
.iconPath=${mdiAsterisk}
tabindex=${tracked ? "0" : "-1"}
tabindex=${track ? "0" : "-1"}
></hat-graph-node>
`;
}
private render_condition(config: Condition, i: number) {
const path = `condition/${i}`;
const trace = this.trace.trace[path] as ConditionTraceStep[] | undefined;
const track_path =
trace?.[0].result === undefined ? 0 : trace[0].result.result ? 1 : 2;
this.renderedNodes[path] = { config, path };
if (trace) {
if (this.trace && path in this.trace.trace) {
this.trackedNodes[path] = this.renderedNodes[path];
}
return html`
<hat-graph
branching
@focus=${this.selectNode(config, path)}
class=${classMap({
track: track_path,
active: this.selected === path,
})}
.track_start=${[track_path]}
.track_end=${[track_path]}
tabindex=${trace ? "-1" : "0"}
short
>
<hat-graph-node
slot="head"
class=${classMap({
track: trace !== undefined,
})}
.iconPath=${mdiAbTesting}
nofocus
graphEnd
></hat-graph-node>
<div
style=${`width: ${NODE_SIZE + SPACING}px;`}
graphStart
graphEnd
></div>
<div></div>
<hat-graph-node
.iconPath=${mdiClose}
graphEnd
nofocus
class=${classMap({
track: track_path === 2,
})}
></hat-graph-node>
</hat-graph>
`;
return this.render_condition_node(config, path);
}
private typeRenderers = {
condition: this.render_condition_node,
delay: this.render_delay_node,
event: this.render_event_node,
scene: this.render_scene_node,
service: this.render_service_node,
wait_template: this.render_wait_node,
wait_for_trigger: this.render_wait_node,
repeat: this.render_repeat_node,
choose: this.render_choose_node,
device_id: this.render_device_node,
other: this.render_other_node,
};
private render_action_node(node: Action, path: string, graphStart = false) {
const type =
Object.keys(this.typeRenderers).find((key) => key in node) || "other";
this.renderedNodes[path] = { config: node, path };
if (this.trace && path in this.trace.trace) {
this.trackedNodes[path] = this.renderedNodes[path];
}
return this.typeRenderers[type].bind(this)(node, path, graphStart);
}
private render_choose_node(
@ -143,30 +130,26 @@ class HatScriptGraph extends LitElement {
graphStart = false
) {
const trace = this.trace.trace[path] as ChooseActionTraceStep[] | undefined;
const trace_path =
trace !== undefined
? trace[0].result === undefined || trace[0].result.choice === "default"
? [Array.isArray(config.choose) ? config.choose.length : 0]
: [trace[0].result.choice]
: [];
const trace_path = trace
? trace.map((trc) =>
trc.result === undefined || trc.result.choice === "default"
? "default"
: trc.result.choice
)
: [];
const track_default = trace_path.includes("default");
return html`
<hat-graph
<hat-graph-branch
tabindex=${trace === undefined ? "-1" : "0"}
branching
.track_start=${trace_path}
.track_end=${trace_path}
@focus=${this.selectNode(config, path)}
class=${classMap({
track: trace !== undefined,
active: this.selected === path,
})}
?track=${trace !== undefined}
?active=${this.selected === path}
>
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiCallSplit}
class=${classMap({
track: trace !== undefined,
})}
?track=${trace !== undefined}
?active=${this.selected === path}
slot="head"
nofocus
></hat-graph-node>
@ -174,46 +157,39 @@ class HatScriptGraph extends LitElement {
${config.choose
? ensureArray(config.choose)?.map((branch, i) => {
const branch_path = `${path}/choose/${i}`;
const track_this =
trace !== undefined && trace[0].result?.choice === i;
const track_this = trace_path.includes(i);
this.renderedNodes[branch_path] = { config, path: branch_path };
if (track_this) {
this.trackedNodes[branch_path] =
this.renderedNodes[branch_path];
}
return html`
<hat-graph>
<div class="graph-container" ?track=${track_this}>
<hat-graph-node
.iconPath=${!trace || track_this
? mdiCheckBoxOutline
: mdiCheckboxBlankOutline}
@focus=${this.selectNode(config, branch_path)}
class=${classMap({
active: this.selected === branch_path,
track: track_this,
})}
?track=${track_this}
?active=${this.selected === branch_path}
></hat-graph-node>
${ensureArray(branch.sequence).map((action, j) =>
this.render_node(action, `${branch_path}/sequence/${j}`)
this.render_action_node(
action,
`${branch_path}/sequence/${j}`
)
)}
</hat-graph>
</div>
`;
})
: ""}
<hat-graph>
<hat-graph-spacer
class=${classMap({
track:
trace !== undefined &&
(trace[0].result === undefined ||
trace[0].result.choice === "default"),
})}
></hat-graph-spacer>
<div ?track=${track_default}>
<hat-graph-spacer ?track=${track_default}></hat-graph-spacer>
${ensureArray(config.default)?.map((action, i) =>
this.render_node(action, `${path}/default/${i}`)
this.render_action_node(action, `${path}/default/${i}`)
)}
</hat-graph>
</hat-graph>
</div>
</hat-graph-branch>
`;
}
@ -222,41 +198,54 @@ class HatScriptGraph extends LitElement {
path: string,
graphStart = false
) {
const trace = (this.trace.trace[path] as ConditionTraceStep[]) || undefined;
const track_path =
trace?.[0].result === undefined ? 0 : trace[0].result.result ? 1 : 2;
const trace = this.trace.trace[path] as ConditionTraceStep[] | undefined;
let track = false;
let trackPass = false;
let trackFailed = false;
if (trace) {
for (const trc of trace) {
if (trc.result) {
track = true;
if (trc.result.result) {
trackPass = true;
} else {
trackFailed = true;
}
}
if (trackPass && trackFailed) {
break;
}
}
}
return html`
<hat-graph
branching
<hat-graph-branch
@focus=${this.selectNode(node, path)}
class=${classMap({
track: track_path,
active: this.selected === path,
})}
.track_start=${[track_path]}
.track_end=${[track_path]}
?track=${track}
?active=${this.selected === path}
tabindex=${trace === undefined ? "-1" : "0"}
short
>
<hat-graph-node
.graphStart=${graphStart}
slot="head"
class=${classMap({
track: Boolean(trace),
})}
?track=${track}
?active=${this.selected === path}
.iconPath=${mdiAbTesting}
nofocus
></hat-graph-node>
<div style=${`width: ${NODE_SIZE + SPACING}px;`}></div>
<div></div>
<div
style=${`width: ${NODE_SIZE + SPACING}px;`}
graphStart
graphEnd
></div>
<div ?track=${trackPass}></div>
<hat-graph-node
.iconPath=${mdiClose}
nofocus
class=${classMap({
track: track_path === 2,
})}
?track=${trackFailed}
?active=${this.selected === path}
></hat-graph-node>
</hat-graph>
</hat-graph-branch>
`;
}
@ -270,10 +259,8 @@ class HatScriptGraph extends LitElement {
.graphStart=${graphStart}
.iconPath=${mdiTimerOutline}
@focus=${this.selectNode(node, path)}
class=${classMap({
track: path in this.trace.trace,
active: this.selected === path,
})}
?track=${path in this.trace.trace}
?active=${this.selected === path}
tabindex=${this.trace && path in this.trace.trace ? "0" : "-1"}
></hat-graph-node>
`;
@ -289,10 +276,8 @@ class HatScriptGraph extends LitElement {
.graphStart=${graphStart}
.iconPath=${mdiDevices}
@focus=${this.selectNode(node, path)}
class=${classMap({
track: path in this.trace.trace,
active: this.selected === path,
})}
?track=${path in this.trace.trace}
?active=${this.selected === path}
tabindex=${this.trace && path in this.trace.trace ? "0" : "-1"}
></hat-graph-node>
`;
@ -308,10 +293,8 @@ class HatScriptGraph extends LitElement {
.graphStart=${graphStart}
.iconPath=${mdiExclamation}
@focus=${this.selectNode(node, path)}
class=${classMap({
track: path in this.trace.trace,
active: this.selected === path,
})}
?track=${path in this.trace.trace}
?active=${this.selected === path}
tabindex=${this.trace && path in this.trace.trace ? "0" : "-1"}
></hat-graph-node>
`;
@ -323,43 +306,35 @@ class HatScriptGraph extends LitElement {
graphStart = false
) {
const trace: any = this.trace.trace[path];
const track_path = trace ? [0, 1] : [];
const repeats = this.trace?.trace[`${path}/repeat/sequence/0`]?.length;
return html`
<hat-graph
.track_start=${track_path}
.track_end=${track_path}
<hat-graph-branch
tabindex=${trace === undefined ? "-1" : "0"}
branching
@focus=${this.selectNode(node, path)}
class=${classMap({
track: path in this.trace.trace,
active: this.selected === path,
})}
?track=${path in this.trace.trace}
?active=${this.selected === path}
>
<hat-graph-node
.graphStart=${graphStart}
.iconPath=${mdiRefresh}
class=${classMap({
track: trace,
})}
?track=${path in this.trace.trace}
?active=${this.selected === path}
slot="head"
nofocus
></hat-graph-node>
<hat-graph-node
.iconPath=${mdiArrowUp}
?track=${repeats > 1}
?active=${this.selected === path}
nofocus
class=${classMap({
track: track_path.includes(1),
})}
.badge=${repeats}
.badge=${repeats > 1 ? repeats : undefined}
></hat-graph-node>
<hat-graph>
<div ?track=${trace}>
${ensureArray(node.repeat.sequence).map((action, i) =>
this.render_node(action, `${path}/repeat/sequence/${i}`)
this.render_action_node(action, `${path}/repeat/sequence/${i}`)
)}
</hat-graph>
</hat-graph>
</div>
</hat-graph-branch>
`;
}
@ -373,10 +348,8 @@ class HatScriptGraph extends LitElement {
.graphStart=${graphStart}
.iconPath=${mdiExclamation}
@focus=${this.selectNode(node, path)}
class=${classMap({
track: path in this.trace.trace,
active: this.selected === path,
})}
?track=${path in this.trace.trace}
?active=${this.selected === path}
tabindex=${this.trace && path in this.trace.trace ? "0" : "-1"}
></hat-graph-node>
`;
@ -392,10 +365,8 @@ class HatScriptGraph extends LitElement {
.graphStart=${graphStart}
.iconPath=${mdiChevronRight}
@focus=${this.selectNode(node, path)}
class=${classMap({
track: path in this.trace.trace,
active: this.selected === path,
})}
?track=${path in this.trace.trace}
?active=${this.selected === path}
tabindex=${this.trace && path in this.trace.trace ? "0" : "-1"}
></hat-graph-node>
`;
@ -411,10 +382,8 @@ class HatScriptGraph extends LitElement {
.graphStart=${graphStart}
.iconPath=${mdiTrafficLight}
@focus=${this.selectNode(node, path)}
class=${classMap({
track: path in this.trace.trace,
active: this.selected === path,
})}
?track=${path in this.trace.trace}
?active=${this.selected === path}
tabindex=${this.trace && path in this.trace.trace ? "0" : "-1"}
></hat-graph-node>
`;
@ -426,95 +395,55 @@ class HatScriptGraph extends LitElement {
.graphStart=${graphStart}
.iconPath=${mdiCodeBrackets}
@focus=${this.selectNode(node, path)}
class=${classMap({
track: path in this.trace.trace,
active: this.selected === path,
})}
?track=${path in this.trace.trace}
?active=${this.selected === path}
></hat-graph-node>
`;
}
private render_node(node: Action, path: string, graphStart = false) {
const NODE_TYPES = {
choose: this.render_choose_node,
condition: this.render_condition_node,
delay: this.render_delay_node,
device_id: this.render_device_node,
event: this.render_event_node,
repeat: this.render_repeat_node,
scene: this.render_scene_node,
service: this.render_service_node,
wait_template: this.render_wait_node,
wait_for_trigger: this.render_wait_node,
other: this.render_other_node,
};
const type = Object.keys(NODE_TYPES).find((key) => key in node) || "other";
const nodeEl = NODE_TYPES[type].bind(this)(node, path, graphStart);
this.renderedNodes[path] = { config: node, path };
if (this.trace && path in this.trace.trace) {
this.trackedNodes[path] = this.renderedNodes[path];
}
return nodeEl;
}
protected render() {
const paths = Object.keys(this.trackedNodes);
const manual_triggered = this.trace && "trigger" in this.trace.trace;
let track_path = manual_triggered ? undefined : [0];
const trigger_nodes =
"trigger" in this.trace.config
? ensureArray(this.trace.config.trigger).map((trigger, i) => {
if (this.trace && `trigger/${i}` in this.trace.trace) {
track_path = [i];
}
return this.render_trigger(trigger, i);
})
? ensureArray(this.trace.config.trigger).map((trigger, i) =>
this.render_trigger(trigger, i)
)
: undefined;
try {
return html`
<hat-graph class="parent">
<div></div>
<div class="parent graph-container">
${trigger_nodes
? html`<hat-graph
branching
id="trigger"
.short=${trigger_nodes.length < 2}
.track_start=${track_path}
.track_end=${track_path}
>
? html`<hat-graph-branch start .short=${trigger_nodes.length < 2}>
${trigger_nodes}
</hat-graph>`
</hat-graph-branch>`
: ""}
${"condition" in this.trace.config
? html`<hat-graph id="condition">
${ensureArray(this.trace.config.condition)?.map(
(condition, i) => this.render_condition(condition!, i)
)}
</hat-graph>`
? html`${ensureArray(this.trace.config.condition)?.map(
(condition, i) => this.render_condition(condition, i)
)}`
: ""}
${"action" in this.trace.config
? html`${ensureArray(this.trace.config.action).map((action, i) =>
this.render_node(action, `action/${i}`)
this.render_action_node(action, `action/${i}`)
)}`
: ""}
${"sequence" in this.trace.config
? html`${ensureArray(this.trace.config.sequence).map((action, i) =>
this.render_node(action, `sequence/${i}`, i === 0)
this.render_action_node(action, `sequence/${i}`, i === 0)
)}`
: ""}
</hat-graph>
</div>
<div class="actions">
<mwc-icon-button
.disabled=${paths.length === 0 || paths[0] === this.selected}
@click=${this.previousTrackedNode}
@click=${this._previousTrackedNode}
>
<ha-svg-icon .path=${mdiChevronUp}></ha-svg-icon>
</mwc-icon-button>
<mwc-icon-button
.disabled=${paths.length === 0 ||
paths[paths.length - 1] === this.selected}
@click=${this.nextTrackedNode}
@click=${this._nextTrackedNode}
>
<ha-svg-icon .path=${mdiChevronDown}></ha-svg-icon>
</mwc-icon-button>
@ -545,44 +474,39 @@ class HatScriptGraph extends LitElement {
protected updated(changedProps: PropertyValues<this>) {
super.updated(changedProps);
// Select first node if new trace loaded but no selection given.
if (changedProps.has("trace")) {
const tracked = this.trackedNodes;
const paths = Object.keys(tracked);
if (!changedProps.has("trace")) {
return;
}
// If trace changed and we have no or an invalid selection, select first option.
if (this.selected === "" || !(this.selected in paths)) {
// Find first tracked node with node info
for (const path of paths) {
if (tracked[path]) {
fireEvent(this, "graph-node-selected", tracked[path]);
break;
}
// If trace changed and we have no or an invalid selection, select first option.
if (!this.selected || !(this.selected in this.trackedNodes)) {
const firstNode = this.trackedNodes[Object.keys(this.trackedNodes)[0]];
if (firstNode) {
fireEvent(this, "graph-node-selected", firstNode);
}
}
if (this.trace) {
const sortKeys = Object.keys(this.trace.trace);
const keys = Object.keys(this.renderedNodes).sort(
(a, b) => sortKeys.indexOf(a) - sortKeys.indexOf(b)
);
const sortedTrackedNodes = {};
const sortedRenderedNodes = {};
for (const key of keys) {
sortedRenderedNodes[key] = this.renderedNodes[key];
if (key in this.trackedNodes) {
sortedTrackedNodes[key] = this.trackedNodes[key];
}
}
if (this.trace) {
const sortKeys = Object.keys(this.trace.trace);
const keys = Object.keys(this.renderedNodes).sort(
(a, b) => sortKeys.indexOf(a) - sortKeys.indexOf(b)
);
const sortedTrackedNodes = {};
const sortedRenderedNodes = {};
for (const key of keys) {
sortedRenderedNodes[key] = this.renderedNodes[key];
if (key in this.trackedNodes) {
sortedTrackedNodes[key] = this.trackedNodes[key];
}
}
this.renderedNodes = sortedRenderedNodes;
this.trackedNodes = sortedTrackedNodes;
}
this.renderedNodes = sortedRenderedNodes;
this.trackedNodes = sortedTrackedNodes;
}
}
public previousTrackedNode() {
private _previousTrackedNode() {
const nodes = Object.keys(this.trackedNodes);
const prevIndex = nodes.indexOf(this.selected) - 1;
const prevIndex = nodes.indexOf(this.selected!) - 1;
if (prevIndex >= 0) {
fireEvent(
this,
@ -592,9 +516,9 @@ class HatScriptGraph extends LitElement {
}
}
public nextTrackedNode() {
private _nextTrackedNode() {
const nodes = Object.keys(this.trackedNodes);
const nextIndex = nodes.indexOf(this.selected) + 1;
const nextIndex = nodes.indexOf(this.selected!) + 1;
if (nextIndex < nodes.length) {
fireEvent(
this,
@ -608,6 +532,25 @@ class HatScriptGraph extends LitElement {
return css`
:host {
display: flex;
--stroke-clr: var(--stroke-color, var(--secondary-text-color));
--active-clr: var(--active-color, var(--primary-color));
--track-clr: var(--track-color, var(--accent-color));
--hover-clr: var(--hover-color, var(--primary-color));
--disabled-clr: var(--disabled-color, var(--disabled-text-color));
--default-trigger-color: 3, 169, 244;
--rgb-trigger-color: var(--trigger-color, var(--default-trigger-color));
--background-clr: var(--background-color, white);
--default-icon-clr: var(--icon-color, black);
--icon-clr: var(--stroke-clr);
--hat-graph-spacing: ${SPACING}px;
--hat-graph-node-size: ${NODE_SIZE}px;
--hat-graph-branch-height: ${BRANCH_HEIGHT}px;
}
.graph-container {
display: flex;
flex-direction: column;
align-items: center;
}
.actions {
display: flex;

View File

@ -46,9 +46,11 @@ export interface BlueprintAutomationConfig extends ManualAutomationConfig {
}
export interface ForDict {
hours?: number | string;
minutes?: number | string;
seconds?: number | string;
days?: number;
hours?: number;
minutes?: number;
seconds?: number;
milliseconds?: number;
}
export interface ContextConstraint {

View File

@ -1,4 +1,4 @@
import { HA_COLOR_PALETTE } from "../common/const";
import { getColorByIndex } from "../common/color/colors";
import { computeDomain } from "../common/entity/compute_domain";
import { computeStateName } from "../common/entity/compute_state_name";
import type { CalendarEvent, HomeAssistant } from "../types";
@ -81,5 +81,5 @@ export const getCalendars = (hass: HomeAssistant): Calendar[] =>
.map((eid, idx) => ({
entity_id: eid,
name: computeStateName(hass.states[eid]),
backgroundColor: `#${HA_COLOR_PALETTE[idx % HA_COLOR_PALETTE.length]}`,
backgroundColor: getColorByIndex(idx),
}));

View File

@ -36,17 +36,21 @@ export interface Stream {
export const computeMJPEGStreamUrl = (entity: CameraEntity) =>
`/api/camera_proxy_stream/${entity.entity_id}?token=${entity.attributes.access_token}`;
export const fetchThumbnailUrlWithCache = (
export const fetchThumbnailUrlWithCache = async (
hass: HomeAssistant,
entityId: string
) =>
timeCachePromiseFunc(
entityId: string,
width: number,
height: number
) => {
const base_url = await timeCachePromiseFunc(
"_cameraTmbUrl",
9000,
fetchThumbnailUrl,
hass,
entityId
);
return `${base_url}&width=${width}&height=${height}`;
};
export const fetchThumbnailUrl = async (
hass: HomeAssistant,

View File

@ -6,6 +6,7 @@ import { DataEntryFlowProgress, DataEntryFlowStep } from "./data_entry_flow";
import { domainToName } from "./integration";
export const DISCOVERY_SOURCES = [
"usb",
"unignore",
"dhcp",
"homekit",

View File

@ -6,6 +6,7 @@ import {
startOfYesterday,
} from "date-fns";
import { Collection, getCollection } from "home-assistant-js-websocket";
import { groupBy } from "../common/util/group-by";
import { subscribeOne } from "../common/util/subscribe-one";
import { HomeAssistant } from "../types";
import { ConfigEntry, getConfigEntries } from "./config_entries";
@ -47,6 +48,28 @@ export const emptySolarEnergyPreference =
config_entry_solar_forecast: null,
});
export const emptyBatteryEnergyPreference =
(): BatterySourceTypeEnergyPreference => ({
type: "battery",
stat_energy_from: "",
stat_energy_to: "",
});
export const emptyGasEnergyPreference = (): GasSourceTypeEnergyPreference => ({
type: "gas",
stat_energy_from: "",
stat_cost: null,
entity_energy_from: null,
entity_energy_price: null,
number_energy_price: null,
});
interface EnergySolarForecast {
wh_hours: Record<string, number>;
}
export type EnergySolarForecasts = {
[config_entry_id: string]: EnergySolarForecast;
};
export interface DeviceConsumptionEnergyPreference {
// This is an ever increasing value
stat_consumption: string;
@ -94,9 +117,31 @@ export interface SolarSourceTypeEnergyPreference {
config_entry_solar_forecast: string[] | null;
}
export interface BatterySourceTypeEnergyPreference {
type: "battery";
stat_energy_from: string;
stat_energy_to: string;
}
export interface GasSourceTypeEnergyPreference {
type: "gas";
// kWh meter
stat_energy_from: string;
// $ meter
stat_cost: string | null;
// Can be used to generate costs if stat_cost omitted
entity_energy_from: string | null;
entity_energy_price: string | null;
number_energy_price: number | null;
}
type EnergySource =
| SolarSourceTypeEnergyPreference
| GridSourceTypeEnergyPreference;
| GridSourceTypeEnergyPreference
| BatterySourceTypeEnergyPreference
| GasSourceTypeEnergyPreference;
export interface EnergyPreferences {
energy_sources: EnergySource[];
@ -105,6 +150,18 @@ export interface EnergyPreferences {
export interface EnergyInfo {
cost_sensors: Record<string, string>;
solar_forecast_domains: string[];
}
export interface EnergyValidationIssue {
type: string;
identifier: string;
value?: unknown;
}
export interface EnergyPreferencesValidation {
energy_sources: EnergyValidationIssue[][];
device_consumption: EnergyValidationIssue[][];
}
export const getEnergyInfo = (hass: HomeAssistant) =>
@ -112,6 +169,11 @@ export const getEnergyInfo = (hass: HomeAssistant) =>
type: "energy/info",
});
export const getEnergyPreferenceValidation = (hass: HomeAssistant) =>
hass.callWS<EnergyPreferencesValidation>({
type: "energy/validate",
});
export const getEnergyPreferences = (hass: HomeAssistant) =>
hass.callWS<EnergyPreferences>({
type: "energy/get_prefs",
@ -132,19 +194,12 @@ export const saveEnergyPreferences = async (
interface EnergySourceByType {
grid?: GridSourceTypeEnergyPreference[];
solar?: SolarSourceTypeEnergyPreference[];
battery?: BatterySourceTypeEnergyPreference[];
gas?: GasSourceTypeEnergyPreference[];
}
export const energySourcesByType = (prefs: EnergyPreferences) => {
const types: EnergySourceByType = {};
for (const source of prefs.energy_sources) {
if (source.type in types) {
types[source.type]!.push(source as any);
} else {
types[source.type] = [source as any];
}
}
return types;
};
export const energySourcesByType = (prefs: EnergyPreferences) =>
groupBy(prefs.energy_sources, (item) => item.type) as EnergySourceByType;
export interface EnergyData {
start: Date;
@ -203,6 +258,24 @@ const getEnergyData = async (
continue;
}
if (source.type === "gas") {
statIDs.push(source.stat_energy_from);
if (source.stat_cost) {
statIDs.push(source.stat_cost);
}
const costStatId = info.cost_sensors[source.stat_energy_from];
if (costStatId) {
statIDs.push(costStatId);
}
continue;
}
if (source.type === "battery") {
statIDs.push(source.stat_energy_from);
statIDs.push(source.stat_energy_to);
continue;
}
// grid source
for (const flowFrom of source.flow_from) {
statIDs.push(flowFrom.stat_energy_from);
@ -375,3 +448,8 @@ export const getEnergyDataCollection = (
};
return collection;
};
export const getEnergySolarForecasts = (hass: HomeAssistant) =>
hass.callWS<EnergySolarForecasts>({
type: "energy/solar_forecast",
});

View File

@ -1,10 +0,0 @@
import { HomeAssistant } from "../types";
export interface ForecastSolarForecast {
wh_hours: Record<string, number>;
}
export const getForecastSolarForecasts = (hass: HomeAssistant) =>
hass.callWS<Record<string, ForecastSolarForecast>>({
type: "forecast_solar/forecasts",
});

233
src/data/hassio/backup.ts Normal file
View File

@ -0,0 +1,233 @@
import { atLeastVersion } from "../../common/config/version";
import { HomeAssistant } from "../../types";
import { hassioApiResultExtractor, HassioResponse } from "./common";
export const friendlyFolderName = {
ssl: "SSL",
homeassistant: "Configuration",
"addons/local": "Local add-ons",
media: "Media",
share: "Share",
};
interface BackupContent {
homeassistant: boolean;
folders: string[];
addons: string[];
}
export interface HassioBackup {
slug: string;
date: string;
name: string;
type: "full" | "partial";
protected: boolean;
content: BackupContent;
}
export interface HassioBackupDetail extends HassioBackup {
size: number;
homeassistant: string;
addons: Array<{
slug: "ADDON_SLUG";
name: "NAME";
version: "INSTALLED_VERSION";
size: "SIZE_IN_MB";
}>;
repositories: string[];
folders: string[];
}
export interface HassioFullBackupCreateParams {
name: string;
password?: string;
confirm_password?: string;
}
export interface HassioPartialBackupCreateParams
extends HassioFullBackupCreateParams {
folders?: string[];
addons?: string[];
homeassistant?: boolean;
}
export const fetchHassioBackups = async (
hass: HomeAssistant
): Promise<HassioBackup[]> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
const data: {
[key: string]: HassioBackup[];
} = await hass.callWS({
type: "supervisor/api",
endpoint: `/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}`,
method: "get",
});
return data[
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
];
}
return hassioApiResultExtractor(
await hass.callApi<HassioResponse<{ snapshots: HassioBackup[] }>>(
"GET",
`hassio/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}`
)
).snapshots;
};
export const fetchHassioBackupInfo = async (
hass: HomeAssistant,
backup: string
): Promise<HassioBackupDetail> => {
if (hass) {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return hass.callWS({
type: "supervisor/api",
endpoint: `/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/${backup}/info`,
method: "get",
});
}
return hassioApiResultExtractor(
await hass.callApi<HassioResponse<HassioBackupDetail>>(
"GET",
`hassio/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/${backup}/info`
)
);
}
// When called from onboarding we don't have hass
const resp = await fetch(`/api/hassio/backups/${backup}/info`, {
method: "GET",
});
const data = (await resp.json()).data;
return data;
};
export const reloadHassioBackups = async (hass: HomeAssistant) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
await hass.callWS({
type: "supervisor/api",
endpoint: `/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/reload`,
method: "post",
});
return;
}
await hass.callApi<HassioResponse<void>>(
"POST",
`hassio/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/reload`
);
};
export const createHassioFullBackup = async (
hass: HomeAssistant,
data: HassioFullBackupCreateParams
) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
await hass.callWS({
type: "supervisor/api",
endpoint: `/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/new/full`,
method: "post",
timeout: null,
data,
});
return;
}
await hass.callApi<HassioResponse<void>>(
"POST",
`hassio/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/new/full`,
data
);
};
export const removeBackup = async (hass: HomeAssistant, slug: string) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
await hass.callWS({
type: "supervisor/api",
endpoint: `/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/${slug}/remove`,
method: "post",
});
return;
}
await hass.callApi<HassioResponse<void>>(
"POST",
`hassio/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/${slug}/remove`
);
};
export const createHassioPartialBackup = async (
hass: HomeAssistant,
data: HassioPartialBackupCreateParams
) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
await hass.callWS({
type: "supervisor/api",
endpoint: `/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/new/partial`,
method: "post",
timeout: null,
data,
});
return;
}
await hass.callApi<HassioResponse<void>>(
"POST",
`hassio/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/new/partial`,
data
);
};
export const uploadBackup = async (
hass: HomeAssistant,
file: File
): Promise<HassioResponse<HassioBackup>> => {
const fd = new FormData();
let resp;
fd.append("file", file);
if (hass) {
resp = await hass.fetchWithAuth(
`/api/hassio/${
atLeastVersion(hass.config.version, 2021, 9) ? "backups" : "snapshots"
}/new/upload`,
{
method: "POST",
body: fd,
}
);
} else {
// When called from onboarding we don't have hass
resp = await fetch("/api/hassio/backups/new/upload", {
method: "POST",
body: fd,
});
}
if (resp.status === 413) {
throw new Error("Uploaded backup is too large");
} else if (resp.status !== 200) {
throw new Error(`${resp.status} ${resp.statusText}`);
}
return resp.json();
};

View File

@ -1,197 +0,0 @@
import { atLeastVersion } from "../../common/config/version";
import { HomeAssistant } from "../../types";
import { hassioApiResultExtractor, HassioResponse } from "./common";
export const friendlyFolderName = {
ssl: "SSL",
homeassistant: "Configuration",
"addons/local": "Local add-ons",
media: "Media",
share: "Share",
};
interface SnapshotContent {
homeassistant: boolean;
folders: string[];
addons: string[];
}
export interface HassioSnapshot {
slug: string;
date: string;
name: string;
type: "full" | "partial";
protected: boolean;
content: SnapshotContent;
}
export interface HassioSnapshotDetail extends HassioSnapshot {
size: number;
homeassistant: string;
addons: Array<{
slug: "ADDON_SLUG";
name: "NAME";
version: "INSTALLED_VERSION";
size: "SIZE_IN_MB";
}>;
repositories: string[];
folders: string[];
}
export interface HassioFullSnapshotCreateParams {
name: string;
password?: string;
confirm_password?: string;
}
export interface HassioPartialSnapshotCreateParams
extends HassioFullSnapshotCreateParams {
folders?: string[];
addons?: string[];
homeassistant?: boolean;
}
export const fetchHassioSnapshots = async (
hass: HomeAssistant
): Promise<HassioSnapshot[]> => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
const data: { snapshots: HassioSnapshot[] } = await hass.callWS({
type: "supervisor/api",
endpoint: `/snapshots`,
method: "get",
});
return data.snapshots;
}
return hassioApiResultExtractor(
await hass.callApi<HassioResponse<{ snapshots: HassioSnapshot[] }>>(
"GET",
"hassio/snapshots"
)
).snapshots;
};
export const fetchHassioSnapshotInfo = async (
hass: HomeAssistant,
snapshot: string
): Promise<HassioSnapshotDetail> => {
if (hass) {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
return hass.callWS({
type: "supervisor/api",
endpoint: `/snapshots/${snapshot}/info`,
method: "get",
});
}
return hassioApiResultExtractor(
await hass.callApi<HassioResponse<HassioSnapshotDetail>>(
"GET",
`hassio/snapshots/${snapshot}/info`
)
);
}
// When called from onboarding we don't have hass
const resp = await fetch(`/api/hassio/snapshots/${snapshot}/info`, {
method: "GET",
});
const data = (await resp.json()).data;
return data;
};
export const reloadHassioSnapshots = async (hass: HomeAssistant) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
await hass.callWS({
type: "supervisor/api",
endpoint: "/snapshots/reload",
method: "post",
});
return;
}
await hass.callApi<HassioResponse<void>>("POST", `hassio/snapshots/reload`);
};
export const createHassioFullSnapshot = async (
hass: HomeAssistant,
data: HassioFullSnapshotCreateParams
) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
await hass.callWS({
type: "supervisor/api",
endpoint: "/snapshots/new/full",
method: "post",
timeout: null,
data,
});
return;
}
await hass.callApi<HassioResponse<void>>(
"POST",
`hassio/snapshots/new/full`,
data
);
};
export const removeSnapshot = async (hass: HomeAssistant, slug: string) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
await hass.callWS({
type: "supervisor/api",
endpoint: `/snapshots/${slug}/remove`,
method: "post",
});
return;
}
await hass.callApi<HassioResponse<void>>(
"POST",
`hassio/snapshots/${slug}/remove`
);
};
export const createHassioPartialSnapshot = async (
hass: HomeAssistant,
data: HassioPartialSnapshotCreateParams
) => {
if (atLeastVersion(hass.config.version, 2021, 2, 4)) {
await hass.callWS({
type: "supervisor/api",
endpoint: "/snapshots/new/partial",
method: "post",
timeout: null,
data,
});
return;
}
await hass.callApi<HassioResponse<void>>(
"POST",
`hassio/snapshots/new/partial`,
data
);
};
export const uploadSnapshot = async (
hass: HomeAssistant,
file: File
): Promise<HassioResponse<HassioSnapshot>> => {
const fd = new FormData();
let resp;
fd.append("file", file);
if (hass) {
resp = await hass.fetchWithAuth("/api/hassio/snapshots/new/upload", {
method: "POST",
body: fd,
});
} else {
// When called from onboarding we don't have hass
resp = await fetch("/api/hassio/snapshots/new/upload", {
method: "POST",
body: fd,
});
}
if (resp.status === 413) {
throw new Error("Uploaded snapshot is too large");
} else if (resp.status !== 200) {
throw new Error(`${resp.status} ${resp.statusText}`);
}
return resp.json();
};

View File

@ -1,3 +1,4 @@
import { addDays, addMonths, startOfDay, startOfMonth } from "date-fns";
import { HassEntity } from "home-assistant-js-websocket";
import { computeStateDisplay } from "../common/entity/compute_state_display";
import { computeStateDomain } from "../common/entity/compute_state_domain";
@ -238,14 +239,17 @@ export const computeHistory = (
return;
}
const stateWithUnit = stateInfo.find(
(state) => state.attributes && "unit_of_measurement" in state.attributes
const stateWithUnitorStateClass = stateInfo.find(
(state) =>
state.attributes &&
("unit_of_measurement" in state.attributes ||
"state_class" in state.attributes)
);
let unit: string | undefined;
if (stateWithUnit) {
unit = stateWithUnit.attributes.unit_of_measurement;
if (stateWithUnitorStateClass) {
unit = stateWithUnitorStateClass.attributes.unit_of_measurement || " ";
} else {
unit = {
climate: hass.config.unit_system.temperature,
@ -406,3 +410,90 @@ export const calculateStatisticsSumGrowthWithPercentage = (
return sum;
};
export const reduceSumStatisticsByDay = (
values: StatisticValue[]
): StatisticValue[] => {
if (!values?.length) {
return [];
}
const result: StatisticValue[] = [];
if (
values.length > 1 &&
new Date(values[0].start).getDate() === new Date(values[1].start).getDate()
) {
// add init value if the first value isn't end of previous period
result.push({
...values[0]!,
start: startOfMonth(addDays(new Date(values[0].start), -1)).toISOString(),
});
}
let lastValue: StatisticValue;
let prevDate: number | undefined;
for (const value of values) {
const date = new Date(value.start).getDate();
if (prevDate === undefined) {
prevDate = date;
}
if (prevDate !== date) {
// Last value of the day
result.push({
...lastValue!,
start: startOfDay(new Date(lastValue!.start)).toISOString(),
});
prevDate = date;
}
lastValue = value;
}
// Add final value
result.push({
...lastValue!,
start: startOfDay(new Date(lastValue!.start)).toISOString(),
});
return result;
};
export const reduceSumStatisticsByMonth = (
values: StatisticValue[]
): StatisticValue[] => {
if (!values?.length) {
return [];
}
const result: StatisticValue[] = [];
if (
values.length > 1 &&
new Date(values[0].start).getMonth() ===
new Date(values[1].start).getMonth()
) {
// add init value if the first value isn't end of previous period
result.push({
...values[0]!,
start: startOfMonth(
addMonths(new Date(values[0].start), -1)
).toISOString(),
});
}
let lastValue: StatisticValue;
let prevMonth: number | undefined;
for (const value of values) {
const month = new Date(value.start).getMonth();
if (prevMonth === undefined) {
prevMonth = month;
}
if (prevMonth !== month) {
// Last value of the day
result.push({
...lastValue!,
start: startOfMonth(new Date(lastValue!.start)).toISOString(),
});
prevMonth = month;
}
lastValue = value;
}
// Add final value
result.push({
...lastValue!,
start: startOfMonth(new Date(lastValue!.start)).toISOString(),
});
return result;
};

4
src/data/usb.ts Normal file
View File

@ -0,0 +1,4 @@
import { HomeAssistant } from "../types";
export const scanUSBDevices = (hass: HomeAssistant) =>
hass.callWS({ type: "usb/scan" });

View File

@ -24,12 +24,22 @@ export interface ZWaveJSController {
is_heal_network_active: boolean;
}
export interface ZWaveJSNode {
export interface ZWaveJSNodeStatus {
node_id: number;
ready: boolean;
status: number;
}
export interface ZwaveJSNodeMetadata {
node_id: number;
exclusion: string;
inclusion: string;
manual: string;
wakeup: string;
reset: string;
device_database_url: string;
}
export interface ZWaveJSNodeConfigParams {
[key: string]: ZWaveJSNodeConfigParam;
}
@ -132,13 +142,24 @@ export const fetchNodeStatus = (
hass: HomeAssistant,
entry_id: string,
node_id: number
): Promise<ZWaveJSNode> =>
): Promise<ZWaveJSNodeStatus> =>
hass.callWS({
type: "zwave_js/node_status",
entry_id,
node_id,
});
export const fetchNodeMetadata = (
hass: HomeAssistant,
entry_id: string,
node_id: number
): Promise<ZwaveJSNodeMetadata> =>
hass.callWS({
type: "zwave_js/node_metadata",
entry_id,
node_id,
});
export const fetchNodeConfigParameters = (
hass: HomeAssistant,
entry_id: string,

View File

@ -41,7 +41,12 @@ class StepFlowPickFlow extends LitElement {
<img
slot="item-icon"
loading="lazy"
src=${brandsUrl(flow.handler, "icon", true)}
src=${brandsUrl({
domain: flow.handler,
type: "icon",
useFallback: true,
darkOptimized: this.hass.selectedTheme?.dark,
})}
referrerpolicy="no-referrer"
/>

View File

@ -96,7 +96,12 @@ class StepFlowPickHandler extends LitElement {
<img
slot="item-icon"
loading="lazy"
src=${brandsUrl(handler.slug, "icon", true)}
src=${brandsUrl({
domain: handler.slug,
type: "icon",
useFallback: true,
darkOptimized: this.hass.selectedTheme?.dark,
})}
referrerpolicy="no-referrer"
/>

View File

@ -149,14 +149,12 @@ class MoreInfoClimate extends LitElement {
${stateObj.attributes.humidity} %
</div>
<ha-slider
class="humidity"
step="1"
pin
ignore-bar-touch
dir=${rtlDirection}
.min=${stateObj.attributes.min_humidity}
.max=${stateObj.attributes.max_humidity}
.secondaryProgress=${stateObj.attributes.max_humidity}
.value=${stateObj.attributes.humidity}
@change=${this._targetHumiditySliderChanged}
>
@ -479,11 +477,6 @@ class MoreInfoClimate extends LitElement {
margin-left: 4%;
}
.humidity {
--paper-slider-active-color: var(--paper-blue-400);
--paper-slider-secondary-color: var(--paper-blue-400);
}
.single-row {
padding: 8px 0;
}

View File

@ -53,14 +53,12 @@ class MoreInfoHumidifier extends LitElement {
<div class="single-row">
<div class="target-humidity">${stateObj.attributes.humidity} %</div>
<ha-slider
class="humidity"
step="1"
pin
ignore-bar-touch
dir=${rtlDirection}
.min=${stateObj.attributes.min_humidity}
.max=${stateObj.attributes.max_humidity}
.secondaryProgress=${stateObj.attributes.max_humidity}
.value=${stateObj.attributes.humidity}
@change=${this._targetHumiditySliderChanged}
>
@ -201,11 +199,6 @@ class MoreInfoHumidifier extends LitElement {
direction: ltr;
}
.humidity {
--paper-slider-active-color: var(--paper-blue-400);
--paper-slider-secondary-color: var(--paper-blue-400);
}
.single-row {
padding: 8px 0;
}

View File

@ -1,191 +0,0 @@
import "@polymer/iron-flex-layout/iron-flex-layout-classes";
import "@polymer/paper-input/paper-input";
import { html } from "@polymer/polymer/lib/utils/html-tag";
/* eslint-plugin-disable lit */
import { PolymerElement } from "@polymer/polymer/polymer-element";
import { attributeClassNames } from "../../../common/entity/attribute_class_names";
import "../../../components/ha-date-input";
import "../../../components/ha-relative-time";
import "../../../components/paper-time-input";
class DatetimeInput extends PolymerElement {
static get template() {
return html`
<div class$="[[computeClassNames(stateObj)]]">
<template is="dom-if" if="[[doesHaveDate(stateObj)]]" restamp="">
<div>
<ha-date-input
id="dateInput"
label="Date"
value="{{selectedDate}}"
></ha-date-input>
</div>
</template>
<template is="dom-if" if="[[doesHaveTime(stateObj)]]" restamp="">
<div>
<paper-time-input
hour="{{selectedHour}}"
min="{{selectedMinute}}"
format="24"
></paper-time-input>
</div>
</template>
</div>
`;
}
constructor() {
super();
this.is_ready = false;
}
static get properties() {
return {
hass: {
type: Object,
},
stateObj: {
type: Object,
observer: "stateObjChanged",
},
selectedDate: {
type: String,
observer: "dateTimeChanged",
},
selectedHour: {
type: Number,
observer: "dateTimeChanged",
},
selectedMinute: {
type: Number,
observer: "dateTimeChanged",
},
};
}
ready() {
super.ready();
this.is_ready = true;
}
/* Convert the date in the stateObj into a string useable by vaadin-date-picker */
getDateString(stateObj) {
if (stateObj.state === "unknown") {
return "";
}
let monthFiller;
if (stateObj.attributes.month < 10) {
monthFiller = "0";
} else {
monthFiller = "";
}
let dayFiller;
if (stateObj.attributes.day < 10) {
dayFiller = "0";
} else {
dayFiller = "";
}
return (
stateObj.attributes.year +
"-" +
monthFiller +
stateObj.attributes.month +
"-" +
dayFiller +
stateObj.attributes.day
);
}
/* Should fire when any value was changed *by the user*, not b/c of setting
* initial values. */
dateTimeChanged() {
// Check if the change is really coming from the user
if (!this.is_ready) {
return;
}
let changed = false;
let minuteFiller;
const serviceData = {
entity_id: this.stateObj.entity_id,
};
if (this.stateObj.attributes.has_time) {
changed =
changed ||
parseInt(this.selectedMinute) !== this.stateObj.attributes.minute;
changed =
changed ||
parseInt(this.selectedHour) !== this.stateObj.attributes.hour;
if (this.selectedMinute < 10) {
minuteFiller = "0";
} else {
minuteFiller = "";
}
const timeStr =
this.selectedHour + ":" + minuteFiller + this.selectedMinute;
serviceData.time = timeStr;
}
if (this.stateObj.attributes.has_date) {
if (this.selectedDate.length === 0) {
return; // Date was not set
}
const dateValInput = new Date(this.selectedDate);
const dateValState = new Date(
this.stateObj.attributes.year,
this.stateObj.attributes.month - 1,
this.stateObj.attributes.day
);
changed = changed || dateValState !== dateValInput;
serviceData.date = this.selectedDate;
}
if (changed) {
this.hass.callService("input_datetime", "set_datetime", serviceData);
}
}
stateObjChanged(newVal) {
// Set to non-ready s.t. dateTimeChanged does not fire
this.is_ready = false;
if (newVal.attributes.has_time) {
this.selectedHour = newVal.attributes.hour;
this.selectedMinute = newVal.attributes.minute;
}
if (newVal.attributes.has_date) {
this.selectedDate = this.getDateString(newVal);
}
this.is_ready = true;
}
doesHaveDate(stateObj) {
return stateObj.attributes.has_date;
}
doesHaveTime(stateObj) {
return stateObj.attributes.has_time;
}
computeClassNames(stateObj) {
return (
"more-info-input_datetime " +
attributeClassNames(stateObj, ["has_time", "has_date"])
);
}
}
customElements.define("more-info-input_datetime", DatetimeInput);

View File

@ -0,0 +1,103 @@
import { HassEntity } from "home-assistant-js-websocket";
import { css, CSSResultGroup, html, LitElement, TemplateResult } from "lit";
import { customElement, property } from "lit/decorators";
import "../../../components/ha-date-input";
import "../../../components/ha-time-input";
import { UNAVAILABLE_STATES, UNKNOWN } from "../../../data/entity";
import { setInputDateTimeValue } from "../../../data/input_datetime";
import type { HomeAssistant } from "../../../types";
@customElement("more-info-input_datetime")
class MoreInfoInputDatetime extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public stateObj?: HassEntity;
protected render(): TemplateResult {
if (!this.stateObj) {
return html``;
}
return html`
${
this.stateObj.attributes.has_date
? html`
<ha-date-input
.value=${`${this.stateObj.attributes.year}-${this.stateObj.attributes.month}-${this.stateObj.attributes.day}`}
.disabled=${UNAVAILABLE_STATES.includes(this.stateObj.state)}
@value-changed=${this._dateChanged}
>
</ha-date-input>
`
: ``
}
${
this.stateObj.attributes.has_time
? html`
<ha-time-input
.value=${this.stateObj.state === UNKNOWN
? ""
: this.stateObj.attributes.has_date
? this.stateObj.state.split(" ")[1]
: this.stateObj.state}
.locale=${this.hass.locale}
.disabled=${UNAVAILABLE_STATES.includes(this.stateObj.state)}
hide-label
@value-changed=${this._timeChanged}
@click=${this._stopEventPropagation}
></ha-time-input>
`
: ``
}
</hui-generic-entity-row>
`;
}
private _stopEventPropagation(ev: Event): void {
ev.stopPropagation();
}
private _timeChanged(ev): void {
setInputDateTimeValue(
this.hass!,
this.stateObj!.entity_id,
ev.detail.value,
this.stateObj!.attributes.has_date
? this.stateObj!.state.split(" ")[0]
: undefined
);
ev.target.blur();
}
private _dateChanged(ev): void {
setInputDateTimeValue(
this.hass!,
this.stateObj!.entity_id,
this.stateObj!.attributes.has_time
? this.stateObj!.state.split(" ")[1]
: undefined,
ev.detail.value
);
ev.target.blur();
}
static get styles(): CSSResultGroup {
return css`
:host {
display: flex;
align-items: center;
justify-content: flex-end;
}
ha-date-input + ha-time-input {
margin-left: 4px;
}
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"more-info-input_datetime": MoreInfoInputDatetime;
}
}

View File

@ -21,5 +21,5 @@
"content" in document.createElement("template"))) {
document.write("<script src='/static/polyfills/webcomponents-bundle.js'><"+"/script>");
}
var isS11_12 = /.*Version\/(?:11|12)(?:\.\d+)*.*Safari\//.test(navigator.userAgent);
var isS11_12 = /(?:.*(?:iPhone|iPad).*OS (?:11|12)_\d)|(?:.*Version\/(?:11|12)(?:\.\d+)*.*Safari\/)/.test(navigator.userAgent);
</script>

View File

@ -211,6 +211,7 @@ export class HomeAssistantAppEl extends QuickBarMixin(HassElement) {
if (!this.hass!.connection.connected) {
return;
}
window.stop();
this.hass!.connection.suspend();
}

View File

@ -89,13 +89,13 @@ class HaOnboarding extends litLocalizeLiteMixin(HassElement) {
</onboarding-create-user>`
: ""}
${this._supervisor
? html`<onboarding-restore-snapshot
? html`<onboarding-restore-backup
.localize=${this.localize}
.restoring=${this._restoring}
.discoveryInformation=${this._discoveryInformation}
@restoring=${this._restoringSnapshot}
@restoring=${this._restoringBackup}
>
</onboarding-restore-snapshot>`
</onboarding-restore-backup>`
: ""}
`;
}
@ -170,7 +170,7 @@ class HaOnboarding extends litLocalizeLiteMixin(HassElement) {
return this._steps ? this._steps.find((stp) => !stp.done) : undefined;
}
private _restoringSnapshot() {
private _restoringBackup() {
this._restoring = true;
}
@ -183,12 +183,12 @@ class HaOnboarding extends litLocalizeLiteMixin(HassElement) {
].includes(response.installation_type);
if (this._supervisor) {
// Only load if we have supervisor
import("./onboarding-restore-snapshot");
import("./onboarding-restore-backup");
}
} catch (err) {
// eslint-disable-next-line no-console
console.error(
"Something went wrong loading onboarding-restore-snapshot",
"Something went wrong loading onboarding-restore-backup",
err
);
}

View File

@ -11,13 +11,19 @@ class IntegrationBadge extends LitElement {
@property() public badgeIcon?: string;
@property({ type: Boolean }) public darkOptimizedIcon?: boolean;
@property({ type: Boolean, reflect: true }) public clickable = false;
protected render(): TemplateResult {
return html`
<div class="icon">
<img
src=${brandsUrl(this.domain, "icon")}
src=${brandsUrl({
domain: this.domain,
type: "icon",
darkOptimized: this.darkOptimizedIcon,
})}
referrerpolicy="no-referrer"
/>
${this.badgeIcon

Some files were not shown because too many files have changed in this diff Show More