20241127.0 (#23027)

This commit is contained in:
Bram Kragten 2024-11-27 15:28:49 +01:00 committed by GitHub
commit 91d5d2f1eb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
279 changed files with 11315 additions and 4509 deletions

View File

@ -1,132 +0,0 @@
{
"extends": [
"airbnb-base",
"airbnb-typescript/base",
"plugin:@typescript-eslint/recommended",
"plugin:wc/recommended",
"plugin:lit/all",
"plugin:lit-a11y/recommended",
"prettier"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 2020,
"ecmaFeatures": {
"modules": true
},
"sourceType": "module",
"project": "./tsconfig.json"
},
"settings": {
"import/resolver": {
"webpack": {
"config": "./webpack.config.cjs"
}
}
},
"globals": {
"__DEV__": false,
"__DEMO__": false,
"__BUILD__": false,
"__VERSION__": false,
"__STATIC_PATH__": false,
"__SUPERVISOR__": false,
"Polymer": true
},
"env": {
"browser": true,
"es6": true
},
"rules": {
"class-methods-use-this": "off",
"new-cap": "off",
"prefer-template": "off",
"object-shorthand": "off",
"func-names": "off",
"no-underscore-dangle": "off",
"strict": "off",
"no-plusplus": "off",
"no-bitwise": "error",
"comma-dangle": "off",
"vars-on-top": "off",
"no-continue": "off",
"no-param-reassign": "off",
"no-multi-assign": "off",
"no-console": "error",
"radix": "off",
"no-alert": "off",
"no-nested-ternary": "off",
"prefer-destructuring": "off",
"no-restricted-globals": [2, "event"],
"prefer-promise-reject-errors": "off",
"import/prefer-default-export": "off",
"import/no-default-export": "off",
"import/no-unresolved": "off",
"import/no-cycle": "off",
"import/extensions": [
"error",
"ignorePackages",
{
"ts": "never",
"js": "never"
}
],
"no-restricted-syntax": ["error", "LabeledStatement", "WithStatement"],
"object-curly-newline": "off",
"default-case": "off",
"wc/no-self-class": "off",
"no-shadow": "off",
"@typescript-eslint/camelcase": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-shadow": ["error"],
"@typescript-eslint/naming-convention": [
"off",
{
"selector": "default",
"format": ["camelCase", "snake_case"],
"leadingUnderscore": "allow",
"trailingUnderscore": "allow"
},
{
"selector": ["variable"],
"format": ["camelCase", "snake_case", "UPPER_CASE"],
"leadingUnderscore": "allow",
"trailingUnderscore": "allow"
},
{
"selector": "typeLike",
"format": ["PascalCase"]
}
],
"@typescript-eslint/no-unused-vars": "off",
"unused-imports/no-unused-vars": [
"error",
{
"vars": "all",
"varsIgnorePattern": "^_",
"args": "after-used",
"argsIgnorePattern": "^_",
"ignoreRestSiblings": true
}
],
"unused-imports/no-unused-imports": "error",
"lit/attribute-names": "warn",
"lit/attribute-value-entities": "off",
"lit/no-template-map": "off",
"lit/no-native-attributes": "warn",
"lit/no-this-assign-in-render": "warn",
"lit-a11y/click-events-have-key-events": ["off"],
"lit-a11y/no-autofocus": "off",
"lit-a11y/alt-text": "warn",
"lit-a11y/anchor-is-valid": "warn",
"lit-a11y/role-has-required-aria-attrs": "warn",
"@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/no-import-type-side-effects": "error"
},
"plugins": ["unused-imports"]
}

View File

@ -26,14 +26,20 @@ jobs:
- name: Check out files from GitHub
uses: actions/checkout@v4.2.2
- name: Setup Node
id: setup-node
uses: actions/setup-node@v4.1.0
with:
node-version-file: ".nvmrc"
cache: yarn
- uses: actions/cache@v4.1.2
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: "node_modules"
key: ${{ runner.os }}-yarn-${{ hashFiles('.yarnrc.yml') }}-${{ steps.setup-node.outputs.node-version }}-${{ hashFiles('yarn.lock') }}
restore-keys: ${{ runner.os }}-yarn-${{ hashFiles('.yarnrc.yml') }}-${{ steps.setup-node.outputs.node-version }}
- name: Install dependencies
if: steps.yarn-cache.outputs.cache-hit != 'true'
run: yarn install --immutable
- name: Check for duplicate dependencies
run: yarn dedupe --check
- name: Build resources
run: ./node_modules/.bin/gulp gen-icons-json build-translations build-locale-data gather-gallery-pages
- name: Setup lint cache
@ -60,11 +66,19 @@ jobs:
- name: Check out files from GitHub
uses: actions/checkout@v4.2.2
- name: Setup Node
id: setup-node
uses: actions/setup-node@v4.1.0
with:
node-version-file: ".nvmrc"
cache: yarn
- uses: actions/cache@v4.1.2
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: "node_modules"
key: ${{ runner.os }}-yarn-${{ hashFiles('.yarnrc.yml') }}-${{ steps.setup-node.outputs.node-version }}-${{ hashFiles('yarn.lock') }}
restore-keys: ${{ runner.os }}-yarn-${{ hashFiles('.yarnrc.yml') }}-${{ steps.setup-node.outputs.node-version }}
- name: Install dependencies
if: steps.yarn-cache.outputs.cache-hit != 'true'
run: yarn install --immutable
- name: Build resources
run: ./node_modules/.bin/gulp gen-icons-json build-translations build-locale-data
@ -78,11 +92,19 @@ jobs:
- name: Check out files from GitHub
uses: actions/checkout@v4.2.2
- name: Setup Node
id: setup-node
uses: actions/setup-node@v4.1.0
with:
node-version-file: ".nvmrc"
cache: yarn
- uses: actions/cache@v4.1.2
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: "node_modules"
key: ${{ runner.os }}-yarn-${{ hashFiles('.yarnrc.yml') }}-${{ steps.setup-node.outputs.node-version }}-${{ hashFiles('yarn.lock') }}
restore-keys: ${{ runner.os }}-yarn-${{ hashFiles('.yarnrc.yml') }}-${{ steps.setup-node.outputs.node-version }}
- name: Install dependencies
if: steps.yarn-cache.outputs.cache-hit != 'true'
run: yarn install --immutable
- name: Build Application
run: ./node_modules/.bin/gulp build-app
@ -102,11 +124,19 @@ jobs:
- name: Check out files from GitHub
uses: actions/checkout@v4.2.2
- name: Setup Node
id: setup-node
uses: actions/setup-node@v4.1.0
with:
node-version-file: ".nvmrc"
cache: yarn
- uses: actions/cache@v4.1.2
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: "node_modules"
key: ${{ runner.os }}-yarn-${{ hashFiles('.yarnrc.yml') }}-${{ steps.setup-node.outputs.node-version }}-${{ hashFiles('yarn.lock') }}
restore-keys: ${{ runner.os }}-yarn-${{ hashFiles('.yarnrc.yml') }}-${{ steps.setup-node.outputs.node-version }}
- name: Install dependencies
if: steps.yarn-cache.outputs.cache-hit != 'true'
run: yarn install --immutable
- name: Build Application
run: ./node_modules/.bin/gulp build-hassio

View File

@ -4,6 +4,7 @@ on:
release:
types:
- published
workflow_dispatch:
env:
PYTHON_VERSION: "3.12"
@ -55,7 +56,7 @@ jobs:
script/release
- name: Upload release assets
uses: softprops/action-gh-release@v2.0.9
uses: softprops/action-gh-release@v2.1.0
with:
files: |
dist/*.whl
@ -74,7 +75,7 @@ jobs:
echo "home-assistant-frontend==$version" > ./requirements.txt
- name: Build wheels
uses: home-assistant/wheels@2024.07.1
uses: home-assistant/wheels@2024.11.0
with:
abi: cp312
tag: musllinux_1_2

3
.gitignore vendored
View File

@ -50,3 +50,6 @@ src/cast/dev_const.ts
# Jetbrains
/.idea/
# test coverage
test/coverage/

View File

@ -4,6 +4,7 @@
"esbenp.prettier-vscode",
"runem.lit-plugin",
"github.vscode-pull-request-github",
"eamodio.gitlens"
"eamodio.gitlens",
"vitest.explorer"
]
}

32
.vscode/tasks.json vendored
View File

@ -100,6 +100,38 @@
"instanceLimit": 1
}
},
{
"label": "Develop Landing Page",
"type": "gulp",
"task": "develop-landing-page",
"problemMatcher": {
"owner": "ha-build",
"source": "ha-build",
"fileLocation": "absolute",
"severity": "error",
"pattern": [
{
"regexp": "(SyntaxError): (.+): (.+) \\((\\d+):(\\d+)\\)",
"severity": 1,
"file": 2,
"message": 3,
"line": 4,
"column": 5
}
],
"background": {
"activeOnStart": true,
"beginsPattern": "Changes detected. Starting compilation",
"endsPattern": "Build done @"
}
},
"isBackground": true,
"group": "build",
"runOptions": {
"instanceLimit": 1
}
},
{
"label": "Develop Demo",
"type": "gulp",

File diff suppressed because one or more lines are too long

View File

@ -6,4 +6,4 @@ enableGlobalCache: false
nodeLinker: node-modules
yarnPath: .yarn/releases/yarn-4.5.1.cjs
yarnPath: .yarn/releases/yarn-4.5.2.cjs

View File

@ -1,12 +0,0 @@
{
"extends": "../.eslintrc.json",
"rules": {
"no-console": "off",
"import/no-extraneous-dependencies": "off",
"import/extensions": "off",
"import/no-dynamic-require": "off",
"global-require": "off",
"@typescript-eslint/no-var-requires": "off",
"prefer-arrow-callback": "off"
}
}

View File

@ -15,7 +15,7 @@ The Home Assistant build pipeline contains various steps to prepare a build.
Currently in Home Assistant we use a bundler to convert TypeScript, CSS and JSON files to JavaScript files that the browser understands.
We currently rely on Webpack but also have experimental Rollup support. Both of these programs bundle the converted files in both production and development.
We currently rely on Webpack. Both of these programs bundle the converted files in both production and development.
For development, bundling is optional. We just want to get the right files in the browser.

View File

@ -147,6 +147,7 @@ const polyfillMap = {
...Object.fromEntries(
[
"DateTimeFormat",
"DurationFormat",
"DisplayNames",
"ListFormat",
"NumberFormat",

View File

@ -152,7 +152,6 @@ module.exports.babelOptions = ({
exclude: [
// \\ for Windows, / for Mac OS and Linux
/node_modules[\\/]core-js/,
/node_modules[\\/]webpack[\\/]buildin/,
],
sourceMaps: !isTestBuild,
overrides: [
@ -226,8 +225,7 @@ module.exports.config = {
return {
name: "frontend" + nameSuffix(latestBuild),
entry: {
"service-worker":
!env.useRollup() && !latestBuild
"service-worker": !latestBuild
? {
import: "./src/entrypoints/service-worker.ts",
layer: "sw",
@ -328,4 +326,17 @@ module.exports.config = {
},
};
},
landingPage({ isProdBuild, latestBuild }) {
return {
name: "landing-page" + nameSuffix(latestBuild),
entry: {
entrypoint: path.resolve(paths.landingPage_dir, "src/entrypoint.js"),
},
outputPath: outputPath(paths.landingPage_output_root, latestBuild),
publicPath: publicPath(latestBuild),
isProdBuild,
latestBuild,
};
},
};

View File

@ -2,12 +2,11 @@ const fs = require("fs");
const path = require("path");
const paths = require("./paths.cjs");
const isTrue = (value) => value === "1" || value?.toLowerCase() === "true";
module.exports = {
useRollup() {
return process.env.ROLLUP === "1";
},
useWDS() {
return process.env.WDS === "1";
return isTrue(process.env.WDS);
},
isProdBuild() {
return (
@ -15,13 +14,13 @@ module.exports = {
);
},
isStatsBuild() {
return process.env.STATS === "1";
return isTrue(process.env.STATS);
},
isTestBuild() {
return process.env.IS_TEST === "true";
return isTrue(process.env.IS_TEST);
},
isNetlify() {
return process.env.NETLIFY === "true";
return isTrue(process.env.NETLIFY);
},
version() {
const version = fs
@ -33,6 +32,6 @@ module.exports = {
return version[1];
},
isDevContainer() {
return process.env.DEV_CONTAINER === "1";
return isTrue(process.env.DEV_CONTAINER);
},
};

View File

@ -0,0 +1,16 @@
import rootConfig from "../eslint.config.mjs";
export default [
...rootConfig,
{
rules: {
"no-console": "off",
"import/no-extraneous-dependencies": "off",
"import/extensions": "off",
"import/no-dynamic-require": "off",
"global-require": "off",
"@typescript-eslint/no-var-requires": "off",
"prefer-arrow-callback": "off",
},
},
];

View File

@ -6,11 +6,10 @@ import "./entry-html.js";
import "./gather-static.js";
import "./gen-icons-json.js";
import "./locale-data.js";
import "./rollup.js";
import "./service-worker.js";
import "./translations.js";
import "./wds.js";
import "./webpack.js";
import "./rspack.js";
gulp.task(
"develop-app",
@ -27,11 +26,7 @@ gulp.task(
"build-locale-data"
),
"copy-static-app",
env.useWDS()
? "wds-watch-app"
: env.useRollup()
? "rollup-watch-app"
: "webpack-watch-app"
env.useWDS() ? "wds-watch-app" : "rspack-watch-app"
)
);
@ -44,9 +39,20 @@ gulp.task(
"clean",
gulp.parallel("gen-icons-json", "build-translations", "build-locale-data"),
"copy-static-app",
env.useRollup() ? "rollup-prod-app" : "webpack-prod-app",
"rspack-prod-app",
gulp.parallel("gen-pages-app-prod", "gen-service-worker-app-prod"),
// Don't compress running tests
...(env.isTestBuild() ? [] : ["compress-app"])
...(env.isTestBuild() || env.isStatsBuild() ? [] : ["compress-app"])
)
);
gulp.task(
"analyze-app",
gulp.series(
async function setEnv() {
process.env.STATS = "1";
},
"clean",
"rspack-prod-app"
)
);

View File

@ -1,12 +1,10 @@
import gulp from "gulp";
import env from "../env.cjs";
import "./clean.js";
import "./entry-html.js";
import "./gather-static.js";
import "./rollup.js";
import "./service-worker.js";
import "./translations.js";
import "./webpack.js";
import "./rspack.js";
gulp.task(
"develop-cast",
@ -19,7 +17,7 @@ gulp.task(
gulp.parallel("gen-icons-json", "build-translations", "build-locale-data"),
"copy-static-cast",
"gen-pages-cast-dev",
env.useRollup() ? "rollup-dev-server-cast" : "webpack-dev-server-cast"
"rspack-dev-server-cast"
)
);
@ -33,7 +31,7 @@ gulp.task(
"translations-enable-merge-backend",
gulp.parallel("gen-icons-json", "build-translations", "build-locale-data"),
"copy-static-cast",
env.useRollup() ? "rollup-prod-cast" : "webpack-prod-cast",
"rspack-prod-cast",
"gen-pages-cast-prod"
)
);

View File

@ -38,3 +38,14 @@ gulp.task(
])
)
);
gulp.task(
"clean-landing-page",
gulp.parallel("clean-translations", async () =>
deleteSync([
paths.landingPage_output_root,
paths.landingPage_build,
paths.build_dir,
])
)
);

View File

@ -1,13 +1,11 @@
import gulp from "gulp";
import env from "../env.cjs";
import "./clean.js";
import "./entry-html.js";
import "./gather-static.js";
import "./gen-icons-json.js";
import "./rollup.js";
import "./service-worker.js";
import "./translations.js";
import "./webpack.js";
import "./rspack.js";
gulp.task(
"develop-demo",
@ -24,7 +22,7 @@ gulp.task(
"build-locale-data"
),
"copy-static-demo",
env.useRollup() ? "rollup-dev-server-demo" : "webpack-dev-server-demo"
"rspack-dev-server-demo"
)
);
@ -39,7 +37,18 @@ gulp.task(
"translations-enable-merge-backend",
gulp.parallel("gen-icons-json", "build-translations", "build-locale-data"),
"copy-static-demo",
env.useRollup() ? "rollup-prod-demo" : "webpack-prod-demo",
"rspack-prod-demo",
"gen-pages-demo-prod"
)
);
gulp.task(
"analyze-demo",
gulp.series(
async function setEnv() {
process.env.STATS = "1";
},
"clean",
"rspack-prod-demo"
)
);

View File

@ -127,6 +127,7 @@ gulp.task("fetch-lokalise", async function () {
replace_breaks: false,
json_unescaped_slashes: true,
export_empty_as: "skip",
filter_data: ["verified"],
})
.then((download) => fetch(download.bundle_url))
.then((response) => {

View File

@ -56,7 +56,6 @@ const getCommonTemplateVars = () => {
{ ignorePatch: true, allowHigherVersions: true }
);
return {
useRollup: env.useRollup(),
useWDS: env.useWDS(),
modernRegex: compileRegex(browserRegexes.concat(haMacOSRegex)).toString(),
};
@ -258,6 +257,28 @@ gulp.task(
)
);
const LANDING_PAGE_PAGE_ENTRIES = { "index.html": ["entrypoint"] };
gulp.task(
"gen-pages-landing-page-dev",
genPagesDevTask(
LANDING_PAGE_PAGE_ENTRIES,
paths.landingPage_dir,
paths.landingPage_output_root
)
);
gulp.task(
"gen-pages-landing-page-prod",
genPagesProdTask(
LANDING_PAGE_PAGE_ENTRIES,
paths.landingPage_dir,
paths.landingPage_output_root,
paths.landingPage_output_latest,
paths.landingPage_output_es5
)
);
const HASSIO_PAGE_ENTRIES = { "entrypoint.js": ["entrypoint"] };
gulp.task(

View File

@ -4,16 +4,14 @@ import gulp from "gulp";
import yaml from "js-yaml";
import { marked } from "marked";
import path from "path";
import env from "../env.cjs";
import paths from "../paths.cjs";
import "./clean.js";
import "./entry-html.js";
import "./gather-static.js";
import "./gen-icons-json.js";
import "./rollup.js";
import "./service-worker.js";
import "./translations.js";
import "./webpack.js";
import "./rspack.js";
gulp.task("gather-gallery-pages", async function gatherPages() {
const pageDir = path.resolve(paths.gallery_dir, "src/pages");
@ -158,9 +156,7 @@ gulp.task(
"copy-static-gallery",
"gen-pages-gallery-dev",
gulp.parallel(
env.useRollup()
? "rollup-dev-server-gallery"
: "webpack-dev-server-gallery",
"rspack-dev-server-gallery",
async function watchMarkdownFiles() {
gulp.watch(
[
@ -189,7 +185,7 @@ gulp.task(
"gather-gallery-pages"
),
"copy-static-gallery",
env.useRollup() ? "rollup-prod-gallery" : "webpack-prod-gallery",
"rspack-prod-gallery",
"gen-pages-gallery-prod"
)
);

View File

@ -4,7 +4,6 @@ import fs from "fs-extra";
import gulp from "gulp";
import path from "path";
import paths from "../paths.cjs";
import env from "../env.cjs";
const npmPath = (...parts) =>
path.resolve(paths.polymer_dir, "node_modules", ...parts);
@ -69,9 +68,6 @@ function copyPolyfills(staticDir) {
}
function copyLoaderJS(staticDir) {
if (!env.useRollup()) {
return;
}
const staticPath = genStaticPath(staticDir);
copyFileDir(npmPath("systemjs/dist/s.min.js"), staticPath("js"));
copyFileDir(npmPath("systemjs/dist/s.min.js.map"), staticPath("js"));
@ -129,6 +125,11 @@ gulp.task("copy-translations-supervisor", async () => {
copyTranslations(staticDir);
});
gulp.task("copy-translations-landing-page", async () => {
const staticDir = paths.landingPage_output_static;
copyTranslations(staticDir);
});
gulp.task("copy-static-supervisor", async () => {
const staticDir = paths.hassio_output_static;
copyLocaleData(staticDir);
@ -203,3 +204,14 @@ gulp.task("copy-static-gallery", async () => {
copyLocaleData(paths.gallery_output_static);
copyMdiIcons(paths.gallery_output_static);
});
gulp.task("copy-static-landing-page", async () => {
// Copy landing-page static files
fs.copySync(
path.resolve(paths.landingPage_dir, "public"),
paths.landingPage_output_root
);
copyFonts(paths.landingPage_output_static);
copyTranslations(paths.landingPage_output_static);
});

View File

@ -5,9 +5,8 @@ import "./compress.js";
import "./entry-html.js";
import "./gather-static.js";
import "./gen-icons-json.js";
import "./rollup.js";
import "./translations.js";
import "./webpack.js";
import "./rspack.js";
gulp.task(
"develop-hassio",
@ -22,7 +21,7 @@ gulp.task(
"copy-translations-supervisor",
"build-locale-data",
"copy-static-supervisor",
env.useRollup() ? "rollup-watch-hassio" : "webpack-watch-hassio"
"rspack-watch-hassio"
)
);
@ -38,7 +37,7 @@ gulp.task(
"copy-translations-supervisor",
"build-locale-data",
"copy-static-supervisor",
env.useRollup() ? "rollup-prod-hassio" : "webpack-prod-hassio",
"rspack-prod-hassio",
"gen-pages-hassio-prod",
...// Don't compress running tests
(env.isTestBuild() ? [] : ["compress-hassio"])

View File

@ -0,0 +1,41 @@
import gulp from "gulp";
import "./clean.js";
import "./compress.js";
import "./entry-html.js";
import "./gather-static.js";
import "./gen-icons-json.js";
import "./translations.js";
import "./rspack.js";
gulp.task(
"develop-landing-page",
gulp.series(
async function setEnv() {
process.env.NODE_ENV = "development";
},
"clean-landing-page",
"translations-enable-merge-backend",
"build-landing-page-translations",
"copy-translations-landing-page",
"build-locale-data",
"copy-static-landing-page",
"gen-pages-landing-page-dev",
"rspack-watch-landing-page"
)
);
gulp.task(
"build-landing-page",
gulp.series(
async function setEnv() {
process.env.NODE_ENV = "production";
},
"clean-landing-page",
"build-landing-page-translations",
"copy-translations-landing-page",
"build-locale-data",
"copy-static-landing-page",
"rspack-prod-landing-page",
"gen-pages-landing-page-prod"
)
);

View File

@ -9,6 +9,7 @@ const outDir = join(paths.build_dir, "locale-data");
const INTL_POLYFILLS = {
"intl-datetimeformat": "DateTimeFormat",
"intl-durationFormat": "DurationFormat",
"intl-displaynames": "DisplayNames",
"intl-listformat": "ListFormat",
"intl-numberformat": "NumberFormat",

View File

@ -1,147 +0,0 @@
// Tasks to run Rollup
import log from "fancy-log";
import gulp from "gulp";
import http from "http";
import open from "open";
import path from "path";
import { rollup } from "rollup";
import handler from "serve-handler";
import paths from "../paths.cjs";
import rollupConfig from "../rollup.cjs";
const bothBuilds = (createConfigFunc, params) =>
gulp.series(
async function buildLatest() {
await buildRollup(
createConfigFunc({
...params,
latestBuild: true,
})
);
},
async function buildES5() {
await buildRollup(
createConfigFunc({
...params,
latestBuild: false,
})
);
}
);
function createServer(serveOptions) {
const server = http.createServer((request, response) =>
handler(request, response, {
public: serveOptions.root,
})
);
server.listen(
serveOptions.port,
serveOptions.networkAccess ? "0.0.0.0" : undefined,
() => {
log.info(`Available at http://localhost:${serveOptions.port}`);
open(`http://localhost:${serveOptions.port}`);
}
);
}
function watchRollup(createConfig, extraWatchSrc = [], serveOptions = null) {
const { inputOptions, outputOptions } = createConfig({
isProdBuild: false,
latestBuild: true,
});
const watcher = rollup.watch({
...inputOptions,
output: [outputOptions],
watch: {
include: ["src/**"] + extraWatchSrc,
},
});
let startedHttp = false;
watcher.on("event", (event) => {
if (event.code === "BUNDLE_END") {
log(`Build done @ ${new Date().toLocaleTimeString()}`);
} else if (event.code === "ERROR") {
log.error(event.error);
} else if (event.code === "END") {
if (startedHttp || !serveOptions) {
return;
}
startedHttp = true;
createServer(serveOptions);
}
});
gulp.watch(
path.join(paths.translations_src, "en.json"),
gulp.series("build-translations", "copy-translations-app")
);
}
async function buildRollup(config) {
const bundle = await rollup.rollup(config.inputOptions);
await bundle.write(config.outputOptions);
}
gulp.task("rollup-watch-app", () => {
watchRollup(rollupConfig.createAppConfig);
});
gulp.task("rollup-watch-hassio", () => {
watchRollup(rollupConfig.createHassioConfig, ["hassio/src/**"]);
});
gulp.task("rollup-dev-server-demo", () => {
watchRollup(rollupConfig.createDemoConfig, ["demo/src/**"], {
root: paths.demo_output_root,
port: 8090,
});
});
gulp.task("rollup-dev-server-cast", () => {
watchRollup(rollupConfig.createCastConfig, ["cast/src/**"], {
root: paths.cast_output_root,
port: 8080,
networkAccess: true,
});
});
gulp.task("rollup-dev-server-gallery", () => {
watchRollup(rollupConfig.createGalleryConfig, ["gallery/src/**"], {
root: paths.gallery_output_root,
port: 8100,
});
});
gulp.task(
"rollup-prod-app",
bothBuilds(rollupConfig.createAppConfig, { isProdBuild: true })
);
gulp.task(
"rollup-prod-demo",
bothBuilds(rollupConfig.createDemoConfig, { isProdBuild: true })
);
gulp.task(
"rollup-prod-cast",
bothBuilds(rollupConfig.createCastConfig, { isProdBuild: true })
);
gulp.task("rollup-prod-hassio", () =>
bothBuilds(rollupConfig.createHassioConfig, { isProdBuild: true })
);
gulp.task("rollup-prod-gallery", () =>
buildRollup(
rollupConfig.createGalleryConfig({
isProdBuild: true,
latestBuild: true,
})
)
);

View File

@ -1,11 +1,11 @@
// Tasks to run webpack.
// Tasks to run rspack.
import fs from "fs";
import path from "path";
import log from "fancy-log";
import gulp from "gulp";
import webpack from "webpack";
import WebpackDevServer from "webpack-dev-server";
import rspack from "@rspack/core";
import { RspackDevServer } from "@rspack/dev-server";
import env from "../env.cjs";
import paths from "../paths.cjs";
import {
@ -14,7 +14,8 @@ import {
createDemoConfig,
createGalleryConfig,
createHassioConfig,
} from "../webpack.cjs";
createLandingPageConfig,
} from "../rspack.cjs";
const bothBuilds = (createConfigFunc, params) => [
createConfigFunc({ ...params, latestBuild: true }),
@ -30,7 +31,7 @@ const isWsl =
/**
* @param {{
* compiler: import("webpack").Compiler,
* compiler: import("@rspack/core").Compiler,
* contentBase: string,
* port: number,
* listenHost?: string
@ -41,12 +42,13 @@ const runDevServer = async ({
contentBase,
port,
listenHost = undefined,
proxy = undefined,
}) => {
if (listenHost === undefined) {
// For dev container, we need to listen on all hosts
listenHost = env.isDevContainer() ? "0.0.0.0" : "localhost";
}
const server = new WebpackDevServer(
const server = new RspackDevServer(
{
hot: false,
open: true,
@ -56,13 +58,14 @@ const runDevServer = async ({
directory: contentBase,
watch: true,
},
proxy,
},
compiler
);
await server.start();
// Server listening
log("[webpack-dev-server]", `Project is running at http://localhost:${port}`);
log("[rspack-dev-server]", `Project is running at http://localhost:${port}`);
};
const doneHandler = (done) => (err, stats) => {
@ -87,16 +90,16 @@ const doneHandler = (done) => (err, stats) => {
const prodBuild = (conf) =>
new Promise((resolve) => {
webpack(
rspack(
conf,
// Resolve promise when done. Because we pass a callback, webpack closes itself
// Resolve promise when done. Because we pass a callback, rspack closes itself
doneHandler(resolve)
);
});
gulp.task("webpack-watch-app", () => {
gulp.task("rspack-watch-app", () => {
// This command will run forever because we don't close compiler
webpack(
rspack(
process.env.ES5
? bothBuilds(createAppConfig, { isProdBuild: false })
: createAppConfig({ isProdBuild: false, latestBuild: true })
@ -107,7 +110,7 @@ gulp.task("webpack-watch-app", () => {
);
});
gulp.task("webpack-prod-app", () =>
gulp.task("rspack-prod-app", () =>
prodBuild(
bothBuilds(createAppConfig, {
isProdBuild: true,
@ -117,9 +120,9 @@ gulp.task("webpack-prod-app", () =>
)
);
gulp.task("webpack-dev-server-demo", () =>
gulp.task("rspack-dev-server-demo", () =>
runDevServer({
compiler: webpack(
compiler: rspack(
createDemoConfig({ isProdBuild: false, latestBuild: true })
),
contentBase: paths.demo_output_root,
@ -127,17 +130,18 @@ gulp.task("webpack-dev-server-demo", () =>
})
);
gulp.task("webpack-prod-demo", () =>
gulp.task("rspack-prod-demo", () =>
prodBuild(
bothBuilds(createDemoConfig, {
isProdBuild: true,
isStatsBuild: env.isStatsBuild(),
})
)
);
gulp.task("webpack-dev-server-cast", () =>
gulp.task("rspack-dev-server-cast", () =>
runDevServer({
compiler: webpack(
compiler: rspack(
createCastConfig({ isProdBuild: false, latestBuild: true })
),
contentBase: paths.cast_output_root,
@ -147,7 +151,7 @@ gulp.task("webpack-dev-server-cast", () =>
})
);
gulp.task("webpack-prod-cast", () =>
gulp.task("rspack-prod-cast", () =>
prodBuild(
bothBuilds(createCastConfig, {
isProdBuild: true,
@ -155,9 +159,9 @@ gulp.task("webpack-prod-cast", () =>
)
);
gulp.task("webpack-watch-hassio", () => {
gulp.task("rspack-watch-hassio", () => {
// This command will run forever because we don't close compiler
webpack(
rspack(
createHassioConfig({
isProdBuild: false,
latestBuild: true,
@ -170,7 +174,7 @@ gulp.task("webpack-watch-hassio", () => {
);
});
gulp.task("webpack-prod-hassio", () =>
gulp.task("rspack-prod-hassio", () =>
prodBuild(
bothBuilds(createHassioConfig, {
isProdBuild: true,
@ -180,9 +184,9 @@ gulp.task("webpack-prod-hassio", () =>
)
);
gulp.task("webpack-dev-server-gallery", () =>
gulp.task("rspack-dev-server-gallery", () =>
runDevServer({
compiler: webpack(
compiler: rspack(
createGalleryConfig({ isProdBuild: false, latestBuild: true })
),
contentBase: paths.gallery_output_root,
@ -191,7 +195,7 @@ gulp.task("webpack-dev-server-gallery", () =>
})
);
gulp.task("webpack-prod-gallery", () =>
gulp.task("rspack-prod-gallery", () =>
prodBuild(
createGalleryConfig({
isProdBuild: true,
@ -199,3 +203,30 @@ gulp.task("webpack-prod-gallery", () =>
})
)
);
gulp.task("rspack-watch-landing-page", () => {
// This command will run forever because we don't close compiler
rspack(
process.env.ES5
? bothBuilds(createLandingPageConfig, { isProdBuild: false })
: createLandingPageConfig({ isProdBuild: false, latestBuild: true })
).watch({ poll: isWsl }, doneHandler());
gulp.watch(
path.join(paths.translations_src, "en.json"),
gulp.series(
"build-landing-page-translations",
"copy-translations-landing-page"
)
);
});
gulp.task("rspack-prod-landing-page", () =>
prodBuild(
bothBuilds(createLandingPageConfig, {
isProdBuild: true,
isStatsBuild: env.isStatsBuild(),
isTestBuild: env.isTestBuild(),
})
)
);

View File

@ -172,12 +172,14 @@ const createMasterTranslation = () =>
const FRAGMENTS = ["base"];
const toggleSupervisorFragment = async () => {
FRAGMENTS[0] = "supervisor";
const setFragment = (fragment) => async () => {
FRAGMENTS[0] = fragment;
};
const panelFragment = (fragment) =>
fragment !== "base" && fragment !== "supervisor";
fragment !== "base" &&
fragment !== "supervisor" &&
fragment !== "landing-page";
const HASHES = new Map();
@ -224,6 +226,9 @@ const createTranslations = async () => {
case "supervisor":
// Supervisor key is at the top level
return [flatten(data.supervisor), ""];
case "landing-page":
// landing-page key is at the top level
return [flatten(data["landing-page"]), ""];
default:
// Create a fragment with only the given panel
return [
@ -322,5 +327,10 @@ gulp.task(
gulp.task(
"build-supervisor-translations",
gulp.series(toggleSupervisorFragment, "build-translations")
gulp.series(setFragment("supervisor"), "build-translations")
);
gulp.task(
"build-landing-page-translations",
gulp.series(setFragment("landing-page"), "build-translations")
);

View File

@ -33,6 +33,22 @@ module.exports = {
),
gallery_output_static: path.resolve(__dirname, "../gallery/dist/static"),
landingPage_dir: path.resolve(__dirname, "../landing-page"),
landingPage_build: path.resolve(__dirname, "../landing-page/build"),
landingPage_output_root: path.resolve(__dirname, "../landing-page/dist"),
landingPage_output_latest: path.resolve(
__dirname,
"../landing-page/dist/frontend_latest"
),
landingPage_output_es5: path.resolve(
__dirname,
"../landing-page/dist/frontend_es5"
),
landingPage_output_static: path.resolve(
__dirname,
"../landing-page/dist/static"
),
hassio_dir: path.resolve(__dirname, "../hassio"),
hassio_output_root: path.resolve(__dirname, "../hassio/build"),
hassio_output_static: path.resolve(__dirname, "../hassio/build/static"),

View File

@ -1,14 +0,0 @@
module.exports = function (opts = {}) {
const dontHash = opts.dontHash || new Set();
return {
name: "dont-hash",
renderChunk(_code, chunk, _options) {
if (!chunk.isEntry || !dontHash.has(chunk.name)) {
return null;
}
chunk.fileName = `${chunk.name}.js`;
return null;
},
};
};

View File

@ -1,24 +0,0 @@
module.exports = function (userOptions = {}) {
// Files need to be absolute paths.
// This only works if the file has no exports
// and only is imported for its side effects
const files = userOptions.files || [];
if (files.length === 0) {
return {
name: "ignore",
};
}
return {
name: "ignore",
load(id) {
return files.some((toIgnorePath) => id.startsWith(toIgnorePath))
? {
code: "",
}
: null;
},
};
};

View File

@ -1,34 +0,0 @@
const url = require("url");
const defaultOptions = {
publicPath: "",
};
module.exports = function (userOptions = {}) {
const options = { ...defaultOptions, ...userOptions };
return {
name: "manifest",
generateBundle(outputOptions, bundle) {
const manifest = {};
for (const chunk of Object.values(bundle)) {
if (!chunk.isEntry) {
continue;
}
// Add js extension to mimic Webpack manifest.
manifest[`${chunk.name}.js`] = url.resolve(
options.publicPath,
chunk.fileName
);
}
this.emitFile({
type: "asset",
source: JSON.stringify(manifest, undefined, 2),
name: "manifest.json",
fileName: "manifest.json",
});
},
};
};

View File

@ -1,152 +0,0 @@
// Worker plugin
// Each worker will include all of its dependencies
// instead of relying on an importer.
// Forked from v.1.4.1
// https://github.com/surma/rollup-plugin-off-main-thread
/**
* Copyright 2018 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const rollup = require("rollup");
const path = require("path");
const MagicString = require("magic-string");
const defaultOpts = {
// A RegExp to find `new Workers()` calls. The second capture group _must_
// capture the provided file name without the quotes.
workerRegexp: /new Worker\((["'])(.+?)\1(,[^)]+)?\)/g,
plugins: ["node-resolve", "commonjs", "babel", "terser", "ignore"],
};
async function getBundledWorker(workerPath, rollupOptions) {
const bundle = await rollup.rollup({
...rollupOptions,
input: {
worker: workerPath,
},
});
const { output } = await bundle.generate({
// Generates cleanest output, we shouldn't have any imports/exports
// that would be incompatible with ES5.
format: "es",
// We should not export anything. This will fail build if we are.
exports: "none",
});
let code;
for (const chunkOrAsset of output) {
if (chunkOrAsset.name === "worker") {
code = chunkOrAsset.code;
} else if (chunkOrAsset.type !== "asset") {
throw new Error("Unexpected extra output");
}
}
return code;
}
module.exports = function (opts = {}) {
opts = { ...defaultOpts, ...opts };
let rollupOptions;
let refIds;
return {
name: "hass-worker",
async buildStart(options) {
refIds = {};
rollupOptions = {
plugins: options.plugins.filter((plugin) =>
opts.plugins.includes(plugin.name)
),
};
},
async transform(code, id) {
// Copy the regexp as they are stateful and this hook is async.
const workerRegexp = new RegExp(
opts.workerRegexp.source,
opts.workerRegexp.flags
);
if (!workerRegexp.test(code)) {
return undefined;
}
const ms = new MagicString(code);
// Reset the regexp
workerRegexp.lastIndex = 0;
for (;;) {
const match = workerRegexp.exec(code);
if (!match) {
break;
}
const workerFile = match[2];
let optionsObject = {};
// Parse the optional options object
if (match[3] && match[3].length > 0) {
// FIXME: ooooof!
// eslint-disable-next-line @typescript-eslint/no-implied-eval
optionsObject = new Function(`return ${match[3].slice(1)};`)();
}
delete optionsObject.type;
if (!/^.*\//.test(workerFile)) {
this.warn(
`Paths passed to the Worker constructor must be relative or absolute, i.e. start with /, ./ or ../ (just like dynamic import!). Ignoring "${workerFile}".`
);
continue;
}
// Find worker file and store it as a chunk with ID prefixed for our loader
// eslint-disable-next-line no-await-in-loop
const resolvedWorkerFile = (await this.resolve(workerFile, id)).id;
let chunkRefId;
if (resolvedWorkerFile in refIds) {
chunkRefId = refIds[resolvedWorkerFile];
} else {
this.addWatchFile(resolvedWorkerFile);
// eslint-disable-next-line no-await-in-loop
const source = await getBundledWorker(
resolvedWorkerFile,
rollupOptions
);
chunkRefId = refIds[resolvedWorkerFile] = this.emitFile({
name: path.basename(resolvedWorkerFile),
source,
type: "asset",
});
}
const workerParametersStartIndex = match.index + "new Worker(".length;
const workerParametersEndIndex =
match.index + match[0].length - ")".length;
ms.overwrite(
workerParametersStartIndex,
workerParametersEndIndex,
`import.meta.ROLLUP_FILE_URL_${chunkRefId}, ${JSON.stringify(
optionsObject
)}`
);
}
return {
code: ms.toString(),
map: ms.generateMap({ hires: true }),
};
},
};
};

View File

@ -1,146 +0,0 @@
const path = require("path");
const commonjs = require("@rollup/plugin-commonjs");
const resolve = require("@rollup/plugin-node-resolve");
const json = require("@rollup/plugin-json");
const { babel } = require("@rollup/plugin-babel");
const replace = require("@rollup/plugin-replace");
const visualizer = require("rollup-plugin-visualizer");
const { string } = require("rollup-plugin-string");
const { terser } = require("rollup-plugin-terser");
const manifest = require("./rollup-plugins/manifest-plugin.cjs");
const worker = require("./rollup-plugins/worker-plugin.cjs");
const dontHashPlugin = require("./rollup-plugins/dont-hash-plugin.cjs");
const ignore = require("./rollup-plugins/ignore-plugin.cjs");
const bundle = require("./bundle.cjs");
const paths = require("./paths.cjs");
const extensions = [".js", ".ts"];
/**
* @param {Object} arg
* @param { import("rollup").InputOption } arg.input
*/
const createRollupConfig = ({
entry,
outputPath,
defineOverlay,
isProdBuild,
latestBuild,
isStatsBuild,
publicPath,
dontHash,
isWDS,
}) => ({
/**
* @type { import("rollup").InputOptions }
*/
inputOptions: {
input: entry,
// Some entry points contain no JavaScript. This setting silences a warning about that.
// https://rollupjs.org/configuration-options/#preserveentrysignatures
preserveEntrySignatures: false,
plugins: [
ignore({
files: bundle
.emptyPackages({ latestBuild })
// TEMP HACK: Makes Rollup build work again
.concat(
require.resolve(
"@webcomponents/scoped-custom-element-registry/scoped-custom-element-registry.min"
)
),
}),
resolve({
extensions,
preferBuiltins: false,
browser: true,
rootDir: paths.polymer_dir,
}),
commonjs(),
json(),
babel({
...bundle.babelOptions({ latestBuild, isProdBuild }),
extensions,
babelHelpers: isWDS ? "inline" : "bundled",
}),
string({
// Import certain extensions as strings
include: [path.join(paths.polymer_dir, "node_modules/**/*.css")],
}),
replace(bundle.definedVars({ isProdBuild, latestBuild, defineOverlay })),
!isWDS &&
manifest({
publicPath,
}),
!isWDS && worker(),
!isWDS && dontHashPlugin({ dontHash }),
!isWDS && isProdBuild && terser(bundle.terserOptions({ latestBuild })),
!isWDS &&
isStatsBuild &&
visualizer({
// https://github.com/btd/rollup-plugin-visualizer#options
open: true,
sourcemap: true,
}),
].filter(Boolean),
},
/**
* @type { import("rollup").OutputOptions }
*/
outputOptions: {
// https://rollupjs.org/configuration-options/#output-dir
dir: outputPath,
// https://rollupjs.org/configuration-options/#output-format
format: latestBuild ? "es" : "systemjs",
// https://rollupjs.org/configuration-options/#output-externallivebindings
externalLiveBindings: false,
// https://rollupjs.org/configuration-options/#output-entryfilenames
// https://rollupjs.org/configuration-options/#output-chunkfilenames
// https://rollupjs.org/configuration-options/#output-assetfilenames
entryFileNames:
isProdBuild && !isStatsBuild ? "[name]-[hash].js" : "[name].js",
chunkFileNames: isProdBuild && !isStatsBuild ? "c.[hash].js" : "[name].js",
assetFileNames: isProdBuild && !isStatsBuild ? "a.[hash].js" : "[name].js",
// https://rollupjs.org/configuration-options/#output-sourcemap
sourcemap: isProdBuild ? true : "inline",
},
});
const createAppConfig = ({ isProdBuild, latestBuild, isStatsBuild, isWDS }) =>
createRollupConfig(
bundle.config.app({
isProdBuild,
latestBuild,
isStatsBuild,
isWDS,
})
);
const createDemoConfig = ({ isProdBuild, latestBuild, isStatsBuild }) =>
createRollupConfig(
bundle.config.demo({
isProdBuild,
latestBuild,
isStatsBuild,
})
);
const createCastConfig = ({ isProdBuild, latestBuild }) =>
createRollupConfig(bundle.config.cast({ isProdBuild, latestBuild }));
const createHassioConfig = ({ isProdBuild, latestBuild }) =>
createRollupConfig(bundle.config.hassio({ isProdBuild, latestBuild }));
const createGalleryConfig = ({ isProdBuild, latestBuild }) =>
createRollupConfig(bundle.config.gallery({ isProdBuild, latestBuild }));
module.exports = {
createAppConfig,
createDemoConfig,
createCastConfig,
createHassioConfig,
createGalleryConfig,
createRollupConfig,
};

View File

@ -1,16 +1,13 @@
const { existsSync } = require("fs");
const path = require("path");
const webpack = require("webpack");
const rspack = require("@rspack/core");
const { RsdoctorRspackPlugin } = require("@rsdoctor/rspack-plugin");
const { StatsWriterPlugin } = require("webpack-stats-plugin");
const filterStats = require("@bundle-stats/plugin-webpack-filter").default;
const TerserPlugin = require("terser-webpack-plugin");
const { WebpackManifestPlugin } = require("webpack-manifest-plugin");
const { WebpackManifestPlugin } = require("rspack-manifest-plugin");
const log = require("fancy-log");
const WebpackBar = require("webpackbar");
const {
TransformAsyncModulesPlugin,
} = require("transform-async-modules-webpack-plugin");
const { dependencies } = require("../package.json");
const WebpackBar = require("webpackbar/rspack");
const paths = require("./paths.cjs");
const bundle = require("./bundle.cjs");
@ -28,7 +25,7 @@ class LogStartCompilePlugin {
}
}
const createWebpackConfig = ({
const createRspackConfig = ({
name,
entry,
outputPath,
@ -102,13 +99,18 @@ const createWebpackConfig = ({
splitChunks: {
// Disable splitting for web workers and worklets because imports of
// external chunks are broken for:
// - ESM output: https://github.com/webpack/webpack/issues/17014
chunks: !isProdBuild
? // improve incremental build speed, but blows up bundle size
new RegExp(
`^(?!(${Object.keys(entry).join("|")}|.*work(?:er|let))$)`
)
: // - ESM output: https://github.com/webpack/webpack/issues/17014
// - Worklets use `importScripts`: https://github.com/webpack/webpack/issues/11543
chunks: (chunk) =>
(chunk) =>
!chunk.canBeInitial() &&
!new RegExp(`^.+-work${latestBuild ? "(?:let|er)" : "let"}$`).test(
chunk.name
),
!new RegExp(
`^.+-work${latestBuild ? "(?:let|er)" : "let"}$`
).test(chunk.name),
},
},
plugins: [
@ -117,10 +119,10 @@ const createWebpackConfig = ({
// Only include the JS of entrypoints
filter: (file) => file.isInitial && !file.name.endsWith(".map"),
}),
new webpack.DefinePlugin(
new rspack.DefinePlugin(
bundle.definedVars({ isProdBuild, latestBuild, defineOverlay })
),
new webpack.IgnorePlugin({
new rspack.IgnorePlugin({
checkResource(resource, context) {
// Only use ignore to intercept imports that we don't control
// inside node_module dependencies.
@ -152,7 +154,7 @@ const createWebpackConfig = ({
);
},
}),
new webpack.NormalModuleReplacementPlugin(
new rspack.NormalModuleReplacementPlugin(
new RegExp(
bundle.emptyPackages({ latestBuild, isHassioBuild }).join("|")
),
@ -168,10 +170,14 @@ const createWebpackConfig = ({
stats: { assets: true, chunks: true, modules: true },
transform: (stats) => JSON.stringify(filterStats(stats)),
}),
!latestBuild &&
new TransformAsyncModulesPlugin({
browserslistEnv: "legacy",
runtime: { version: dependencies["@babel/runtime"] },
isProdBuild &&
isStatsBuild &&
new RsdoctorRspackPlugin({
reportDir: path.join(paths.build_dir, "rsdoctor"),
features: ["plugins", "bundle"],
supports: {
generateTileGraph: true,
},
}),
].filter(Boolean),
resolve: {
@ -188,6 +194,7 @@ const createWebpackConfig = ({
"lit/directives/cache$": "lit/directives/cache.js",
"lit/directives/repeat$": "lit/directives/repeat.js",
"lit/directives/live$": "lit/directives/live.js",
"lit/directives/keyed$": "lit/directives/keyed.js",
"lit/polyfill-support$": "lit/polyfill-support.js",
"@lit-labs/virtualizer/layouts/grid":
"@lit-labs/virtualizer/layouts/grid.js",
@ -209,8 +216,6 @@ const createWebpackConfig = ({
isProdBuild && !isStatsBuild ? "[id].[contenthash][ext]" : "[id][ext]",
crossOriginLoading: "use-credentials",
hashFunction: "xxhash64",
hashDigest: "base64url",
hashDigestLength: 11, // full length of 64 bit base64url
path: outputPath,
publicPath,
// To silence warning in worker plugin
@ -252,17 +257,17 @@ const createAppConfig = ({
isStatsBuild,
isTestBuild,
}) =>
createWebpackConfig(
createRspackConfig(
bundle.config.app({ isProdBuild, latestBuild, isStatsBuild, isTestBuild })
);
const createDemoConfig = ({ isProdBuild, latestBuild, isStatsBuild }) =>
createWebpackConfig(
createRspackConfig(
bundle.config.demo({ isProdBuild, latestBuild, isStatsBuild })
);
const createCastConfig = ({ isProdBuild, latestBuild }) =>
createWebpackConfig(bundle.config.cast({ isProdBuild, latestBuild }));
createRspackConfig(bundle.config.cast({ isProdBuild, latestBuild }));
const createHassioConfig = ({
isProdBuild,
@ -270,7 +275,7 @@ const createHassioConfig = ({
isStatsBuild,
isTestBuild,
}) =>
createWebpackConfig(
createRspackConfig(
bundle.config.hassio({
isProdBuild,
latestBuild,
@ -280,7 +285,10 @@ const createHassioConfig = ({
);
const createGalleryConfig = ({ isProdBuild, latestBuild }) =>
createWebpackConfig(bundle.config.gallery({ isProdBuild, latestBuild }));
createRspackConfig(bundle.config.gallery({ isProdBuild, latestBuild }));
const createLandingPageConfig = ({ isProdBuild, latestBuild }) =>
createRspackConfig(bundle.config.landingPage({ isProdBuild, latestBuild }));
module.exports = {
createAppConfig,
@ -288,5 +296,6 @@ module.exports = {
createCastConfig,
createHassioConfig,
createGalleryConfig,
createWebpackConfig,
createRspackConfig,
createLandingPageConfig,
};

View File

@ -1,10 +0,0 @@
import rollup from "../build-scripts/rollup.cjs";
import env from "../build-scripts/env.cjs";
const config = rollup.createCastConfig({
isProdBuild: env.isProdBuild(),
latestBuild: true,
isStatsBuild: env.isStatsBuild(),
});
export default { ...config.inputOptions, output: config.outputOptions };

View File

@ -1,8 +0,0 @@
import webpack from "../build-scripts/webpack.cjs";
import env from "../build-scripts/env.cjs";
export default webpack.createCastConfig({
isProdBuild: env.isProdBuild(),
isStatsBuild: env.isStatsBuild(),
latestBuild: true,
});

View File

@ -1,10 +0,0 @@
import rollup from "../build-scripts/rollup.cjs";
import env from "../build-scripts/env.cjs";
const config = rollup.createDemoConfig({
isProdBuild: env.isProdBuild(),
latestBuild: true,
isStatsBuild: env.isStatsBuild(),
});
export default { ...config.inputOptions, output: config.outputOptions };

View File

@ -4,11 +4,6 @@
# Stop on errors
set -e
cd "$(dirname "$0")/.."
cd "$(dirname "$0")/../.."
export STATS=1
statsfile="compilation-stats-demo.json"
./node_modules/.bin/webpack-cli --profile --node-env=production --json=$statsfile
npx webpack-bundle-analyzer $statsfile dist/frontend_latest
rm -f $statsfile
./node_modules/.bin/gulp analyze-demo

View File

@ -1,11 +0,0 @@
import webpack from "../build-scripts/webpack.cjs";
import env from "../build-scripts/env.cjs";
// File just used for stats builds
const latestBuild = true;
export default webpack.createDemoConfig({
isProdBuild: env.isProdBuild(),
isStatsBuild: env.isStatsBuild(),
latestBuild,
});

164
eslint.config.mjs Normal file
View File

@ -0,0 +1,164 @@
/* eslint-disable import/no-extraneous-dependencies */
import unusedImports from "eslint-plugin-unused-imports";
import globals from "globals";
import tsParser from "@typescript-eslint/parser";
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all,
});
export default [
...compat.extends(
"airbnb-base",
"airbnb-typescript/base",
"plugin:@typescript-eslint/recommended",
"plugin:wc/recommended",
"plugin:lit/all",
"plugin:lit-a11y/recommended",
"prettier"
),
{
plugins: {
"unused-imports": unusedImports,
},
languageOptions: {
globals: {
...globals.browser,
__DEV__: false,
__DEMO__: false,
__BUILD__: false,
__VERSION__: false,
__STATIC_PATH__: false,
__SUPERVISOR__: false,
Polymer: true,
},
parser: tsParser,
ecmaVersion: 2020,
sourceType: "module",
parserOptions: {
ecmaFeatures: {
modules: true,
},
project: "./tsconfig.json",
},
},
settings: {
"import/resolver": {
webpack: {
config: "./rspack.config.cjs",
},
},
},
rules: {
"class-methods-use-this": "off",
"new-cap": "off",
"prefer-template": "off",
"object-shorthand": "off",
"func-names": "off",
"no-underscore-dangle": "off",
strict: "off",
"no-plusplus": "off",
"no-bitwise": "error",
"comma-dangle": "off",
"vars-on-top": "off",
"no-continue": "off",
"no-param-reassign": "off",
"no-multi-assign": "off",
"no-console": "error",
radix: "off",
"no-alert": "off",
"no-nested-ternary": "off",
"prefer-destructuring": "off",
"no-restricted-globals": [2, "event"],
"prefer-promise-reject-errors": "off",
"import/prefer-default-export": "off",
"import/no-default-export": "off",
"import/no-unresolved": "off",
"import/no-cycle": "off",
"import/extensions": [
"error",
"ignorePackages",
{
ts: "never",
js: "never",
},
],
"no-restricted-syntax": ["error", "LabeledStatement", "WithStatement"],
"object-curly-newline": "off",
"default-case": "off",
"wc/no-self-class": "off",
"no-shadow": "off",
"@typescript-eslint/camelcase": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/no-shadow": ["error"],
"@typescript-eslint/naming-convention": [
"off",
{
selector: "default",
format: ["camelCase", "snake_case"],
leadingUnderscore: "allow",
trailingUnderscore: "allow",
},
{
selector: ["variable"],
format: ["camelCase", "snake_case", "UPPER_CASE"],
leadingUnderscore: "allow",
trailingUnderscore: "allow",
},
{
selector: "typeLike",
format: ["PascalCase"],
},
],
"@typescript-eslint/no-unused-vars": "off",
"unused-imports/no-unused-vars": [
"error",
{
vars: "all",
varsIgnorePattern: "^_",
args: "after-used",
argsIgnorePattern: "^_",
ignoreRestSiblings: true,
},
],
"unused-imports/no-unused-imports": "error",
"lit/attribute-names": "warn",
"lit/attribute-value-entities": "off",
"lit/no-template-map": "off",
"lit/no-native-attributes": "warn",
"lit/no-this-assign-in-render": "warn",
"lit-a11y/click-events-have-key-events": ["off"],
"lit-a11y/no-autofocus": "off",
"lit-a11y/alt-text": "warn",
"lit-a11y/anchor-is-valid": "warn",
"lit-a11y/role-has-required-aria-attrs": "warn",
"@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/no-import-type-side-effects": "error",
},
},
];

View File

@ -1,6 +0,0 @@
{
"extends": "../.eslintrc.json",
"rules": {
"no-console": 0
}
}

10
gallery/eslint.config.mjs Normal file
View File

@ -0,0 +1,10 @@
import rootConfig from "../eslint.config.mjs";
export default [
...rootConfig,
{
rules: {
"no-console": "off",
},
},
];

View File

@ -1,10 +0,0 @@
import rollup from "../build-scripts/rollup.cjs";
import env from "../build-scripts/env.cjs";
const config = rollup.createGalleryConfig({
isProdBuild: env.isProdBuild(),
latestBuild: true,
isStatsBuild: env.isStatsBuild(),
});
export default { ...config.inputOptions, output: config.outputOptions };

View File

@ -1,4 +1,3 @@
/* eslint-disable lit/no-template-arrow */
import type { TemplateResult } from "lit";
import { LitElement, html, css } from "lit";
import { customElement, state } from "lit/decorators";
@ -15,7 +14,6 @@ import { HaDelayAction } from "../../../../src/panels/config/automation/action/t
import { HaDeviceAction } from "../../../../src/panels/config/automation/action/types/ha-automation-action-device_id";
import { HaEventAction } from "../../../../src/panels/config/automation/action/types/ha-automation-action-event";
import { HaRepeatAction } from "../../../../src/panels/config/automation/action/types/ha-automation-action-repeat";
import { HaSceneAction } from "../../../../src/panels/config/automation/action/types/ha-automation-action-activate_scene";
import { HaServiceAction } from "../../../../src/panels/config/automation/action/types/ha-automation-action-service";
import { HaWaitForTriggerAction } from "../../../../src/panels/config/automation/action/types/ha-automation-action-wait_for_trigger";
import { HaWaitAction } from "../../../../src/panels/config/automation/action/types/ha-automation-action-wait_template";
@ -33,7 +31,6 @@ const SCHEMAS: { name: string; actions: Action[] }[] = [
{ name: "Service", actions: [HaServiceAction.defaultConfig] },
{ name: "Condition", actions: [HaConditionAction.defaultConfig] },
{ name: "Delay", actions: [HaDelayAction.defaultConfig] },
{ name: "Scene", actions: [HaSceneAction.defaultConfig] },
{ name: "Play media", actions: [HaPlayMediaAction.defaultConfig] },
{ name: "Wait", actions: [HaWaitAction.defaultConfig] },
{ name: "WaitForTrigger", actions: [HaWaitForTriggerAction.defaultConfig] },

View File

@ -1,4 +1,3 @@
/* eslint-disable lit/no-template-arrow */
import type { TemplateResult } from "lit";
import { LitElement, html, css } from "lit";
import { customElement, state } from "lit/decorators";

View File

@ -86,9 +86,11 @@ const ENTITIES = [
friendly_name: "Sensibo purifier",
fan_modes: ["low", "high"],
fan_mode: "low",
swing_modes: ["on", "off", "both", "vertical", "horizontal"],
swing_mode: "vertical",
supported_features: 41,
swing_modes: ["both", "rangefull", "off"],
swing_mode: "rangefull",
swing_horizontal_modes: ["both", "rangefull", "off"],
swing_horizontal_mode: "both",
supported_features: 553,
}),
getEntity("climate", "unavailable", "unavailable", {
supported_features: 43,
@ -188,11 +190,13 @@ const CONFIGS = [
- type: climate-swing-modes
style: icons
swing_modes:
- 'on'
- 'off'
- 'both'
- 'vertical'
- 'horizontal'
- 'rangefull'
- 'off'
swing_horizontal_modes:
- 'both'
- 'rangefull'
- 'off'
`,
},
{

View File

@ -78,16 +78,19 @@ const ENTITIES = [
fan_modes: ["on_low", "on_high", "auto_low", "auto_high", "off"],
preset_modes: ["home", "eco", "away"],
swing_modes: ["auto", "1", "2", "3", "off"],
switch_horizontal_modes: ["auto", "4", "5", "6", "off"],
current_temperature: 23,
target_temp_high: 24,
target_temp_low: 21,
fan_mode: "auto_low",
preset_mode: "home",
swing_mode: "auto",
swing_horizontal_mode: "off",
supported_features:
ClimateEntityFeature.TURN_ON +
ClimateEntityFeature.TURN_OFF +
ClimateEntityFeature.SWING_MODE +
ClimateEntityFeature.SWING_HORIZONTAL_MODE +
ClimateEntityFeature.PRESET_MODE +
ClimateEntityFeature.FAN_MODE +
ClimateEntityFeature.TARGET_TEMPERATURE_RANGE,

View File

@ -1,8 +0,0 @@
import webpack from "../build-scripts/webpack.cjs";
import env from "../build-scripts/env.cjs";
export default webpack.createGalleryConfig({
isProdBuild: env.isProdBuild(),
isStatsBuild: env.isStatsBuild(),
latestBuild: true,
});

View File

@ -1,10 +0,0 @@
import rollup from "../build-scripts/rollup.cjs";
import env from "../build-scripts/env.cjs";
const config = rollup.createHassioConfig({
isProdBuild: env.isProdBuild(),
latestBuild: false,
isStatsBuild: env.isStatsBuild(),
});
export default { ...config.inputOptions, output: config.outputOptions };

View File

@ -315,6 +315,7 @@ class HassioAddonConfig extends LitElement {
text: this.supervisor.localize("confirm.reset_options.text"),
confirmText: this.supervisor.localize("common.reset_options"),
dismissText: this.supervisor.localize("common.cancel"),
destructive: true,
});
if (!confirmed) {

View File

@ -323,6 +323,7 @@ export class HassioBackups extends LitElement {
number: this._selectedBackups.length,
}),
confirmText: this.supervisor.localize("backup.delete_backup_confirm"),
destructive: true,
});
if (!confirm) {

View File

@ -302,6 +302,7 @@ class HassioBackupDialog
text: supervisor!.localize("backup.confirm_delete_text"),
confirmText: supervisor!.localize("backup.delete"),
dismissText: supervisor!.localize("backup.cancel"),
destructive: true,
}))
) {
return;

View File

@ -1,8 +0,0 @@
import webpack from "../build-scripts/webpack.cjs";
import env from "../build-scripts/env.cjs";
export default webpack.createHassioConfig({
isProdBuild: env.isProdBuild(),
isStatsBuild: env.isStatsBuild(),
latestBuild: true,
});

44
landing-page/README.md Normal file
View File

@ -0,0 +1,44 @@
# Home Assistant OS Landingpage
On initial startup of Home Assistant, HAOS needs to download Home Assistant core before the setup can start.
In this time the [home-assistant/landingpage](https://github.com/home-assistant/landingpage) is serving a "Preparing Home Assistant" page.
## Functionality
- Progress bar to show download
- Show / hide supervisor logs
- Links
- Read our Vision
- Join our community
- Download our app
- DNS issue handler
- if the supervisor is not able to connect to the internet
- Show actions to set dns to google or cloudflare to resolve the issue
- Error handler
- if something with the installation goes wrong, we show the logs
## Develop
It is similar to the core frontend dev.
- frontend repo is building stuff
- landingpage repo can set the frontend repo path and serve the dev frontend
### landingpage dev server
- clone [home-assistant/landingpage](https://github.com/home-assistant/landingpage)
- Add frontend repo as mount to your devcontainer config
- please do not commit this changes, you can remove it after initial dev container build, because the build will keep the options as long as you don't rebuild it.
- `"mounts": ["source=/path/to/hass/frontend,target=/workspaces/frontend,type=bind,consistency=cached"]`
- use the dev container
- start the dev server with following optional env vars:
- `SUPERVISOR_HOST` to have real supervisor data, you can [setup a supervisor remote API access](https://developers.home-assistant.io/docs/supervisor/development/#supervisor-api-access) and set the host of your supervisor. e.g.: `SUPERVISOR_HOST=192.168.0.20:8888`
- `SUPERVISOR_TOKEN` the supervisor api token you get from the Remote API proxy Addon Logs
- `FRONTEND_PATH` the path inside your container should be `/workspaces/frontend`
- example: `SUPERVISOR_TOKEN=abc123 SUPERVISOR_HOST=192.168.0.20:8888 FRONTEND_PATH=/workspaces/frontend go run main.go http.go mdns.go`
- You can also add this into your devcontainer settings, but then it's not so flexible to change if you want to test something else.
### frontend dev server
- install all dependencies
- run `landing-page/script/develop`

View File

@ -0,0 +1,8 @@
import rootConfig from "../eslint.config.mjs";
export default [
...rootConfig,
{
rules: {},
},
];

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,3 @@
<svg width="92" height="136" viewBox="0 0 92 136" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M76.38 104.9H3.03C2.24231 104.9 1.48688 105.213 0.929897 105.77C0.372914 106.327 0.0600052 107.082 0.0600052 107.87V132.47C0.0600052 133.258 0.372914 134.013 0.929897 134.57C1.48688 135.127 2.24231 135.44 3.03 135.44H12.36C13.1477 135.44 13.9031 135.127 14.4601 134.57C15.0171 134.013 15.33 133.258 15.33 132.47V120.17H76.39V132.47C76.39 133.258 76.7029 134.013 77.2599 134.57C77.8169 135.127 78.5723 135.44 79.36 135.44H88.69C89.4777 135.44 90.2331 135.127 90.7901 134.57C91.3471 134.013 91.66 133.258 91.66 132.47V107.87C91.66 107.082 91.3471 106.327 90.7901 105.77C90.2331 105.213 89.4777 104.9 88.69 104.9H76.39H76.38ZM50.04 2.24996C47.73 -0.0600439 43.95 -0.0600439 41.65 2.24996L4.25 39.65C1.94 41.96 0.0500031 46.52 0.0500031 49.78V83.7C0.0500031 86.96 2.72 89.64 5.99 89.64H85.7C88.96 89.64 91.64 86.97 91.64 83.7V49.78C91.64 46.52 89.75 41.96 87.44 39.65L50.04 2.24996Z" fill="#18BCF2"/>
</svg>

After

Width:  |  Height:  |  Size: 1011 B

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.2 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1,10 @@
<svg width="75" height="79" viewBox="0 0 75 79" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M73.8393 17.4898C72.6973 9.00165 65.2994 2.31235 56.5296 1.01614C55.05 0.797115 49.4441 0 36.4582 0H36.3612C23.3717 0 20.585 0.797115 19.1054 1.01614C10.5798 2.27644 2.79399 8.28712 0.904997 16.8758C-0.00358524 21.1056 -0.100549 25.7949 0.0682394 30.0965C0.308852 36.2651 0.355538 42.423 0.91577 48.5665C1.30307 52.6474 1.97872 56.6957 2.93763 60.6812C4.73325 68.042 12.0019 74.1676 19.1233 76.6666C26.7478 79.2728 34.9474 79.7055 42.8039 77.9162C43.6682 77.7151 44.5217 77.4817 45.3645 77.216C47.275 76.6092 49.5123 75.9305 51.1571 74.7385C51.1797 74.7217 51.1982 74.7001 51.2112 74.6753C51.2243 74.6504 51.2316 74.6229 51.2325 74.5948V68.6416C51.2321 68.6154 51.2259 68.5896 51.2142 68.5661C51.2025 68.5426 51.1858 68.522 51.1651 68.5058C51.1444 68.4896 51.1204 68.4783 51.0948 68.4726C51.0692 68.4669 51.0426 68.467 51.0171 68.4729C45.9835 69.675 40.8254 70.2777 35.6502 70.2682C26.7439 70.2682 24.3486 66.042 23.6626 64.2826C23.1113 62.762 22.7612 61.1759 22.6212 59.5646C22.6197 59.5375 22.6247 59.5105 22.6357 59.4857C22.6466 59.4609 22.6633 59.4391 22.6843 59.422C22.7053 59.4048 22.73 59.3929 22.7565 59.3871C22.783 59.3813 22.8104 59.3818 22.8367 59.3886C27.7864 60.5826 32.8604 61.1853 37.9522 61.1839C39.1768 61.1839 40.3978 61.1839 41.6224 61.1516C46.7435 61.008 52.1411 60.7459 57.1796 59.7621C57.3053 59.7369 57.431 59.7154 57.5387 59.6831C65.4861 58.157 73.0493 53.3672 73.8178 41.2381C73.8465 40.7606 73.9184 36.2364 73.9184 35.7409C73.9219 34.0569 74.4606 23.7949 73.8393 17.4898Z" fill="url(#paint0_linear_549_34)"/>
<path d="M61.2484 27.0263V48.114H52.8916V27.6475C52.8916 23.3388 51.096 21.1413 47.4437 21.1413C43.4287 21.1413 41.4177 23.7409 41.4177 28.8755V40.0782H33.1111V28.8755C33.1111 23.7409 31.0965 21.1413 27.0815 21.1413C23.4507 21.1413 21.6371 23.3388 21.6371 27.6475V48.114H13.2839V27.0263C13.2839 22.7176 14.384 19.2946 16.5843 16.7572C18.8539 14.2258 21.8311 12.926 25.5264 12.926C29.8036 12.926 33.0357 14.5705 35.1905 17.8559L37.2698 21.346L39.3527 17.8559C41.5074 14.5705 44.7395 12.926 49.0095 12.926C52.7013 12.926 55.6784 14.2258 57.9553 16.7572C60.1531 19.2922 61.2508 22.7152 61.2484 27.0263Z" fill="white"/>
<defs>
<linearGradient id="paint0_linear_549_34" x1="37.0692" y1="0" x2="37.0692" y2="79" gradientUnits="userSpaceOnUse">
<stop stop-color="#6364FF"/>
<stop offset="1" stop-color="#563ACC"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@ -0,0 +1,3 @@
<svg width="1200" height="1227" viewBox="0 0 1200 1227" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M714.163 519.284L1160.89 0H1055.03L667.137 450.887L357.328 0H0L468.492 681.821L0 1226.37H105.866L515.491 750.218L842.672 1226.37H1200L714.137 519.284H714.163ZM569.165 687.828L521.697 619.934L144.011 79.6944H306.615L611.412 515.685L658.88 583.579L1055.08 1150.3H892.476L569.165 687.854V687.828Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 430 B

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.2 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 52 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 69 KiB

View File

@ -0,0 +1,9 @@
#!/bin/sh
# Run the landing-page
# Stop on errors
set -e
cd "$(dirname "$0")/../.."
./node_modules/.bin/gulp build-landing-page

9
landing-page/script/develop Executable file
View File

@ -0,0 +1,9 @@
#!/bin/sh
# Run the landing-page
# Stop on errors
set -e
cd "$(dirname "$0")/../.."
./node_modules/.bin/gulp develop-landing-page

View File

@ -0,0 +1,334 @@
import "@material/mwc-linear-progress/mwc-linear-progress";
import { mdiArrowCollapseDown, mdiDownload } from "@mdi/js";
// eslint-disable-next-line import/extensions
import { IntersectionController } from "@lit-labs/observers/intersection-controller.js";
import { LitElement, type PropertyValues, css, html, nothing } from "lit";
import { classMap } from "lit/directives/class-map";
import { customElement, property, query, state } from "lit/decorators";
import type {
LandingPageKeys,
LocalizeFunc,
} from "../../../src/common/translations/localize";
import "../../../src/components/ha-button";
import "../../../src/components/ha-icon-button";
import "../../../src/components/ha-svg-icon";
import "../../../src/components/ha-ansi-to-html";
import "../../../src/components/ha-alert";
import type { HaAnsiToHtml } from "../../../src/components/ha-ansi-to-html";
import {
getObserverLogs,
downloadUrl as observerLogsDownloadUrl,
} from "../data/observer";
import { fireEvent } from "../../../src/common/dom/fire_event";
import { fileDownload } from "../../../src/util/file_download";
import { getSupervisorLogs, getSupervisorLogsFollow } from "../data/supervisor";
const ERROR_CHECK = /^[\d\s-:]+(ERROR|CRITICAL)(.*)/gm;
declare global {
interface HASSDomEvents {
"landing-page-error": undefined;
}
}
const SCHEDULE_FETCH_OBSERVER_LOGS = 5;
@customElement("landing-page-logs")
class LandingPageLogs extends LitElement {
@property({ attribute: false })
public localize!: LocalizeFunc<LandingPageKeys>;
@query("ha-ansi-to-html") private _ansiToHtmlElement?: HaAnsiToHtml;
@query(".logs") private _logElement?: HTMLElement;
@query("#scroll-bottom-marker")
private _scrollBottomMarkerElement?: HTMLElement;
@state() private _show = false;
@state() private _scrolledToBottomController =
new IntersectionController<boolean>(this, {
callback(this: IntersectionController<boolean>, entries) {
return entries[0].isIntersecting;
},
});
@state() private _error = false;
@state() private _newLogsIndicator?: boolean;
@state() private _logLinesCount = 0;
protected render() {
return html`
<div class="actions">
<ha-button @click=${this._toggleLogDetails}>
${this.localize(this._show ? "hide_details" : "show_details")}
</ha-button>
${this._show
? html`<ha-icon-button
.label=${this.localize("logs.download_logs")}
.path=${mdiDownload}
@click=${this._downloadLogs}
></ha-icon-button>`
: nothing}
</div>
${this._error
? html`
<ha-alert
alert-type="error"
.title=${this.localize("logs.fetch_error")}
>
<ha-button @click=${this._startLogStream}>
${this.localize("logs.retry")}
</ha-button>
</ha-alert>
`
: nothing}
<div
class=${classMap({
logs: true,
hidden: !this._show,
})}
>
<ha-ansi-to-html></ha-ansi-to-html>
<div id="scroll-bottom-marker"></div>
</div>
<ha-button
class="new-logs-indicator ${classMap({
visible:
(this._show &&
this._newLogsIndicator &&
!this._scrolledToBottomController.value) ||
false,
})}"
@click=${this._scrollToBottom}
>
<ha-svg-icon .path=${mdiArrowCollapseDown} slot="icon"></ha-svg-icon>
${this.localize("logs.scroll_down_button")}
<ha-svg-icon
.path=${mdiArrowCollapseDown}
slot="trailingIcon"
></ha-svg-icon>
</ha-button>
`;
}
protected firstUpdated(changedProps: PropertyValues): void {
super.firstUpdated(changedProps);
this._scrolledToBottomController.observe(this._scrollBottomMarkerElement!);
this._startLogStream();
}
protected updated(changedProps: PropertyValues): void {
super.updated(changedProps);
if (this._newLogsIndicator && this._scrolledToBottomController.value) {
this._newLogsIndicator = false;
}
if (changedProps.has("_show") && this._show) {
this._scrollToBottom();
}
}
private _toggleLogDetails() {
this._show = !this._show;
}
private _scrollToBottom(): void {
if (this._logElement) {
this._newLogsIndicator = false;
this._logElement!.scrollTo(0, this._logElement!.scrollHeight);
}
}
private _displayLogs(logs: string, tempLogLine = "", clear = false): string {
if (clear) {
this._ansiToHtmlElement?.clear();
this._logLinesCount = 0;
}
const showError = ERROR_CHECK.test(logs);
const scrolledToBottom = this._scrolledToBottomController.value;
const lines = `${tempLogLine}${logs}`
.split("\n")
.filter((line) => line.trim() !== "");
// handle edge case where the last line is not complete
if (logs.endsWith("\n")) {
tempLogLine = "";
} else {
tempLogLine = lines.splice(-1, 1)[0];
}
if (lines.length) {
this._ansiToHtmlElement?.parseLinesToColoredPre(lines);
this._logLinesCount += lines.length;
}
if (showError) {
fireEvent(this, "landing-page-error");
this._show = true;
}
if (showError || (scrolledToBottom && this._logElement)) {
this._scrollToBottom();
} else {
this._newLogsIndicator = true;
}
return tempLogLine;
}
private async _startLogStream() {
this._error = false;
this._newLogsIndicator = false;
this._ansiToHtmlElement?.clear();
try {
const response = await getSupervisorLogsFollow();
if (!response.ok || !response.body) {
throw new Error("No stream body found");
}
let tempLogLine = "";
const reader = response.body.getReader();
const decoder = new TextDecoder();
let done = false;
while (!done) {
// eslint-disable-next-line no-await-in-loop
const { value, done: readerDone } = await reader.read();
done = readerDone;
if (value) {
const chunk = decoder.decode(value, { stream: !done });
tempLogLine = this._displayLogs(chunk, tempLogLine);
}
}
} catch (err: any) {
// eslint-disable-next-line no-console
console.error(err);
// fallback to observerlogs if there is a problem with supervisor
this._loadObserverLogs();
}
}
private _scheduleObserverLogs() {
setTimeout(async () => {
try {
// check if supervisor logs are available
const superVisorLogsResponse = await getSupervisorLogs(1);
if (superVisorLogsResponse.ok) {
this._startLogStream();
return;
}
} catch (err) {
// ignore and continue with observer logs
}
this._loadObserverLogs();
}, SCHEDULE_FETCH_OBSERVER_LOGS * 1000);
}
private async _loadObserverLogs() {
try {
const response = await getObserverLogs();
if (!response.ok) {
throw new Error("Error fetching observer logs");
}
const logs = await response.text();
this._displayLogs(logs, "", true);
this._scheduleObserverLogs();
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
this._error = true;
}
}
private _downloadLogs() {
const timeString = new Date().toISOString().replace(/:/g, "-");
fileDownload(observerLogsDownloadUrl, `observer_${timeString}.log`);
}
static styles = [
css`
:host {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
}
ha-alert {
width: 100%;
}
.actions {
position: relative;
width: 100%;
text-align: center;
}
.actions ha-icon-button {
position: absolute;
right: 0;
top: -4px;
--icon-primary-color: var(--primary-color);
}
.logs {
width: 100%;
max-height: 300px;
overflow: auto;
border: 1px solid var(--divider-color);
border-radius: 4px;
padding: 4px;
}
.logs.hidden {
display: none;
}
.new-logs-indicator {
--mdc-theme-primary: var(--text-primary-color);
overflow: hidden;
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 0;
background-color: var(--primary-color);
border-radius: 8px;
transition: height 0.4s ease-out;
display: flex;
justify-content: space-between;
align-items: center;
}
.new-logs-indicator.visible {
height: 24px;
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"landing-page-logs": LandingPageLogs;
}
}

View File

@ -0,0 +1,186 @@
import "@material/mwc-linear-progress/mwc-linear-progress";
import {
type CSSResultGroup,
LitElement,
type PropertyValues,
css,
html,
nothing,
} from "lit";
import { customElement, property, state } from "lit/decorators";
import type {
LandingPageKeys,
LocalizeFunc,
} from "../../../src/common/translations/localize";
import "../../../src/components/ha-button";
import "../../../src/components/ha-alert";
import {
ALTERNATIVE_DNS_SERVERS,
getSupervisorNetworkInfo,
setSupervisorNetworkDns,
} from "../data/supervisor";
import { fireEvent } from "../../../src/common/dom/fire_event";
import { showAlertDialog } from "../../../src/dialogs/generic/show-dialog-box";
const SCHEDULE_FETCH_NETWORK_INFO_SECONDS = 5;
@customElement("landing-page-network")
class LandingPageNetwork extends LitElement {
@property({ attribute: false })
public localize!: LocalizeFunc<LandingPageKeys>;
@state() private _networkIssue = false;
@state() private _getNetworkInfoError = false;
@state() private _dnsPrimaryInterfaceNameservers?: string;
@state() private _dnsPrimaryInterface?: string;
protected render() {
if (!this._networkIssue && !this._getNetworkInfoError) {
return nothing;
}
if (this._getNetworkInfoError) {
return html`
<ha-alert alert-type="error">
<p>${this.localize("network_issue.error_get_network_info")}</p>
</ha-alert>
`;
}
return html`
<ha-alert
alert-type="warning"
.title=${this.localize("network_issue.title")}
>
<p>
${this.localize("network_issue.description", {
dns: this._dnsPrimaryInterfaceNameservers || "?",
})}
</p>
<p>${this.localize("network_issue.resolve_different")}</p>
${!this._dnsPrimaryInterfaceNameservers
? html`
<p>
<b>${this.localize("network_issue.no_primary_interface")} </b>
</p>
`
: nothing}
<div class="actions">
${ALTERNATIVE_DNS_SERVERS.map(
({ translationKey }, key) =>
html`<ha-button
.index=${key}
.disabled=${!this._dnsPrimaryInterfaceNameservers}
@click=${this._setDns}
>${this.localize(translationKey)}</ha-button
>`
)}
</div>
</ha-alert>
`;
}
protected firstUpdated(_changedProperties: PropertyValues): void {
super.firstUpdated(_changedProperties);
this._fetchSupervisorInfo();
}
private _scheduleFetchSupervisorInfo() {
setTimeout(
() => this._fetchSupervisorInfo(),
SCHEDULE_FETCH_NETWORK_INFO_SECONDS * 1000
);
}
private async _fetchSupervisorInfo() {
let data;
try {
const response = await getSupervisorNetworkInfo();
if (!response.ok) {
throw new Error("Failed to fetch network info");
}
({ data } = await response.json());
} catch (err) {
// eslint-disable-next-line no-console
console.error(err);
this._getNetworkInfoError = true;
this._dnsPrimaryInterfaceNameservers = undefined;
this._dnsPrimaryInterface = undefined;
return;
}
this._getNetworkInfoError = false;
const primaryInterface = data.interfaces.find(
(intf) => intf.primary && intf.enabled
);
if (primaryInterface) {
this._dnsPrimaryInterfaceNameservers = [
...(primaryInterface.ipv4?.nameservers || []),
...(primaryInterface.ipv6?.nameservers || []),
].join(", ");
this._dnsPrimaryInterface = primaryInterface.interface;
} else {
this._dnsPrimaryInterfaceNameservers = undefined;
this._dnsPrimaryInterface = undefined;
}
if (!data.host_internet) {
this._networkIssue = true;
} else {
this._networkIssue = false;
}
fireEvent(this, "value-changed", {
value: this._networkIssue,
});
this._scheduleFetchSupervisorInfo();
}
private async _setDns(ev) {
const index = ev.target?.index;
try {
const response = await setSupervisorNetworkDns(
index,
this._dnsPrimaryInterface!
);
if (!response.ok) {
throw new Error("Failed to set DNS");
}
this._networkIssue = false;
} catch (err: any) {
// eslint-disable-next-line no-console
console.error(err);
showAlertDialog(this, {
title: this.localize("network_issue.failed"),
warning: true,
text: `${this.localize(
"network_issue.set_dns_failed"
)}${err?.message ? ` ${this.localize("network_issue.error")}: ${err.message}` : ""}`,
confirmText: this.localize("network_issue.close"),
});
}
}
static get styles(): CSSResultGroup {
return [
css`
.actions {
display: flex;
justify-content: flex-end;
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"landing-page-network": LandingPageNetwork;
}
}

View File

@ -0,0 +1,5 @@
export async function getObserverLogs() {
return fetch("/observer/logs");
}
export const downloadUrl = "/observer/logs";

View File

@ -0,0 +1,59 @@
import type { LandingPageKeys } from "../../../src/common/translations/localize";
export const ALTERNATIVE_DNS_SERVERS: {
ipv4: string[];
ipv6: string[];
translationKey: LandingPageKeys;
}[] = [
{
ipv4: ["1.1.1.1", "1.0.0.1"],
ipv6: ["2606:4700:4700::1111", "2606:4700:4700::1001"],
translationKey: "network_issue.use_cloudflare",
},
{
ipv4: ["8.8.8.8", "8.8.4.4"],
ipv6: ["2001:4860:4860::8888", "2001:4860:4860::8844"],
translationKey: "network_issue.use_google",
},
];
export async function getSupervisorLogs(lines = 100) {
return fetch(`/supervisor/supervisor/logs?lines=${lines}`, {
headers: {
Accept: "text/plain",
},
});
}
export async function getSupervisorLogsFollow(lines = 500) {
return fetch(`/supervisor/supervisor/logs/follow?lines=${lines}`, {
headers: {
Accept: "text/plain",
},
});
}
export async function getSupervisorNetworkInfo() {
return fetch("/supervisor/network/info");
}
export const setSupervisorNetworkDns = async (
dnsServerIndex: number,
primaryInterface: string
) =>
fetch(`/supervisor/network/interface/${primaryInterface}/update`, {
method: "POST",
body: JSON.stringify({
ipv4: {
method: "auto",
nameservers: ALTERNATIVE_DNS_SERVERS[dnsServerIndex].ipv4,
},
ipv6: {
method: "auto",
nameservers: ALTERNATIVE_DNS_SERVERS[dnsServerIndex].ipv6,
},
}),
headers: {
"Content-Type": "application/json",
},
});

View File

@ -0,0 +1,3 @@
import "./ha-landing-page";
import("../../src/resources/ha-style");

View File

@ -0,0 +1,179 @@
import "@material/mwc-linear-progress";
import { type PropertyValues, css, html, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../src/components/ha-alert";
import { haStyle } from "../../src/resources/styles";
import "../../src/onboarding/onboarding-welcome-links";
import "./components/landing-page-network";
import "./components/landing-page-logs";
import { extractSearchParam } from "../../src/common/url/search-params";
import { onBoardingStyles } from "../../src/onboarding/styles";
import { makeDialogManager } from "../../src/dialogs/make-dialog-manager";
import { LandingPageBaseElement } from "./landing-page-base-element";
const SCHEDULE_CORE_CHECK_SECONDS = 5;
@customElement("ha-landing-page")
class HaLandingPage extends LandingPageBaseElement {
@property({ attribute: false }) public translationFragment = "landing-page";
@state() private _networkIssue = false;
@state() private _supervisorError = false;
private _mobileApp =
extractSearchParam("redirect_uri") === "homeassistant://auth-callback";
render() {
return html`
<ha-card>
<div class="card-content">
<h1>${this.localize("header")}</h1>
${!this._networkIssue && !this._supervisorError
? html`
<p>${this.localize("subheader")}</p>
<mwc-linear-progress indeterminate></mwc-linear-progress>
`
: nothing}
<landing-page-network
@value-changed=${this._networkInfoChanged}
.localize=${this.localize}
></landing-page-network>
${this._supervisorError
? html`
<ha-alert
alert-type="error"
.title=${this.localize("error_title")}
>
${this.localize("error_description")}
</ha-alert>
`
: nothing}
<landing-page-logs
.localize=${this.localize}
@landing-page-error=${this._showError}
></landing-page-logs>
</div>
</ha-card>
<onboarding-welcome-links
.localize=${this.localize}
.mobileApp=${this._mobileApp}
></onboarding-welcome-links>
<div class="footer">
<ha-language-picker
.value=${this.language}
.label=${""}
nativeName
@value-changed=${this._languageChanged}
inlineArrow
></ha-language-picker>
<a
href="https://www.home-assistant.io/getting-started/onboarding/"
target="_blank"
rel="noreferrer noopener"
>${this.localize("ui.panel.page-onboarding.help")}</a
>
</div>
`;
}
protected firstUpdated(changedProps: PropertyValues) {
super.firstUpdated(changedProps);
makeDialogManager(this, this.shadowRoot!);
if (window.innerWidth > 450) {
import("../../src/resources/particles");
}
import("../../src/components/ha-language-picker");
this._scheduleCoreCheck();
}
private _scheduleCoreCheck() {
setTimeout(
() => this._checkCoreAvailability(),
SCHEDULE_CORE_CHECK_SECONDS * 1000
);
}
private async _checkCoreAvailability() {
try {
const response = await fetch("/manifest.json");
if (response.ok) {
location.reload();
}
} finally {
this._scheduleCoreCheck();
}
}
private _showError() {
this._supervisorError = true;
}
private _networkInfoChanged(ev: CustomEvent) {
this._networkIssue = ev.detail.value;
}
private _languageChanged(ev: CustomEvent) {
const language = ev.detail.value;
if (language !== this.language && language) {
this.language = language;
try {
localStorage.setItem("selectedLanguage", JSON.stringify(language));
} catch (err: any) {
// Ignore
}
}
}
static styles = [
haStyle,
onBoardingStyles,
css`
.footer {
padding-top: 8px;
display: flex;
justify-content: space-between;
align-items: center;
}
ha-card .card-content {
display: flex;
flex-direction: column;
gap: 16px;
}
ha-alert p {
text-align: unset;
}
ha-language-picker {
display: block;
width: 200px;
border-radius: 4px;
overflow: hidden;
--ha-select-height: 40px;
--mdc-select-fill-color: none;
--mdc-select-label-ink-color: var(--primary-text-color, #212121);
--mdc-select-ink-color: var(--primary-text-color, #212121);
--mdc-select-idle-line-color: transparent;
--mdc-select-hover-line-color: transparent;
--mdc-select-dropdown-icon-color: var(--primary-text-color, #212121);
--mdc-shape-small: 0;
}
a {
text-decoration: none;
color: var(--primary-text-color);
margin-right: 16px;
margin-inline-end: 16px;
margin-inline-start: initial;
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"ha-landing-page": HaLandingPage;
}
}

View File

@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home Assistant</title>
<%= renderTemplate("../../../src/html/_header.html.template") %>
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
<style>
html {
background-color: var(--primary-background-color, #fafafa);
color: var(--primary-text-color, #212121);
}
@media (prefers-color-scheme: dark) {
html {
background-color: var(--primary-background-color, #111111);
color: var(--primary-text-color, #e1e1e1);
}
}
body {
height: auto;
padding: 32px 0;
}
.content {
max-width: 560px;
margin: 0 auto;
padding: 0 16px;
box-sizing: content-box;
}
.header {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 32px;
}
.header img {
height: 56px;
width: 56px;
}
</style>
</head>
<body id="particles">
<div class="content">
<div class="header">
<img src="/static/icons/favicon-192x192.png" alt="Home Assistant" />
</div>
<ha-landing-page></ha-landing-page>
</div>
<%= renderTemplate("../../../src/html/_js_base.html.template") %>
<%= renderTemplate("../../../src/html/_preload_roboto.html.template") %>
<%= renderTemplate("../../../src/html/_script_loader.html.template") %>
</body>
</html>

View File

@ -0,0 +1,74 @@
import type { PropertyValues } from "lit";
import { LitElement } from "lit";
import { property, state } from "lit/decorators";
import {
computeLocalize,
type LandingPageKeys,
type LocalizeFunc,
} from "../../src/common/translations/localize";
import { ProvideHassLitMixin } from "../../src/mixins/provide-hass-lit-mixin";
import type { Constructor, Resources } from "../../src/types";
import {
getLocalLanguage,
getTranslation,
} from "../../src/util/common-translation";
import { computeDirectionStyles } from "../../src/common/util/compute_rtl";
import themesMixin from "../../src/state/themes-mixin";
import { translationMetadata } from "../../src/resources/translations-metadata";
import type { HassBaseEl } from "../../src/state/hass-base-mixin";
export class LandingPageBaseElement extends themesMixin(
ProvideHassLitMixin(LitElement) as unknown as Constructor<HassBaseEl>
) {
// Initialized to empty will prevent undefined errors if called before connected to DOM.
@property({ attribute: false })
public localize: LocalizeFunc<LandingPageKeys> = () => "";
// Use browser language setup before login.
@property() public language?: string = getLocalLanguage();
@state() private _resources?: Resources;
public connectedCallback(): void {
super.connectedCallback();
this._initializeLocalize();
}
protected willUpdate(changedProperties: PropertyValues) {
if (changedProperties.get("language")) {
this._resources = undefined;
this._initializeLocalize();
}
if (
this.language &&
this._resources &&
(changedProperties.has("language") || changedProperties.has("_resources"))
) {
this._setLocalize();
}
}
private async _initializeLocalize() {
if (this._resources || !this.language) {
return;
}
const { data } = await getTranslation(null, this.language);
this._resources = {
[this.language]: data,
};
}
private async _setLocalize() {
this.localize = await computeLocalize(
this.constructor.prototype,
this.language!,
this._resources!
);
computeDirectionStyles(
translationMetadata.translations[this.language!].isRTL,
this
);
}
}

View File

@ -1,6 +1,6 @@
export default {
"*.?(c|m){js,ts}": [
"eslint --cache --cache-strategy=content --cache-location=node_modules/.cache/eslint/.eslintcache --fix",
"eslint --flag unstable_config_lookup_from_file --cache --cache-strategy=content --cache-location=node_modules/.cache/eslint/.eslintcache --fix",
"prettier --cache --write",
"lit-analyzer --quiet",
],

View File

@ -8,8 +8,8 @@
"version": "1.0.0",
"scripts": {
"build": "script/build_frontend",
"lint:eslint": "eslint \"**/src/**/*.{js,ts,html}\" --cache --cache-strategy=content --cache-location=node_modules/.cache/eslint/.eslintcache --ignore-path=.gitignore",
"format:eslint": "eslint \"**/src/**/*.{js,ts,html}\" --cache --cache-strategy=content --cache-location=node_modules/.cache/eslint/.eslintcache --ignore-path=.gitignore --fix",
"lint:eslint": "eslint --flag unstable_config_lookup_from_file \"**/src/**/*.{js,ts,html}\" --cache --cache-strategy=content --cache-location=node_modules/.cache/eslint/.eslintcache --ignore-pattern=.gitignore",
"format:eslint": "eslint --flag unstable_config_lookup_from_file \"**/src/**/*.{js,ts,html}\" --cache --cache-strategy=content --cache-location=node_modules/.cache/eslint/.eslintcache --ignore-pattern=.gitignore --fix",
"lint:prettier": "prettier . --cache --check",
"format:prettier": "prettier . --cache --write",
"lint:types": "tsc",
@ -19,7 +19,8 @@
"postinstall": "husky",
"prepack": "pinst --disable",
"postpack": "pinst --enable",
"test": "instant-mocha --webpack-config ./test/webpack.config.js --require ./test/setup.cjs \"test/**/*.ts\""
"test": "vitest run --config test/vitest.config.ts",
"test:coverage": "vitest run --config test/vitest.config.ts --coverage"
},
"author": "Paulus Schoutsen <Paulus@PaulusSchoutsen.nl> (http://paulusschoutsen.nl)",
"license": "Apache-2.0",
@ -27,22 +28,23 @@
"dependencies": {
"@babel/runtime": "7.26.0",
"@braintree/sanitize-url": "7.1.0",
"@codemirror/autocomplete": "6.18.2",
"@codemirror/autocomplete": "6.18.3",
"@codemirror/commands": "6.7.1",
"@codemirror/language": "6.10.3",
"@codemirror/legacy-modes": "6.4.1",
"@codemirror/search": "6.5.7",
"@codemirror/legacy-modes": "6.4.2",
"@codemirror/search": "6.5.8",
"@codemirror/state": "6.4.1",
"@codemirror/view": "6.34.1",
"@codemirror/view": "6.35.0",
"@egjs/hammerjs": "2.0.17",
"@formatjs/intl-datetimeformat": "6.16.1",
"@formatjs/intl-displaynames": "6.8.1",
"@formatjs/intl-getcanonicallocales": "2.5.1",
"@formatjs/intl-listformat": "7.7.1",
"@formatjs/intl-locale": "4.2.1",
"@formatjs/intl-numberformat": "8.14.1",
"@formatjs/intl-pluralrules": "5.3.1",
"@formatjs/intl-relativetimeformat": "11.4.1",
"@formatjs/intl-datetimeformat": "6.16.5",
"@formatjs/intl-displaynames": "6.8.5",
"@formatjs/intl-durationformat": "0.6.4",
"@formatjs/intl-getcanonicallocales": "2.5.3",
"@formatjs/intl-listformat": "7.7.5",
"@formatjs/intl-locale": "4.2.5",
"@formatjs/intl-numberformat": "8.14.5",
"@formatjs/intl-pluralrules": "5.3.5",
"@formatjs/intl-relativetimeformat": "11.4.5",
"@fullcalendar/core": "6.1.15",
"@fullcalendar/daygrid": "6.1.15",
"@fullcalendar/interaction": "6.1.15",
@ -52,7 +54,7 @@
"@lezer/highlight": "1.2.1",
"@lit-labs/context": "0.4.1",
"@lit-labs/motion": "1.0.7",
"@lit-labs/observers": "2.0.2",
"@lit-labs/observers": "2.0.4",
"@lit-labs/virtualizer": "2.0.14",
"@lrnwebcomponents/simple-tooltip": "8.0.2",
"@material/chips": "=14.0.0-canary.53b3cad2f.0",
@ -89,8 +91,8 @@
"@polymer/polymer": "3.5.2",
"@replit/codemirror-indentation-markers": "6.5.3",
"@thomasloven/round-slider": "0.6.0",
"@vaadin/combo-box": "24.5.1",
"@vaadin/vaadin-themable-mixin": "24.5.1",
"@vaadin/combo-box": "24.5.4",
"@vaadin/vaadin-themable-mixin": "24.5.4",
"@vibrant/color": "3.2.1-alpha.1",
"@vibrant/core": "3.2.1-alpha.1",
"@vibrant/quantizer-mmcq": "3.2.1-alpha.1",
@ -98,10 +100,10 @@
"@webcomponents/scoped-custom-element-registry": "0.0.9",
"@webcomponents/webcomponentsjs": "2.8.0",
"app-datepicker": "5.1.1",
"barcode-detector": "2.2.11",
"barcode-detector": "2.3.1",
"chart.js": "4.4.6",
"color-name": "2.0.0",
"comlink": "4.4.1",
"comlink": "4.4.2",
"core-js": "3.39.0",
"cropperjs": "1.6.2",
"date-fns": "4.1.0",
@ -115,13 +117,14 @@
"hls.js": "patch:hls.js@npm%3A1.5.7#~/.yarn/patches/hls.js-npm-1.5.7-f5bbd3d060.patch",
"home-assistant-js-websocket": "9.4.0",
"idb-keyval": "6.2.1",
"intl-messageformat": "10.7.3",
"intl-messageformat": "10.7.7",
"js-yaml": "4.1.0",
"leaflet": "1.9.4",
"leaflet-draw": "patch:leaflet-draw@npm%3A1.0.4#./.yarn/patches/leaflet-draw-npm-1.0.4-0ca0ebcf65.patch",
"lit": "2.8.0",
"lit-html": "2.8.0",
"luxon": "3.5.0",
"marked": "14.1.3",
"marked": "15.0.2",
"memoize-one": "6.0.0",
"node-vibrant": "3.2.1-alpha.1",
"proxy-polyfill": "0.3.2",
@ -153,26 +156,24 @@
},
"devDependencies": {
"@babel/core": "7.26.0",
"@babel/helper-define-polyfill-provider": "0.6.2",
"@babel/helper-define-polyfill-provider": "0.6.3",
"@babel/plugin-proposal-decorators": "7.25.9",
"@babel/plugin-transform-runtime": "7.25.9",
"@babel/preset-env": "7.26.0",
"@babel/preset-typescript": "7.26.0",
"@bundle-stats/plugin-webpack-filter": "4.16.0",
"@bundle-stats/plugin-webpack-filter": "4.17.0",
"@koa/cors": "5.0.0",
"@lokalise/node-api": "12.8.0",
"@octokit/auth-oauth-device": "7.1.1",
"@octokit/plugin-retry": "7.1.2",
"@octokit/rest": "21.0.2",
"@open-wc/dev-server-hmr": "0.1.4",
"@rollup/plugin-babel": "6.0.4",
"@rollup/plugin-commonjs": "26.0.1",
"@rollup/plugin-json": "6.1.0",
"@rollup/plugin-node-resolve": "15.2.4",
"@rollup/plugin-replace": "5.0.7",
"@rsdoctor/rspack-plugin": "0.4.8",
"@rspack/cli": "1.1.4",
"@rspack/core": "1.1.4",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "6.0.17",
"@types/chromecast-caf-sender": "1.0.10",
"@types/chromecast-caf-receiver": "6.0.19",
"@types/chromecast-caf-sender": "1.0.11",
"@types/color-name": "2.0.0",
"@types/glob": "8.1.0",
"@types/html-minifier-terser": "7.0.2",
@ -181,7 +182,7 @@
"@types/leaflet-draw": "1.0.11",
"@types/lodash.merge": "4.6.9",
"@types/luxon": "3.4.2",
"@types/mocha": "10.0.9",
"@types/mocha": "10.0.10",
"@types/qrcode": "1.5.5",
"@types/serve-handler": "6.1.4",
"@types/sortablejs": "1.15.8",
@ -190,14 +191,13 @@
"@types/webspeechapi": "0.0.29",
"@typescript-eslint/eslint-plugin": "7.18.0",
"@typescript-eslint/parser": "7.18.0",
"@vitest/coverage-v8": "2.1.5",
"@web/dev-server": "0.1.38",
"@web/dev-server-rollup": "0.4.1",
"babel-loader": "9.2.1",
"babel-plugin-template-html-minifier": "4.1.0",
"browserslist-useragent-regexp": "4.1.3",
"chai": "5.1.2",
"del": "8.0.0",
"eslint": "8.57.1",
"eslint": "9.15.0",
"eslint-config-airbnb-base": "15.0.0",
"eslint-config-airbnb-typescript": "18.0.0",
"eslint-config-prettier": "9.1.0",
@ -216,24 +216,19 @@
"gulp-rename": "2.0.0",
"gulp-zopfli-green": "6.0.2",
"html-minifier-terser": "7.2.0",
"husky": "9.1.6",
"instant-mocha": "1.5.3",
"husky": "9.1.7",
"jszip": "3.10.1",
"lint-staged": "15.2.10",
"lit-analyzer": "2.0.3",
"lodash.merge": "4.6.2",
"lodash.template": "4.5.0",
"magic-string": "0.30.12",
"magic-string": "0.30.13",
"map-stream": "0.0.7",
"mocha": "10.8.2",
"object-hash": "3.0.0",
"open": "10.1.0",
"pinst": "3.0.0",
"prettier": "3.3.3",
"rollup": "2.79.2",
"rollup-plugin-string": "3.0.0",
"rollup-plugin-terser": "7.0.2",
"rollup-plugin-visualizer": "5.12.0",
"rspack-manifest-plugin": "5.0.2",
"serve-handler": "6.1.6",
"sinon": "19.0.2",
"systemjs": "6.15.1",
@ -241,13 +236,10 @@
"terser-webpack-plugin": "5.3.10",
"transform-async-modules-webpack-plugin": "1.1.1",
"ts-lit-plugin": "2.0.2",
"typescript": "5.6.3",
"webpack": "5.96.1",
"webpack-cli": "5.1.4",
"webpack-dev-server": "5.1.0",
"webpack-manifest-plugin": "5.0.0",
"typescript": "5.7.2",
"vitest": "2.1.5",
"webpack-stats-plugin": "1.1.3",
"webpackbar": "6.0.1",
"webpackbar": "7.0.0",
"workbox-build": "patch:workbox-build@npm%3A7.1.1#~/.yarn/patches/workbox-build-npm-7.1.1-a854f3faae.patch"
},
"_comment": "Polymer 3.2 contained a bug, fixed in https://github.com/Polymer/polymer/pull/5569, add as patch",
@ -255,9 +247,11 @@
"@polymer/polymer": "patch:@polymer/polymer@3.5.2#./.yarn/patches/@polymer/polymer/pr-5569.patch",
"@material/mwc-button@^0.25.3": "^0.27.0",
"lit": "2.8.0",
"lit-html": "2.8.0",
"clean-css": "5.3.3",
"@lit/reactive-element": "1.6.3",
"@fullcalendar/daygrid": "6.1.15"
"@fullcalendar/daygrid": "6.1.15",
"globals": "15.12.0"
},
"packageManager": "yarn@4.5.1"
"packageManager": "yarn@4.5.2"
}

View File

@ -0,0 +1,3 @@
<svg width="92" height="136" viewBox="0 0 92 136" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M76.38 104.9H3.03C2.24231 104.9 1.48688 105.213 0.929897 105.77C0.372914 106.327 0.0600052 107.082 0.0600052 107.87V132.47C0.0600052 133.258 0.372914 134.013 0.929897 134.57C1.48688 135.127 2.24231 135.44 3.03 135.44H12.36C13.1477 135.44 13.9031 135.127 14.4601 134.57C15.0171 134.013 15.33 133.258 15.33 132.47V120.17H76.39V132.47C76.39 133.258 76.7029 134.013 77.2599 134.57C77.8169 135.127 78.5723 135.44 79.36 135.44H88.69C89.4777 135.44 90.2331 135.127 90.7901 134.57C91.3471 134.013 91.66 133.258 91.66 132.47V107.87C91.66 107.082 91.3471 106.327 90.7901 105.77C90.2331 105.213 89.4777 104.9 88.69 104.9H76.39H76.38ZM50.04 2.24996C47.73 -0.0600439 43.95 -0.0600439 41.65 2.24996L4.25 39.65C1.94 41.96 0.0500031 46.52 0.0500031 49.78V83.7C0.0500031 86.96 2.72 89.64 5.99 89.64H85.7C88.96 89.64 91.64 86.97 91.64 83.7V49.78C91.64 46.52 89.75 41.96 87.44 39.65L50.04 2.24996Z" fill="#18BCF2"/>
</svg>

After

Width:  |  Height:  |  Size: 1011 B

View File

@ -0,0 +1,10 @@
<svg width="75" height="79" viewBox="0 0 75 79" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M73.8393 17.4898C72.6973 9.00165 65.2994 2.31235 56.5296 1.01614C55.05 0.797115 49.4441 0 36.4582 0H36.3612C23.3717 0 20.585 0.797115 19.1054 1.01614C10.5798 2.27644 2.79399 8.28712 0.904997 16.8758C-0.00358524 21.1056 -0.100549 25.7949 0.0682394 30.0965C0.308852 36.2651 0.355538 42.423 0.91577 48.5665C1.30307 52.6474 1.97872 56.6957 2.93763 60.6812C4.73325 68.042 12.0019 74.1676 19.1233 76.6666C26.7478 79.2728 34.9474 79.7055 42.8039 77.9162C43.6682 77.7151 44.5217 77.4817 45.3645 77.216C47.275 76.6092 49.5123 75.9305 51.1571 74.7385C51.1797 74.7217 51.1982 74.7001 51.2112 74.6753C51.2243 74.6504 51.2316 74.6229 51.2325 74.5948V68.6416C51.2321 68.6154 51.2259 68.5896 51.2142 68.5661C51.2025 68.5426 51.1858 68.522 51.1651 68.5058C51.1444 68.4896 51.1204 68.4783 51.0948 68.4726C51.0692 68.4669 51.0426 68.467 51.0171 68.4729C45.9835 69.675 40.8254 70.2777 35.6502 70.2682C26.7439 70.2682 24.3486 66.042 23.6626 64.2826C23.1113 62.762 22.7612 61.1759 22.6212 59.5646C22.6197 59.5375 22.6247 59.5105 22.6357 59.4857C22.6466 59.4609 22.6633 59.4391 22.6843 59.422C22.7053 59.4048 22.73 59.3929 22.7565 59.3871C22.783 59.3813 22.8104 59.3818 22.8367 59.3886C27.7864 60.5826 32.8604 61.1853 37.9522 61.1839C39.1768 61.1839 40.3978 61.1839 41.6224 61.1516C46.7435 61.008 52.1411 60.7459 57.1796 59.7621C57.3053 59.7369 57.431 59.7154 57.5387 59.6831C65.4861 58.157 73.0493 53.3672 73.8178 41.2381C73.8465 40.7606 73.9184 36.2364 73.9184 35.7409C73.9219 34.0569 74.4606 23.7949 73.8393 17.4898Z" fill="url(#paint0_linear_549_34)"/>
<path d="M61.2484 27.0263V48.114H52.8916V27.6475C52.8916 23.3388 51.096 21.1413 47.4437 21.1413C43.4287 21.1413 41.4177 23.7409 41.4177 28.8755V40.0782H33.1111V28.8755C33.1111 23.7409 31.0965 21.1413 27.0815 21.1413C23.4507 21.1413 21.6371 23.3388 21.6371 27.6475V48.114H13.2839V27.0263C13.2839 22.7176 14.384 19.2946 16.5843 16.7572C18.8539 14.2258 21.8311 12.926 25.5264 12.926C29.8036 12.926 33.0357 14.5705 35.1905 17.8559L37.2698 21.346L39.3527 17.8559C41.5074 14.5705 44.7395 12.926 49.0095 12.926C52.7013 12.926 55.6784 14.2258 57.9553 16.7572C60.1531 19.2922 61.2508 22.7152 61.2484 27.0263Z" fill="white"/>
<defs>
<linearGradient id="paint0_linear_549_34" x1="37.0692" y1="0" x2="37.0692" y2="79" gradientUnits="userSpaceOnUse">
<stop stop-color="#6364FF"/>
<stop offset="1" stop-color="#563ACC"/>
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "home-assistant-frontend"
version = "20241106.2"
version = "20241127.0"
license = {text = "Apache-2.0"}
description = "The Home Assistant frontend"
readme = "README.md"

View File

@ -1,10 +0,0 @@
import rollup from "../build-scripts/rollup.cjs";
import env from "../build-scripts/env.cjs";
const config = rollup.createAppConfig({
isProdBuild: env.isProdBuild(),
latestBuild: true,
isStatsBuild: env.isStatsBuild(),
});
export default { ...config.inputOptions, output: config.outputOptions };

View File

@ -1,12 +1,12 @@
/* eslint-disable @typescript-eslint/no-var-requires */
// Needs to remain CommonJS until eslint-import-resolver-webpack supports ES modules
const webpack = require("./build-scripts/webpack.cjs");
const rspack = require("./build-scripts/rspack.cjs");
const env = require("./build-scripts/env.cjs");
// This file exists because we haven't migrated the stats script yet
const configs = [
webpack.createAppConfig({
rspack.createAppConfig({
isProdBuild: env.isProdBuild(),
isStatsBuild: env.isStatsBuild(),
isTestBuild: env.isTestBuild(),
@ -16,7 +16,7 @@ const configs = [
if (env.isProdBuild() && !env.isStatsBuild()) {
configs.push(
webpack.createAppConfig({
rspack.createAppConfig({
isProdBuild: env.isProdBuild(),
isStatsBuild: env.isStatsBuild(),
isTestBuild: env.isTestBuild(),

View File

@ -6,9 +6,4 @@ set -e
cd "$(dirname "$0")/.."
export STATS=1
statsfile="compilation-stats.json"
./node_modules/.bin/webpack-cli --profile --node-env=production --json=$statsfile
npx webpack-bundle-analyzer $statsfile hass_frontend/frontend_latest
rm -f $statsfile
./node_modules/.bin/gulp analyze-app

View File

@ -3,6 +3,7 @@ import "@material/mwc-button";
import { genClientId } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit";
import { keyed } from "lit/directives/keyed";
import { customElement, property, state } from "lit/decorators";
import type { LocalizeFunc } from "../common/translations/localize";
import "../components/ha-alert";
@ -224,7 +225,9 @@ export class HaAuthFlow extends LitElement {
: this.localize("ui.panel.page-authorize.just_checking")}
</h1>
${this._computeStepDescription(step)}
<ha-auth-form
${keyed(
step.step_id,
html`<ha-auth-form
.localize=${this.localize}
.data=${this._stepData!}
.schema=${autocompleteLoginFields(step.data_schema)}
@ -233,7 +236,8 @@ export class HaAuthFlow extends LitElement {
.computeLabel=${this._computeLabelCallback(step)}
.computeError=${this._computeErrorCallback(step)}
@value-changed=${this._stepDataChanged}
></ha-auth-form>
></ha-auth-form>`
)}
${this.clientId === genClientId() &&
!["select_mfa_module", "mfa"].includes(step.step_id)
? html`

View File

@ -54,6 +54,7 @@ export class HaAuthFormString extends HaFormString {
.autoValidate=${this.schema.required}
.name=${this.schema.name}
.autocomplete=${this.schema.autocomplete}
?autofocus=${this.schema.autofocus}
.suffix=${
this.isPassword
? // reserve some space for the icon.

View File

@ -69,6 +69,7 @@ export class HaAuthTextField extends HaTextField {
name=${ifDefined(this.name === "" ? undefined : this.name)}
inputmode=${ifDefined(this.inputMode)}
autocapitalize=${ifDefined(autocapitalizeOrUndef)}
?autofocus=${this.autofocus}
@input=${this.handleInputChange}
@focus=${this.onInputFocus}
@blur=${this.onInputBlur}
@ -246,6 +247,14 @@ export class HaAuthTextField extends HaTextField {
this.append(style);
return this;
}
public firstUpdated() {
super.firstUpdated();
if (this.autofocus) {
this.focus();
}
}
}
declare global {

View File

@ -204,6 +204,7 @@ export class HaAuthorize extends litLocalizeLiteMixin(LitElement) {
.label=${""}
nativeName
@value-changed=${this._languageChanged}
inlineArrow
></ha-language-picker>
<a
href="https://www.home-assistant.io/docs/authentication/"

View File

@ -1,3 +1,8 @@
/**
* Get all possible combinations of an array
* @param arr - The array to get combinations of
* @returns A multidimensional array of all possible combinations
*/
export function getAllCombinations<T>(arr: T[]) {
return arr.reduce<T[][]>(
(combinations, element) =>

View File

@ -1,5 +1,9 @@
type NonUndefined<T> = T extends undefined ? never : T;
/**
* Ensure that the input is an array or wrap it in an array
* @param value - The value to ensure is an array
*/
export function ensureArray(value: undefined): undefined;
export function ensureArray<T>(value: T | T[]): NonUndefined<T>[];
export function ensureArray<T>(value: T | readonly T[]): NonUndefined<T>[];

View File

@ -1,4 +1,8 @@
// Creates a type predicate function for determining if an array literal includes a given value
/**
* Creates a type predicate function for determining if an array literal includes a given value
* @param array - The array to check
* @returns A type predicate function
*/
export const arrayLiteralIncludes =
<T extends readonly unknown[]>(array: T) =>
(searchElement: unknown, fromIndex?: number): searchElement is T[number] =>

View File

@ -1,19 +0,0 @@
import millisecondsToDuration from "./milliseconds_to_duration";
const DAY_IN_MILLISECONDS = 86400000;
const HOUR_IN_MILLISECONDS = 3600000;
const MINUTE_IN_MILLISECONDS = 60000;
const SECOND_IN_MILLISECONDS = 1000;
export const UNIT_TO_MILLISECOND_CONVERT = {
ms: 1,
s: SECOND_IN_MILLISECONDS,
min: MINUTE_IN_MILLISECONDS,
h: HOUR_IN_MILLISECONDS,
d: DAY_IN_MILLISECONDS,
};
export const formatDuration = (duration: string, units: string): string =>
millisecondsToDuration(
parseFloat(duration) * UNIT_TO_MILLISECOND_CONVERT[units]
) || "0";

View File

@ -1,9 +1,13 @@
import { DurationFormat } from "@formatjs/intl-durationformat";
import type { DurationInput } from "@formatjs/intl-durationformat/src/types";
import memoizeOne from "memoize-one";
import type { HaDurationData } from "../../components/ha-duration-input";
import type { FrontendLocaleData } from "../../data/translation";
import { round } from "../number/round";
const leftPad = (num: number) => (num < 10 ? `0${num}` : num);
export const formatDuration = (
export const formatNumericDuration = (
locale: FrontendLocaleData,
duration: HaDurationData
) => {
@ -42,3 +46,132 @@ export const formatDuration = (
}
return null;
};
const formatDurationLongMem = memoizeOne(
(locale: FrontendLocaleData) =>
new DurationFormat(locale.language, {
style: "long",
})
);
export const formatDurationLong = (
locale: FrontendLocaleData,
duration: HaDurationData
) => formatDurationLongMem(locale).format(duration);
const formatDigitalDurationMem = memoizeOne(
(locale: FrontendLocaleData) =>
new DurationFormat(locale.language, {
style: "digital",
hoursDisplay: "auto",
})
);
export const formatDurationDigital = (
locale: FrontendLocaleData,
duration: HaDurationData
) => formatDigitalDurationMem(locale).format(duration);
export const DURATION_UNITS = ["ms", "s", "min", "h", "d"] as const;
type DurationUnit = (typeof DURATION_UNITS)[number];
const formatDurationDayMem = memoizeOne(
(locale: FrontendLocaleData) =>
new DurationFormat(locale.language, {
style: "narrow",
daysDisplay: "always",
})
);
const formatDurationHourMem = memoizeOne(
(locale: FrontendLocaleData) =>
new DurationFormat(locale.language, {
style: "narrow",
hoursDisplay: "always",
})
);
const formatDurationMinuteMem = memoizeOne(
(locale: FrontendLocaleData) =>
new DurationFormat(locale.language, {
style: "narrow",
minutesDisplay: "always",
})
);
const formatDurationSecondMem = memoizeOne(
(locale: FrontendLocaleData) =>
new DurationFormat(locale.language, {
style: "narrow",
secondsDisplay: "always",
})
);
const formatDurationMillisecondMem = memoizeOne(
(locale: FrontendLocaleData) =>
new DurationFormat(locale.language, {
style: "narrow",
millisecondsDisplay: "always",
})
);
export const formatDuration = (
locale: FrontendLocaleData,
duration: string,
unit: DurationUnit,
precision?: number | undefined
): string => {
const value =
precision !== undefined
? round(parseFloat(duration), precision)
: parseFloat(duration);
switch (unit) {
case "d": {
const days = Math.floor(value);
const hours = Math.floor((value - days) * 24);
const input: DurationInput = {
days,
hours,
};
return formatDurationDayMem(locale).format(input);
}
case "h": {
const hours = Math.floor(value);
const minutes = Math.floor((value - hours) * 60);
const input: DurationInput = {
hours,
minutes,
};
return formatDurationHourMem(locale).format(input);
}
case "min": {
const minutes = Math.floor(value);
const seconds = Math.floor((value - minutes) * 60);
const input: DurationInput = {
minutes,
seconds,
};
return formatDurationMinuteMem(locale).format(input);
}
case "s": {
const seconds = Math.floor(value);
const milliseconds = Math.floor((value - seconds) * 1000);
const input: DurationInput = {
seconds,
milliseconds,
};
return formatDurationSecondMem(locale).format(input);
}
case "ms": {
const milliseconds = Math.floor(value);
const input: DurationInput = {
milliseconds,
};
return formatDurationMillisecondMem(locale).format(input);
}
default:
throw new Error("Invalid duration unit");
}
};

View File

@ -1,15 +1,12 @@
import { TimeZone } from "../../data/translation";
const RESOLVED_TIME_ZONE = Intl.DateTimeFormat?.().resolvedOptions?.().timeZone;
// Browser time zone can be determined from Intl, with fallback to UTC for polyfill or no support.
// Alternatively, we could fallback to a fixed offset IANA zone (e.g. "Etc/GMT+5") using
// Date.prototype.getTimeOffset(), but IANA only has whole hour Etc zones, and problems
// might occur with relative time due to DST.
// Use optional chain instead of polyfill import since polyfill will always return UTC
export const LOCAL_TIME_ZONE =
Intl.DateTimeFormat?.().resolvedOptions?.().timeZone ?? "UTC";
export const LOCAL_TIME_ZONE = RESOLVED_TIME_ZONE ?? "UTC";
// Pick time zone based on user profile option. Core zone is used when local cannot be determined.
export const resolveTimeZone = (option: TimeZone, serverTimeZone: string) =>
option === TimeZone.local && LOCAL_TIME_ZONE !== "UTC"
option === TimeZone.local && RESOLVED_TIME_ZONE
? LOCAL_TIME_ZONE
: serverTimeZone;

View File

@ -4,10 +4,7 @@ import type { EntityRegistryDisplayEntry } from "../../data/entity_registry";
import type { FrontendLocaleData } from "../../data/translation";
import { TimeZone } from "../../data/translation";
import type { HomeAssistant } from "../../types";
import {
UNIT_TO_MILLISECOND_CONVERT,
formatDuration,
} from "../datetime/duration";
import { DURATION_UNITS, formatDuration } from "../datetime/format_duration";
import { formatDate } from "../datetime/format_date";
import { formatDateTime } from "../datetime/format_date_time";
import { formatTime } from "../datetime/format_time";
@ -32,7 +29,6 @@ export const computeStateDisplay = (
const entity = entities?.[stateObj.entity_id] as
| EntityRegistryDisplayEntry
| undefined;
return computeStateDisplayFromEntityAttributes(
localize,
locale,
@ -72,10 +68,15 @@ export const computeStateDisplayFromEntityAttributes = (
if (
attributes.device_class === "duration" &&
attributes.unit_of_measurement &&
UNIT_TO_MILLISECOND_CONVERT[attributes.unit_of_measurement]
DURATION_UNITS.includes(attributes.unit_of_measurement)
) {
try {
return formatDuration(state, attributes.unit_of_measurement);
return formatDuration(
locale,
state,
attributes.unit_of_measurement,
entity?.display_precision
);
} catch (_err) {
// fallback to default
}
@ -103,7 +104,12 @@ export const computeStateDisplayFromEntityAttributes = (
getNumberFormatOptions({ state, attributes } as HassEntity, entity)
);
const unit = attributes.unit_of_measurement;
const unit =
(entity?.translation_key &&
localize(
`component.${entity.platform}.entity.${domain}.${entity.translation_key}.unit_of_measurement`
)) ||
attributes.unit_of_measurement;
if (unit) {
return `${value}${blankBeforeUnit(unit, locale)}${unit}`;

View File

@ -0,0 +1,91 @@
import type { HomeAssistant } from "../../types";
import type { IntegrationManifest } from "../../data/integration";
import { computeDomain } from "./compute_domain";
import { HELPERS_CRUD } from "../../data/helpers_crud";
import type { Helper } from "../../panels/config/helpers/const";
import { isHelperDomain } from "../../panels/config/helpers/const";
import { isComponentLoaded } from "../config/is_component_loaded";
import type { EntityRegistryEntry } from "../../data/entity_registry";
import { removeEntityRegistryEntry } from "../../data/entity_registry";
import type { ConfigEntry } from "../../data/config_entries";
import { deleteConfigEntry } from "../../data/config_entries";
export const isDeletableEntity = (
hass: HomeAssistant,
entity_id: string,
manifests: IntegrationManifest[],
entityRegistry: EntityRegistryEntry[],
configEntries: ConfigEntry[],
fetchedHelpers: Helper[]
): boolean => {
const restored = !!hass.states[entity_id]?.attributes.restored;
if (restored) {
return true;
}
const domain = computeDomain(entity_id);
const entityRegEntry = entityRegistry.find((e) => e.entity_id === entity_id);
if (isHelperDomain(domain)) {
return !!(
isComponentLoaded(hass, domain) &&
entityRegEntry &&
fetchedHelpers.some((e) => e.id === entityRegEntry.unique_id)
);
}
const configEntryId = entityRegEntry?.config_entry_id;
if (!configEntryId) {
return false;
}
const configEntry = configEntries.find((e) => e.entry_id === configEntryId);
return (
manifests.find((m) => m.domain === configEntry?.domain)
?.integration_type === "helper"
);
};
export const deleteEntity = (
hass: HomeAssistant,
entity_id: string,
manifests: IntegrationManifest[],
entityRegistry: EntityRegistryEntry[],
configEntries: ConfigEntry[],
fetchedHelpers: Helper[]
) => {
// This function assumes the entity_id already was validated by isDeletableEntity and does not repeat all those checks.
const domain = computeDomain(entity_id);
const entityRegEntry = entityRegistry.find((e) => e.entity_id === entity_id);
if (isHelperDomain(domain)) {
if (isComponentLoaded(hass, domain)) {
if (
entityRegEntry &&
fetchedHelpers.some((e) => e.id === entityRegEntry.unique_id)
) {
HELPERS_CRUD[domain].delete(hass, entityRegEntry.unique_id);
return;
}
}
const stateObj = hass.states[entity_id];
if (!stateObj?.attributes.restored) {
return;
}
removeEntityRegistryEntry(hass, entity_id);
return;
}
const configEntryId = entityRegEntry?.config_entry_id;
const configEntry = configEntryId
? configEntries.find((e) => e.entry_id === configEntryId)
: undefined;
const isHelperEntryType = configEntry
? manifests.find((m) => m.domain === configEntry.domain)
?.integration_type === "helper"
: false;
if (isHelperEntryType) {
deleteConfigEntry(hass, configEntryId!);
return;
}
removeEntityRegistryEntry(hass, entity_id);
};

View File

@ -5,7 +5,7 @@ export const blankBeforePercent = (
localeOptions: FrontendLocaleData
): string => {
switch (localeOptions.language) {
case "cz":
case "cs":
case "de":
case "fi":
case "fr":

View File

@ -16,6 +16,8 @@ export type LocalizeKeys =
| `ui.card.lawn_mower.actions.${string}`
| `ui.components.calendar.event.rrule.${string}`
| `ui.components.selectors.file.${string}`
| `ui.components.logbook.messages.detected_device_classes.${string}`
| `ui.components.logbook.messages.cleared_device_classes.${string}`
| `ui.dialogs.entity_registry.editor.${string}`
| `ui.dialogs.more_info_control.lawn_mower.${string}`
| `ui.dialogs.more_info_control.vacuum.${string}`
@ -31,6 +33,10 @@ export type LocalizeKeys =
| `ui.panel.page-authorize.form.${string}`
| `component.${string}`;
export type LandingPageKeys = FlattenObjectKeys<
TranslationDict["landing-page"]
>;
// Tweaked from https://www.raygesualdo.com/posts/flattening-object-keys-with-typescript-types
export type FlattenObjectKeys<
T extends Record<string, any>,

View File

@ -22,7 +22,6 @@ export class HaProgressButton extends LitElement {
<mwc-button
?raised=${this.raised}
.disabled=${this.disabled || this.progress}
@click=${this._buttonTapped}
class=${this._result || ""}
>
<slot></slot>
@ -63,22 +62,18 @@ export class HaProgressButton extends LitElement {
}, 2000);
}
private _buttonTapped(ev: Event): void {
if (this.progress) {
ev.stopPropagation();
}
}
static get styles(): CSSResultGroup {
return css`
:host {
outline: none;
display: inline-block;
position: relative;
pointer-events: none;
}
mwc-button {
transition: all 1s;
pointer-events: initial;
}
mwc-button.success {

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