Compare commits

..
Author SHA1 Message Date
Maarten Lakerveld da3977e061 Let users hide entities from the lights page
Move the lights panel onto HaHomeSummaryPanelBase, which brings a light hidden list in system data, config loading and the edit mode the climate and maintenance pages have. In edit mode the strategy sets `hideable` metadata on its tiles; the toggle groups and heading buttons have none, so they stay inert. It also drops the panel's leftover min-height: 100vh, which overflowed the top app bar's scroll area.

Hidden lights leave the page's tiles, the desktop toggle group and the mobile area on/off buttons. Those buttons now target the visible lights instead of the whole area, so they match the toggle group. A visible light group still switches all its members, hidden or not.

The Home overview's light badge and on count skip hidden lights too, and so does the Lights section of area pages, whose on/off buttons get the same visible-lights target.
2026-11-30 15:36:21 +01:00
Maarten Lakerveld 99edd37944 Let users hide entities from the climate page
Give the climate page a hidden list in system data by moving it onto the summary panel base, so it gets the same edit mode as maintenance. In edit mode the strategy sets `hideable` metadata on every tile it generates. The climate resolver also covers the area temperature and humidity sensors, which the page adds outside the entity filters, so they can be hidden too and the Home climate badge skips them.

The visible area sensor map is built once with the hidden list applied, so the page and the Home badge share one rule. Temperature and humidity tiles are labelled from the area slot they fill instead of reading device_class back off the state, which produced an empty name for sensors set through the API without a device class.
2026-11-30 15:36:20 +01:00
Maarten Lakerveld 4171b95acb Hide maintenance entities through Lovelace edit mode
Admins can hide entities from the maintenance page and the Home maintenance summary. The hidden ids are stored as the strategy's `hidden` option in frontend system data. The maintenance panel becomes a subclass of a new HaHomeSummaryPanelBase that holds loading, saving and edit mode, so the climate and lights pages can reuse them.

The pencil turns on real Lovelace edit mode, and the panel hands hui-view the strategy view instead of a generated one. Lovelace already knows which content a strategy generated: sections view, header, footer, sidebar and badges now skip their layout tools for a strategy view, its sections count as strategy content, and its cards aren't previewed.

In edit mode a strategy can set `metadata` on the cards it generates, only for the controls that apply. The maintenance tiles get `{ id, hideable: true }`, and grid sections wrap such cards in a show/hide toggle that fires `item-visibility-changed`. Other generated cards are inert while editing. While editing, the panel leaves `hidden` out so hidden tiles show, dimmed from `lovelace.hiddenIds`.

The panel sets `strategyEditSupport` on Lovelace to say it applies these controls. Only then does hui-view pass `editMode` to the view strategy and regenerate it when edit mode changes, and only then do grid sections show the toggles and make the other generated cards inert. A strategy view on a regular dashboard gets no controls that nothing would save.

A toggle saves and hands the view a new Lovelace object with the same config, so nothing rebuilds and focus stays on the toggle.

The view container now uses min-height: 100%, the value the climate and lights panels get once they move onto the base.

This replaces #55610, reverted in #55979, which faked edit mode with an entity-visibility wrapper card that any YAML dashboard could use.
2026-11-30 15:36:20 +01:00
878 changed files with 9322 additions and 27845 deletions

No files matched your search

@@ -108,5 +108,3 @@ Panels commonly extend `SubscribeMixin(LitElement)` and receive route and narrow
Lovelace cards should implement `LovelaceCard`, validate config in `setConfig()`, handle loading, error, unavailable, and missing-entity states, and add a configuration editor when needed.
Cards are user-story surfaces. Support different households, entity types, responsive layouts, and accessible interaction states.
A new card, badge, or card feature, or a change to their options, needs documentation in other repositories. Follow "Documentation Elsewhere" in `ha-frontend-review`.
+2 -4
View File
@@ -44,8 +44,6 @@ Lazy contexts subscribe on first consumer and tear down after the last consumer:
The single-field contexts such as `localizeContext`, `themesContext`, and `userContext` are deprecated. Use grouped contexts instead.
Custom cards request contexts by key with a `context-request` event, as the custom card documentation on contributors.home-assistant.io describes, so the keys in `src/data/context/index.ts` and their values are a public API. Renaming or removing a key, changing its value, or dropping a deprecated context breaks them. A change to how card, badge, or feature hosts pass data, such as no longer setting `hass` or offering a new context, changes what custom cards should do too. For both, follow "Documentation Elsewhere" in `ha-frontend-review`.
## Consumption Patterns
Import `consume` from `src/common/decorators/consume`, not from `@lit/context`. The `@lit/context` version forces a host update on every context change, so every consumed field rerenders the component, even without `@state()`, and `@transform` cannot skip anything. Our `consume` leaves update scheduling to the field:
@@ -62,7 +60,7 @@ Use entity-scoped helpers when the component watches an entity ID held on the ho
```ts
@state() @consumeEntityState({ entityIdPath: ["_config", "entity"] })
private _stateObj?: HassEntityState;
private _stateObj?: HassEntity;
@state() @consumeEntityRegistryEntry({ entityIdPath: ["_config", "entity"] })
private _entity?: EntityRegistryDisplayEntry;
@@ -75,7 +73,7 @@ Use `consumeEntityStates` when the host property contains one or more entity IDs
```ts
@state() @consumeEntityStates({ entityIdPath: ["_config", "entities"] })
private _stateObjs?: Record<string, HassEntityState>;
private _stateObjs?: Record<string, HassEntity>;
```
For a single field from a grouped context, pair `@consume` with `@transform`:
+1 -11
View File
@@ -1,6 +1,6 @@
---
name: ha-frontend-demo
description: Home Assistant standalone demo structure, configurations, URL navigation, mocked APIs, shared demo stubs used by gallery, the embed other sites use, and verification. Use when changing files under demo/, including demo/src/embed/, changing gallery consumers of demo/src/stubs/, or running and validating the demo.
description: Home Assistant standalone demo structure, configurations, URL navigation, mocked APIs, shared demo stubs used by gallery, and verification. Use when changing files under demo/, changing gallery consumers of demo/src/stubs/, or running and validating the demo.
---
# HA Frontend Demo
@@ -52,7 +52,6 @@ http://localhost:8090/?demo=<second slug>#/energy/water
- `demo/src/configs/<slug>/`: One directory per demo configuration, containing entities, dashboard, and theme data.
- `demo/src/configs/demo-configs.ts`: Registry of demo configurations and URL slug handling.
- `demo/src/stubs/`: Mocked WebSocket and REST APIs.
- `demo/src/embed/`: The embed, built as `embed.js`. Its `ha-embed-*` elements put cards, sections, views, and dashboards on other sites, against a mocked backend.
- `demo/script/develop_demo`, `demo/script/build_demo`: Development server and static build wrappers.
## Core Data
@@ -65,15 +64,6 @@ The service descriptions in `src/fake_data/demo_services.ts` and the trigger and
The two consumers use a stub differently, so demo behavior does not predict gallery behavior. A gallery page calls stubs against the `hass` from `provideHass`, where `hass.config` is the shared `demoConfig` object. A stub that mutates `hass.config` in place is therefore visible to the page. `demo/src/ha-demo.ts` copies `components` into a new array before the stubs run, so the same mutation never reaches the demo. A change can look correct in the demo while quietly breaking a gallery page.
## Embed
The embed puts parts of the dashboard on any web page, against a mocked backend: a single card with `ha-embed-card`, a section with `ha-embed-section`, a view with `ha-embed-view`, and a whole dashboard with `ha-embed-dashboard`. An `ha-embed-provider` holds the entities and other data they share. The live dashboard demos on home-assistant.io use it, and so can card authors, following the embed's page on contributors.home-assistant.io. Treat the `ha-embed-*` element names, their attributes, and the data the provider takes as a public API.
- `demo/src/html/components.html.template` documents the embed, at `/components.html` of the demo. Update it in the same pull request as an embed change.
- The provider takes most of its mocks from `demo/src/stubs/`, so a stub change reaches the embed as well as the demo and the gallery.
- demo.home-assistant.io deploys from `master`, and the development demo from `dev` (`.github/workflows/demo_deployment.yaml`), so other sites get an embed change only once it is released.
- When the embed's elements or data change, or a change alters what a live demo can show, follow "Documentation Elsewhere" in `ha-frontend-review`.
## Verification
Load `ha-frontend-testing` and use its demo and gallery workflows. Validate both consumers when changing shared stubs. Documentation-only changes do not require code tests unless examples or commands change.
+1 -21
View File
@@ -10,7 +10,6 @@ Use this skill for every loading state, following the [Loading pattern](https://
## Pick The Indicator
- Use a skeleton from `src/components/skeleton/` (`ha-skeleton`, `ha-skeleton-text`, `ha-skeleton-icon`, `ha-skeleton-log`) when content loads into a layout you already know, such as table rows, tile text, or a log. It holds the layout, so nothing jumps when the content arrives.
- Use `ha-skeleton-overlay` when the content renders before its data arrives, such as a card or badge, or when content reloads over what's already shown. See [Skeleton Overlay](#skeleton-overlay).
- Use `ha-spinner` only when a whole area loads and its shape is unknown.
- Use `ha-button` with `loading`, or `ha-progress-button`, for an action started from a button. Don't put a separate spinner next to it.
@@ -28,7 +27,7 @@ Wrap the indicator in `ha-fade-in` from `src/components/animation/ha-fade-in.ts`
- Fade a skeleton in straight away over about 300ms (`.duration=${300}`), as the data table does. It stands in for the content, so a delay would leave an empty gap.
- Delay a spinner or progress bar, usually by `.delay=${500}`, so a load that finishes within that time never flashes it. Some slower areas, such as backups and updates, use `${1000}`.
- Content that takes a skeleton's place fades in over `--ha-animation-duration-fast`, which reduced motion makes instant. `ha-skeleton-overlay` does this for you. Elsewhere, use `skeletonOr(loading, skeleton, () => content)` from `src/components/skeleton/skeleton-arrival.ts`: it shows the skeleton while loading and fades the content in once when it replaces it, but not where no skeleton showed, such as table rows made as the table scrolls. Put text in an element of its own inside the content, as only elements fade. For content that fills in where it already is, such as a log, call `fadeInArrival(element)` once when its skeleton goes. Don't add any other fade to loaded content.
- Don't fade in the loaded content itself.
Give a skeleton group the `progressbar` role and a translated label, as `ha-spinner` has, rather than visible "Loading" text.
@@ -46,24 +45,6 @@ html`
`;
```
## Skeleton Overlay
`ha-skeleton-overlay` reads a skeleton from the content it wraps, so it can't drift from it: each text line, icon, image, control and drawing gets its own piece, and the real parts are hidden underneath until loading ends. Prefer it to drawing a skeleton by hand whenever the content can render before its data.
```ts
html`
<ha-skeleton-overlay .loading=${this._loading}>
<my-content></my-content>
</ha-skeleton-overlay>
`;
```
- Turn it on with `loading`, or fire `skeleton-loading` (`{ loading: true }`, later `{ loading: false }`) from inside the content. The event stops at the nearest overlay, so content doesn't need to know what wraps it.
- Mark parts that shouldn't be read with `data-skeleton`: `none` leaves an element out and showing, `keep` leaves it showing but reads what's inside, and `text`, `round` or `block` force one piece of that kind. Skeletons the content draws itself are left alone.
- Put your own skeleton in the `skeleton` slot to replace the reading altogether.
- Call `refresh()` when the content changes without changing size.
- It gives the skeleton the `progressbar` role and the translated label itself.
## Checking It
Check a loading state in the browser, not only by reading the code. These work on any setup: a dev server, the demo, or the gallery.
@@ -90,6 +71,5 @@ Check a loading state in the browser, not only by reading the code. These work o
};
```
- **Compare the skeleton with the content.** It should take the same space, so nothing moves when the content arrives. Measure the wrapper's height while loading and once loaded (`element.getBoundingClientRect().height` in the console), or take a screenshot of each at the same size and flick between them. Look for pieces that are missing, extra or in the wrong place, and fix those with `data-skeleton`.
- **Compare before and after.** Take screenshots of the same screen on `dev` and on your branch, at the same viewport size, both loading and loaded, and put them side by side. In a pull request, show both.
- **Check every look.** Light and dark themes, a right-to-left language (the wave starts from the right), reduced motion (DevTools, Rendering, "Emulate CSS media feature prefers-reduced-motion": the wave stops), and a phone width (DevTools device toolbar).
+1 -15
View File
@@ -1,6 +1,6 @@
---
name: ha-frontend-review
description: Home Assistant frontend PR and review guidance, including implementation quality, existing review feedback, established design patterns, the authority of UI/UX evidence, and documentation needed in other repositories. Use when reviewing frontend changes, preparing a PR, checking recurring review issues, applying the PR template, or working out which docs a change needs.
description: Home Assistant frontend PR and review guidance, including implementation quality, existing review feedback, established design patterns, and the authority of UI/UX evidence. Use when reviewing frontend changes, preparing a PR, checking recurring review issues, or applying the PR template.
---
# HA Frontend Review
@@ -24,19 +24,6 @@ When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the body
- Explain what the change does for users, not only implementation details.
- Use Markdown.
## Documentation Elsewhere
A frontend change that adds or changes something users see or configure, or an API others build on, needs companion documentation in the user or contributor docs, or the docs miss it. Spot this while making the change, and recommend the documentation changes it needs.
- home-assistant.io documents what users see and configure: a new card, badge, card feature, or heading entity; a new, changed, or removed option or default; a renamed label or menu path; and anything visible that its pages show, in screenshots or in live demos of the demo embed.
- contributors.home-assistant.io documents the design of components and cards in its Design area, and the APIs that custom cards, badges, card features, strategies, and themes use. When a change touches something they could rely on, search its custom UI and Marketplace pages for it. Announce a removal or rename there in a blog post.
To make the change:
- Read the other repository's agent instructions and skills first, and follow them for where and how the change goes.
- Docs follow what people can use. User docs can wait until a feature is usable, such as the last pull request of a stack, and an API still being tried out may stay undocumented, so recommend the docs.
- When a documentation pull request goes with a frontend one, link them to each other, and say in the description when one needs the other merged first.
## Pre-Submission Checklist
- `pnpm lint` passes when practical for the scope.
@@ -47,7 +34,6 @@ To make the change:
- Entity existence is checked before property access.
- Event listeners and subscriptions are cleaned up.
- UI is accessible to screen readers and keyboard users.
- Documentation the change needs in other repositories is linked.
## Recurring Review Issues
@@ -17,7 +17,6 @@ Use this skill when editing CSS, layout, visual hierarchy, theme integration, re
- Prefer `ha-*` components and current Web Awesome wrappers.
- Avoid adding new legacy Material Web Components (`mwc-*`).
- Scope styles to the component. Do not rely on global styles for component internals.
- Themes set theme variables and design tokens by name, so renaming or removing one breaks them. The theme variables reference on contributors.home-assistant.io is generated from the frontend, but its theme guides may need a change too: follow "Documentation Elsewhere" in `ha-frontend-review`.
Spacing tokens are defined in `src/resources/theme/core.globals.ts`. The scale runs from `--ha-space-1` at 4px through `--ha-space-20` at 80px in 4px increments. Common values are `--ha-space-2` at 8px, `--ha-space-4` at 16px, and `--ha-space-8` at 32px.
+1 -2
View File
@@ -20,9 +20,8 @@ runs:
steps:
- name: Build ${{ inputs.target }}
shell: bash
run: ./node_modules/.bin/gulp "$TARGET"
run: ./node_modules/.bin/gulp ${{ inputs.target }}
env:
TARGET: ${{ inputs.target }}
GITHUB_TOKEN: ${{ inputs.github-token }}
IS_TEST: ${{ inputs.is-test }}
RSPACK_CACHE: ${{ inputs.rspack-cache }}
-19
View File
@@ -40,22 +40,3 @@ jobs:
curl -sSfL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
| tar -xz actionlint
./actionlint -color
zizmor:
name: Check workflow security
runs-on: ubuntu-latest
env:
# renovate: datasource=github-releases depName=zizmorcore/zizmor
ZIZMOR_VERSION: 1.33.1
steps:
- name: Check out files from GitHub
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Run zizmor
env:
GH_TOKEN: ${{ github.token }}
run: |
curl -sSfL "https://github.com/zizmorcore/zizmor/releases/download/v${ZIZMOR_VERSION}/zizmor-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz zizmor
./zizmor --format=github .
+1 -3
View File
@@ -47,6 +47,4 @@ jobs:
site-id: ${{ secrets.NETLIFY_GALLERY_SITE_ID }}
- name: Generate summary
env:
NETLIFY_URL: ${{ steps.deploy.outputs.netlify_url }}
run: echo "$NETLIFY_URL" >> "$GITHUB_STEP_SUMMARY"
run: echo "${{ steps.deploy.outputs.netlify_url }}" >> "$GITHUB_STEP_SUMMARY"
-3
View File
@@ -2,8 +2,6 @@ name: "Pull Request Labeler"
on: pull_request_target # zizmor: ignore[dangerous-triggers] -- safe: checks out base repo scripts only and reads PR files through the API, never PR head code
permissions: {}
# Runs one at a time per pull request, so an older run can't undo a newer one
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}
@@ -15,7 +13,6 @@ jobs:
contents: read
pull-requests: write
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Apply labels
id: labeler
@@ -20,7 +20,6 @@ jobs:
check:
name: Check pull request follows contribution standards
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
pull-requests: write # To label and comment on pull requests
steps:
+1 -1
View File
@@ -1 +1 @@
24.23.0
24.22.3
+2 -4
View File
@@ -49,14 +49,12 @@ Detailed guidance lives in `.agents/skills/<name>/SKILL.md`. Load every matching
- `ha-frontend-testing`: lint, typecheck, Vitest, Playwright e2e dev servers, and benchmarks.
- `ha-frontend-query-params`: typed URL query params, `QueryParamsController`, data table URL sync, in-app links, and My Home Assistant redirect params.
- `ha-frontend-user-facing-text`: localization, terminology, sentence case, and Home Assistant text style.
- `ha-frontend-review`: PR template use, documentation needed in other repositories, existing review feedback, review checklist, recurring issues, and UI/UX evidence including gallery specifications.
- `ha-frontend-review`: PR template use, existing review feedback, review checklist, recurring issues, and UI/UX evidence including gallery specifications.
- `ha-frontend-ux-readiness`: UI/UX routing that complements frontend review for new user experiences.
- `ha-frontend-gallery`: gallery pages, demos, sidebar structure, content, and verification.
- `ha-frontend-demo`: standalone demo structure, configurations, navigation, shared stubs, the embed other sites use, and verification.
- `ha-frontend-demo`: standalone demo structure, configurations, navigation, shared stubs, and verification.
- `ha-frontend-browser-checks`: checking a change in a browser at real device sizes, in light and dark mode, right to left (RTL) and with long translations, and screenshots and recorded demos for pull requests.
Keep skills current with the code they describe. When a change makes a skill wrong, or adds an area no skill covers yet, update or add the skill in the same pull request, or in one stacked on it. Change skills in a pull request of their own only for a large rework.
## Pull Requests
When creating a pull request, use `.github/PULL_REQUEST_TEMPLATE.md` as the PR body. Preserve template sections, check only the appropriate type-of-change boxes, and do not check checklist items on behalf of the user. If the PR includes UI changes, add screenshots or a short video, taken as `ha-frontend-browser-checks` describes. Only ask the user to add them when you can't take them yourself.
+8
View File
@@ -28,10 +28,18 @@ 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
@@ -198,7 +198,10 @@ async function fetchTranslations(currentArtifact: Artifact | null) {
console.log("Unpacking downloaded translations...");
const zip = await jszip.loadAsync(downloadResponse.data as ArrayBuffer);
await deleteCurrent;
await extract({ input: await zip.file(/.*/)[0].async("uint8array") });
const extractStream = zip.file(/.*/)[0].nodeStream().pipe(extract());
await new Promise((resolve, reject) => {
extractStream.on("close", resolve).on("error", reject);
});
// Record the artifact only after successful extraction, so a failed fetch
// is retried by the next build instead of being considered current.
+4
View File
@@ -69,6 +69,10 @@ async function copyMapPanel(staticDir) {
npmPath("leaflet/dist/leaflet.css"),
staticPath("images/leaflet/")
);
copyFileDir(
npmPath("leaflet.markercluster/dist/MarkerCluster.css"),
staticPath("images/leaflet/")
);
fs.copySync(
npmPath("leaflet/dist/images"),
staticPath("images/leaflet/images/")
+4 -3
View File
@@ -466,9 +466,6 @@ const createRspackConfig = ({
),
}),
...componentsSourceAliases,
// elkjs isn't installed (see pnpm-workspace.yaml), so Mermaid's ELK
// layout chunk gets an empty module
"elkjs/lib/elk.bundled.js": false,
"lit/static-html$": "lit/static-html.js",
"lit/decorators$": "lit/decorators.js",
"lit/directive$": "lit/directive.js",
@@ -511,8 +508,12 @@ const createRspackConfig = ({
"@formatjs/intl-locale/should-polyfill.js",
"@formatjs/intl-locale/polyfill-force":
"@formatjs/intl-locale/polyfill-force.js",
"@formatjs/intl-numberformat/should-polyfill":
"@formatjs/intl-numberformat/should-polyfill.js",
"@formatjs/intl-numberformat/polyfill-force":
"@formatjs/intl-numberformat/polyfill-force.js",
"@formatjs/intl-pluralrules/should-polyfill":
"@formatjs/intl-pluralrules/should-polyfill.js",
"@formatjs/intl-pluralrules/polyfill-force":
"@formatjs/intl-pluralrules/polyfill-force.js",
"@formatjs/intl-relativetimeformat/should-polyfill":
+1 -2
View File
@@ -73,8 +73,7 @@ class HcLovelace extends LitElement {
if (index !== undefined) {
const title = getPanelTitleFromUrlPath(
this.hass.localize,
this.hass.panels,
this.hass,
this.urlPath || "lovelace"
);
+1 -2
View File
@@ -355,8 +355,7 @@ export class HcMain extends HassElement {
private _handleNewLovelaceConfig(lovelaceConfig: LovelaceConfig) {
const title = getPanelTitleFromUrlPath(
this.hass!.localize,
this.hass!.panels,
this.hass!,
this._urlPath || "lovelace"
);
castContext.setApplicationState(title || "");
+2 -3
View File
@@ -1,5 +1,5 @@
import { ContextProvider, provide } from "@lit/context";
import type { HassEntityStates } from "home-assistant-js-websocket";
import type { HassEntities } from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { html, LitElement } from "lit";
import { customElement, property } from "lit/decorators";
@@ -207,7 +207,6 @@ export class HaEmbedProvider extends LitElement {
}));
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
this._applyColorScheme();
@@ -317,6 +316,6 @@ declare global {
"ha-embed-provider": HaEmbedProvider;
}
interface HASSDomEvents {
"states-changed": { states: HassEntityStates };
"states-changed": { states: HassEntities };
}
}
+2 -4
View File
@@ -580,10 +580,8 @@ provider.entities = Object.values(provider.hass.states).map((entity) =&gt;
<ul>
<li>
<code>areas</code>: a list of areas, each with an
<code>area_id</code> and a <code>name</code>, and optionally an
<code>icon</code> and a <code>picture</code>, the URL of an image.
Without it, each <code>area_id</code> of the entities and devices
becomes an area.
<code>area_id</code> and a <code>name</code>. Without it, each
<code>area_id</code> of the entities and devices becomes an area.
</li>
<li>
<code>devices</code>: a list of devices, each with an
+1 -3
View File
@@ -6,8 +6,6 @@ export interface DemoArea {
name: string;
floor_id?: string;
icon?: string;
// An image URL, such as for an area card with `display_type: picture`
picture?: string;
temperature_entity_id?: string;
humidity_entity_id?: string;
}
@@ -23,7 +21,7 @@ export const toAreaRegistryEntry = (area: DemoArea): AreaRegistryEntry => ({
humidity_entity_id: area.humidity_entity_id ?? null,
aliases: [],
labels: [],
picture: area.picture ?? null,
picture: null,
created_at: 0,
modified_at: 0,
});
-67
View File
@@ -1,67 +0,0 @@
// Made-up values for the mock history and statistics that look like a real
// home and are the same on every load, so a chart doesn't change each time
// the page opens.
const HOUR = 60 * 60 * 1000;
/** A number from 0 up to 1 for each key, the same every time. */
export const hashFraction = (key: string): number => {
let hash = 0;
for (let i = 0; i < key.length; i++) {
hash = (hash * 31 + key.charCodeAt(i)) % 2147483647;
}
return hash / 2147483647;
};
/**
* How far a value drifts from its state: 10% of it, or 5% above 80, as for a
* temperature or a power reading. A state of 0 drifts by up to 1.
*/
export const driftScale = (value: number): number =>
value === 0 ? 1 : Math.abs(value) * (Math.abs(value) > 80 ? 0.05 : 0.1);
/**
* A drifted reading kept on the same side of 0 as the state, as a reading such
* as a power or a speed doesn't cross 0. A state of 0 stays at 0 or above.
*/
export const sameSideOfZero = (value: number, drifted: number): number =>
value < 0 ? Math.min(drifted, 0) : Math.max(drifted, 0);
// The point each wave starts at, kept once picked from its key, as a long
// period asks for the drift of hundreds of thousands of hours
const phases = new Map<string, number>();
const phase = (key: string): number => {
let value = phases.get(key);
if (value === undefined) {
value = 2 * Math.PI * hashFraction(key);
phases.set(key, value);
}
return value;
};
const wave = (key: string, time: number, period: number): number =>
Math.sin((2 * Math.PI * time) / period + phase(key));
/**
* The value of an entity at a time, drifting slowly around its state: a swing
* over the day and two faster, smaller ones, each starting at a point picked
* from the entity ID.
*/
export const driftedValue = (
key: string,
time: number,
value: number
): number =>
sameSideOfZero(
value,
value +
driftScale(value) *
(0.6 * wave(`${key}:day`, time, 24 * HOUR) +
0.3 * wave(`${key}:hours`, time, 5 * HOUR) +
0.1 * wave(`${key}:hour`, time, 1.3 * HOUR))
);
-3
View File
@@ -120,12 +120,10 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
stat_consumption: "sensor.gas_heat_pump",
},
],
fixed_costs: [],
};
hass.mockWS("energy/get_prefs", (): EnergyPreferences => prefs);
hass.mockWS("energy/info", (): EnergyInfo => ({
cost_sensors: {},
fixed_cost_sensors: {},
solar_forecast_domains: [],
}));
hass.mockWS("energy/validate", () => ({
@@ -133,7 +131,6 @@ export const mockEnergy = (hass: MockHomeAssistant) => {
device_consumption: prefs.device_consumption.map(() => []),
device_consumption_water: prefs.device_consumption_water.map(() => []),
device_consumption_gas: prefs.device_consumption_gas.map(() => []),
fixed_costs: prefs.fixed_costs.map(() => []),
}));
hass.mockWS(
"energy/fossil_energy_consumption",
+23 -102
View File
@@ -1,10 +1,9 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import type { HistoryStates } from "../../../src/data/history";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import { driftedValue, hashFraction } from "./drift";
const generateStateHistory = (
state: HassEntityState,
state: HassEntity,
deltas,
start_date: Date,
end_date: Date
@@ -41,76 +40,6 @@ const generateStateHistory = (
const incrementalUnits = ["clients", "queries", "ads"];
// Changes over the range of an on/off entity, ending in its state
const ON_OFF_CHANGES = 6;
// The most points of a number over the range
const NUMBER_POINTS = 96;
// An on/off entity, such as a light, switches a few times over the range, at
// times picked from its entity ID, and ends in its state
const generateOnOffHistory = (
state: HassEntityState,
start: Date,
end: Date
): HistoryStates[string] => {
const span = end.getTime() - start.getTime();
const opposite = state.state === "on" ? "off" : "on";
return Array.from({ length: ON_OFF_CHANGES }, (_, index) => {
const time =
index === 0
? start.getTime()
: start.getTime() +
(span *
(index - 0.3 + 0.6 * hashFraction(`${state.entity_id}:${index}`))) /
ON_OFF_CHANGES;
return {
a: state.attributes,
s: (ON_OFF_CHANGES - 1 - index) % 2 === 0 ? state.state : opposite,
lc: time / 1000,
lu: time / 1000,
};
});
};
// A number drifts around its state over the range, the same on every load,
// with as many decimals as its state, and ends in its state
const generateNumberHistory = (
state: HassEntityState,
value: number,
start: Date,
end: Date
): HistoryStates[string] => {
const decimals = Math.max(state.state.split(".")[1]?.length ?? 0, 1);
const step = Math.max(
(end.getTime() - start.getTime()) / NUMBER_POINTS,
5 * 60 * 1000
);
const history: HistoryStates[string] = [];
for (let time = start.getTime(); time < end.getTime(); time += step) {
history.push({
a: state.attributes,
s: driftedValue(state.entity_id, time, value).toFixed(decimals),
lc: time / 1000,
lu: time / 1000,
});
}
history.push({
a: state.attributes,
s: state.state,
lc: end.getTime() / 1000,
lu: end.getTime() / 1000,
});
return history;
};
export const mockHistory = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
"history/stream",
@@ -141,11 +70,6 @@ export const mockHistory = (mockHass: MockHomeAssistant) => {
continue;
}
if (state.state === "on" || state.state === "off") {
states[entityId] = generateOnOffHistory(state, start, end);
continue;
}
if (!state.attributes.unit_of_measurement) {
states[entityId] = generateStateHistory(
state,
@@ -168,35 +92,32 @@ export const mockHistory = (mockHass: MockHomeAssistant) => {
continue;
}
if (!incrementalUnits.includes(state.attributes.unit_of_measurement)) {
states[entityId] = generateNumberHistory(
state,
numberState,
start,
end
);
continue;
}
// A counter climbs to its state
const statesToGenerate = 15;
let genFunc;
let initial = Math.floor(
numberState * 0.4 + numberState * Math.random() * 0.2
);
const diff = Math.max(
1,
Math.floor((numberState - initial) / statesToGenerate)
);
if (incrementalUnits.includes(state.attributes.unit_of_measurement)) {
let initial = Math.floor(
numberState * 0.4 + numberState * Math.random() * 0.2
);
const diff = Math.max(
1,
Math.floor((numberState - initial) / statesToGenerate)
);
genFunc = () => {
initial += diff;
return Math.min(numberState, initial);
};
} else {
const diff = Math.floor(
numberState * (numberState > 80 ? 0.05 : 0.5)
);
genFunc = () =>
numberState - diff + Math.floor(Math.random() * 2 * diff);
}
states[entityId] = generateStateHistory(
state,
Array.from({ length: statesToGenerate }, () => {
initial += diff;
return Math.min(numberState, initial);
}),
Array.from({ length: statesToGenerate }, genFunc),
start,
end
);
-10
View File
@@ -22,14 +22,6 @@ const baseRepository = {
status: "default" as const,
};
// The names of the connectivity of the demo repositories. Home Assistant
// translates them, the mocked hass has no backend translations.
export const marketplaceBackendTranslations = {
"component.homeassistant.integration_connectivity.mqtt.name": "MQTT",
"component.homeassistant.integration_connectivity.network.name":
"Local network",
};
const repositories: RepositoryBase[] = [
{
...baseRepository,
@@ -40,7 +32,6 @@ const repositories: RepositoryBase[] = [
description: "Watch camera streams with low latency through WebRTC.",
authors: ["@AlexxIT"],
domain: "webrtc",
connectivity: ["network"],
config_flow: true,
available_version: "v3.6.1",
downloads: 98000,
@@ -77,7 +68,6 @@ const repositories: RepositoryBase[] = [
description: "Use the cameras and events of a Frigate NVR.",
authors: ["@blakeblackshear", "@dermotduffy", "@NickM-27"],
domain: "frigate",
connectivity: ["network", "mqtt"],
config_flow: true,
available_version: "v5.9.0",
installed: true,
+66 -386
View File
@@ -1,37 +1,19 @@
import { TZDate } from "@date-fns/tz";
import type { Day } from "date-fns";
import {
addDays,
addHours,
addMinutes,
addMonths,
addWeeks,
addYears,
constructFrom,
differenceInHours,
endOfDay,
startOfDay,
startOfHour,
startOfMonth,
startOfWeek,
startOfYear,
} from "date-fns";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HaDurationData } from "../../../src/components/ha-duration-input";
import type {
Statistic,
Statistics,
StatisticsMetaData,
StatisticsUnitConfiguration,
StatisticValue,
} from "../../../src/data/recorder";
import { StatisticMeanType } from "../../../src/data/recorder";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import {
driftedValue,
driftScale,
hashFraction,
sameSideOfZero,
} from "./drift";
const getFirstDate = (
start: Date,
@@ -49,57 +31,34 @@ const getNextDate = (
currentDate: Date,
period: "5minute" | "hour" | "day" | "month"
): Date => {
if (period === "day") {
return addDays(currentDate, 1);
}
if (period === "month") {
return addMonths(currentDate, 1);
}
// An hour or 5 minutes is the same length in any timezone, so a plain Date
// will do. Making a timezone date for each one is slow over a long period,
// which has hundreds of thousands of hours.
return new Date(
currentDate.getTime() + (period === "hour" ? 60 : 5) * 60 * 1000
);
return period === "day"
? addDays(currentDate, 1)
: period === "month"
? addMonths(currentDate, 1)
: period === "hour"
? addHours(currentDate, 1)
: addMinutes(currentDate, 5);
};
// The mean of each period drifts around the entity's state, as its history
// does, and the same on every load. Longer periods span more of the drift.
// The values drift in the entity's unit, then are multiplied by factor to give
// them in the unit asked for.
const generateMeanStatistics = (
id: string,
start: Date,
end: Date,
period: "5minute" | "hour" | "day" | "month" = "hour",
value: number,
factor = 1
maxDiff: number
): StatisticValue[] => {
const statistics: StatisticValue[] = [];
const spread =
driftScale(value) *
(period === "5minute" || period === "hour" ? 0.2 : 0.8) *
factor;
let currentDate = getFirstDate(start, period);
const now = new Date();
while (end > currentDate && currentDate < now) {
const delta = Math.random() * maxDiff;
const mean = delta;
const nextDate = getNextDate(currentDate, period);
const mean =
driftedValue(
id,
(currentDate.getTime() + nextDate.getTime()) / 2,
value
) * factor;
statistics.push({
start: currentDate.getTime(),
end: nextDate.getTime(),
mean,
min: sameSideOfZero(value, mean - spread),
max: sameSideOfZero(value, mean + spread),
min: mean - Math.random() * maxDiff,
max: mean + Math.random() * maxDiff,
last_reset: 0,
state: mean,
sum: null,
@@ -114,9 +73,7 @@ const generateSumStatistics = (
end: Date,
period: "5minute" | "hour" | "day" | "month" = "hour",
initValue: number,
maxDiff: number | ((start: Date, end: Date) => number),
// A number from 0 up to 1 for each period's share of maxDiff
random: (periodStart: Date) => number = () => Math.random()
maxDiff: number | ((start: Date, end: Date) => number)
): StatisticValue[] => {
const statistics: StatisticValue[] = [];
let currentDate = getFirstDate(start, period);
@@ -126,8 +83,7 @@ const generateSumStatistics = (
const nextDate = getNextDate(currentDate, period);
const bound =
typeof maxDiff === "function" ? maxDiff(currentDate, nextDate) : maxDiff;
const add = random(currentDate) * bound;
const add = Math.random() * bound;
sum += add;
statistics.push({
start: currentDate.getTime(),
@@ -416,346 +372,70 @@ const derivedBatteryFlows: Record<string, { source: string; share: number }> = {
},
};
const hasSum = (stateObj: HassEntityState | undefined): boolean =>
stateObj?.attributes.state_class === "total" ||
stateObj?.attributes.state_class === "total_increasing";
// Like Core, statistics are given in the unit asked for, such as power in kW
// for the energy dashboard while the demo's power sensors are in W
const unitFactor = (
stateObj: HassEntityState | undefined,
units?: StatisticsUnitConfiguration
): number => {
const unit = stateObj?.attributes.unit_of_measurement;
if (unit === "W" && units?.power === "kW") {
return 1 / 1000;
}
if (unit === "kW" && units?.power === "W") {
return 1000;
}
return 1;
};
const getStatistics = (
hass: MockHomeAssistant,
statisticIds: string[],
start: Date,
end: Date,
period: "5minute" | "hour" | "day" | "month",
units?: StatisticsUnitConfiguration
): Statistics => {
const statistics: Record<string, StatisticValue[]> = {};
const cache: Record<string, StatisticValue[]> = {};
const getStats = (id: string) => {
cache[id] ??= statisticsFunctions[id](id, start, end, period);
return cache[id];
};
const scaleStats = (source: string, factor: number) => {
let sum = 0;
return getStats(source).map((statistic) => {
const change = (statistic.change ?? 0) * factor;
sum += change;
return { ...statistic, change, state: sum, sum };
});
};
statisticIds.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);
} else if (id in statisticsFunctions) {
statistics[id] = getStats(id);
} else {
const entityState = hass.states[id];
// Like Core, only an entity with a state class has statistics, so the
// history of a light has no empty chart of them
if (entityState && !entityState.attributes.state_class) {
return;
}
const state = entityState ? Number(entityState.state) : 1;
// Each period's share is picked from the entity ID, so a meter's bars
// are the same on every load. The cap grows with the period's length,
// so a day's bar adds up to about 24 hours' worth.
statistics[id] = hasSum(entityState)
? generateSumStatistics(
start,
end,
period,
state,
(periodStart, periodEnd) =>
state *
(state > 80 ? 0.01 : 0.05) *
((periodEnd.getTime() - periodStart.getTime()) / 3600000),
(periodStart) => hashFraction(`${id}:${periodStart.getTime()}`)
)
: generateMeanStatistics(
id,
start,
end,
period,
state,
unitFactor(entityState, units)
);
}
});
return statistics;
};
const durationMs = (duration?: HaDurationData): number =>
duration
? ((duration.days ?? 0) * 24 + (duration.hours ?? 0)) * 3600000 +
(duration.minutes ?? 0) * 60000 +
(duration.seconds ?? 0) * 1000 +
(duration.milliseconds ?? 0)
: 0;
const WEEK_STARTS = {
sun: 0,
mon: 1,
tue: 2,
wed: 3,
thu: 4,
fri: 5,
sat: 6,
} satisfies Record<string, Day>;
interface StatisticDuringPeriodMessage {
statistic_id: string;
types?: string[];
fixed_period?: { start_time?: string; end_time?: string };
calendar?: {
period: "hour" | "day" | "week" | "month" | "year";
offset?: number;
first_weekday?: keyof typeof WEEK_STARTS;
};
rolling_window?: { duration: HaDurationData; offset?: HaDurationData };
units?: StatisticsUnitConfiguration;
}
// The start and end of the period of recorder/statistic_during_period, as
// Core reads it, in the server timezone
const statisticPeriodBounds = (
message: StatisticDuringPeriodMessage,
timeZone: string
): [Date, Date] => {
const now = new TZDate(Date.now(), timeZone);
if (message.fixed_period) {
const { start_time, end_time } = message.fixed_period;
return [
new TZDate(start_time ? Date.parse(start_time) : 0, timeZone),
new TZDate(end_time ? Date.parse(end_time) : Date.now(), timeZone),
];
}
if (message.rolling_window) {
const end = new TZDate(
now.getTime() + durationMs(message.rolling_window.offset),
timeZone
);
return [
new TZDate(
end.getTime() - durationMs(message.rolling_window.duration),
timeZone
),
end,
];
}
if (message.calendar) {
const offset = message.calendar.offset ?? 0;
switch (message.calendar.period) {
case "hour": {
const start = addHours(startOfHour(now), offset);
return [start, addHours(start, 1)];
}
case "week": {
const weekStartsOn =
WEEK_STARTS[message.calendar.first_weekday ?? "mon"];
const start = addWeeks(startOfWeek(now, { weekStartsOn }), offset);
return [start, addWeeks(start, 1)];
}
case "month": {
const start = addMonths(startOfMonth(now), offset);
return [start, addMonths(start, 1)];
}
case "year": {
const start = addYears(startOfYear(now), offset);
return [start, addYears(start, 1)];
}
default: {
const start = addDays(startOfDay(now), offset);
return [start, addDays(start, 1)];
}
}
}
// All the history, which the mock makes up for the last day
return [addDays(now, -1), now];
};
export const mockRecorder = (mockHass: MockHomeAssistant) => {
mockHass.mockWS(
"recorder/get_statistics_metadata",
(
{ statistic_ids }: { statistic_ids?: string[] },
hass
): StatisticsMetaData[] =>
(statistic_ids ?? []).flatMap((id) => {
const stateObj = hass.states[id];
if (!stateObj?.attributes.state_class) {
return [];
}
const sum = hasSum(stateObj);
return [
{
statistic_id: id,
source: "recorder",
name: stateObj.attributes.friendly_name ?? null,
statistics_unit_of_measurement:
stateObj.attributes.unit_of_measurement ?? null,
has_sum: sum,
mean_type: sum
? StatisticMeanType.NONE
: StatisticMeanType.ARITHMETIC,
unit_class: null,
},
];
})
(): StatisticsMetaData[] => []
);
mockHass.mockWS(
"recorder/list_statistic_ids",
(): StatisticsMetaData[] => []
);
mockHass.mockWS(
"recorder/statistics_during_period",
(
{ statistic_ids, start_time, end_time, period, units },
hass
): Statistics =>
({ statistic_ids, start_time, end_time, period }, hass): Statistics => {
// Calendar buckets follow the server timezone, independent of the browser.
getStatistics(
hass,
statistic_ids,
new TZDate(start_time, hass.config.time_zone),
new TZDate(end_time ?? Date.now(), hass.config.time_zone),
period,
units
)
);
const start = new TZDate(start_time, hass.config.time_zone);
const end = new TZDate(end_time ?? Date.now(), hass.config.time_zone);
// The statistic card asks for one number over a period: the mean, lowest,
// highest or change of the hourly statistics in it
mockHass.mockWS(
"recorder/statistic_during_period",
(message: StatisticDuringPeriodMessage, hass): Statistic => {
const [start, end] = statisticPeriodBounds(
message,
hass.config.time_zone
);
const id = message.statistic_id;
// Like Core, an ID without statistics, such as a misspelled one, gets
// none, rather than values made up for it
const hasStatistics =
id in hass.states ||
id in statisticsFunctions ||
id in derivedCosts ||
id in derivedBatteryFlows;
// The energy demo's tariffs place their phases from the start they're
// asked for, as the energy dashboard asks from midnight. So the hours
// are made up one day at a time from each midnight, then only those
// inside the period count. Like Core, an hour that runs past the end
// isn't counted, so a day ending at 23:59:59.999 leaves out the hour
// from 23:00.
const days: Date[] = [];
for (
let day = startOfDay(start);
hasStatistics && day < end;
day = addDays(day, 1)
) {
days.push(day);
}
const values = days
.flatMap(
(day) =>
getStatistics(
hass,
[id],
day,
addDays(day, 1),
"hour",
message.units
)[id] ?? []
)
.filter(
(value) =>
value.start >= start.getTime() && value.end <= end.getTime()
);
const numbers = (key: "mean" | "min" | "max" | "change") =>
values.flatMap((value) => (value[key] == null ? [] : [value[key]]));
const means = numbers("mean");
const mins = numbers("min");
const maxes = numbers("max");
const changes = numbers("change");
return {
mean: means.length
? means.reduce((total, mean) => total + mean, 0) / means.length
: null,
// Reduced rather than spread, as a long period has more hours than a
// call can take as arguments
min: mins.length
? mins.reduce((lowest, min) => Math.min(lowest, min))
: null,
max: maxes.length
? maxes.reduce((highest, max) => Math.max(highest, max))
: null,
change: changes.length
? changes.reduce((total, change) => total + change, 0)
: null,
const statistics: Record<string, StatisticValue[]> = {};
const cache: Record<string, StatisticValue[]> = {};
const getStats = (id: string) => {
cache[id] ??= statisticsFunctions[id](id, start, end, period);
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);
} else if (id in statisticsFunctions) {
statistics[id] = getStats(id);
} else {
const entityState = hass.states[id];
const state = entityState ? Number(entityState.state) : 1;
statistics[id] =
entityState &&
(entityState.attributes.state_class === "total" ||
entityState.attributes.state_class === "total_increasing")
? generateSumStatistics(
start,
end,
period,
state,
state * (state > 80 ? 0.01 : 0.05)
)
: generateMeanStatistics(
start,
end,
period,
state * (state > 80 ? 0.05 : 0.1)
);
}
});
return statistics;
}
);
};
+1 -6
View File
@@ -1,7 +1,6 @@
import type { LocalizeFunc } from "../../../src/common/translations/localize";
import type { MockHomeAssistant } from "../../../src/fake_data/provide_hass";
import { connectivityBackendTranslations } from "./connectivity/fixtures";
import { marketplaceBackendTranslations } from "./marketplace";
export const mockTranslations = (
hass: MockHomeAssistant,
@@ -21,11 +20,7 @@ export const mockTranslations = (
// this merges on top of them.
(localizePromise ?? Promise.resolve()).then(() =>
hass.addTranslations(
Object.assign(
{},
...Object.values(connectivityBackendTranslations),
marketplaceBackendTranslations
)
Object.assign({}, ...Object.values(connectivityBackendTranslations))
)
);
};
-12
View File
@@ -1,8 +1,6 @@
import type { PropertyValues } from "lit";
import { html, css, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import "../../../src/components/ha-switch";
import { handleAction } from "../../../src/panels/lovelace/common/handle-action";
import type { HomeAssistant } from "../../../src/types";
import "./demo-card";
import type { DemoCardConfig } from "./demo-card";
@@ -16,16 +14,6 @@ class DemoCards extends LitElement {
@state() private _showConfig = false;
protected firstUpdated(changedProps: PropertyValues<this>) {
super.firstUpdated(changedProps);
// Handles card actions like the app's action mixin
this.addEventListener("hass-action", (ev) => {
ev.stopPropagation();
const node = (ev.composedPath()[0] as HTMLElement | undefined) ?? this;
handleAction(node, this.hass, ev.detail.config, ev.detail.action);
});
}
render() {
return html`
<ha-demo-options>
@@ -61,6 +61,6 @@ The badge component is a small component that displays a number or status inform
**CSS Custom Properties**
- `--ha-badge-size` (default `36px`)
- `--ha-badge-border-radius` (default `calc(var(--ha-border-radius-lg) + 3px)`)
- `--ha-badge-border-radius` (default `calc(var(--ha-badge-size, 36px) / 2)`)
- `--ha-badge-font-size` (default `var(--ha-font-size-s)`)
- `--ha-badge-icon-size` (default `18px`)
@@ -22,27 +22,20 @@ export class DemoHaCircularSlider extends LitElement {
@state()
private changingHigh?: number;
// A handle that passes the other one pushes it along, like the slider does
private _lowChanged(ev) {
this.low = ev.detail.value;
this.high = Math.max(this.high, this.low);
}
private _lowChanging(ev) {
const value = ev.detail.value;
this.changingLow = value;
this.changingHigh = value != null && value > this.high ? value : undefined;
this.changingLow = ev.detail.value;
}
private _highChanged(ev) {
this.high = ev.detail.value;
this.low = Math.min(this.low, this.high);
}
private _highChanging(ev) {
const value = ev.detail.value;
this.changingHigh = value;
this.changingLow = value != null && value < this.low ? value : undefined;
this.changingHigh = ev.detail.value;
}
private _currentChanged(ev) {
@@ -462,14 +462,6 @@ const SCHEMAS: {
},
},
},
select_search: {
name: "Select (more than 12 options)",
selector: {
select: {
options: Array.from({ length: 20 }, (_, i) => `Option ${i + 1}`),
},
},
},
select_disabled_list: {
name: "Select disabled option",
selector: {
@@ -640,10 +632,6 @@ const SCHEMAS: {
},
language: { name: "Language", selector: { language: {} } },
navigation: { name: "Navigation", selector: { navigation: {} } },
ui_condition: {
name: "Dashboard conditions",
selector: { ui_condition: {} },
},
numeric_threshold: {
name: "Numeric threshold",
selector: { numeric_threshold: {} },
@@ -22,13 +22,6 @@ const ENTITIES = [
friendly_name: "Bed Light",
},
},
{
entity_id: "light.living_room_ceiling_accent_lights",
state: "on",
attributes: {
friendly_name: "Living Room Ceiling Accent Lights",
},
},
{
entity_id: "person.paulus",
state: "home",
@@ -80,14 +73,6 @@ const CONFIGS = [
entity: "person.paulus",
},
},
{
heading: "Long name",
config: {
type: "picture-entity",
image: "/images/living_room.png",
entity: "light.living_room_ceiling_accent_lights",
},
},
{
heading: "Hidden name",
config: {
+7 -7
View File
@@ -1,6 +1,6 @@
import type {
HassEntityState,
HassEntityStateAttributeBase,
HassEntity,
HassEntityAttributeBase,
} from "home-assistant-js-websocket";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
@@ -94,7 +94,7 @@ const BINARY_SENSOR_DEVICE_CLASSES = [
"window",
];
const ENTITIES: HassEntityState[] = [
const ENTITIES: HassEntity[] = [
// Alarm control panel
createEntity("alarm_control_panel.disarmed", "disarmed"),
createEntity("alarm_control_panel.armed_home", "armed_home"),
@@ -305,8 +305,8 @@ function createEntity(
entity_id: string,
state: string,
device_class?: string,
attributes?: HassEntityStateAttributeBase | HassEntityState["attributes"]
): HassEntityState {
attributes?: HassEntityAttributeBase | HassEntity["attributes"]
): HassEntity {
return {
entity_id,
state,
@@ -325,14 +325,14 @@ function createEntity(
}
interface EntityRowData {
stateObj: HassEntityState;
stateObj: HassEntity;
entity_id: string;
state: string;
device_class?: string;
domain: string;
}
function createRowData(stateObj: HassEntityState): EntityRowData {
function createRowData(stateObj: HassEntity): EntityRowData {
return {
stateObj,
entity_id: stateObj.entity_id,
-51
View File
@@ -54,57 +54,6 @@ lorem | ipsum
`,
})
),
mdContentwithDefaults({
content: `
<p align="center">
<img src="https://img.shields.io/badge/markdown-rendering-brightgreen" alt="Centred badge">
</p>
- [Installation](#installation)
- [Configuration](#configuration)
## Installation
Install it from the Marketplace[^marketplace] and restart Home Assistant.[^restart]
## Configuration
Add the integration from the integrations page.
[Back to the top](#installation)
[^marketplace]: Settings > Marketplace.
[^restart]: Only needed the first time.
`,
}),
mdContentwithDefaults({
content: `
\`\`\`mermaid
flowchart LR
router[Router] --> switch[Switch]
switch --> nas[(NAS)]
switch --> ha[[Home Assistant]]
ha -. Zigbee .-> lights([Lights])
\`\`\`
\`\`\`mermaid
sequenceDiagram
Door sensor->>Home Assistant: Opened
Home Assistant->>Hallway light: Turn on
Hallway light-->>Home Assistant: On
\`\`\`
`,
}),
mdContentwithDefaults({
content: `
A diagram that doesn't parse shows the error and its source:
\`\`\`mermaid
flowchart LR
A -->
\`\`\`
`,
}),
];
@customElement("demo-misc-ha-markdown")
+15 -17
View File
@@ -40,7 +40,7 @@
"license": "Apache-2.0",
"type": "module",
"dependencies": {
"@babel/runtime": "8.1.4",
"@babel/runtime": "8.1.3",
"@braintree/sanitize-url": "7.1.2",
"@codemirror/autocomplete": "6.20.4",
"@codemirror/commands": "6.11.2",
@@ -84,7 +84,7 @@
"@vvo/tzdb": "6.208.0",
"@webcomponents/scoped-custom-element-registry": "0.0.11",
"barcode-detector": "3.2.5",
"cally": "0.10.1",
"cally": "0.10.0",
"color-name": "2.1.1",
"comlink": "4.4.2",
"core-js": "3.51.0",
@@ -105,15 +105,12 @@
"intl-messageformat": "12.2.1",
"js-yaml": "5.5.0",
"leaflet": "1.9.4",
"leaflet.markercluster": "2.0.0",
"leaflet.markercluster": "1.5.3",
"lit": "3.3.3",
"lit-html": "3.3.3",
"maplibre-gl": "6.20.0",
"marked": "18.4.0",
"marked-footnote": "1.4.0",
"marked-gfm-heading-id": "4.1.4",
"marked": "18.3.0",
"memoize-one": "7.0.0",
"mermaid": "12.4.0",
"nanoid": "6.0.2",
"node-vibrant": "4.0.4",
"object-hash": "3.0.0",
@@ -125,7 +122,7 @@
"sortablejs": "1.15.7",
"stacktrace-js": "2.0.2",
"superstruct": "2.0.2",
"temporal-polyfill": "1.0.9",
"temporal-polyfill": "1.0.8",
"tinykeys": "4.0.1",
"weekstart": "2.0.0",
"workbox-cacheable-response": "7.4.1",
@@ -139,13 +136,13 @@
},
"devDependencies": {
"@ampproject/remapping": "2.3.0",
"@babel/core": "8.1.4",
"@babel/core": "8.1.3",
"@babel/helper-compilation-targets": "8.0.7",
"@babel/helper-define-polyfill-provider": "1.0.0",
"@babel/plugin-transform-class-properties": "8.0.1",
"@babel/plugin-transform-private-methods": "8.0.1",
"@babel/plugin-transform-runtime": "8.1.2",
"@babel/preset-env": "8.1.4",
"@babel/preset-env": "8.0.7",
"@bundle-stats/plugin-webpack-filter": "4.23.1",
"@eslint/js": "10.0.1",
"@gfx/zopfli": "1.0.15",
@@ -157,7 +154,7 @@
"@playwright/test": "1.65.1",
"@rsdoctor/rspack-plugin": "1.6.5",
"@rspack/core": "2.3.4",
"@rspack/dev-server": "2.2.3",
"@rspack/dev-server": "2.2.2",
"@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "7.0.1",
"@types/chromecast-caf-sender": "1.0.11",
@@ -171,6 +168,7 @@
"@types/node": "24.19.4",
"@types/qrcode": "1.5.6",
"@types/sortablejs": "1.15.9",
"@types/tar": "7.0.87",
"@typescript/native": "npm:[email protected]",
"@vitest/coverage-v8": "5.1.2",
"babel-loader": "10.1.1",
@@ -179,7 +177,7 @@
"browserslist-useragent-regexp": "4.1.4",
"core-js-compat": "3.51.0",
"del": "9.0.1",
"eslint": "10.16.0",
"eslint": "10.15.0",
"eslint-config-prettier": "10.1.9",
"eslint-import-resolver-webpack": "0.13.11",
"eslint-plugin-import-x": "4.18.1",
@@ -190,7 +188,7 @@
"fancy-log": "2.0.0",
"fs-extra": "11.4.1",
"generate-license-file": "4.2.5",
"glob": "15.0.0",
"glob": "14.0.6",
"globals": "17.14.0",
"gulp": "5.0.1",
"gulp-json-transform": "0.5.0",
@@ -201,7 +199,7 @@
"jszip": "3.10.2",
"license-checker-rseidelsohn": "5.0.1",
"lightningcss": "1.33.0",
"lint-staged": "17.6.3",
"lint-staged": "17.6.2",
"lit-analyzer": "2.0.3",
"lodash.merge": "4.6.2",
"lodash.template": "4.18.1",
@@ -212,7 +210,7 @@
"rspack-manifest-plugin": "5.2.2",
"serve": "14.2.8",
"sinon": "22.1.0",
"tar": "8.0.4",
"tar": "7.5.24",
"terser-webpack-plugin": "5.6.1",
"ts-lit-plugin": "2.0.2",
"typescript": "6.0.3",
@@ -224,8 +222,8 @@
"webpackbar": "7.0.0",
"workbox-build": "7.4.1"
},
"packageManager": "[email protected]5.1",
"packageManager": "[email protected]3.0",
"volta": {
"node": "24.23.0"
"node": "24.22.3"
}
}
+624 -1447
View File
File diff suppressed because it is too large. Load diff
-2
View File
@@ -34,8 +34,6 @@ overrides:
clean-css: 5.3.3
"@lit/reactive-element": 2.1.2
tslib: 2.9.1
# ELK is copyleft (EPL-2.0 or GPL-3.0) and diagrams use dagre, so leave it out
"mermaid>elkjs": "-"
patchedDependencies:
[email protected]: patches/[email protected]
-9
View File
@@ -62,15 +62,6 @@
"datasourceTemplate": "github-releases",
"extractVersionTemplate": "^v(?<version>.+)$"
},
{
"description": "Keep zizmor used in CI up to date",
"customType": "regex",
"managerFilePatterns": ["/^\\.github/workflows/actionlint\\.yaml$/"],
"matchStrings": ["ZIZMOR_VERSION: (?<currentValue>\\S+)"],
"depNameTemplate": "zizmorcore/zizmor",
"datasourceTemplate": "github-releases",
"extractVersionTemplate": "^v(?<version>.+)$"
},
{
"description": "Keep gh-actions-lock in CI and Renovate's lockfile generator on the same version",
"customType": "regex",
-1
View File
@@ -28,7 +28,6 @@ const ALLOWED_LICENSES = new Set([
"CC0-1.0",
"(MIT OR CC0-1.0)",
"(MIT OR Apache-2.0)",
"(MPL-2.0 OR Apache-2.0)", // dompurify, used under Apache-2.0
"(MIT AND Zlib)",
"PSF-2.0", // argparse - Python Software Foundation License (permissive)
"Public Domain",
+7 -1
View File
@@ -1,6 +1,8 @@
/* eslint-disable lit/prefer-static-styles */
import { html } from "lit";
import { customElement } from "lit/decorators";
import { customElement, state } from "lit/decorators";
import { consumeLocalize } from "../common/decorators/consume-context-entry";
import type { LocalizeFunc } from "../common/translations/localize";
import { HaForm } from "../components/ha-form/ha-form";
import "./ha-auth-form-string";
@@ -8,6 +10,10 @@ const localizeBaseKey = "ui.panel.page-authorize.form";
@customElement("ha-auth-form")
export class HaAuthForm extends HaForm {
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
protected getFormProperties(): Record<string, any> {
return {
localize: this._localize,
+7 -20
View File
@@ -1,6 +1,5 @@
import type { HassConfig } from "home-assistant-js-websocket";
import { listenMediaQuery } from "../dom/media_query";
import type { FrontendLocaleData } from "../../data/translation";
import type { HomeAssistant } from "../../types";
import type {
TimeCondition,
VisibilityCondition,
@@ -20,8 +19,7 @@ const MAX_TIMEOUT_DELAY = 2147483647;
* Delays past the setTimeout max are capped and retried without firing.
*/
function scheduleTimeBoundaryListener(
getLocale: () => FrontendLocaleData,
getConfig: () => HassConfig,
getHass: () => HomeAssistant,
timeCondition: Omit<TimeCondition, "condition">,
addListener: (unsub: () => void) => void,
onBoundary: () => void
@@ -29,12 +27,8 @@ function scheduleTimeBoundaryListener(
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const scheduleUpdate = () => {
// Read these here so a timezone change applies at the next boundary.
const delay = calculateNextTimeUpdate(
getLocale(),
getConfig(),
timeCondition
);
// Read hass here so a timezone change applies at the next boundary.
const delay = calculateNextTimeUpdate(getHass(), timeCondition);
if (delay === undefined) return;
@@ -65,14 +59,13 @@ function scheduleTimeBoundaryListener(
* could have flipped.
*
* This does not evaluate the conditions itself: the caller recombines client
* and server results on notification. Used by `ConditionEvaluator`,
* and server results on notification. Used by `ConditionEvaluatorController`,
* which merges these client signals with the results of `subscribe_condition`
* subscriptions.
*/
export function observeConditionChanges(
conditions: VisibilityCondition[],
getLocale: () => FrontendLocaleData,
getConfig: () => HassConfig,
getHass: () => HomeAssistant,
addListener: (unsub: () => void) => void,
onChange: () => void
): void {
@@ -81,12 +74,6 @@ export function observeConditionChanges(
});
extractTimeConditions(conditions).forEach((timeCondition) => {
scheduleTimeBoundaryListener(
getLocale,
getConfig,
timeCondition,
addListener,
onChange
);
scheduleTimeBoundaryListener(getHass, timeCondition, addListener, onChange);
});
}
@@ -1,66 +0,0 @@
import type {
ConditionContext,
VisibilityCondition,
} from "../../panels/lovelace/common/validate-condition";
import { addEntityToCondition } from "../../panels/lovelace/common/validate-condition";
import type { HomeAssistant } from "../../types";
import type { ConditionEvaluation } from "../controllers/condition-evaluator-controller";
import { ConditionEvaluator } from "../controllers/condition-evaluator-controller";
import { dropInvalidConditions } from "./sanitize";
export interface VisibilitySubscription {
/** Pass each new hass object so client-side conditions check again. */
update(hass: HomeAssistant): void;
/** Close the subscriptions. `onChange` is not called again. */
unsubscribe(): void;
}
/**
* Live visibility of a list of dashboard visibility conditions, for code
* without a Lit host, such as custom cards and plugins. Conditions core
* evaluates are subscribed to; the rest are checked locally. Reports
* `unknown` until core replies.
*/
export const subscribeVisibility = (
hass: HomeAssistant,
conditions: VisibilityCondition[],
onChange: (result: ConditionEvaluation, error?: string) => void,
context: ConditionContext = {}
): VisibilitySubscription => {
let active = true;
const evaluator = new ConditionEvaluator({
resubscribeDelay: 0,
onResult: (result, error) => {
if (active) {
onChange(result, error);
}
},
});
const sanitized = dropInvalidConditions(conditions);
const { entity_id: entityId } = context;
// Core-evaluated conditions never see the context, so fold its entity in
// first, as the dashboard mixin does.
const validConditions = entityId
? sanitized.map((condition) => addEntityToCondition(condition, entityId))
: sanitized;
const getContext = () => context;
evaluator.connect();
evaluator.setInputs(hass, hass.connection, hass.localize);
evaluator.observe(validConditions, getContext);
return {
update: (newHass) => {
if (active) {
evaluator.setInputs(newHass, newHass.connection, newHass.localize);
}
},
unsubscribe: () => {
active = false;
evaluator.disconnect();
},
};
};
+5 -8
View File
@@ -5,27 +5,24 @@ import {
addMinutes,
differenceInMilliseconds,
} from "date-fns";
import type { HassConfig } from "home-assistant-js-websocket";
import type { FrontendLocaleData } from "../../data/translation";
import type { HomeAssistant } from "../../types";
import { TimeZone } from "../../data/translation";
import { parseTimeString } from "../datetime/check_time";
import type { TimeCondition } from "../../panels/lovelace/common/validate-condition";
/**
* Calculate milliseconds until next time boundary for a time condition
* @param locale User locale (time zone preference)
* @param config Core config (server time zone)
* @param hass Home Assistant object
* @param timeCondition Time condition to calculate next update for
* @returns Milliseconds until next boundary, or undefined if no boundaries
*/
export function calculateNextTimeUpdate(
locale: FrontendLocaleData,
config: HassConfig,
hass: HomeAssistant,
{ after, before, weekdays }: Omit<TimeCondition, "condition">
): number | undefined {
const timezone =
locale.time_zone === TimeZone.server
? config.time_zone
hass.locale.time_zone === TimeZone.server
? hass.config.time_zone
: Intl.DateTimeFormat().resolvedOptions().timeZone;
const now = new TZDate(new Date(), timezone);
@@ -1,31 +1,16 @@
import type { ReactiveControllerHost } from "@lit/reactive-element/reactive-controller";
import type {
Connection,
HassEntityStates,
UnsubscribeFunc,
} from "home-assistant-js-websocket";
ReactiveController,
ReactiveControllerHost,
} from "@lit/reactive-element/reactive-controller";
import type { Connection, UnsubscribeFunc } from "home-assistant-js-websocket";
import { subscribeCondition } from "../../data/automation";
import {
configContext,
connectionContext,
internationalizationContext,
registriesContext,
statesContext,
} from "../../data/context";
import type {
Condition,
ConditionContext,
ConditionHass,
VisibilityCondition,
} from "../../panels/lovelace/common/validate-condition";
import { checkConditionsMet } from "../../panels/lovelace/common/validate-condition";
import type {
HomeAssistantConfig,
HomeAssistantInternationalization,
HomeAssistantRegistries,
} from "../../types";
import { consumeContext, ContextController } from "../decorators/consume";
import type { LocalizeFunc } from "../translations/localize";
import type { HomeAssistant } from "../../types";
import { observeConditionChanges } from "../condition/listeners";
import { isPureClientCondition } from "../condition/translate";
import type {
@@ -53,22 +38,19 @@ const firstDefined = (
/**
* Live evaluation of a visibility tree: `subscribe_condition` for server
* subtrees, local checks for screen/user/time/etc. Call {@link observe} and
* {@link setInputs} when inputs change. Result stays `unknown` until server
* replies so nothing flashes.
* subtrees, local checks for screen/user/time/etc. Call {@link observe} when
* inputs change. Result stays `unknown` until server replies so nothing flashes.
*/
export class ConditionEvaluator {
export class ConditionEvaluatorController implements ReactiveController {
private _host: ReactiveControllerHost;
private readonly _onResult: ConditionEvaluatorOptions["onResult"];
private readonly _resubscribeDelay: number;
private _conditions?: VisibilityCondition[];
private _conditionHass?: ConditionHass;
private _connection?: Connection;
private _localize?: LocalizeFunc;
private _hass?: HomeAssistant;
private _getContext?: () => ConditionContext;
@@ -83,7 +65,7 @@ export class ConditionEvaluator {
private _hasPendingResubscribe = false;
// Resubscribe if the connection is replaced even when the tree is unchanged.
// Resubscribe if hass.connection is replaced even when the tree is unchanged.
private _subscribedConnection?: Connection;
// Skip JSON.stringify when the same array is observed again.
@@ -118,10 +100,15 @@ export class ConditionEvaluator {
private _notifiedError?: string;
constructor(options: ConditionEvaluatorOptions) {
constructor(
host: ReactiveControllerHost,
options: ConditionEvaluatorOptions
) {
this._host = host;
this._onResult = options.onResult;
this._resubscribeDelay =
options.resubscribeDelay ?? DEFAULT_RESUBSCRIBE_DELAY;
host.addController(this);
}
public get result(): ConditionEvaluation {
@@ -133,38 +120,25 @@ export class ConditionEvaluator {
}
/**
* Update the tree. Resubscribes only when its content changes.
* Update inputs. Resubscribes only when the tree (or connection) changes.
*/
public observe(
conditions: VisibilityCondition[] | undefined,
hass: HomeAssistant | undefined,
getContext?: () => ConditionContext
): void {
this._conditions = conditions;
this._hass = hass;
this._getContext = getContext;
this._sync();
}
/**
* Update what client conditions read and where server subtrees subscribe.
* Resubscribes only when the connection is replaced.
*/
public setInputs(
conditionHass: ConditionHass | undefined,
connection: Connection | undefined,
localize: LocalizeFunc | undefined
): void {
this._conditionHass = conditionHass;
this._connection = connection;
this._localize = localize;
this._sync();
}
public connect(): void {
public hostConnected(): void {
this._connected = true;
this._sync();
}
public disconnect(): void {
public hostDisconnected(): void {
this._connected = false;
this._teardown();
// Subscriptions are gone; don't keep showing a stale result.
@@ -202,14 +176,14 @@ export class ConditionEvaluator {
return;
}
const signature = this._signatureOf(this._conditions);
// Resubscribe when the tree content or the connection changed.
// Resubscribe when the tree content or hass.connection changed.
const targetSignature = this._hasPendingResubscribe
? this._pendingSignature
: this._subscribedSignature;
const connectionReplaced =
this._subscribedConnection !== undefined &&
this._connection !== undefined &&
this._connection !== this._subscribedConnection;
this._hass !== undefined &&
this._hass.connection !== this._subscribedConnection;
if (signature !== targetSignature || connectionReplaced) {
// Drop the old subscriptions immediately so their result can't leak through.
this._teardown();
@@ -243,13 +217,12 @@ export class ConditionEvaluator {
this._teardown();
const conditions = this._conditions;
const conditionHass = this._conditionHass;
const connection = this._connection;
const hass = this._hass;
this._pendingSignature = undefined;
this._hasPendingResubscribe = false;
if (!conditions || !conditionHass || !connection) {
// Don't mark subscribed yet; inputs often arrive after connect.
if (!conditions || !hass) {
// Don't mark subscribed yet; hass often arrives after connect.
this._setResult("unknown", undefined);
return;
}
@@ -259,6 +232,7 @@ export class ConditionEvaluator {
this._split = split;
const generation = this._generation;
const connection: Connection = hass.connection;
this._subscribedConnection = connection;
for (const subtree of split.serverSubtrees) {
@@ -270,7 +244,7 @@ export class ConditionEvaluator {
return;
}
if (message.error !== undefined) {
this._serverResults[subtree.id] = undefined;
this._serverResults[subtree.id] = false;
this._subtreeErrors[subtree.id] =
typeof message.error === "string"
? message.error
@@ -291,11 +265,9 @@ export class ConditionEvaluator {
if (generation !== this._generation) {
return;
}
this._serverResults[subtree.id] = undefined;
this._serverResults[subtree.id] = false;
this._subtreeErrors[subtree.id] =
getWsErrorMessage(err) ??
this._localize?.("ui.common.unknown_error") ??
String(err);
getWsErrorMessage(err) ?? hass.localize("ui.common.unknown_error");
this._recompute();
});
this._subscriptions.push(subscription);
@@ -303,8 +275,7 @@ export class ConditionEvaluator {
observeConditionChanges(
conditions,
() => (this._conditionHass ?? conditionHass).locale,
() => (this._conditionHass ?? conditionHass).config,
() => this._hass ?? hass,
(unsub) => this._listeners.push(unsub),
() => this._recompute()
);
@@ -313,38 +284,33 @@ export class ConditionEvaluator {
}
private _recompute(): void {
if (!this._split || !this._conditionHass) {
if (!this._split || !this._hass) {
this._setResult("unknown", undefined);
return;
}
const conditionHass = this._conditionHass;
const hass = this._hass;
const context = this._getContext?.() ?? {};
const clientEvaluator: ClientConditionEvaluator = (condition) => {
try {
return checkConditionsMet(
[condition as Condition],
conditionHass,
context
);
return checkConditionsMet([condition as Condition], hass, context);
} catch (_err) {
return false;
}
};
// A failed subtree stays unknown, so it only hides the card when the
// result depends on it (a true `or` sibling still wins).
const value = this._split.evaluate(clientEvaluator, this._serverResults);
const error = firstDefined(this._subtreeErrors);
if (value === undefined && error !== undefined) {
// Don't treat a server error as `false` that a client `not` would invert.
if (error !== undefined) {
this._setResult("hidden", error);
return;
}
const value = this._split.evaluate(clientEvaluator, this._serverResults);
const result: ConditionEvaluation =
value === undefined ? "unknown" : value ? "visible" : "hidden";
this._setResult(result, error ?? firstDefined(this._subtreeTemplateErrors));
this._setResult(result, firstDefined(this._subtreeTemplateErrors));
}
private _setResult(
@@ -359,6 +325,7 @@ export class ConditionEvaluator {
this._notifiedResult = result;
this._notifiedError = error;
this._onResult(result, error);
this._host.requestUpdate();
}
private _teardown(): void {
@@ -385,108 +352,3 @@ export class ConditionEvaluator {
this._subscribedConnection = undefined;
}
}
/**
* {@link ConditionEvaluator} for a Lit host. Reads states, user, config,
* locale, registries and the connection from context; the host only passes
* the tree to {@link observe}.
*/
export class ConditionEvaluatorController extends ContextController {
@consumeContext({ context: statesContext, subscribe: true })
private _states?: HassEntityStates | null;
@consumeContext({ context: configContext, subscribe: true })
private _hassConfig?: HomeAssistantConfig | null;
@consumeContext({ context: internationalizationContext, subscribe: true })
private _i18n?: HomeAssistantInternationalization | null;
@consumeContext({ context: registriesContext, subscribe: true })
private _registries?: HomeAssistantRegistries | null;
@consumeContext({
context: connectionContext,
subscribe: true,
transform: (value) => value?.connection,
})
private _connection?: Connection;
private readonly _evaluator: ConditionEvaluator;
// Hosts without conditions skip the per-state-message input rebuild.
private _observing = false;
private _inputsStale = false;
constructor(
host: ReactiveControllerHost & HTMLElement,
options: ConditionEvaluatorOptions
) {
super(host);
this._evaluator = new ConditionEvaluator({
resubscribeDelay: options.resubscribeDelay,
onResult: (result, error) => {
options.onResult(result, error);
host.requestUpdate();
},
});
}
public get result(): ConditionEvaluation {
return this._evaluator.result;
}
public get error(): string | undefined {
return this._evaluator.error;
}
public observe(
conditions: VisibilityCondition[] | undefined,
getContext?: () => ConditionContext
): void {
this._observing = conditions !== undefined;
if (this._observing && this._inputsStale) {
this._pushInputs();
}
this._evaluator.observe(conditions, getContext);
}
public hostConnected(): void {
this._evaluator.connect();
}
public hostDisconnected(): void {
this._evaluator.disconnect();
}
protected contextUpdated(): void {
if (!this._observing) {
this._inputsStale = true;
return;
}
this._pushInputs();
}
private _pushInputs(): void {
this._inputsStale = false;
const hassConfig = this._hassConfig;
const locale = this._i18n?.locale;
// States and registries load after connect; missing ones read as empty,
// so conditions that don't need them are not held back.
this._evaluator.setInputs(
hassConfig && locale
? {
states: this._states ?? {},
user: hassConfig.user,
locale,
config: hassConfig.config,
entities: this._registries?.entities ?? {},
devices: this._registries?.devices ?? {},
areas: this._registries?.areas ?? {},
}
: undefined,
this._connection,
this._i18n?.localize
);
}
}
@@ -2,7 +2,7 @@ import type {
ReactiveController,
ReactiveControllerHost,
} from "@lit/reactive-element/reactive-controller";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { timerTimeRemaining } from "../../data/timer";
/**
@@ -17,7 +17,7 @@ export class TimerRemainingTimeController implements ReactiveController {
private _host: ReactiveControllerHost;
private _stateObj?: HassEntityState;
private _stateObj?: HassEntity;
private _interval?: number;
@@ -26,7 +26,7 @@ export class TimerRemainingTimeController implements ReactiveController {
host.addController(this);
}
public setStateObj(stateObj: HassEntityState | undefined): void {
public setStateObj(stateObj: HassEntity | undefined): void {
this._stateObj = stateObj;
this._startInterval();
}
+6 -13
View File
@@ -209,16 +209,6 @@ const formatDurationMinuteMem = memoizeOne((locale: FrontendLocaleData) =>
})
);
// Splits a value into whole units and whole sub-units, e.g. 1.15 h into 1 h
// and 9 min. The value is converted to sub-units and rounded before flooring,
// as floating point math puts many of them just below a whole number:
// (1.15 - 1) * 60 is 8.999999999999995.
const splitDuration = (value: number, subUnits: number): [number, number] => {
const total = Math.floor(round(value * subUnits, 6));
const units = Math.floor(total / subUnits);
return [units, total - units * subUnits];
};
export const formatDuration = (
locale: FrontendLocaleData,
duration: string,
@@ -232,7 +222,8 @@ export const formatDuration = (
switch (unit) {
case "d": {
const [days, hours] = splitDuration(value, 24);
const days = Math.floor(value);
const hours = Math.floor((value - days) * 24);
const input = {
days,
hours,
@@ -240,7 +231,8 @@ export const formatDuration = (
return formatDurationDayMem(locale)(input);
}
case "h": {
const [hours, minutes] = splitDuration(value, 60);
const hours = Math.floor(value);
const minutes = Math.floor((value - hours) * 60);
const input = {
hours,
minutes,
@@ -248,7 +240,8 @@ export const formatDuration = (
return formatDurationHourMem(locale)(input);
}
case "min": {
const [minutes, seconds] = splitDuration(value, 60);
const minutes = Math.floor(value);
const seconds = Math.floor((value - minutes) * 60);
const input = {
minutes,
seconds,
+13 -16
View File
@@ -1,8 +1,5 @@
import type { Context } from "@lit/context";
import type {
HassEntityStates,
HassEntityState,
} from "home-assistant-js-websocket";
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import type {
HomeAssistant,
HomeAssistantInternationalization,
@@ -31,9 +28,9 @@ const resolveAtPath = (host: unknown, path: readonly string[]) => {
return cur;
};
/** Reuse `previous` when every entry still references the same `HassEntityState`. */
/** Reuse `previous` when every entry still references the same `HassEntity`. */
export const preserveUnchangedEntityStatesRecord = <
T extends Record<string, HassEntityState | undefined>,
T extends Record<string, HassEntity | undefined>,
>(
previous: T | undefined,
next: T
@@ -83,7 +80,7 @@ const composeDecorator = <T, V>(
};
/**
* Consumes `statesContext` and narrows it to the `HassEntityState` for the entity
* Consumes `statesContext` and narrows it to the `HassEntity` for the entity
* ID found at `entityIdPath` on the host (e.g. `["_config", "entity"]`).
*
* The first path segment is watched on the host — changes to it re-run the
@@ -91,7 +88,7 @@ const composeDecorator = <T, V>(
* nullish values.
*/
export const consumeEntityState = (config: ConsumeEntryConfig) =>
composeDecorator<HassEntityStates, HassEntityState>(
composeDecorator<HassEntities, HassEntity>(
statesContext,
config.entityIdPath[0],
function (states) {
@@ -109,10 +106,10 @@ export const consumeEntityState = (config: ConsumeEntryConfig) =>
*/
export const consumeEntityStates = (config: ConsumeEntryConfig) => {
const watchKey = config.entityIdPath[0];
const buildRecord = function (this: unknown, states: HassEntityStates) {
const buildRecord = function (this: unknown, states: HassEntities) {
const ids = ensureArray(resolveAtPath(this, config.entityIdPath));
if (!ids || !states) return undefined;
const result: Record<string, HassEntityState> = {};
const result: Record<string, HassEntity> = {};
for (const id of ids) {
if (typeof id !== "string") continue;
const state = states[id];
@@ -124,22 +121,22 @@ export const consumeEntityStates = (config: ConsumeEntryConfig) => {
return (proto: unknown, propertyKey: string) => {
const key = String(propertyKey);
const transformDec = transform<
HassEntityStates,
Record<string, HassEntityState> | undefined
HassEntities,
Record<string, HassEntity> | undefined
>({
transformer: function (this: unknown, states: HassEntityStates) {
transformer: function (this: unknown, states: HassEntities) {
const next = buildRecord.call(this, states);
if (next === undefined) {
return undefined;
}
const previous = (this as Record<string, unknown>)[
`__transform_${key}`
] as Record<string, HassEntityState> | undefined;
] as Record<string, HassEntity> | undefined;
return preserveUnchangedEntityStatesRecord(previous, next);
},
watch: watchKey ? [watchKey] : [],
});
const consumeDec = subscribeContext<HassEntityStates>(statesContext);
const consumeDec = subscribeContext<HassEntities>(statesContext);
transformDec(proto as never, propertyKey);
consumeDec(proto as never, propertyKey);
};
@@ -169,5 +166,5 @@ export const consumeLocalize = () =>
composeDecorator<HomeAssistantInternationalization, LocalizeFunc>(
internationalizationContext,
undefined,
(i18n) => i18n?.localize
({ localize }) => localize
);
-12
View File
@@ -1,12 +0,0 @@
import { getShadowRootHost } from "./get-shadow-root-host";
/** The element and its ancestors, crossing shadow root boundaries. */
export const composedAncestors = (element: Element | null): Element[] => {
const ancestors: Element[] = [];
let current = element;
while (current) {
ancestors.push(current);
current = current.parentElement ?? getShadowRootHost(current);
}
return ancestors;
};
-47
View File
@@ -1,47 +0,0 @@
/**
* How long after the full screen button the companion apps hide the page for
* the change, and after that how long they keep it hidden. A later hide ends
* streams as usual.
*/
export const FULLSCREEN_ENTER_TIME = 1000;
let enterStart = 0;
let enterId = 0;
// The last entering each stream let a hidden page through for
const claimedEnters = new WeakMap<object, number>();
/**
* Marks that the full screen button was pressed to enter full screen. The
* companion apps hide the page for a moment then, which shouldn't end a
* stream. Leaving full screen isn't marked, so locking the phone or leaving
* the app right after it always ends the streams.
*/
export const startEnteringFullscreen = () => {
enterId++;
enterStart = Date.now();
};
/** Ends it early, like when the browser denies full screen. */
export const cancelEnteringFullscreen = () => {
enterStart = 0;
};
export const isEnteringFullscreen = () =>
Date.now() - enterStart < FULLSCREEN_ENTER_TIME;
/**
* Whether the page is hidden by entering full screen, which hides it only
* once. Any later hiding is the user leaving, so each stream gets true only
* once per entering.
*/
export const claimFullscreenEnterHide = (stream: object): boolean => {
if (!isEnteringFullscreen() || claimedEnters.get(stream) === enterId) {
return false;
}
claimedEnters.set(stream, enterId);
// Counts from here, so the video still plays on when the page shows again
enterStart = Date.now();
return true;
};
-623
View File
@@ -1,623 +0,0 @@
/**
* Read a skeleton from rendered content, such as a dashboard card: where its
* text lines, icons, images, controls and drawings are, inside shadow roots
* too. The content stays the source of truth for layout, so the skeleton
* can't drift from it.
*
* Any element can say how it's read with a `data-skeleton` attribute:
* - `text`, `round` or `block`: one piece of that kind, the size of the element
* - `none`: left out and left showing, such as a card's own chrome
* - `keep`: left showing, but what's inside it is still read
*
* Skeletons a component already draws itself (`ha-skeleton` and its
* variants) are left out and left showing, as `none`.
*/
export type SkeletonPieceKind = "text" | "round" | "block" | "shape" | "scrim";
type SkeletonOverride = "text" | "round" | "block" | "none" | "keep";
const OVERRIDES = new Set<string>(["text", "round", "block", "none", "keep"]);
const isOverride = (value: string | null): value is SkeletonOverride =>
value !== null && OVERRIDES.has(value);
const skeletonOverride = (element: Element): SkeletonOverride | undefined => {
if (element.localName.startsWith("ha-skeleton")) {
return "none";
}
const value = element.getAttribute("data-skeleton");
return isOverride(value) ? value : undefined;
};
export interface SkeletonPiece {
kind: SkeletonPieceKind;
x: number;
y: number;
width: number;
height: number;
radius?: string;
/* An SVG mask for a drawing, such as a gauge arc */
mask?: string;
/* Where that mask sits in the piece, when something cuts the drawing short:
still the drawing's whole size and place, with the piece only its part */
maskBox?: { x: number; y: number; width: number; height: number };
/* The part sits on a dark overlay, such as a picture card's name bar */
onDark?: boolean;
/* A see-through bar laid over a picture, kept as it is */
background?: string;
}
export interface ExtractedSkeleton {
pieces: SkeletonPiece[];
/* The elements the pieces stand in for, hidden while loading */
parts: (HTMLElement | SVGElement)[];
/* Elements holding text: hide only the text colour, as the same element
often draws a frame, such as a badge's pill, that has to stay */
textParts: HTMLElement[];
}
const ROUND_TAGS = new Set([
"ha-tile-icon",
"ha-state-icon",
"ha-svg-icon",
"ha-icon",
"state-badge",
]);
const BLOCK_TAGS = new Set(["img", "video", "canvas", "ha-camera-stream"]);
/* A canvas to measure fonts with, made on first use */
let measuringContext: CanvasRenderingContext2D | null | undefined;
const fontContext = (style: CSSStyleDeclaration, size: string) => {
measuringContext ??= document.createElement("canvas").getContext("2d");
if (measuringContext) {
measuringContext.font = `${style.fontStyle} ${style.fontWeight} ${size} ${style.fontFamily}`;
}
return measuringContext;
};
/**
* Where a text bar goes on a line of this font: from the top of the
* capitals down to the baseline, measured from the font itself.
* `size` is the size as drawn, after any SVG scaling.
*/
const capitalBand = (style: CSSStyleDeclaration, size: number) => {
const metrics = fontContext(style, `${size}px`)?.measureText("H");
// Missing before Chrome 87 and Firefox 116
if (!metrics?.fontBoundingBoxAscent || !metrics.actualBoundingBoxAscent) {
return { top: size * 0.2, height: size * 0.7 };
}
return {
// The line box holds the font's ascent, so the baseline sits that far down
top: metrics.fontBoundingBoxAscent - metrics.actualBoundingBoxAscent,
height: metrics.actualBoundingBoxAscent,
};
};
/* How wide "…" is in this font, the room cut-off text leaves at its end */
const ellipsisWidth = (style: CSSStyleDeclaration) =>
fontContext(style, style.fontSize)?.measureText("…").width ??
parseFloat(style.fontSize);
/* The icon as drawn, not its box, which a line of text can crop */
const findGlyph = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
for (const child of [
...(element.shadowRoot?.children ?? []),
...element.children,
]) {
if (child instanceof SVGSVGElement) {
return child;
}
const found = findGlyph(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Near-white text or icons, as on a picture card's dark name bar */
const isNearWhite = (color: string): boolean => {
const channels = color
.match(/[\d.]+/g)
?.slice(0, 3)
.map(Number);
return channels?.length === 3 && channels.every((channel) => channel >= 200);
};
const isRendered = (style: CSSStyleDeclaration) =>
style.display !== "none" && style.visibility !== "hidden";
const isSeeThrough = (color: string) => {
const alpha = Number(color.match(/rgba\(.*,\s*([\d.]+)\)/)?.[1] ?? 1);
return alpha > 0 && alpha < 1;
};
/* The first element, inside shadow roots too, that rounds its corners */
const findRounded = (element: Element, depth = 4): Element | undefined => {
if (depth === 0) {
return undefined;
}
const children = [
...(element.shadowRoot?.children ?? []),
...element.children,
];
for (const child of children) {
if (parseFloat(getComputedStyle(child).borderTopLeftRadius) > 0) {
return child;
}
const found = findRounded(child, depth - 1);
if (found) {
return found;
}
}
return undefined;
};
/* Join the pieces of one line of text, such as "Heat", "·" and "21 °C" */
const mergeLines = (pieces: SkeletonPiece[]): SkeletonPiece[] => {
const merged: SkeletonPiece[] = [];
for (const piece of pieces) {
const previous = merged[merged.length - 1];
// Either side, so right-to-left lines join too
const gap = previous
? Math.max(
piece.x - (previous.x + previous.width),
previous.x - (piece.x + piece.width)
)
: Infinity;
const sameLine =
previous?.kind === "text" &&
piece.kind === "text" &&
Math.abs(previous.y - piece.y) < 2 &&
Math.abs(previous.height - piece.height) < 2 &&
gap < 12;
if (sameLine) {
const left = Math.min(previous.x, piece.x);
const right = Math.max(
previous.x + previous.width,
piece.x + piece.width
);
previous.x = left;
previous.width = right - left;
continue;
}
merged.push({ ...piece });
}
return merged;
};
const svgMask = (svg: SVGSVGElement, width: number, height: number) => {
const clone = svg.cloneNode(true);
if (!(clone instanceof SVGSVGElement)) {
return undefined;
}
const originals = [svg, ...svg.querySelectorAll("*")];
const copies = [clone, ...clone.querySelectorAll("*")];
let drawnPaths = 0;
originals.forEach((original, index) => {
const copy = copies[index];
const style = getComputedStyle(original);
if (original.localName === "text" || !isRendered(style)) {
copy.setAttribute("display", "none");
return;
}
if (original !== svg && original.localName !== "g") {
drawnPaths++;
}
copy.removeAttribute("class");
copy.removeAttribute("style");
copy.setAttribute("fill", style.fill === "none" ? "none" : "#000");
copy.setAttribute("stroke", style.stroke === "none" ? "none" : "#000");
copy.setAttribute("stroke-width", style.strokeWidth);
copy.setAttribute("stroke-linecap", style.strokeLinecap);
// Keep what moves or cuts a shape, such as a gauge's needle and the
// dashes that draw its value arc
if (style.transform !== "none") {
copy.setAttribute(
"style",
`transform: ${style.transform}; transform-origin: ${style.transformOrigin}; transform-box: ${style.transformBox}`
);
}
if (style.strokeDasharray !== "none") {
copy.setAttribute("stroke-dasharray", style.strokeDasharray);
copy.setAttribute("stroke-dashoffset", style.strokeDashoffset);
}
});
if (drawnPaths === 0) {
return undefined;
}
clone.setAttribute("width", String(width));
clone.setAttribute("height", String(height));
const markup = new XMLSerializer().serializeToString(clone);
return `url("data:image/svg+xml,${encodeURIComponent(markup)}")`;
};
export const extractSkeleton = (
root: Element,
origin: DOMRect
): ExtractedSkeleton => {
const pieces: SkeletonPiece[] = [];
const parts = new Set<HTMLElement | SVGElement>();
const textParts = new Set<HTMLElement>();
/* The card's own background, the first solid one found */
let surface: string | undefined;
const box = (rect: DOMRect) => ({
x: rect.left - origin.left,
y: rect.top - origin.top,
width: rect.width,
height: rect.height,
});
/* Near-white content on a light card must sit on a dark bar */
const onDark = (style: CSSStyleDeclaration) =>
surface !== undefined && isNearWhite(surface) && isNearWhite(style.color);
/* An element that cuts off its overflow, such as a scrolling list, cuts the
pieces read inside it too, as the overlay draws them on a layer of its
own where that clip doesn't reach */
const clipPieces = (from: number, rect: DOMRect) => {
const bounds = box(rect);
const clipped = pieces.splice(from).flatMap((piece): SkeletonPiece[] => {
const x = Math.max(piece.x, bounds.x);
const y = Math.max(piece.y, bounds.y);
const right = Math.min(piece.x + piece.width, bounds.x + bounds.width);
const bottom = Math.min(piece.y + piece.height, bounds.y + bounds.height);
if (right <= x || bottom <= y) {
return [];
}
const cut = { ...piece, x, y, width: right - x, height: bottom - y };
// A drawing's mask is made for its whole box, so it keeps that box
if (piece.kind === "shape") {
const mask = piece.maskBox ?? {
x: 0,
y: 0,
width: piece.width,
height: piece.height,
};
return [
{
...cut,
maskBox: {
...mask,
x: piece.x + mask.x - x,
y: piece.y + mask.y - y,
},
},
];
}
return [cut];
});
pieces.push(...clipped);
};
const addText = (element: Element | ShadowRoot) => {
const owner = element instanceof ShadowRoot ? element.host : element;
// Text cut short with an ellipsis reaches past its box, so clip to it.
// An owner with no box of its own, such as one with display: contents,
// cuts nothing off.
const clip = owner.getBoundingClientRect();
const clips = clip.width > 0 || clip.height > 0;
element.childNodes.forEach((node) => {
if (!(node instanceof Text) || !node.textContent?.trim()) {
return;
}
// Slotted text takes its font and colour from the slot it shows in,
// so that's where it's measured and hidden
const slot = node.assignedSlot;
const hideTarget = slot ?? owner;
const style = getComputedStyle(hideTarget);
const band = capitalBand(style, parseFloat(style.fontSize));
if (hideTarget instanceof HTMLElement) {
textParts.add(hideTarget);
}
const range = document.createRange();
range.selectNodeContents(node);
for (const rect of range.getClientRects()) {
// Cut-off text ends in "…", on the right or, right to left, on the
// left, so stop the bar where that starts
const left =
clips && rect.left < clip.left - 1
? clip.left + ellipsisWidth(style)
: rect.left;
const right =
clips && rect.right > clip.right + 1
? clip.right - ellipsisWidth(style)
: rect.right;
if (right <= left) {
continue;
}
pieces.push({
kind: "text",
x: left - origin.left,
width: right - left,
y: rect.top - origin.top + band.top,
height: band.height,
onDark: onDark(style),
});
}
});
};
const walk = (node: Element | ShadowRoot) => {
// Text straight inside a shadow root, as state-display renders its state
if (node instanceof ShadowRoot) {
addText(node);
}
for (const child of node.children) {
const style = getComputedStyle(child);
if (!isRendered(style)) {
continue;
}
const rect = child.getBoundingClientRect();
const tag = child.localName;
// Elements such as slots take no space but their content does
const hasSize = rect.width > 0 && rect.height > 0;
const override = skeletonOverride(child);
if (override === "none") {
continue;
}
const clipsOverflow =
hasSize &&
(style.overflowX !== "visible" || style.overflowY !== "visible");
const from = pieces.length;
// Read what's inside, cut to the child where it hides its overflow
const descend = () => {
if (child instanceof HTMLElement) {
addText(child);
}
if (child.shadowRoot) {
walk(child.shadowRoot);
}
walk(child);
if (clipsOverflow) {
clipPieces(from, rect);
}
};
if (override === "keep") {
// Its frame stays, but its own text is read like any other
descend();
continue;
}
if (override !== undefined) {
if (
hasSize &&
(child instanceof HTMLElement || child instanceof SVGElement)
) {
const size = Math.min(rect.width, rect.height);
const piece = box(rect);
pieces.push(
override === "round"
? {
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
}
: { kind: override, ...piece, radius: style.borderRadius }
);
parts.add(child);
}
continue;
}
if (
surface === undefined &&
hasSize &&
style.backgroundColor !== "rgba(0, 0, 0, 0)" &&
!isSeeThrough(style.backgroundColor)
) {
surface = style.backgroundColor;
}
if (child instanceof HTMLElement && ROUND_TAGS.has(tag)) {
// Use the circle itself, such as the tile icon's 36px background
const circle = (
findRounded(child) ??
findGlyph(child) ??
child
).getBoundingClientRect();
const size =
Math.min(circle.width, circle.height) ||
Math.max(circle.width, circle.height);
const piece = box(circle);
if (size > 0) {
pieces.push({
kind: "round",
x: piece.x + (piece.width - size) / 2,
y: piece.y + (piece.height - size) / 2,
width: size,
height: size,
onDark: onDark(style),
});
parts.add(child);
}
continue;
}
// A see-through bar over a picture stays, so text keeps its contrast
if (
child instanceof HTMLElement &&
hasSize &&
style.position === "absolute" &&
isSeeThrough(style.backgroundColor)
) {
pieces.push({
kind: "scrim",
...box(rect),
radius: style.borderRadius,
background: style.backgroundColor,
});
}
// Pictures drawn as a background, as hui-image does in a fixed ratio
if (
child instanceof HTMLElement &&
hasSize &&
style.backgroundImage.startsWith("url(")
) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (child instanceof HTMLElement && hasSize && BLOCK_TAGS.has(tag)) {
pieces.push({
kind: "block",
...box(rect),
radius: style.borderRadius,
});
parts.add(child);
continue;
}
if (
child instanceof HTMLElement &&
hasSize &&
tag.endsWith("-card-feature")
) {
const control = findRounded(child);
const radius = control
? getComputedStyle(control).borderRadius
: style.borderRadius;
pieces.push({ kind: "block", ...box(rect), radius });
parts.add(child);
continue;
}
if (child instanceof SVGSVGElement && hasSize) {
const piece = box(rect);
const mask = svgMask(child, piece.width, piece.height);
if (mask) {
pieces.push({ kind: "shape", ...piece, mask });
}
child.querySelectorAll("text").forEach((text) => {
const textRect = text.getBoundingClientRect();
if (textRect.width === 0) {
return;
}
// SVG text is scaled with its drawing, as the gauge value is
const scale = text.getScreenCTM()?.a ?? 1;
const textStyle = getComputedStyle(text);
const band = capitalBand(
textStyle,
parseFloat(textStyle.fontSize) * scale
);
pieces.push({
kind: "text",
...box(textRect),
y: textRect.top - origin.top + band.top,
height: band.height,
});
});
parts.add(child);
continue;
}
descend();
}
};
// Text straight inside the root, such as plain text in an overlay
addText(root);
walk(root);
return {
pieces: mergeLines(pieces),
parts: [...parts],
textParts: [...textParts],
};
};
+10
View File
@@ -31,6 +31,8 @@ export const setupLeafletMap = async (
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
await import("leaflet.markercluster");
const map = Leaflet.map(mapElement, {
minZoom: MAP_MIN_ZOOM,
maxZoom: MAP_MAX_ZOOM,
@@ -41,6 +43,14 @@ export const setupLeafletMap = async (
style.setAttribute("rel", "stylesheet");
mapElement.parentNode.appendChild(style);
const markerClusterStyle = document.createElement("link");
markerClusterStyle.setAttribute(
"href",
"/static/images/leaflet/MarkerCluster.css"
);
markerClusterStyle.setAttribute("rel", "stylesheet");
mapElement.parentNode.appendChild(markerClusterStyle);
if (initialView) {
map.setView(
[initialView.latitude, initialView.longitude],
+3 -3
View File
@@ -1,4 +1,4 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { computeCssColor } from "../color/compute-color";
import { computeDomain } from "./compute_domain";
import { stateColorCss } from "./state_color";
@@ -23,11 +23,11 @@ export const computeAlertActiveStates = (entityId: string): string[] => {
}
};
export const isAlertActive = (stateObj: HassEntityState): boolean =>
export const isAlertActive = (stateObj: HassEntity): boolean =>
computeAlertActiveStates(stateObj.entity_id).includes(stateObj.state);
export const computeAlertColor = (
stateObj: HassEntityState,
stateObj: HassEntity,
color: string
): string | undefined => {
if (color === "none") {
+2 -2
View File
@@ -1,7 +1,7 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
export const attributeClassNames = (
stateObj: HassEntityState,
stateObj: HassEntity,
attributes: string[]
): string => {
if (!stateObj) {
+2 -2
View File
@@ -12,7 +12,7 @@ import {
mdiBatteryAlertVariantOutline,
mdiBatteryUnknown,
} from "@mdi/js";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
const BATTERY_ICONS = {
10: "mdi:battery-10",
@@ -51,7 +51,7 @@ const BATTERY_CHARGING_ICONS = {
100: "mdi:battery-charging",
};
export const batteryIcon = (stateObj: HassEntityState, state?: string) => {
export const batteryIcon = (stateObj: HassEntity, state?: string) => {
const level = state ?? stateObj.state;
return batteryLevelIcon(level);
};
+4 -4
View File
@@ -1,6 +1,6 @@
import type {
HassEntityStates,
HassEntityState,
HassEntities,
HassEntity,
HassServices,
} from "home-assistant-js-websocket";
import { canToggleDomain } from "./can_toggle_domain";
@@ -9,9 +9,9 @@ import { supportsFeature } from "./supports-feature";
import { SPECIAL_TOGGLE_ACTIONS } from "./get_toggle_action";
export const canToggleState = (
states: HassEntityStates,
states: HassEntities,
services: HassServices,
stateObj: HassEntityState
stateObj: HassEntity
) => {
const domain = computeStateDomain(stateObj);
@@ -1,4 +1,4 @@
import type { HassConfig, HassEntityState } from "home-assistant-js-websocket";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import {
DOMAIN_ATTRIBUTES_FORMATERS,
DOMAIN_ATTRIBUTES_UNITS,
@@ -25,7 +25,7 @@ import { computeStateDomain } from "./compute_state_domain";
export const computeAttributeValueDisplay = (
localize: LocalizeFunc,
stateObj: HassEntityState,
stateObj: HassEntity,
locale: FrontendLocaleData,
config: HassConfig,
entities: HomeAssistant["entities"],
@@ -47,7 +47,7 @@ export const computeAttributeValueDisplay = (
export const computeAttributeValueToParts = (
localize: LocalizeFunc,
stateObj: HassEntityState,
stateObj: HassEntity,
locale: FrontendLocaleData,
config: HassConfig,
entities: HomeAssistant["entities"],
@@ -205,7 +205,7 @@ export const computeAttributeValueToParts = (
// effects of a light group, so use the translation of a member.
const computeMemberAttributeValueDisplay = (
localize: LocalizeFunc,
stateObj: HassEntityState,
stateObj: HassEntity,
entities: HomeAssistant["entities"],
attribute: string,
attributeValue: string
@@ -224,7 +224,7 @@ const computeMemberAttributeValueDisplay = (
export const computeAttributeNameDisplay = (
localize: LocalizeFunc,
stateObj: HassEntityState,
stateObj: HassEntity,
entities: HomeAssistant["entities"],
attribute: string
): string => {
@@ -1,4 +1,4 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import type {
EntityRegistryDisplayEntry,
EntityRegistryEntry,
@@ -56,7 +56,7 @@ const computeTextOnlyName = (
* while the real formatter is still loading.
*/
export const computeEntityNameDisplayWithoutContext = (
stateObj: HassEntityState,
stateObj: HassEntity,
name?: string | EntityNameItem | EntityNameItem[],
options?: EntityNameOptions
): string => {
@@ -125,7 +125,7 @@ export const computeEntityEntryNameParts = (
};
export const computeEntityNameParts = (
stateObj: HassEntityState,
stateObj: HassEntity,
registries: HomeAssistantRegistries,
options?: EntityNamePartsOptions
): EntityNameParts => {
@@ -139,7 +139,7 @@ export const computeEntityNameParts = (
};
export const computeDefaultEntityNameItems = (
stateObj: HassEntityState,
stateObj: HassEntity,
registries: HomeAssistantRegistries
): EntityNameItem[] => {
const parts = computeEntityNameParts(stateObj, registries);
@@ -147,7 +147,7 @@ export const computeDefaultEntityNameItems = (
};
export const computeEntityNameDisplay = (
stateObj: HassEntityState,
stateObj: HassEntity,
name: string | EntityNameItem | EntityNameItem[] | undefined,
registries: HomeAssistantRegistries,
options?: EntityNameOptions
@@ -194,7 +194,7 @@ export const computeEntityNameDisplay = (
};
export const computeEntitySearchLabels = (
stateObj: HassEntityState,
stateObj: HassEntity,
registries: HomeAssistantRegistries
) => {
const parts = computeEntityNameParts(stateObj, registries, {
@@ -221,7 +221,7 @@ export interface EntityPickerDisplayOptions extends HomeAssistantRegistries {
export const computeEntityPickerDisplay = (
options: EntityPickerDisplayOptions,
stateObj: HassEntityState
stateObj: HassEntity
): EntityPickerDisplay => {
const parts = computeEntityNameParts(stateObj, options);
@@ -1,6 +1,6 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { HomeAssistantFormatters } from "../../types";
import type { HomeAssistant } from "../../types";
import { unitFromParts } from "./value_parts";
interface EntityUnitStubConfig {
@@ -12,14 +12,14 @@ interface EntityUnitStubConfig {
/**
* Computes the display unit for an entity.
*
* @param formatters - Entity formatters
* @param hass - Home Assistant instance
* @param stateObj - Entity state object
* @param config - Element configuration
* @returns Computed entity unit
*/
export const computeEntityUnitDisplay = (
formatters: HomeAssistantFormatters,
stateObj: HassEntityState | undefined,
hass: HomeAssistant,
stateObj: HassEntity | undefined,
config: EntityUnitStubConfig
): string => {
if (
@@ -38,8 +38,8 @@ export const computeEntityUnitDisplay = (
// otherwise derive from the entity's state or attribute
const parts = config.attribute
? formatters.formatEntityAttributeValueToParts(stateObj, config.attribute)
: formatters.formatEntityStateToParts(stateObj);
? hass.formatEntityAttributeValueToParts(stateObj, config.attribute)
: hass.formatEntityStateToParts(stateObj);
return unitFromParts(parts);
};
+13 -17
View File
@@ -1,11 +1,10 @@
import { parseISO } from "date-fns";
import type { HassConfig, HassEntityState } from "home-assistant-js-websocket";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
import type { FrontendLocaleData } from "../../data/translation";
import { TimeZone } from "../../data/translation";
import type { HomeAssistant, ValuePart } from "../../types";
import { formatDateNumeric } from "../datetime/format_date";
import { formatDate } from "../datetime/format_date";
import { formatDateTime } from "../datetime/format_date_time";
import { DURATION_UNITS, formatDuration } from "../datetime/format_duration";
import { formatTime } from "../datetime/format_time";
@@ -15,7 +14,6 @@ import {
getNumberFormatOptions,
isNumericFromAttributes,
} from "../number/format_number";
import { isDate } from "../string/is_date";
import { blankBeforeUnit } from "../translations/blank_before_unit";
import type { LocalizeFunc } from "../translations/localize";
import { computeDomain } from "./compute_domain";
@@ -44,7 +42,7 @@ const NUMERICAL_DOMAINS = ["counter", "input_number", "number"];
export const computeStateDisplay = (
localize: LocalizeFunc,
stateObj: HassEntityState,
stateObj: HassEntity,
locale: FrontendLocaleData,
config: HassConfig,
entities: HomeAssistant["entities"],
@@ -146,7 +144,7 @@ const computeStateToPartsFromEntityAttributes = (
minimumFractionDigits: 2,
// Override monetary options with number format
...getNumberFormatOptions(
{ state, attributes } as HassEntityState,
{ state, attributes } as HassEntity,
entity
),
});
@@ -177,7 +175,7 @@ const computeStateToPartsFromEntityAttributes = (
const value = formatNumber(
state,
locale,
getNumberFormatOptions({ state, attributes } as HassEntityState, entity)
getNumberFormatOptions({ state, attributes } as HassEntity, entity)
);
const unit =
@@ -198,9 +196,7 @@ const computeStateToPartsFromEntityAttributes = (
return [{ type: "value", value: value }];
}
const isDateSensor = isSensorDomain && attributes.device_class === "date";
if (DATE_TIME_DOMAINS.has(domain) || isDateSensor) {
if (DATE_TIME_DOMAINS.has(domain)) {
// If trying to display an explicit state, need to parse the explicit state to `Date` then format.
// Attributes aren't available, we have to use `state`.
@@ -221,15 +217,15 @@ const computeStateToPartsFromEntityAttributes = (
];
}
if (components.length === 1) {
if (isDate(state)) {
// Parse and format date-only values in UTC to preserve the calendar day.
if (state.includes("-")) {
// Date only.
return [
{
type: "value",
value: formatDateNumeric(
parseISO(`${state}T00:00:00Z`),
{ ...locale, time_zone: TimeZone.server },
{ ...config, time_zone: "UTC" }
value: formatDate(
new Date(`${state}T00:00`),
{ ...locale, time_zone: TimeZone.local },
config
),
},
];
@@ -298,7 +294,7 @@ const computeStateToPartsFromEntityAttributes = (
export const computeStateToParts = (
localize: LocalizeFunc,
stateObj: HassEntityState,
stateObj: HassEntity,
locale: FrontendLocaleData,
config: HassConfig,
entities: HomeAssistant["entities"],
+2 -2
View File
@@ -1,5 +1,5 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { computeDomain } from "./compute_domain";
export const computeStateDomain = (stateObj: HassEntityState) =>
export const computeStateDomain = (stateObj: HassEntity) =>
computeDomain(stateObj.entity_id);
+2 -2
View File
@@ -1,4 +1,4 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { computeObjectId } from "./compute_object_id";
export const computeStateNameFromEntityAttributes = (
@@ -9,5 +9,5 @@ export const computeStateNameFromEntityAttributes = (
? computeObjectId(entityId).replace(/_/g, " ")
: (attributes.friendly_name ?? "").toString();
export const computeStateName = (stateObj: HassEntityState): string =>
export const computeStateName = (stateObj: HassEntity): string =>
computeStateNameFromEntityAttributes(stateObj.entity_id, stateObj.attributes);
@@ -1,4 +1,4 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import type { AreaRegistryEntry } from "../../../data/area/area_registry";
import type { DeviceRegistryEntry } from "../../../data/device/device_registry";
import type {
@@ -19,7 +19,7 @@ interface EntityContext {
}
export const getEntityContext = (
stateObj: HassEntityState,
stateObj: HassEntity,
entities: HomeAssistant["entities"],
devices: HomeAssistant["devices"],
areas: HomeAssistant["areas"],
+3 -3
View File
@@ -9,9 +9,9 @@ import {
mdiGate,
mdiGateOpen,
} from "@mdi/js";
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
export const computeOpenIcon = (stateObj: HassEntityState): string => {
export const computeOpenIcon = (stateObj: HassEntity): string => {
switch (stateObj.attributes.device_class) {
case "door":
return mdiDoorOpen;
@@ -26,7 +26,7 @@ export const computeOpenIcon = (stateObj: HassEntityState): string => {
}
};
export const computeCloseIcon = (stateObj: HassEntityState): string => {
export const computeCloseIcon = (stateObj: HassEntity): string => {
switch (stateObj.attributes.device_class) {
case "door":
return mdiDoorClosed;
+2 -5
View File
@@ -1,9 +1,6 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
export const deviceTrackerIcon = (
stateObj: HassEntityState,
state?: string
) => {
export const deviceTrackerIcon = (stateObj: HassEntity, state?: string) => {
const compareState = state ?? stateObj.state;
if (stateObj?.attributes.source_type === "router") {
return compareState === "home" ? "mdi:lan-connect" : "mdi:lan-disconnect";
+18 -68
View File
@@ -1,10 +1,8 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import memoizeOne from "memoize-one";
import type { HassEntity } from "home-assistant-js-websocket";
import type { HomeAssistant } from "../../types";
import { ensureArray } from "../array/ensure-array";
import { computeDomain } from "./compute_domain";
import { getEntityContext } from "./context/get_entity_context";
import { getEntityIds } from "./get_entity_ids";
type EntityCategory = "none" | "config" | "diagnostic";
@@ -68,7 +66,7 @@ export const generateEntityFilter = (
: undefined;
return (entityId: string) => {
const stateObj = states[entityId] as HassEntityState | undefined;
const stateObj = states[entityId] as HassEntity | undefined;
if (!stateObj) {
return false;
}
@@ -165,9 +163,21 @@ 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[]
filters: EntityFilter[],
excludedEntityIds?: string[]
): string[] => {
const filterFuncs = filters.map((filter) =>
generateEntityFilter(
@@ -179,68 +189,8 @@ export const findFilteredEntities = (
filter
)
);
return findEntities(Object.keys(sources.states), filterFuncs);
};
export type EntityFinder = (
states: HomeAssistant["states"],
entities: HomeAssistant["entities"],
devices: HomeAssistant["devices"],
areas: HomeAssistant["areas"],
floors: HomeAssistant["floors"]
) => string[];
/**
* Finds the same entities as `findFilteredEntities`, for repeated calls.
* Of a state, the filters only read its device class, so everything else is
* matched again only when the entity ids or the registries change.
*/
export const createEntityFinder = (filters: EntityFilter[]): EntityFinder => {
const registryFilters = filters.map(
({ device_class: _deviceClass, ...filter }) => filter
);
const deviceClasses = filters.map((filter) =>
filter.device_class ? new Set(ensureArray(filter.device_class)) : undefined
);
let candidatesKey: unknown[] = [];
let candidates: string[][] = [];
return memoizeOne<EntityFinder>(
(states, entities, devices, areas, floors) => {
const entityIds = getEntityIds(states);
const key = [entityIds, entities, devices, areas, floors];
if (key.some((value, i) => value !== candidatesKey[i])) {
candidatesKey = key;
candidates = registryFilters.map((filter) =>
entityIds.filter(
generateEntityFilter(
states,
entities,
devices,
areas,
floors,
filter
)
)
);
}
const seen = new Set<string>();
const results: string[] = [];
candidates.forEach((candidateIds, i) => {
const classes = deviceClasses[i];
for (const entityId of candidateIds) {
if (
!seen.has(entityId) &&
(!classes ||
classes.has(states[entityId].attributes.device_class || "none"))
) {
seen.add(entityId);
results.push(entityId);
}
}
});
return results;
}
return excludeEntities(
findEntities(Object.keys(sources.states), filterFuncs),
excludedEntityIds
);
};
+2 -2
View File
@@ -1,9 +1,9 @@
import type { HassEntityStates } from "home-assistant-js-websocket";
import type { HassEntities } from "home-assistant-js-websocket";
import type { GroupEntity } from "../../data/group";
import { DEFAULT_VIEW_ENTITY_ID } from "../const";
// Return an ordered array of available views
export const extractViews = (entities: HassEntityStates): GroupEntity[] => {
export const extractViews = (entities: HassEntities): GroupEntity[] => {
const views: GroupEntity[] = [];
Object.keys(entities).forEach((entityId) => {
-22
View File
@@ -1,22 +0,0 @@
import type { HomeAssistant } from "../../types";
let lastStates: HomeAssistant["states"] | undefined;
let lastEntityIds: string[] = [];
/**
* Returns the ids of `states`, as the same array for as long as they stay the
* same, so callers can memoize on it.
*/
export const getEntityIds = (states: HomeAssistant["states"]): string[] => {
if (states !== lastStates) {
lastStates = states;
const entityIds = Object.keys(states);
if (
entityIds.length !== lastEntityIds.length ||
entityIds.some((entityId, i) => entityId !== lastEntityIds[i])
) {
lastEntityIds = entityIds;
}
}
return lastEntityIds;
};
+5 -8
View File
@@ -1,7 +1,4 @@
import type {
HassEntityStates,
HassEntityState,
} from "home-assistant-js-websocket";
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import { computeStateDomain } from "./compute_state_domain";
export interface EntityLocation {
@@ -12,8 +9,8 @@ export interface EntityLocation {
export const findFirstActiveZone = (
inZones: readonly string[],
states: HassEntityStates
): HassEntityState | undefined => {
states: HassEntities
): HassEntity | undefined => {
for (const zoneId of inZones) {
const zone = states[zoneId];
if (
@@ -29,8 +26,8 @@ export const findFirstActiveZone = (
};
export const getEntityLocation = (
stateObj: HassEntityState,
states: HassEntityStates
stateObj: HassEntity,
states: HassEntities
): EntityLocation | undefined => {
const {
latitude,
+2 -2
View File
@@ -1,8 +1,8 @@
import type { HassEntityStates } from "home-assistant-js-websocket";
import type { HassEntities } from "home-assistant-js-websocket";
import type { GroupEntity } from "../../data/group";
export const getGroupEntities = (
entities: HassEntityStates,
entities: HassEntities,
group: GroupEntity
) => {
const result = {};
+4 -47
View File
@@ -1,10 +1,5 @@
import type {
HassEntityStates,
HassEntityState,
} from "home-assistant-js-websocket";
import { HVAC_MODES } from "../../data/climate";
import type { HassEntities, HassEntity } from "home-assistant-js-websocket";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import { OPERATION_MODES } from "../../data/water_heater";
import { stringCompare } from "../string/compare";
import { computeDomain } from "./compute_domain";
import { computeStateDomain } from "./compute_state_domain";
@@ -252,7 +247,7 @@ const FIXED_DOMAIN_ATTRIBUTE_STATES = {
};
export const getStatesDomain = (
states: HassEntityStates,
states: HassEntities,
language: string,
domain: string,
attribute?: string | undefined
@@ -360,44 +355,6 @@ const DOMAIN_VALUE_ATTRIBUTES: Record<
])
);
// Options shown in a fixed order, whatever order the entity lists them in.
// Keyed like DOMAIN_OPTIONS_ATTRIBUTES (`_` = main state).
const DOMAIN_OPTIONS_ORDER: Record<
string,
Record<string, readonly string[]>
> = {
climate: {
_: HVAC_MODES,
},
water_heater: {
_: OPERATION_MODES,
operation_mode: OPERATION_MODES,
},
};
export const hasFixedStatesOrder = (
domain: string,
attribute: string | undefined
): boolean => DOMAIN_OPTIONS_ORDER[domain]?.[attribute ?? "_"] !== undefined;
// States missing from the order keep their position.
export const orderStates = (
domain: string,
attribute: string | undefined,
states: string[]
): string[] => {
const order = DOMAIN_OPTIONS_ORDER[domain]?.[attribute ?? "_"];
if (!order) {
return states;
}
const orderedStates = states
.filter((state) => order.includes(state))
.sort((a, b) => order.indexOf(a) - order.indexOf(b));
return states.map((state) =>
order.includes(state) ? orderedStates.shift()! : state
);
};
// value attribute (or main state) → its options-list attribute
export const getOptionsAttribute = (
domain: string,
@@ -411,9 +368,9 @@ export const getValueAttribute = (
): string | undefined => DOMAIN_VALUE_ATTRIBUTES[domain]?.[optionsAttribute];
export const getStates = (
states: HassEntityStates,
states: HassEntities,
language: string,
stateObj: HassEntityState,
stateObj: HassEntity,
attribute: string | undefined = undefined
): string[] => {
const domain = computeStateDomain(stateObj);
-2
View File
@@ -3,7 +3,6 @@ import { ClimateEntityFeature } from "../../data/feature/climate_entity_feature"
import { CoverEntityFeature } from "../../data/feature/cover_entity_feature";
import { MediaPlayerEntityFeature } from "../../data/feature/media-player_entity_feature";
import { SirenEntityFeature } from "../../data/feature/siren_entity_feature";
import { ValveEntityFeature } from "../../data/feature/valve_entity_feature";
// These are domains which have nonstandard 'toggle' behavior.
// Otherwise, any domain with a turn_on and turn_off service may be toggled.
@@ -59,7 +58,6 @@ export const SPECIAL_TOGGLE_ACTIONS: Record<string, SpecialToggleAction> = {
valve: {
on: "open_valve",
off: "close_valve",
feature: [ValveEntityFeature.OPEN, ValveEntityFeature.CLOSE],
},
};
+3 -3
View File
@@ -1,4 +1,4 @@
import type { HassEntityStates } from "home-assistant-js-websocket";
import type { HassEntities } from "home-assistant-js-websocket";
import type { GroupEntity } from "../../data/group";
import { computeDomain } from "./compute_domain";
import { getGroupEntities } from "./get_group_entities";
@@ -6,9 +6,9 @@ import { getGroupEntities } from "./get_group_entities";
// Return an object containing all entities that the view will show
// including embedded groups.
export const getViewEntities = (
entities: HassEntityStates,
entities: HassEntities,
view: GroupEntity
): HassEntityStates => {
): HassEntities => {
const viewEntities = {};
view.attributes.entity_id.forEach((entityId) => {
+3 -5
View File
@@ -1,12 +1,10 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import type { HomeAssistant } from "../../types";
import { computeStateDomain } from "./compute_state_domain";
import { getToggleAction } from "./get_toggle_action";
export const computeGroupEntitiesState = (
states: HassEntityState[]
): string => {
export const computeGroupEntitiesState = (states: HassEntity[]): string => {
if (!states.length) {
return UNAVAILABLE;
}
@@ -46,7 +44,7 @@ export const computeGroupEntitiesState = (
export const toggleGroupEntities = (
hass: Pick<HomeAssistant, "callService">,
states: HassEntityState[]
states: HassEntity[]
) => {
if (!states.length) {
return;
+2 -2
View File
@@ -1,4 +1,4 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
export const hasLocation = (stateObj: HassEntityState) =>
export const hasLocation = (stateObj: HassEntity) =>
"latitude" in stateObj.attributes && "longitude" in stateObj.attributes;
+3 -3
View File
@@ -1,13 +1,13 @@
import type { HassEntityStates } from "home-assistant-js-websocket";
import type { HassEntities } from "home-assistant-js-websocket";
import type { GroupEntity } from "../../data/group";
import { computeDomain } from "./compute_domain";
// Split a collection into a list of groups and a 'rest' list of ungrouped
// entities.
// Returns { groups: [], ungrouped: {} }
export const splitByGroups = (entities: HassEntityStates) => {
export const splitByGroups = (entities: HassEntities) => {
const groups: GroupEntity[] = [];
const ungrouped: HassEntityStates = {};
const ungrouped: HassEntities = {};
Object.keys(entities).forEach((entityId) => {
const entity = entities[entityId];
+2 -5
View File
@@ -1,12 +1,9 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { OFF, UNAVAILABLE, UNKNOWN } from "../../data/entity/entity";
import { computeDomain } from "./compute_domain";
import { TIMESTAMP_STATE_DOMAINS } from "../const";
export function stateActive(
stateObj: HassEntityState,
state?: string
): boolean {
export function stateActive(stateObj: HassEntity, state?: string): boolean {
const domain = computeDomain(stateObj.entity_id);
const compareState = state !== undefined ? state : stateObj?.state;
+4 -4
View File
@@ -1,6 +1,6 @@
import type {
HassEntityStates,
HassEntityState,
HassEntities,
HassEntity,
HassServices,
} from "home-assistant-js-websocket";
import { UNAVAILABLE } from "../../data/entity/entity";
@@ -9,9 +9,9 @@ import { canToggleState } from "./can_toggle_state";
import { computeStateDomain } from "./compute_state_domain";
export const stateCardType = (
states: HassEntityStates,
states: HassEntities,
services: HassServices,
stateObj: HassEntityState
stateObj: HassEntity
) => {
if (stateObj.state === UNAVAILABLE) {
return "display";
+5 -5
View File
@@ -1,5 +1,5 @@
/** Return a color representing a state. */
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { UNAVAILABLE } from "../../data/entity/entity";
import type { GroupEntity } from "../../data/group";
import { computeGroupDomain } from "../../data/group";
@@ -44,7 +44,7 @@ const STATE_COLORED_DOMAIN = new Set([
"weather",
]);
export const stateColorCss = (stateObj: HassEntityState, state?: string) => {
export const stateColorCss = (stateObj: HassEntity, state?: string) => {
const compareState = state !== undefined ? state : stateObj?.state;
if (compareState === UNAVAILABLE) {
return `var(--state-unavailable-color)`;
@@ -60,7 +60,7 @@ export const stateColorCss = (stateObj: HassEntityState, state?: string) => {
export const domainStateColorProperties = (
domain: string,
stateObj: HassEntityState,
stateObj: HassEntity,
state?: string
): string[] => {
const compareState = state !== undefined ? state : stateObj.state;
@@ -99,7 +99,7 @@ export const domainColorProperties = (
};
export const stateColorProperties = (
stateObj: HassEntityState,
stateObj: HassEntity,
state?: string
): string[] | undefined => {
const compareState = state !== undefined ? state : stateObj?.state;
@@ -129,7 +129,7 @@ export const stateColorProperties = (
return undefined;
};
export const stateColorBrightness = (stateObj: HassEntityState): string => {
export const stateColorBrightness = (stateObj: HassEntity): string => {
if (
stateObj.attributes.brightness &&
computeDomain(stateObj.entity_id) !== "plant"
+2 -2
View File
@@ -1,10 +1,10 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import { computeStateDomain } from "./compute_state_domain";
import { updateIcon } from "./update_icon";
import { deviceTrackerIcon } from "./device_tracker_icon";
export const stateIcon = (
stateObj: HassEntityState,
stateObj: HassEntity,
state?: string
): string | undefined => {
const domain = computeStateDomain(stateObj);
+2 -2
View File
@@ -1,7 +1,7 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
export const supportsFeature = (
stateObj: HassEntityState,
stateObj: HassEntity,
feature: number
): boolean => supportsFeatureFromAttributes(stateObj.attributes, feature);
+2 -2
View File
@@ -1,8 +1,8 @@
import type { HassEntityState } from "home-assistant-js-websocket";
import type { HassEntity } from "home-assistant-js-websocket";
import type { UpdateEntity } from "../../data/update";
import { updateIsInstalling } from "../../data/update";
export const updateIcon = (stateObj: HassEntityState, state?: string) => {
export const updateIcon = (stateObj: HassEntity, state?: string) => {
const compareState = state ?? stateObj.state;
// An install can be in progress even when the state is "off", e.g. when
// downgrading firmware. Show the installing icon regardless of state.
@@ -1,5 +1,4 @@
import { html } from "lit";
import type { HassConfig } from "home-assistant-js-websocket";
import { getConfigEntries } from "../../data/config_entries";
import { domainToName } from "../../data/integration";
import { getIntegrationDescriptions } from "../../data/integrations";
@@ -7,11 +6,7 @@ import { showConfigFlowDialog } from "../../dialogs/config-flow/show-dialog-conf
import { showConfirmationDialog } from "../../dialogs/generic/show-dialog-box";
import { showMatterAddDeviceDialog } from "../../panels/config/integrations/integration-panels/matter/show-dialog-add-matter-device";
import { showZWaveJSAddNodeDialog } from "../../panels/config/integrations/integration-panels/zwave_js/add-node/show-dialog-zwave_js-add-node";
import type { LocalizeFunc } from "../translations/localize";
import type {
HomeAssistantApi,
HomeAssistantInternationalization,
} from "../../types";
import type { HomeAssistant } from "../../types";
import { documentationUrl } from "../../util/documentation-url";
import { isComponentLoaded } from "../config/is_component_loaded";
import { navigate } from "../navigate";
@@ -20,20 +15,17 @@ export const PROTOCOL_INTEGRATIONS = ["zha", "zwave_js", "matter"] as const;
export const protocolIntegrationPicked = async (
element: HTMLElement,
callWS: HomeAssistantApi["callWS"],
localize: LocalizeFunc,
loadBackendTranslation: HomeAssistantInternationalization["loadBackendTranslation"],
hassConfig: HassConfig,
hass: HomeAssistant,
domain: string,
options?: { brand?: string; domain?: string; config_entry?: string }
) => {
if (options?.domain) {
const titleLocalize = await loadBackendTranslation("title", options.domain);
options.domain = domainToName(titleLocalize, options.domain);
const localize = await hass.loadBackendTranslation("title", options.domain);
options.domain = domainToName(localize, options.domain);
}
if (options?.brand) {
const integrationDescriptions = await getIntegrationDescriptions(callWS);
const integrationDescriptions = await getIntegrationDescriptions(hass);
options.brand =
integrationDescriptions.core.integration[options.brand]?.name ||
options.brand;
@@ -43,40 +35,37 @@ export const protocolIntegrationPicked = async (
const entries = options?.config_entry
? undefined
: (
await getConfigEntries(
{ callWS },
{
domain,
}
)
await getConfigEntries(hass, {
domain,
})
).filter((e) => !e.disabled_by);
if (
!isComponentLoaded(hassConfig, "zwave_js") ||
!isComponentLoaded(hass.config, "zwave_js") ||
(!options?.config_entry && !entries?.length)
) {
// If the component isn't loaded, ask them to load the integration first
showConfirmationDialog(element, {
title: localize(
title: hass.localize(
"ui.panel.config.integrations.config_flow.missing_zwave_zigbee_title",
{ integration: "Z-Wave" }
),
text: localize(
text: hass.localize(
"ui.panel.config.integrations.config_flow.missing_zwave_zigbee",
{
integration: "Z-Wave",
brand: options?.brand || options?.domain || "Z-Wave",
supported_hardware_link: html`<a
href=${documentationUrl({ config: hassConfig }, "/docs/z-wave/controllers")}
href=${documentationUrl(hass, "/docs/z-wave/controllers")}
target="_blank"
rel="noreferrer"
>${localize(
>${hass.localize(
"ui.panel.config.integrations.config_flow.supported_hardware"
)}</a
>`,
}
),
confirmText: localize(
confirmText: hass.localize(
"ui.panel.config.integrations.config_flow.proceed"
),
confirm: () => {
@@ -95,43 +84,40 @@ export const protocolIntegrationPicked = async (
const entries = options?.config_entry
? undefined
: (
await getConfigEntries(
{ callWS },
{
domain,
}
)
await getConfigEntries(hass, {
domain,
})
).filter((e) => !e.disabled_by);
if (
!isComponentLoaded(hassConfig, "zha") ||
!isComponentLoaded(hass.config, "zha") ||
(!options?.config_entry && !entries?.length)
) {
// If the component isn't loaded, ask them to load the integration first
showConfirmationDialog(element, {
title: localize(
title: hass.localize(
"ui.panel.config.integrations.config_flow.missing_zwave_zigbee_title",
{ integration: "Zigbee" }
),
text: localize(
text: hass.localize(
"ui.panel.config.integrations.config_flow.missing_zwave_zigbee",
{
integration: "Zigbee",
brand: options?.brand || options?.domain || "Zigbee",
supported_hardware_link: html`<a
href=${documentationUrl(
{ config: hassConfig },
hass,
"/integrations/zha/#known-working-zigbee-radio-modules"
)}
target="_blank"
rel="noreferrer"
>${localize(
>${hass.localize(
"ui.panel.config.integrations.config_flow.supported_hardware"
)}</a
>`,
}
),
confirmText: localize(
confirmText: hass.localize(
"ui.panel.config.integrations.config_flow.proceed"
),
confirm: () => {
@@ -148,39 +134,36 @@ export const protocolIntegrationPicked = async (
const entries = options?.config_entry
? undefined
: (
await getConfigEntries(
{ callWS },
{
domain,
}
)
await getConfigEntries(hass, {
domain,
})
).filter((e) => !e.disabled_by);
if (
!isComponentLoaded(hassConfig, domain) ||
!isComponentLoaded(hass.config, domain) ||
(!options?.config_entry && !entries?.length)
) {
// If the component isn't loaded, ask them to load the integration first
showConfirmationDialog(element, {
title: localize(
title: hass.localize(
"ui.panel.config.integrations.config_flow.missing_zwave_zigbee_title",
{ integration: "Matter" }
),
text: localize(
text: hass.localize(
"ui.panel.config.integrations.config_flow.missing_matter",
{
integration: "Matter",
brand: options?.brand || options?.domain || "Matter",
supported_hardware_link: html`<a
href=${documentationUrl({ config: hassConfig }, "/integrations/matter")}
href=${documentationUrl(hass, "/integrations/matter")}
target="_blank"
rel="noreferrer"
>${localize(
>${hass.localize(
"ui.panel.config.integrations.config_flow.supported_hardware"
)}</a
>`,
}
),
confirmText: localize(
confirmText: hass.localize(
"ui.panel.config.integrations.config_flow.proceed"
),
confirm: () => {
+13 -46
View File
@@ -1,12 +1,9 @@
/// <reference types="leaflet.markercluster" />
import type {
CircleMarker,
Control,
DivIcon,
Map,
MarkerCluster,
MarkerClusterGroup,
MarkerClusterGroupOptions,
Polyline,
} from "leaflet";
import type { LeafletModuleType } from "../../dom/setup-leaflet-map";
@@ -39,18 +36,8 @@ interface HandledMarker extends DecoratedMarker {
interface LeafletMarkerHandle extends MapMarkerHandle {
marker: HandledMarker;
title?: string;
}
// v2 option the 1.x types don't know yet
interface ClusterGroupOptions extends MarkerClusterGroupOptions {
clusterLabel?(cluster: MarkerCluster): string;
}
// Stands in for getAnimations on browsers without it (Chrome before 84),
// which markercluster calls whenever the map zooms
const noAnimations = (): Animation[] => [];
/** The Leaflet engine: raster viewing fallback without WebGL2, no editing */
export class LeafletMapEngine implements MapEngine {
/** For the ha-map jsdom tests only */
@@ -62,14 +49,10 @@ export class LeafletMapEngine implements MapEngine {
private _clusterable: HandledMarker[] = [];
private _MarkerClusterGroup?: typeof MarkerClusterGroup;
private _cluster?: MarkerClusterGroup;
private _clusterOptions: MapClusterOptions | null = null;
private _animateClusters = true;
private _scaleControl?: Control.Scale;
public async init(
@@ -83,26 +66,22 @@ export class LeafletMapEngine implements MapEngine {
// eslint-disable-next-line
const Leaflet = (await import("leaflet")).default as LeafletModuleType;
Leaflet.Icon.Default.imagePath = "/static/images/leaflet/images/";
// The package's own types are for Leaflet 2; on our Leaflet 1.9,
// @types/leaflet.markercluster describes it
this._MarkerClusterGroup = (await import("leaflet.markercluster"))
.MarkerClusterGroup as unknown as typeof MarkerClusterGroup;
// Without a native getAnimations, markercluster can't cancel the
// animations a zoom interrupts, so clusters don't animate there
this._animateClusters =
"getAnimations" in Element.prototype &&
Element.prototype.getAnimations !== noAnimations;
Element.prototype.getAnimations ??= noAnimations;
await import("leaflet.markercluster");
const map = Leaflet.map(container, {
minZoom: MAP_MIN_ZOOM,
maxZoom: MAP_MAX_ZOOM,
});
map.attributionControl.setPrefix("");
const style = document.createElement("link");
style.setAttribute("href", "/static/images/leaflet/leaflet.css");
style.setAttribute("rel", "stylesheet");
root.appendChild(style);
for (const href of [
"/static/images/leaflet/leaflet.css",
"/static/images/leaflet/MarkerCluster.css",
]) {
const style = document.createElement("link");
style.setAttribute("href", href);
style.setAttribute("rel", "stylesheet");
root.appendChild(style);
}
map.setView(options.center, options.zoom);
// The base layer adds itself; a vector layer may still fall back to raster
@@ -278,7 +257,6 @@ export class LeafletMapEngine implements MapEngine {
const handle: LeafletMarkerHandle = {
marker,
location,
title: options.title,
clusterData: options.clusterData,
remove: () => {
this._cluster?.removeLayer(marker);
@@ -367,27 +345,18 @@ export class LeafletMapEngine implements MapEngine {
this._cluster = undefined;
}
this._clusterOptions = options;
if (!this.leafletMap || !this.Leaflet || !this._MarkerClusterGroup) {
if (!this.leafletMap || !this.Leaflet) {
return;
}
if (!options) {
this._clusterable.forEach((marker) => marker.addTo(this.leafletMap!));
return;
}
// markercluster groups by proximity only; groupKey is not supported here
const clusterOptions: ClusterGroupOptions = {
this._cluster = this.Leaflet.markerClusterGroup({
showCoverageOnHover: false,
removeOutsideVisibleBounds: false,
animate: this._animateClusters,
maxClusterRadius: options.radius,
// The members' names, as the MapLibre engine labels its clusters
clusterLabel: (cluster) =>
(cluster.getAllChildMarkers() as HandledMarker[])
.map((marker) => marker.engineHandle?.title)
.filter(Boolean)
.join(", "),
iconCreateFunction: (cluster) => {
const build = () => {
const members = (cluster.getAllChildMarkers() as HandledMarker[]).map(
@@ -428,9 +397,7 @@ export class LeafletMapEngine implements MapEngine {
createShadow: () => null,
} as unknown as DivIcon;
},
};
this._cluster = new this._MarkerClusterGroup(clusterOptions);
});
this._cluster.addLayers(this._clusterable);
this.leafletMap!.addLayer(this._cluster!);
}
@@ -849,9 +849,6 @@ export class MapLibreMapEngine implements MapEngine {
if (!interactive) {
// Leaflet lets input through non-interactive markers; MapLibre does not
element.style.pointerEvents = "none";
} else {
// Leaflet points at what takes a click; MapLibre leaves the map's grab
element.style.cursor = "pointer";
}
setMarkerAccessibility(element, options.title, focusable);
element.style.zIndex = options.raised ? "1" : "";
@@ -1049,8 +1046,6 @@ export class MapLibreMapEngine implements MapEngine {
setMarkerAccessibility(centerEl, options.title, !!options.onClick);
if (options.moveable) {
centerEl.style.cursor = "move";
} else if (options.onClick) {
centerEl.style.cursor = "pointer";
}
this._placedElements.add(centerEl);
const centerMarker = new maplibre.Marker({
@@ -1655,7 +1650,6 @@ export class MapLibreMapEngine implements MapEngine {
this._hideEmerging(members);
};
setMarkerAccessibility(icon.element, this._groupTitle(group), true);
icon.element.style.cursor = "pointer";
icon.element.addEventListener("click", (ev) => {
ev.stopPropagation();
zoomToMembers();
+1 -24
View File
@@ -108,32 +108,9 @@ const addAtmosphere = (style: StyleSpecification): StyleSpecification => ({
sky: { ...style.sky, "atmosphere-blend": ATMOSPHERE_BLEND },
});
// MapLibre keeps the globe until it blends into mercator between zoom 11 and
// 12, but unbuffered ocean polygons leave hairline gaps between tiles on it
// from about zoom 6. Flatten it earlier, between zoom 5 and 6.
const GLOBE_FLATTEN_ZOOM = 5;
const flattenGlobeEarly = (style: StyleSpecification): StyleSpecification =>
style.projection?.type === "globe"
? {
...style,
projection: {
type: [
"interpolate",
["linear"],
["zoom"],
GLOBE_FLATTEN_ZOOM,
"vertical-perspective",
GLOBE_FLATTEN_ZOOM + 1,
"mercator",
],
},
}
: style;
/** Everything a freshly built style needs before it is handed to MapLibre */
export const finalizeMapStyle = (
name: string,
style: StyleSpecification
): StyleSpecification =>
flattenGlobeEarly(addAtmosphere(addLatinLabels(useTileJson(name, style))));
addAtmosphere(addLatinLabels(useTileJson(name, style)));
+3 -1
View File
@@ -1,6 +1,5 @@
import {
closeAllDialogs,
DIALOG_WAIT_TIMEOUT,
updateClosedDialogSearch,
} from "../dialogs/make-dialog-manager";
import { fireEvent } from "./dom/fire_event";
@@ -26,6 +25,9 @@ export interface NavigateOptions {
keepDialogs?: boolean;
}
// max time to wait for dialogs to close before navigating
const DIALOG_WAIT_TIMEOUT = 500;
/**
* State of the current history entry. Always read through this, the app writes
* to the main window and a panel running in an iframe has its own history.
+5 -15
View File
@@ -1,22 +1,21 @@
import type {
HassEntityState,
HassEntityStateAttributeBase,
HassEntity,
HassEntityAttributeBase,
} from "home-assistant-js-websocket";
import type { EntityRegistryDisplayEntry } from "../../data/entity/entity_registry";
import type { FrontendLocaleData } from "../../data/translation";
import { NumberFormat } from "../../data/translation";
import { getLocaleDataVersion } from "../../resources/polyfills/locale-data-polyfill";
import { blankBeforeUnit } from "../translations/blank_before_unit";
/**
* Returns true if the entity is considered numeric based on the attributes it has
* @param stateObj The entity state object
*/
export const isNumericState = (stateObj: HassEntityState): boolean =>
export const isNumericState = (stateObj: HassEntity): boolean =>
isNumericFromAttributes(stateObj.attributes);
export const isNumericFromAttributes = (
attributes: HassEntityStateAttributeBase
attributes: HassEntityAttributeBase
): boolean => !!attributes.unit_of_measurement || !!attributes.state_class;
export const numberFormatToLocale = (
@@ -43,20 +42,11 @@ export const numberFormatToLocale = (
// (locale, options) combinations is small and bounded in practice, so cache the
// instances instead of rebuilding them on every call.
const numberFormatCache = new Map<string, Intl.NumberFormat>();
let numberFormatCacheVersion = getLocaleDataVersion();
const getNumberFormatter = (
locale: string | string[] | undefined,
options: Intl.NumberFormatOptions
): Intl.NumberFormat => {
// The Intl polyfill falls back to another locale while the data for the
// requested one is still loading, e.g. right after a language change.
// Start over when locale data is added, so the cache doesn't keep those.
const version = getLocaleDataVersion();
if (version !== numberFormatCacheVersion) {
numberFormatCache.clear();
numberFormatCacheVersion = version;
}
const key = JSON.stringify([locale, options]);
let formatter = numberFormatCache.get(key);
if (!formatter) {
@@ -152,7 +142,7 @@ export const formatNumberToParts = (
* @returns An `Intl.NumberFormatOptions` object with `maximumFractionDigits` set to 0, or `undefined`
*/
export const getNumberFormatOptions = (
entityState?: HassEntityState,
entityState?: HassEntity,
entity?: EntityRegistryDisplayEntry
): Intl.NumberFormatOptions | undefined => {
const precision = entity?.display_precision;
+7 -7
View File
@@ -1,4 +1,4 @@
import type { HassConfig, HassEntityState } from "home-assistant-js-websocket";
import type { HassConfig, HassEntity } from "home-assistant-js-websocket";
import type { FrontendLocaleData } from "../../data/translation";
import type { HomeAssistant, ValuePart } from "../../types";
import {
@@ -9,30 +9,30 @@ import {
import type { LocalizeFunc } from "./localize";
export type FormatEntityStateFunc = (
stateObj: HassEntityState,
stateObj: HassEntity,
state?: string
) => string;
export type FormatEntityStateToPartsFunc = (
stateObj: HassEntityState,
stateObj: HassEntity,
state?: string
) => ValuePart[];
export type FormatEntityAttributeValueFunc = (
stateObj: HassEntityState,
stateObj: HassEntity,
attribute: string,
value?: any
) => string;
export type FormatEntityAttributeValueToPartsFunc = (
stateObj: HassEntityState,
stateObj: HassEntity,
attribute: string,
value?: any
) => ValuePart[];
export type FormatEntityAttributeNameFunc = (
stateObj: HassEntityState,
stateObj: HassEntity,
attribute: string
) => string;
export type FormatEntityNameFunc = (
stateObj: HassEntityState,
stateObj: HassEntity,
name?: string | EntityNameItem | EntityNameItem[],
options?: EntityNameOptions
) => string;
+26 -38
View File
@@ -1,15 +1,9 @@
import type {
DataTableFilter,
DataTableFilters,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
floorAreasFilterFromParams,
floorAreasFilterParams,
listFilterFromParams,
listFilterIds,
listFilterNone,
} from "./filter-query-params";
import {
createQueryString,
decodeQueryParams,
@@ -32,33 +26,33 @@ export const automationsFilterQueryParamConfig = {
"assistants",
"blueprint",
],
boolean: [
{ key: "no_area", trueValue: "1" },
{ key: "no_label", trueValue: "1" },
{ key: "no_category", trueValue: "1" },
{ key: "no_assistants", trueValue: "1" },
{ key: "no_blueprint", trueValue: "1" },
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type AutomationsFilterQueryParams = QueryParamValues<
typeof automationsFilterQueryParamConfig
>;
const list = (filter: DataTableFilter | undefined): string[] | undefined =>
Array.isArray(filter?.value) ? filter.value : undefined;
const floorAreas = (
filter: DataTableFilter | undefined
): FloorAreasFilterValue | undefined =>
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
export const automationsFilterQueryParams = (
filters: DataTableFilters
): AutomationsFilterQueryParams => ({
...floorAreasFilterParams(filters["ha-filter-floor-areas"]?.value),
device: listFilterIds(filters["ha-filter-devices"]?.value),
entity: listFilterIds(filters["ha-filter-entities"]?.value),
label: listFilterIds(filters["ha-filter-labels"]?.value),
no_label: listFilterNone(filters["ha-filter-labels"]?.value),
category: listFilterIds(filters["ha-filter-categories"]?.value),
no_category: listFilterNone(filters["ha-filter-categories"]?.value),
assistants: listFilterIds(filters["ha-filter-voice-assistants"]?.value),
no_assistants: listFilterNone(filters["ha-filter-voice-assistants"]?.value),
blueprint: listFilterIds(filters["ha-filter-blueprints"]?.value),
no_blueprint: listFilterNone(filters["ha-filter-blueprints"]?.value),
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"]),
category: list(filters["ha-filter-categories"]),
assistants: list(filters["ha-filter-voice-assistants"]),
blueprint: list(filters["ha-filter-blueprints"]),
});
// The filters as the URL holds them, so values that filter the same, such as
@@ -119,22 +113,16 @@ export const automationsLinkFromUrl = (
search: search ?? "",
filters: {
"ha-filter-floor-areas": filter(
floorAreasFilterFromParams(floors, areas, params.no_area)
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined
),
"ha-filter-devices": filter(values("device")),
"ha-filter-entities": filter(values("entity")),
"ha-filter-labels": filter(
listFilterFromParams(values("label"), params.no_label)
),
"ha-filter-categories": filter(
listFilterFromParams(values("category"), params.no_category)
),
"ha-filter-voice-assistants": filter(
listFilterFromParams(values("assistants"), params.no_assistants)
),
"ha-filter-blueprints": filter(
listFilterFromParams(values("blueprint"), params.no_blueprint)
),
"ha-filter-labels": filter(values("label")),
"ha-filter-categories": filter(values("category")),
"ha-filter-voice-assistants": filter(values("assistants")),
"ha-filter-blueprints": filter(values("blueprint")),
},
};
};
+15 -18
View File
@@ -1,15 +1,9 @@
import type {
DataTableFilter,
DataTableFilters,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
floorAreasFilterFromParams,
floorAreasFilterParams,
listFilterFromParams,
listFilterIds,
listFilterNone,
} from "./filter-query-params";
import {
createQueryString,
decodeQueryParams,
@@ -31,10 +25,7 @@ export const devicesFilterQueryParamConfig = {
"config_entry",
"sub_entry",
],
boolean: [
{ key: "no_area", trueValue: "1" },
{ key: "no_label", trueValue: "1" },
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type DevicesFilterQueryParams = QueryParamValues<
@@ -44,14 +35,20 @@ export type DevicesFilterQueryParams = QueryParamValues<
const list = (filter: DataTableFilter | undefined): string[] | undefined =>
Array.isArray(filter?.value) ? filter.value : undefined;
const floorAreas = (
filter: DataTableFilter | undefined
): FloorAreasFilterValue | undefined =>
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
export const devicesFilterQueryParams = (
filters: DataTableFilters
): DevicesFilterQueryParams => ({
status: list(filters["ha-filter-states"]),
...floorAreasFilterParams(filters["ha-filter-floor-areas"]?.value),
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: listFilterIds(filters["ha-filter-labels"]?.value),
no_label: listFilterNone(filters["ha-filter-labels"]?.value),
label: list(filters["ha-filter-labels"]),
config_entry: list(filters.config_entry),
sub_entry: list(filters.sub_entry),
});
@@ -110,12 +107,12 @@ export const devicesLinkFromUrl = (
filters: {
"ha-filter-states": filter(values("status")),
"ha-filter-floor-areas": filter(
floorAreasFilterFromParams(floors, areas, params.no_area)
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined
),
"ha-filter-integrations": filter(values("domain")),
"ha-filter-labels": filter(
listFilterFromParams(values("label"), params.no_label)
),
"ha-filter-labels": filter(values("label")),
config_entry: filter(values("config_entry")),
sub_entry: filter(values("sub_entry")),
},
+24 -44
View File
@@ -1,15 +1,9 @@
import type {
DataTableFiltersValue,
DataTableFiltersValues,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
floorAreasFilterFromParams,
floorAreasFilterParams,
listFilterFromParams,
listFilterIds,
listFilterNone,
} from "./filter-query-params";
import {
createQueryString,
decodeQueryParams,
@@ -37,13 +31,7 @@ export const entitiesFilterQueryParamConfig = {
// Read until 2027.5, replaced with `assistants` on the next write
"voice_assistant",
],
boolean: [
{ key: "no_area", trueValue: "1" },
{ key: "no_device", trueValue: "1" },
{ key: "no_label", trueValue: "1" },
{ key: "no_device_class", trueValue: "1" },
{ key: "no_assistants", trueValue: "1" },
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type EntitiesFilterQueryParams = QueryParamValues<
@@ -53,21 +41,24 @@ export type EntitiesFilterQueryParams = QueryParamValues<
const list = (value: DataTableFiltersValue): string[] | undefined =>
Array.isArray(value) ? value : undefined;
const floorAreas = (
value: DataTableFiltersValue
): FloorAreasFilterValue | undefined =>
value && !Array.isArray(value) ? value : undefined;
export const entitiesFilterQueryParams = (
filters: DataTableFiltersValues
): EntitiesFilterQueryParams => ({
status: list(filters["ha-filter-states"]),
...floorAreasFilterParams(filters["ha-filter-floor-areas"]),
device: listFilterIds(filters["ha-filter-devices"]),
no_device: listFilterNone(filters["ha-filter-devices"]),
device_class: listFilterIds(filters["ha-filter-device-classes"]),
no_device_class: listFilterNone(filters["ha-filter-device-classes"]),
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"]),
entity_domain: list(filters["ha-filter-domains"]),
label: listFilterIds(filters["ha-filter-labels"]),
no_label: listFilterNone(filters["ha-filter-labels"]),
assistants: listFilterIds(filters["ha-filter-voice-assistants"]),
no_assistants: listFilterNone(filters["ha-filter-voice-assistants"]),
label: list(filters["ha-filter-labels"]),
assistants: list(filters["ha-filter-voice-assistants"]),
config_entry: list(filters.config_entry),
sub_entry: list(filters.sub_entry),
});
@@ -126,29 +117,18 @@ export const entitiesLinkFromUrl = (
search: search ?? "",
filters: {
"ha-filter-states": values("status"),
"ha-filter-floor-areas": floorAreasFilterFromParams(
floors,
areas,
params.no_area
),
"ha-filter-devices": listFilterFromParams(
values("device"),
params.no_device
),
"ha-filter-device-classes": listFilterFromParams(
values("device_class"),
params.no_device_class
),
"ha-filter-floor-areas":
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined,
"ha-filter-devices": values("device"),
"ha-filter-device-classes": values("device_class"),
"ha-filter-integrations": values("domain"),
"ha-filter-domains": values("entity_domain"),
"ha-filter-labels": listFilterFromParams(
values("label"),
params.no_label
),
"ha-filter-voice-assistants": listFilterFromParams(
assistants.length ? assistants : values("voice_assistant"),
params.no_assistants
),
"ha-filter-labels": values("label"),
"ha-filter-voice-assistants": assistants.length
? assistants
: values("voice_assistant"),
config_entry: values("config_entry"),
sub_entry: values("sub_entry"),
},
-57
View File
@@ -1,57 +0,0 @@
import type {
DataTableFiltersValue,
FloorAreasFilterValue,
ListFilterValue,
} from "../../data/data_table_filters";
import { listFilterValue } from "../../data/data_table_filters";
// Params shared by the filters of the config tables for the items without an
// area, device, label or category, like `no_label=1`.
const floorAreasValue = (
value: DataTableFiltersValue
): FloorAreasFilterValue | undefined =>
value && !Array.isArray(value) ? (value as FloorAreasFilterValue) : undefined;
/** The params of the floor and area filter. */
export const floorAreasFilterParams = (value: DataTableFiltersValue) => {
const floorAreas = floorAreasValue(value);
return {
floor: floorAreas?.floors,
area: floorAreas?.areas,
no_area: floorAreas?.no_area,
};
};
/** The ids a list filter has selected, for its list param. */
export const listFilterIds = (
value: DataTableFiltersValue
): string[] | undefined => listFilterValue(value)?.ids;
/** Whether a list filter shows the items that have none, for its `no_` param. */
export const listFilterNone = (value: DataTableFiltersValue): boolean =>
!!listFilterValue(value)?.none;
/** The floor and area filter a link asks for. */
export const floorAreasFilterFromParams = (
floors: string[],
areas: string[],
noArea: boolean | undefined
): FloorAreasFilterValue | undefined => {
if (!floors.length && !areas.length && !noArea) {
return undefined;
}
return {
floors,
areas,
...(noArea ? { no_area: true } : {}),
};
};
/** A list filter a link asks for. */
export const listFilterFromParams = (
ids: string[],
none: boolean | undefined
): ListFilterValue | string[] | undefined =>
// Without "No …" it's a plain list, as the filters send it
none ? { ids, none: true } : ids;
+31 -45
View File
@@ -1,12 +1,9 @@
import type { DataTableFiltersValues } from "../../data/data_table_filters";
import type {
DataTableFiltersValue,
DataTableFiltersValues,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
floorAreasFilterFromParams,
floorAreasFilterParams,
listFilterFromParams,
listFilterIds,
listFilterNone,
} from "./filter-query-params";
import {
createQueryString,
decodeQueryParams,
@@ -29,31 +26,31 @@ export const helpersFilterQueryParamConfig = {
// Read until 2027.5, replaced with `assistants` on the next write
"voice_assistant",
],
boolean: [
{ key: "no_area", trueValue: "1" },
{ key: "no_device", trueValue: "1" },
{ key: "no_label", trueValue: "1" },
{ key: "no_category", trueValue: "1" },
{ key: "no_assistants", trueValue: "1" },
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type HelpersFilterQueryParams = QueryParamValues<
typeof helpersFilterQueryParamConfig
>;
const list = (value: DataTableFiltersValue): string[] | undefined =>
Array.isArray(value) ? value : undefined;
const floorAreas = (
value: DataTableFiltersValue
): FloorAreasFilterValue | undefined =>
value && !Array.isArray(value) ? value : undefined;
export const helpersFilterQueryParams = (
filters: DataTableFiltersValues
): HelpersFilterQueryParams => ({
...floorAreasFilterParams(filters["ha-filter-floor-areas"]),
device: listFilterIds(filters["ha-filter-devices"]),
no_device: listFilterNone(filters["ha-filter-devices"]),
label: listFilterIds(filters["ha-filter-labels"]),
no_label: listFilterNone(filters["ha-filter-labels"]),
category: listFilterIds(filters["ha-filter-categories"]),
no_category: listFilterNone(filters["ha-filter-categories"]),
assistants: listFilterIds(filters["ha-filter-voice-assistants"]),
no_assistants: listFilterNone(filters["ha-filter-voice-assistants"]),
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"]),
assistants: list(filters["ha-filter-voice-assistants"]),
});
// The filters as the URL holds them, so values that filter the same, such as
@@ -106,27 +103,16 @@ export const helpersLinkFromUrl = (
return {
search: search ?? "",
filters: {
"ha-filter-floor-areas": floorAreasFilterFromParams(
floors,
areas,
params.no_area
),
"ha-filter-devices": listFilterFromParams(
values("device"),
params.no_device
),
"ha-filter-labels": listFilterFromParams(
values("label"),
params.no_label
),
"ha-filter-categories": listFilterFromParams(
values("category"),
params.no_category
),
"ha-filter-voice-assistants": listFilterFromParams(
assistants.length ? assistants : values("voice_assistant"),
params.no_assistants
),
"ha-filter-floor-areas":
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined,
"ha-filter-devices": values("device"),
"ha-filter-labels": values("label"),
"ha-filter-categories": values("category"),
"ha-filter-voice-assistants": assistants.length
? assistants
: values("voice_assistant"),
},
};
};
+1 -1
View File
@@ -9,7 +9,7 @@ import {
// The filters of the Marketplace tables. Search, sorting and grouping are kept
// by the data table, see data-table-query-params.
export const marketplaceFilterQueryParamConfig = {
list: ["status", "type", "source", "integration_category", "connectivity"],
list: ["status", "type", "source", "integration_category"],
} as const satisfies QueryParamConfig;
export type MarketplaceFilterQueryParams = QueryParamValues<
+24 -32
View File
@@ -1,15 +1,9 @@
import type {
DataTableFilter,
DataTableFilters,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
floorAreasFilterFromParams,
floorAreasFilterParams,
listFilterFromParams,
listFilterIds,
listFilterNone,
} from "./filter-query-params";
import {
createQueryString,
decodeQueryParams,
@@ -31,30 +25,32 @@ export const scenesFilterQueryParamConfig = {
"category",
"assistants",
],
boolean: [
{ key: "no_area", trueValue: "1" },
{ key: "no_label", trueValue: "1" },
{ key: "no_category", trueValue: "1" },
{ key: "no_assistants", trueValue: "1" },
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type ScenesFilterQueryParams = QueryParamValues<
typeof scenesFilterQueryParamConfig
>;
const list = (filter: DataTableFilter | undefined): string[] | undefined =>
Array.isArray(filter?.value) ? filter.value : undefined;
const floorAreas = (
filter: DataTableFilter | undefined
): FloorAreasFilterValue | undefined =>
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
export const scenesFilterQueryParams = (
filters: DataTableFilters
): ScenesFilterQueryParams => ({
...floorAreasFilterParams(filters["ha-filter-floor-areas"]?.value),
device: listFilterIds(filters["ha-filter-devices"]?.value),
entity: listFilterIds(filters["ha-filter-entities"]?.value),
label: listFilterIds(filters["ha-filter-labels"]?.value),
no_label: listFilterNone(filters["ha-filter-labels"]?.value),
category: listFilterIds(filters["ha-filter-categories"]?.value),
no_category: listFilterNone(filters["ha-filter-categories"]?.value),
assistants: listFilterIds(filters["ha-filter-voice-assistants"]?.value),
no_assistants: listFilterNone(filters["ha-filter-voice-assistants"]?.value),
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"]),
category: list(filters["ha-filter-categories"]),
assistants: list(filters["ha-filter-voice-assistants"]),
});
// The filters as the URL holds them, so values that filter the same, such as
@@ -110,19 +106,15 @@ export const scenesLinkFromUrl = (
search: search ?? "",
filters: {
"ha-filter-floor-areas": filter(
floorAreasFilterFromParams(floors, areas, params.no_area)
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined
),
"ha-filter-devices": filter(values("device")),
"ha-filter-entities": filter(values("entity")),
"ha-filter-labels": filter(
listFilterFromParams(values("label"), params.no_label)
),
"ha-filter-categories": filter(
listFilterFromParams(values("category"), params.no_category)
),
"ha-filter-voice-assistants": filter(
listFilterFromParams(values("assistants"), params.no_assistants)
),
"ha-filter-labels": filter(values("label")),
"ha-filter-categories": filter(values("category")),
"ha-filter-voice-assistants": filter(values("assistants")),
},
};
};
+26 -38
View File
@@ -1,15 +1,9 @@
import type {
DataTableFilter,
DataTableFilters,
FloorAreasFilterValue,
} from "../../data/data_table_filters";
import { dataTableQueryParamConfig } from "./data-table-query-params";
import {
floorAreasFilterFromParams,
floorAreasFilterParams,
listFilterFromParams,
listFilterIds,
listFilterNone,
} from "./filter-query-params";
import {
createQueryString,
decodeQueryParams,
@@ -32,33 +26,33 @@ export const scriptsFilterQueryParamConfig = {
"assistants",
"blueprint",
],
boolean: [
{ key: "no_area", trueValue: "1" },
{ key: "no_label", trueValue: "1" },
{ key: "no_category", trueValue: "1" },
{ key: "no_assistants", trueValue: "1" },
{ key: "no_blueprint", trueValue: "1" },
],
boolean: [{ key: "no_area", trueValue: "1" }],
} as const satisfies QueryParamConfig;
export type ScriptsFilterQueryParams = QueryParamValues<
typeof scriptsFilterQueryParamConfig
>;
const list = (filter: DataTableFilter | undefined): string[] | undefined =>
Array.isArray(filter?.value) ? filter.value : undefined;
const floorAreas = (
filter: DataTableFilter | undefined
): FloorAreasFilterValue | undefined =>
filter?.value && !Array.isArray(filter.value) ? filter.value : undefined;
export const scriptsFilterQueryParams = (
filters: DataTableFilters
): ScriptsFilterQueryParams => ({
...floorAreasFilterParams(filters["ha-filter-floor-areas"]?.value),
device: listFilterIds(filters["ha-filter-devices"]?.value),
entity: listFilterIds(filters["ha-filter-entities"]?.value),
label: listFilterIds(filters["ha-filter-labels"]?.value),
no_label: listFilterNone(filters["ha-filter-labels"]?.value),
category: listFilterIds(filters["ha-filter-categories"]?.value),
no_category: listFilterNone(filters["ha-filter-categories"]?.value),
assistants: listFilterIds(filters["ha-filter-voice-assistants"]?.value),
no_assistants: listFilterNone(filters["ha-filter-voice-assistants"]?.value),
blueprint: listFilterIds(filters["ha-filter-blueprints"]?.value),
no_blueprint: listFilterNone(filters["ha-filter-blueprints"]?.value),
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"]),
category: list(filters["ha-filter-categories"]),
assistants: list(filters["ha-filter-voice-assistants"]),
blueprint: list(filters["ha-filter-blueprints"]),
});
// The filters as the URL holds them, so values that filter the same, such as
@@ -114,22 +108,16 @@ export const scriptsLinkFromUrl = (
search: search ?? "",
filters: {
"ha-filter-floor-areas": filter(
floorAreasFilterFromParams(floors, areas, params.no_area)
floors.length || areas.length || params.no_area
? { floors, areas, no_area: params.no_area }
: undefined
),
"ha-filter-devices": filter(values("device")),
"ha-filter-entities": filter(values("entity")),
"ha-filter-labels": filter(
listFilterFromParams(values("label"), params.no_label)
),
"ha-filter-categories": filter(
listFilterFromParams(values("category"), params.no_category)
),
"ha-filter-voice-assistants": filter(
listFilterFromParams(values("assistants"), params.no_assistants)
),
"ha-filter-blueprints": filter(
listFilterFromParams(values("blueprint"), params.no_blueprint)
),
"ha-filter-labels": filter(values("label")),
"ha-filter-categories": filter(values("category")),
"ha-filter-voice-assistants": filter(values("assistants")),
"ha-filter-blueprints": filter(values("blueprint")),
},
};
};
@@ -37,29 +37,3 @@ export const preserveUnchangedRecord = <T>(
}
return changed ? next : previous;
};
/**
* List variant of {@link preserveUnchangedRecord}: replaces each item in `next`
* with the equal `previous` item that has the same key, in place.
*/
export const preserveUnchangedItems = <T>(
previous: readonly T[] | undefined,
next: T[],
getKey: (item: T) => string,
equal: (a: T, b: T) => boolean
): T[] => {
if (!previous?.length) {
return next;
}
const previousByKey = new Map<string, T>();
for (const item of previous) {
previousByKey.set(getKey(item), item);
}
for (let i = 0; i < next.length; i++) {
const previousItem = previousByKey.get(getKey(next[i]));
if (previousItem !== undefined && equal(previousItem, next[i])) {
next[i] = previousItem;
}
}
return next;
};
+14 -96
View File
@@ -17,21 +17,12 @@ import { consumeLocalize } from "../../common/decorators/consume-context-entry";
import { storage } from "../../common/decorators/storage";
import { deepActiveElement } from "../../common/dom/deep-active-element";
import { fireEvent, type HASSDomEvent } from "../../common/dom/fire_event";
import {
cancelEnteringFullscreen,
isEnteringFullscreen,
startEnteringFullscreen,
} from "../../common/dom/entering-fullscreen";
import { ctrlOrCmdLabel } from "../../common/keyboard/ctrl-or-cmd";
import type { LocalizeFunc } from "../../common/translations/localize";
import { nextRender } from "../../common/util/render-status";
import type { CameraCapabilities, CameraEntity } from "../../data/camera";
import type { CameraStreamStatus } from "../../data/camera-streams";
import { isExternal } from "../../data/external";
import {
showCameraStreamInfoDialog,
type CameraStreamInfo,
} from "../../dialogs/camera/show-dialog-camera-stream-info";
import { showCameraStreamInfoDialog } from "../../dialogs/camera/show-dialog-camera-stream-info";
import "../ha-camera-stream";
import type { HaCameraStream } from "../ha-camera-stream";
import "../ha-icon-button";
@@ -117,8 +108,6 @@ export class HaCameraPlayer extends LitElement {
@state() private _capabilities?: CameraCapabilities;
private _streamInfoCallbacks = new Set<(info: CameraStreamInfo) => void>();
@state() private _video?: HTMLVideoElement;
@state() private _muted = false;
@@ -148,10 +137,6 @@ export class HaCameraPlayer extends LitElement {
// full screen player
@state() private _paused = false;
// Playing when its button entered full screen, so a pause meanwhile is the
// companion app's
private _playingBeforeFullscreen = false;
@query("ha-camera-stream") private _stream?: HaCameraStream;
@query(".player") private _player?: HTMLElement;
@@ -178,16 +163,6 @@ export class HaCameraPlayer extends LitElement {
private _controlsTimeout?: number;
// A pointer type or "keyboard", as hover sticks after a tap on touch
// screens and focus moved by a script can look like keyboard focus
private _lastInput?: string;
// Captured, as dialogs stop the propagation of their key presses
private _inputChanged = (ev: KeyboardEvent | PointerEvent) => {
this._lastInput =
ev.type === "keydown" ? "keyboard" : (ev as PointerEvent).pointerType;
};
private _wheelHintTimeout?: number;
private _videoRequest = 0;
@@ -215,7 +190,7 @@ export class HaCameraPlayer extends LitElement {
public connectedCallback() {
super.connectedCallback();
document.addEventListener("visibilitychange", this._visibilityChanged);
document.addEventListener("visibilitychange", this._requestWakeLock);
// The first update requests it, once keep-awake is set
if (this.hasUpdated) {
this._requestWakeLock();
@@ -225,28 +200,19 @@ export class HaCameraPlayer extends LitElement {
"webkitfullscreenchange",
this._fullscreenChanged
);
const inputOptions = { capture: true, passive: true };
document.addEventListener("keydown", this._inputChanged, inputOptions);
document.addEventListener("pointerdown", this._inputChanged, inputOptions);
if (this._controlsVisible) {
this._scheduleHideControls();
}
}
public disconnectedCallback() {
super.disconnectedCallback();
document.removeEventListener("visibilitychange", this._visibilityChanged);
document.removeEventListener("visibilitychange", this._requestWakeLock);
this._releaseWakeLock();
document.removeEventListener("fullscreenchange", this._fullscreenChanged);
document.removeEventListener(
"webkitfullscreenchange",
this._fullscreenChanged
);
document.removeEventListener("keydown", this._inputChanged, true);
document.removeEventListener("pointerdown", this._inputChanged, true);
clearTimeout(this._controlsTimeout);
clearTimeout(this._wheelHintTimeout);
this._streamInfoCallbacks.clear();
this._unbindVideo(this._video);
this._video = undefined;
this._pointers.clear();
@@ -286,10 +252,6 @@ export class HaCameraPlayer extends LitElement {
this._unbindVideo(changedProps.get("_video") as HTMLVideoElement);
this._bindVideo(this._video);
}
if (changedProps.has("_status") || changedProps.has("_capabilities")) {
const info = this._streamInfo();
this._streamInfoCallbacks.forEach((callback) => callback(info));
}
}
protected render() {
@@ -513,11 +475,6 @@ export class HaCameraPlayer extends LitElement {
</div>`;
}
private _visibilityChanged = () => {
this._requestWakeLock();
this._resumeAfterEnteringFullscreen();
};
/**
* Browsers release the lock when the page is hidden, so it is requested
* again whenever the page shows.
@@ -566,10 +523,9 @@ export class HaCameraPlayer extends LitElement {
this._controlsTimeout = window.setTimeout(() => {
this._controlsTimeout = undefined;
if (
(this._lastInput === "mouse" &&
this._overlay?.querySelector(
".control:hover, ha-camera-stream-badge:hover"
)) ||
this._overlay?.querySelector(
".control:hover, ha-camera-stream-badge:hover"
) ||
this._hasKeyboardFocus()
) {
this._scheduleHideControls();
@@ -581,7 +537,6 @@ export class HaCameraPlayer extends LitElement {
private _hasKeyboardFocus(): boolean {
return Boolean(
this._lastInput === "keyboard" &&
this.shadowRoot &&
deepActiveElement(this.shadowRoot)?.matches(":focus-visible")
);
@@ -647,26 +602,10 @@ export class HaCameraPlayer extends LitElement {
this._posterSize = ev.detail.size;
}
private _streamInfo(): CameraStreamInfo {
return {
status: this._status,
supportedTypes: this._capabilities?.frontend_stream_types,
};
}
private _subscribeStreamInfo = (
callback: (info: CameraStreamInfo) => void
) => {
this._streamInfoCallbacks.add(callback);
callback(this._streamInfo());
return () => {
this._streamInfoCallbacks.delete(callback);
};
};
private _showStreamInfo() {
showCameraStreamInfoDialog(this, {
subscribe: this._subscribeStreamInfo,
status: this._status,
supportedTypes: this._capabilities?.frontend_stream_types,
});
}
@@ -755,7 +694,6 @@ export class HaCameraPlayer extends LitElement {
this._paused = Boolean(
video?.paused && (video.srcObject || video.currentSrc)
);
this._resumeAfterEnteringFullscreen();
};
private _toggleMute() {
@@ -807,26 +745,15 @@ export class HaCameraPlayer extends LitElement {
("webkitFullscreenElement" in document
? (document.webkitFullscreenElement as Element | null)
: null);
this._fullscreen = Boolean(
const fullscreen = Boolean(
this._player && fullscreenElement === this._player
);
this._resumeAfterEnteringFullscreen();
};
// The companion apps pause the video while entering full screen
private _resumeAfterEnteringFullscreen() {
if (
isExternal &&
this._playingBeforeFullscreen &&
this._paused &&
document.visibilityState === "visible" &&
isEnteringFullscreen()
) {
// Only once, so a pause in the iPhone's own full screen controls stays
this._playingBeforeFullscreen = false;
this._ensurePlaying();
if (fullscreen !== this._fullscreen) {
this._fullscreen = fullscreen;
// The size changes, so the zoomed in area would be off
this._zoom = ZOOM_PAN_IDENTITY;
}
}
};
private async _toggleFullscreen() {
const player = this._player;
@@ -842,10 +769,6 @@ export class HaCameraPlayer extends LitElement {
}
return;
}
this._playingBeforeFullscreen = Boolean(
this._video && !this._video.paused
);
startEnteringFullscreen();
if (player.requestFullscreen) {
await player.requestFullscreen();
} else if ("webkitRequestFullscreen" in player) {
@@ -859,7 +782,6 @@ export class HaCameraPlayer extends LitElement {
}
} catch (_err: unknown) {
// Denied by the browser
cancelEnteringFullscreen();
}
}
@@ -1008,10 +930,6 @@ export class HaCameraPlayer extends LitElement {
private _pointerMove(ev: PointerEvent) {
if (ev.pointerType === "mouse" && !this._pointers.size) {
// A click changes it, so the control focused with the keyboard stays
if (!this._hasKeyboardFocus()) {
this._lastInput = "mouse";
}
this._showControls();
}
const pointer = this._pointers.get(ev.pointerId);
+99 -277
View File
@@ -9,7 +9,6 @@ import {
import { differenceInMinutes } from "date-fns";
import type {
DataZoomComponentOption,
GridComponentOption,
MarkAreaComponentOption,
} from "echarts/components";
import type { EChartsType } from "echarts/core";
@@ -28,7 +27,6 @@ import {
eventOptions,
property,
query,
queryAll,
state,
} from "lit/decorators";
import { classMap } from "lit/directives/class-map";
@@ -152,9 +150,6 @@ const processSeriesTooltipFormatter = (s: HaECSeriesItem): RawSeriesOption => {
export type CustomLegendOption = ECOption["legend"] & {
type: "custom";
// "y-axis" lists the items beside the chart, each one next to its category,
// in place of the y-axis labels.
position?: "bottom" | "y-axis";
data?: {
id?: string;
secondaryIds?: string[]; // Other dataset IDs that should be controlled by this legend item.
@@ -253,9 +248,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
@query(".chart") private _chartContainer?: HTMLDivElement;
@queryAll(".chart-legend button[data-id]")
private _legendButtons!: NodeListOf<HTMLElement>;
@query(".sonification-output")
private _sonificationOutput?: HTMLDivElement;
@@ -327,25 +319,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
},
});
// The axis legend takes width from the chart without resizing the host
private _chartResizeController = new ResizeController(this, {
target: null,
callback: (entries) => {
const contentRect = entries[entries.length - 1]?.contentRect;
if (
this.chart &&
contentRect &&
(Math.round(contentRect.width) !== this.chart.getWidth() ||
Math.round(contentRect.height) !== this.chart.getHeight())
) {
this._shouldResizeChart = true;
this._resizeChartIfNeeded();
}
},
});
private _focusedLegendButton?: { id: string; toggle: boolean };
private _loading = false;
private _reducedMotion = false;
@@ -468,7 +441,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!this.isConnected) {
return;
}
this._chartResizeController.observe(this._chartContainer!);
// The only measurement taken here: neither observer has reported yet, and a
// chart first rendered inside a hidden container has to defer its setup
// rather than build against a guessed width.
@@ -517,16 +489,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
public willUpdate(changedProps: PropertyValues): void {
const focused = this.shadowRoot?.activeElement as HTMLElement | null;
this._focusedLegendButton =
focused?.dataset.id &&
focused.closest(".chart-legend") &&
focused.matches(":focus-visible")
? {
id: focused.dataset.id,
toggle: focused.classList.contains("legend-toggle"),
}
: undefined;
if (!this.chart) {
return;
}
@@ -634,7 +596,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
this._resizeChartIfNeeded();
}
this._renderedLegendFit = this._legendFit.fit;
this._restoreLegendFocus();
if (changedProps.has("options") || changedProps.has("data")) {
// New values keep the widest widths, but other items are fitted afresh
const legendItemsKey = JSON.stringify(
@@ -649,30 +610,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
}
// The legend reuses its buttons when items move, which would leave focus on
// whichever item now sits where the focused one was
private _restoreLegendFocus() {
const focused = this._focusedLegendButton;
const active = this.shadowRoot?.activeElement as HTMLElement | null;
if (!focused || active?.dataset.id === focused.id) {
return;
}
const className = focused.toggle ? "legend-toggle" : "label";
Array.from(this._legendButtons)
.find(
(button) =>
button.dataset.id === focused.id &&
button.classList.contains(className)
)
?.focus();
}
protected render() {
const sonifiable =
!this._sonificationUnavailable &&
canSonifyChart(this.data, this._hiddenDatasets);
const showZoomSlider = this._showZoomSlider();
const axisLegend = this._hasAxisLegend();
return html`
<div
class="container ${classMap({ "has-height": !!this.height })}"
@@ -684,14 +626,11 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
})}
>
<div
class="chart-container ${classMap({
"has-axis-legend": axisLegend,
})}"
class="chart-container"
style=${styleMap({
height: this.height ? undefined : `${this._getDefaultHeight()}px`,
})}
>
${axisLegend ? this._renderAxisLegend() : nothing}
<div
class="chart ${classMap({
"touch-scrub": this._isTouchDevice && this._hasZoomableXAxis(),
@@ -717,7 +656,7 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
${showZoomSlider ? this._renderZoomSlider() : nothing}
</div>
<div class="sonification-output"></div>
${axisLegend ? nothing : this._renderLegend()}
${this._renderLegend()}
<div class="top-controls ${classMap({ small: this.smallControls })}">
<slot name="search"></slot>
<div
@@ -744,22 +683,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
`;
}
private _getCustomLegend() {
if (!this.options?.legend) {
private _getLegendItems() {
if (!this.options?.legend || !this.data) {
return undefined;
}
return ensureArray(this.options.legend).find(
const legend = ensureArray(this.options.legend).find(
(l) => l.show && l.type === "custom"
) as CustomLegendOption | undefined;
}
private _hasAxisLegend() {
return this._getCustomLegend()?.position === "y-axis";
}
private _getLegendItems() {
const legend = this._getCustomLegend();
if (!legend || !this.data) {
if (!legend) {
return undefined;
}
const datasets = ensureArray(this.data);
@@ -776,6 +707,20 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
if (!items) {
return nothing;
}
const datasets = ensureArray(this.data!);
// Index datasets by id and name so each legend item is an O(1) lookup
// instead of scanning every dataset twice. Charts can have many series.
const datasetById = new Map<unknown, (typeof datasets)[number]>();
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
for (const dataset of datasets) {
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
datasetById.set(dataset.id, dataset);
}
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
datasetByName.set(dataset.name, dataset);
}
}
const fit = this._legendFit.fit ?? items.length;
return html`<div
class=${classMap({
@@ -784,7 +729,73 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
})}
>
<ul ${this._legendFit.target()}>
${this._renderLegendItems(items, fit)}
${items.map((item, index) => {
let itemStyle: Record<string, any> = {};
let value = "";
let noLabelClick = false;
const name = typeof item === "string" ? item : (item.name ?? "");
let id: string;
if (typeof item === "string") {
id = item;
} else {
id = item.id ?? name;
value = item.value ?? "";
itemStyle = item.itemStyle ?? {};
noLabelClick = item.noLabelClick ?? false;
}
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
const dataset = datasetById.get(id) ?? datasetByName.get(id);
itemStyle = {
color: dataset?.color as string,
...(dataset?.itemStyle as { borderColor?: string }),
...itemStyle,
};
const color = itemStyle?.color as string;
return html`<li
.id=${id}
@pointerdown=${this._legendPointerDown}
@pointerup=${this._legendPointerCancel}
@pointerleave=${this._legendPointerCancel}
@pointercancel=${this._legendPointerCancel}
@contextmenu=${this._legendContextMenu}
class=${classMap({
hidden: this._hiddenDatasets.has(id),
overflow: !this.expandLegend && index >= fit,
})}
>
<button
type="button"
class="legend-toggle"
data-id=${id}
aria-pressed=${!this._hiddenDatasets.has(id)}
.title=${this._i18n.localize(
"ui.components.history_charts.toggle_visibility"
)}
@click=${this._toggleDataset}
>
<ha-svg-icon
.path=${
this._hiddenDatasets.has(id)
? mdiCircleOutline
: mdiCheckCircle
}
style=${styleMap({
color: this._hiddenDatasets.has(id) ? undefined : color,
})}
></ha-svg-icon>
</button>
<button
type="button"
class=${classMap({ label: true, clickable: labelClickable })}
data-id=${id}
.title=${name}
@click=${this._labelClick}
>
${name}
</button>
${value ? html`<div class="value">${value}</div>` : nothing}
</li>`;
})}
${
items.length
? html`<li
@@ -818,107 +829,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
</div>`;
}
private _renderAxisLegend() {
const items = this._getLegendItems() ?? [];
const grid = ensureArray(this._getGridOption()!)[0];
return html`<div class="chart-legend axis-legend">
<ul
@pointerover=${this._axisLegendPointerOver}
@pointerleave=${this._axisLegendPointerLeave}
style=${styleMap({
paddingTop: `${grid.top}px`,
paddingBottom: `${grid.bottom}px`,
})}
>
${this._renderLegendItems(items, items.length)}
</ul>
</div>`;
}
private _renderLegendItems(
items: NonNullable<ReturnType<HaChartBase["_getLegendItems"]>>,
fit: number
) {
const datasets = ensureArray(this.data!);
// Index datasets by id and name so each legend item is an O(1) lookup
// instead of scanning every dataset twice. Charts can have many series.
const datasetById = new Map<unknown, (typeof datasets)[number]>();
const datasetByName = new Map<unknown, (typeof datasets)[number]>();
for (const dataset of datasets) {
if (dataset.id !== undefined && !datasetById.has(dataset.id)) {
datasetById.set(dataset.id, dataset);
}
if (dataset.name !== undefined && !datasetByName.has(dataset.name)) {
datasetByName.set(dataset.name, dataset);
}
}
return items.map((item, index) => {
let itemStyle: Record<string, any> = {};
let value = "";
let noLabelClick = false;
const name = typeof item === "string" ? item : (item.name ?? "");
let id: string;
if (typeof item === "string") {
id = item;
} else {
id = item.id ?? name;
value = item.value ?? "";
itemStyle = item.itemStyle ?? {};
noLabelClick = item.noLabelClick ?? false;
}
const labelClickable = this.clickLabelForMoreInfo && !noLabelClick;
const dataset = datasetById.get(id) ?? datasetByName.get(id);
itemStyle = {
color: dataset?.color as string,
...(dataset?.itemStyle as { borderColor?: string }),
...itemStyle,
};
const color = itemStyle?.color as string;
return html`<li
.id=${id}
@pointerdown=${this._legendPointerDown}
@pointerup=${this._legendPointerCancel}
@pointerleave=${this._legendPointerCancel}
@pointercancel=${this._legendPointerCancel}
@contextmenu=${this._legendContextMenu}
class=${classMap({
hidden: this._hiddenDatasets.has(id),
overflow: !this.expandLegend && index >= fit,
})}
>
<button
type="button"
class="legend-toggle"
data-id=${id}
aria-pressed=${!this._hiddenDatasets.has(id)}
.title=${this._i18n.localize(
"ui.components.history_charts.toggle_visibility"
)}
@click=${this._toggleDataset}
>
<ha-svg-icon
.path=${
this._hiddenDatasets.has(id) ? mdiCircleOutline : mdiCheckCircle
}
style=${styleMap({
color: this._hiddenDatasets.has(id) ? undefined : color,
})}
></ha-svg-icon>
</button>
<button
type="button"
class=${classMap({ label: true, clickable: labelClickable })}
data-id=${id}
.title=${name}
@click=${this._labelClick}
>
${name}
</button>
${value ? html`<div class="value">${value}</div>` : nothing}
</li>`;
});
}
// Chart2Music adds ~45 kB gzipped, so it is only fetched once someone actually
// moves keyboard focus into a chart.
private async _handleChartFocus() {
@@ -1059,7 +969,12 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
this.chart!.dispatchAction({ type: "downplay" });
});
this.chart.on("graphroam", this._updateGraphRoamed);
this.chart.on("graphroam", () => {
this._isGraphRoamed = this._getGraphRoams().some(
({ zoom, x, y }) =>
Math.abs(zoom - 1) > 1e-6 || Math.abs(x) > 0.5 || Math.abs(y) > 0.5
);
});
if (!this.options?.dataZoom) {
this.chart.getZr().on("dblclick", this._handleClickZoom);
@@ -1394,28 +1309,14 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
private _getGridOption() {
const grid = this.options?.grid;
const axisLegend = this._hasAxisLegend();
if (!axisLegend && (!grid || !this._zoomSliderRoom)) {
if (!grid || !this._zoomSliderRoom) {
return grid;
}
const [first, ...rest] = ensureArray(grid ?? {});
const result: GridComponentOption = { ...first };
if (axisLegend) {
// The legend rows are laid out from these, so labels must not move them
result.top = this._getGridTop();
result.bottom = this._getGridBottom();
result.containLabel = false;
result.outerBoundsMode = "none";
}
if (this._zoomSliderRoom) {
result.bottom = this._getGridBottom() + this._getZoomSliderSpace();
}
return [result, ...rest];
}
private _getGridTop() {
const top = this.options?.grid && ensureArray(this.options.grid)[0].top;
return typeof top === "number" ? top : 0;
const [first, ...rest] = ensureArray(grid);
return [
{ ...first, bottom: this._getGridBottom() + this._getZoomSliderSpace() },
...rest,
];
}
private _getGridBottom() {
@@ -1488,22 +1389,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
} as XAXisOption;
});
}
let yAxis = this.options?.yAxis;
if (this._hasAxisLegend()) {
const [first, ...rest] = ensureArray(yAxis ?? {});
yAxis = [
{
...first,
type: "category",
inverse: true,
data: this._getLegendItems()?.map((item) =>
typeof item === "string" ? item : (item.id ?? item.name)
),
axisLabel: { ...first.axisLabel, show: false },
} as YAXisOption,
...rest,
];
}
let legend = this.options?.legend;
if (legend) {
legend = ensureArray(legend).map((l) =>
@@ -1533,7 +1418,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
grid: this._getGridOption(),
legend,
xAxis,
yAxis,
};
if (options.tooltip) {
@@ -1997,7 +1881,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
series.option.center = null;
series.option.zoom = 1;
});
fireEvent(this, "chart-zoom-reset");
}
private _getGraphRoams(): {
@@ -2135,24 +2018,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
};
private _axisLegendPointerOver(ev: PointerEvent) {
if (ev.pointerType !== "mouse" || !this.chart) {
return;
}
const id = (ev.target as HTMLElement).closest("li")?.id;
if (!id || this._hiddenDatasets.has(id)) {
this._hideTooltip();
return;
}
this.chart.dispatchAction({ type: "showTip", seriesIndex: 0, name: id });
}
private _axisLegendPointerLeave(ev: PointerEvent) {
if (ev.pointerType === "mouse") {
this._hideTooltip();
}
}
private _hideTooltip() {
this.chart?.dispatchAction({ type: "hideTip" });
this.chart?.dispatchAction({
@@ -2378,18 +2243,9 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
}
private _handleChartRenderFinished = () => {
// Also after a center or zoom in the options, which ends without graphroam
this._updateGraphRoamed();
this._resizeChartIfNeeded();
};
private _updateGraphRoamed = () => {
this._isGraphRoamed = this._getGraphRoams().some(
({ zoom, x, y }) =>
Math.abs(zoom - 1) > 1e-6 || Math.abs(x) > 0.5 || Math.abs(y) > 0.5
);
};
private _resizeChartIfNeeded() {
if (!this.chart || !this._shouldResizeChart) {
return;
@@ -2466,15 +2322,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
.has-height .chart-container {
flex: 1;
}
.chart-container.has-axis-legend {
display: flex;
/* The chart is not mirrored in RTL, so its legend stays on the left */
direction: ltr;
}
.has-axis-legend .chart {
flex: 1;
min-width: 0;
}
.chart {
height: 100%;
width: 100%;
@@ -2575,29 +2422,6 @@ export class HaChartBase extends MobileAwareMixin(LitElement) {
position: absolute;
visibility: hidden;
}
.chart-legend.axis-legend {
flex: none;
max-width: min(200px, 40%);
max-height: none;
padding: 0;
overflow: visible;
direction: var(--direction);
}
.chart-legend.axis-legend ul {
height: 100%;
box-sizing: border-box;
flex-direction: column;
flex-wrap: nowrap;
align-items: stretch;
gap: 0;
}
.chart-legend.axis-legend li,
.chart-legend.axis-legend li:has(.legend-toggle) {
flex: 1 1 0;
height: auto;
min-height: 0;
max-width: none;
}
.chart-legend .hidden {
color: var(--secondary-text-color);
}
@@ -2702,7 +2526,5 @@ declare global {
};
"chart-sankeyroam": { zoom: number };
"chart-setup": undefined;
// The user reset the zoom
"chart-zoom-reset": undefined;
}
}
Loaded 100 of 878 files, more files were not shown because too many files have changed in this diff. Show more