mirror of
https://github.com/home-assistant/frontend.git
synced 2026-11-17 02:12:47 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
175636d20d | ||
|
|
da47ac9c16 | ||
|
|
3c49abb492 | ||
|
|
9494db6462 | ||
|
|
06461704ad |
No files matched your search
@@ -10,7 +10,6 @@ Use this skill when editing CSS, layout, visual hierarchy, theme integration, re
|
||||
## Theme And Layout Basics
|
||||
|
||||
- Use Home Assistant CSS custom properties instead of hardcoded colors.
|
||||
- CSS in the static HTML templates under `src/html/` must give custom properties a fallback value (for example `var(--ha-space-4, 16px)`), because the global tokens only exist once the JS-appended global stylesheet from `append-ha-style` has loaded.
|
||||
- Use `--ha-space-*` spacing tokens instead of hardcoded spacing where possible.
|
||||
- Keep components mobile-first and enhance for desktop.
|
||||
- Keep layouts RTL-safe. Prefer logical properties when they fit.
|
||||
|
||||
@@ -35,12 +35,11 @@ runs:
|
||||
NETLIFY_AUTH_TOKEN: ${{ inputs.auth-token }}
|
||||
NETLIFY_SITE_ID: ${{ inputs.site-id }}
|
||||
run: |
|
||||
# Execute the deployment (--filter picks the root workspace project,
|
||||
# --no-build because we deploy an already built directory)
|
||||
# Execute the deployment
|
||||
if [ -n "$ALIAS" ]; then
|
||||
npx -y netlify-cli deploy --filter home-assistant-frontend --no-build --dir="$DIR" --alias "$ALIAS" --json > deploy_output.json
|
||||
npx -y netlify-cli deploy --dir="$DIR" --alias "$ALIAS" --json > deploy_output.json
|
||||
else
|
||||
npx -y netlify-cli deploy --filter home-assistant-frontend --no-build --dir="$DIR" --prod --json > deploy_output.json
|
||||
npx -y netlify-cli deploy --dir="$DIR" --prod --json > deploy_output.json
|
||||
fi
|
||||
|
||||
# Collect the urls from the deployment output
|
||||
|
||||
@@ -16,7 +16,6 @@ runs:
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
packages/*/node_modules
|
||||
~/.local/share/pnpm/store
|
||||
key: >-
|
||||
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
|
||||
@@ -36,7 +35,6 @@ runs:
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
packages/*/node_modules
|
||||
~/.local/share/pnpm/store
|
||||
key: >-
|
||||
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
|
||||
|
||||
@@ -28,7 +28,6 @@ runs:
|
||||
with:
|
||||
path: |
|
||||
node_modules
|
||||
packages/*/node_modules
|
||||
~/.local/share/pnpm/store
|
||||
key: >-
|
||||
${{ inputs.node-modules-cache-key }}-${{ runner.os }}-${{ runner.arch }}-${{
|
||||
|
||||
@@ -18,7 +18,7 @@ workflows:
|
||||
- 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9'
|
||||
'.github/workflows/codeql-analysis.yaml':
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
- 'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066'
|
||||
- 'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
'.github/workflows/copilot-setup-steps.yml':
|
||||
- 'actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9'
|
||||
- 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1'
|
||||
@@ -151,9 +151,9 @@ dependencies:
|
||||
commit: 'sha1-89ae32b08ed1a541efecbab17912962a5e38981c'
|
||||
owner_id: 7513068
|
||||
repo_id: 113918130
|
||||
'github/codeql-action@33d7b85da1a04171e211befe2c739303b9a4c066':
|
||||
ref: 'v4.39.3'
|
||||
commit: 'sha1-33d7b85da1a04171e211befe2c739303b9a4c066'
|
||||
'github/codeql-action@9b3254085494b55a0f7c4c2b3d2d52cc712ce370':
|
||||
ref: 'v4.39.1'
|
||||
commit: 'sha1-9b3254085494b55a0f7c4c2b3d2d52cc712ce370'
|
||||
owner_id: 9919
|
||||
repo_id: 259445878
|
||||
'home-assistant/actions@86d4564712fa02543c808e3a693dd04f9d3f8361':
|
||||
|
||||
@@ -32,12 +32,12 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
languages: javascript-typescript
|
||||
build-mode: none
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
|
||||
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
||||
with:
|
||||
category: "/language:javascript-typescript"
|
||||
@@ -38,7 +38,7 @@ jobs:
|
||||
name: Prepare container dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001
|
||||
defaults:
|
||||
run:
|
||||
@@ -155,7 +155,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
@@ -207,7 +207,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
@@ -261,7 +261,7 @@ jobs:
|
||||
- prepare-container-dependencies
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: mcr.microsoft.com/playwright:v1.65.0-noble@sha256:6e3fb709361521eb27161606e6da6d2674e5e89fa16516cb37d6fdd91372273d
|
||||
image: mcr.microsoft.com/playwright:v1.64.1-noble@sha256:47b510dd9230bf0b9bfc9b20102241e577ea7a99334ab4c3ca19f19770e9b8ea
|
||||
options: --user 1001 --ipc=host
|
||||
defaults:
|
||||
run:
|
||||
|
||||
@@ -28,18 +28,10 @@ AI can be a helpful tool for writing code and documentation. However, due to the
|
||||
|
||||
All contributions must be reviewed and understood by the contributor before submission. You should be able to explain every change in a pull request you submit. Pull requests that appear to be unreviewed AI output will be closed without review.
|
||||
|
||||
## Design contributions
|
||||
|
||||
AI can be a helpful tool to explore ideas and build mockups and prototypes. But AI tends to give the most common answer, not the one that fits Home Assistant and its users. So we require a human who brings the point of view and owns the design decisions.
|
||||
|
||||
You should be able to explain the problem your design solves and why you made your choices. If a mockup or prototype was mostly generated with AI, say so when you share it. Check your work against the [design guidelines](https://contributors.home-assistant.io/design/), as AI tools often make up components, colors, or spacing that don't exist in Home Assistant. Design proposals that look like unreviewed AI output may be closed or hidden.
|
||||
|
||||
## Our use of AI
|
||||
|
||||
Some of our projects use AI tools to assist with code reviews, issue triaging, reporting, and other project management tasks. These tools may leave comments on pull requests or issues. As with any automated tooling, these comments are not always correct.
|
||||
|
||||
We also use AI to help keep the design system, the Figma kit, and the code in sync. The design decisions behind them are made by people.
|
||||
|
||||
If an AI tool leaves a comment on your contribution, treat it as you would any other review comment. If you believe it is incorrect, say so; a brief explanation is sufficient. Maintainers always have the final say. If in doubt, ask a maintainer.
|
||||
|
||||
## Enforcement
|
||||
|
||||
@@ -157,99 +157,6 @@ async function pollProcess(lokaliseApi, projectId, processId) {
|
||||
}
|
||||
/* eslint-enable no-await-in-loop */
|
||||
|
||||
const DRAFTS_ACCEPTED_KEYS = [
|
||||
// Written per language rather than translated from English, so an English edit doesn't make them outdated
|
||||
"ui.components.rooms.keywords",
|
||||
];
|
||||
|
||||
async function exportTranslations(lokaliseApi, projectId) {
|
||||
const exportProcess = await lokaliseApi.files().async_download(projectId, {
|
||||
format: "json",
|
||||
original_filenames: false,
|
||||
replace_breaks: false,
|
||||
json_unescaped_slashes: true,
|
||||
export_empty_as: "skip",
|
||||
filter_data: ["verified"],
|
||||
});
|
||||
|
||||
const finishedProcess = await pollProcess(
|
||||
lokaliseApi,
|
||||
projectId,
|
||||
exportProcess.process_id
|
||||
);
|
||||
|
||||
const bundleUrl = finishedProcess.details.download_url;
|
||||
|
||||
console.log(`Downloading translations from: ${bundleUrl}`);
|
||||
|
||||
const response = await fetch(bundleUrl);
|
||||
|
||||
if (response.status !== 200 && response.status !== 0) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
|
||||
console.log(`Extracting translations...`);
|
||||
|
||||
const contents = await JSZip.loadAsync(await response.arrayBuffer());
|
||||
|
||||
const files = {};
|
||||
await Promise.all(
|
||||
Object.keys(contents.files).map(async (filename) => {
|
||||
const file = contents.file(filename);
|
||||
if (!file) {
|
||||
// no file, probably a directory
|
||||
return;
|
||||
}
|
||||
files[filename.split("/").splice(-1)[0]] = await file.async("string");
|
||||
})
|
||||
);
|
||||
return files;
|
||||
}
|
||||
|
||||
async function fetchDrafts(lokaliseApi, projectId) {
|
||||
const english = JSON.parse(
|
||||
await fs.readFile("src/translations/en.json", { encoding })
|
||||
);
|
||||
const keyNames = DRAFTS_ACCEPTED_KEYS.flatMap((key) => {
|
||||
const keys = key.split(".");
|
||||
const drafts = keys.reduce((obj, part) => obj?.[part], english) ?? {};
|
||||
return Object.keys(drafts).map((name) => [...keys, name].join("::"));
|
||||
});
|
||||
if (!keyNames.length) {
|
||||
return [];
|
||||
}
|
||||
const { items } = await lokaliseApi.keys().list({
|
||||
project_id: projectId,
|
||||
filter_keys: keyNames.join(","),
|
||||
include_translations: 1,
|
||||
limit: keyNames.length,
|
||||
});
|
||||
return items.flatMap((key) =>
|
||||
key.translations
|
||||
.filter(({ translation }) => translation)
|
||||
.map(({ language_iso, translation }) => ({
|
||||
filename: `${language_iso}.json`,
|
||||
path: key.key_name.web.split("::"),
|
||||
translation,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
function acceptDrafts(files, drafts) {
|
||||
const data = {};
|
||||
drafts.forEach(({ filename, path: keyPath, translation }) => {
|
||||
data[filename] ??= files[filename] ? JSON.parse(files[filename]) : {};
|
||||
const parent = keyPath.slice(0, -1).reduce((obj, part) => {
|
||||
obj[part] ??= {};
|
||||
return obj[part];
|
||||
}, data[filename]);
|
||||
parent[keyPath.at(-1)] = translation;
|
||||
});
|
||||
Object.entries(data).forEach(([filename, content]) => {
|
||||
files[filename] = JSON.stringify(content, null, 2);
|
||||
});
|
||||
}
|
||||
|
||||
gulp.task("fetch-lokalise", async function () {
|
||||
let apiKey;
|
||||
try {
|
||||
@@ -286,24 +193,52 @@ gulp.task("fetch-lokalise", async function () {
|
||||
await Promise.all(
|
||||
projects.map(async ([project, projectId]) => {
|
||||
try {
|
||||
const [files, drafts] = await Promise.all([
|
||||
exportTranslations(lokaliseApi, projectId),
|
||||
project === "frontend"
|
||||
? fetchDrafts(lokaliseApi, projectId)
|
||||
: undefined,
|
||||
]);
|
||||
if (drafts) {
|
||||
acceptDrafts(files, drafts);
|
||||
const exportProcess = await lokaliseApi
|
||||
.files()
|
||||
.async_download(projectId, {
|
||||
format: "json",
|
||||
original_filenames: false,
|
||||
replace_breaks: false,
|
||||
json_unescaped_slashes: true,
|
||||
export_empty_as: "skip",
|
||||
filter_data: ["verified"],
|
||||
});
|
||||
|
||||
const finishedProcess = await pollProcess(
|
||||
lokaliseApi,
|
||||
projectId,
|
||||
exportProcess.process_id
|
||||
);
|
||||
|
||||
const bundleUrl = finishedProcess.details.download_url;
|
||||
|
||||
console.log(`Downloading translations from: ${bundleUrl}`);
|
||||
|
||||
const response = await fetch(bundleUrl);
|
||||
|
||||
if (response.status !== 200 && response.status !== 0) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
|
||||
console.log(`Extracting translations...`);
|
||||
|
||||
const contents = await JSZip.loadAsync(await response.arrayBuffer());
|
||||
|
||||
await mkdirPromise;
|
||||
await Promise.all(
|
||||
Object.entries(files).map(([filename, content]) =>
|
||||
fs.writeFile(path.join(inDir, project, filename), content, {
|
||||
flag: "w",
|
||||
encoding,
|
||||
})
|
||||
)
|
||||
Object.keys(contents.files).map(async (filename) => {
|
||||
const file = contents.file(filename);
|
||||
if (!file) {
|
||||
// no file, probably a directory
|
||||
return;
|
||||
}
|
||||
const content = await file.async("nodebuffer");
|
||||
await fs.writeFile(
|
||||
path.join(inDir, project, filename.split("/").splice(-1)[0]),
|
||||
content,
|
||||
{ flag: "w", encoding }
|
||||
);
|
||||
})
|
||||
);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
|
||||
@@ -50,9 +50,7 @@ const convertToJSON = async (
|
||||
const encodedData = localeData.match(
|
||||
/JSON\.parse\((?<data>"(?:[^"\\]|\\.)*")\)/
|
||||
)?.groups?.data;
|
||||
localeData =
|
||||
localeData.match(/\}\)\((?<data>\{.*\})\)\s*;?\s*$/s)?.groups?.data ??
|
||||
firstBlock.match(dataRegex)?.groups?.data;
|
||||
localeData = firstBlock.match(dataRegex)?.groups?.data;
|
||||
if (!localeData && !encodedData) {
|
||||
throw Error(`Failed to extract data for language ${lang} from ${pkg}`);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* global module, require */
|
||||
// rspack/webpack loader that minifies the HTML, SVG, and CSS inside lit
|
||||
// tagged template literals using `minify-literals` (html-minifier-next +
|
||||
// lightningcss). Replaces the unmaintained babel-plugin-template-html-minifier.
|
||||
@@ -35,14 +36,6 @@ const initLoader = (browserslistEnv) => {
|
||||
return {
|
||||
minifyHTMLLiterals: minifyModule.minifyHTMLLiterals,
|
||||
lightningcssTargets,
|
||||
// With the legacy floor at Chrome 67, lightningcss rewrites rgba()
|
||||
// to 8-digit hex (#rrggbbaa). Some kiosk webviews served the legacy
|
||||
// build (e.g. Shelly Wall Display) can't parse that, so any
|
||||
// var(--divider-color) border falls back to currentColor. Always
|
||||
// compile hex alpha colors to rgba() in legacy builds.
|
||||
lightningcssInclude: browserslistEnv.startsWith("legacy")
|
||||
? lightningcssModule.Features.HexAlphaColors
|
||||
: 0,
|
||||
};
|
||||
})
|
||||
);
|
||||
@@ -74,13 +67,12 @@ module.exports = function minifyTemplateLiteralsLoader(source, map, meta) {
|
||||
const { browserslistEnv } = this.getOptions();
|
||||
|
||||
initLoader(browserslistEnv)
|
||||
.then(({ minifyHTMLLiterals, lightningcssTargets, lightningcssInclude }) =>
|
||||
.then(({ minifyHTMLLiterals, lightningcssTargets }) =>
|
||||
minifyHTMLLiterals(source, {
|
||||
fileName: this.resourcePath,
|
||||
html: htmlOptions,
|
||||
css: {
|
||||
targets: lightningcssTargets,
|
||||
include: lightningcssInclude,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
@@ -68,42 +68,8 @@ const CONFIG_FILES = [
|
||||
path.join(__dirname, "lit-disable-dev-mode-loader.cjs"),
|
||||
path.join(__dirname, "babel-plugins", "custom-polyfill-plugin.js"),
|
||||
path.join(__dirname, "babel-plugins", "inline-constants-plugin.cjs"),
|
||||
// Its exports define the components source aliases below
|
||||
path.join(__dirname, "..", "packages", "components", "package.json"),
|
||||
];
|
||||
|
||||
// Resolve @home-assistant/components entry points to their sources, so the package
|
||||
// needs no build step during development. The entry points are read from the
|
||||
// "ha-source" export condition of the package; subpath patterns are expanded
|
||||
// for every element, i.e. every directory with a global.ts, like "card".
|
||||
const COMPONENTS_PACKAGE_DIR = path.join(
|
||||
paths.root_dir,
|
||||
"packages",
|
||||
"components"
|
||||
);
|
||||
const COMPONENTS_SRC_DIR = path.join(
|
||||
COMPONENTS_PACKAGE_DIR,
|
||||
"src",
|
||||
"components"
|
||||
);
|
||||
const componentElements = fs
|
||||
.readdirSync(COMPONENTS_SRC_DIR, { recursive: true })
|
||||
.filter((file) => path.basename(file) === "global.ts")
|
||||
.map((file) => path.dirname(file).split(path.sep).join("/"));
|
||||
const componentsSourceAliases = Object.fromEntries(
|
||||
Object.entries(require("../packages/components/package.json").exports)
|
||||
.filter(([, target]) => target["ha-source"])
|
||||
.flatMap(([subpath, target]) =>
|
||||
(subpath.includes("*") ? componentElements : [undefined]).map((name) => [
|
||||
`${path.posix.join("@home-assistant/components", name ? subpath.replaceAll("*", name) : subpath)}$`,
|
||||
path.join(
|
||||
COMPONENTS_PACKAGE_DIR,
|
||||
name ? target["ha-source"].replaceAll("*", name) : target["ha-source"]
|
||||
),
|
||||
])
|
||||
)
|
||||
);
|
||||
|
||||
// Patches change a package's files but not its version, which is all the
|
||||
// node_modules snapshot checks, so their contents go into the version too.
|
||||
const PATCHES_DIR = path.join(paths.root_dir, "patches");
|
||||
@@ -278,9 +244,6 @@ const createRspackConfig = ({
|
||||
path: paths.root_dir,
|
||||
env: "legacy",
|
||||
}),
|
||||
// Keep rgba() instead of #rrggbbaa, see
|
||||
// minify-template-literals-loader.cjs
|
||||
include: { hexAlphaColors: true },
|
||||
},
|
||||
},
|
||||
],
|
||||
@@ -465,7 +428,6 @@ const createRspackConfig = ({
|
||||
"src/resources/polyfills/bigdecimal.ts"
|
||||
),
|
||||
}),
|
||||
...componentsSourceAliases,
|
||||
"lit/static-html$": "lit/static-html.js",
|
||||
"lit/decorators$": "lit/decorators.js",
|
||||
"lit/directive$": "lit/directive.js",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
Cache-Control: public, max-age=0, s-maxage=3600, must-revalidate
|
||||
Cache-Control: public, max-age: 0, s-maxage=3600, must-revalidate
|
||||
Content-Security-Policy: form-action https:
|
||||
Feature-Policy: vibrate 'none'; geolocation 'none'; midi 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; vibrate 'none'; payment 'none'
|
||||
Referrer-Policy: no-referrer-when-downgrade
|
||||
@@ -8,13 +8,13 @@
|
||||
X-XSS-Protection: 1; mode=block
|
||||
|
||||
/images/*
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
|
||||
/manifest.json
|
||||
Cache-Control: public, max-age=3600, s-maxage=3600
|
||||
Cache-Control: public, max-age: 3600, s-maxage=3600
|
||||
|
||||
/frontend_es5/*
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
|
||||
/frontend_latest/*
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"background_color": "#FFFFFF",
|
||||
"description": "Show Home Assistant on your Chromecast or Google Home devices with a screen.",
|
||||
"description": "Show Home Assistant on your Chromecast or Google Assistant devices with a screen.",
|
||||
"dir": "ltr",
|
||||
"display": "standalone",
|
||||
"icons": [
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta property="og:type" content="website" />
|
||||
<meta
|
||||
property="og:description"
|
||||
content="Show Home Assistant on your Chromecast or Google Home devices with a screen."
|
||||
content="Show Home Assistant on your Chromecast or Google Assistant devices with a screen."
|
||||
/>
|
||||
<meta
|
||||
property="og:image"
|
||||
@@ -16,7 +16,7 @@
|
||||
<meta name="twitter:title" content="Home Assistant Cast" />
|
||||
<meta
|
||||
name="twitter:description"
|
||||
content="Show Home Assistant on your Chromecast or Google Home devices with a screen."
|
||||
content="Show Home Assistant on your Chromecast or Google Assistant devices with a screen."
|
||||
/>
|
||||
<meta
|
||||
name="twitter:image"
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
<head>
|
||||
<title>Home Assistant Cast - FAQ</title>
|
||||
<link rel="icon" href="/images/ha-cast-icon.png" type="image/png" />
|
||||
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
|
||||
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
|
||||
<style>
|
||||
body {
|
||||
@@ -53,7 +52,7 @@
|
||||
<p>
|
||||
Home Assistant Cast allows you to show your Home Assistant data on a
|
||||
Chromecast device and allows you to interact with Home Assistant on
|
||||
Google Home devices with a screen.
|
||||
Google Assistant devices with a screen.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<title>Home Assistant Cast</title>
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<link rel="icon" href="/images/ha-cast-icon.png" type="image/png" />
|
||||
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
|
||||
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
|
||||
<style>
|
||||
body {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<% for (const entry of latestEntryJS) { %>
|
||||
<script type="module" src="<%= entry %>"></script>
|
||||
<% } %>
|
||||
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
|
||||
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
|
||||
<style>
|
||||
body {
|
||||
|
||||
@@ -48,7 +48,7 @@ const translateErr = (err) =>
|
||||
const INTRO = html`
|
||||
<p>
|
||||
Home Assistant Cast allows you to cast your Home Assistant installation to
|
||||
Chromecast video devices and to Google Home devices with a screen.
|
||||
Chromecast video devices and to Google Assistant devices with a screen.
|
||||
</p>
|
||||
<p>
|
||||
For more information, see the
|
||||
|
||||
@@ -6,7 +6,7 @@ const playerManager = castContext.getPlayerManager();
|
||||
|
||||
playerManager.setMessageInterceptor("LOAD", (loadRequestData) => {
|
||||
const media = loadRequestData.media;
|
||||
// Special handling if it came from Google Home
|
||||
// Special handling if it came from Google Assistant
|
||||
if (media.entity) {
|
||||
media.contentId = media.entity;
|
||||
media.streamType = "LIVE";
|
||||
|
||||
@@ -13,7 +13,7 @@ export const castDemoLovelace: () => LovelaceConfig = () => {
|
||||
{
|
||||
type: "markdown",
|
||||
title: "Home Assistant Cast",
|
||||
content: `With Home Assistant you can easily create interfaces (just like this one) which can be shown on Chromecast devices connected to TVs or Google Home devices with a screen.${
|
||||
content: `With Home Assistant you can easily create interfaces (just like this one) which can be shown on Chromecast devices connected to TVs or Google Assistant devices with a screen.${
|
||||
touchSupported
|
||||
? "\n\nYou are able to interact with this demo using the touch screen."
|
||||
: "\n\nOn a Google Nest Hub you are able to interact with Home Assistant Cast via the touch screen."
|
||||
|
||||
@@ -117,7 +117,7 @@ playerManager.setMessageInterceptor("LOAD", (loadRequestData) => {
|
||||
// We received a play media command, hide Lovelace and show media player
|
||||
showMediaPlayer();
|
||||
const media = loadRequestData.media;
|
||||
// Special handling if it came from Google Home
|
||||
// Special handling if it came from Google Assistant
|
||||
if (media.entity) {
|
||||
media.contentId = media.entity;
|
||||
media.streamType = "LIVE";
|
||||
|
||||
@@ -28,7 +28,7 @@ class HcLaunchScreen extends LitElement {
|
||||
:host {
|
||||
display: block;
|
||||
height: 100vh;
|
||||
background-color: var(--primary-background-color, #f2f4f9);
|
||||
background-color: #f2f4f9;
|
||||
font-size: var(--ha-font-size-2xl);
|
||||
}
|
||||
.container {
|
||||
@@ -44,7 +44,7 @@ class HcLaunchScreen extends LitElement {
|
||||
object-fit: cover;
|
||||
}
|
||||
.status {
|
||||
color: var(--primary-text-color, #1d2126);
|
||||
color: #1d2126;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
/*
|
||||
Cache-Control: public, max-age=0, s-maxage=3600, must-revalidate
|
||||
Cache-Control: public, max-age: 0, s-maxage=3600, must-revalidate
|
||||
Content-Security-Policy: form-action https:
|
||||
Referrer-Policy: no-referrer-when-downgrade
|
||||
X-Content-Type-Options: nosniff
|
||||
X-XSS-Protection: 1; mode=block
|
||||
|
||||
/api/*
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
|
||||
/assets/*
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
|
||||
/frontend_es5/*
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
|
||||
/frontend_latest/*
|
||||
Cache-Control: public, max-age=604800, s-maxage=604800
|
||||
Cache-Control: public, max-age: 604800, s-maxage=604800
|
||||
Access-Control-Allow-Origin: *
|
||||
|
||||
/embed.js
|
||||
|
||||
@@ -168,8 +168,7 @@ export class HaEmbedProvider extends LitElement {
|
||||
hass.mockWS("config/device_registry/list", (_msg, currentHass) =>
|
||||
Object.values(currentHass.devices)
|
||||
);
|
||||
// The registry of the entities, with the options each entity sets, such
|
||||
// as timer presets. Other settings, such as calendar colors, are not set.
|
||||
// The registry of the entities, without settings such as calendar colors
|
||||
const registryEntries = (currentHass: MockHomeAssistant) =>
|
||||
Object.values(currentHass.entities).map(
|
||||
(entity): EntityRegistryEntry => ({
|
||||
@@ -180,9 +179,6 @@ export class HaEmbedProvider extends LitElement {
|
||||
}),
|
||||
area_id: entity.area_id ?? null,
|
||||
device_id: entity.device_id ?? null,
|
||||
options:
|
||||
this.entities.find((item) => item.entity_id === entity.entity_id)
|
||||
?.options ?? null,
|
||||
})
|
||||
);
|
||||
hass.mockWS("config/entity_registry/list", (_msg, currentHass) =>
|
||||
|
||||
@@ -35,12 +35,13 @@
|
||||
/>
|
||||
<meta name="theme-color" content="#03a9f4" />
|
||||
<%= renderTemplate("_social_meta.html.template") %>
|
||||
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
|
||||
<style>
|
||||
html {
|
||||
background-color: var(--primary-background-color, #fafafa);
|
||||
color: var(--primary-text-color, #212121);
|
||||
height: 100vh;
|
||||
/* Prevent iOS Safari from inflating text when rotating to landscape */
|
||||
-webkit-text-size-adjust: 100%;
|
||||
text-size-adjust: 100%;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html {
|
||||
@@ -48,8 +49,94 @@
|
||||
color: var(--primary-text-color, #e1e1e1);
|
||||
}
|
||||
}
|
||||
body {
|
||||
font-family: Roboto, Noto, sans-serif;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
font-weight: 400;
|
||||
height: 100vh;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
#ha-launch-screen {
|
||||
font-family: ui-sans-serif, system-ui, sans-serif;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
transition: opacity var(--ha-animation-duration-normal, 250ms) ease-out;
|
||||
}
|
||||
#ha-launch-screen.removing {
|
||||
opacity: 0;
|
||||
}
|
||||
@keyframes launch-lockup-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
#ha-launch-screen .ha-lockup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
animation: launch-lockup-in var(--ha-animation-duration-normal, 250ms) ease-out both;
|
||||
}
|
||||
#ha-launch-screen-info-box > *,
|
||||
#ha-launch-screen .ohf-logo {
|
||||
animation: launch-lockup-in var(--ha-animation-duration-normal, 250ms) ease-out both;
|
||||
}
|
||||
#ha-launch-screen .ha-logo {
|
||||
width: 96px;
|
||||
height: 96px;
|
||||
}
|
||||
#ha-launch-screen .ha-launch-screen-spacer-top {
|
||||
flex: 1;
|
||||
margin-top: calc( 2 * max(var(--safe-area-inset-top, 0px), 48px) + 46px );
|
||||
padding-top: 48px;
|
||||
}
|
||||
#ha-launch-screen .ha-launch-screen-spacer-bottom {
|
||||
flex: 1;
|
||||
padding-top: 16px;
|
||||
}
|
||||
.ohf-logo {
|
||||
margin: max(var(--safe-area-inset-bottom, 0px), 48px) 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
opacity: .66;
|
||||
}
|
||||
.ohf-logo span {
|
||||
font-size: 12px;
|
||||
line-height: 12px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.ohf-logo picture {
|
||||
display: flex;
|
||||
}
|
||||
.ohf-logo img {
|
||||
width: 237px;
|
||||
aspect-ratio: 237 / 24;
|
||||
height: auto;
|
||||
}
|
||||
@media (max-height: 560px) {
|
||||
#ha-launch-screen .ha-launch-screen-spacer-top {
|
||||
margin-top: 24px;
|
||||
padding-top: 24px;
|
||||
}
|
||||
#ha-launch-screen .ha-launch-screen-spacer-bottom {
|
||||
padding-top: 16px;
|
||||
}
|
||||
.ohf-logo {
|
||||
margin-block: 24px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<%= renderTemplate("../../../src/html/_style_launch_screen.html.template") %>
|
||||
</head>
|
||||
<body>
|
||||
<div id="ha-launch-screen">
|
||||
|
||||
@@ -44,21 +44,14 @@ export const lorawanFixtures: ConnectivityFixtures = {
|
||||
],
|
||||
commands: ["lorawan/"],
|
||||
manifests: [
|
||||
manifest("lorawan", "LoRaWAN", {
|
||||
config_flow: false,
|
||||
integration_type: "service",
|
||||
}),
|
||||
manifest("lorawan", "LoRaWAN", { integration_type: "helper" }),
|
||||
manifest("sensecap_lorawan", "SenseCAP", {
|
||||
integration_type: "device",
|
||||
dependencies: ["lorawan"],
|
||||
}),
|
||||
manifest("chirpstack", "ChirpStack", {
|
||||
integration_type: "hub",
|
||||
dependencies: ["lorawan"],
|
||||
}),
|
||||
manifest("chirpstack", "ChirpStack", { integration_type: "hub" }),
|
||||
manifest("thethingsnetwork_lorawan", "The Things Network", {
|
||||
integration_type: "hub",
|
||||
dependencies: ["lorawan"],
|
||||
}),
|
||||
],
|
||||
configEntries: [
|
||||
|
||||
@@ -10,26 +10,19 @@ export const FRONIUS_ENTRY_ID = "mock-fronius";
|
||||
export const RS485_PORT = "/dev/ttyUSB1";
|
||||
|
||||
export const modbusFixtures: ConnectivityFixtures = {
|
||||
components: ["modbus", "flexit", "solaredge_modbus", "fronius"],
|
||||
components: ["modbus"],
|
||||
commands: ["modbus/"],
|
||||
manifests: [
|
||||
manifest("modbus", "Modbus", {
|
||||
config_flow: false,
|
||||
iot_class: "local_polling",
|
||||
}),
|
||||
manifest("flexit", "Flexit", {
|
||||
integration_type: "device",
|
||||
dependencies: ["modbus"],
|
||||
iot_class: "local_polling",
|
||||
}),
|
||||
manifest("solaredge_modbus", "SolarEdge Modbus", {
|
||||
integration_type: "device",
|
||||
dependencies: ["modbus"],
|
||||
iot_class: "local_polling",
|
||||
}),
|
||||
manifest("fronius", "Fronius", {
|
||||
integration_type: "device",
|
||||
dependencies: ["modbus"],
|
||||
iot_class: "local_polling",
|
||||
}),
|
||||
],
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
|
||||
|
||||
export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
const prefs: EnergyPreferences = {
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => ({
|
||||
energy_sources: [
|
||||
{
|
||||
type: "grid",
|
||||
@@ -21,6 +21,7 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
stat_rate: "sensor.power_grid",
|
||||
cost_adjustment_day: 0,
|
||||
},
|
||||
{
|
||||
type: "grid",
|
||||
@@ -33,6 +34,7 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
entity_energy_price_export: null,
|
||||
number_energy_price_export: null,
|
||||
stat_rate: "sensor.power_grid_return",
|
||||
cost_adjustment_day: 0,
|
||||
},
|
||||
{
|
||||
type: "solar",
|
||||
@@ -46,23 +48,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_energy_to: "sensor.battery_input",
|
||||
stat_rate: "sensor.power_battery",
|
||||
},
|
||||
{
|
||||
type: "battery",
|
||||
name: "Powerwall",
|
||||
stat_energy_from_grid: "sensor.powerwall_from_grid",
|
||||
stat_energy_from_solar: "sensor.powerwall_from_solar",
|
||||
stat_energy_to_home: "sensor.powerwall_to_home",
|
||||
stat_energy_to_grid: "sensor.powerwall_to_grid",
|
||||
stat_rate: "sensor.powerwall_power",
|
||||
power_config: {
|
||||
stat_rate_from_grid: "sensor.powerwall_power_from_grid",
|
||||
stat_rate_from_solar: "sensor.powerwall_power_from_solar",
|
||||
stat_rate_to_home: "sensor.powerwall_power_to_home",
|
||||
stat_rate_to_grid: "sensor.powerwall_power_to_grid",
|
||||
},
|
||||
stat_soc: "sensor.powerwall_battery_level",
|
||||
capacity: 13.5,
|
||||
},
|
||||
{
|
||||
type: "gas",
|
||||
stat_energy_from: "sensor.energy_gas",
|
||||
@@ -112,25 +97,15 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
|
||||
stat_consumption: "sensor.water_garden",
|
||||
},
|
||||
],
|
||||
device_consumption_gas: [
|
||||
{
|
||||
stat_consumption: "sensor.gas_kitchen",
|
||||
},
|
||||
{
|
||||
stat_consumption: "sensor.gas_heat_pump",
|
||||
},
|
||||
],
|
||||
};
|
||||
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
|
||||
}));
|
||||
hass.mockWS("energy/info", (): EnergyInfo => ({
|
||||
cost_sensors: {},
|
||||
solar_forecast_domains: [],
|
||||
}));
|
||||
hass.mockWS("energy/validate", () => ({
|
||||
energy_sources: prefs.energy_sources.map(() => []),
|
||||
device_consumption: prefs.device_consumption.map(() => []),
|
||||
device_consumption_water: prefs.device_consumption_water.map(() => []),
|
||||
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
|
||||
energy_sources: Array.from({ length: 6 }, () => []),
|
||||
device_consumption: Array.from({ length: 6 }, () => []),
|
||||
device_consumption_water: Array.from({ length: 2 }, () => []),
|
||||
}));
|
||||
hass.mockWS(
|
||||
"energy/fossil_energy_consumption",
|
||||
|
||||
@@ -1,30 +1,3 @@
|
||||
// Live power of the battery measured per direction, in W
|
||||
const powerwallPower = {
|
||||
from_grid: 50,
|
||||
from_solar: 150,
|
||||
to_home: 0,
|
||||
to_grid: 0,
|
||||
};
|
||||
|
||||
const powerEntity = (entityId: string, power: number) => ({
|
||||
entity_id: entityId,
|
||||
state: String(power),
|
||||
attributes: {
|
||||
state_class: "measurement",
|
||||
unit_of_measurement: "W",
|
||||
},
|
||||
});
|
||||
|
||||
const powerwallEnergyEntity = (entityId: string, friendlyName: string) => ({
|
||||
entity_id: entityId,
|
||||
state: "2",
|
||||
attributes: {
|
||||
last_reset: "1970-01-01T00:00:00:00+00",
|
||||
friendly_name: friendlyName,
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
});
|
||||
|
||||
export const energyEntities = () =>
|
||||
Object.values({
|
||||
"sensor.grid_fossil_fuel_percentage": {
|
||||
@@ -61,31 +34,6 @@ export const energyEntities = () =>
|
||||
unit_of_measurement: "kWh",
|
||||
},
|
||||
},
|
||||
"sensor.powerwall_from_grid": powerwallEnergyEntity(
|
||||
"sensor.powerwall_from_grid",
|
||||
"Powerwall charged from grid"
|
||||
),
|
||||
"sensor.powerwall_from_solar": powerwallEnergyEntity(
|
||||
"sensor.powerwall_from_solar",
|
||||
"Powerwall charged from solar"
|
||||
),
|
||||
"sensor.powerwall_to_home": powerwallEnergyEntity(
|
||||
"sensor.powerwall_to_home",
|
||||
"Powerwall discharged to home"
|
||||
),
|
||||
"sensor.powerwall_to_grid": powerwallEnergyEntity(
|
||||
"sensor.powerwall_to_grid",
|
||||
"Powerwall discharged to grid"
|
||||
),
|
||||
"sensor.powerwall_battery_level": {
|
||||
entity_id: "sensor.powerwall_battery_level",
|
||||
state: "62",
|
||||
attributes: {
|
||||
device_class: "battery",
|
||||
friendly_name: "Powerwall battery level",
|
||||
unit_of_measurement: "%",
|
||||
},
|
||||
},
|
||||
"sensor.energy_consumption_tarif_1": {
|
||||
entity_id: "sensor.energy_consumption_tarif_1",
|
||||
state: "88.6",
|
||||
@@ -186,29 +134,6 @@ export const energyEntities = () =>
|
||||
unit_of_measurement: "W",
|
||||
},
|
||||
},
|
||||
"sensor.powerwall_power_from_grid": powerEntity(
|
||||
"sensor.powerwall_power_from_grid",
|
||||
powerwallPower.from_grid
|
||||
),
|
||||
"sensor.powerwall_power_from_solar": powerEntity(
|
||||
"sensor.powerwall_power_from_solar",
|
||||
powerwallPower.from_solar
|
||||
),
|
||||
"sensor.powerwall_power_to_home": powerEntity(
|
||||
"sensor.powerwall_power_to_home",
|
||||
powerwallPower.to_home
|
||||
),
|
||||
"sensor.powerwall_power_to_grid": powerEntity(
|
||||
"sensor.powerwall_power_to_grid",
|
||||
powerwallPower.to_grid
|
||||
),
|
||||
"sensor.powerwall_power": powerEntity(
|
||||
"sensor.powerwall_power",
|
||||
powerwallPower.to_home +
|
||||
powerwallPower.to_grid -
|
||||
powerwallPower.from_grid -
|
||||
powerwallPower.from_solar
|
||||
),
|
||||
"sensor.energy_gas_cost": {
|
||||
entity_id: "sensor.energy_gas_cost",
|
||||
state: "2",
|
||||
@@ -235,26 +160,6 @@ export const energyEntities = () =>
|
||||
unit_of_measurement: "L",
|
||||
},
|
||||
},
|
||||
"sensor.gas_kitchen": {
|
||||
entity_id: "sensor.gas_kitchen",
|
||||
state: "100",
|
||||
attributes: {
|
||||
friendly_name: "Gas kitchen",
|
||||
unit_of_measurement: "m³",
|
||||
device_class: "gas",
|
||||
state_class: "total_increasing",
|
||||
},
|
||||
},
|
||||
"sensor.gas_heat_pump": {
|
||||
entity_id: "sensor.gas_heat_pump",
|
||||
state: "500",
|
||||
attributes: {
|
||||
friendly_name: "Gas heat pump",
|
||||
unit_of_measurement: "m³",
|
||||
device_class: "gas",
|
||||
state_class: "total_increasing",
|
||||
},
|
||||
},
|
||||
"sensor.energy_car": {
|
||||
entity_id: "sensor.energy_car",
|
||||
state: "4",
|
||||
|
||||
@@ -158,24 +158,6 @@ const statisticsFunctions: Record<
|
||||
(bucketStart, bucketEnd) =>
|
||||
(20 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
|
||||
),
|
||||
"sensor.gas_kitchen": (_id, start, end, period = "hour") =>
|
||||
generateSumStatistics(
|
||||
start,
|
||||
end,
|
||||
period,
|
||||
100,
|
||||
(bucketStart, bucketEnd) =>
|
||||
(0.1 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
|
||||
),
|
||||
"sensor.gas_heat_pump": (_id, start, end, period = "hour") =>
|
||||
generateSumStatistics(
|
||||
start,
|
||||
end,
|
||||
period,
|
||||
500,
|
||||
(bucketStart, bucketEnd) =>
|
||||
(0.6 * (bucketEnd.getTime() - bucketStart.getTime())) / 3600000
|
||||
),
|
||||
"sensor.energy_consumption_tarif_1": (
|
||||
_id: string,
|
||||
start: Date,
|
||||
@@ -351,26 +333,6 @@ const statisticsFunctions: Record<
|
||||
const derivedCosts: Record<string, { source: string; price: number }> = {
|
||||
"sensor.energy_water_cost": { source: "sensor.energy_water", price: 0.004 },
|
||||
};
|
||||
// Battery directions as a share of the meter the energy also passes, so they
|
||||
// never exceed it
|
||||
const derivedBatteryFlows: Record<string, { source: string; share: number }> = {
|
||||
"sensor.powerwall_from_grid": {
|
||||
source: "sensor.energy_consumption_tarif_1",
|
||||
share: 0.4,
|
||||
},
|
||||
"sensor.powerwall_from_solar": {
|
||||
source: "sensor.solar_production",
|
||||
share: 0.3,
|
||||
},
|
||||
"sensor.powerwall_to_home": {
|
||||
source: "sensor.energy_consumption_tarif_2",
|
||||
share: 0.5,
|
||||
},
|
||||
"sensor.powerwall_to_grid": {
|
||||
source: "sensor.energy_production_tarif_2",
|
||||
share: 0.3,
|
||||
},
|
||||
};
|
||||
|
||||
export const mockRecorder = (mockHass: MockHomeAssistant) => {
|
||||
mockHass.mockWS(
|
||||
@@ -395,22 +357,15 @@ export const mockRecorder = (mockHass: MockHomeAssistant) => {
|
||||
return cache[id];
|
||||
};
|
||||
|
||||
const scaleStats = (source: string, factor: number) => {
|
||||
let sum = 0;
|
||||
return getStats(source).map((statistic) => {
|
||||
const change = statistic.change! * factor;
|
||||
sum += change;
|
||||
return { ...statistic, change, state: sum, sum };
|
||||
});
|
||||
};
|
||||
|
||||
statistic_ids.forEach((id: string) => {
|
||||
if (id in derivedCosts) {
|
||||
const { source, price } = derivedCosts[id];
|
||||
statistics[id] = scaleStats(source, price);
|
||||
} else if (id in derivedBatteryFlows) {
|
||||
const { source, share } = derivedBatteryFlows[id];
|
||||
statistics[id] = scaleStats(source, share);
|
||||
let cost = 0;
|
||||
statistics[id] = getStats(source).map((statistic) => {
|
||||
const change = statistic.change! * price;
|
||||
cost += change;
|
||||
return { ...statistic, change, state: cost, sum: cost };
|
||||
});
|
||||
} else if (id in statisticsFunctions) {
|
||||
statistics[id] = getStats(id);
|
||||
} else {
|
||||
|
||||
@@ -301,14 +301,6 @@ export default tseslint.config(
|
||||
globals: globals.node,
|
||||
},
|
||||
},
|
||||
{
|
||||
// Published as native ESM, where package subpath imports such as
|
||||
// "lit/decorators.js" need their extension.
|
||||
files: ["packages/*/src/**/*.ts"],
|
||||
rules: {
|
||||
"import-x/extensions": ["error", "ignorePackages", { ts: "never" }],
|
||||
},
|
||||
},
|
||||
{
|
||||
plugins: {
|
||||
html,
|
||||
|
||||
@@ -25,6 +25,7 @@ class DemoMoreInfo extends LitElement {
|
||||
!computeShowNewMoreInfo(state)
|
||||
? html`<state-card-content
|
||||
.stateObj=${state}
|
||||
.hass=${this.hass}
|
||||
in-dialog
|
||||
></state-card-content>`
|
||||
: nothing
|
||||
|
||||
@@ -4,7 +4,7 @@ title: "Our story"
|
||||
|
||||
## Open source home automation that puts local control and privacy first
|
||||
|
||||
Home Assistant is a free and open-source software for home automation that is designed to be the central control system for smart home devices with a focus on local control and privacy. It can be accessed via a web-based user interface, via apps for Android and iOS, or using voice commands via a supported virtual assistant like Google Home and Amazon Alexa.
|
||||
Home Assistant is a free and open-source software for home automation that is designed to be the central control system for smart home devices with a focus on local control and privacy. It can be accessed via a web-based user interface, via apps for Android and iOS, or using voice commands via a supported virtual assistant like Google Assistant and Amazon Alexa.
|
||||
|
||||
IoT devices and services are supported by modular support for controlling proprietary ecosystems if they provide public access via an Open API for third-party integrations and protocols like Bluetooth, MQTT, Zigbee, and Z-Wave, After the Home Assistant software application is installed as a computer appliance it will act as a central control system for home automation. Information from all entities it sees can be used and controlled from within scripts trigger automations using scheduling and "blueprint" subroutines, e.g. for controlling lighting, climate, entertainment systems, and appliances.
|
||||
|
||||
@@ -36,6 +36,6 @@ Durability for the Open Home means that devices are designed and built to keep w
|
||||
|
||||
The project was started as a Python application by Paulus Schoutsen in September 2013 and first published publicly on GitHub in November 2013. In July 2017, a managed operating system called Hass.io was initially introduced to make it easier use to use Home Assistant on single-board computers like the Raspberry Pi series. Its bundled "supervisor" management system allowed users to manage, backup, and update the local installation and introduced the option to extend the functionality of the software with add-ons.
|
||||
|
||||
An optional subscription service was introduced in December 2017 for $5/month to solve the complexities associated with secured remote access, as well as linking to Amazon Alexa and Google Home. Nabu Casa, Inc. was formed in September 2018 to take over the subscription service. The company's funding is based solely on revenue from the subscription service. It is used to finance the project's infrastructure and to pay for full-time employees contributing to the project.
|
||||
An optional subscription service was introduced in December 2017 for $5/month to solve the complexities associated with secured remote access, as well as linking to Amazon Alexa and Google Assistant. Nabu Casa, Inc. was formed in September 2018 to take over the subscription service. The company's funding is based solely on revenue from the subscription service. It is used to finance the project's infrastructure and to pay for full-time employees contributing to the project.
|
||||
|
||||
In January 2020, branding was adjusted to make it easier to refer to different parts of the project. The main piece of software was renamed to Home Assistant Core, while the full suite of software with the embedded operating system and bundled "supervisor" management system was renamed to Home Assistant.
|
||||
@@ -117,17 +117,11 @@ shared slots/attributes below.
|
||||
|
||||
**Attributes**
|
||||
|
||||
| Name | Type | Default | Description |
|
||||
| ---------------------- | ------- | ------- | -------------------------------------------------- |
|
||||
| `headline` | String | — | Primary text. Overridden by the slot. |
|
||||
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
|
||||
| `wrap-headline` | Boolean | `false` | Wrap the headline instead of truncating it. |
|
||||
| `wrap-supporting-text` | Boolean | `false` | Wrap the supporting text instead of truncating it. |
|
||||
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
|
||||
|
||||
The headline and the supporting text stay on one line and are truncated with an
|
||||
ellipsis by default. Set `wrap-headline` or `wrap-supporting-text` on rows whose
|
||||
text has to stay readable in full, like settings with a description.
|
||||
| Name | Type | Default | Description |
|
||||
| ----------------- | ------- | ------- | --------------------------------------- |
|
||||
| `headline` | String | — | Primary text. Overridden by the slot. |
|
||||
| `supporting-text` | String | — | Secondary text. Overridden by the slot. |
|
||||
| `disabled` | Boolean | `false` | Dims the row and blocks pointer events. |
|
||||
|
||||
**CSS parts**
|
||||
|
||||
@@ -171,18 +165,6 @@ Interactive row. Renders an inner `<a>` when `href` is set, otherwise a
|
||||
roving tabindex, the host is the tab stop and the inner element carries
|
||||
`tabindex="-1"`.
|
||||
|
||||
Only the headline and supporting text are inside the `<a>` or `<button>`; its
|
||||
hit area is stretched over the whole row. The `start` and `end` slots sit next
|
||||
to it, so controls placed there, like an `ha-icon-button` or `ha-dropdown`,
|
||||
stay separate controls for screen readers. Slotted elements are raised above
|
||||
the hit area so they can be clicked, except icons, badges, `span`s and empty
|
||||
`div`s (dividers), which let clicks and hover through to the row. A focusable
|
||||
element (with `tabindex`) is always raised. To keep another element clickable
|
||||
on its own, like a drag handle, give it `z-index: 1` in the consumer's styles.
|
||||
|
||||
Subclasses customize the row by overriding `_renderStart()`,
|
||||
`_renderContent()` and `_renderEnd()`. `_renderInner()` is not used.
|
||||
|
||||
**Attributes**
|
||||
|
||||
- `href` (String) — when set, renders an `<a>` instead of a `<button>`.
|
||||
@@ -192,7 +174,6 @@ Subclasses customize the row by overriding `_renderStart()`,
|
||||
|
||||
**CSS parts**
|
||||
|
||||
- `control` — the inner `<a>` or `<button>`.
|
||||
- `ripple` — the ripple effect element.
|
||||
|
||||
### `<ha-list-item-option>`
|
||||
|
||||
@@ -2,12 +2,10 @@ import {
|
||||
mdiAccount,
|
||||
mdiChevronRight,
|
||||
mdiCog,
|
||||
mdiDelete,
|
||||
mdiHome,
|
||||
mdiInformationOutline,
|
||||
mdiMapMarker,
|
||||
mdiOpenInNew,
|
||||
mdiPencil,
|
||||
mdiViewDashboard,
|
||||
mdiWifi,
|
||||
} from "@mdi/js";
|
||||
@@ -15,8 +13,6 @@ import type { TemplateResult } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, state } from "lit/decorators";
|
||||
import "../../../../src/components/ha-card";
|
||||
import "../../../../src/components/ha-icon-button";
|
||||
import "../../../../src/components/ha-icon-next";
|
||||
import "../../../../src/components/ha-svg-icon";
|
||||
import "../../../../src/components/item/ha-list-item-base";
|
||||
import "../../../../src/components/item/ha-list-item-button";
|
||||
@@ -81,8 +77,6 @@ const treeKey = (group: TreeGroup, child: TreeChild) =>
|
||||
export class DemoHaList extends LitElement {
|
||||
@state() private _buttonClicks = 0;
|
||||
|
||||
@state() private _lastAction = "none";
|
||||
|
||||
@state() private _single: number | Set<number> = -1;
|
||||
|
||||
@state() private _multiLine: number | Set<number> = new Set();
|
||||
@@ -191,20 +185,6 @@ export class DemoHaList extends LitElement {
|
||||
<ha-list-item-base headline="Disabled row" disabled>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
<ha-list-item-base
|
||||
headline="Truncated by default, a long headline stays on one line and ends with an ellipsis"
|
||||
supporting-text="Long supporting text is truncated as well, so every row in the list keeps the same height"
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
<ha-list-item-base
|
||||
wrap-headline
|
||||
wrap-supporting-text
|
||||
headline="With wrap-headline, a long headline wraps onto as many lines as it needs"
|
||||
supporting-text="With wrap-supporting-text, long supporting text wraps too, which suits settings with a description"
|
||||
>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
</ha-list-item-base>
|
||||
</ha-list-base>
|
||||
</ha-card>
|
||||
|
||||
@@ -240,51 +220,6 @@ export class DemoHaList extends LitElement {
|
||||
</ha-list-base>
|
||||
</ha-card>
|
||||
|
||||
<ha-card header="Row with actions in the end slot">
|
||||
<p class="card-text">
|
||||
Last action: <code>${this._lastAction}</code>. The action buttons are
|
||||
separate controls; icons and the divider activate the row.
|
||||
</p>
|
||||
<ha-list-base aria-label="Rows with actions">
|
||||
<ha-list-item-button data-action="row" @click=${this._onActionClick}>
|
||||
<ha-svg-icon slot="start" .path=${mdiHome}></ha-svg-icon>
|
||||
<span slot="headline">Button row</span>
|
||||
<span slot="supporting-text">Click the row or an action</span>
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
<div slot="end" class="vertical-divider"></div>
|
||||
<ha-icon-button
|
||||
slot="end"
|
||||
data-action="edit"
|
||||
.path=${mdiPencil}
|
||||
label="Edit"
|
||||
@click=${this._onActionClick}
|
||||
></ha-icon-button>
|
||||
<ha-icon-button
|
||||
slot="end"
|
||||
data-action="delete"
|
||||
.path=${mdiDelete}
|
||||
label="Delete"
|
||||
@click=${this._onActionClick}
|
||||
></ha-icon-button>
|
||||
</ha-list-item-button>
|
||||
<ha-list-item-button href="#components/ha-list">
|
||||
<ha-svg-icon slot="start" .path=${mdiMapMarker}></ha-svg-icon>
|
||||
<span slot="headline">Link row</span>
|
||||
<span slot="supporting-text"
|
||||
>Cmd/Ctrl-click on the icon or chevron opens a new tab</span
|
||||
>
|
||||
<ha-icon-button
|
||||
slot="end"
|
||||
data-action="link-edit"
|
||||
.path=${mdiPencil}
|
||||
label="Edit"
|
||||
@click=${this._onActionClick}
|
||||
></ha-icon-button>
|
||||
<ha-icon-next slot="end"></ha-icon-next>
|
||||
</ha-list-item-button>
|
||||
</ha-list-base>
|
||||
</ha-card>
|
||||
|
||||
<h2>ha-list-selectable + ha-list-item-option</h2>
|
||||
<p>
|
||||
Selectable list (<code>role="listbox"</code>). Items must be
|
||||
@@ -493,12 +428,6 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
|
||||
return value instanceof Set ? [...value] : value;
|
||||
}
|
||||
|
||||
private _onActionClick = (ev: MouseEvent) => {
|
||||
ev.stopPropagation();
|
||||
this._lastAction =
|
||||
(ev.currentTarget as HTMLElement).dataset.action ?? "none";
|
||||
};
|
||||
|
||||
private _onButtonClick = () => {
|
||||
this._buttonClicks++;
|
||||
};
|
||||
@@ -613,15 +542,6 @@ selected: ${JSON.stringify(this._toJson(this._multiCheckEnd))}</pre>
|
||||
ha-card {
|
||||
max-width: 560px;
|
||||
}
|
||||
.card-text {
|
||||
margin: 0;
|
||||
padding: 0 var(--ha-space-4) var(--ha-space-2);
|
||||
}
|
||||
.vertical-divider {
|
||||
align-self: stretch;
|
||||
width: 1px;
|
||||
background: var(--divider-color);
|
||||
}
|
||||
pre {
|
||||
padding: var(--ha-space-4);
|
||||
background: var(--secondary-background-color);
|
||||
|
||||
@@ -121,7 +121,7 @@ const brandEntries: ConfigEntryExtended[] = (
|
||||
["tuya", "Tuya", "setup_error"],
|
||||
["unifi", "UniFi Network", "not_loaded"],
|
||||
["met", "Meteorologisk institutt (Met.no)", "setup_error"],
|
||||
["google_assistant", "Google Home", "not_loaded"],
|
||||
["google_assistant", "Google Assistant", "not_loaded"],
|
||||
["homekit_controller", "HomeKit Device", "setup_retry"],
|
||||
] as [string, string, ConfigEntryExtended["state"]][]
|
||||
).map(([domain, name, entryState]) =>
|
||||
|
||||
@@ -187,139 +187,6 @@ const ENTITIES = [
|
||||
current_tilt_position: 70,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.shade",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Shade",
|
||||
device_class: "shade",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 60,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.shutter",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Shutter",
|
||||
device_class: "shutter",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 40,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.awning",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Awning",
|
||||
device_class: "awning",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 70,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.curtain",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Curtain",
|
||||
device_class: "curtain",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 50,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.door",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Door",
|
||||
device_class: "door",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 30,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.gate",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Gate",
|
||||
device_class: "gate",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 30,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.window",
|
||||
state: "open",
|
||||
attributes: {
|
||||
friendly_name: "Window",
|
||||
device_class: "window",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
current_position: 50,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.garage",
|
||||
state: "closed",
|
||||
attributes: {
|
||||
friendly_name: "Garage door",
|
||||
device_class: "garage",
|
||||
supported_features: CoverEntityFeature.OPEN + CoverEntityFeature.CLOSE,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.unknown",
|
||||
state: "unknown",
|
||||
attributes: {
|
||||
friendly_name: "Unknown position",
|
||||
device_class: "shade",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
},
|
||||
},
|
||||
{
|
||||
entity_id: "cover.unavailable",
|
||||
state: "unavailable",
|
||||
attributes: {
|
||||
friendly_name: "Unavailable",
|
||||
device_class: "shutter",
|
||||
supported_features:
|
||||
CoverEntityFeature.OPEN +
|
||||
CoverEntityFeature.STOP +
|
||||
CoverEntityFeature.CLOSE +
|
||||
CoverEntityFeature.SET_POSITION,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@customElement("demo-more-info-cover")
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
<head>
|
||||
<title>Home Assistant</title>
|
||||
<%= renderTemplate("../../../src/html/_header.html.template") %>
|
||||
<%= renderTemplate("../../../src/html/_meta_viewport.html.template") %>
|
||||
<%= renderTemplate("../../../src/html/_style_base.html.template") %>
|
||||
<style>
|
||||
html {
|
||||
|
||||
+42
-42
@@ -13,7 +13,7 @@
|
||||
"lint:prettier": "prettier . --cache --check",
|
||||
"format:prettier": "prettier . --cache --write",
|
||||
"lint:types": "node ./node_modules/@typescript/native/bin/tsc && node ./node_modules/@typescript/native/bin/tsc -p .github/scripts",
|
||||
"lint:lit": "lit-analyzer \"{.,*,packages/*}/src/**/*.ts\"",
|
||||
"lint:lit": "lit-analyzer \"{.,*}/src/**/*.ts\"",
|
||||
"lint:element-imports": "eslint \"**/src/**/*.{js,ts,html}\" --ignore-pattern=.gitignore --rule '{\"ha/no-unused-element-import\": \"warn\"}'",
|
||||
"lint:licenses": "node --no-deprecation script/check-licenses",
|
||||
"lint": "pnpm run lint:eslint && pnpm run lint:prettier && pnpm run lint:types && pnpm run lint:lit",
|
||||
@@ -40,7 +40,7 @@
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "8.1.2",
|
||||
"@babel/runtime": "8.0.10",
|
||||
"@braintree/sanitize-url": "7.1.2",
|
||||
"@codemirror/autocomplete": "6.20.4",
|
||||
"@codemirror/commands": "6.11.1",
|
||||
@@ -48,21 +48,21 @@
|
||||
"@codemirror/lang-python": "6.2.1",
|
||||
"@codemirror/lang-yaml": "6.1.3",
|
||||
"@codemirror/language": "6.13.1",
|
||||
"@codemirror/lint": "6.9.8",
|
||||
"@codemirror/lint": "6.9.7",
|
||||
"@codemirror/search": "6.7.2",
|
||||
"@codemirror/state": "6.7.6",
|
||||
"@codemirror/view": "6.43.15",
|
||||
"@date-fns/tz": "1.5.0",
|
||||
"@egjs/hammerjs": "2.0.17",
|
||||
"@formatjs/intl-datetimeformat": "8.0.3",
|
||||
"@formatjs/intl-displaynames": "8.0.3",
|
||||
"@formatjs/intl-durationformat": "0.12.4",
|
||||
"@formatjs/intl-getcanonicallocales": "3.3.1",
|
||||
"@formatjs/intl-listformat": "9.0.3",
|
||||
"@formatjs/intl-locale": "5.4.3",
|
||||
"@formatjs/intl-numberformat": "10.0.4",
|
||||
"@formatjs/intl-pluralrules": "7.0.4",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.3",
|
||||
"@formatjs/intl-datetimeformat": "8.0.2",
|
||||
"@formatjs/intl-displaynames": "8.0.1",
|
||||
"@formatjs/intl-durationformat": "0.12.3",
|
||||
"@formatjs/intl-getcanonicallocales": "3.3.0",
|
||||
"@formatjs/intl-listformat": "9.0.1",
|
||||
"@formatjs/intl-locale": "5.4.2",
|
||||
"@formatjs/intl-numberformat": "10.0.2",
|
||||
"@formatjs/intl-pluralrules": "7.0.2",
|
||||
"@formatjs/intl-relativetimeformat": "13.0.1",
|
||||
"@home-assistant/webawesome": "3.14.0-ha.2",
|
||||
"@lezer/common": "1.5.5",
|
||||
"@lezer/highlight": "1.2.5",
|
||||
@@ -73,22 +73,23 @@
|
||||
"@lit/reactive-element": "2.1.2",
|
||||
"@lit/task": "1.0.3",
|
||||
"@maplibre/maplibre-gl-leaflet": "0.1.4",
|
||||
"@material/mwc-list": "0.27.0",
|
||||
"@mdi/js": "7.4.47",
|
||||
"@mdi/svg": "7.4.47",
|
||||
"@replit/codemirror-indentation-markers": "6.5.3",
|
||||
"@swc/helpers": "0.5.24",
|
||||
"@tsparticles/engine": "4.5.4",
|
||||
"@tsparticles/preset-links": "4.5.4",
|
||||
"@versatiles/style": "9.1.0",
|
||||
"@swc/helpers": "0.5.23",
|
||||
"@tsparticles/engine": "4.5.0",
|
||||
"@tsparticles/preset-links": "4.5.0",
|
||||
"@versatiles/style": "7.1.0",
|
||||
"@vibrant/color": "4.0.4",
|
||||
"@vvo/tzdb": "6.204.0",
|
||||
"@vvo/tzdb": "6.202.0",
|
||||
"@webcomponents/scoped-custom-element-registry": "0.0.10",
|
||||
"barcode-detector": "3.2.3",
|
||||
"cally": "0.9.2",
|
||||
"color-name": "2.1.1",
|
||||
"comlink": "4.4.2",
|
||||
"core-js": "3.51.0",
|
||||
"cropperjs": "2.3.1",
|
||||
"cropperjs": "1.7.0",
|
||||
"culori": "4.0.2",
|
||||
"date-fns": "4.4.0",
|
||||
"decimal.js": "10.6.0",
|
||||
@@ -97,19 +98,19 @@
|
||||
"echarts": "6.1.0",
|
||||
"echarts-extension-chart2music": "0.1.1",
|
||||
"element-internals-polyfill": "3.0.2",
|
||||
"fullcalendar": "7.1.5",
|
||||
"fullcalendar": "7.1.3",
|
||||
"fuse.js": "7.5.0",
|
||||
"hls.js": "1.7.4",
|
||||
"home-assistant-js-websocket": "9.8.1",
|
||||
"idb-keyval": "6.3.0",
|
||||
"intl-messageformat": "12.1.5",
|
||||
"intl-messageformat": "12.1.4",
|
||||
"js-yaml": "5.5.0",
|
||||
"leaflet": "1.9.4",
|
||||
"leaflet.markercluster": "1.5.3",
|
||||
"lit": "3.3.3",
|
||||
"lit-html": "3.3.3",
|
||||
"maplibre-gl": "6.18.0",
|
||||
"marked": "18.2.0",
|
||||
"maplibre-gl": "6.16.0",
|
||||
"marked": "18.1.2",
|
||||
"memoize-one": "6.0.0",
|
||||
"nanoid": "6.0.2",
|
||||
"node-vibrant": "4.0.4",
|
||||
@@ -122,7 +123,7 @@
|
||||
"sortablejs": "1.15.7",
|
||||
"stacktrace-js": "2.0.2",
|
||||
"superstruct": "2.0.2",
|
||||
"temporal-polyfill": "1.0.8",
|
||||
"temporal-polyfill": "1.0.6",
|
||||
"tinykeys": "4.0.1",
|
||||
"weekstart": "2.0.0",
|
||||
"workbox-cacheable-response": "7.4.1",
|
||||
@@ -136,24 +137,23 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ampproject/remapping": "2.3.0",
|
||||
"@babel/core": "8.1.2",
|
||||
"@babel/core": "8.0.10",
|
||||
"@babel/helper-compilation-targets": "8.0.7",
|
||||
"@babel/helper-define-polyfill-provider": "1.0.0",
|
||||
"@babel/plugin-transform-class-properties": "8.0.1",
|
||||
"@babel/plugin-transform-private-methods": "8.0.1",
|
||||
"@babel/plugin-transform-runtime": "8.1.2",
|
||||
"@babel/plugin-transform-runtime": "8.0.6",
|
||||
"@babel/preset-env": "8.0.7",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.23.1",
|
||||
"@bundle-stats/plugin-webpack-filter": "4.23.0",
|
||||
"@eslint/js": "10.0.1",
|
||||
"@gfx/zopfli": "1.0.15",
|
||||
"@home-assistant/components": "workspace:*",
|
||||
"@html-eslint/eslint-plugin": "0.68.0",
|
||||
"@html-eslint/eslint-plugin": "0.67.0",
|
||||
"@lokalise/node-api": "17.0.1",
|
||||
"@octokit/auth-oauth-device": "8.0.5",
|
||||
"@octokit/rest": "22.0.1",
|
||||
"@playwright/test": "1.65.0",
|
||||
"@playwright/test": "1.64.1",
|
||||
"@rsdoctor/rspack-plugin": "1.6.5",
|
||||
"@rspack/core": "2.3.2",
|
||||
"@rspack/core": "2.3.0",
|
||||
"@rspack/dev-server": "2.2.2",
|
||||
"@types/babel__plugin-transform-runtime": "7.9.5",
|
||||
"@types/chromecast-caf-receiver": "7.0.1",
|
||||
@@ -170,7 +170,7 @@
|
||||
"@types/sortablejs": "1.15.9",
|
||||
"@types/tar": "7.0.87",
|
||||
"@typescript/native": "npm:[email protected]",
|
||||
"@vitest/coverage-v8": "5.1.0",
|
||||
"@vitest/coverage-v8": "5.0.5",
|
||||
"babel-loader": "10.1.1",
|
||||
"babel-plugin-polyfill-corejs3": "1.0.0",
|
||||
"browserslist": "4.29.5",
|
||||
@@ -180,7 +180,7 @@
|
||||
"eslint": "10.14.0",
|
||||
"eslint-config-prettier": "10.1.8",
|
||||
"eslint-import-resolver-webpack": "0.13.11",
|
||||
"eslint-plugin-import-x": "4.18.1",
|
||||
"eslint-plugin-import-x": "4.17.1",
|
||||
"eslint-plugin-lit": "2.3.1",
|
||||
"eslint-plugin-lit-a11y": "5.1.3",
|
||||
"eslint-plugin-unused-imports": "4.4.1",
|
||||
@@ -188,14 +188,14 @@
|
||||
"fancy-log": "2.0.0",
|
||||
"fs-extra": "11.4.1",
|
||||
"generate-license-file": "4.2.5",
|
||||
"glob": "14.0.6",
|
||||
"glob": "14.0.3",
|
||||
"globals": "17.14.0",
|
||||
"gulp": "5.0.1",
|
||||
"gulp-json-transform": "0.5.0",
|
||||
"gulp-rename": "2.1.0",
|
||||
"html-minifier-terser": "7.2.0",
|
||||
"husky": "9.1.7",
|
||||
"jsdom": "31.0.1",
|
||||
"jsdom": "30.1.3",
|
||||
"jszip": "3.10.2",
|
||||
"license-checker-rseidelsohn": "5.0.1",
|
||||
"lightningcss": "1.33.0",
|
||||
@@ -206,24 +206,24 @@
|
||||
"map-stream": "0.0.7",
|
||||
"minify-literals": "2.2.0",
|
||||
"pinst": "3.0.0",
|
||||
"prettier": "3.10.1",
|
||||
"prettier": "3.9.10",
|
||||
"rspack-manifest-plugin": "5.2.2",
|
||||
"serve": "14.2.7",
|
||||
"serve": "14.2.6",
|
||||
"sinon": "22.1.0",
|
||||
"tar": "7.5.23",
|
||||
"tar": "7.5.22",
|
||||
"terser-webpack-plugin": "5.6.1",
|
||||
"ts-lit-plugin": "2.0.2",
|
||||
"typescript": "6.0.3",
|
||||
"typescript-eslint": "8.72.2",
|
||||
"vite": "8.3.8",
|
||||
"typescript-eslint": "8.72.1",
|
||||
"vite": "8.3.5",
|
||||
"vite-tsconfig-paths": "6.1.1",
|
||||
"vitest": "5.1.0",
|
||||
"vitest": "5.0.5",
|
||||
"webpack-stats-plugin": "1.1.3",
|
||||
"webpackbar": "7.0.0",
|
||||
"workbox-build": "7.4.1"
|
||||
},
|
||||
"packageManager": "pnpm@12.20.0",
|
||||
"packageManager": "pnpm@12.16.1",
|
||||
"volta": {
|
||||
"node": "24.22.3"
|
||||
"node": "24.22.2"
|
||||
}
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
# @home-assistant/components
|
||||
|
||||
Home Assistant Components (`hac-*`): framework-agnostic web components built
|
||||
with [Lit](https://lit.dev).
|
||||
|
||||
> Work in progress, not published yet.
|
||||
|
||||
## Registration
|
||||
|
||||
Every element is imported on its own, in one of two ways:
|
||||
|
||||
| Import | Registers in | For |
|
||||
| --------------------------------------------- | -------------------- | ----------------------------------------------------------- |
|
||||
| `@home-assistant/components/<element>` | Global registry | Home Assistant itself |
|
||||
| `@home-assistant/components/<element>/scoped` | Your scoped registry | Custom cards and other code that runs inside Home Assistant |
|
||||
|
||||
`<element>` is the tag name without the `hac-` prefix, like `card` for
|
||||
`hac-card`.
|
||||
|
||||
Both use the copy bundled with your code. A scoped copy is isolated from the
|
||||
one Home Assistant registers globally, so a custom card keeps the version it
|
||||
was built with.
|
||||
|
||||
Global registration skips tag names that are already registered, so the first
|
||||
registration wins and nothing throws.
|
||||
|
||||
### Global
|
||||
|
||||
```ts
|
||||
import "@home-assistant/components/card";
|
||||
```
|
||||
|
||||
### Scoped
|
||||
|
||||
Pass the component's elements to `ScopedElementsMixin` for Lit, or to
|
||||
`createScopedElementRegistry` for plain custom elements. Forgetting the
|
||||
elements is a TypeScript error, and a runtime error in plain JavaScript.
|
||||
|
||||
Lit:
|
||||
|
||||
```ts
|
||||
import { LitElement, html } from "lit";
|
||||
import { ScopedElementsMixin } from "@home-assistant/components/scoped";
|
||||
import { hacCard } from "@home-assistant/components/card/scoped";
|
||||
|
||||
class MyCard extends ScopedElementsMixin(LitElement, [hacCard]) {
|
||||
render() {
|
||||
return html`<hac-card>…</hac-card>`;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Plain custom elements:
|
||||
|
||||
```js
|
||||
import {
|
||||
attachScopedShadow,
|
||||
createScopedElement,
|
||||
createScopedElementRegistry,
|
||||
} from "@home-assistant/components/scoped";
|
||||
import { hacCard } from "@home-assistant/components/card/scoped";
|
||||
|
||||
// Create the registry once, outside the class: all instances of the card share it
|
||||
const registry = createScopedElementRegistry([hacCard]);
|
||||
|
||||
class MyCard extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
const root = attachScopedShadow(this, { mode: "open" }, registry);
|
||||
root.innerHTML = "<hac-card>…</hac-card>";
|
||||
// or: root.append(createScopedElement(root, "hac-card"));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`innerHTML`, `insertAdjacentHTML` and `createScopedElement` use the scoped
|
||||
registry. `document.createElement` uses the global one, so avoid it for
|
||||
scoped elements.
|
||||
|
||||
Scoped registries need native support (Chrome 146+, Safari 26) or
|
||||
`@webcomponents/scoped-custom-element-registry`, which Home Assistant loads.
|
||||
Without either, elements are registered globally instead, and an already
|
||||
registered tag name keeps its existing class.
|
||||
|
||||
Only elements rendered inside the shadow root use the scoped registry. Light
|
||||
DOM content, such as slotted elements, uses the registry of the tree it is
|
||||
written in.
|
||||
|
||||
`lit` is a peer dependency.
|
||||
|
||||
### TypeScript
|
||||
|
||||
Each element's entry points declare its tag in `HTMLElementTagNameMap`, so
|
||||
`document.querySelector("hac-card")` and templates are typed once the element
|
||||
is imported. For the class itself, import its type from the `scoped` entry
|
||||
point; `import type` loads nothing at runtime:
|
||||
|
||||
```ts
|
||||
import type { HacCard } from "@home-assistant/components/card/scoped";
|
||||
```
|
||||
|
||||
The package has no root entry point: each element and the scoped helpers
|
||||
(`@home-assistant/components/scoped`) have their own.
|
||||
|
||||
## Theming
|
||||
|
||||
Each component exposes its own `--hac-*` custom properties, documented in its
|
||||
source, which take precedence. Next come the theme variables of the existing
|
||||
Home Assistant element it replaces, so current themes keep working: `hac-card`
|
||||
reads the variables of `ha-card` (`--ha-card-background`,
|
||||
`--card-background-color`, `--ha-card-border-radius`, …). Last come the
|
||||
semantic color tokens (`--ha-color-*`, like `--ha-color-surface-default`) and
|
||||
their light values, so the components also render outside Home Assistant.
|
||||
|
||||
The legacy theme variables are a temporary bridge for this experiment, not the
|
||||
target design. Home Assistant always defines some of them, like
|
||||
`--card-background-color`, so inside Home Assistant they currently win over
|
||||
the semantic tokens. Once themes move to the semantic tokens, the legacy
|
||||
variables will be removed from the fallbacks.
|
||||
|
||||
## Structure
|
||||
|
||||
Each element has its own directory, named like its import path:
|
||||
|
||||
```
|
||||
src/components/card/ <hac-card> -> @home-assistant/components/card
|
||||
hac-card.ts class, does not register itself
|
||||
info.ts tag name and version
|
||||
global.ts registers globally
|
||||
scoped.ts element for a scoped registry -> …/card/scoped
|
||||
```
|
||||
|
||||
Shared code lives in `src/utils/`: `registration/` for defining elements
|
||||
(global and scoped) and `element/` for helpers that components use
|
||||
themselves, like slot checks.
|
||||
|
||||
Every element has its own version in `info.ts`.
|
||||
|
||||
Entry points are mapped with subpath patterns in `package.json`, so a new
|
||||
element directory needs no `package.json` change. Only `global.ts` files have
|
||||
side effects, which `sideEffects` relies on for tree shaking.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
pnpm --filter @home-assistant/components build # ESM, type declarations and custom-elements.json to dist/
|
||||
pnpm --filter @home-assistant/components dev # rebuild on change
|
||||
```
|
||||
|
||||
Inside this repository the app uses the sources directly through
|
||||
the `ha-source` export condition, so no build is needed during development.
|
||||
The package is built with [Rslib](https://rslib.rs) in bundleless mode: every
|
||||
source file becomes its own ES module. The build then generates a
|
||||
[custom elements manifest](https://custom-elements-manifest.open-wc.org) from
|
||||
the JSDoc of each element, so document new slots, parts, CSS properties and
|
||||
events there.
|
||||
@@ -1,84 +0,0 @@
|
||||
// Generates dist/custom-elements.json from the JSDoc of the hac elements, for
|
||||
// editors and documentation tools. Only hac-*.ts files declare elements; the
|
||||
// entry points just re-export them.
|
||||
|
||||
const forEachDeclaration = (customElementsManifest, callback) => {
|
||||
for (const module of customElementsManifest.modules) {
|
||||
for (const declaration of module.declarations ?? []) {
|
||||
callback(declaration);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// The analyzer leaves the readme empty. Paths in the manifest are relative to
|
||||
// the package root, like the module paths.
|
||||
const packageReadme = () => ({
|
||||
name: "package-readme",
|
||||
packageLinkPhase({ customElementsManifest }) {
|
||||
customElementsManifest.readme = "README.md";
|
||||
},
|
||||
});
|
||||
|
||||
// Elements are documented with @summary, which the analyzer only puts into
|
||||
// `summary`. Most tools show `description`, so fall back to the summary.
|
||||
const summaryAsDescription = () => ({
|
||||
name: "summary-as-description",
|
||||
packageLinkPhase({ customElementsManifest }) {
|
||||
forEachDeclaration(customElementsManifest, (declaration) => {
|
||||
if (!declaration.description && declaration.summary) {
|
||||
declaration.description = declaration.summary;
|
||||
}
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// Private and protected members are internal, so keep them out of the
|
||||
// documented API.
|
||||
const publicApiOnly = () => ({
|
||||
name: "public-api-only",
|
||||
packageLinkPhase({ customElementsManifest }) {
|
||||
forEachDeclaration(customElementsManifest, (declaration) => {
|
||||
declaration.members = declaration.members?.filter(
|
||||
(member) => !member.privacy || member.privacy === "public"
|
||||
);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const distPaths = () => {
|
||||
const toDist = (value) => value.replace(/^src\/(.+)\.ts$/, "dist/$1.js");
|
||||
const rewrite = (node) => {
|
||||
if (Array.isArray(node)) {
|
||||
node.forEach(rewrite);
|
||||
return;
|
||||
}
|
||||
if (!node || typeof node !== "object") {
|
||||
return;
|
||||
}
|
||||
for (const [key, value] of Object.entries(node)) {
|
||||
if ((key === "path" || key === "module") && typeof value === "string") {
|
||||
node[key] = toDist(value);
|
||||
} else {
|
||||
rewrite(value);
|
||||
}
|
||||
}
|
||||
};
|
||||
return {
|
||||
name: "dist-paths",
|
||||
packageLinkPhase({ customElementsManifest }) {
|
||||
rewrite(customElementsManifest.modules);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export default {
|
||||
globs: ["src/components/**/hac-*.ts"],
|
||||
outdir: "dist",
|
||||
litelement: true,
|
||||
plugins: [
|
||||
packageReadme(),
|
||||
summaryAsDescription(),
|
||||
publicApiOnly(),
|
||||
distPaths(),
|
||||
],
|
||||
};
|
||||
@@ -1,60 +0,0 @@
|
||||
{
|
||||
"name": "@home-assistant/components",
|
||||
"version": "0.0.0",
|
||||
"description": "Home Assistant web components (hac-* elements) built with Lit",
|
||||
"license": "Apache-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/home-assistant/frontend.git",
|
||||
"directory": "packages/components"
|
||||
},
|
||||
"type": "module",
|
||||
"sideEffects": [
|
||||
"./dist/components/**/global.js",
|
||||
"./src/components/**/global.ts"
|
||||
],
|
||||
"customElements": "dist/custom-elements.json",
|
||||
"exports": {
|
||||
"./scoped": {
|
||||
"ha-source": "./src/scoped.ts",
|
||||
"types": "./dist/scoped.d.ts",
|
||||
"import": "./dist/scoped.js"
|
||||
},
|
||||
"./package.json": "./package.json",
|
||||
"./*/scoped": {
|
||||
"ha-source": "./src/components/*/scoped.ts",
|
||||
"types": "./dist/components/*/scoped.d.ts",
|
||||
"import": "./dist/components/*/scoped.js"
|
||||
},
|
||||
"./*/info": {
|
||||
"ha-source": "./src/components/*/info.ts",
|
||||
"types": "./dist/components/*/info.d.ts",
|
||||
"import": "./dist/components/*/info.js"
|
||||
},
|
||||
"./*": {
|
||||
"ha-source": "./src/components/*/global.ts",
|
||||
"types": "./dist/components/*/global.d.ts",
|
||||
"import": "./dist/components/*/global.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rslib build && cem analyze",
|
||||
"dev": "rslib build --watch",
|
||||
"prepublishOnly": "pnpm run build"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"lit": "^3.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@custom-elements-manifest/analyzer": "0.11.0",
|
||||
"@rslib/core": "1.0.7",
|
||||
"lit": "3.3.3",
|
||||
"typescript": "6.0.3"
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
import { defineConfig } from "@rslib/core";
|
||||
|
||||
// Bundleless build: every source file becomes its own ESM file, so consumers'
|
||||
// bundlers only include the entry points they import. Only global.ts files
|
||||
// register elements; everything else is free of side effects.
|
||||
export default defineConfig({
|
||||
source: {
|
||||
entry: { index: ["./src/**/*.ts"] },
|
||||
decorators: { version: "legacy" },
|
||||
tsconfigPath: "./tsconfig.json",
|
||||
},
|
||||
tools: {
|
||||
swc: { jsc: { transform: { decoratorMetadata: false } } },
|
||||
},
|
||||
lib: [
|
||||
{
|
||||
format: "esm",
|
||||
bundle: false,
|
||||
syntax: "es2021",
|
||||
dts: true,
|
||||
output: { target: "web", distPath: { root: "./dist" } },
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
import { define } from "../../utils/registration/define";
|
||||
import { HacCard } from "./hac-card";
|
||||
import { TAG_NAME } from "./info";
|
||||
|
||||
// Registers <hac-card> in the global registry, as used by Home Assistant
|
||||
define(TAG_NAME, HacCard);
|
||||
|
||||
export { HacCard };
|
||||
@@ -1,165 +0,0 @@
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { property, state } from "lit/decorators.js";
|
||||
import {
|
||||
hasAssignedContent,
|
||||
hasAssignedElements,
|
||||
} from "../../utils/element/slot";
|
||||
|
||||
/**
|
||||
* @element hac-card
|
||||
*
|
||||
* @summary
|
||||
* Card that groups related content, with an optional header and footer.
|
||||
*
|
||||
* @slot header - Header of the card. Its spacing replaces the top padding of
|
||||
* the content.
|
||||
* @slot - Content of the card. Its padding is omitted when empty.
|
||||
* @slot footer - Footer of the card. Hidden when empty.
|
||||
*
|
||||
* @csspart header - Wrapper of the header slot.
|
||||
* @csspart content - Wrapper of the default slot.
|
||||
* @csspart footer - Wrapper of the footer slot.
|
||||
*
|
||||
* @cssprop --hac-card-background - Background of the card.
|
||||
* @cssprop --hac-card-color - Text color of the card.
|
||||
* @cssprop --hac-card-border-color - Border color of the card and the footer divider.
|
||||
* @cssprop --hac-card-border-width - Border width of the card.
|
||||
* @cssprop --hac-card-border-radius - Border radius of the card.
|
||||
* @cssprop --hac-card-box-shadow - Box shadow of the card.
|
||||
* @cssprop --hac-card-content-padding - Padding of the content.
|
||||
* @cssprop --hac-card-footer-padding - Padding of the footer.
|
||||
*/
|
||||
export class HacCard extends LitElement {
|
||||
/**
|
||||
* Visual style of the card. `outlined` draws a border without a shadow.
|
||||
* `raised` hides the border and lifts the card with a shadow instead.
|
||||
*/
|
||||
@property({ reflect: true }) public appearance: "outlined" | "raised" =
|
||||
"outlined";
|
||||
|
||||
@state() private _hasHeader = false;
|
||||
|
||||
@state() private _hasFooter = false;
|
||||
|
||||
@state() private _hasContent = false;
|
||||
|
||||
protected render() {
|
||||
return html`
|
||||
<div class="header" part="header" ?hidden=${!this._hasHeader}>
|
||||
<slot name="header" @slotchange=${this._headerChanged}></slot>
|
||||
</div>
|
||||
<div
|
||||
class="content ${this._hasHeader ? "below-header" : ""}"
|
||||
part="content"
|
||||
?hidden=${!this._hasContent}
|
||||
>
|
||||
<slot @slotchange=${this._contentChanged}></slot>
|
||||
</div>
|
||||
<div class="footer" part="footer" ?hidden=${!this._hasFooter}>
|
||||
<slot name="footer" @slotchange=${this._footerChanged}></slot>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
private _headerChanged(ev: Event) {
|
||||
this._hasHeader = hasAssignedElements(ev);
|
||||
}
|
||||
|
||||
private _contentChanged(ev: Event) {
|
||||
this._hasContent = hasAssignedContent(ev);
|
||||
}
|
||||
|
||||
private _footerChanged(ev: Event) {
|
||||
this._hasFooter = hasAssignedElements(ev);
|
||||
}
|
||||
|
||||
/*
|
||||
* Fallback order: --hac-card-*, then the theme variables of ha-card
|
||||
* (--ha-card-*, --card-background-color, --divider-color,
|
||||
* --primary-text-color) so existing themes keep working, then the semantic
|
||||
* tokens and their light values for use outside Home Assistant.
|
||||
* The ha-card variables are temporary, see "Theming" in the README.
|
||||
*/
|
||||
static styles = css`
|
||||
:host {
|
||||
display: block;
|
||||
position: relative;
|
||||
box-sizing: border-box;
|
||||
background: var(
|
||||
--hac-card-background,
|
||||
var(
|
||||
--ha-card-background,
|
||||
var(--card-background-color, var(--ha-color-surface-default, #fff))
|
||||
)
|
||||
);
|
||||
backdrop-filter: var(--ha-card-backdrop-filter, none);
|
||||
color: var(
|
||||
--hac-card-color,
|
||||
var(--primary-text-color, var(--ha-color-on-surface-default, #141414))
|
||||
);
|
||||
border: var(--hac-card-border-width, var(--ha-card-border-width, 1px))
|
||||
solid
|
||||
var(
|
||||
--hac-card-border-color,
|
||||
var(
|
||||
--ha-card-border-color,
|
||||
var(--divider-color, var(--ha-color-border-neutral-quiet, #e6e6e6))
|
||||
)
|
||||
);
|
||||
border-radius: var(
|
||||
--hac-card-border-radius,
|
||||
var(--ha-card-border-radius, var(--ha-border-radius-lg, 12px))
|
||||
);
|
||||
box-shadow: var(--hac-card-box-shadow, var(--ha-card-box-shadow, none));
|
||||
}
|
||||
|
||||
:host([appearance="raised"]) {
|
||||
border-color: transparent;
|
||||
box-shadow: var(
|
||||
--hac-card-box-shadow,
|
||||
var(
|
||||
--ha-card-box-shadow,
|
||||
var(
|
||||
--ha-box-shadow-s,
|
||||
0 1px 2px 0 rgba(0, 0, 0, 0.08),
|
||||
0 1px 3px 0 rgba(0, 0, 0, 0.12)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
.content {
|
||||
padding: var(--hac-card-content-padding, var(--ha-space-4, 16px));
|
||||
}
|
||||
|
||||
/* The header already provides the spacing above the content */
|
||||
.content.below-header {
|
||||
padding-block-start: 0;
|
||||
}
|
||||
|
||||
.footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--ha-space-2, 8px);
|
||||
padding: var(--hac-card-footer-padding, var(--ha-space-2, 8px));
|
||||
border-block-start: 1px solid
|
||||
var(
|
||||
--hac-card-border-color,
|
||||
var(--divider-color, var(--ha-color-border-neutral-quiet, #e6e6e6))
|
||||
);
|
||||
}
|
||||
|
||||
.header[hidden],
|
||||
.content[hidden],
|
||||
.footer[hidden] {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"hac-card": HacCard;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
/** Tag name of the element. */
|
||||
export const TAG_NAME = "hac-card";
|
||||
|
||||
/** Version of <hac-card>. */
|
||||
export const VERSION = "0.1.0";
|
||||
@@ -1,15 +0,0 @@
|
||||
import type { ElementDefinition } from "../../utils/registration/definition";
|
||||
import { HacCard } from "./hac-card";
|
||||
import { TAG_NAME } from "./info";
|
||||
|
||||
export { HacCard };
|
||||
|
||||
/**
|
||||
* The bundled <hac-card> for a scoped registry:
|
||||
* `ScopedElementsMixin(LitElement, [hacCard])` or
|
||||
* `createScopedElementRegistry([hacCard])`.
|
||||
*/
|
||||
export const hacCard: ElementDefinition<typeof HacCard> = {
|
||||
tagName: TAG_NAME,
|
||||
element: HacCard,
|
||||
};
|
||||
@@ -1,132 +0,0 @@
|
||||
import type { LitElement } from "lit";
|
||||
import { define } from "./utils/registration/define";
|
||||
import type { ElementDefinition } from "./utils/registration/definition";
|
||||
import {
|
||||
createScopedRegistry,
|
||||
scopedCreationScope,
|
||||
scopedRegistrySupport,
|
||||
scopedShadowRootInit,
|
||||
} from "./utils/registration/scoped-registry";
|
||||
|
||||
export type { ElementDefinition } from "./utils/registration/definition";
|
||||
|
||||
/**
|
||||
* Creates a registry with the given elements, for `attachScopedShadow`:
|
||||
* definitions from `scoped` entry points, e.g. `[hacCard]`.
|
||||
* Create it once, outside the class, so all instances of a card share it.
|
||||
*
|
||||
* Without scoped registry support (native or polyfill), the elements are
|
||||
* registered in the global registry instead, unless their tag name is already
|
||||
* taken there, and the global registry is returned.
|
||||
*/
|
||||
export const createScopedElementRegistry = (
|
||||
elements: readonly ElementDefinition[]
|
||||
): CustomElementRegistry => {
|
||||
// Checked as unknown: Array.isArray would narrow the list to any[]
|
||||
if (!Array.isArray(elements as unknown)) {
|
||||
throw new TypeError(
|
||||
"@home-assistant/components: pass the elements to register, e.g. [hacCard]"
|
||||
);
|
||||
}
|
||||
const registry = createScopedRegistry() ?? customElements;
|
||||
for (const { tagName, element } of elements) {
|
||||
define(tagName, element, registry);
|
||||
}
|
||||
return registry;
|
||||
};
|
||||
|
||||
const shadowRootInit = (
|
||||
init: ShadowRootInit,
|
||||
registry: CustomElementRegistry
|
||||
): ShadowRootInit =>
|
||||
registry === customElements ? init : scopedShadowRootInit(init, registry);
|
||||
|
||||
const registries = new WeakMap<ShadowRoot, CustomElementRegistry>();
|
||||
|
||||
/**
|
||||
* Attaches a shadow root that uses `registry` for custom elements in it.
|
||||
*
|
||||
* Content added with `innerHTML` or `insertAdjacentHTML` uses the registry.
|
||||
* Create single elements with `createScopedElement`; `document.createElement`
|
||||
* would use the global registry.
|
||||
*
|
||||
* Light DOM content, like slotted elements, keeps using the registry of the
|
||||
* tree it is written in.
|
||||
*/
|
||||
export const attachScopedShadow = (
|
||||
host: HTMLElement,
|
||||
init: ShadowRootInit,
|
||||
registry: CustomElementRegistry
|
||||
): ShadowRoot => {
|
||||
const root = host.attachShadow(shadowRootInit(init, registry));
|
||||
registries.set(root, registry);
|
||||
return root;
|
||||
};
|
||||
|
||||
/** Creates an element from the registry of a shadow root. */
|
||||
export const createScopedElement = <K extends keyof HTMLElementTagNameMap>(
|
||||
root: ShadowRoot,
|
||||
tagName: K
|
||||
): HTMLElementTagNameMap[K] => {
|
||||
const registry = registries.get(root);
|
||||
if (!registry || registry === customElements) {
|
||||
return document.createElement(tagName);
|
||||
}
|
||||
if (scopedRegistrySupport() === "polyfill") {
|
||||
// The polyfill adds createElement to shadow roots
|
||||
return (
|
||||
root as unknown as {
|
||||
createElement(tagName: K): HTMLElementTagNameMap[K];
|
||||
}
|
||||
).createElement(tagName);
|
||||
}
|
||||
return (
|
||||
document.createElement as (
|
||||
tagName: K,
|
||||
options: { customElementRegistry: CustomElementRegistry }
|
||||
) => HTMLElementTagNameMap[K]
|
||||
)(tagName, { customElementRegistry: registry });
|
||||
};
|
||||
|
||||
type LitElementConstructor = abstract new (...args: any[]) => LitElement;
|
||||
|
||||
/**
|
||||
* Renders a Lit element into a shadow root with its own custom element
|
||||
* registry, containing `elements`:
|
||||
*
|
||||
* ```ts
|
||||
* class MyCard extends ScopedElementsMixin(LitElement, [hacCard]) {}
|
||||
* ```
|
||||
*
|
||||
* See `createScopedElementRegistry` and `attachScopedShadow` for the details.
|
||||
*/
|
||||
export const ScopedElementsMixin = <T extends LitElementConstructor>(
|
||||
superClass: T,
|
||||
elements: readonly ElementDefinition[]
|
||||
) => {
|
||||
// Created on first use, so defining the class has no side effects
|
||||
let registry: CustomElementRegistry | undefined;
|
||||
const getRegistry = () => {
|
||||
registry ??= createScopedElementRegistry(elements);
|
||||
return registry;
|
||||
};
|
||||
|
||||
abstract class ScopedElementsHost extends superClass {
|
||||
public attachShadow(init: ShadowRootInit): ShadowRoot {
|
||||
const root = super.attachShadow(shadowRootInit(init, getRegistry()));
|
||||
registries.set(root, getRegistry());
|
||||
return root;
|
||||
}
|
||||
|
||||
protected createRenderRoot() {
|
||||
const root = super.createRenderRoot();
|
||||
const scoped = getRegistry();
|
||||
if (scoped !== customElements && root instanceof ShadowRoot) {
|
||||
this.renderOptions.creationScope = scopedCreationScope(root, scoped);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
}
|
||||
// Typed as the base class: the overrides add no public API
|
||||
return ScopedElementsHost as unknown as T;
|
||||
};
|
||||
@@ -1,15 +0,0 @@
|
||||
/** Whether the slot of a `slotchange` event has elements assigned. */
|
||||
export const hasAssignedElements = (ev: Event): boolean =>
|
||||
(ev.target as HTMLSlotElement).assignedElements().length > 0;
|
||||
|
||||
/**
|
||||
* Whether the slot of a `slotchange` event has content assigned: elements or
|
||||
* text. Whitespace between tags is not content.
|
||||
*/
|
||||
export const hasAssignedContent = (ev: Event): boolean =>
|
||||
(ev.target as HTMLSlotElement)
|
||||
.assignedNodes()
|
||||
.some(
|
||||
(node) =>
|
||||
node.nodeType === Node.ELEMENT_NODE || Boolean(node.textContent?.trim())
|
||||
);
|
||||
@@ -1,17 +0,0 @@
|
||||
/**
|
||||
* Registers a custom element unless the tag name is already taken in the
|
||||
* registry.
|
||||
*
|
||||
* Home Assistant and custom cards can each ship a copy of this library, so
|
||||
* registering the same tag name twice must not throw. The first registration
|
||||
* wins.
|
||||
*/
|
||||
export const define = (
|
||||
tagName: string,
|
||||
elementClass: CustomElementConstructor,
|
||||
registry: CustomElementRegistry = customElements
|
||||
): void => {
|
||||
if (!registry.get(tagName)) {
|
||||
registry.define(tagName, elementClass);
|
||||
}
|
||||
};
|
||||
@@ -1,10 +0,0 @@
|
||||
/**
|
||||
* An element to register: its tag name and its class. The `scoped` entry
|
||||
* point of an element exports one, e.g. `hacCard`.
|
||||
*/
|
||||
export interface ElementDefinition<
|
||||
E extends CustomElementConstructor = CustomElementConstructor,
|
||||
> {
|
||||
readonly tagName: string;
|
||||
readonly element: E;
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/**
|
||||
* Scoped custom element registries come in two flavors: the standard API
|
||||
* (Chrome 146+, Safari 26) and the older API of
|
||||
* `@webcomponents/scoped-custom-element-registry`, which Home Assistant loads
|
||||
* and which replaces the native implementation when present.
|
||||
*/
|
||||
export type ScopedRegistrySupport = "polyfill" | "native" | "none";
|
||||
|
||||
let support: ScopedRegistrySupport | undefined;
|
||||
|
||||
export const scopedRegistrySupport = (): ScopedRegistrySupport => {
|
||||
if (support) {
|
||||
return support;
|
||||
}
|
||||
if ("CustomElementRegistryPolyfill" in globalThis) {
|
||||
support = "polyfill";
|
||||
} else {
|
||||
try {
|
||||
new CustomElementRegistry();
|
||||
support = "native";
|
||||
} catch (_err) {
|
||||
support = "none";
|
||||
}
|
||||
}
|
||||
return support;
|
||||
};
|
||||
|
||||
/** A new scoped registry, or `undefined` if the browser has no support. */
|
||||
export const createScopedRegistry = (): CustomElementRegistry | undefined =>
|
||||
scopedRegistrySupport() === "none" ? undefined : new CustomElementRegistry();
|
||||
|
||||
/** Shadow root options that make the shadow root use `registry`. */
|
||||
export const scopedShadowRootInit = (
|
||||
init: ShadowRootInit,
|
||||
registry: CustomElementRegistry
|
||||
): ShadowRootInit =>
|
||||
scopedRegistrySupport() === "polyfill"
|
||||
? ({ ...init, registry } as ShadowRootInit)
|
||||
: ({ ...init, customElementRegistry: registry } as ShadowRootInit);
|
||||
|
||||
interface CreationScope {
|
||||
importNode(node: Node, deep?: boolean): Node;
|
||||
}
|
||||
|
||||
/**
|
||||
* The object Lit should create template content with, so custom elements in
|
||||
* it are created from the scoped registry (Lit's `creationScope`).
|
||||
*/
|
||||
export const scopedCreationScope = (
|
||||
root: ShadowRoot,
|
||||
registry: CustomElementRegistry
|
||||
): CreationScope => {
|
||||
if (scopedRegistrySupport() === "polyfill") {
|
||||
// The polyfill adds importNode to shadow roots
|
||||
return root as unknown as CreationScope;
|
||||
}
|
||||
// Standard API: the registry is passed to importNode
|
||||
return {
|
||||
importNode: (node, deep) =>
|
||||
(
|
||||
document.importNode as (
|
||||
node: Node,
|
||||
options: { selfOnly: boolean; customElementRegistry: unknown }
|
||||
) => Node
|
||||
)(node, { selfOnly: !deep, customElementRegistry: registry }),
|
||||
};
|
||||
};
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { define } from "../src/utils/registration/define";
|
||||
|
||||
// Home Assistant and custom cards can each ship a copy of the library, so a
|
||||
// second registration of the same tag must be ignored instead of throwing.
|
||||
describe("define", () => {
|
||||
it("registers an element that is not registered yet", () => {
|
||||
class First extends HTMLElement {}
|
||||
define("hac-test-first", First);
|
||||
expect(customElements.get("hac-test-first")).toBe(First);
|
||||
});
|
||||
|
||||
it("keeps the first registration of a tag name", () => {
|
||||
class Original extends HTMLElement {}
|
||||
class Duplicate extends HTMLElement {}
|
||||
define("hac-test-duplicate", Original);
|
||||
expect(() => define("hac-test-duplicate", Duplicate)).not.toThrow();
|
||||
expect(customElements.get("hac-test-duplicate")).toBe(Original);
|
||||
});
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
hasAssignedContent,
|
||||
hasAssignedElements,
|
||||
} from "../src/utils/element/slot";
|
||||
|
||||
// Components hide wrappers of empty slots, e.g. the padding of an empty card.
|
||||
// Whitespace between tags must not count as content.
|
||||
const slotEvent = (light: string, name?: string) => {
|
||||
const host = document.createElement("div");
|
||||
host.innerHTML = light;
|
||||
const slot = document.createElement("slot");
|
||||
if (name) {
|
||||
slot.name = name;
|
||||
}
|
||||
host.attachShadow({ mode: "open" }).append(slot);
|
||||
return { target: slot } as unknown as Event;
|
||||
};
|
||||
|
||||
describe("hasAssignedContent", () => {
|
||||
it("ignores whitespace", () => {
|
||||
expect(hasAssignedContent(slotEvent("\n \n"))).toBe(false);
|
||||
});
|
||||
|
||||
it("counts text", () => {
|
||||
expect(hasAssignedContent(slotEvent(" Hello "))).toBe(true);
|
||||
});
|
||||
|
||||
it("counts elements", () => {
|
||||
expect(hasAssignedContent(slotEvent("\n <p></p>\n"))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasAssignedElements", () => {
|
||||
it("only counts elements assigned to the slot", () => {
|
||||
const light = '<span slot="icon"></span> text';
|
||||
expect(hasAssignedElements(slotEvent(light, "icon"))).toBe(true);
|
||||
expect(hasAssignedElements(slotEvent(light, "actions"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"lib": ["ES2021", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noImplicitReturns": true,
|
||||
"isolatedModules": true,
|
||||
"skipLibCheck": true,
|
||||
"declaration": true,
|
||||
"rootDir": "src",
|
||||
"outDir": "dist"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
diff --git a/mwc-list-base.js b/mwc-list-base.js
|
||||
index 1ba95b6a01dcecea4d85b5cbbbcc3dfb04c40d5f..dced13fdb7929c490d6661b1bbe7e9f96dcd2285 100644
|
||||
--- a/mwc-list-base.js
|
||||
+++ b/mwc-list-base.js
|
||||
@@ -11,7 +11,7 @@ import { BaseElement } from '@material/mwc-base/base-element.js';
|
||||
import { observer } from '@material/mwc-base/observer.js';
|
||||
import { deepActiveElementPath, doesElementContainFocus, isNodeElement } from '@material/mwc-base/utils.js';
|
||||
import { html } from 'lit';
|
||||
-import { property, query, queryAssignedNodes } from 'lit/decorators.js';
|
||||
+import { property, query, queryAssignedElements } from 'lit/decorators.js';
|
||||
import { ifDefined } from 'lit/directives/if-defined.js';
|
||||
import MDCListFoundation, { isIndexSet } from './mwc-list-foundation.js';
|
||||
export { createSetFromIndex, isEventMulti, isIndexSet } from './mwc-list-foundation.js';
|
||||
@@ -425,10 +425,10 @@ __decorate([
|
||||
query('.mdc-deprecated-list')
|
||||
], ListBase.prototype, "mdcRoot", void 0);
|
||||
__decorate([
|
||||
- queryAssignedNodes('', true, '*')
|
||||
+ queryAssignedElements({ flatten: true, selector: "*" })
|
||||
], ListBase.prototype, "assignedElements", void 0);
|
||||
__decorate([
|
||||
- queryAssignedNodes('', true, '[tabindex="0"]')
|
||||
+ queryAssignedElements({ flatten: true, selector: '[tabindex="0"]' })
|
||||
], ListBase.prototype, "tabbableElements", void 0);
|
||||
__decorate([
|
||||
property({ type: Boolean }),
|
||||
Generated
+1514
-1966
File diff suppressed because it is too large.
Load diff
+1
-5
@@ -1,7 +1,3 @@
|
||||
packages:
|
||||
- "."
|
||||
- "packages/*"
|
||||
|
||||
savePrefix: ""
|
||||
autoInstallPeers: false
|
||||
|
||||
@@ -23,7 +19,6 @@ trustPolicyExclude:
|
||||
allowBuilds:
|
||||
"@tsparticles/engine": false
|
||||
core-js: false
|
||||
rs-module-lexer: false
|
||||
unrs-resolver: false
|
||||
|
||||
overrides:
|
||||
@@ -34,6 +29,7 @@ overrides:
|
||||
tslib: 2.9.1
|
||||
|
||||
patchedDependencies:
|
||||
"@material/[email protected]": patches/@[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
[email protected]: patches/[email protected]
|
||||
|
||||
@@ -89,11 +89,6 @@
|
||||
}
|
||||
],
|
||||
"packageRules": [
|
||||
{
|
||||
"description": "Keep semver ranges for peer dependencies of published packages, pinning them would force consumers onto one exact version",
|
||||
"matchDepTypes": ["peerDependencies"],
|
||||
"rangeStrategy": "widen"
|
||||
},
|
||||
{
|
||||
"description": "Group all Python version updates from home-assistant/core",
|
||||
"matchDepNames": ["python"],
|
||||
|
||||
@@ -3,12 +3,6 @@ import { ref } from "lit/directives/ref";
|
||||
|
||||
const MAX_ROWS = 2;
|
||||
|
||||
// A narrow list, as on a phone or a half width card, fits about one item per
|
||||
// row, so two rows hide most of the legend. 450px is about the widest list a
|
||||
// phone viewport gives.
|
||||
const NARROW_MAX_ROWS = 3;
|
||||
const NARROW_WIDTH = 450;
|
||||
|
||||
// How many items fit in maxRows of a wrapping row, leaving room for the
|
||||
// "more" item after them when not all of them fit.
|
||||
export const fitInRows = (
|
||||
@@ -40,10 +34,9 @@ export const fitInRows = (
|
||||
return widths.length;
|
||||
};
|
||||
|
||||
// Fits the items of a wrapping legend list into two rows, three when it is
|
||||
// narrow. The list keeps its "more" item rendered with the legend-more class,
|
||||
// and items past the fit stay rendered out of the flow, so both can always be
|
||||
// measured.
|
||||
// Fits the items of a wrapping legend list into two rows. The list keeps its
|
||||
// "more" item rendered with the legend-more class, and items past the fit
|
||||
// stay rendered out of the flow, so both can always be measured.
|
||||
export class LegendFitController {
|
||||
// Items to show while collapsed, undefined until the list is measured
|
||||
public fit?: number;
|
||||
@@ -89,19 +82,10 @@ export class LegendFitController {
|
||||
|
||||
private _fit() {
|
||||
const list = this._element;
|
||||
if (!list) {
|
||||
const rowWidth = list?.getBoundingClientRect().width;
|
||||
if (!list || !rowWidth) {
|
||||
return;
|
||||
}
|
||||
const style = getComputedStyle(list);
|
||||
const rowWidth = parseFloat(style.width);
|
||||
// Bounding rects include transforms, such as a dialog scaling in, which
|
||||
// never resize the list, so measure in layout pixels
|
||||
const scale = list.getBoundingClientRect().width / rowWidth;
|
||||
if (!rowWidth || !scale) {
|
||||
return;
|
||||
}
|
||||
const layoutWidth = (element: Element) =>
|
||||
element.getBoundingClientRect().width / scale;
|
||||
const children = Array.from(list.children);
|
||||
const more = children.find((child) =>
|
||||
child.classList.contains("legend-more")
|
||||
@@ -116,7 +100,9 @@ export class LegendFitController {
|
||||
}
|
||||
this._more = more;
|
||||
}
|
||||
const widths = children.filter((child) => child !== more).map(layoutWidth);
|
||||
const widths = children
|
||||
.filter((child) => child !== more)
|
||||
.map((child) => child.getBoundingClientRect().width);
|
||||
// Values resize the items on every state update. Fitting each item at its
|
||||
// widest since the last resize keeps the more button from flickering.
|
||||
if (rowWidth !== this._rowWidth || widths.length !== this._widths.length) {
|
||||
@@ -129,10 +115,10 @@ export class LegendFitController {
|
||||
}
|
||||
const fit = fitInRows(
|
||||
this._widths,
|
||||
more ? layoutWidth(more) : 0,
|
||||
more?.getBoundingClientRect().width ?? 0,
|
||||
rowWidth,
|
||||
parseFloat(style.columnGap) || 0,
|
||||
rowWidth < NARROW_WIDTH ? NARROW_MAX_ROWS : MAX_ROWS
|
||||
parseFloat(getComputedStyle(list).columnGap) || 0,
|
||||
MAX_ROWS
|
||||
);
|
||||
if (fit !== this.fit) {
|
||||
this.fit = fit;
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
const INTERACTIVE_SELECTOR = [
|
||||
"a[href]",
|
||||
"button",
|
||||
"input",
|
||||
"select",
|
||||
"textarea",
|
||||
"summary",
|
||||
"label",
|
||||
"[contenteditable]:not([contenteditable='false'])",
|
||||
"[tabindex]:not([tabindex='-1'])",
|
||||
"[role='button']",
|
||||
"[role='link']",
|
||||
"[role='checkbox']",
|
||||
"[role='radio']",
|
||||
"[role='switch']",
|
||||
"[role='slider']",
|
||||
"[role='tab']",
|
||||
"[role='menuitem']",
|
||||
"[role='option']",
|
||||
"[role='combobox']",
|
||||
"[role='textbox']",
|
||||
].join(",");
|
||||
|
||||
/**
|
||||
* Whether `node` is an element that handles clicks or keyboard input on its
|
||||
* own, such as a button, link, form control or a focusable widget.
|
||||
*/
|
||||
export const isInteractiveElement = (node: EventTarget): boolean =>
|
||||
node instanceof Element && node.matches(INTERACTIVE_SELECTOR);
|
||||
@@ -3,7 +3,6 @@ const SWIPE_LOCKED_COMPONENTS = new Set([
|
||||
"ha-slider",
|
||||
"ha-control-switch",
|
||||
"ha-control-circular-slider",
|
||||
"ha-state-control-cover",
|
||||
"ha-hs-color-picker",
|
||||
"ha-map",
|
||||
// Charts pan and pinch-zoom on touch
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import type { HassServices } from "home-assistant-js-websocket";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { getToggleAction } from "./get_toggle_action";
|
||||
|
||||
export const canToggleDomain = (services: HassServices, domain: string) => {
|
||||
const domainServices = services[domain];
|
||||
if (!domainServices) {
|
||||
export const canToggleDomain = (hass: HomeAssistant, domain: string) => {
|
||||
const services = hass.services[domain];
|
||||
if (!services) {
|
||||
return false;
|
||||
}
|
||||
const actionOn = getToggleAction(domain, true);
|
||||
const actionOff = getToggleAction(domain, false);
|
||||
return actionOn in domainServices && actionOff in domainServices;
|
||||
return actionOn in services && actionOff in services;
|
||||
};
|
||||
@@ -1,30 +1,23 @@
|
||||
import type {
|
||||
HassEntities,
|
||||
HassEntity,
|
||||
HassServices,
|
||||
} from "home-assistant-js-websocket";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { canToggleDomain } from "./can_toggle_domain";
|
||||
import { computeStateDomain } from "./compute_state_domain";
|
||||
import { supportsFeature } from "./supports-feature";
|
||||
import { SPECIAL_TOGGLE_ACTIONS } from "./get_toggle_action";
|
||||
|
||||
export const canToggleState = (
|
||||
states: HassEntities,
|
||||
services: HassServices,
|
||||
stateObj: HassEntity
|
||||
) => {
|
||||
export const canToggleState = (hass: HomeAssistant, stateObj: HassEntity) => {
|
||||
const domain = computeStateDomain(stateObj);
|
||||
|
||||
if (domain === "group") {
|
||||
if (
|
||||
stateObj.attributes?.entity_id?.some((entity) => {
|
||||
const entityStateObj = states[entity];
|
||||
const entityStateObj = hass.states[entity];
|
||||
if (!entityStateObj) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const entityDomain = computeStateDomain(entityStateObj);
|
||||
return canToggleDomain(services, entityDomain);
|
||||
return canToggleDomain(hass, entityDomain);
|
||||
})
|
||||
) {
|
||||
return stateObj.state === "on" || stateObj.state === "off";
|
||||
@@ -42,5 +35,5 @@ export const canToggleState = (
|
||||
);
|
||||
}
|
||||
|
||||
return canToggleDomain(services, domain);
|
||||
return canToggleDomain(hass, domain);
|
||||
};
|
||||
@@ -4,23 +4,16 @@ import {
|
||||
mdiArrowDown,
|
||||
mdiArrowExpandHorizontal,
|
||||
mdiArrowUp,
|
||||
mdiDoorClosed,
|
||||
mdiDoorOpen,
|
||||
mdiGate,
|
||||
mdiGateOpen,
|
||||
} from "@mdi/js";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
|
||||
export const computeOpenIcon = (stateObj: HassEntity): string => {
|
||||
switch (stateObj.attributes.device_class) {
|
||||
case "awning":
|
||||
case "door":
|
||||
return mdiDoorOpen;
|
||||
case "gate":
|
||||
return mdiGateOpen;
|
||||
case "curtain":
|
||||
return mdiArrowExpandHorizontal;
|
||||
case "awning":
|
||||
return mdiArrowDown;
|
||||
default:
|
||||
return mdiArrowUp;
|
||||
}
|
||||
@@ -28,14 +21,11 @@ export const computeOpenIcon = (stateObj: HassEntity): string => {
|
||||
|
||||
export const computeCloseIcon = (stateObj: HassEntity): string => {
|
||||
switch (stateObj.attributes.device_class) {
|
||||
case "awning":
|
||||
case "door":
|
||||
return mdiDoorClosed;
|
||||
case "gate":
|
||||
return mdiGate;
|
||||
case "curtain":
|
||||
return mdiArrowCollapseHorizontal;
|
||||
case "awning":
|
||||
return mdiArrowUp;
|
||||
default:
|
||||
return mdiArrowDown;
|
||||
}
|
||||
|
||||
@@ -163,21 +163,9 @@ export const findEntities = (
|
||||
return results;
|
||||
};
|
||||
|
||||
export const excludeEntities = (
|
||||
entityIds: string[],
|
||||
excludedEntityIds?: string[]
|
||||
): string[] => {
|
||||
if (!excludedEntityIds?.length) {
|
||||
return entityIds;
|
||||
}
|
||||
const excluded = new Set(excludedEntityIds);
|
||||
return entityIds.filter((entityId) => !excluded.has(entityId));
|
||||
};
|
||||
|
||||
export const findFilteredEntities = (
|
||||
sources: EntityFilterSources,
|
||||
filters: EntityFilter[],
|
||||
excludedEntityIds?: string[]
|
||||
filters: EntityFilter[]
|
||||
): string[] => {
|
||||
const filterFuncs = filters.map((filter) =>
|
||||
generateEntityFilter(
|
||||
@@ -189,8 +177,5 @@ export const findFilteredEntities = (
|
||||
filter
|
||||
)
|
||||
);
|
||||
return excludeEntities(
|
||||
findEntities(Object.keys(sources.states), filterFuncs),
|
||||
excludedEntityIds
|
||||
);
|
||||
return findEntities(Object.keys(sources.states), filterFuncs);
|
||||
};
|
||||
@@ -1,18 +1,11 @@
|
||||
import type {
|
||||
HassEntities,
|
||||
HassEntity,
|
||||
HassServices,
|
||||
} from "home-assistant-js-websocket";
|
||||
import type { HassEntity } from "home-assistant-js-websocket";
|
||||
import { UNAVAILABLE } from "../../data/entity/entity";
|
||||
import type { HomeAssistant } from "../../types";
|
||||
import { DOMAINS_WITH_CARD } from "../const";
|
||||
import { canToggleState } from "./can_toggle_state";
|
||||
import { computeStateDomain } from "./compute_state_domain";
|
||||
|
||||
export const stateCardType = (
|
||||
states: HassEntities,
|
||||
services: HassServices,
|
||||
stateObj: HassEntity
|
||||
) => {
|
||||
export const stateCardType = (hass: HomeAssistant, stateObj: HassEntity) => {
|
||||
if (stateObj.state === UNAVAILABLE) {
|
||||
return "display";
|
||||
}
|
||||
@@ -23,7 +16,7 @@ export const stateCardType = (
|
||||
return domain;
|
||||
}
|
||||
if (
|
||||
canToggleState(states, services, stateObj) &&
|
||||
canToggleState(hass, stateObj) &&
|
||||
stateObj.attributes.control !== "hidden"
|
||||
) {
|
||||
return "toggle";
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { LocalizeFunc } from "./localize";
|
||||
|
||||
const YAML_ERROR_REASON_KEYS = new Map(
|
||||
Object.entries({
|
||||
"duplicated mapping key": "duplicated_mapping_key",
|
||||
"bad indentation of a mapping entry": "bad_mapping_indentation",
|
||||
"bad indentation of a sequence entry": "bad_sequence_indentation",
|
||||
"deficient indentation": "deficient_indentation",
|
||||
"tab characters must not be used in indentation": "tab_indentation",
|
||||
"can not read a block mapping entry; a multiline key may not be an implicit key":
|
||||
"multiline_implicit_key",
|
||||
"a whitespace character is expected after the key-value separator within a block mapping":
|
||||
"missing_key_value_space",
|
||||
"expected ':' after a mapping key": "missing_colon",
|
||||
"missed comma between flow collection entries": "missing_comma",
|
||||
"unexpected end of the stream within a flow collection":
|
||||
"unterminated_flow_collection",
|
||||
"unexpected end of the stream within a single quoted scalar":
|
||||
"unterminated_single_quote",
|
||||
"unexpected end of the stream within a double quoted scalar":
|
||||
"unterminated_double_quote",
|
||||
"end of the stream or a document separator is expected":
|
||||
"unexpected_content",
|
||||
} as const)
|
||||
);
|
||||
|
||||
export const localizeYamlErrorReason = (
|
||||
localize: LocalizeFunc,
|
||||
reason: string | undefined
|
||||
): string | undefined => {
|
||||
const key = reason ? YAML_ERROR_REASON_KEYS.get(reason) : undefined;
|
||||
return key ? localize(`ui.components.yaml-editor.reasons.${key}`) : reason;
|
||||
};
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DataTableFilter,
|
||||
DataTableFilters,
|
||||
FloorAreasFilterValue,
|
||||
} from "../../data/data_table_filters";
|
||||
import { dataTableQueryParamConfig } from "./data-table-query-params";
|
||||
import {
|
||||
@@ -26,7 +25,6 @@ export const automationsFilterQueryParamConfig = {
|
||||
"assistants",
|
||||
"blueprint",
|
||||
],
|
||||
boolean: [{ key: "no_area", trueValue: "1" }],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type AutomationsFilterQueryParams = QueryParamValues<
|
||||
@@ -38,7 +36,7 @@ const list = (filter: DataTableFilter | undefined): string[] | undefined =>
|
||||
|
||||
const floorAreas = (
|
||||
filter: DataTableFilter | undefined
|
||||
): FloorAreasFilterValue | undefined =>
|
||||
): Record<string, string[]> | undefined =>
|
||||
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
|
||||
|
||||
export const automationsFilterQueryParams = (
|
||||
@@ -46,7 +44,6 @@ export const automationsFilterQueryParams = (
|
||||
): AutomationsFilterQueryParams => ({
|
||||
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
|
||||
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
|
||||
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
|
||||
device: list(filters["ha-filter-devices"]),
|
||||
entity: list(filters["ha-filter-entities"]),
|
||||
label: list(filters["ha-filter-labels"]),
|
||||
@@ -62,7 +59,7 @@ export const automationsFilterQueryString = (
|
||||
filters: DataTableFilters
|
||||
): string => {
|
||||
const params = automationsFilterQueryParams(filters);
|
||||
const sorted: AutomationsFilterQueryParams = { ...params };
|
||||
const sorted: AutomationsFilterQueryParams = {};
|
||||
|
||||
for (const key of automationsFilterQueryParamConfig.list) {
|
||||
sorted[key] = params[key] && [...params[key]].sort();
|
||||
@@ -97,9 +94,8 @@ export const automationsLinkFromUrl = (
|
||||
|
||||
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
|
||||
|
||||
const values = (
|
||||
key: (typeof automationsFilterQueryParamConfig.list)[number]
|
||||
): string[] => params[key]?.filter(Boolean) ?? [];
|
||||
const values = (key: keyof AutomationsFilterQueryParams): string[] =>
|
||||
params[key]?.filter(Boolean) ?? [];
|
||||
|
||||
const filter = (value: DataTableFilter["value"]): DataTableFilter => ({
|
||||
value,
|
||||
@@ -113,9 +109,7 @@ export const automationsLinkFromUrl = (
|
||||
search: search ?? "",
|
||||
filters: {
|
||||
"ha-filter-floor-areas": filter(
|
||||
floors.length || areas.length || params.no_area
|
||||
? { floors, areas, no_area: params.no_area }
|
||||
: undefined
|
||||
floors.length || areas.length ? { floors, areas } : undefined
|
||||
),
|
||||
"ha-filter-devices": filter(values("device")),
|
||||
"ha-filter-entities": filter(values("entity")),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DataTableFilter,
|
||||
DataTableFilters,
|
||||
FloorAreasFilterValue,
|
||||
} from "../../data/data_table_filters";
|
||||
import { dataTableQueryParamConfig } from "./data-table-query-params";
|
||||
import {
|
||||
@@ -25,7 +24,6 @@ export const devicesFilterQueryParamConfig = {
|
||||
"config_entry",
|
||||
"sub_entry",
|
||||
],
|
||||
boolean: [{ key: "no_area", trueValue: "1" }],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type DevicesFilterQueryParams = QueryParamValues<
|
||||
@@ -37,7 +35,7 @@ const list = (filter: DataTableFilter | undefined): string[] | undefined =>
|
||||
|
||||
const floorAreas = (
|
||||
filter: DataTableFilter | undefined
|
||||
): FloorAreasFilterValue | undefined =>
|
||||
): Record<string, string[]> | undefined =>
|
||||
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
|
||||
|
||||
export const devicesFilterQueryParams = (
|
||||
@@ -46,7 +44,6 @@ export const devicesFilterQueryParams = (
|
||||
status: list(filters["ha-filter-states"]),
|
||||
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
|
||||
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
|
||||
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
|
||||
domain: list(filters["ha-filter-integrations"]),
|
||||
label: list(filters["ha-filter-labels"]),
|
||||
config_entry: list(filters.config_entry),
|
||||
@@ -58,7 +55,7 @@ export const devicesFilterQueryParams = (
|
||||
// filter list sends back what it was given in its own order.
|
||||
export const devicesFilterQueryString = (filters: DataTableFilters): string => {
|
||||
const params = devicesFilterQueryParams(filters);
|
||||
const sorted: DevicesFilterQueryParams = { ...params };
|
||||
const sorted: DevicesFilterQueryParams = {};
|
||||
|
||||
for (const key of devicesFilterQueryParamConfig.list) {
|
||||
sorted[key] = params[key] && [...params[key]].sort();
|
||||
@@ -90,9 +87,8 @@ export const devicesLinkFromUrl = (
|
||||
|
||||
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
|
||||
|
||||
const values = (
|
||||
key: (typeof devicesFilterQueryParamConfig.list)[number]
|
||||
): string[] => params[key]?.filter(Boolean) ?? [];
|
||||
const values = (key: keyof DevicesFilterQueryParams): string[] =>
|
||||
params[key]?.filter(Boolean) ?? [];
|
||||
|
||||
const filter = (value: DataTableFilter["value"]): DataTableFilter => ({
|
||||
value,
|
||||
@@ -107,9 +103,7 @@ export const devicesLinkFromUrl = (
|
||||
filters: {
|
||||
"ha-filter-states": filter(values("status")),
|
||||
"ha-filter-floor-areas": filter(
|
||||
floors.length || areas.length || params.no_area
|
||||
? { floors, areas, no_area: params.no_area }
|
||||
: undefined
|
||||
floors.length || areas.length ? { floors, areas } : undefined
|
||||
),
|
||||
"ha-filter-integrations": filter(values("domain")),
|
||||
"ha-filter-labels": filter(values("label")),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DataTableFiltersValue,
|
||||
DataTableFiltersValues,
|
||||
FloorAreasFilterValue,
|
||||
} from "../../data/data_table_filters";
|
||||
import { dataTableQueryParamConfig } from "./data-table-query-params";
|
||||
import {
|
||||
@@ -31,7 +30,6 @@ export const entitiesFilterQueryParamConfig = {
|
||||
// Read until 2027.5, replaced with `assistants` on the next write
|
||||
"voice_assistant",
|
||||
],
|
||||
boolean: [{ key: "no_area", trueValue: "1" }],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type EntitiesFilterQueryParams = QueryParamValues<
|
||||
@@ -43,7 +41,7 @@ const list = (value: DataTableFiltersValue): string[] | undefined =>
|
||||
|
||||
const floorAreas = (
|
||||
value: DataTableFiltersValue
|
||||
): FloorAreasFilterValue | undefined =>
|
||||
): Record<string, string[]> | undefined =>
|
||||
value && !Array.isArray(value) ? value : undefined;
|
||||
|
||||
export const entitiesFilterQueryParams = (
|
||||
@@ -52,7 +50,6 @@ export const entitiesFilterQueryParams = (
|
||||
status: list(filters["ha-filter-states"]),
|
||||
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
|
||||
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
|
||||
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
|
||||
device: list(filters["ha-filter-devices"]),
|
||||
device_class: list(filters["ha-filter-device-classes"]),
|
||||
domain: list(filters["ha-filter-integrations"]),
|
||||
@@ -70,7 +67,7 @@ export const entitiesFilterQueryString = (
|
||||
filters: DataTableFiltersValues
|
||||
): string => {
|
||||
const params = entitiesFilterQueryParams(filters);
|
||||
const sorted: EntitiesFilterQueryParams = { ...params };
|
||||
const sorted: EntitiesFilterQueryParams = {};
|
||||
|
||||
for (const key of entitiesFilterQueryParamConfig.list) {
|
||||
sorted[key] = params[key] && [...params[key]].sort();
|
||||
@@ -105,9 +102,8 @@ export const entitiesLinkFromUrl = (
|
||||
|
||||
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
|
||||
|
||||
const values = (
|
||||
key: (typeof entitiesFilterQueryParamConfig.list)[number]
|
||||
): string[] => params[key]?.filter(Boolean) ?? [];
|
||||
const values = (key: keyof EntitiesFilterQueryParams): string[] =>
|
||||
params[key]?.filter(Boolean) ?? [];
|
||||
|
||||
const floors = values("floor");
|
||||
const areas = values("area");
|
||||
@@ -118,9 +114,7 @@ export const entitiesLinkFromUrl = (
|
||||
filters: {
|
||||
"ha-filter-states": values("status"),
|
||||
"ha-filter-floor-areas":
|
||||
floors.length || areas.length || params.no_area
|
||||
? { floors, areas, no_area: params.no_area }
|
||||
: undefined,
|
||||
floors.length || areas.length ? { floors, areas } : undefined,
|
||||
"ha-filter-devices": values("device"),
|
||||
"ha-filter-device-classes": values("device_class"),
|
||||
"ha-filter-integrations": values("domain"),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DataTableFiltersValue,
|
||||
DataTableFiltersValues,
|
||||
FloorAreasFilterValue,
|
||||
} from "../../data/data_table_filters";
|
||||
import { dataTableQueryParamConfig } from "./data-table-query-params";
|
||||
import {
|
||||
@@ -26,7 +25,6 @@ export const helpersFilterQueryParamConfig = {
|
||||
// Read until 2027.5, replaced with `assistants` on the next write
|
||||
"voice_assistant",
|
||||
],
|
||||
boolean: [{ key: "no_area", trueValue: "1" }],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type HelpersFilterQueryParams = QueryParamValues<
|
||||
@@ -38,7 +36,7 @@ const list = (value: DataTableFiltersValue): string[] | undefined =>
|
||||
|
||||
const floorAreas = (
|
||||
value: DataTableFiltersValue
|
||||
): FloorAreasFilterValue | undefined =>
|
||||
): Record<string, string[]> | undefined =>
|
||||
value && !Array.isArray(value) ? value : undefined;
|
||||
|
||||
export const helpersFilterQueryParams = (
|
||||
@@ -46,7 +44,6 @@ export const helpersFilterQueryParams = (
|
||||
): HelpersFilterQueryParams => ({
|
||||
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
|
||||
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
|
||||
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
|
||||
device: list(filters["ha-filter-devices"]),
|
||||
label: list(filters["ha-filter-labels"]),
|
||||
category: list(filters["ha-filter-categories"]),
|
||||
@@ -60,7 +57,7 @@ export const helpersFilterQueryString = (
|
||||
filters: DataTableFiltersValues
|
||||
): string => {
|
||||
const params = helpersFilterQueryParams(filters);
|
||||
const sorted: HelpersFilterQueryParams = { ...params };
|
||||
const sorted: HelpersFilterQueryParams = {};
|
||||
|
||||
for (const key of helpersFilterQueryParamConfig.list) {
|
||||
sorted[key] = params[key] && [...params[key]].sort();
|
||||
@@ -92,9 +89,8 @@ export const helpersLinkFromUrl = (
|
||||
|
||||
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
|
||||
|
||||
const values = (
|
||||
key: (typeof helpersFilterQueryParamConfig.list)[number]
|
||||
): string[] => params[key]?.filter(Boolean) ?? [];
|
||||
const values = (key: keyof HelpersFilterQueryParams): string[] =>
|
||||
params[key]?.filter(Boolean) ?? [];
|
||||
|
||||
const floors = values("floor");
|
||||
const areas = values("area");
|
||||
@@ -104,9 +100,7 @@ export const helpersLinkFromUrl = (
|
||||
search: search ?? "",
|
||||
filters: {
|
||||
"ha-filter-floor-areas":
|
||||
floors.length || areas.length || params.no_area
|
||||
? { floors, areas, no_area: params.no_area }
|
||||
: undefined,
|
||||
floors.length || areas.length ? { floors, areas } : undefined,
|
||||
"ha-filter-devices": values("device"),
|
||||
"ha-filter-labels": values("label"),
|
||||
"ha-filter-categories": values("category"),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DataTableFilter,
|
||||
DataTableFilters,
|
||||
FloorAreasFilterValue,
|
||||
} from "../../data/data_table_filters";
|
||||
import { dataTableQueryParamConfig } from "./data-table-query-params";
|
||||
import {
|
||||
@@ -25,7 +24,6 @@ export const scenesFilterQueryParamConfig = {
|
||||
"category",
|
||||
"assistants",
|
||||
],
|
||||
boolean: [{ key: "no_area", trueValue: "1" }],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type ScenesFilterQueryParams = QueryParamValues<
|
||||
@@ -37,7 +35,7 @@ const list = (filter: DataTableFilter | undefined): string[] | undefined =>
|
||||
|
||||
const floorAreas = (
|
||||
filter: DataTableFilter | undefined
|
||||
): FloorAreasFilterValue | undefined =>
|
||||
): Record<string, string[]> | undefined =>
|
||||
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
|
||||
|
||||
export const scenesFilterQueryParams = (
|
||||
@@ -45,7 +43,6 @@ export const scenesFilterQueryParams = (
|
||||
): ScenesFilterQueryParams => ({
|
||||
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
|
||||
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
|
||||
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
|
||||
device: list(filters["ha-filter-devices"]),
|
||||
entity: list(filters["ha-filter-entities"]),
|
||||
label: list(filters["ha-filter-labels"]),
|
||||
@@ -58,7 +55,7 @@ export const scenesFilterQueryParams = (
|
||||
// filter list sends back what it was given in its own order.
|
||||
export const scenesFilterQueryString = (filters: DataTableFilters): string => {
|
||||
const params = scenesFilterQueryParams(filters);
|
||||
const sorted: ScenesFilterQueryParams = { ...params };
|
||||
const sorted: ScenesFilterQueryParams = {};
|
||||
|
||||
for (const key of scenesFilterQueryParamConfig.list) {
|
||||
sorted[key] = params[key] && [...params[key]].sort();
|
||||
@@ -90,9 +87,8 @@ export const scenesLinkFromUrl = (
|
||||
|
||||
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
|
||||
|
||||
const values = (
|
||||
key: (typeof scenesFilterQueryParamConfig.list)[number]
|
||||
): string[] => params[key]?.filter(Boolean) ?? [];
|
||||
const values = (key: keyof ScenesFilterQueryParams): string[] =>
|
||||
params[key]?.filter(Boolean) ?? [];
|
||||
|
||||
const filter = (value: DataTableFilter["value"]): DataTableFilter => ({
|
||||
value,
|
||||
@@ -106,9 +102,7 @@ export const scenesLinkFromUrl = (
|
||||
search: search ?? "",
|
||||
filters: {
|
||||
"ha-filter-floor-areas": filter(
|
||||
floors.length || areas.length || params.no_area
|
||||
? { floors, areas, no_area: params.no_area }
|
||||
: undefined
|
||||
floors.length || areas.length ? { floors, areas } : undefined
|
||||
),
|
||||
"ha-filter-devices": filter(values("device")),
|
||||
"ha-filter-entities": filter(values("entity")),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type {
|
||||
DataTableFilter,
|
||||
DataTableFilters,
|
||||
FloorAreasFilterValue,
|
||||
} from "../../data/data_table_filters";
|
||||
import { dataTableQueryParamConfig } from "./data-table-query-params";
|
||||
import {
|
||||
@@ -26,7 +25,6 @@ export const scriptsFilterQueryParamConfig = {
|
||||
"assistants",
|
||||
"blueprint",
|
||||
],
|
||||
boolean: [{ key: "no_area", trueValue: "1" }],
|
||||
} as const satisfies QueryParamConfig;
|
||||
|
||||
export type ScriptsFilterQueryParams = QueryParamValues<
|
||||
@@ -38,7 +36,7 @@ const list = (filter: DataTableFilter | undefined): string[] | undefined =>
|
||||
|
||||
const floorAreas = (
|
||||
filter: DataTableFilter | undefined
|
||||
): FloorAreasFilterValue | undefined =>
|
||||
): Record<string, string[]> | undefined =>
|
||||
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
|
||||
|
||||
export const scriptsFilterQueryParams = (
|
||||
@@ -46,7 +44,6 @@ export const scriptsFilterQueryParams = (
|
||||
): ScriptsFilterQueryParams => ({
|
||||
floor: floorAreas(filters["ha-filter-floor-areas"])?.floors,
|
||||
area: floorAreas(filters["ha-filter-floor-areas"])?.areas,
|
||||
no_area: floorAreas(filters["ha-filter-floor-areas"])?.no_area,
|
||||
device: list(filters["ha-filter-devices"]),
|
||||
entity: list(filters["ha-filter-entities"]),
|
||||
label: list(filters["ha-filter-labels"]),
|
||||
@@ -60,7 +57,7 @@ export const scriptsFilterQueryParams = (
|
||||
// filter list sends back what it was given in its own order.
|
||||
export const scriptsFilterQueryString = (filters: DataTableFilters): string => {
|
||||
const params = scriptsFilterQueryParams(filters);
|
||||
const sorted: ScriptsFilterQueryParams = { ...params };
|
||||
const sorted: ScriptsFilterQueryParams = {};
|
||||
|
||||
for (const key of scriptsFilterQueryParamConfig.list) {
|
||||
sorted[key] = params[key] && [...params[key]].sort();
|
||||
@@ -92,9 +89,8 @@ export const scriptsLinkFromUrl = (
|
||||
|
||||
const { search } = decodeQueryParams(searchParams, dataTableQueryParamConfig);
|
||||
|
||||
const values = (
|
||||
key: (typeof scriptsFilterQueryParamConfig.list)[number]
|
||||
): string[] => params[key]?.filter(Boolean) ?? [];
|
||||
const values = (key: keyof ScriptsFilterQueryParams): string[] =>
|
||||
params[key]?.filter(Boolean) ?? [];
|
||||
|
||||
const filter = (value: DataTableFilter["value"]): DataTableFilter => ({
|
||||
value,
|
||||
@@ -108,9 +104,7 @@ export const scriptsLinkFromUrl = (
|
||||
search: search ?? "",
|
||||
filters: {
|
||||
"ha-filter-floor-areas": filter(
|
||||
floors.length || areas.length || params.no_area
|
||||
? { floors, areas, no_area: params.no_area }
|
||||
: undefined
|
||||
floors.length || areas.length ? { floors, areas } : undefined
|
||||
),
|
||||
"ha-filter-devices": filter(values("device")),
|
||||
"ha-filter-entities": filter(values("entity")),
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
/** Where a value is in a config, e.g. `["actions", 0, "then", 1]`. */
|
||||
export type ConfigPath = (string | number)[];
|
||||
|
||||
export const stringifyPath = (path: ConfigPath): string => path.join("/");
|
||||
|
||||
export const pathEquals = (a: ConfigPath, b: ConfigPath): boolean =>
|
||||
a.length === b.length && a.every((segment, index) => segment === b[index]);
|
||||
@@ -30,40 +30,10 @@ export class HaAutomationRow extends LitElement {
|
||||
@property({ type: Boolean, reflect: true })
|
||||
public dim = false;
|
||||
|
||||
/** Makes the row a link, with the icons slot outside of it */
|
||||
@property() public href?: string;
|
||||
|
||||
@query(".row")
|
||||
private _rowElement?: HTMLDivElement;
|
||||
|
||||
@query(".link")
|
||||
private _linkElement?: HTMLAnchorElement;
|
||||
|
||||
protected render(): TemplateResult {
|
||||
const content = html`
|
||||
<div class="leading-icon-wrapper">
|
||||
<slot name="leading-icon"></slot>
|
||||
</div>
|
||||
<div class="header">
|
||||
<slot name="header"></slot>
|
||||
<slot name="event"></slot>
|
||||
</div>
|
||||
`;
|
||||
const icons = html`
|
||||
<div class="icons">
|
||||
<slot name="icons"></slot>
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (this.href) {
|
||||
return html`
|
||||
<div class="row has-link">
|
||||
<a class="link" href=${this.href}>${content}</a>
|
||||
${icons}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
return html`
|
||||
<div
|
||||
class="row"
|
||||
@@ -83,7 +53,17 @@ export class HaAutomationRow extends LitElement {
|
||||
`
|
||||
: nothing
|
||||
}
|
||||
${content} ${icons}
|
||||
<div class="leading-icon-wrapper">
|
||||
<slot name="leading-icon"></slot>
|
||||
</div>
|
||||
<div class="header">
|
||||
<slot name="header"></slot>
|
||||
<slot name="event"></slot>
|
||||
</div>
|
||||
|
||||
<div class="icons">
|
||||
<slot name="icons"></slot>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
@@ -139,7 +119,7 @@ export class HaAutomationRow extends LitElement {
|
||||
|
||||
public focus() {
|
||||
requestAnimationFrame(() => {
|
||||
(this._linkElement ?? this._rowElement)?.focus();
|
||||
this._rowElement?.focus();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -164,30 +144,6 @@ export class HaAutomationRow extends LitElement {
|
||||
outline: var(--wa-focus-ring);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.row.has-link {
|
||||
padding-left: 0;
|
||||
padding-inline-start: 0;
|
||||
cursor: default;
|
||||
}
|
||||
.link {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
align-self: stretch;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding-left: var(--ha-space-3);
|
||||
padding-inline-start: var(--ha-space-3);
|
||||
padding-inline-end: initial;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
border-radius: inherit;
|
||||
}
|
||||
.link:focus-visible {
|
||||
outline: var(--wa-focus-ring);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.expand-button {
|
||||
transition: transform 150ms cubic-bezier(0.4, 0, 0.2, 1);
|
||||
color: var(--ha-color-on-neutral-quiet);
|
||||
|
||||
@@ -19,7 +19,6 @@ interface MinMaxFrame {
|
||||
maxPoint: Point;
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
lastX: number;
|
||||
gapPoint: Point | undefined;
|
||||
}
|
||||
|
||||
@@ -69,7 +68,6 @@ function newFrame(
|
||||
maxPoint: point,
|
||||
maxX: x,
|
||||
maxY: y,
|
||||
lastX: x,
|
||||
gapPoint,
|
||||
};
|
||||
}
|
||||
@@ -176,7 +174,6 @@ export function downSampleLineData<
|
||||
if (!frame) {
|
||||
frames.set(frameIndex, newFrame(point, x, y, undefined));
|
||||
} else if (frame.hasValue) {
|
||||
frame.lastX = x;
|
||||
// Match the original strict-less / strict-greater comparisons so the
|
||||
// first occurrence wins on ties.
|
||||
if (y < frame.minY) {
|
||||
@@ -192,7 +189,6 @@ export function downSampleLineData<
|
||||
} else {
|
||||
// the frame held nothing but a marker so far
|
||||
frame.hasValue = true;
|
||||
frame.lastX = x;
|
||||
frame.minPoint = point;
|
||||
frame.minX = x;
|
||||
frame.minY = y;
|
||||
@@ -217,8 +213,11 @@ export function downSampleLineData<
|
||||
if (frame.gapPoint !== undefined) {
|
||||
// A marker followed by a value in its own frame is a gap that closed
|
||||
// within one frame, which is about one device pixel: too narrow to show.
|
||||
// That value may be neither min nor max, so check the frame's last x.
|
||||
if (Number(getPointData(frame.gapPoint)[0]) >= frame.lastX) {
|
||||
// The kept points are exactly min and max, so comparing against the
|
||||
// later of the two catches that without any work on the ingest path. A
|
||||
// marker-only frame compares against its own x and always passes.
|
||||
const lastValueX = frame.minX > frame.maxX ? frame.minX : frame.maxX;
|
||||
if (Number(getPointData(frame.gapPoint)[0]) >= lastValueX) {
|
||||
result.push(frame.gapPoint as T);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,18 +76,6 @@ export interface NetworkData {
|
||||
|
||||
const PHYSICS_DISABLE_THRESHOLD = 512;
|
||||
|
||||
const LAYOUT_ANIMATION_THRESHOLD = 100;
|
||||
|
||||
// Every event of a change of the legend selection, each with the whole
|
||||
// selection
|
||||
const LEGEND_SELECT_EVENTS = [
|
||||
"legendselectchanged",
|
||||
"legendselected",
|
||||
"legendunselected",
|
||||
"legendselectall",
|
||||
"legendinverseselect",
|
||||
];
|
||||
|
||||
const SELECTED_NODE_MAX_ZOOM = 2;
|
||||
|
||||
// Keeps neighbors clear of the search field, buttons and legend
|
||||
@@ -136,22 +124,8 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
@state() private _showLabels = true;
|
||||
|
||||
// Not reactive: a new series option starts the layout again, so a drop only
|
||||
// reaches the option with the next render
|
||||
private _nodePositions: Record<string, { x: number; y: number }> = {};
|
||||
|
||||
// Dragged nodes stay where they are dropped, the force layout moves the others
|
||||
private _pinnedNodes: string[] = [];
|
||||
|
||||
// Names of the legend categories that are switched off. Not reactive: the
|
||||
// legend lays the graph out itself, only the layout animation threshold
|
||||
// needs a render
|
||||
private _hiddenCategories: string[] = [];
|
||||
|
||||
private _dragNode?: string;
|
||||
|
||||
private _dragMoved = false;
|
||||
|
||||
private _followSelectedNode = false;
|
||||
|
||||
private _followedChart?: EChartsType;
|
||||
@@ -196,15 +170,12 @@ export class HaNetworkGraph extends LitElement {
|
||||
this._showLabels,
|
||||
isMobile,
|
||||
hasHighlightedNodes,
|
||||
this.selectedNode,
|
||||
this._nodePositions,
|
||||
this._pinnedNodes,
|
||||
this._fewVisibleNodes()
|
||||
this.selectedNode
|
||||
)}
|
||||
.options=${this._createOptions(this.data?.categories)}
|
||||
height="100%"
|
||||
.extraComponents=${[GraphChart]}
|
||||
@chart-setup=${this._handleChartSetup}
|
||||
@chart-setup=${this._updateFollowing}
|
||||
>
|
||||
<slot name="search" slot="search"></slot>
|
||||
<slot name="button" slot="button"></slot>
|
||||
@@ -302,10 +273,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
showLabels: boolean,
|
||||
isMobile: boolean,
|
||||
hasHighlightedNodes?: boolean,
|
||||
selectedNode?: string,
|
||||
nodePositions: Record<string, { x: number; y: number }> = {},
|
||||
pinnedNodes: string[] = [],
|
||||
fewVisibleNodes = true
|
||||
selectedNode?: string
|
||||
) => ({
|
||||
id: "network",
|
||||
type: "graph",
|
||||
@@ -343,15 +311,14 @@ export class HaNetworkGraph extends LitElement {
|
||||
repulsion: [400, 600],
|
||||
edgeLength: [200, 350],
|
||||
gravity: 0.05,
|
||||
layoutAnimation: !reducedMotion && fewVisibleNodes,
|
||||
layoutAnimation: !reducedMotion && data.nodes.length < 100,
|
||||
},
|
||||
edgeSymbol: ["none", "arrow"],
|
||||
edgeSymbolSize: 10,
|
||||
data: this._getSeriesData(
|
||||
data.nodes,
|
||||
data.links,
|
||||
nodePositions,
|
||||
pinnedNodes,
|
||||
this._nodePositions,
|
||||
selectedNode
|
||||
),
|
||||
links: data.links.map((link) => ({
|
||||
@@ -367,25 +334,11 @@ export class HaNetworkGraph extends LitElement {
|
||||
deepEqual
|
||||
);
|
||||
|
||||
// The legend leaves the nodes of hidden categories out of the layout
|
||||
private _fewVisibleNodes() {
|
||||
const hidden = this._hiddenCategories;
|
||||
const visibleNodes = hidden.length
|
||||
? this.data.nodes.filter(
|
||||
(node) =>
|
||||
node.category === undefined ||
|
||||
!hidden.includes(this.data.categories?.[node.category]?.name ?? "")
|
||||
).length
|
||||
: this.data.nodes.length;
|
||||
return visibleNodes < LAYOUT_ANIMATION_THRESHOLD;
|
||||
}
|
||||
|
||||
private _getSeriesData = memoizeOne(
|
||||
(
|
||||
nodes: NetworkNode[],
|
||||
links: NetworkLink[],
|
||||
nodePositions: Record<string, { x: number; y: number }>,
|
||||
pinnedNodes: string[],
|
||||
selectedNode?: string
|
||||
) =>
|
||||
this._getPositionedNodes(nodes, links, nodePositions).map((node) => {
|
||||
@@ -402,7 +355,7 @@ export class HaNetworkGraph extends LitElement {
|
||||
? { ...node.itemStyle, borderWidth: 3 }
|
||||
: node.itemStyle || {},
|
||||
label: selected ? { ...node.label, fontWeight: "bold" } : node.label,
|
||||
fixed: node.fixed || pinnedNodes.includes(node.id),
|
||||
fixed: node.fixed,
|
||||
x: node.x,
|
||||
y: node.y,
|
||||
} as NonNullable<GraphSeriesOption["data"]>[number];
|
||||
@@ -562,90 +515,6 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private _handleChartSetup() {
|
||||
const chart = this._baseChart?.chart;
|
||||
chart?.on("mousedown", this._handleNodeMouseDown);
|
||||
chart?.getZr().on("drag", this._handleDrag);
|
||||
chart?.getZr().on("dragend", this._handleDragEnd);
|
||||
for (const event of LEGEND_SELECT_EVENTS) {
|
||||
chart?.on(event, this._handleLegendChange);
|
||||
}
|
||||
const legend = (
|
||||
chart?.getOption() as
|
||||
{ legend?: { selected?: Record<string, boolean> }[] } | undefined
|
||||
)?.legend?.[0];
|
||||
this._setHiddenCategories(legend?.selected ?? {});
|
||||
// A recreated chart, e.g. after a theme change, lacks the drops since the
|
||||
// last render
|
||||
this.requestUpdate();
|
||||
this._updateFollowing();
|
||||
}
|
||||
|
||||
private _handleLegendChange = (params: unknown) => {
|
||||
const fewVisibleNodes = this._fewVisibleNodes();
|
||||
this._setHiddenCategories(
|
||||
(params as { selected: Record<string, boolean> }).selected
|
||||
);
|
||||
if (this._fewVisibleNodes() !== fewVisibleNodes) {
|
||||
// The new series option lays out again from where the nodes are now
|
||||
this._saveNodePositions();
|
||||
this.requestUpdate();
|
||||
}
|
||||
};
|
||||
|
||||
private _setHiddenCategories(selected: Record<string, boolean>) {
|
||||
this._hiddenCategories = Object.keys(selected).filter(
|
||||
(name) => !selected[name]
|
||||
);
|
||||
}
|
||||
|
||||
private _handleNodeMouseDown = (params: {
|
||||
dataType?: string;
|
||||
data?: unknown;
|
||||
}) => {
|
||||
this._dragNode =
|
||||
params.dataType === "node" ? (params.data as NetworkNode).id : undefined;
|
||||
this._dragMoved = false;
|
||||
};
|
||||
|
||||
private _handleDrag = () => {
|
||||
this._dragMoved = true;
|
||||
};
|
||||
|
||||
private _handleDragEnd = () => {
|
||||
const id = this._dragNode;
|
||||
const moved = this._dragMoved;
|
||||
this._dragNode = undefined;
|
||||
this._dragMoved = false;
|
||||
// A click also ends a drag, which releases a pinned node in ECharts
|
||||
if (!id || (!moved && !this._pinnedNodes.includes(id))) {
|
||||
return;
|
||||
}
|
||||
this._pinNodeInChart(id);
|
||||
if (!this._pinnedNodes.includes(id)) {
|
||||
this._pinnedNodes = [...this._pinnedNodes, id];
|
||||
}
|
||||
this._saveNodePositions();
|
||||
};
|
||||
|
||||
// A new series option would start the layout again, so the pin goes into
|
||||
// the running force layout, and into the item option that ECharts lays out
|
||||
// from again, e.g. on a legend change
|
||||
private _pinNodeInChart(id: string) {
|
||||
const series = this._getGraphSeries();
|
||||
const node = series?.getGraph().getNodeById(id);
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
series.forceLayout?.setFixed(node.dataIndex);
|
||||
const [x, y] = node.getLayout();
|
||||
Object.assign(series.getData().getRawDataItem(node.dataIndex), {
|
||||
fixed: true,
|
||||
x,
|
||||
y,
|
||||
});
|
||||
}
|
||||
|
||||
private _updateFollowing() {
|
||||
const chart = this._followSelectedNode ? this._baseChart?.chart : undefined;
|
||||
if (chart !== this._followedChart) {
|
||||
@@ -681,7 +550,10 @@ export class HaNetworkGraph extends LitElement {
|
||||
if (!chart) {
|
||||
return;
|
||||
}
|
||||
const series = this._getGraphSeries(chart);
|
||||
const series: any = chart
|
||||
// @ts-ignore private method but no other way to get the graph positions
|
||||
.getModel()
|
||||
.getSeriesByIndex(0);
|
||||
const node = series?.getGraph().getNodeById(this.selectedNode);
|
||||
const position: number[] | undefined = node?.getLayout();
|
||||
if (!position) {
|
||||
@@ -742,7 +614,6 @@ export class HaNetworkGraph extends LitElement {
|
||||
|
||||
private _togglePhysics() {
|
||||
this._saveNodePositions();
|
||||
this._pinnedNodes = [];
|
||||
this._physicsEnabled = !this._physicsEnabled;
|
||||
}
|
||||
|
||||
@@ -751,28 +622,24 @@ export class HaNetworkGraph extends LitElement {
|
||||
}
|
||||
|
||||
private _saveNodePositions() {
|
||||
// Nodes that are not drawn keep their earlier position
|
||||
const positions = { ...this._nodePositions };
|
||||
this._getGraphSeries()
|
||||
?.getGraph()
|
||||
.eachNode((node: any) => {
|
||||
const layout = node.getLayout();
|
||||
if (layout) {
|
||||
positions[node.id] = {
|
||||
x: layout[0],
|
||||
y: layout[1],
|
||||
};
|
||||
}
|
||||
});
|
||||
this._nodePositions = positions;
|
||||
}
|
||||
|
||||
private _getGraphSeries(chart = this._baseChart?.chart): any {
|
||||
if (!chart || chart.isDisposed()) {
|
||||
return undefined;
|
||||
const positions = {};
|
||||
if (this._baseChart?.chart) {
|
||||
this._baseChart.chart
|
||||
// @ts-ignore private method but no other way to get the graph positions
|
||||
.getModel()
|
||||
.getSeriesByIndex(0)
|
||||
.getGraph()
|
||||
.eachNode((node: any) => {
|
||||
const layout = node.getLayout();
|
||||
if (layout) {
|
||||
positions[node.id] = {
|
||||
x: layout[0],
|
||||
y: layout[1],
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
// @ts-ignore private method but no other way to get the graph
|
||||
return chart.getModel().getSeriesByIndex(0);
|
||||
this._nodePositions = positions;
|
||||
}
|
||||
|
||||
static styles = css`
|
||||
|
||||
@@ -35,29 +35,26 @@ function computeTimelineStateColor(
|
||||
|
||||
const domain = computeDomain(stateObj.entity_id);
|
||||
|
||||
// Zone states would all share --state-person-active-color, so only an
|
||||
// exact state variable may color them, like states of uncolored domains.
|
||||
const isZoneState =
|
||||
// Zone states for person/device_tracker don't have specific CSS color variables,
|
||||
// so they all fall back to the same --state-person-active-color.
|
||||
// Only use a custom CSS variable if explicitly defined (e.g. --state-person-kitchen-color),
|
||||
// otherwise return undefined to get unique colors from the generic color handler.
|
||||
if (
|
||||
(domain === "person" || domain === "device_tracker") &&
|
||||
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state);
|
||||
const properties = isZoneState
|
||||
? undefined
|
||||
: stateColorProperties(stateObj, state);
|
||||
|
||||
if (!properties) {
|
||||
const stateKey = slugify(state, "_");
|
||||
const deviceClass = stateObj.attributes.device_class;
|
||||
!((FIXED_DOMAIN_STATES[domain] || []) as readonly string[]).includes(state)
|
||||
) {
|
||||
return computeCssValue(
|
||||
[
|
||||
...(deviceClass
|
||||
? [`--state-${domain}-${deviceClass}-${stateKey}-color`]
|
||||
: []),
|
||||
`--state-${domain}-${stateKey}-color`,
|
||||
],
|
||||
`--state-${domain}-${slugify(state, "_")}-color`,
|
||||
computedStyles
|
||||
);
|
||||
}
|
||||
|
||||
const properties = stateColorProperties(stateObj, state);
|
||||
|
||||
if (!properties) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const rgb = computeCssValue(properties, computedStyles);
|
||||
|
||||
if (!rgb) return undefined;
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
import { classMap } from "lit/directives/class-map";
|
||||
import { ifDefined } from "lit/directives/if-defined";
|
||||
import { join } from "lit/directives/join";
|
||||
import { keyed } from "lit/directives/keyed";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../../common/decorators/consume";
|
||||
@@ -125,16 +124,16 @@ export interface DataTableRowData {
|
||||
|
||||
export type SortableColumnContainer = Record<string, ClonedDataTableColumnData>;
|
||||
|
||||
// Renders the actions at the end of a group's header, they don't toggle the
|
||||
// group. Return `ha-icon-button`s with a label. They get the rows' icon
|
||||
// Slot for the actions at the end of a group's header, they don't toggle the
|
||||
// group. Put `ha-icon-button`s with a label in it. They get the rows' icon
|
||||
// colour and size by default, which `--data-table-group-actions-color`,
|
||||
// `--data-table-group-actions-button-size` and
|
||||
// `--data-table-group-actions-icon-size` change for all of them; style a
|
||||
// button itself for its own colour or size. Not a slot per group, as WebKit
|
||||
// is slow to add and remove slots while the rows scroll.
|
||||
export type DataTableGroupActions = (
|
||||
group: string
|
||||
) => TemplateResult | typeof nothing;
|
||||
// button itself for its own colour or size.
|
||||
export const GROUP_ACTIONS_SLOT_PREFIX = "group-actions-";
|
||||
|
||||
export const groupActionsSlot = (group: string) =>
|
||||
`${GROUP_ACTIONS_SLOT_PREFIX}${group}`;
|
||||
|
||||
const UNDEFINED_GROUP_KEY = "zzzzz_undefined";
|
||||
|
||||
@@ -198,9 +197,6 @@ export class HaDataTable extends LitElement {
|
||||
|
||||
@property({ attribute: false }) public groupOrder?: string[];
|
||||
|
||||
@property({ attribute: false })
|
||||
public renderGroupActions?: DataTableGroupActions;
|
||||
|
||||
@property({ attribute: false }) public sortColumn?: string;
|
||||
|
||||
@property({ attribute: false }) public sortDirection: SortingDirection = null;
|
||||
@@ -401,13 +397,9 @@ export class HaDataTable extends LitElement {
|
||||
}
|
||||
|
||||
if (properties.has("data")) {
|
||||
// Clean up checked rows that no longer exist or can no longer be selected
|
||||
// Clean up checked rows that no longer exist in the data
|
||||
if (this._checkedRows.length) {
|
||||
const validIds = new Set(
|
||||
this.data
|
||||
.filter((row) => row.selectable !== false)
|
||||
.map((row) => String(row[this.id]))
|
||||
);
|
||||
const validIds = new Set(this.data.map((row) => String(row[this.id])));
|
||||
const validCheckedRows = this._checkedRows.filter((id) =>
|
||||
validIds.has(id)
|
||||
);
|
||||
@@ -514,8 +506,7 @@ export class HaDataTable extends LitElement {
|
||||
this.groupOrder,
|
||||
this._collapsedGroups,
|
||||
this.sortColumn,
|
||||
this.sortDirection,
|
||||
this.renderGroupActions
|
||||
this.sortDirection
|
||||
)
|
||||
: [];
|
||||
|
||||
@@ -768,6 +759,8 @@ export class HaDataTable extends LitElement {
|
||||
`
|
||||
: html`
|
||||
${
|
||||
// Rendered before the rows, so the group's actions slot
|
||||
// shows here and not in its scrolled out header row
|
||||
this.groupColumn &&
|
||||
!this.autoHeight &&
|
||||
this._stickyGroup !== undefined
|
||||
@@ -782,15 +775,11 @@ export class HaDataTable extends LitElement {
|
||||
.group=${this._stickyGroup}
|
||||
@click=${this._collapseStickyGroup}
|
||||
>
|
||||
${keyed(
|
||||
${this._renderGroupHeader(
|
||||
this._stickyGroup,
|
||||
this._renderGroupHeader(
|
||||
this._stickyGroup,
|
||||
this._collapsedGroups.includes(this._stickyGroup),
|
||||
this._i18n?.localize,
|
||||
this.renderGroupActions,
|
||||
true
|
||||
)
|
||||
this._collapsedGroups.includes(this._stickyGroup),
|
||||
this._i18n?.localize,
|
||||
true
|
||||
)}
|
||||
</div>`
|
||||
: nothing
|
||||
@@ -814,14 +803,7 @@ export class HaDataTable extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
// Group headers are keyed by their group, so they keep their actions' state
|
||||
// when the data changes. The prefixes keep them apart from row ids.
|
||||
private _keyFunction = (row: DataTableRowData) =>
|
||||
row?.[this.id]
|
||||
? `row-${row[this.id]}`
|
||||
: row?.groupHeader !== undefined
|
||||
? `group-${row.groupHeader}`
|
||||
: row;
|
||||
private _keyFunction = (row: DataTableRowData) => row?.[this.id] || row;
|
||||
|
||||
private _renderMainValue(value: unknown) {
|
||||
return this.clickable
|
||||
@@ -1081,8 +1063,7 @@ export class HaDataTable extends LitElement {
|
||||
groupOrder: string[] | undefined,
|
||||
collapsedGroups: string[],
|
||||
sortColumn: string | undefined,
|
||||
sortDirection: SortingDirection,
|
||||
renderGroupActions: DataTableGroupActions | undefined
|
||||
sortDirection: SortingDirection
|
||||
) => {
|
||||
if (appendRow || groupColumn) {
|
||||
let items = [...data];
|
||||
@@ -1141,8 +1122,7 @@ export class HaDataTable extends LitElement {
|
||||
content: this._renderGroupHeader(
|
||||
groupName,
|
||||
collapsedGroups.includes(groupName),
|
||||
localize,
|
||||
renderGroupActions
|
||||
localize
|
||||
),
|
||||
});
|
||||
if (!collapsedGroups.includes(groupName)) {
|
||||
@@ -1168,7 +1148,6 @@ export class HaDataTable extends LitElement {
|
||||
groupName: string,
|
||||
collapsed: boolean,
|
||||
localize: LocalizeFunc | undefined,
|
||||
renderGroupActions: DataTableGroupActions | undefined,
|
||||
sticky = false
|
||||
) {
|
||||
// The sticky copy's button and name are hidden from assistive technology,
|
||||
@@ -1204,7 +1183,7 @@ export class HaDataTable extends LitElement {
|
||||
}
|
||||
</span>
|
||||
<div class="group-actions" @click=${this._stopGroupToggle}>
|
||||
${renderGroupActions?.(groupName)}
|
||||
<slot name=${groupActionsSlot(groupName)}></slot>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -1285,8 +1264,7 @@ export class HaDataTable extends LitElement {
|
||||
this.groupOrder,
|
||||
this._collapsedGroups,
|
||||
this.sortColumn,
|
||||
this.sortDirection,
|
||||
this.renderGroupActions
|
||||
this.sortDirection
|
||||
);
|
||||
|
||||
if (
|
||||
@@ -1983,7 +1961,7 @@ export class HaDataTable extends LitElement {
|
||||
align-self: stretch;
|
||||
margin-top: -12px;
|
||||
margin-inline-start: auto;
|
||||
/* The rows' icon button size, inherited by the actions */
|
||||
/* The rows' icon button size, inherited by the slotted ones */
|
||||
--_button-size: var(--data-table-group-actions-button-size, 48px);
|
||||
--ha-icon-button-size: var(--_button-size);
|
||||
--mdc-icon-size: var(--data-table-group-actions-icon-size, 24px);
|
||||
@@ -1996,9 +1974,9 @@ export class HaDataTable extends LitElement {
|
||||
position: sticky;
|
||||
inset-inline-end: 0;
|
||||
cursor: default;
|
||||
/* Don't pass the group name's weight on to the actions */
|
||||
/* Don't pass the group name's weight on to slotted menus */
|
||||
font-weight: var(--ha-font-weight-normal);
|
||||
/* Inherited by the actions, like the rows' icon cells */
|
||||
/* Inherited by the slotted icon buttons, like the rows' icon cells */
|
||||
color: var(
|
||||
--data-table-group-actions-color,
|
||||
var(--secondary-text-color)
|
||||
|
||||
@@ -97,8 +97,6 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
|
||||
|
||||
@state() private _dateValue?: string;
|
||||
|
||||
@state() private _rangeIncomplete = false;
|
||||
|
||||
@state() private _timeValue = {
|
||||
from: { hours: 0, minutes: 0 },
|
||||
to: { hours: 23, minutes: 59 },
|
||||
@@ -197,7 +195,6 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
|
||||
.locale=${this._i18n.locale.language}
|
||||
.focusedDate=${this._focusDate}
|
||||
@focusday=${this._focusChanged}
|
||||
@rangestart=${this._handleRangeStart}
|
||||
@change=${this._handleChange}
|
||||
show-outside-days
|
||||
.firstDayOfWeek=${firstWeekdayIndex(this._i18n.locale)}
|
||||
@@ -256,9 +253,7 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
|
||||
<ha-button appearance="plain" @click=${this._cancel}
|
||||
>${this._i18n.localize("ui.common.cancel")}</ha-button
|
||||
>
|
||||
<ha-button
|
||||
.disabled=${!this._dateValue || this._rangeIncomplete}
|
||||
@click=${this._save}
|
||||
<ha-button .disabled=${!this._dateValue} @click=${this._save}
|
||||
>${this._i18n.localize(
|
||||
"ui.components.date-range-picker.select"
|
||||
)}</ha-button
|
||||
@@ -285,7 +280,7 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
|
||||
}
|
||||
|
||||
private _save() {
|
||||
if (!this._dateValue || this._rangeIncomplete) {
|
||||
if (!this._dateValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -336,21 +331,9 @@ export class DateRangePicker extends MobileAwareMixin(LitElement) {
|
||||
this._focusDate = ev.target.focusedDate;
|
||||
}
|
||||
|
||||
private _handleRangeStart(
|
||||
ev: HASSDomTargetEvent<HTMLElementTagNameMap["calendar-range"]>
|
||||
) {
|
||||
this._rangeIncomplete = matchMedia("(hover: hover)").matches;
|
||||
if (this._rangeIncomplete) {
|
||||
return;
|
||||
}
|
||||
const day = ev.target.tentative;
|
||||
this._dateValue = `${day}/${day}`;
|
||||
}
|
||||
|
||||
private _handleChange(
|
||||
ev: HASSDomTargetEvent<HTMLElementTagNameMap["calendar-range"]>
|
||||
) {
|
||||
this._rangeIncomplete = false;
|
||||
const dateElement = ev.target as HTMLElementTagNameMap["calendar-range"];
|
||||
this._dateValue = dateElement.value;
|
||||
this._focusDate = dateElement.focusedDate;
|
||||
|
||||
@@ -371,24 +371,25 @@ export class HaEntityPicker extends LitElement {
|
||||
excludeEntities?: string[],
|
||||
value?: string
|
||||
) =>
|
||||
getEntities({
|
||||
states,
|
||||
entities: registries.entities,
|
||||
devices: registries.devices,
|
||||
areas: registries.areas,
|
||||
floors: registries.floors,
|
||||
localize: i18n.localize,
|
||||
language: i18n.language,
|
||||
translationMetadata: i18n.translationMetadata,
|
||||
includeDomains,
|
||||
excludeDomains,
|
||||
entityFilter,
|
||||
includeDeviceClasses,
|
||||
includeUnitOfMeasurement,
|
||||
includeEntities,
|
||||
excludeEntities,
|
||||
value,
|
||||
})
|
||||
getEntities(
|
||||
{
|
||||
states,
|
||||
...registries,
|
||||
language: i18n.language,
|
||||
translationMetadata: i18n.translationMetadata,
|
||||
localize: i18n.localize,
|
||||
},
|
||||
{
|
||||
includeDomains,
|
||||
excludeDomains,
|
||||
entityFilter,
|
||||
includeDeviceClasses,
|
||||
includeUnitOfMeasurement,
|
||||
includeEntities,
|
||||
excludeEntities,
|
||||
value,
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
private _sortByRelatedContext = memoizeOne(
|
||||
|
||||
@@ -52,7 +52,7 @@ class StateInfo extends LitElement {
|
||||
${
|
||||
this.inDialog
|
||||
? html`<div class="time-ago">
|
||||
<ha-tooltip for="relative-time" trigger="hover focus click">
|
||||
<ha-tooltip for="relative-time">
|
||||
<div class="row">
|
||||
<span class="column-name">
|
||||
${this._localize(
|
||||
|
||||
@@ -6,7 +6,7 @@ import { repeat } from "lit/directives/repeat";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { fireEvent, type HASSDomEvent } from "../common/dom/fire_event";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { supportsFeature } from "../common/entity/supports-feature";
|
||||
import {
|
||||
CameraEntityFeature,
|
||||
@@ -17,14 +17,8 @@ import {
|
||||
STREAM_TYPE_WEB_RTC,
|
||||
type CameraCapabilities,
|
||||
type CameraEntity,
|
||||
type StreamType,
|
||||
} from "../data/camera";
|
||||
import {
|
||||
MJPEG_STREAM,
|
||||
selectCameraStreams,
|
||||
type CameraStream,
|
||||
type CameraStreamTracks,
|
||||
type CameraStreamType,
|
||||
} from "../data/camera-streams";
|
||||
import {
|
||||
apiContext,
|
||||
configContext,
|
||||
@@ -35,7 +29,14 @@ import "./ha-hls-player";
|
||||
import "./ha-web-rtc-player";
|
||||
import type { HaWebRtcPlayer } from "./ha-web-rtc-player";
|
||||
|
||||
export type { CameraStreamType } from "../data/camera-streams";
|
||||
const MJPEG_STREAM = "mjpeg";
|
||||
|
||||
export type CameraStreamType = StreamType | typeof MJPEG_STREAM;
|
||||
|
||||
interface Stream {
|
||||
type: CameraStreamType;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
@customElement("ha-camera-stream")
|
||||
export class HaCameraStream extends LitElement {
|
||||
@@ -77,15 +78,13 @@ export class HaCameraStream extends LitElement {
|
||||
|
||||
@state() private _capabilities?: CameraCapabilities;
|
||||
|
||||
@state() private _hlsStreams?: CameraStreamTracks;
|
||||
@state() private _hlsStreams?: { hasAudio: boolean; hasVideo: boolean };
|
||||
|
||||
@state() private _webRtcStreams?: CameraStreamTracks;
|
||||
@state() private _webRtcStreams?: { hasAudio: boolean; hasVideo: boolean };
|
||||
|
||||
@query("ha-web-rtc-player") private _webRtcPlayer?: HaWebRtcPlayer;
|
||||
|
||||
private _visibleStreamType?: CameraStreamType;
|
||||
|
||||
private _capabilitiesRequest = 0;
|
||||
private _visibleStreamType?: Stream["type"];
|
||||
|
||||
private _thumbnailApi = memoizeOne(
|
||||
(
|
||||
@@ -133,10 +132,6 @@ export class HaCameraStream extends LitElement {
|
||||
public connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this._connected = true;
|
||||
if (this.hasUpdated) {
|
||||
// The players start again when reattached, so their results do as well
|
||||
this._resetStreams();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback() {
|
||||
@@ -151,8 +146,9 @@ export class HaCameraStream extends LitElement {
|
||||
capabilities: this._capabilities,
|
||||
});
|
||||
}
|
||||
const streams = this._currentStreams();
|
||||
const visibleStreamType = streams.find((stream) => stream.visible)?.type;
|
||||
const visibleStreamType = this._currentStreams().find(
|
||||
(stream) => stream.visible
|
||||
)?.type;
|
||||
if (visibleStreamType !== this._visibleStreamType) {
|
||||
this._visibleStreamType = visibleStreamType;
|
||||
fireEvent(this, "stream-type-changed", { type: visibleStreamType });
|
||||
@@ -171,7 +167,7 @@ export class HaCameraStream extends LitElement {
|
||||
)}`;
|
||||
}
|
||||
|
||||
private _renderStream(stream: CameraStream) {
|
||||
private _renderStream(stream: Stream) {
|
||||
if (!this.stateObj) {
|
||||
return nothing;
|
||||
}
|
||||
@@ -233,14 +229,15 @@ export class HaCameraStream extends LitElement {
|
||||
return this._streams(
|
||||
this._capabilities?.frontend_stream_types,
|
||||
this._hlsStreams,
|
||||
this._webRtcStreams
|
||||
this._webRtcStreams,
|
||||
this.muted
|
||||
);
|
||||
}
|
||||
|
||||
private async _getCapabilities() {
|
||||
this._capabilities = undefined;
|
||||
this._resetStreams();
|
||||
const request = ++this._capabilitiesRequest;
|
||||
this._hlsStreams = undefined;
|
||||
this._webRtcStreams = undefined;
|
||||
if (!supportsFeature(this.stateObj!, CameraEntityFeature.STREAM)) {
|
||||
this._capabilities = {
|
||||
frontend_stream_types: [],
|
||||
@@ -248,19 +245,10 @@ export class HaCameraStream extends LitElement {
|
||||
};
|
||||
return;
|
||||
}
|
||||
const capabilities = await fetchCameraCapabilities(
|
||||
this._capabilities = await fetchCameraCapabilities(
|
||||
this._api,
|
||||
this.stateObj!.entity_id
|
||||
);
|
||||
if (request !== this._capabilitiesRequest) {
|
||||
return;
|
||||
}
|
||||
this._capabilities = capabilities;
|
||||
}
|
||||
|
||||
private _resetStreams() {
|
||||
this._hlsStreams = undefined;
|
||||
this._webRtcStreams = undefined;
|
||||
}
|
||||
|
||||
private async _getPosterUrl(): Promise<void> {
|
||||
@@ -281,38 +269,89 @@ export class HaCameraStream extends LitElement {
|
||||
fireEvent(this, "load");
|
||||
}
|
||||
|
||||
private _handleHlsStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
|
||||
private _handleHlsStreams(ev: CustomEvent) {
|
||||
this._hlsStreams = ev.detail;
|
||||
}
|
||||
|
||||
private _handleWebRtcStreams(ev: HASSDomEvent<HASSDomEvents["streams"]>) {
|
||||
if (
|
||||
!ev.detail.hasVideo &&
|
||||
!ev.detail.hasAudio &&
|
||||
this._capabilities?.frontend_stream_types.length === 1 &&
|
||||
typeof RTCPeerConnection !== "undefined"
|
||||
) {
|
||||
// Without another stream type, keep the player to show why it failed.
|
||||
// Only a browser without WebRTC falls back to MJPEG.
|
||||
return;
|
||||
}
|
||||
private _handleWebRtcStreams(ev: CustomEvent) {
|
||||
this._webRtcStreams = ev.detail;
|
||||
}
|
||||
|
||||
private _streams = memoizeOne(
|
||||
(
|
||||
supportedTypes?: CameraCapabilities["frontend_stream_types"],
|
||||
hlsStreams?: CameraStreamTracks,
|
||||
webRtcStreams?: CameraStreamTracks
|
||||
): CameraStream[] => {
|
||||
supportedTypes?: StreamType[],
|
||||
hlsStreams?: { hasAudio: boolean; hasVideo: boolean },
|
||||
webRtcStreams?: { hasAudio: boolean; hasVideo: boolean },
|
||||
muted?: boolean
|
||||
): Stream[] => {
|
||||
if (__DEMO__) {
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
return selectCameraStreams({
|
||||
supportedTypes,
|
||||
hlsStreams,
|
||||
webRtcStreams,
|
||||
});
|
||||
if (!supportedTypes) {
|
||||
return [];
|
||||
}
|
||||
if (supportedTypes.length === 0) {
|
||||
// doesn't support any stream type, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
if (supportedTypes.length === 1) {
|
||||
// only 1 stream type, no need to choose
|
||||
if (
|
||||
(supportedTypes[0] === STREAM_TYPE_HLS &&
|
||||
hlsStreams?.hasVideo === false) ||
|
||||
(supportedTypes[0] === STREAM_TYPE_WEB_RTC &&
|
||||
webRtcStreams?.hasVideo === false)
|
||||
) {
|
||||
// stream failed to load, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
return [{ type: supportedTypes[0], visible: true }];
|
||||
}
|
||||
if (hlsStreams && webRtcStreams) {
|
||||
// fully loaded
|
||||
if (
|
||||
hlsStreams.hasVideo &&
|
||||
hlsStreams.hasAudio &&
|
||||
!webRtcStreams.hasAudio &&
|
||||
!muted
|
||||
) {
|
||||
// webRTC stream is missing audio and audio is not muted, use HLS
|
||||
return [{ type: STREAM_TYPE_HLS, visible: true }];
|
||||
}
|
||||
if (webRtcStreams.hasVideo) {
|
||||
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
|
||||
}
|
||||
// both streams failed to load, fallback to mjpeg
|
||||
return [{ type: MJPEG_STREAM, visible: true }];
|
||||
}
|
||||
|
||||
if (hlsStreams?.hasVideo !== webRtcStreams?.hasVideo) {
|
||||
// one of the two streams is loaded, or errored
|
||||
// choose the one that has video or is still loading
|
||||
if (hlsStreams?.hasVideo) {
|
||||
return [
|
||||
{ type: STREAM_TYPE_HLS, visible: true },
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: false },
|
||||
];
|
||||
}
|
||||
if (hlsStreams?.hasVideo === false) {
|
||||
return [{ type: STREAM_TYPE_WEB_RTC, visible: true }];
|
||||
}
|
||||
if (webRtcStreams?.hasVideo) {
|
||||
return [
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: true },
|
||||
{ type: STREAM_TYPE_HLS, visible: false },
|
||||
];
|
||||
}
|
||||
if (webRtcStreams?.hasVideo === false) {
|
||||
return [{ type: STREAM_TYPE_HLS, visible: true }];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{ type: STREAM_TYPE_HLS, visible: true },
|
||||
{ type: STREAM_TYPE_WEB_RTC, visible: false },
|
||||
];
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { ContextType } from "@lit/context";
|
||||
import type { CSSResultGroup, TemplateResult } from "lit";
|
||||
import { css, html, LitElement } from "lit";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import { styleMap } from "lit/directives/style-map";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { configContext } from "../data/context";
|
||||
import "./ha-icon-next";
|
||||
@@ -33,18 +32,27 @@ class HaConfigNavigationList extends LitElement {
|
||||
return html`
|
||||
<ha-list-item-button
|
||||
.href=${externalApp ? undefined : page.path}
|
||||
.headline=${page.name}
|
||||
.supportingText=${this.hasSecondary ? page.description : undefined}
|
||||
@click=${externalApp ? this._handleExternalApp : undefined}
|
||||
>
|
||||
<ha-svg-icon
|
||||
<div
|
||||
slot="start"
|
||||
class=${page.iconColor ? "icon-background" : ""}
|
||||
style=${styleMap({ backgroundColor: page.iconColor })}
|
||||
.path=${page.iconPath}
|
||||
.secondaryPath=${page.iconSecondaryPath}
|
||||
.viewBox=${page.iconViewBox}
|
||||
></ha-svg-icon>
|
||||
.style="background-color: ${page.iconColor || "undefined"}"
|
||||
>
|
||||
<ha-svg-icon
|
||||
.path=${page.iconPath}
|
||||
.secondaryPath=${page.iconSecondaryPath}
|
||||
.viewBox=${page.iconViewBox}
|
||||
></ha-svg-icon>
|
||||
</div>
|
||||
<span slot="headline">${page.name}</span>
|
||||
${
|
||||
this.hasSecondary
|
||||
? html`<span slot="supporting-text"
|
||||
>${page.description}</span
|
||||
>`
|
||||
: ""
|
||||
}
|
||||
${
|
||||
!this.narrow
|
||||
? html`<ha-icon-next slot="end"></ha-icon-next>`
|
||||
@@ -74,6 +82,8 @@ class HaConfigNavigationList extends LitElement {
|
||||
}
|
||||
.icon-background {
|
||||
border-radius: var(--ha-border-radius-circle);
|
||||
}
|
||||
.icon-background ha-svg-icon {
|
||||
color: #fff;
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -387,7 +387,7 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _handleKeyDown(e: KeyboardEvent) {
|
||||
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
|
||||
if (!A11Y_KEY_CODES.has(e.code)) return;
|
||||
e.preventDefault();
|
||||
if (this._lastSlider) {
|
||||
this.shadowRoot?.getElementById(this._lastSlider)?.focus();
|
||||
@@ -439,7 +439,7 @@ export class HaControlCircularSlider extends LitElement {
|
||||
}
|
||||
|
||||
private _handleKeyUp(e: KeyboardEvent) {
|
||||
if (this.disabled || !A11Y_KEY_CODES.has(e.code)) return;
|
||||
if (!A11Y_KEY_CODES.has(e.code)) return;
|
||||
this._activeSlider = (e.currentTarget as any).id as ActiveSlider;
|
||||
e.preventDefault();
|
||||
fireEvent(this, `${this._activeSlider}-changing`, {
|
||||
|
||||
@@ -219,7 +219,6 @@ export class HaControlSlider extends LitElement {
|
||||
this.pressed = false;
|
||||
this._hideTooltip();
|
||||
this.value = savedValue;
|
||||
fireEvent(this, "slider-moved", { value: undefined });
|
||||
});
|
||||
this._mc.on("panmove", (e) => {
|
||||
if (this.disabled) return;
|
||||
|
||||
@@ -87,12 +87,11 @@ export class HaFilterCategories extends LitElement {
|
||||
public disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._unsubscribeCategories();
|
||||
this._categories = [];
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues) {
|
||||
super.willUpdate(changedProps);
|
||||
if (changedProps.has("scope") && this.scope !== this._categoriesScope) {
|
||||
if (changedProps.get("scope") !== undefined) {
|
||||
this._categories = [];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@ import { createRef, ref } from "lit/directives/ref";
|
||||
import { repeat } from "lit/directives/repeat";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consume } from "../common/decorators/consume";
|
||||
import { transform } from "../common/decorators/transform";
|
||||
import { getDeviceAreaId } from "../common/entity/context/get_device_context";
|
||||
import {
|
||||
FilterPanelController,
|
||||
filterPanelStyles,
|
||||
@@ -19,16 +17,11 @@ import { fireEvent } from "../common/dom/fire_event";
|
||||
import { computeRTL } from "../common/util/compute_rtl";
|
||||
import { deepEqual } from "../common/util/deep-equal";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import type { AreaRegistryEntry } from "../data/area/area_registry";
|
||||
import type { FloorAreasFilterValue } from "../data/data_table_filters";
|
||||
import {
|
||||
apiContext,
|
||||
areasContext,
|
||||
devicesContext,
|
||||
floorsContext,
|
||||
fullEntitiesContext,
|
||||
internationalizationContext,
|
||||
statesContext,
|
||||
} from "../data/context";
|
||||
import { getFloorAreaLookup } from "../data/floor_registry";
|
||||
import type { RelatedResult } from "../data/search";
|
||||
@@ -40,7 +33,6 @@ import "./ha-icon";
|
||||
import "./ha-icon-button";
|
||||
import "./ha-svg-icon";
|
||||
import "./ha-tree-indicator";
|
||||
import "./item/ha-list-item-base";
|
||||
import "./item/ha-list-item-option";
|
||||
import type { HaListItemOption } from "./item/ha-list-item-option";
|
||||
import "./list/ha-list-selectable";
|
||||
@@ -67,27 +59,10 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
@consume({ context: apiContext, subscribe: true })
|
||||
private _api!: ContextType<typeof apiContext>;
|
||||
|
||||
@consume({ context: devicesContext, subscribe: true })
|
||||
@state()
|
||||
private _devices!: ContextType<typeof devicesContext>;
|
||||
|
||||
@consume({ context: fullEntitiesContext, subscribe: true })
|
||||
@state()
|
||||
private _entities?: ContextType<typeof fullEntitiesContext>;
|
||||
|
||||
// Only a state being added or removed can change the state-only entities,
|
||||
// so plain state updates keep the previous set and don't rerender
|
||||
@state()
|
||||
@consume({ context: statesContext, subscribe: true })
|
||||
@transform<ContextType<typeof statesContext>, Set<string>>({
|
||||
transformer: function (this: HaFilterFloorAreas, states) {
|
||||
const ids = new Set(Object.keys(states));
|
||||
return deepEqual(ids, this._stateIds) ? this._stateIds : ids;
|
||||
},
|
||||
})
|
||||
private _stateIds?: Set<string>;
|
||||
|
||||
@property({ attribute: false }) public value?: FloorAreasFilterValue;
|
||||
@property({ attribute: false }) public value?: {
|
||||
floors?: string[];
|
||||
areas?: string[];
|
||||
};
|
||||
|
||||
@property() public type?: keyof RelatedResult;
|
||||
|
||||
@@ -106,17 +81,12 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
|
||||
private _relatedRequestId = 0;
|
||||
|
||||
public willUpdate(properties: PropertyValues) {
|
||||
public willUpdate(properties: PropertyValues<this>) {
|
||||
super.willUpdate(properties);
|
||||
|
||||
if (
|
||||
(properties.has("value") &&
|
||||
!deepEqual(this.value, properties.get("value"))) ||
|
||||
// Items without an area are worked out from the registries
|
||||
(this.value?.no_area &&
|
||||
(properties.has("_devices") ||
|
||||
properties.has("_entities") ||
|
||||
(this.type !== "device" && properties.has("_stateIds"))))
|
||||
properties.has("value") &&
|
||||
!deepEqual(this.value, properties.get("value"))
|
||||
) {
|
||||
this._findRelated();
|
||||
}
|
||||
@@ -124,12 +94,6 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
|
||||
protected render() {
|
||||
const areas = this._areas(this._areasReg, this._floorsReg);
|
||||
const groupOtherAreas =
|
||||
!!areas.floors.length && !!areas.unassisgnedAreas.length;
|
||||
const count =
|
||||
(this.value?.areas?.length || 0) +
|
||||
(this.value?.floors?.length || 0) +
|
||||
(this.value?.no_area ? 1 : 0);
|
||||
|
||||
return html`
|
||||
<ha-expansion-panel
|
||||
@@ -140,8 +104,13 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
<div slot="header" class="header">
|
||||
${this._localize("ui.panel.config.areas.caption")}
|
||||
${
|
||||
count
|
||||
? html`<div class="badge">${count}</div>
|
||||
this.value?.areas?.length || this.value?.floors?.length
|
||||
? html`<div class="badge">
|
||||
${
|
||||
(this.value?.areas?.length || 0) +
|
||||
(this.value?.floors?.length || 0)
|
||||
}
|
||||
</div>
|
||||
<ha-icon-button
|
||||
.path=${mdiFilterVariantRemove}
|
||||
@click=${this._clearFilter}
|
||||
@@ -162,17 +131,6 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
@ha-list-item-deselected=${this._handleRemoved}
|
||||
aria-label=${this._localize("ui.panel.config.areas.caption")}
|
||||
>
|
||||
<ha-list-item-option
|
||||
appearance="checkbox"
|
||||
selection-position="end"
|
||||
.value=${"no_area"}
|
||||
.type=${"no_area"}
|
||||
.selected=${this.value?.no_area || false}
|
||||
>
|
||||
<span slot="headline">
|
||||
${this._localize("ui.components.area-picker.no_area")}
|
||||
</span>
|
||||
</ha-list-item-option>
|
||||
${repeat(
|
||||
areas?.floors || [],
|
||||
(floor) => floor.floor_id,
|
||||
@@ -204,31 +162,10 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
)}
|
||||
`
|
||||
)}
|
||||
${
|
||||
groupOtherAreas
|
||||
? html`<ha-list-item-base role="presentation">
|
||||
<ha-svg-icon
|
||||
slot="start"
|
||||
.path=${mdiTextureBox}
|
||||
></ha-svg-icon>
|
||||
<span slot="headline">
|
||||
${this._localize(
|
||||
"ui.panel.config.areas.picker.other_areas"
|
||||
)}
|
||||
</span>
|
||||
</ha-list-item-base>`
|
||||
: nothing
|
||||
}
|
||||
${repeat(
|
||||
areas.unassisgnedAreas,
|
||||
(area, index) =>
|
||||
`${area.area_id}${index === areas.unassisgnedAreas.length - 1 ? "___last" : ""}`,
|
||||
(area, index) =>
|
||||
this._renderArea(
|
||||
area,
|
||||
index === areas.unassisgnedAreas.length - 1,
|
||||
groupOtherAreas
|
||||
)
|
||||
areas?.unassisgnedAreas,
|
||||
(area) => area.area_id,
|
||||
(area) => this._renderArea(area)
|
||||
)}
|
||||
</ha-list-selectable>
|
||||
</div>
|
||||
@@ -238,11 +175,9 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _renderArea(
|
||||
area: AreaRegistryEntry,
|
||||
last = false,
|
||||
nested = !!area.floor_id
|
||||
) {
|
||||
private _renderArea(area, last = false) {
|
||||
const hasFloor = !!area.floor_id;
|
||||
|
||||
return html`
|
||||
<ha-list-item-option
|
||||
appearance="checkbox"
|
||||
@@ -255,11 +190,11 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
this._i18n.language,
|
||||
this._i18n.translationMetadata.translations
|
||||
),
|
||||
floor: nested,
|
||||
floor: hasFloor,
|
||||
})}
|
||||
>
|
||||
${
|
||||
nested
|
||||
hasFloor
|
||||
? html`<ha-tree-indicator
|
||||
slot="start"
|
||||
.end=${last}
|
||||
@@ -292,11 +227,6 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
return;
|
||||
}
|
||||
|
||||
if (addedItem.type === "no_area") {
|
||||
this.value = { ...this.value, no_area: true };
|
||||
return;
|
||||
}
|
||||
|
||||
this.value = {
|
||||
...this.value,
|
||||
[addedItem.type]: [
|
||||
@@ -319,11 +249,6 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
return;
|
||||
}
|
||||
|
||||
if (removedItem.type === "no_area") {
|
||||
this.value = { ...this.value, no_area: false };
|
||||
return;
|
||||
}
|
||||
|
||||
this.value = {
|
||||
...this.value,
|
||||
[removedItem.type]: this.value![removedItem.type].filter(
|
||||
@@ -364,9 +289,7 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
|
||||
if (
|
||||
!this.value ||
|
||||
(!this.value.areas?.length &&
|
||||
!this.value.floors?.length &&
|
||||
!this.value.no_area)
|
||||
(!this.value.areas?.length && !this.value.floors?.length)
|
||||
) {
|
||||
this.value = {};
|
||||
fireEvent(this, "data-table-filter-changed", {
|
||||
@@ -409,9 +332,6 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
}
|
||||
|
||||
const items = new Set<string>();
|
||||
if (this.value.no_area) {
|
||||
this._itemsWithoutArea().forEach((item) => items.add(item));
|
||||
}
|
||||
for (const result of results) {
|
||||
if (result[this.type!]) {
|
||||
result[this.type!]!.forEach((item) => items.add(item));
|
||||
@@ -424,39 +344,6 @@ export class HaFilterFloorAreas extends LitElement {
|
||||
});
|
||||
}
|
||||
|
||||
private _itemsWithoutArea(): string[] {
|
||||
if (this.type === "device") {
|
||||
return Object.values(this._devices)
|
||||
.filter((device) => !getDeviceAreaId(device, this._devices))
|
||||
.map((device) => device.id);
|
||||
}
|
||||
// Matches the area column of each table: the entities and helpers tables
|
||||
// give an entity without its own area the area of its device, the
|
||||
// automations, scripts and scenes tables only show the entity's own area
|
||||
const useDeviceArea = this.type === "entity";
|
||||
const entities = this._entities || [];
|
||||
const items = entities
|
||||
.filter(
|
||||
(entity) =>
|
||||
(this.includeDisabledEntities || !entity.disabled_by) &&
|
||||
!entity.area_id &&
|
||||
!(
|
||||
useDeviceArea &&
|
||||
entity.device_id &&
|
||||
this._devices[entity.device_id]?.area_id
|
||||
)
|
||||
)
|
||||
.map((entity) => entity.entity_id);
|
||||
// Entities without a registry entry can't have an area
|
||||
const registered = new Set(entities.map((entity) => entity.entity_id));
|
||||
for (const entityId of this._stateIds || []) {
|
||||
if (!registered.has(entityId)) {
|
||||
items.push(entityId);
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
private _handleClearFilterKeydown(ev: KeyboardEvent) {
|
||||
if (ev.key === "Enter" || ev.key === " ") {
|
||||
ev.stopPropagation();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ensureArray } from "../../common/array/ensure-array";
|
||||
import type {
|
||||
HaFormCondition,
|
||||
HaFormDataContainer,
|
||||
@@ -88,38 +87,26 @@ export const combineVisible = (
|
||||
return conditions;
|
||||
};
|
||||
|
||||
const getConditionFields = (visible: HaFormVisible | undefined): string[] =>
|
||||
visible === undefined || typeof visible === "boolean"
|
||||
? []
|
||||
: ensureArray(visible).flatMap((condition) =>
|
||||
"condition" in condition
|
||||
? condition.conditions.flatMap((sub) => getConditionFields(sub))
|
||||
: [condition.field]
|
||||
);
|
||||
|
||||
// Hiding a field drops its value, which can flip another field's condition, so
|
||||
// a field is evaluated after the fields its condition depends on.
|
||||
// resolve the set to a fixpoint. Fields are given in order as name and visible.
|
||||
export const getHiddenFields = (
|
||||
fields: readonly (readonly [string, HaFormVisible | undefined])[],
|
||||
data: HaFormDataContainer | undefined
|
||||
): Set<string> => {
|
||||
const conditions = new Map(fields);
|
||||
const evalData: HaFormDataContainer = { ...(data ?? {}) };
|
||||
const hidden = new Set<string>();
|
||||
const resolved = new Set<string>();
|
||||
const resolve = (name: string) => {
|
||||
if (resolved.has(name) || !conditions.has(name)) {
|
||||
return;
|
||||
}
|
||||
resolved.add(name);
|
||||
const visible = conditions.get(name);
|
||||
getConditionFields(visible).forEach(resolve);
|
||||
if (!isVisible(visible, evalData)) {
|
||||
const evalData: HaFormDataContainer = { ...(data ?? {}) };
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const [name, visible] of fields) {
|
||||
if (hidden.has(name) || isVisible(visible, evalData)) {
|
||||
continue;
|
||||
}
|
||||
hidden.add(name);
|
||||
delete evalData[name];
|
||||
changed = true;
|
||||
}
|
||||
};
|
||||
fields.forEach(([name]) => resolve(name));
|
||||
}
|
||||
return hidden;
|
||||
};
|
||||
|
||||
|
||||
@@ -16,30 +16,6 @@ import type {
|
||||
HaFormIntegerSchema,
|
||||
} from "./types";
|
||||
|
||||
/**
|
||||
* The value the slider shows: the data, or for a required field without data
|
||||
* its suggested value, default or minimum.
|
||||
*/
|
||||
export const computeIntegerSliderValue = (
|
||||
schema: HaFormIntegerSchema,
|
||||
data?: HaFormIntegerData
|
||||
): number => {
|
||||
if (data !== undefined) {
|
||||
return data;
|
||||
}
|
||||
|
||||
if (!schema.required) {
|
||||
return schema.valueMin || 0;
|
||||
}
|
||||
|
||||
return (
|
||||
(schema.description?.suggested_value as HaFormIntegerData | undefined) ??
|
||||
schema.default ??
|
||||
schema.valueMin ??
|
||||
0
|
||||
);
|
||||
};
|
||||
|
||||
@customElement("ha-form-integer")
|
||||
export class HaFormInteger extends LitElement implements HaFormElement {
|
||||
@property({ attribute: false }) public localize?: LocalizeFunc;
|
||||
@@ -103,7 +79,7 @@ export class HaFormInteger extends LitElement implements HaFormElement {
|
||||
}
|
||||
<ha-slider
|
||||
labeled
|
||||
.value=${computeIntegerSliderValue(this.schema, this.data)}
|
||||
.value=${this._value}
|
||||
.min=${this.schema.valueMin}
|
||||
.max=${this.schema.valueMax}
|
||||
.disabled=${
|
||||
@@ -160,6 +136,24 @@ export class HaFormInteger extends LitElement implements HaFormElement {
|
||||
}
|
||||
}
|
||||
|
||||
private get _value() {
|
||||
if (this.data !== undefined) {
|
||||
return this.data;
|
||||
}
|
||||
|
||||
if (!this.schema.required) {
|
||||
return this.schema.valueMin || 0;
|
||||
}
|
||||
|
||||
return (
|
||||
(this.schema.description?.suggested_value !== undefined &&
|
||||
this.schema.description?.suggested_value !== null) ||
|
||||
this.schema.default ||
|
||||
this.schema.valueMin ||
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
private _handleCheckboxChange(ev: HASSDomTargetEvent<HaCheckbox>) {
|
||||
const checked = (ev.target as HaCheckbox).checked;
|
||||
let value: HaFormIntegerData | undefined;
|
||||
|
||||
@@ -112,9 +112,6 @@ export class HaGenericPicker extends PickerMixin(LitElement) {
|
||||
|
||||
@property({ type: Boolean, attribute: "no-sort" }) public noSort = false;
|
||||
|
||||
@property({ attribute: "pin-block" })
|
||||
public pinBlock?: "start" | "center" | "end" | "nearest";
|
||||
|
||||
// Skip the "unknown value" highlight and note for a value that is not in the
|
||||
// list but that the value renderer presents on its own.
|
||||
@property({ type: Boolean, attribute: "no-unknown-state" })
|
||||
@@ -350,7 +347,6 @@ export class HaGenericPicker extends PickerMixin(LitElement) {
|
||||
.searchKeys=${this.searchKeys}
|
||||
.customValueLabel=${this.customValueLabel}
|
||||
.noSort=${this.noSort}
|
||||
.pinBlock=${this.pinBlock}
|
||||
></ha-picker-combo-box>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -26,11 +26,7 @@ export class HaHelpTooltip extends LitElement {
|
||||
protected render(): TemplateResult {
|
||||
return html`
|
||||
<ha-svg-icon id="svg-icon" .path=${mdiHelpCircleOutline}></ha-svg-icon>
|
||||
<ha-tooltip
|
||||
trigger="hover focus click"
|
||||
for="svg-icon"
|
||||
.placement=${this.position}
|
||||
>
|
||||
<ha-tooltip for="svg-icon" .placement=${this.position}>
|
||||
${this.label}
|
||||
</ha-tooltip>
|
||||
`;
|
||||
|
||||
@@ -12,7 +12,6 @@ import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { nextRender } from "../common/util/render-status";
|
||||
import { fetchStreamUrl } from "../data/camera";
|
||||
import { apiContext, configContext, connectionContext } from "../data/context";
|
||||
import { isExternal } from "../data/external";
|
||||
import "./ha-alert";
|
||||
|
||||
type HlsLite = Omit<
|
||||
@@ -72,7 +71,7 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
@state() private _errorIsFatal = false;
|
||||
|
||||
private _url?: string;
|
||||
@state() private _url!: string;
|
||||
|
||||
private _hlsPolyfillInstance?: HlsLite;
|
||||
|
||||
@@ -82,22 +81,12 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
private _hiddenCleanupTimeout?: number;
|
||||
|
||||
// Increased on every clean up, so a start that is still waiting on the
|
||||
// network knows it is outdated
|
||||
private _cleanUpCount = 0;
|
||||
|
||||
private _handleVisibilityChange = () => {
|
||||
if (document.pictureInPictureElement) {
|
||||
// video is playing in picture-in-picture mode, don't do anything
|
||||
return;
|
||||
}
|
||||
if (document.hidden) {
|
||||
if (isExternal) {
|
||||
// The companion apps pause JavaScript timers while in the background,
|
||||
// so a delayed clean up would not run until the app is opened again
|
||||
this._cleanUp();
|
||||
return;
|
||||
}
|
||||
this._hiddenCleanupTimeout = window.setTimeout(() => {
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
this._cleanUp();
|
||||
@@ -107,7 +96,8 @@ class HaHLSPlayer extends LitElement {
|
||||
clearTimeout(this._hiddenCleanupTimeout);
|
||||
this._hiddenCleanupTimeout = undefined;
|
||||
} else {
|
||||
this._restartHls();
|
||||
this._resetError();
|
||||
this._startHls();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -115,7 +105,8 @@ class HaHLSPlayer extends LitElement {
|
||||
super.connectedCallback();
|
||||
HaHLSPlayer.streamCount += 1;
|
||||
if (this.hasUpdated) {
|
||||
this._restartHls();
|
||||
this._resetError();
|
||||
this._startHls();
|
||||
}
|
||||
document.addEventListener("visibilitychange", this._handleVisibilityChange);
|
||||
}
|
||||
@@ -180,44 +171,24 @@ class HaHLSPlayer extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts the stream again, replacing a start that is still pending. */
|
||||
private _restartHls() {
|
||||
if (this.entityid) {
|
||||
// The stream URL stops working once the stream has been idle for a while
|
||||
this._getStreamUrlFromEntityId();
|
||||
return;
|
||||
}
|
||||
this._cleanUp();
|
||||
this._resetError();
|
||||
this._startHls();
|
||||
}
|
||||
|
||||
private async _getStreamUrlFromEntityId(): Promise<void> {
|
||||
this._cleanUp();
|
||||
this._resetError();
|
||||
this._url = undefined;
|
||||
|
||||
if (!isComponentLoaded(this._config.config, "stream")) {
|
||||
this._setFatalError("Streaming component is not loaded.");
|
||||
return;
|
||||
}
|
||||
|
||||
const entityId = this.entityid;
|
||||
if (!entityId) {
|
||||
if (!this.entityid) {
|
||||
return;
|
||||
}
|
||||
const cleanUpCount = this._cleanUpCount;
|
||||
try {
|
||||
const { url } = await fetchStreamUrl(
|
||||
{ callWS: this._api.callWS, hassUrl: this._connection.hassUrl },
|
||||
entityId
|
||||
this.entityid
|
||||
);
|
||||
|
||||
if (cleanUpCount !== this._cleanUpCount) {
|
||||
// Removed, hidden or switched camera while fetching
|
||||
return;
|
||||
}
|
||||
|
||||
this._url = this._connection.hassUrl(url);
|
||||
this._cleanUp();
|
||||
this._resetError();
|
||||
@@ -227,27 +198,18 @@ class HaHLSPlayer extends LitElement {
|
||||
// eslint-disable-next-line
|
||||
console.error(err);
|
||||
|
||||
if (cleanUpCount !== this._cleanUpCount || entityId !== this.entityid) {
|
||||
// Removed, hidden or switched camera while fetching
|
||||
return;
|
||||
}
|
||||
fireEvent(this, "streams", { hasAudio: false, hasVideo: false });
|
||||
}
|
||||
}
|
||||
|
||||
private async _startHls(): Promise<void> {
|
||||
const url = this._url;
|
||||
if (!url) {
|
||||
return;
|
||||
}
|
||||
const cleanUpCount = this._cleanUpCount;
|
||||
const masterPlaylistPromise = fetch(url);
|
||||
const masterPlaylistPromise = fetch(this._url);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
const Hls: typeof HlsType = (await import("hls.js/dist/hls.light.mjs"))
|
||||
.default;
|
||||
|
||||
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
|
||||
if (!this.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -269,7 +231,7 @@ class HaHLSPlayer extends LitElement {
|
||||
this.allowExoPlayer && this._config.auth.external?.config.hasExoPlayer;
|
||||
const masterPlaylist = await (await masterPlaylistPromise).text();
|
||||
|
||||
if (cleanUpCount !== this._cleanUpCount || !this.isConnected) {
|
||||
if (!this.isConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -285,9 +247,9 @@ class HaHLSPlayer extends LitElement {
|
||||
let playlist_url: string;
|
||||
if (match !== null && matchTwice === null) {
|
||||
// Only send the regular playlist url if we match exactly once
|
||||
playlist_url = new URL(match[3], url).href;
|
||||
playlist_url = new URL(match[3], this._url).href;
|
||||
} else {
|
||||
playlist_url = url;
|
||||
playlist_url = this._url;
|
||||
}
|
||||
|
||||
const codecs = match ? `${match[1]},${match[2]}` : undefined;
|
||||
@@ -425,17 +387,12 @@ class HaHLSPlayer extends LitElement {
|
||||
|
||||
private async _renderHLSNative(videoEl: HTMLVideoElement, url: string) {
|
||||
videoEl.src = url;
|
||||
videoEl.addEventListener(
|
||||
"loadedmetadata",
|
||||
() => {
|
||||
videoEl.play();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
videoEl.addEventListener("loadedmetadata", () => {
|
||||
videoEl.play();
|
||||
});
|
||||
}
|
||||
|
||||
private _cleanUp() {
|
||||
this._cleanUpCount++;
|
||||
if (this._hlsPolyfillInstance) {
|
||||
this._hlsPolyfillInstance.destroy();
|
||||
this._hlsPolyfillInstance = undefined;
|
||||
|
||||
@@ -214,19 +214,15 @@ class HaHsColorPicker extends LitElement {
|
||||
this._mc.add(new Tap({ event: "singletap" }));
|
||||
|
||||
let savedPosition;
|
||||
let savedValue: [number, number] | undefined;
|
||||
this._mc.on("panstart", (e) => {
|
||||
if (this.disabled) return;
|
||||
this._pressed = e.pointerType;
|
||||
savedPosition = this._cursorPosition;
|
||||
savedValue = this._localValue;
|
||||
});
|
||||
this._mc.on("pancancel", () => {
|
||||
if (this.disabled) return;
|
||||
this._pressed = undefined;
|
||||
this._cursorPosition = savedPosition;
|
||||
this._localValue = savedValue;
|
||||
fireEvent(this, "cursor-moved", { value: undefined });
|
||||
});
|
||||
this._mc.on("panmove", (e) => {
|
||||
if (this.disabled) return;
|
||||
@@ -287,14 +283,13 @@ class HaHsColorPicker extends LitElement {
|
||||
const x = e.center.x;
|
||||
const y = e.center.y;
|
||||
const boundingRect = e.target.getBoundingClientRect();
|
||||
// The wheel is drawn as a centered square (object-fit: contain), but the
|
||||
// canvas box itself is not always square (e.g. wider in Safari).
|
||||
const size = Math.min(boundingRect.width, boundingRect.height);
|
||||
const centerX = boundingRect.left + boundingRect.width / 2;
|
||||
const centerY = boundingRect.top + boundingRect.height / 2;
|
||||
const offsetX = boundingRect.left;
|
||||
const offsetY = boundingRect.top;
|
||||
const maxX = e.target.clientWidth;
|
||||
const maxY = e.target.clientHeight;
|
||||
|
||||
const _x = (2 * (x - centerX)) / size;
|
||||
const _y = (2 * (y - centerY)) / size;
|
||||
const _x = (2 * (x - offsetX)) / maxX - 1;
|
||||
const _y = (2 * (y - offsetY)) / maxY - 1;
|
||||
|
||||
const [r, phi] = xy2polar(_x, _y);
|
||||
const [xx, yy] = polar2xy(Math.min(1, r), phi);
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
|
||||
import type { PropertyValues, TemplateResult } from "lit";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { LitElement, css, html } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators";
|
||||
import { customElement, property } from "lit/decorators";
|
||||
import memoizeOne from "memoize-one";
|
||||
import { consumeLocalize } from "../common/decorators/consume-context-entry";
|
||||
import { fireEvent } from "../common/dom/fire_event";
|
||||
import { caseInsensitiveStringCompare } from "../common/string/compare";
|
||||
import type { LocalizeFunc } from "../common/translations/localize";
|
||||
import { customIcons } from "../data/custom_icons";
|
||||
import type { ValueChangedEvent } from "../types";
|
||||
import "./ha-combo-box-item";
|
||||
import "./ha-generic-picker";
|
||||
import type { HaGenericPicker } from "./ha-generic-picker";
|
||||
import "./ha-icon";
|
||||
import type { PickerComboBoxItem } from "./ha-picker-combo-box";
|
||||
|
||||
@@ -54,17 +50,16 @@ const createIconItem = (icon: IconData, prefix: string): PickerComboBoxItem => {
|
||||
const loadIcons = async () => {
|
||||
ICONS_LOADED = true;
|
||||
|
||||
const sortIcons = (icons: PickerComboBoxItem[]) =>
|
||||
icons.sort((a, b) => caseInsensitiveStringCompare(a.id, b.id));
|
||||
|
||||
const iconList = await import("../../build/mdi/iconList.json");
|
||||
const mdiIcons = iconList.default.map((icon) => createIconItem(icon, "mdi"));
|
||||
ICONS = sortIcons([...mdiIcons]);
|
||||
ICONS = iconList.default.map((icon) => createIconItem(icon, "mdi"));
|
||||
|
||||
const customIconItems = await Promise.all(
|
||||
Object.keys(customIcons).map(loadCustomIconItems)
|
||||
);
|
||||
ICONS = sortIcons([...mdiIcons, ...customIconItems.flat()]);
|
||||
const customIconLoads: Promise<PickerComboBoxItem[]>[] = [];
|
||||
Object.keys(customIcons).forEach((iconSet) => {
|
||||
customIconLoads.push(loadCustomIconItems(iconSet));
|
||||
});
|
||||
(await Promise.all(customIconLoads)).forEach((customIconItems) => {
|
||||
ICONS.push(...customIconItems);
|
||||
});
|
||||
};
|
||||
|
||||
const loadCustomIconItems = async (
|
||||
@@ -86,8 +81,8 @@ const loadCustomIconItems = async (
|
||||
|
||||
const rowRenderer: RenderItemFunction<PickerComboBoxItem> = (item) => html`
|
||||
<ha-combo-box-item>
|
||||
<ha-icon .icon=${item.icon ?? item.id} slot="start"></ha-icon>
|
||||
${item.icon ?? item.id}
|
||||
<ha-icon .icon=${item.id} slot="start"></ha-icon>
|
||||
${item.id}
|
||||
</ha-combo-box-item>
|
||||
`;
|
||||
|
||||
@@ -109,32 +104,12 @@ export class HaIconPicker extends LitElement {
|
||||
|
||||
@property({ type: Boolean }) public invalid = false;
|
||||
|
||||
@property({ attribute: false }) public suggestedIcons?: string[];
|
||||
|
||||
@state() @consumeLocalize() private _localize!: LocalizeFunc;
|
||||
|
||||
@query("ha-generic-picker") private _picker?: HaGenericPicker;
|
||||
|
||||
private _getIconPickerItems = () =>
|
||||
this._itemsWithSuggestions(ICONS, this.suggestedIcons, this._localize);
|
||||
|
||||
protected updated(changedProps: PropertyValues) {
|
||||
super.updated(changedProps);
|
||||
if (changedProps.has("suggestedIcons") || changedProps.has("_localize")) {
|
||||
this._picker?.refreshItems();
|
||||
}
|
||||
}
|
||||
private _getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
|
||||
|
||||
protected render(): TemplateResult {
|
||||
return html`
|
||||
<ha-generic-picker
|
||||
allow-custom-value
|
||||
no-sort
|
||||
.pinBlock=${
|
||||
this.value && this.suggestedIcons?.includes(this.value)
|
||||
? "end"
|
||||
: undefined
|
||||
}
|
||||
.getItems=${this._getIconPickerItems}
|
||||
.helper=${this.helper}
|
||||
.disabled=${this.disabled}
|
||||
@@ -153,35 +128,15 @@ export class HaIconPicker extends LitElement {
|
||||
`;
|
||||
}
|
||||
|
||||
private _itemsWithSuggestions = memoizeOne(
|
||||
(
|
||||
icons: PickerComboBoxItem[],
|
||||
suggestedIcons: string[] | undefined,
|
||||
localize: LocalizeFunc
|
||||
): (PickerComboBoxItem | string)[] => {
|
||||
if (!suggestedIcons?.length) {
|
||||
return icons;
|
||||
}
|
||||
const suggested = new Set(suggestedIcons);
|
||||
return [
|
||||
localize("ui.components.icon_picker.suggested"),
|
||||
...suggestedIcons.map((icon) => ({ id: icon, primary: icon, icon })),
|
||||
localize("ui.components.icon_picker.all_icons"),
|
||||
...icons.filter((item) => !suggested.has(item.id)),
|
||||
];
|
||||
}
|
||||
);
|
||||
|
||||
// Filter can take a significant chunk of frame (up to 3-5 ms)
|
||||
private _filterIcons = memoizeOne(
|
||||
(
|
||||
filter: string,
|
||||
filteredItems: PickerComboBoxItem[],
|
||||
_allItems: PickerComboBoxItem[]
|
||||
allItems: PickerComboBoxItem[]
|
||||
): PickerComboBoxItem[] => {
|
||||
const normalizedFilter = filter.toLowerCase().replace(/\s+/g, "-");
|
||||
// The full list also holds the suggestions and their section titles
|
||||
const iconItems = ICONS.length ? ICONS : filteredItems;
|
||||
const iconItems = allItems?.length ? allItems : filteredItems;
|
||||
|
||||
if (!normalizedFilter.length) {
|
||||
return iconItems;
|
||||
@@ -220,7 +175,8 @@ export class HaIconPicker extends LitElement {
|
||||
protected firstUpdated() {
|
||||
if (!ICONS_LOADED) {
|
||||
loadIcons().then(() => {
|
||||
this._picker?.refreshItems();
|
||||
this._getIconPickerItems = (): PickerComboBoxItem[] => ICONS;
|
||||
this.requestUpdate();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -406,8 +406,6 @@ export class HaItemDisplayEditor extends LitElement {
|
||||
cursor: move;
|
||||
padding: 8px;
|
||||
margin: -8px;
|
||||
/* Keep the handle above the row's hit area so dragging can start */
|
||||
z-index: 1;
|
||||
}
|
||||
.separator {
|
||||
width: 1px;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { ListItemBase } from "@material/mwc-list/mwc-list-item-base";
|
||||
import { styles } from "@material/mwc-list/mwc-list-item.css";
|
||||
import type { CSSResultGroup } from "lit";
|
||||
import { css } from "lit";
|
||||
import { customElement } from "lit/decorators";
|
||||
|
||||
@customElement("ha-list-item")
|
||||
export class HaListItem extends ListItemBase {
|
||||
protected renderRipple() {
|
||||
if (this.noninteractive) {
|
||||
return "";
|
||||
}
|
||||
return super.renderRipple();
|
||||
}
|
||||
|
||||
static get styles(): CSSResultGroup {
|
||||
return [
|
||||
styles,
|
||||
css`
|
||||
:host {
|
||||
padding-left: var(
|
||||
--mdc-list-side-padding-left,
|
||||
var(--mdc-list-side-padding, 20px)
|
||||
);
|
||||
padding-inline-start: var(
|
||||
--mdc-list-side-padding-left,
|
||||
var(--mdc-list-side-padding, 20px)
|
||||
);
|
||||
padding-right: var(
|
||||
--mdc-list-side-padding-right,
|
||||
var(--mdc-list-side-padding, 20px)
|
||||
);
|
||||
padding-inline-end: var(
|
||||
--mdc-list-side-padding-right,
|
||||
var(--mdc-list-side-padding, 20px)
|
||||
);
|
||||
}
|
||||
:host([graphic="avatar"]:not([twoLine])),
|
||||
:host([graphic="icon"]:not([twoLine])) {
|
||||
height: 48px;
|
||||
}
|
||||
span.material-icons:first-of-type {
|
||||
margin-inline-start: 0px !important;
|
||||
margin-inline-end: var(
|
||||
--mdc-list-item-graphic-margin,
|
||||
16px
|
||||
) !important;
|
||||
direction: var(--direction) !important;
|
||||
}
|
||||
span.material-icons:last-of-type {
|
||||
margin-inline-start: auto !important;
|
||||
margin-inline-end: 0px !important;
|
||||
direction: var(--direction) !important;
|
||||
}
|
||||
.mdc-deprecated-list-item__meta {
|
||||
display: var(--mdc-list-item-meta-display);
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
:host([graphic="icon"]:not([twoline]))
|
||||
.mdc-deprecated-list-item__graphic {
|
||||
margin-inline-end: var(
|
||||
--mdc-list-item-graphic-margin,
|
||||
20px
|
||||
) !important;
|
||||
}
|
||||
:host([multiline-secondary]) {
|
||||
height: auto;
|
||||
}
|
||||
:host([multiline-secondary]) .mdc-deprecated-list-item__text {
|
||||
padding: 8px 0;
|
||||
}
|
||||
:host([multiline-secondary]) .mdc-deprecated-list-item__secondary-text {
|
||||
text-overflow: initial;
|
||||
white-space: normal;
|
||||
overflow: auto;
|
||||
display: inline-block;
|
||||
margin-top: 10px;
|
||||
}
|
||||
:host([multiline-secondary]) .mdc-deprecated-list-item__primary-text {
|
||||
margin-top: 10px;
|
||||
}
|
||||
:host([multiline-secondary])
|
||||
.mdc-deprecated-list-item__secondary-text::before {
|
||||
display: none;
|
||||
}
|
||||
:host([multiline-secondary])
|
||||
.mdc-deprecated-list-item__primary-text::before {
|
||||
display: none;
|
||||
}
|
||||
:host([disabled]) {
|
||||
color: var(--disabled-text-color);
|
||||
}
|
||||
:host([noninteractive]) {
|
||||
pointer-events: unset;
|
||||
}
|
||||
`,
|
||||
// safari workaround - must be explicit
|
||||
document.dir === "rtl"
|
||||
? css`
|
||||
span.material-icons:first-of-type,
|
||||
span.material-icons:last-of-type {
|
||||
direction: rtl !important;
|
||||
--direction: rtl;
|
||||
}
|
||||
`
|
||||
: css``,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"ha-list-item": HaListItem;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 547 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user