Compare commits

..

1 Commits

Author SHA1 Message Date
Claude
39a7d92ff0 Add loading timeout with retry buttons to init page
- Add 30 second timeout for loading state
- Show retry options when loading takes too long
- Fix bug where retry interval ran in all states (should only run on error)
- Add 'Clear cache and retry' option to help with stuck loading
- Improve UX especially for Android users without pull-to-refresh
2025-11-07 11:37:45 +00:00
146 changed files with 2762 additions and 7423 deletions

View File

@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Send bundle stats and build information to RelativeCI - name: Send bundle stats and build information to RelativeCI
uses: relative-ci/agent-action@feb19ddc698445db27401f1490f6ac182da0816f # v3.2.0 uses: relative-ci/agent-action@8504826a02078b05756e4c07e380023cc2c4274a # v3.1.0
with: with:
key: ${{ secrets[format('RELATIVE_CI_KEY_{0}_{1}', matrix.bundle, matrix.build)] }} key: ${{ secrets[format('RELATIVE_CI_KEY_{0}_{1}', matrix.bundle, matrix.build)] }}
token: ${{ github.token }} token: ${{ github.token }}

View File

@@ -55,7 +55,7 @@ jobs:
script/release script/release
- name: Upload release assets - name: Upload release assets
uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2 uses: softprops/action-gh-release@6da8fa9354ddfdc4aeace5fc48d7f679b5214090 # v2.4.1
with: with:
files: | files: |
dist/*.whl dist/*.whl
@@ -108,7 +108,7 @@ jobs:
- name: Tar folder - name: Tar folder
run: tar -czf landing-page/home_assistant_frontend_landingpage-${{ github.event.release.tag_name }}.tar.gz -C landing-page/dist . run: tar -czf landing-page/home_assistant_frontend_landingpage-${{ github.event.release.tag_name }}.tar.gz -C landing-page/dist .
- name: Upload release asset - name: Upload release asset
uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2 uses: softprops/action-gh-release@6da8fa9354ddfdc4aeace5fc48d7f679b5214090 # v2.4.1
with: with:
files: landing-page/home_assistant_frontend_landingpage-${{ github.event.release.tag_name }}.tar.gz files: landing-page/home_assistant_frontend_landingpage-${{ github.event.release.tag_name }}.tar.gz
@@ -137,6 +137,6 @@ jobs:
- name: Tar folder - name: Tar folder
run: tar -czf hassio/home_assistant_frontend_supervisor-${{ github.event.release.tag_name }}.tar.gz -C hassio/build . run: tar -czf hassio/home_assistant_frontend_supervisor-${{ github.event.release.tag_name }}.tar.gz -C hassio/build .
- name: Upload release asset - name: Upload release asset
uses: softprops/action-gh-release@5be0e66d93ac7ed76da52eca8bb058f665c3a5fe # v2.4.2 uses: softprops/action-gh-release@6da8fa9354ddfdc4aeace5fc48d7f679b5214090 # v2.4.1
with: with:
files: hassio/home_assistant_frontend_supervisor-${{ github.event.release.tag_name }}.tar.gz files: hassio/home_assistant_frontend_supervisor-${{ github.event.release.tag_name }}.tar.gz

View File

@@ -260,6 +260,7 @@ const createRspackConfig = ({
), ),
}, },
experiments: { experiments: {
layers: true,
outputModule: true, outputModule: true,
}, },
}; };

View File

@@ -3,7 +3,7 @@ import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import "../../../../src/components/ha-card"; import "../../../../src/components/ha-card";
import "../../../../src/components/ha-yaml-editor"; import "../../../../src/components/ha-yaml-editor";
import type { LegacyTrigger } from "../../../../src/data/automation"; import type { Trigger } from "../../../../src/data/automation";
import { describeTrigger } from "../../../../src/data/automation_i18n"; import { describeTrigger } from "../../../../src/data/automation_i18n";
import { getEntity } from "../../../../src/fake_data/entity"; import { getEntity } from "../../../../src/fake_data/entity";
import { provideHass } from "../../../../src/fake_data/provide_hass"; import { provideHass } from "../../../../src/fake_data/provide_hass";
@@ -66,7 +66,7 @@ const triggers = [
}, },
]; ];
const initialTrigger: LegacyTrigger = { const initialTrigger: Trigger = {
trigger: "state", trigger: "state",
entity_id: "light.kitchen", entity_id: "light.kitchen",
}; };

View File

@@ -1,55 +0,0 @@
---
title: Dropdown
---
# Dropdown `<ha-dropdown>`
## Implementation
A compact, accessible dropdown menu for choosing actions or settings. `ha-dropdown` supports composed menu items (`<ha-dropdown-item>`) for icons, submenus, checkboxes, disabled entries, and destructive variants. Use composition with `slot="trigger"` to control the trigger button and use `<ha-dropdown-item>` for rich item content.
### Example usage (composition)
```html
<ha-dropdown open>
<ha-button slot="trigger" with-caret>Dropdown</ha-button>
<ha-dropdown-item>
<ha-svg-icon .path="mdiContentCut" slot="icon"></ha-svg-icon>
Cut
</ha-dropdown-item>
<ha-dropdown-item>
<ha-svg-icon .path="mdiContentCopy" slot="icon"></ha-svg-icon>
Copy
</ha-dropdown-item>
<ha-dropdown-item disabled>
<ha-svg-icon .path="mdiContentPaste" slot="icon"></ha-svg-icon>
Paste
</ha-dropdown-item>
<ha-dropdown-item>
Show images
<ha-dropdown-item slot="submenu" value="show-all-images"
>Show all images</ha-dropdown-item
>
<ha-dropdown-item slot="submenu" value="show-thumbnails"
>Show thumbnails</ha-dropdown-item
>
</ha-dropdown-item>
<ha-dropdown-item type="checkbox" checked>Emoji shortcuts</ha-dropdown-item>
<ha-dropdown-item type="checkbox" checked>Word wrap</ha-dropdown-item>
<ha-dropdown-item variant="danger">
<ha-svg-icon .path="mdiDelete" slot="icon"></ha-svg-icon>
Delete
</ha-dropdown-item>
</ha-dropdown>
```
### API
This component is based on the webawesome dropdown component.
Check the [webawesome documentation](https://webawesome.com/docs/components/dropdown/) for more details.

View File

@@ -1,133 +0,0 @@
import "@home-assistant/webawesome/dist/components/button/button";
import "@home-assistant/webawesome/dist/components/dropdown/dropdown";
import "@home-assistant/webawesome/dist/components/icon/icon";
import "@home-assistant/webawesome/dist/components/popup/popup";
import {
mdiContentCopy,
mdiContentCut,
mdiContentPaste,
mdiDelete,
} from "@mdi/js";
import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit";
import { customElement } from "lit/decorators";
import { applyThemesOnElement } from "../../../../src/common/dom/apply_themes_on_element";
import "../../../../src/components/ha-button";
import "../../../../src/components/ha-card";
import "../../../../src/components/ha-dropdown";
import "../../../../src/components/ha-dropdown-item";
import "../../../../src/components/ha-icon-button";
import "../../../../src/components/ha-svg-icon";
@customElement("demo-components-ha-dropdown")
export class DemoHaDropdown extends LitElement {
protected render(): TemplateResult {
return html`
${["light", "dark"].map(
(mode) => html`
<div class=${mode}>
<ha-card header="ha-button in ${mode}">
<div class="card-content">
<ha-dropdown open>
<ha-button slot="trigger" with-caret>Dropdown</ha-button>
<ha-dropdown-item>
<ha-svg-icon
.path=${mdiContentCut}
slot="icon"
></ha-svg-icon>
Cut
</ha-dropdown-item>
<ha-dropdown-item>
<ha-svg-icon
.path=${mdiContentCopy}
slot="icon"
></ha-svg-icon>
Copy
</ha-dropdown-item>
<ha-dropdown-item disabled>
<ha-svg-icon
.path=${mdiContentPaste}
slot="icon"
></ha-svg-icon>
Paste
</ha-dropdown-item>
<ha-dropdown-item>
Show images
<ha-dropdown-item slot="submenu" value="show-all-images"
>Show All Images</ha-dropdown-item
>
<ha-dropdown-item slot="submenu" value="show-thumbnails"
>Show Thumbnails</ha-dropdown-item
>
</ha-dropdown-item>
<ha-dropdown-item type="checkbox" checked
>Emoji Shortcuts</ha-dropdown-item
>
<ha-dropdown-item type="checkbox" checked
>Word Wrap</ha-dropdown-item
>
<ha-dropdown-item variant="danger">
<ha-svg-icon .path=${mdiDelete} slot="icon"></ha-svg-icon>
Delete
</ha-dropdown-item>
</ha-dropdown>
</div>
</ha-card>
</div>
`
)}
`;
}
firstUpdated(changedProps) {
super.firstUpdated(changedProps);
applyThemesOnElement(
this.shadowRoot!.querySelector(".dark"),
{
default_theme: "default",
default_dark_theme: "default",
themes: {},
darkMode: true,
theme: "default",
},
undefined,
undefined,
true
);
}
static styles = css`
:host {
display: flex;
justify-content: center;
}
.dark,
.light {
display: block;
background-color: var(--primary-background-color);
padding: 0 50px;
}
.button {
padding: unset;
}
ha-card {
margin: 24px auto;
}
.card-content {
display: flex;
flex-direction: column;
gap: 24px;
}
.card-content div {
display: flex;
gap: 8px;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"demo-components-ha-dropdown": DemoHaDropdown;
}
}

View File

@@ -52,7 +52,7 @@
"@fullcalendar/list": "6.1.19", "@fullcalendar/list": "6.1.19",
"@fullcalendar/luxon3": "6.1.19", "@fullcalendar/luxon3": "6.1.19",
"@fullcalendar/timegrid": "6.1.19", "@fullcalendar/timegrid": "6.1.19",
"@home-assistant/webawesome": "3.0.0", "@home-assistant/webawesome": "3.0.0-beta.6.ha.7",
"@lezer/highlight": "1.2.3", "@lezer/highlight": "1.2.3",
"@lit-labs/motion": "1.0.9", "@lit-labs/motion": "1.0.9",
"@lit-labs/observers": "2.0.6", "@lit-labs/observers": "2.0.6",
@@ -89,8 +89,8 @@
"@thomasloven/round-slider": "0.6.0", "@thomasloven/round-slider": "0.6.0",
"@tsparticles/engine": "3.9.1", "@tsparticles/engine": "3.9.1",
"@tsparticles/preset-links": "3.2.0", "@tsparticles/preset-links": "3.2.0",
"@vaadin/combo-box": "24.9.5", "@vaadin/combo-box": "24.9.4",
"@vaadin/vaadin-themable-mixin": "24.9.5", "@vaadin/vaadin-themable-mixin": "24.9.4",
"@vibrant/color": "4.0.0", "@vibrant/color": "4.0.0",
"@vue/web-component-wrapper": "1.3.0", "@vue/web-component-wrapper": "1.3.0",
"@webcomponents/scoped-custom-element-registry": "0.0.10", "@webcomponents/scoped-custom-element-registry": "0.0.10",
@@ -122,7 +122,7 @@
"lit": "3.3.1", "lit": "3.3.1",
"lit-html": "3.3.1", "lit-html": "3.3.1",
"luxon": "3.7.2", "luxon": "3.7.2",
"marked": "17.0.0", "marked": "16.4.1",
"memoize-one": "6.0.0", "memoize-one": "6.0.0",
"node-vibrant": "4.0.3", "node-vibrant": "4.0.3",
"object-hash": "3.0.0", "object-hash": "3.0.0",
@@ -157,8 +157,8 @@
"@octokit/auth-oauth-device": "8.0.3", "@octokit/auth-oauth-device": "8.0.3",
"@octokit/plugin-retry": "8.0.3", "@octokit/plugin-retry": "8.0.3",
"@octokit/rest": "22.0.1", "@octokit/rest": "22.0.1",
"@rsdoctor/rspack-plugin": "1.3.8", "@rsdoctor/rspack-plugin": "1.3.7",
"@rspack/core": "1.6.1", "@rspack/core": "1.6.0",
"@rspack/dev-server": "1.1.4", "@rspack/dev-server": "1.1.4",
"@types/babel__plugin-transform-runtime": "7.9.5", "@types/babel__plugin-transform-runtime": "7.9.5",
"@types/chromecast-caf-receiver": "6.0.22", "@types/chromecast-caf-receiver": "6.0.22",
@@ -178,7 +178,7 @@
"@types/tar": "6.1.13", "@types/tar": "6.1.13",
"@types/ua-parser-js": "0.7.39", "@types/ua-parser-js": "0.7.39",
"@types/webspeechapi": "0.0.29", "@types/webspeechapi": "0.0.29",
"@vitest/coverage-v8": "4.0.8", "@vitest/coverage-v8": "4.0.6",
"babel-loader": "10.0.0", "babel-loader": "10.0.0",
"babel-plugin-template-html-minifier": "4.1.0", "babel-plugin-template-html-minifier": "4.1.0",
"browserslist-useragent-regexp": "4.1.3", "browserslist-useragent-regexp": "4.1.3",
@@ -219,7 +219,7 @@
"typescript": "5.9.3", "typescript": "5.9.3",
"typescript-eslint": "8.46.3", "typescript-eslint": "8.46.3",
"vite-tsconfig-paths": "5.1.4", "vite-tsconfig-paths": "5.1.4",
"vitest": "4.0.8", "vitest": "4.0.6",
"webpack-stats-plugin": "1.1.3", "webpack-stats-plugin": "1.1.3",
"webpackbar": "7.0.0", "webpackbar": "7.0.0",
"workbox-build": "patch:workbox-build@npm%3A7.1.1#~/.yarn/patches/workbox-build-npm-7.1.1-a854f3faae.patch" "workbox-build": "patch:workbox-build@npm%3A7.1.1#~/.yarn/patches/workbox-build-npm-7.1.1-a854f3faae.patch"

View File

@@ -1,36 +0,0 @@
import type {
Condition,
TimeCondition,
} from "../../panels/lovelace/common/validate-condition";
/**
* Extract media queries from conditions recursively
*/
export function extractMediaQueries(conditions: Condition[]): string[] {
return conditions.reduce<string[]>((array, c) => {
if ("conditions" in c && c.conditions) {
array.push(...extractMediaQueries(c.conditions));
}
if (c.condition === "screen" && c.media_query) {
array.push(c.media_query);
}
return array;
}, []);
}
/**
* Extract time conditions from conditions recursively
*/
export function extractTimeConditions(
conditions: Condition[]
): TimeCondition[] {
return conditions.reduce<TimeCondition[]>((array, c) => {
if ("conditions" in c && c.conditions) {
array.push(...extractTimeConditions(c.conditions));
}
if (c.condition === "time") {
array.push(c);
}
return array;
}, []);
}

View File

@@ -1,89 +0,0 @@
import { listenMediaQuery } from "../dom/media_query";
import type { HomeAssistant } from "../../types";
import type { Condition } from "../../panels/lovelace/common/validate-condition";
import { checkConditionsMet } from "../../panels/lovelace/common/validate-condition";
import { extractMediaQueries, extractTimeConditions } from "./extract";
import { calculateNextTimeUpdate } from "./time-calculator";
/** Maximum delay for setTimeout (2^31 - 1 milliseconds, ~24.8 days)
* Values exceeding this will overflow and execute immediately
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#maximum_delay_value
*/
const MAX_TIMEOUT_DELAY = 2147483647;
/**
* Helper to setup media query listeners for conditional visibility
*/
export function setupMediaQueryListeners(
conditions: Condition[],
hass: HomeAssistant,
addListener: (unsub: () => void) => void,
onUpdate: (conditionsMet: boolean) => void
): void {
const mediaQueries = extractMediaQueries(conditions);
if (mediaQueries.length === 0) return;
// Optimization for single media query
const hasOnlyMediaQuery =
conditions.length === 1 &&
conditions[0].condition === "screen" &&
!!conditions[0].media_query;
mediaQueries.forEach((mediaQuery) => {
const unsub = listenMediaQuery(mediaQuery, (matches) => {
if (hasOnlyMediaQuery) {
onUpdate(matches);
} else {
const conditionsMet = checkConditionsMet(conditions, hass);
onUpdate(conditionsMet);
}
});
addListener(unsub);
});
}
/**
* Helper to setup time-based listeners for conditional visibility
*/
export function setupTimeListeners(
conditions: Condition[],
hass: HomeAssistant,
addListener: (unsub: () => void) => void,
onUpdate: (conditionsMet: boolean) => void
): void {
const timeConditions = extractTimeConditions(conditions);
if (timeConditions.length === 0) return;
timeConditions.forEach((timeCondition) => {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const scheduleUpdate = () => {
const delay = calculateNextTimeUpdate(hass, timeCondition);
if (delay === undefined) return;
// Cap delay to prevent setTimeout overflow
const cappedDelay = Math.min(delay, MAX_TIMEOUT_DELAY);
timeoutId = setTimeout(() => {
if (delay <= MAX_TIMEOUT_DELAY) {
const conditionsMet = checkConditionsMet(conditions, hass);
onUpdate(conditionsMet);
}
scheduleUpdate();
}, cappedDelay);
};
// Register cleanup function once, outside of scheduleUpdate
addListener(() => {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
});
scheduleUpdate();
});
}

View File

@@ -1,73 +0,0 @@
import { TZDate } from "@date-fns/tz";
import {
startOfDay,
addDays,
addMinutes,
differenceInMilliseconds,
} from "date-fns";
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 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(
hass: HomeAssistant,
{ after, before, weekdays }: Omit<TimeCondition, "condition">
): number | undefined {
const timezone =
hass.locale.time_zone === TimeZone.server
? hass.config.time_zone
: Intl.DateTimeFormat().resolvedOptions().timeZone;
const now = new TZDate(new Date(), timezone);
const updates: Date[] = [];
// Calculate next occurrence of after time
if (after) {
let afterDate = parseTimeString(after, timezone);
if (afterDate <= now) {
// If time has passed today, schedule for tomorrow
afterDate = addDays(afterDate, 1);
}
updates.push(afterDate);
}
// Calculate next occurrence of before time
if (before) {
let beforeDate = parseTimeString(before, timezone);
if (beforeDate <= now) {
// If time has passed today, schedule for tomorrow
beforeDate = addDays(beforeDate, 1);
}
updates.push(beforeDate);
}
// If weekdays are specified, check for midnight (weekday transition)
if (weekdays && weekdays.length > 0 && weekdays.length < 7) {
// Calculate next midnight using startOfDay + addDays
const tomorrow = addDays(now, 1);
const midnight = startOfDay(tomorrow);
updates.push(midnight);
}
if (updates.length === 0) {
return undefined;
}
// Find the soonest update time
const nextUpdate = updates.reduce((soonest, current) =>
current < soonest ? current : soonest
);
// Add 1 minute buffer to ensure we're past the boundary
const updateWithBuffer = addMinutes(nextUpdate, 1);
// Calculate difference in milliseconds
return differenceInMilliseconds(updateWithBuffer, now);
}

View File

@@ -1,131 +0,0 @@
import { TZDate } from "@date-fns/tz";
import { isBefore, isAfter, isWithinInterval } from "date-fns";
import type { HomeAssistant } from "../../types";
import { TimeZone } from "../../data/translation";
import { WEEKDAY_MAP } from "./weekday";
import type { TimeCondition } from "../../panels/lovelace/common/validate-condition";
/**
* Validate a time string format and value ranges without creating Date objects
* @param timeString Time string to validate (HH:MM or HH:MM:SS)
* @returns true if valid, false otherwise
*/
export function isValidTimeString(timeString: string): boolean {
// Reject empty strings
if (!timeString || timeString.trim() === "") {
return false;
}
const parts = timeString.split(":");
if (parts.length < 2 || parts.length > 3) {
return false;
}
// Ensure each part contains only digits (and optional leading zeros)
// This prevents "8:00 AM" from passing validation
if (!parts.every((part) => /^\d+$/.test(part))) {
return false;
}
const hours = parseInt(parts[0], 10);
const minutes = parseInt(parts[1], 10);
const seconds = parts.length === 3 ? parseInt(parts[2], 10) : 0;
if (isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
return false;
}
return (
hours >= 0 &&
hours <= 23 &&
minutes >= 0 &&
minutes <= 59 &&
seconds >= 0 &&
seconds <= 59
);
}
/**
* Parse a time string (HH:MM or HH:MM:SS) and set it on today's date in the given timezone
*
* Note: This function assumes the time string has already been validated by
* isValidTimeString() at configuration time. It does not re-validate at runtime
* for consistency with other condition types (screen, user, location, etc.)
*
* @param timeString The time string to parse (must be pre-validated)
* @param timezone The timezone to use
* @returns The Date object
*/
export const parseTimeString = (timeString: string, timezone: string): Date => {
const parts = timeString.split(":");
const hours = parseInt(parts[0], 10);
const minutes = parseInt(parts[1], 10);
const seconds = parts.length === 3 ? parseInt(parts[2], 10) : 0;
const now = new TZDate(new Date(), timezone);
const dateWithTime = new TZDate(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hours,
minutes,
seconds,
0,
timezone
);
return new Date(dateWithTime.getTime());
};
/**
* Check if the current time matches the time condition (after/before/weekday)
* @param hass Home Assistant object
* @param timeCondition Time condition to check
* @returns true if current time matches the condition
*/
export const checkTimeInRange = (
hass: HomeAssistant,
{ after, before, weekdays }: Omit<TimeCondition, "condition">
): boolean => {
const timezone =
hass.locale.time_zone === TimeZone.server
? hass.config.time_zone
: Intl.DateTimeFormat().resolvedOptions().timeZone;
const now = new TZDate(new Date(), timezone);
// Check weekday condition
if (weekdays && weekdays.length > 0) {
const currentWeekday = WEEKDAY_MAP[now.getDay()];
if (!weekdays.includes(currentWeekday)) {
return false;
}
}
// Check time conditions
if (!after && !before) {
return true;
}
const afterDate = after ? parseTimeString(after, timezone) : undefined;
const beforeDate = before ? parseTimeString(before, timezone) : undefined;
if (afterDate && beforeDate) {
if (isBefore(beforeDate, afterDate)) {
// Crosses midnight (e.g., 22:00 to 06:00)
return !isBefore(now, afterDate) || !isAfter(now, beforeDate);
}
return isWithinInterval(now, { start: afterDate, end: beforeDate });
}
if (afterDate) {
return !isBefore(now, afterDate);
}
if (beforeDate) {
return !isAfter(now, beforeDate);
}
return true;
};

View File

@@ -1,7 +1,18 @@
import { getWeekStartByLocale } from "weekstart"; import { getWeekStartByLocale } from "weekstart";
import type { FrontendLocaleData } from "../../data/translation"; import type { FrontendLocaleData } from "../../data/translation";
import { FirstWeekday } from "../../data/translation"; import { FirstWeekday } from "../../data/translation";
import { WEEKDAYS_LONG, type WeekdayIndex } from "./weekday";
export const weekdays = [
"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
] as const;
type WeekdayIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export const firstWeekdayIndex = (locale: FrontendLocaleData): WeekdayIndex => { export const firstWeekdayIndex = (locale: FrontendLocaleData): WeekdayIndex => {
if (locale.first_weekday === FirstWeekday.language) { if (locale.first_weekday === FirstWeekday.language) {
@@ -12,12 +23,12 @@ export const firstWeekdayIndex = (locale: FrontendLocaleData): WeekdayIndex => {
} }
return (getWeekStartByLocale(locale.language) % 7) as WeekdayIndex; return (getWeekStartByLocale(locale.language) % 7) as WeekdayIndex;
} }
return WEEKDAYS_LONG.includes(locale.first_weekday) return weekdays.includes(locale.first_weekday)
? (WEEKDAYS_LONG.indexOf(locale.first_weekday) as WeekdayIndex) ? (weekdays.indexOf(locale.first_weekday) as WeekdayIndex)
: 1; : 1;
}; };
export const firstWeekday = (locale: FrontendLocaleData) => { export const firstWeekday = (locale: FrontendLocaleData) => {
const index = firstWeekdayIndex(locale); const index = firstWeekdayIndex(locale);
return WEEKDAYS_LONG[index]; return weekdays[index];
}; };

View File

@@ -1,59 +0,0 @@
export type WeekdayIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;
export type WeekdayShort =
| "sun"
| "mon"
| "tue"
| "wed"
| "thu"
| "fri"
| "sat";
export type WeekdayLong =
| "sunday"
| "monday"
| "tuesday"
| "wednesday"
| "thursday"
| "friday"
| "saturday";
export const WEEKDAYS_SHORT = [
"sun",
"mon",
"tue",
"wed",
"thu",
"fri",
"sat",
] as const satisfies readonly WeekdayShort[];
export const WEEKDAYS_LONG = [
"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
] as const satisfies readonly WeekdayLong[];
export const WEEKDAY_MAP = {
0: "sun",
1: "mon",
2: "tue",
3: "wed",
4: "thu",
5: "fri",
6: "sat",
} as const satisfies Record<WeekdayIndex, WeekdayShort>;
export const WEEKDAY_SHORT_TO_LONG = {
sun: "sunday",
mon: "monday",
tue: "tuesday",
wed: "wednesday",
thu: "thursday",
fri: "friday",
sat: "saturday",
} as const satisfies Record<WeekdayShort, WeekdayLong>;

View File

@@ -1,6 +1,5 @@
import type { ThemeVars } from "../../data/ws-themes"; import type { ThemeVars } from "../../data/ws-themes";
import { darkColorVariables } from "../../resources/theme/color"; import { darkColorVariables } from "../../resources/theme/color";
import { darkSemanticVariables } from "../../resources/theme/semantic.globals";
import { derivedStyles } from "../../resources/theme/theme"; import { derivedStyles } from "../../resources/theme/theme";
import type { HomeAssistant } from "../../types"; import type { HomeAssistant } from "../../types";
import { import {
@@ -53,7 +52,7 @@ export const applyThemesOnElement = (
if (themeToApply && darkMode) { if (themeToApply && darkMode) {
cacheKey = `${cacheKey}__dark`; cacheKey = `${cacheKey}__dark`;
themeRules = { ...darkSemanticVariables, ...darkColorVariables }; themeRules = { ...darkColorVariables };
} }
if (themeToApply === "default") { if (themeToApply === "default") {

View File

@@ -1,36 +0,0 @@
/**
* Parses a CSS duration string (e.g., "300ms", "3s") and returns the duration in milliseconds.
*
* @param duration - A CSS duration string (e.g., "300ms", "3s", "0.5s")
* @returns The duration in milliseconds, or 0 if the input is invalid
*
* @example
* parseAnimationDuration("300ms") // Returns 300
* parseAnimationDuration("3s") // Returns 3000
* parseAnimationDuration("0.5s") // Returns 500
* parseAnimationDuration("invalid") // Returns 0
*/
export const parseAnimationDuration = (duration: string): number => {
const trimmed = duration.trim();
let value: number;
let multiplier: number;
if (trimmed.endsWith("ms")) {
value = parseFloat(trimmed.slice(0, -2));
multiplier = 1;
} else if (trimmed.endsWith("s")) {
value = parseFloat(trimmed.slice(0, -1));
multiplier = 1000;
} else {
// No recognized unit, try parsing as number (assume ms)
value = parseFloat(trimmed);
multiplier = 1;
}
if (!isFinite(value) || value < 0) {
return 0;
}
return value * multiplier;
};

View File

@@ -119,8 +119,8 @@ type Thresholds = Record<
>; >;
export const DEFAULT_THRESHOLDS: Thresholds = { export const DEFAULT_THRESHOLDS: Thresholds = {
second: 59, // seconds to minute second: 45, // seconds to minute
minute: 59, // minutes to hour minute: 45, // minutes to hour
hour: 22, // hour to day hour: 22, // hour to day
day: 5, // day to week day: 5, // day to week
week: 4, // week to months week: 4, // week to months

View File

@@ -1,30 +0,0 @@
/**
* Executes a callback within a View Transition if supported, otherwise runs it directly.
*
* @param callback - Function to execute. Can be synchronous or return a Promise. The callback will be passed a boolean indicating whether the view transition is available.
* @returns Promise that resolves when the transition completes (or immediately if not supported)
*
* @example
* ```typescript
* // Synchronous callback
* withViewTransition(() => {
* this.large = !this.large;
* });
*
* // Async callback
* await withViewTransition(async () => {
* await this.updateData();
* });
* ```
*/
export const withViewTransition = (
callback: (viewTransitionAvailable: boolean) => void | Promise<void>
): Promise<void> => {
if (document.startViewTransition) {
return document.startViewTransition(() => callback(true)).finished;
}
// Fallback: Execute callback directly without transition
const result = callback(false);
return result instanceof Promise ? result : Promise.resolve();
};

View File

@@ -6,8 +6,7 @@ export function downSampleLineData<
data: T[] | undefined, data: T[] | undefined,
maxDetails: number, maxDetails: number,
minX?: number, minX?: number,
maxX?: number, maxX?: number
useMean = false
): T[] { ): T[] {
if (!data) { if (!data) {
return []; return [];
@@ -18,13 +17,15 @@ export function downSampleLineData<
const min = minX ?? getPointData(data[0]!)[0]; const min = minX ?? getPointData(data[0]!)[0];
const max = maxX ?? getPointData(data[data.length - 1]!)[0]; const max = maxX ?? getPointData(data[data.length - 1]!)[0];
const step = Math.ceil((max - min) / Math.floor(maxDetails)); const step = Math.ceil((max - min) / Math.floor(maxDetails));
// Group points into frames
const frames = new Map< const frames = new Map<
number, number,
{ point: (typeof data)[number]; x: number; y: number }[] {
min: { point: (typeof data)[number]; x: number; y: number };
max: { point: (typeof data)[number]; x: number; y: number };
}
>(); >();
// Group points into frames
for (const point of data) { for (const point of data) {
const pointData = getPointData(point); const pointData = getPointData(point);
if (!Array.isArray(pointData)) continue; if (!Array.isArray(pointData)) continue;
@@ -35,53 +36,28 @@ export function downSampleLineData<
const frameIndex = Math.floor((x - min) / step); const frameIndex = Math.floor((x - min) / step);
const frame = frames.get(frameIndex); const frame = frames.get(frameIndex);
if (!frame) { if (!frame) {
frames.set(frameIndex, [{ point, x, y }]); frames.set(frameIndex, { min: { point, x, y }, max: { point, x, y } });
} else { } else {
frame.push({ point, x, y }); if (frame.min.y > y) {
frame.min = { point, x, y };
}
if (frame.max.y < y) {
frame.max = { point, x, y };
}
} }
} }
// Convert frames back to points // Convert frames back to points
const result: T[] = []; const result: T[] = [];
for (const [_i, frame] of frames) {
if (useMean) { // Use min/max points to preserve visual accuracy
// Use mean values for each frame // The order of the data must be preserved so max may be before min
for (const [_i, framePoints] of frames) { if (frame.min.x > frame.max.x) {
const sumY = framePoints.reduce((acc, p) => acc + p.y, 0); result.push(frame.max.point);
const meanY = sumY / framePoints.length;
const sumX = framePoints.reduce((acc, p) => acc + p.x, 0);
const meanX = sumX / framePoints.length;
const firstPoint = framePoints[0].point;
const pointData = getPointData(firstPoint);
const meanPoint = (
Array.isArray(pointData) ? [meanX, meanY] : { value: [meanX, meanY] }
) as T;
result.push(meanPoint);
} }
} else { result.push(frame.min.point);
// Use min/max values for each frame if (frame.min.x < frame.max.x) {
for (const [_i, framePoints] of frames) { result.push(frame.max.point);
let minPoint = framePoints[0];
let maxPoint = framePoints[0];
for (const p of framePoints) {
if (p.y < minPoint.y) {
minPoint = p;
}
if (p.y > maxPoint.y) {
maxPoint = p;
}
}
// The order of the data must be preserved so max may be before min
if (minPoint.x > maxPoint.x) {
result.push(maxPoint.point);
}
result.push(minPoint.point);
if (minPoint.x < maxPoint.x) {
result.push(maxPoint.point);
}
} }
} }

View File

@@ -427,7 +427,6 @@ export class HaChartBase extends LitElement {
...axis.axisPointer?.handle, ...axis.axisPointer?.handle,
show: true, show: true,
}, },
label: { show: false },
}, },
} }
: axis : axis
@@ -628,10 +627,6 @@ export class HaChartBase extends LitElement {
} }
private _createTheme(style: CSSStyleDeclaration) { private _createTheme(style: CSSStyleDeclaration) {
const textBorderColor =
style.getPropertyValue("--ha-card-background") ||
style.getPropertyValue("--card-background-color");
const textBorderWidth = 2;
return { return {
color: getAllGraphColors(style), color: getAllGraphColors(style),
backgroundColor: "transparent", backgroundColor: "transparent",
@@ -655,22 +650,22 @@ export class HaChartBase extends LitElement {
graph: { graph: {
label: { label: {
color: style.getPropertyValue("--primary-text-color"), color: style.getPropertyValue("--primary-text-color"),
textBorderColor, textBorderColor: style.getPropertyValue("--primary-background-color"),
textBorderWidth, textBorderWidth: 2,
}, },
}, },
pie: { pie: {
label: { label: {
color: style.getPropertyValue("--primary-text-color"), color: style.getPropertyValue("--primary-text-color"),
textBorderColor, textBorderColor: style.getPropertyValue("--primary-background-color"),
textBorderWidth, textBorderWidth: 2,
}, },
}, },
sankey: { sankey: {
label: { label: {
color: style.getPropertyValue("--primary-text-color"), color: style.getPropertyValue("--primary-text-color"),
textBorderColor, textBorderColor: style.getPropertyValue("--primary-background-color"),
textBorderWidth, textBorderWidth: 2,
}, },
}, },
categoryAxis: { categoryAxis: {

View File

@@ -2,10 +2,7 @@ import type { EChartsType } from "echarts/core";
import type { GraphSeriesOption } from "echarts/charts"; import type { GraphSeriesOption } from "echarts/charts";
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state, query } from "lit/decorators"; import { customElement, property, state, query } from "lit/decorators";
import type { import type { TopLevelFormatterParams } from "echarts/types/dist/shared";
CallbackDataParams,
TopLevelFormatterParams,
} from "echarts/types/dist/shared";
import { mdiFormatTextVariant, mdiGoogleCirclesGroup } from "@mdi/js"; import { mdiFormatTextVariant, mdiGoogleCirclesGroup } from "@mdi/js";
import memoizeOne from "memoize-one"; import memoizeOne from "memoize-one";
import { listenMediaQuery } from "../../common/dom/media_query"; import { listenMediaQuery } from "../../common/dom/media_query";
@@ -19,7 +16,6 @@ import { deepEqual } from "../../common/util/deep-equal";
export interface NetworkNode { export interface NetworkNode {
id: string; id: string;
name?: string; name?: string;
context?: string;
category?: number; category?: number;
value?: number; value?: number;
symbolSize?: number; symbolSize?: number;
@@ -192,25 +188,6 @@ export class HaNetworkGraph extends SubscribeMixin(LitElement) {
label: { label: {
show: showLabels, show: showLabels,
position: "right", position: "right",
formatter: (params: CallbackDataParams) => {
const node = params.data as NetworkNode;
if (node.context) {
return `{primary|${node.name ?? ""}}\n{secondary|${node.context}}`;
}
return node.name ?? "";
},
rich: {
primary: {
fontSize: 12,
},
secondary: {
fontSize: 12,
color: getComputedStyle(document.body).getPropertyValue(
"--secondary-text-color"
),
lineHeight: 16,
},
},
}, },
emphasis: { emphasis: {
focus: isMobile ? "none" : "adjacency", focus: isMobile ? "none" : "adjacency",
@@ -248,7 +225,6 @@ export class HaNetworkGraph extends SubscribeMixin(LitElement) {
({ ({
id: node.id, id: node.id,
name: node.name, name: node.name,
context: node.context,
category: node.category, category: node.category,
value: node.value, value: node.value,
symbolSize: node.symbolSize || 30, symbolSize: node.symbolSize || 30,

View File

@@ -62,7 +62,6 @@ class HaDataTableLabels extends LitElement {
@click=${clickAction ? this._labelClicked : undefined} @click=${clickAction ? this._labelClicked : undefined}
@keydown=${clickAction ? this._labelClicked : undefined} @keydown=${clickAction ? this._labelClicked : undefined}
style=${color ? `--color: ${color}` : ""} style=${color ? `--color: ${color}` : ""}
.description=${label.description}
> >
${label?.icon ${label?.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`

View File

@@ -197,6 +197,9 @@ export class HaDevicePicker extends LitElement {
const placeholder = const placeholder =
this.placeholder ?? this.placeholder ??
this.hass.localize("ui.components.device-picker.placeholder"); this.hass.localize("ui.components.device-picker.placeholder");
const notFoundLabel = this.hass.localize(
"ui.components.device-picker.no_match"
);
const valueRenderer = this._valueRenderer(this._configEntryLookup); const valueRenderer = this._valueRenderer(this._configEntryLookup);
@@ -206,10 +209,7 @@ export class HaDevicePicker extends LitElement {
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.searchLabel=${this.searchLabel} .searchLabel=${this.searchLabel}
.notFoundLabel=${this._notFoundLabel} .notFoundLabel=${notFoundLabel}
.emptyLabel=${this.hass.localize(
"ui.components.device-picker.no_devices"
)}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
.rowRenderer=${this._rowRenderer} .rowRenderer=${this._rowRenderer}
@@ -233,11 +233,6 @@ export class HaDevicePicker extends LitElement {
this.value = value; this.value = value;
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.device-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -269,6 +269,9 @@ export class HaEntityPicker extends LitElement {
const placeholder = const placeholder =
this.placeholder ?? this.placeholder ??
this.hass.localize("ui.components.entity.entity-picker.placeholder"); this.hass.localize("ui.components.entity.entity-picker.placeholder");
const notFoundLabel = this.hass.localize(
"ui.components.entity.entity-picker.no_match"
);
return html` return html`
<ha-generic-picker <ha-generic-picker
@@ -279,7 +282,7 @@ export class HaEntityPicker extends LitElement {
.label=${this.label} .label=${this.label}
.helper=${this.helper} .helper=${this.helper}
.searchLabel=${this.searchLabel} .searchLabel=${this.searchLabel}
.notFoundLabel=${this._notFoundLabel} .notFoundLabel=${notFoundLabel}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.addButton ? undefined : this.value} .value=${this.addButton ? undefined : this.value}
.rowRenderer=${this._rowRenderer} .rowRenderer=${this._rowRenderer}
@@ -353,11 +356,6 @@ export class HaEntityPicker extends LitElement {
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
fireEvent(this, "change"); fireEvent(this, "change");
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.entity.entity-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -21,6 +21,7 @@ import "../ha-combo-box-item";
import "../ha-generic-picker"; import "../ha-generic-picker";
import type { HaGenericPicker } from "../ha-generic-picker"; import type { HaGenericPicker } from "../ha-generic-picker";
import "../ha-icon-button"; import "../ha-icon-button";
import "../ha-input-helper-text";
import type { import type {
PickerComboBoxItem, PickerComboBoxItem,
PickerComboBoxSearchFn, PickerComboBoxSearchFn,
@@ -270,6 +271,7 @@ export class HaStatisticPicker extends LitElement {
const secondary = [areaName, entityName ? deviceName : undefined] const secondary = [areaName, entityName ? deviceName : undefined]
.filter(Boolean) .filter(Boolean)
.join(isRTL ? " ◂ " : " ▸ "); .join(isRTL ? " ◂ " : " ▸ ");
const a11yLabel = [deviceName, entityName].filter(Boolean).join(" - ");
const sortingPrefix = `${TYPE_ORDER.indexOf("entity")}`; const sortingPrefix = `${TYPE_ORDER.indexOf("entity")}`;
output.push({ output.push({
@@ -277,6 +279,7 @@ export class HaStatisticPicker extends LitElement {
statistic_id: id, statistic_id: id,
primary, primary,
secondary, secondary,
a11y_label: a11yLabel,
stateObj: stateObj, stateObj: stateObj,
type: "entity", type: "entity",
sorting_label: [sortingPrefix, deviceName, entityName].join("_"), sorting_label: [sortingPrefix, deviceName, entityName].join("_"),
@@ -455,6 +458,9 @@ export class HaStatisticPicker extends LitElement {
const placeholder = const placeholder =
this.placeholder ?? this.placeholder ??
this.hass.localize("ui.components.statistic-picker.placeholder"); this.hass.localize("ui.components.statistic-picker.placeholder");
const notFoundLabel = this.hass.localize(
"ui.components.statistic-picker.no_match"
);
return html` return html`
<ha-generic-picker <ha-generic-picker
@@ -462,10 +468,7 @@ export class HaStatisticPicker extends LitElement {
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.allowCustomValue=${this.allowCustomEntity} .allowCustomValue=${this.allowCustomEntity}
.label=${this.label} .label=${this.label}
.notFoundLabel=${this._notFoundLabel} .notFoundLabel=${notFoundLabel}
.emptyLabel=${this.hass.localize(
"ui.components.statistic-picker.no_statistics"
)}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
.rowRenderer=${this._rowRenderer} .rowRenderer=${this._rowRenderer}
@@ -474,7 +477,6 @@ export class HaStatisticPicker extends LitElement {
.hideClearIcon=${this.hideClearIcon} .hideClearIcon=${this.hideClearIcon}
.searchFn=${this._searchFn} .searchFn=${this._searchFn}
.valueRenderer=${this._valueRenderer} .valueRenderer=${this._valueRenderer}
.helper=${this.helper}
@value-changed=${this._valueChanged} @value-changed=${this._valueChanged}
> >
</ha-generic-picker> </ha-generic-picker>
@@ -519,11 +521,6 @@ export class HaStatisticPicker extends LitElement {
await this.updateComplete; await this.updateComplete;
await this._picker?.open(); await this._picker?.open();
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.statistic-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -369,10 +369,9 @@ export class HaAreaPicker extends LitElement {
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.helper=${this.helper} .helper=${this.helper}
.notFoundLabel=${this._notFoundLabel} .notFoundLabel=${this.hass.localize(
.emptyLabel=${this.hass.localize("ui.components.area-picker.no_areas")} "ui.components.area-picker.no_match"
.disabled=${this.disabled} )}
.required=${this.required}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
.getItems=${this._getItems} .getItems=${this._getItems}
@@ -426,11 +425,6 @@ export class HaAreaPicker extends LitElement {
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
fireEvent(this, "change"); fireEvent(this, "change");
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.area-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -1,41 +0,0 @@
import DropdownItem from "@home-assistant/webawesome/dist/components/dropdown-item/dropdown-item";
import { css, type CSSResultGroup } from "lit";
import { customElement } from "lit/decorators";
/**
* Home Assistant dropdown item component
*
* @element ha-dropdown-item
* @extends {DropdownItem}
*
* @summary
* A stylable dropdown item component supporting Home Assistant theming, variants, and appearances based on webawesome dropdown item.
*
*/
@customElement("ha-dropdown-item")
export class HaDropdownItem extends DropdownItem {
static get styles(): CSSResultGroup {
return [
DropdownItem.styles,
css`
:host {
min-height: var(--ha-space-10);
}
#icon ::slotted(*) {
color: var(--ha-color-on-neutral-normal);
}
:host([variant="danger"]) #icon ::slotted(*) {
color: var(--ha-color-on-danger-quiet);
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-dropdown-item": HaDropdownItem;
}
}

View File

@@ -1,45 +0,0 @@
import Dropdown from "@home-assistant/webawesome/dist/components/dropdown/dropdown";
import { css, type CSSResultGroup } from "lit";
import { customElement, property } from "lit/decorators";
/**
* Home Assistant dropdown component
*
* @element ha-dropdown
* @extends {Dropdown}
*
* @summary
* A stylable dropdown component supporting Home Assistant theming, variants, and appearances based on webawesome dropdown.
*
*/
@customElement("ha-dropdown")
export class HaDropdown extends Dropdown {
@property({ attribute: false }) dropdownTag = "ha-dropdown";
@property({ attribute: false }) dropdownItemTag = "ha-dropdown-item";
static get styles(): CSSResultGroup {
return [
Dropdown.styles,
css`
:host {
font-size: var(--ha-dropdown-font-size, var(--ha-font-size-m));
--wa-color-surface-raised: var(
--card-background-color,
var(--ha-dialog-surface-background, var(--mdc-theme-surface, #fff)),
);
}
#menu {
padding: var(--ha-space-1);
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-dropdown": HaDropdown;
}
}

View File

@@ -109,10 +109,7 @@ export class HaFilterLabels extends SubscribeMixin(LitElement) {
.selected=${(this.value || []).includes(label.label_id)} .selected=${(this.value || []).includes(label.label_id)}
hasMeta hasMeta
> >
<ha-label <ha-label style=${color ? `--color: ${color}` : ""}>
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon ? html`<ha-icon
slot="icon" slot="icon"

View File

@@ -383,9 +383,8 @@ export class HaFloorPicker extends LitElement {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.notFoundLabel=${this._notFoundLabel} .notFoundLabel=${this.hass.localize(
.emptyLabel=${this.hass.localize( "ui.components.floor-picker.no_match"
"ui.components.floor-picker.no_floors"
)} )}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
@@ -445,11 +444,6 @@ export class HaFloorPicker extends LitElement {
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
fireEvent(this, "change"); fireEvent(this, "change");
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.floor-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -25,6 +25,9 @@ import "./ha-svg-icon";
export class HaGenericPicker extends LitElement { export class HaGenericPicker extends LitElement {
@property({ attribute: false }) public hass?: HomeAssistant; @property({ attribute: false }) public hass?: HomeAssistant;
// eslint-disable-next-line lit/no-native-attributes
@property({ type: Boolean }) public autofocus = false;
@property({ type: Boolean }) public disabled = false; @property({ type: Boolean }) public disabled = false;
@property({ type: Boolean }) public required = false; @property({ type: Boolean }) public required = false;
@@ -46,11 +49,8 @@ export class HaGenericPicker extends LitElement {
@property({ attribute: "hide-clear-icon", type: Boolean }) @property({ attribute: "hide-clear-icon", type: Boolean })
public hideClearIcon = false; public hideClearIcon = false;
@property({ attribute: false }) @property({ attribute: false, type: Array })
public getItems?: ( public getItems?: () => PickerComboBoxItem[];
searchString?: string,
section?: string
) => (PickerComboBoxItem | string)[];
@property({ attribute: false, type: Array }) @property({ attribute: false, type: Array })
public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[]; public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[];
@@ -64,11 +64,8 @@ export class HaGenericPicker extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
public searchFn?: PickerComboBoxSearchFn<PickerComboBoxItem>; public searchFn?: PickerComboBoxSearchFn<PickerComboBoxItem>;
@property({ attribute: false }) @property({ attribute: "not-found-label", type: String })
public notFoundLabel?: string | ((search: string) => string); public notFoundLabel?: string;
@property({ attribute: "empty-label" })
public emptyLabel?: string;
@property({ attribute: "popover-placement" }) @property({ attribute: "popover-placement" })
public popoverPlacement: public popoverPlacement:
@@ -88,25 +85,6 @@ export class HaGenericPicker extends LitElement {
/** If set picker shows an add button instead of textbox when value isn't set */ /** If set picker shows an add button instead of textbox when value isn't set */
@property({ attribute: "add-button-label" }) public addButtonLabel?: string; @property({ attribute: "add-button-label" }) public addButtonLabel?: string;
/** Section filter buttons for the list, section headers needs to be defined in getItems as strings */
@property({ attribute: false }) public sections?: (
| {
id: string;
label: string;
}
| "separator"
)[];
@property({ attribute: false }) public sectionTitleFunction?: (listInfo: {
firstIndex: number;
lastIndex: number;
firstItem: PickerComboBoxItem | string;
secondItem: PickerComboBoxItem | string;
itemsCount: number;
}) => string | undefined;
@property({ attribute: "selected-section" }) public selectedSection?: string;
@query(".container") private _containerElement?: HTMLDivElement; @query(".container") private _containerElement?: HTMLDivElement;
@query("ha-picker-combo-box") private _comboBox?: HaPickerComboBox; @query("ha-picker-combo-box") private _comboBox?: HaPickerComboBox;
@@ -119,11 +97,6 @@ export class HaGenericPicker extends LitElement {
@state() private _openedNarrow = false; @state() private _openedNarrow = false;
static shadowRootOptions = {
...LitElement.shadowRootOptions,
delegatesFocus: true,
};
private _narrow = false; private _narrow = false;
// helper to set new value after closing picker, to avoid flicker // helper to set new value after closing picker, to avoid flicker
@@ -216,19 +189,16 @@ export class HaGenericPicker extends LitElement {
<ha-picker-combo-box <ha-picker-combo-box
.hass=${this.hass} .hass=${this.hass}
.allowCustomValue=${this.allowCustomValue} .allowCustomValue=${this.allowCustomValue}
.label=${this.searchLabel} .label=${this.searchLabel ??
(this.hass?.localize("ui.common.search") || "Search")}
.value=${this.value} .value=${this.value}
@value-changed=${this._valueChanged} @value-changed=${this._valueChanged}
.rowRenderer=${this.rowRenderer} .rowRenderer=${this.rowRenderer}
.notFoundLabel=${this.notFoundLabel} .notFoundLabel=${this.notFoundLabel}
.emptyLabel=${this.emptyLabel}
.getItems=${this.getItems} .getItems=${this.getItems}
.getAdditionalItems=${this.getAdditionalItems} .getAdditionalItems=${this.getAdditionalItems}
.searchFn=${this.searchFn} .searchFn=${this.searchFn}
.mode=${dialogMode ? "dialog" : "popover"} .mode=${dialogMode ? "dialog" : "popover"}
.sections=${this.sections}
.sectionTitleFunction=${this.sectionTitleFunction}
.selectedSection=${this.selectedSection}
></ha-picker-combo-box> ></ha-picker-combo-box>
`; `;
} }

View File

@@ -224,9 +224,8 @@ export class HaLabelPicker extends SubscribeMixin(LitElement) {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.notFoundLabel=${this._notFoundLabel} .notFoundLabel=${this.hass.localize(
.emptyLabel=${this.hass.localize( "ui.components.label-picker.no_match"
"ui.components.label-picker.no_labels"
)} )}
.addButtonLabel=${this.hass.localize("ui.components.label-picker.add")} .addButtonLabel=${this.hass.localize("ui.components.label-picker.add")}
.placeholder=${placeholder} .placeholder=${placeholder}
@@ -289,11 +288,6 @@ export class HaLabelPicker extends SubscribeMixin(LitElement) {
fireEvent(this, "change"); fireEvent(this, "change");
}, 0); }, 0);
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.label-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -1,32 +1,17 @@
import type { CSSResultGroup, TemplateResult } from "lit"; import type { CSSResultGroup, TemplateResult } from "lit";
import { css, html, LitElement } from "lit"; import { css, html, LitElement } from "lit";
import { customElement, property } from "lit/decorators"; import { customElement, property } from "lit/decorators";
import { uid } from "../common/util/uid";
import "./ha-tooltip";
@customElement("ha-label") @customElement("ha-label")
class HaLabel extends LitElement { class HaLabel extends LitElement {
@property({ type: Boolean, reflect: true }) dense = false; @property({ type: Boolean, reflect: true }) dense = false;
@property({ attribute: "description" })
public description?: string;
private _elementId = "label-" + uid();
protected render(): TemplateResult { protected render(): TemplateResult {
return html` return html`
<ha-tooltip <span class="content">
.for=${this._elementId} <slot name="icon"></slot>
.disabled=${!this.description?.trim()} <slot></slot>
> </span>
${this.description}
</ha-tooltip>
<div class="container" .id=${this._elementId}>
<span class="content">
<slot name="icon"></slot>
<slot></slot>
</span>
</div>
`; `;
} }
@@ -51,7 +36,9 @@ class HaLabel extends LitElement {
font-weight: var(--ha-font-weight-medium); font-weight: var(--ha-font-weight-medium);
line-height: var(--ha-line-height-condensed); line-height: var(--ha-line-height-condensed);
letter-spacing: 0.1px; letter-spacing: 0.1px;
vertical-align: middle;
height: 32px; height: 32px;
padding: 0 16px;
border-radius: var(--ha-border-radius-xl); border-radius: var(--ha-border-radius-xl);
color: var(--ha-label-text-color); color: var(--ha-label-text-color);
--mdc-icon-size: 12px; --mdc-icon-size: 12px;
@@ -79,23 +66,14 @@ class HaLabel extends LitElement {
display: flex; display: flex;
} }
.container {
display: flex;
position: relative;
height: 100%;
padding: 0 16px;
}
span { span {
display: inline-flex; display: inline-flex;
} }
:host([dense]) { :host([dense]) {
height: 20px; height: 20px;
border-radius: var(--ha-border-radius-md);
}
:host([dense]) .container {
padding: 0 12px; padding: 0 12px;
border-radius: var(--ha-border-radius-md);
} }
:host([dense]) ::slotted([slot="icon"]) { :host([dense]) ::slotted([slot="icon"]) {
margin-right: 4px; margin-right: 4px;

View File

@@ -21,7 +21,6 @@ import "./chips/ha-input-chip";
import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker"; import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker";
import "./ha-label-picker"; import "./ha-label-picker";
import type { HaLabelPicker } from "./ha-label-picker"; import type { HaLabelPicker } from "./ha-label-picker";
import "./ha-tooltip";
@customElement("ha-labels-picker") @customElement("ha-labels-picker")
export class HaLabelsPicker extends SubscribeMixin(LitElement) { export class HaLabelsPicker extends SubscribeMixin(LitElement) {
@@ -143,17 +142,9 @@ export class HaLabelsPicker extends SubscribeMixin(LitElement) {
const color = label?.color const color = label?.color
? computeCssColor(label.color) ? computeCssColor(label.color)
: undefined; : undefined;
const elementId = "label-" + label.label_id;
return html` return html`
<ha-tooltip
.for=${elementId}
.disabled=${!label?.description?.trim()}
>
${label?.description}
</ha-tooltip>
<ha-input-chip <ha-input-chip
.item=${label} .item=${label}
.id=${elementId}
@remove=${this._removeItem} @remove=${this._removeItem}
@click=${this._openDetail} @click=${this._openDetail}
.disabled=${this.disabled} .disabled=${this.disabled}

View File

@@ -125,10 +125,9 @@ export class HaLanguagePicker extends LitElement {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
popover-placement="bottom-end" popover-placement="bottom-end"
.notFoundLabel=${this._notFoundLabel} .notFoundLabel=${this.hass?.localize(
.emptyLabel=${this.hass?.localize( "ui.components.language-picker.no_match"
"ui.components.language-picker.no_languages" )}
) || "No languages available"}
.placeholder=${this.label ?? .placeholder=${this.label ??
(this.hass?.localize("ui.components.language-picker.language") || (this.hass?.localize("ui.components.language-picker.language") ||
"Language")} "Language")}
@@ -173,15 +172,6 @@ export class HaLanguagePicker extends LitElement {
this.value = ev.detail.value; this.value = ev.detail.value;
fireEvent(this, "value-changed", { value: this.value }); fireEvent(this, "value-changed", { value: this.value });
} }
private _notFoundLabel = (search: string) => {
const term = html`<b>${search}</b>`;
return this.hass
? this.hass.localize("ui.components.language-picker.no_match", {
term,
})
: html`No languages found for ${term}`;
};
} }
declare global { declare global {

View File

@@ -1,8 +1,7 @@
import { ListItemEl } from "@material/web/list/internal/listitem/list-item"; import { ListItemEl } from "@material/web/list/internal/listitem/list-item";
import { styles } from "@material/web/list/internal/listitem/list-item-styles"; import { styles } from "@material/web/list/internal/listitem/list-item-styles";
import { css, html, nothing, type TemplateResult } from "lit"; import { css } from "lit";
import { customElement } from "lit/decorators"; import { customElement } from "lit/decorators";
import "./ha-ripple";
export const haMdListStyles = [ export const haMdListStyles = [
styles, styles,
@@ -26,18 +25,6 @@ export const haMdListStyles = [
@customElement("ha-md-list-item") @customElement("ha-md-list-item")
export class HaMdListItem extends ListItemEl { export class HaMdListItem extends ListItemEl {
static override styles = haMdListStyles; static override styles = haMdListStyles;
protected renderRipple(): TemplateResult | typeof nothing {
if (this.type === "text") {
return nothing;
}
return html`<ha-ripple
part="ripple"
for="item"
?disabled=${this.disabled && this.type !== "link"}
></ha-ripple>`;
}
} }
declare global { declare global {

View File

@@ -1,6 +1,6 @@
import type { LitVirtualizer } from "@lit-labs/virtualizer"; import type { LitVirtualizer } from "@lit-labs/virtualizer";
import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize"; import type { RenderItemFunction } from "@lit-labs/virtualizer/virtualize";
import { mdiMagnify, mdiMinusBoxOutline } from "@mdi/js"; import { mdiMagnify } from "@mdi/js";
import Fuse from "fuse.js"; import Fuse from "fuse.js";
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { import {
@@ -14,12 +14,11 @@ import memoizeOne from "memoize-one";
import { tinykeys } from "tinykeys"; import { tinykeys } from "tinykeys";
import { fireEvent } from "../common/dom/fire_event"; import { fireEvent } from "../common/dom/fire_event";
import { caseInsensitiveStringCompare } from "../common/string/compare"; import { caseInsensitiveStringCompare } from "../common/string/compare";
import type { LocalizeFunc } from "../common/translations/localize";
import { HaFuse } from "../resources/fuse"; import { HaFuse } from "../resources/fuse";
import { haStyleScrollbar } from "../resources/styles"; import { haStyleScrollbar } from "../resources/styles";
import { loadVirtualizer } from "../resources/virtualizer"; import { loadVirtualizer } from "../resources/virtualizer";
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
import "./chips/ha-chip-set";
import "./chips/ha-filter-chip";
import "./ha-combo-box-item"; import "./ha-combo-box-item";
import "./ha-icon"; import "./ha-icon";
import "./ha-textfield"; import "./ha-textfield";
@@ -28,18 +27,28 @@ import type { HaTextField } from "./ha-textfield";
export interface PickerComboBoxItem { export interface PickerComboBoxItem {
id: string; id: string;
primary: string; primary: string;
a11y_label?: string;
secondary?: string; secondary?: string;
search_labels?: string[]; search_labels?: string[];
sorting_label?: string; sorting_label?: string;
icon_path?: string; icon_path?: string;
icon?: string; icon?: string;
} }
const NO_ITEMS_AVAILABLE_ID = "___no_items_available___";
// Hack to force empty label to always display empty value by default in the search field
export interface PickerComboBoxItemWithLabel extends PickerComboBoxItem {
a11y_label: string;
}
const NO_MATCHING_ITEMS_FOUND_ID = "___no_matching_items_found___";
const DEFAULT_ROW_RENDERER: RenderItemFunction<PickerComboBoxItem> = ( const DEFAULT_ROW_RENDERER: RenderItemFunction<PickerComboBoxItem> = (
item item
) => html` ) => html`
<ha-combo-box-item type="button" compact> <ha-combo-box-item
.type=${item.id === NO_MATCHING_ITEMS_FOUND_ID ? "text" : "button"}
compact
>
${item.icon ${item.icon
? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>` ? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>`
: item.icon_path : item.icon_path
@@ -78,11 +87,8 @@ export class HaPickerComboBox extends LitElement {
@state() private _listScrolled = false; @state() private _listScrolled = false;
@property({ attribute: false }) @property({ attribute: false, type: Array })
public getItems?: ( public getItems?: () => PickerComboBoxItem[];
searchString?: string,
section?: string
) => (PickerComboBoxItem | string)[];
@property({ attribute: false, type: Array }) @property({ attribute: false, type: Array })
public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[]; public getAdditionalItems?: (searchString?: string) => PickerComboBoxItem[];
@@ -90,45 +96,21 @@ export class HaPickerComboBox extends LitElement {
@property({ attribute: false }) @property({ attribute: false })
public rowRenderer?: RenderItemFunction<PickerComboBoxItem>; public rowRenderer?: RenderItemFunction<PickerComboBoxItem>;
@property({ attribute: false }) @property({ attribute: "not-found-label", type: String })
public notFoundLabel?: string | ((search: string) => string); public notFoundLabel?: string;
@property({ attribute: "empty-label" })
public emptyLabel?: string;
@property({ attribute: false }) @property({ attribute: false })
public searchFn?: PickerComboBoxSearchFn<PickerComboBoxItem>; public searchFn?: PickerComboBoxSearchFn<PickerComboBoxItem>;
@property({ reflect: true }) public mode: "popover" | "dialog" = "popover"; @property({ reflect: true }) public mode: "popover" | "dialog" = "popover";
/** Section filter buttons for the list, section headers needs to be defined in getItems as strings */
@property({ attribute: false }) public sections?: (
| {
id: string;
label: string;
}
| "separator"
)[];
@property({ attribute: false }) public sectionTitleFunction?: (listInfo: {
firstIndex: number;
lastIndex: number;
firstItem: PickerComboBoxItem | string;
secondItem: PickerComboBoxItem | string;
itemsCount: number;
}) => string | undefined;
@property({ attribute: "selected-section" }) public selectedSection?: string;
@query("lit-virtualizer") private _virtualizerElement?: LitVirtualizer; @query("lit-virtualizer") private _virtualizerElement?: LitVirtualizer;
@query("ha-textfield") private _searchFieldElement?: HaTextField; @query("ha-textfield") private _searchFieldElement?: HaTextField;
@state() private _items: (PickerComboBoxItem | string)[] = []; @state() private _items: PickerComboBoxItemWithLabel[] = [];
@state() private _sectionTitle?: string; private _allItems: PickerComboBoxItemWithLabel[] = [];
private _allItems: (PickerComboBoxItem | string)[] = [];
private _selectedItemIndex = -1; private _selectedItemIndex = -1;
@@ -139,8 +121,6 @@ export class HaPickerComboBox extends LitElement {
private _removeKeyboardShortcuts?: () => void; private _removeKeyboardShortcuts?: () => void;
private _search = "";
protected firstUpdated() { protected firstUpdated() {
this._registerKeyboardShortcuts(); this._registerKeyboardShortcuts();
} }
@@ -165,142 +145,74 @@ export class HaPickerComboBox extends LitElement {
"Search"} "Search"}
@input=${this._filterChanged} @input=${this._filterChanged}
></ha-textfield> ></ha-textfield>
${this._renderSectionButtons()}
${this.sections?.length
? html`
<div class="section-title-wrapper">
<div
class="section-title ${!this.selectedSection &&
this._sectionTitle
? "show"
: ""}"
>
${this._sectionTitle}
</div>
</div>
`
: nothing}
<lit-virtualizer <lit-virtualizer
.keyFunction=${this._keyFunction} @scroll=${this._onScrollList}
tabindex="0" tabindex="0"
scroller scroller
.items=${this._items} .items=${this._items}
.renderItem=${this._renderItem} .renderItem=${this._renderItem}
style="min-height: 36px;" style="min-height: 36px;"
class=${this._listScrolled ? "scrolled" : ""} class=${this._listScrolled ? "scrolled" : ""}
@scroll=${this._onScrollList}
@focus=${this._focusList} @focus=${this._focusList}
@visibilityChanged=${this._visibilityChanged}
> >
</lit-virtualizer> `; </lit-virtualizer> `;
} }
private _renderSectionButtons() { private _defaultNotFoundItem = memoizeOne(
if (!this.sections || this.sections.length === 0) { (
return nothing; label: this["notFoundLabel"],
} localize?: LocalizeFunc
): PickerComboBoxItemWithLabel => ({
id: NO_MATCHING_ITEMS_FOUND_ID,
primary:
label ||
(localize && localize("ui.components.combo-box.no_match")) ||
"No matching items found",
icon_path: mdiMagnify,
a11y_label:
label ||
(localize && localize("ui.components.combo-box.no_match")) ||
"No matching items found",
})
);
return html` private _getAdditionalItems = (searchString?: string) => {
<ha-chip-set class="sections"> const items = this.getAdditionalItems?.(searchString) || [];
${this.sections.map((section) =>
section === "separator"
? html`<div class="separator"></div>`
: html`<ha-filter-chip
@click=${this._toggleSection}
.section-id=${section.id}
.selected=${this.selectedSection === section.id}
.label=${section.label}
>
</ha-filter-chip>`
)}
</ha-chip-set>
`;
}
@eventOptions({ passive: true }) return items.map<PickerComboBoxItemWithLabel>((item) => ({
private _visibilityChanged(ev) { ...item,
if ( a11y_label: item.a11y_label || item.primary,
this._virtualizerElement && }));
this.sectionTitleFunction && };
this.sections?.length
) {
const firstItem = this._virtualizerElement.items[ev.first];
const secondItem = this._virtualizerElement.items[ev.first + 1];
this._sectionTitle = this.sectionTitleFunction({
firstIndex: ev.first,
lastIndex: ev.last,
firstItem: firstItem as PickerComboBoxItem | string,
secondItem: secondItem as PickerComboBoxItem | string,
itemsCount: this._virtualizerElement.items.length,
});
}
}
private _getAdditionalItems = (searchString?: string) => private _getItems = (): PickerComboBoxItemWithLabel[] => {
this.getAdditionalItems?.(searchString) || []; const items = this.getItems ? this.getItems() : [];
private _getItems = () => { const sortedItems = items
let items = [ .map<PickerComboBoxItemWithLabel>((item) => ({
...(this.getItems ...item,
? this.getItems(this._search, this.selectedSection) a11y_label: item.a11y_label || item.primary,
: []), }))
]; .sort((entityA, entityB) =>
if (!this.sections?.length) {
items = items.sort((entityA, entityB) =>
caseInsensitiveStringCompare( caseInsensitiveStringCompare(
(entityA as PickerComboBoxItem).sorting_label!, entityA.sorting_label!,
(entityB as PickerComboBoxItem).sorting_label!, entityB.sorting_label!,
this.hass?.locale.language ?? navigator.language this.hass?.locale.language ?? navigator.language
) )
); );
}
if (!items.length) { if (!sortedItems.length) {
items.push(NO_ITEMS_AVAILABLE_ID); sortedItems.push(
this._defaultNotFoundItem(this.notFoundLabel, this.hass?.localize)
);
} }
const additionalItems = this._getAdditionalItems(); const additionalItems = this._getAdditionalItems();
items.push(...additionalItems); sortedItems.push(...additionalItems);
return sortedItems;
if (this.mode === "dialog") {
items.push("padding"); // padding for safe area inset
}
return items;
}; };
private _renderItem = (item: PickerComboBoxItem | string, index: number) => { private _renderItem = (item: PickerComboBoxItem, index: number) => {
if (item === "padding") {
return html`<div class="bottom-padding"></div>`;
}
if (item === NO_ITEMS_AVAILABLE_ID) {
return html`
<div class="combo-box-row">
<ha-combo-box-item type="text" compact>
<ha-svg-icon
slot="start"
.path=${this._search ? mdiMagnify : mdiMinusBoxOutline}
></ha-svg-icon>
<span slot="headline"
>${this._search
? typeof this.notFoundLabel === "function"
? this.notFoundLabel(this._search)
: this.notFoundLabel ||
this.hass?.localize("ui.components.combo-box.no_match") ||
"No matching items found"
: this.emptyLabel ||
this.hass?.localize("ui.components.combo-box.no_items") ||
"No items available"}</span
>
</ha-combo-box-item>
</div>
`;
}
if (typeof item === "string") {
return html`<div class="title">${item}</div>`;
}
const renderer = this.rowRenderer || DEFAULT_ROW_RENDERER; const renderer = this.rowRenderer || DEFAULT_ROW_RENDERER;
return html`<div return html`<div
id=${`list-item-${index}`} id=${`list-item-${index}`}
@@ -309,7 +221,9 @@ export class HaPickerComboBox extends LitElement {
.index=${index} .index=${index}
@click=${this._valueSelected} @click=${this._valueSelected}
> >
${renderer(item, index)} ${item.id === NO_MATCHING_ITEMS_FOUND_ID
? DEFAULT_ROW_RENDERER(item, index)
: renderer(item, index)}
</div>`; </div>`;
}; };
@@ -328,6 +242,10 @@ export class HaPickerComboBox extends LitElement {
const value = (ev.currentTarget as any).value as string; const value = (ev.currentTarget as any).value as string;
const newValue = value?.trim(); const newValue = value?.trim();
if (newValue === NO_MATCHING_ITEMS_FOUND_ID) {
return;
}
fireEvent(this, "value-changed", { value: newValue }); fireEvent(this, "value-changed", { value: newValue });
}; };
@@ -338,83 +256,51 @@ export class HaPickerComboBox extends LitElement {
private _filterChanged = (ev: Event) => { private _filterChanged = (ev: Event) => {
const textfield = ev.target as HaTextField; const textfield = ev.target as HaTextField;
const searchString = textfield.value.trim(); const searchString = textfield.value.trim();
this._search = searchString;
if (this.sections?.length) { if (!searchString) {
this._items = this._getItems(); this._items = this._allItems;
} else { return;
if (!searchString) {
this._items = this._allItems;
return;
}
const index = this._fuseIndex(this._allItems as PickerComboBoxItem[]);
const fuse = new HaFuse(
this._allItems as PickerComboBoxItem[],
{
shouldSort: false,
minMatchCharLength: Math.min(searchString.length, 2),
},
index
);
const results = fuse.multiTermsSearch(searchString);
let filteredItems = [...this._allItems];
if (results) {
const items: (PickerComboBoxItem | string)[] = results.map(
(result) => result.item
);
if (!items.length) {
filteredItems.push(NO_ITEMS_AVAILABLE_ID);
}
const additionalItems = this._getAdditionalItems();
items.push(...additionalItems);
filteredItems = items;
}
if (this.searchFn) {
filteredItems = this.searchFn(
searchString,
filteredItems as PickerComboBoxItem[],
this._allItems as PickerComboBoxItem[]
);
}
this._items = filteredItems as PickerComboBoxItem[];
} }
const index = this._fuseIndex(this._allItems);
const fuse = new HaFuse(
this._allItems,
{
shouldSort: false,
minMatchCharLength: Math.min(searchString.length, 2),
},
index
);
const results = fuse.multiTermsSearch(searchString);
let filteredItems = this._allItems as PickerComboBoxItem[];
if (results) {
const items = results.map((result) => result.item);
if (items.length === 0) {
items.push(
this._defaultNotFoundItem(this.notFoundLabel, this.hass?.localize)
);
}
const additionalItems = this._getAdditionalItems(searchString);
items.push(...additionalItems);
filteredItems = items;
}
if (this.searchFn) {
filteredItems = this.searchFn(
searchString,
filteredItems,
this._allItems
);
}
this._items = filteredItems as PickerComboBoxItemWithLabel[];
this._selectedItemIndex = -1; this._selectedItemIndex = -1;
if (this._virtualizerElement) { if (this._virtualizerElement) {
this._virtualizerElement.scrollTo(0, 0); this._virtualizerElement.scrollTo(0, 0);
} }
}; };
private _toggleSection(ev: Event) {
ev.stopPropagation();
this._resetSelectedItem();
this._sectionTitle = undefined;
const section = (ev.target as HTMLElement)["section-id"] as string;
if (!section) {
return;
}
if (this.selectedSection === section) {
this.selectedSection = undefined;
} else {
this.selectedSection = section;
}
this._items = this._getItems();
// Reset scroll position when filter changes
if (this._virtualizerElement) {
this._virtualizerElement.scrollToIndex(0);
}
}
private _registerKeyboardShortcuts() { private _registerKeyboardShortcuts() {
this._removeKeyboardShortcuts = tinykeys(this, { this._removeKeyboardShortcuts = tinykeys(this, {
ArrowUp: this._selectPreviousItem, ArrowUp: this._selectPreviousItem,
@@ -458,7 +344,7 @@ export class HaPickerComboBox extends LitElement {
return; return;
} }
if (typeof items[nextIndex] === "string") { if (items[nextIndex].id === NO_MATCHING_ITEMS_FOUND_ID) {
// Skip titles, padding and empty search // Skip titles, padding and empty search
if (nextIndex === maxItems) { if (nextIndex === maxItems) {
return; return;
@@ -487,7 +373,7 @@ export class HaPickerComboBox extends LitElement {
return; return;
} }
if (typeof items[nextIndex] === "string") { if (items[nextIndex]?.id === NO_MATCHING_ITEMS_FOUND_ID) {
// Skip titles, padding and empty search // Skip titles, padding and empty search
if (nextIndex === 0) { if (nextIndex === 0) {
return; return;
@@ -509,6 +395,13 @@ export class HaPickerComboBox extends LitElement {
const nextIndex = 0; const nextIndex = 0;
if (
(this._virtualizerElement.items[nextIndex] as PickerComboBoxItem)?.id ===
NO_MATCHING_ITEMS_FOUND_ID
) {
return;
}
if (typeof this._virtualizerElement.items[nextIndex] === "string") { if (typeof this._virtualizerElement.items[nextIndex] === "string") {
this._selectedItemIndex = nextIndex + 1; this._selectedItemIndex = nextIndex + 1;
} else { } else {
@@ -526,6 +419,13 @@ export class HaPickerComboBox extends LitElement {
const nextIndex = this._virtualizerElement.items.length - 1; const nextIndex = this._virtualizerElement.items.length - 1;
if (
(this._virtualizerElement.items[nextIndex] as PickerComboBoxItem)?.id ===
NO_MATCHING_ITEMS_FOUND_ID
) {
return;
}
if (typeof this._virtualizerElement.items[nextIndex] === "string") { if (typeof this._virtualizerElement.items[nextIndex] === "string") {
this._selectedItemIndex = nextIndex - 1; this._selectedItemIndex = nextIndex - 1;
} else { } else {
@@ -553,7 +453,10 @@ export class HaPickerComboBox extends LitElement {
ev.stopPropagation(); ev.stopPropagation();
const firstItem = this._virtualizerElement?.items[0] as PickerComboBoxItem; const firstItem = this._virtualizerElement?.items[0] as PickerComboBoxItem;
if (this._virtualizerElement?.items.length === 1) { if (
this._virtualizerElement?.items.length === 1 &&
firstItem.id !== NO_MATCHING_ITEMS_FOUND_ID
) {
fireEvent(this, "value-changed", { fireEvent(this, "value-changed", {
value: firstItem.id, value: firstItem.id,
}); });
@@ -569,7 +472,7 @@ export class HaPickerComboBox extends LitElement {
const item = this._virtualizerElement?.items[ const item = this._virtualizerElement?.items[
this._selectedItemIndex this._selectedItemIndex
] as PickerComboBoxItem; ] as PickerComboBoxItem;
if (item) { if (item && item.id !== NO_MATCHING_ITEMS_FOUND_ID) {
fireEvent(this, "value-changed", { value: item.id }); fireEvent(this, "value-changed", { value: item.id });
} }
}; };
@@ -581,9 +484,6 @@ export class HaPickerComboBox extends LitElement {
this._selectedItemIndex = -1; this._selectedItemIndex = -1;
} }
private _keyFunction = (item: PickerComboBoxItem | string) =>
typeof item === "string" ? item : item.id;
static styles = [ static styles = [
haStyleScrollbar, haStyleScrollbar,
css` css`
@@ -658,80 +558,6 @@ export class HaPickerComboBox extends LitElement {
background-color: var(--ha-color-fill-neutral-normal-hover); background-color: var(--ha-color-fill-neutral-normal-hover);
} }
} }
.sections {
display: flex;
flex-wrap: nowrap;
gap: var(--ha-space-2);
padding: var(--ha-space-3) var(--ha-space-3);
overflow: auto;
}
:host([mode="dialog"]) .sections {
padding: var(--ha-space-3) var(--ha-space-4);
}
.sections ha-filter-chip {
flex-shrink: 0;
--md-filter-chip-selected-container-color: var(
--ha-color-fill-primary-normal-hover
);
color: var(--primary-color);
}
.sections .separator {
height: var(--ha-space-8);
width: 0;
border: 1px solid var(--ha-color-border-neutral-quiet);
}
.section-title,
.title {
background-color: var(--ha-color-fill-neutral-quiet-resting);
padding: var(--ha-space-1) var(--ha-space-2);
font-weight: var(--ha-font-weight-bold);
color: var(--secondary-text-color);
min-height: var(--ha-space-6);
display: flex;
align-items: center;
}
.title {
width: 100%;
}
:host([mode="dialog"]) .title {
padding: var(--ha-space-1) var(--ha-space-4);
}
:host([mode="dialog"]) ha-textfield {
padding: 0 var(--ha-space-4);
}
.section-title-wrapper {
height: 0;
position: relative;
}
.section-title {
opacity: 0;
position: absolute;
top: 1px;
width: calc(100% - var(--ha-space-8));
}
.section-title.show {
opacity: 1;
z-index: 1;
}
.empty-search {
display: flex;
width: 100%;
flex-direction: column;
align-items: center;
padding: var(--ha-space-3);
}
`, `,
]; ];
} }

View File

@@ -1,8 +1,6 @@
import type { HassServiceTarget } from "home-assistant-js-websocket";
import { html, LitElement } from "lit"; import { html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property } from "lit/decorators";
import type { StateSelector } from "../../data/selector"; import type { StateSelector } from "../../data/selector";
import { extractFromTarget } from "../../data/target";
import { SubscribeMixin } from "../../mixins/subscribe-mixin"; import { SubscribeMixin } from "../../mixins/subscribe-mixin";
import type { HomeAssistant } from "../../types"; import type { HomeAssistant } from "../../types";
import "../entity/ha-entity-state-picker"; import "../entity/ha-entity-state-picker";
@@ -27,29 +25,15 @@ export class HaSelectorState extends SubscribeMixin(LitElement) {
@property({ attribute: false }) public context?: { @property({ attribute: false }) public context?: {
filter_attribute?: string; filter_attribute?: string;
filter_entity?: string | string[]; filter_entity?: string | string[];
filter_target?: HassServiceTarget;
}; };
@state() private _entityIds?: string | string[];
willUpdate(changedProps) {
if (changedProps.has("selector") || changedProps.has("context")) {
this._resolveEntityIds(
this.selector.state?.entity_id,
this.context?.filter_entity,
this.context?.filter_target
).then((entityIds) => {
this._entityIds = entityIds;
});
}
}
protected render() { protected render() {
if (this.selector.state?.multiple) { if (this.selector.state?.multiple) {
return html` return html`
<ha-entity-states-picker <ha-entity-states-picker
.hass=${this.hass} .hass=${this.hass}
.entityId=${this._entityIds} .entityId=${this.selector.state?.entity_id ||
this.context?.filter_entity}
.attribute=${this.selector.state?.attribute || .attribute=${this.selector.state?.attribute ||
this.context?.filter_attribute} this.context?.filter_attribute}
.extraOptions=${this.selector.state?.extra_options} .extraOptions=${this.selector.state?.extra_options}
@@ -66,7 +50,8 @@ export class HaSelectorState extends SubscribeMixin(LitElement) {
return html` return html`
<ha-entity-state-picker <ha-entity-state-picker
.hass=${this.hass} .hass=${this.hass}
.entityId=${this._entityIds} .entityId=${this.selector.state?.entity_id ||
this.context?.filter_entity}
.attribute=${this.selector.state?.attribute || .attribute=${this.selector.state?.attribute ||
this.context?.filter_attribute} this.context?.filter_attribute}
.extraOptions=${this.selector.state?.extra_options} .extraOptions=${this.selector.state?.extra_options}
@@ -80,24 +65,6 @@ export class HaSelectorState extends SubscribeMixin(LitElement) {
></ha-entity-state-picker> ></ha-entity-state-picker>
`; `;
} }
private async _resolveEntityIds(
selectorEntityId: string | string[] | undefined,
contextFilterEntity: string | string[] | undefined,
contextFilterTarget: HassServiceTarget | undefined
): Promise<string | string[] | undefined> {
if (selectorEntityId !== undefined) {
return selectorEntityId;
}
if (contextFilterEntity !== undefined) {
return contextFilterEntity;
}
if (contextFilterTarget !== undefined) {
const result = await extractFromTarget(this.hass, contextFilterTarget);
return result.referenced_entities;
}
return undefined;
}
} }
declare global { declare global {

View File

@@ -157,9 +157,7 @@ export const computePanels = memoizeOne(
Object.values(panels).forEach((panel) => { Object.values(panels).forEach((panel) => {
if ( if (
hiddenPanels.includes(panel.url_path) || hiddenPanels.includes(panel.url_path) ||
(!panel.title && panel.url_path !== defaultPanel) || (!panel.title && panel.url_path !== defaultPanel)
(panel.default_visible === false &&
!panelsOrder.includes(panel.url_path))
) { ) {
return; return;
} }

View File

@@ -1,31 +1,15 @@
import "@home-assistant/webawesome/dist/components/popover/popover"; import "@home-assistant/webawesome/dist/components/popover/popover";
import { consume } from "@lit/context";
// @ts-ignore // @ts-ignore
import chipStyles from "@material/chips/dist/mdc.chips.min.css"; import chipStyles from "@material/chips/dist/mdc.chips.min.css";
import { mdiPlus, mdiTextureBox } from "@mdi/js"; import { mdiPlaylistPlus } from "@mdi/js";
import Fuse from "fuse.js";
import type { HassServiceTarget } from "home-assistant-js-websocket"; import type { HassServiceTarget } from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues } from "lit"; import type { CSSResultGroup } from "lit";
import { LitElement, css, html, nothing, unsafeCSS } from "lit"; import { LitElement, css, html, nothing, unsafeCSS } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, query, state } from "lit/decorators";
import { styleMap } from "lit/directives/style-map";
import memoizeOne from "memoize-one";
import { ensureArray } from "../common/array/ensure-array"; import { ensureArray } from "../common/array/ensure-array";
import { fireEvent } from "../common/dom/fire_event"; import { fireEvent } from "../common/dom/fire_event";
import { isValidEntityId } from "../common/entity/valid_entity_id"; import { isValidEntityId } from "../common/entity/valid_entity_id";
import { computeRTL } from "../common/util/compute_rtl";
import {
getAreasAndFloors,
type AreaFloorValue,
type FloorComboBoxItem,
} from "../data/area_floor";
import { getConfigEntries, type ConfigEntry } from "../data/config_entries";
import { labelsContext } from "../data/context";
import { getDevices, type DevicePickerItem } from "../data/device_registry";
import type { HaEntityPickerEntityFilterFunc } from "../data/entity"; import type { HaEntityPickerEntityFilterFunc } from "../data/entity";
import { getEntities, type EntityComboBoxItem } from "../data/entity_registry";
import { domainToName } from "../data/integration";
import { getLabels, type LabelRegistryEntry } from "../data/label_registry";
import { import {
areaMeetsFilter, areaMeetsFilter,
deviceMeetsFilter, deviceMeetsFilter,
@@ -34,23 +18,18 @@ import {
type TargetTypeFloorless, type TargetTypeFloorless,
} from "../data/target"; } from "../data/target";
import { SubscribeMixin } from "../mixins/subscribe-mixin"; import { SubscribeMixin } from "../mixins/subscribe-mixin";
import { isHelperDomain } from "../panels/config/helpers/const";
import { showHelperDetailDialog } from "../panels/config/helpers/show-dialog-helper-detail"; import { showHelperDetailDialog } from "../panels/config/helpers/show-dialog-helper-detail";
import { HaFuse } from "../resources/fuse";
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
import { brandsUrl } from "../util/brands-url";
import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker"; import type { HaDevicePickerDeviceFilterFunc } from "./device/ha-device-picker";
import "./ha-generic-picker"; import "./ha-bottom-sheet";
import type { PickerComboBoxItem } from "./ha-picker-combo-box"; import "./ha-button";
import "./ha-input-helper-text";
import "./ha-svg-icon"; import "./ha-svg-icon";
import "./ha-tree-indicator";
import "./target-picker/ha-target-picker-item-group"; import "./target-picker/ha-target-picker-item-group";
import "./target-picker/ha-target-picker-selector";
import type { HaTargetPickerSelector } from "./target-picker/ha-target-picker-selector";
import "./target-picker/ha-target-picker-value-chip"; import "./target-picker/ha-target-picker-value-chip";
const EMPTY_SEARCH = "___EMPTY_SEARCH___";
const SEPARATOR = "________";
const CREATE_ID = "___create-new-entity___";
@customElement("ha-target-picker") @customElement("ha-target-picker")
export class HaTargetPicker extends SubscribeMixin(LitElement) { export class HaTargetPicker extends SubscribeMixin(LitElement) {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@@ -89,54 +68,23 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
@property({ attribute: "add-on-top", type: Boolean }) public addOnTop = false; @property({ attribute: "add-on-top", type: Boolean }) public addOnTop = false;
@state() private _selectedSection?: TargetTypeFloorless; @state() private _open = false;
@state() private _configEntryLookup: Record<string, ConfigEntry> = {}; @state() private _addTargetWidth = 0;
@state() @state() private _narrow = false;
@consume({ context: labelsContext, subscribe: true })
private _labelRegistry!: LabelRegistryEntry[]; @state() private _pickerFilter?: TargetTypeFloorless;
@state() private _pickerWrapperOpen = false;
@query(".add-target-wrapper") private _addTargetWrapper?: HTMLDivElement;
@query("ha-target-picker-selector")
private _targetPickerSelectorElement?: HaTargetPickerSelector;
private _newTarget?: { type: TargetType; id: string }; private _newTarget?: { type: TargetType; id: string };
private _getDevicesMemoized = memoizeOne(getDevices);
private _getLabelsMemoized = memoizeOne(getLabels);
private _getEntitiesMemoized = memoizeOne(getEntities);
private _getAreasAndFloorsMemoized = memoizeOne(getAreasAndFloors);
private get _showEntityId() {
return this.hass.userData?.showEntityIdPicker;
}
private _fuseIndexes = {
area: memoizeOne((states: FloorComboBoxItem[]) =>
this._createFuseIndex(states)
),
entity: memoizeOne((states: EntityComboBoxItem[]) =>
this._createFuseIndex(states)
),
device: memoizeOne((states: DevicePickerItem[]) =>
this._createFuseIndex(states)
),
label: memoizeOne((states: PickerComboBoxItem[]) =>
this._createFuseIndex(states)
),
};
public willUpdate(changedProps: PropertyValues) {
super.willUpdate(changedProps);
if (!this.hasUpdated) {
this._loadConfigEntries();
}
}
private _createFuseIndex = (states) =>
Fuse.createIndex(["search_labels"], states);
protected render() { protected render() {
if (this.addOnTop) { if (this.addOnTop) {
return html` ${this._renderPicker()} ${this._renderItems()} `; return html` ${this._renderPicker()} ${this._renderItems()} `;
@@ -341,63 +289,137 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
} }
private _renderPicker() { private _renderPicker() {
const sections = [
{
id: "entity",
label: this.hass.localize("ui.components.target-picker.type.entities"),
},
{
id: "device",
label: this.hass.localize("ui.components.target-picker.type.devices"),
},
{
id: "area",
label: this.hass.localize("ui.components.target-picker.type.areas"),
},
"separator" as const,
{
id: "label",
label: this.hass.localize("ui.components.target-picker.type.labels"),
},
];
return html` return html`
<div class="add-target-wrapper"> <div class="add-target-wrapper">
<ha-generic-picker <ha-button
.hass=${this.hass} id="add-target-button"
.disabled=${this.disabled} size="small"
.autofocus=${this.autofocus} appearance="filled"
.helper=${this.helper} @click=${this._showPicker}
.sections=${sections}
.notFoundLabel=${this._noTargetFoundLabel}
.emptyLabel=${this.hass.localize(
"ui.components.target-picker.no_targets"
)}
.sectionTitleFunction=${this._sectionTitleFunction}
.selectedSection=${this._selectedSection}
.rowRenderer=${this._renderRow}
.getItems=${this._getItems}
@value-changed=${this._targetPicked}
.addButtonLabel=${this.hass.localize(
"ui.components.target-picker.add_target"
)}
.getAdditionalItems=${this._getAdditionalItems}
> >
</ha-generic-picker> <ha-svg-icon .path=${mdiPlaylistPlus} slot="start"></ha-svg-icon>
${this.hass.localize("ui.components.target-picker.add_target")}
</ha-button>
${!this._narrow && (this._pickerWrapperOpen || this._open)
? html`
<wa-popover
.open=${this._pickerWrapperOpen}
style="--body-width: ${this._addTargetWidth}px;"
without-arrow
distance="-4"
placement="bottom-start"
for="add-target-button"
auto-size="vertical"
auto-size-padding="16"
@wa-after-show=${this._showSelector}
@wa-after-hide=${this._hidePicker}
trap-focus
role="dialog"
aria-modal="true"
aria-label=${this.hass.localize(
"ui.components.target-picker.add_target"
)}
>
${this._renderTargetSelector()}
</wa-popover>
`
: this._pickerWrapperOpen || this._open
? html`<ha-bottom-sheet
flexcontent
.open=${this._pickerWrapperOpen}
@wa-after-show=${this._showSelector}
@closed=${this._hidePicker}
role="dialog"
aria-modal="true"
aria-label=${this.hass.localize(
"ui.components.target-picker.add_target"
)}
>
${this._renderTargetSelector(true)}
</ha-bottom-sheet>`
: nothing}
</div> </div>
${this.helper
? html`<ha-input-helper-text .disabled=${this.disabled}
>${this.helper}</ha-input-helper-text
>`
: nothing}
`; `;
} }
private _targetPicked(ev: CustomEvent<{ value: string }>) { connectedCallback() {
ev.stopPropagation(); super.connectedCallback();
const value = ev.detail.value; this._handleResize();
if (value.startsWith(CREATE_ID)) { window.addEventListener("resize", this._handleResize);
this._createNewDomainElement(value.substring(CREATE_ID.length)); }
return;
}
const [type, id] = ev.detail.value.split(SEPARATOR); public disconnectedCallback() {
this._addTarget(id, type as TargetType); super.disconnectedCallback();
window.removeEventListener("resize", this._handleResize);
}
private _handleResize = () => {
this._narrow =
window.matchMedia("(max-width: 870px)").matches ||
window.matchMedia("(max-height: 500px)").matches;
};
private _showPicker() {
this._addTargetWidth = this._addTargetWrapper?.offsetWidth || 0;
this._pickerWrapperOpen = true;
}
// wait for drawer animation to finish
private _showSelector = () => {
this._open = true;
requestAnimationFrame(() => {
this._targetPickerSelectorElement?.focus();
});
};
private _handleUpdatePickerFilter(
ev: CustomEvent<TargetTypeFloorless | undefined>
) {
this._updatePickerFilter(
typeof ev.detail === "string" ? ev.detail : undefined
);
}
private _updatePickerFilter = (filter?: TargetTypeFloorless) => {
this._pickerFilter = filter;
};
private _hidePicker(ev) {
ev.stopPropagation();
this._open = false;
this._pickerWrapperOpen = false;
if (this._newTarget) {
this._addTarget(this._newTarget.id, this._newTarget.type);
this._newTarget = undefined;
}
}
private _renderTargetSelector(dialogMode = false) {
if (!this._open) {
return nothing;
}
return html`
<ha-target-picker-selector
.hass=${this.hass}
@filter-type-changed=${this._handleUpdatePickerFilter}
.filterType=${this._pickerFilter}
@target-picked=${this._handleTargetPicked}
@create-domain-picked=${this._handleCreateDomain}
.targetValue=${this.value}
.deviceFilter=${this.deviceFilter}
.entityFilter=${this.entityFilter}
.includeDomains=${this.includeDomains}
.includeDeviceClasses=${this.includeDeviceClasses}
.createDomains=${this.createDomains}
.mode=${dialogMode ? "dialog" : "popover"}
></ha-target-picker-selector>
`;
} }
private _addTarget(id: string, type: TargetType) { private _addTarget(id: string, type: TargetType) {
@@ -432,7 +454,26 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
?.removeAttribute("collapsed"); ?.removeAttribute("collapsed");
} }
private _createNewDomainElement = (domain: string) => { private _handleTargetPicked = async (
ev: CustomEvent<{ type: TargetType; id: string }>
) => {
ev.stopPropagation();
this._pickerWrapperOpen = false;
if (!ev.detail.type || !ev.detail.id) {
return;
}
// save new target temporarily to add it after dialog closes
this._newTarget = ev.detail;
};
private _handleCreateDomain = (ev: CustomEvent<string>) => {
this._pickerWrapperOpen = false;
const domain = ev.detail;
showHelperDetailDialog(this, { showHelperDetailDialog(this, {
domain, domain,
dialogClosedCallback: (item) => { dialogClosedCallback: (item) => {
@@ -634,459 +675,6 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
return undefined; return undefined;
} }
private _getRowType = (
item:
| PickerComboBoxItem
| (FloorComboBoxItem & { last?: boolean | undefined })
| EntityComboBoxItem
| DevicePickerItem
) => {
if (
(item as FloorComboBoxItem).type === "area" ||
(item as FloorComboBoxItem).type === "floor"
) {
return (item as FloorComboBoxItem).type;
}
if ("domain" in item) {
return "device";
}
if ("stateObj" in item) {
return "entity";
}
if (item.id === EMPTY_SEARCH) {
return "empty";
}
return "label";
};
private _sectionTitleFunction = ({
firstIndex,
lastIndex,
firstItem,
secondItem,
itemsCount,
}: {
firstIndex: number;
lastIndex: number;
firstItem: PickerComboBoxItem | string;
secondItem: PickerComboBoxItem | string;
itemsCount: number;
}) => {
if (
firstItem === undefined ||
secondItem === undefined ||
typeof firstItem === "string" ||
(typeof secondItem === "string" && secondItem !== "padding") ||
(firstIndex === 0 && lastIndex === itemsCount - 1)
) {
return undefined;
}
const type = this._getRowType(firstItem as PickerComboBoxItem);
const translationType:
| "areas"
| "entities"
| "devices"
| "labels"
| undefined =
type === "area" || type === "floor"
? "areas"
: type === "entity"
? "entities"
: type && type !== "empty"
? `${type}s`
: undefined;
return translationType
? this.hass.localize(
`ui.components.target-picker.type.${translationType}`
)
: undefined;
};
private _getItems = (searchString: string, section: string) => {
this._selectedSection = section as TargetTypeFloorless | undefined;
return this._getItemsMemoized(
this.hass.localize,
this.entityFilter,
this.deviceFilter,
this.includeDomains,
this.includeDeviceClasses,
this.value,
searchString,
this._configEntryLookup,
this._selectedSection
);
};
private _getItemsMemoized = memoizeOne(
(
localize: HomeAssistant["localize"],
entityFilter: this["entityFilter"],
deviceFilter: this["deviceFilter"],
includeDomains: this["includeDomains"],
includeDeviceClasses: this["includeDeviceClasses"],
targetValue: this["value"],
searchTerm: string,
configEntryLookup: Record<string, ConfigEntry>,
filterType?: TargetTypeFloorless
) => {
const items: (
| string
| FloorComboBoxItem
| EntityComboBoxItem
| PickerComboBoxItem
)[] = [];
if (!filterType || filterType === "entity") {
let entityItems = this._getEntitiesMemoized(
this.hass,
includeDomains,
undefined,
entityFilter,
includeDeviceClasses,
undefined,
undefined,
targetValue?.entity_id
? ensureArray(targetValue.entity_id)
: undefined,
undefined,
`entity${SEPARATOR}`
);
if (searchTerm) {
entityItems = this._filterGroup(
"entity",
entityItems,
searchTerm,
(item: EntityComboBoxItem) =>
item.stateObj?.entity_id === searchTerm
) as EntityComboBoxItem[];
}
if (!filterType && entityItems.length) {
// show group title
items.push(localize("ui.components.target-picker.type.entities"));
}
items.push(...entityItems);
}
if (!filterType || filterType === "device") {
let deviceItems = this._getDevicesMemoized(
this.hass,
configEntryLookup,
includeDomains,
undefined,
includeDeviceClasses,
deviceFilter,
entityFilter,
targetValue?.device_id
? ensureArray(targetValue.device_id)
: undefined,
undefined,
`device${SEPARATOR}`
);
if (searchTerm) {
deviceItems = this._filterGroup("device", deviceItems, searchTerm);
}
if (!filterType && deviceItems.length) {
// show group title
items.push(localize("ui.components.target-picker.type.devices"));
}
items.push(...deviceItems);
}
if (!filterType || filterType === "area") {
let areasAndFloors = this._getAreasAndFloorsMemoized(
this.hass.states,
this.hass.floors,
this.hass.areas,
this.hass.devices,
this.hass.entities,
memoizeOne((value: AreaFloorValue): string =>
[value.type, value.id].join(SEPARATOR)
),
includeDomains,
undefined,
includeDeviceClasses,
deviceFilter,
entityFilter,
targetValue?.area_id ? ensureArray(targetValue.area_id) : undefined,
targetValue?.floor_id ? ensureArray(targetValue.floor_id) : undefined
);
if (searchTerm) {
areasAndFloors = this._filterGroup(
"area",
areasAndFloors,
searchTerm
) as FloorComboBoxItem[];
}
if (!filterType && areasAndFloors.length) {
// show group title
items.push(localize("ui.components.target-picker.type.areas"));
}
items.push(
...areasAndFloors.map((item, index) => {
const nextItem = areasAndFloors[index + 1];
if (
!nextItem ||
(item.type === "area" && nextItem.type === "floor")
) {
return {
...item,
last: true,
};
}
return item;
})
);
}
if (!filterType || filterType === "label") {
let labels = this._getLabelsMemoized(
this.hass,
this._labelRegistry,
includeDomains,
undefined,
includeDeviceClasses,
deviceFilter,
entityFilter,
targetValue?.label_id ? ensureArray(targetValue.label_id) : undefined,
`label${SEPARATOR}`
);
if (searchTerm) {
labels = this._filterGroup("label", labels, searchTerm);
}
if (!filterType && labels.length) {
// show group title
items.push(localize("ui.components.target-picker.type.labels"));
}
items.push(...labels);
}
return items;
}
);
private _filterGroup(
type: TargetType,
items: (FloorComboBoxItem | PickerComboBoxItem | EntityComboBoxItem)[],
searchTerm: string,
checkExact?: (
item: FloorComboBoxItem | PickerComboBoxItem | EntityComboBoxItem
) => boolean
) {
const fuseIndex = this._fuseIndexes[type](items);
const fuse = new HaFuse(
items,
{
shouldSort: false,
minMatchCharLength: Math.min(searchTerm.length, 2),
},
fuseIndex
);
const results = fuse.multiTermsSearch(searchTerm);
let filteredItems = items;
if (results) {
filteredItems = results.map((result) => result.item);
}
if (!checkExact) {
return filteredItems;
}
// If there is exact match for entity id, put it first
const index = filteredItems.findIndex((item) => checkExact(item));
if (index === -1) {
return filteredItems;
}
const [exactMatch] = filteredItems.splice(index, 1);
filteredItems.unshift(exactMatch);
return filteredItems;
}
private _getAdditionalItems = () => this._getCreateItems(this.createDomains);
private _getCreateItems = memoizeOne(
(createDomains: this["createDomains"]) => {
if (!createDomains?.length) {
return [];
}
return createDomains.map((domain) => {
const primary = this.hass.localize(
"ui.components.entity.entity-picker.create_helper",
{
domain: isHelperDomain(domain)
? this.hass.localize(`ui.panel.config.helpers.types.${domain}`)
: domainToName(this.hass.localize, domain),
}
);
return {
id: CREATE_ID + domain,
primary: primary,
secondary: this.hass.localize(
"ui.components.entity.entity-picker.new_entity"
),
icon_path: mdiPlus,
} satisfies EntityComboBoxItem;
});
}
);
private async _loadConfigEntries() {
const configEntries = await getConfigEntries(this.hass);
this._configEntryLookup = Object.fromEntries(
configEntries.map((entry) => [entry.entry_id, entry])
);
}
private _renderRow = (
item:
| PickerComboBoxItem
| (FloorComboBoxItem & { last?: boolean | undefined })
| EntityComboBoxItem
| DevicePickerItem,
index: number
) => {
if (!item) {
return nothing;
}
const type = this._getRowType(item);
let hasFloor = false;
let rtl = false;
let showEntityId = false;
if (type === "area" || type === "floor") {
item.id = item[type]?.[`${type}_id`];
rtl = computeRTL(this.hass);
hasFloor =
type === "area" && !!(item as FloorComboBoxItem).area?.floor_id;
}
if (type === "entity") {
showEntityId = !!this._showEntityId;
}
return html`
<ha-combo-box-item
id=${`list-item-${index}`}
tabindex="-1"
.type=${type === "empty" ? "text" : "button"}
class=${type === "empty" ? "empty" : ""}
style=${(item as FloorComboBoxItem).type === "area" && hasFloor
? "--md-list-item-leading-space: var(--ha-space-12);"
: ""}
>
${(item as FloorComboBoxItem).type === "area" && hasFloor
? html`
<ha-tree-indicator
style=${styleMap({
width: "var(--ha-space-12)",
position: "absolute",
top: "var(--ha-space-0)",
left: rtl ? undefined : "var(--ha-space-1)",
right: rtl ? "var(--ha-space-1)" : undefined,
transform: rtl ? "scaleX(-1)" : "",
})}
.end=${(
item as FloorComboBoxItem & { last?: boolean | undefined }
).last}
slot="start"
></ha-tree-indicator>
`
: nothing}
${item.icon
? html`<ha-icon slot="start" .icon=${item.icon}></ha-icon>`
: item.icon_path
? html`<ha-svg-icon
slot="start"
.path=${item.icon_path}
></ha-svg-icon>`
: type === "entity" && (item as EntityComboBoxItem).stateObj
? html`
<state-badge
slot="start"
.stateObj=${(item as EntityComboBoxItem).stateObj}
.hass=${this.hass}
></state-badge>
`
: type === "device" && (item as DevicePickerItem).domain
? html`
<img
slot="start"
alt=""
crossorigin="anonymous"
referrerpolicy="no-referrer"
src=${brandsUrl({
domain: (item as DevicePickerItem).domain!,
type: "icon",
darkOptimized: this.hass.themes.darkMode,
})}
/>
`
: type === "floor"
? html`<ha-floor-icon
slot="start"
.floor=${(item as FloorComboBoxItem).floor!}
></ha-floor-icon>`
: type === "area"
? html`<ha-svg-icon
slot="start"
.path=${item.icon_path || mdiTextureBox}
></ha-svg-icon>`
: nothing}
<span slot="headline">${item.primary}</span>
${item.secondary
? html`<span slot="supporting-text">${item.secondary}</span>`
: nothing}
${(item as EntityComboBoxItem).stateObj && showEntityId
? html`
<span slot="supporting-text" class="code">
${(item as EntityComboBoxItem).stateObj?.entity_id}
</span>
`
: nothing}
${(item as EntityComboBoxItem).domain_name &&
(type !== "entity" || !showEntityId)
? html`
<div slot="trailing-supporting-text" class="domain">
${(item as EntityComboBoxItem).domain_name}
</div>
`
: nothing}
</ha-combo-box-item>
`;
};
private _noTargetFoundLabel = (search: string) =>
this.hass.localize("ui.components.target-picker.no_target_found", {
term: html`<b>${search}</b>`,
});
static get styles(): CSSResultGroup { static get styles(): CSSResultGroup {
return css` return css`
.add-target-wrapper { .add-target-wrapper {
@@ -1095,8 +683,31 @@ export class HaTargetPicker extends SubscribeMixin(LitElement) {
margin-top: var(--ha-space-3); margin-top: var(--ha-space-3);
} }
ha-generic-picker { wa-popover {
width: 100%; --wa-space-l: var(--ha-space-0);
}
wa-popover::part(body) {
width: min(max(var(--body-width), 336px), 600px);
max-width: min(max(var(--body-width), 336px), 600px);
max-height: 500px;
height: 70vh;
overflow: hidden;
}
@media (max-height: 1000px) {
wa-popover::part(body) {
max-height: 400px;
}
}
ha-bottom-sheet {
--ha-bottom-sheet-height: 90vh;
--ha-bottom-sheet-height: calc(100dvh - var(--ha-space-12));
--ha-bottom-sheet-max-height: var(--ha-bottom-sheet-height);
--ha-bottom-sheet-max-width: 600px;
--ha-bottom-sheet-padding: var(--ha-space-0);
--ha-bottom-sheet-surface-background: var(--card-background-color);
} }
${unsafeCSS(chipStyles)} ${unsafeCSS(chipStyles)}

View File

@@ -1,97 +0,0 @@
import {
mdiAvTimer,
mdiCalendar,
mdiClockOutline,
mdiCodeBraces,
mdiDevices,
mdiFormatListBulleted,
mdiGestureDoubleTap,
mdiHomeAssistant,
mdiMapMarker,
mdiMapMarkerRadius,
mdiMessageAlert,
mdiMicrophoneMessage,
mdiNfcVariant,
mdiNumeric,
mdiStateMachine,
mdiSwapHorizontal,
mdiWeatherSunny,
mdiWebhook,
} from "@mdi/js";
import { html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { until } from "lit/directives/until";
import { computeDomain } from "../common/entity/compute_domain";
import { FALLBACK_DOMAIN_ICONS, triggerIcon } from "../data/icons";
import type { HomeAssistant } from "../types";
import "./ha-icon";
import "./ha-svg-icon";
export const TRIGGER_ICONS = {
calendar: mdiCalendar,
device: mdiDevices,
event: mdiGestureDoubleTap,
state: mdiStateMachine,
geo_location: mdiMapMarker,
homeassistant: mdiHomeAssistant,
mqtt: mdiSwapHorizontal,
numeric_state: mdiNumeric,
sun: mdiWeatherSunny,
conversation: mdiMicrophoneMessage,
tag: mdiNfcVariant,
template: mdiCodeBraces,
time: mdiClockOutline,
time_pattern: mdiAvTimer,
webhook: mdiWebhook,
persistent_notification: mdiMessageAlert,
zone: mdiMapMarkerRadius,
list: mdiFormatListBulleted,
};
@customElement("ha-trigger-icon")
export class HaTriggerIcon extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property() public trigger?: string;
@property() public icon?: string;
protected render() {
if (this.icon) {
return html`<ha-icon .icon=${this.icon}></ha-icon>`;
}
if (!this.trigger) {
return nothing;
}
if (!this.hass) {
return this._renderFallback();
}
const icon = triggerIcon(this.hass, this.trigger).then((icn) => {
if (icn) {
return html`<ha-icon .icon=${icn}></ha-icon>`;
}
return this._renderFallback();
});
return html`${until(icon)}`;
}
private _renderFallback() {
const domain = computeDomain(this.trigger!);
return html`
<ha-svg-icon
.path=${TRIGGER_ICONS[this.trigger!] || FALLBACK_DOMAIN_ICONS[domain]}
></ha-svg-icon>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
"ha-trigger-icon": HaTriggerIcon;
}
}

View File

@@ -1,4 +1,6 @@
import { css, html, LitElement } from "lit"; import "@home-assistant/webawesome/dist/components/dialog/dialog";
import { mdiClose } from "@mdi/js";
import { css, html, LitElement, nothing } from "lit";
import { import {
customElement, customElement,
eventOptions, eventOptions,
@@ -6,9 +8,6 @@ import {
query, query,
state, state,
} from "lit/decorators"; } from "lit/decorators";
import { ifDefined } from "lit/directives/if-defined";
import { mdiClose } from "@mdi/js";
import "@home-assistant/webawesome/dist/components/dialog/dialog";
import { fireEvent } from "../common/dom/fire_event"; import { fireEvent } from "../common/dom/fire_event";
import { haStyleScrollbar } from "../resources/styles"; import { haStyleScrollbar } from "../resources/styles";
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
@@ -32,8 +31,6 @@ export type DialogWidth = "small" | "medium" | "large" | "full";
* *
* @slot header - Replace the entire header area. * @slot header - Replace the entire header area.
* @slot headerNavigationIcon - Leading header action (e.g. close/back button). * @slot headerNavigationIcon - Leading header action (e.g. close/back button).
* @slot headerTitle - Custom title content (used when header-title is not set).
* @slot headerSubtitle - Custom subtitle content (used when header-subtitle is not set).
* @slot headerActionItems - Trailing header actions (e.g. buttons, menus). * @slot headerActionItems - Trailing header actions (e.g. buttons, menus).
* @slot - Dialog content body. * @slot - Dialog content body.
* @slot footer - Dialog footer content. * @slot footer - Dialog footer content.
@@ -55,8 +52,8 @@ export type DialogWidth = "small" | "medium" | "large" | "full";
* @attr {boolean} open - Controls the dialog open state. * @attr {boolean} open - Controls the dialog open state.
* @attr {("small"|"medium"|"large"|"full")} width - Preferred dialog width preset. Defaults to "medium". * @attr {("small"|"medium"|"large"|"full")} width - Preferred dialog width preset. Defaults to "medium".
* @attr {boolean} prevent-scrim-close - Prevents closing the dialog by clicking the scrim/overlay. Defaults to false. * @attr {boolean} prevent-scrim-close - Prevents closing the dialog by clicking the scrim/overlay. Defaults to false.
* @attr {string} header-title - Header title text. If not set, the headerTitle slot is used. * @attr {string} header-title - Header title text when no custom title slot is provided.
* @attr {string} header-subtitle - Header subtitle text. If not set, the headerSubtitle slot is used. * @attr {string} header-subtitle - Header subtitle text when no custom subtitle slot is provided.
* @attr {("above"|"below")} header-subtitle-position - Position of the subtitle relative to the title. Defaults to "below". * @attr {("above"|"below")} header-subtitle-position - Position of the subtitle relative to the title. Defaults to "below".
* @attr {boolean} flexcontent - Makes the dialog body a flex container for flexible layouts. * @attr {boolean} flexcontent - Makes the dialog body a flex container for flexible layouts.
* *
@@ -75,12 +72,6 @@ export type DialogWidth = "small" | "medium" | "large" | "full";
export class HaWaDialog extends LitElement { export class HaWaDialog extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: "aria-labelledby" })
public ariaLabelledBy?: string;
@property({ attribute: "aria-describedby" })
public ariaDescribedBy?: string;
@property({ type: Boolean, reflect: true }) @property({ type: Boolean, reflect: true })
public open = false; public open = false;
@@ -90,11 +81,11 @@ export class HaWaDialog extends LitElement {
@property({ type: Boolean, reflect: true, attribute: "prevent-scrim-close" }) @property({ type: Boolean, reflect: true, attribute: "prevent-scrim-close" })
public preventScrimClose = false; public preventScrimClose = false;
@property({ attribute: "header-title" }) @property({ type: String, attribute: "header-title" })
public headerTitle?: string; public headerTitle = "";
@property({ attribute: "header-subtitle" }) @property({ type: String, attribute: "header-subtitle" })
public headerSubtitle?: string; public headerSubtitle = "";
@property({ type: String, attribute: "header-subtitle-position" }) @property({ type: String, attribute: "header-subtitle-position" })
public headerSubtitlePosition: "above" | "below" = "below"; public headerSubtitlePosition: "above" | "below" = "below";
@@ -126,11 +117,6 @@ export class HaWaDialog extends LitElement {
.open=${this._open} .open=${this._open}
.lightDismiss=${!this.preventScrimClose} .lightDismiss=${!this.preventScrimClose}
without-header without-header
aria-labelledby=${ifDefined(
this.ariaLabelledBy ||
(this.headerTitle !== undefined ? "ha-wa-dialog-title" : undefined)
)}
aria-describedby=${ifDefined(this.ariaDescribedBy)}
@wa-show=${this._handleShow} @wa-show=${this._handleShow}
@wa-after-show=${this._handleAfterShow} @wa-after-show=${this._handleAfterShow}
@wa-after-hide=${this._handleAfterHide} @wa-after-hide=${this._handleAfterHide}
@@ -147,14 +133,14 @@ export class HaWaDialog extends LitElement {
.path=${mdiClose} .path=${mdiClose}
></ha-icon-button> ></ha-icon-button>
</slot> </slot>
${this.headerTitle !== undefined ${this.headerTitle
? html`<span slot="title" class="title" id="ha-wa-dialog-title"> ? html`<span slot="title" class="title">
${this.headerTitle} ${this.headerTitle}
</span>` </span>`
: html`<slot name="headerTitle" slot="title"></slot>`} : nothing}
${this.headerSubtitle !== undefined ${this.headerSubtitle
? html`<span slot="subtitle">${this.headerSubtitle}</span>` ? html`<span slot="subtitle">${this.headerSubtitle}</span>`
: html`<slot name="headerSubtitle" slot="subtitle"></slot>`} : nothing}
<slot name="headerActionItems" slot="actionItems"></slot> <slot name="headerActionItems" slot="actionItems"></slot>
</ha-dialog-header> </ha-dialog-header>
</slot> </slot>

View File

@@ -545,7 +545,7 @@ export class HaTargetPickerItemRow extends LitElement {
name: entityName || deviceName || item, name: entityName || deviceName || item,
context, context,
stateObject, stateObject,
notFound: !stateObject && item !== "all" && item !== "none", notFound: !stateObject && item !== "all",
}; };
} }

File diff suppressed because it is too large Load Diff

View File

@@ -128,7 +128,9 @@ class HaUserPicker extends LitElement {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.notFoundLabel=${this._notFoundLabel} .notFoundLabel=${this.hass.localize(
"ui.components.user-picker.no_match"
)}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
.getItems=${this._getItems} .getItems=${this._getItems}
@@ -147,11 +149,6 @@ class HaUserPicker extends LitElement {
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
fireEvent(this, "change"); fireEvent(this, "change");
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.user-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -50,7 +50,7 @@ export const ACTION_COLLECTIONS: AutomationElementGroupCollection[] = [
{ {
groups: { groups: {
device_id: {}, device_id: {},
dynamicGroups: {}, serviceGroups: {},
}, },
}, },
{ {
@@ -117,6 +117,14 @@ export const VIRTUAL_ACTIONS: Partial<
}, },
} as const; } as const;
export const SERVICE_PREFIX = "__SERVICE__";
export const isService = (key: string | undefined): boolean | undefined =>
key?.startsWith(SERVICE_PREFIX);
export const getService = (key: string): string =>
key.substring(SERVICE_PREFIX.length);
export const COLLAPSIBLE_ACTION_ELEMENTS = [ export const COLLAPSIBLE_ACTION_ELEMENTS = [
"ha-automation-action-choose", "ha-automation-action-choose",
"ha-automation-action-condition", "ha-automation-action-condition",

View File

@@ -5,7 +5,6 @@ export interface AnalyticsPreferences {
diagnostics?: boolean; diagnostics?: boolean;
usage?: boolean; usage?: boolean;
statistics?: boolean; statistics?: boolean;
snapshots?: boolean;
} }
export interface Analytics { export interface Analytics {

View File

@@ -1,10 +1,8 @@
import type { import type {
HassEntityAttributeBase, HassEntityAttributeBase,
HassEntityBase, HassEntityBase,
HassServiceTarget,
} from "home-assistant-js-websocket"; } from "home-assistant-js-websocket";
import { ensureArray } from "../common/array/ensure-array"; import { ensureArray } from "../common/array/ensure-array";
import type { WeekdayShort } from "../common/datetime/weekday";
import { navigate } from "../common/navigate"; import { navigate } from "../common/navigate";
import type { LocalizeKeys } from "../common/translations/localize"; import type { LocalizeKeys } from "../common/translations/localize";
import { createSearchParam } from "../common/url/search-params"; import { createSearchParam } from "../common/url/search-params";
@@ -14,19 +12,10 @@ import { CONDITION_BUILDING_BLOCKS } from "./condition";
import type { DeviceCondition, DeviceTrigger } from "./device_automation"; import type { DeviceCondition, DeviceTrigger } from "./device_automation";
import type { Action, Field, MODES } from "./script"; import type { Action, Field, MODES } from "./script";
import { migrateAutomationAction } from "./script"; import { migrateAutomationAction } from "./script";
import type { TriggerDescription } from "./trigger";
export const AUTOMATION_DEFAULT_MODE: (typeof MODES)[number] = "single"; export const AUTOMATION_DEFAULT_MODE: (typeof MODES)[number] = "single";
export const AUTOMATION_DEFAULT_MAX = 10; export const AUTOMATION_DEFAULT_MAX = 10;
export const DYNAMIC_PREFIX = "__DYNAMIC__";
export const isDynamic = (key: string | undefined): boolean | undefined =>
key?.startsWith(DYNAMIC_PREFIX);
export const getValueFromDynamic = (key: string): string =>
key.substring(DYNAMIC_PREFIX.length);
export interface AutomationEntity extends HassEntityBase { export interface AutomationEntity extends HassEntityBase {
attributes: HassEntityAttributeBase & { attributes: HassEntityAttributeBase & {
id?: string; id?: string;
@@ -96,12 +85,6 @@ export interface BaseTrigger {
id?: string; id?: string;
variables?: Record<string, unknown>; variables?: Record<string, unknown>;
enabled?: boolean; enabled?: boolean;
options?: Record<string, unknown>;
}
export interface PlatformTrigger extends BaseTrigger {
trigger: Exclude<string, LegacyTrigger["trigger"]>;
target?: HassServiceTarget;
} }
export interface StateTrigger extends BaseTrigger { export interface StateTrigger extends BaseTrigger {
@@ -211,7 +194,7 @@ export interface CalendarTrigger extends BaseTrigger {
offset: string; offset: string;
} }
export type LegacyTrigger = export type Trigger =
| StateTrigger | StateTrigger
| MqttTrigger | MqttTrigger
| GeoLocationTrigger | GeoLocationTrigger
@@ -228,9 +211,8 @@ export type LegacyTrigger =
| TemplateTrigger | TemplateTrigger
| EventTrigger | EventTrigger
| DeviceTrigger | DeviceTrigger
| CalendarTrigger; | CalendarTrigger
| TriggerList;
export type Trigger = LegacyTrigger | TriggerList | PlatformTrigger;
interface BaseCondition { interface BaseCondition {
condition: string; condition: string;
@@ -275,11 +257,13 @@ export interface ZoneCondition extends BaseCondition {
zone: string; zone: string;
} }
type Weekday = "sun" | "mon" | "tue" | "wed" | "thu" | "fri" | "sat";
export interface TimeCondition extends BaseCondition { export interface TimeCondition extends BaseCondition {
condition: "time"; condition: "time";
after?: string; after?: string;
before?: string; before?: string;
weekday?: WeekdayShort | WeekdayShort[]; weekday?: Weekday | Weekday[];
} }
export interface TemplateCondition extends BaseCondition { export interface TemplateCondition extends BaseCondition {
@@ -592,7 +576,6 @@ export interface TriggerSidebarConfig extends BaseSidebarConfig {
insertAfter: (value: Trigger | Trigger[]) => boolean; insertAfter: (value: Trigger | Trigger[]) => boolean;
toggleYamlMode: () => void; toggleYamlMode: () => void;
config: Trigger; config: Trigger;
description?: TriggerDescription;
yamlMode: boolean; yamlMode: boolean;
uiSupported: boolean; uiSupported: boolean;
} }

View File

@@ -16,9 +16,8 @@ import {
formatListWithAnds, formatListWithAnds,
formatListWithOrs, formatListWithOrs,
} from "../common/string/format-list"; } from "../common/string/format-list";
import { hasTemplate } from "../common/string/has-template";
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
import type { Condition, ForDict, LegacyTrigger, Trigger } from "./automation"; import type { Condition, ForDict, Trigger } from "./automation";
import type { DeviceCondition, DeviceTrigger } from "./device_automation"; import type { DeviceCondition, DeviceTrigger } from "./device_automation";
import { import {
localizeDeviceAutomationCondition, localizeDeviceAutomationCondition,
@@ -26,7 +25,8 @@ import {
} from "./device_automation"; } from "./device_automation";
import type { EntityRegistryEntry } from "./entity_registry"; import type { EntityRegistryEntry } from "./entity_registry";
import type { FrontendLocaleData } from "./translation"; import type { FrontendLocaleData } from "./translation";
import { getTriggerDomain, getTriggerObjectId, isTriggerList } from "./trigger"; import { isTriggerList } from "./trigger";
import { hasTemplate } from "../common/string/has-template";
const triggerTranslationBaseKey = const triggerTranslationBaseKey =
"ui.panel.config.automation.editor.triggers.type"; "ui.panel.config.automation.editor.triggers.type";
@@ -121,37 +121,6 @@ const tryDescribeTrigger = (
return trigger.alias; return trigger.alias;
} }
const description = describeLegacyTrigger(
trigger as LegacyTrigger,
hass,
entityRegistry
);
if (description) {
return description;
}
const triggerType = trigger.trigger;
const domain = getTriggerDomain(trigger.trigger);
const type = getTriggerObjectId(trigger.trigger);
return (
hass.localize(
`component.${domain}.triggers.${type}.description_configured`
) ||
hass.localize(
`ui.panel.config.automation.editor.triggers.type.${triggerType as LegacyTrigger["trigger"]}.label`
) ||
hass.localize(`ui.panel.config.automation.editor.triggers.unknown_trigger`)
);
};
const describeLegacyTrigger = (
trigger: LegacyTrigger,
hass: HomeAssistant,
entityRegistry: EntityRegistryEntry[]
) => {
// Event Trigger // Event Trigger
if (trigger.trigger === "event" && trigger.event_type) { if (trigger.trigger === "event" && trigger.event_type) {
const eventTypes: string[] = []; const eventTypes: string[] = [];
@@ -833,7 +802,13 @@ const describeLegacyTrigger = (
} }
); );
} }
return undefined;
return (
hass.localize(
`ui.panel.config.automation.editor.triggers.type.${trigger.trigger}.label`
) ||
hass.localize(`ui.panel.config.automation.editor.triggers.unknown_trigger`)
);
}; };
export const describeCondition = ( export const describeCondition = (

View File

@@ -186,8 +186,7 @@ export const getDevices = (
deviceFilter?: HaDevicePickerDeviceFilterFunc, deviceFilter?: HaDevicePickerDeviceFilterFunc,
entityFilter?: HaEntityPickerEntityFilterFunc, entityFilter?: HaEntityPickerEntityFilterFunc,
excludeDevices?: string[], excludeDevices?: string[],
value?: string, value?: string
idPrefix = ""
): DevicePickerItem[] => { ): DevicePickerItem[] => {
const devices = Object.values(hass.devices); const devices = Object.values(hass.devices);
const entities = Object.values(hass.entities); const entities = Object.values(hass.entities);
@@ -299,7 +298,7 @@ export const getDevices = (
const domainName = domain ? domainToName(hass.localize, domain) : undefined; const domainName = domain ? domainToName(hass.localize, domain) : undefined;
return { return {
id: `${idPrefix}${device.id}`, id: device.id,
label: "", label: "",
primary: primary:
deviceName || deviceName ||

View File

@@ -102,7 +102,6 @@ export type EnergySolarForecasts = Record<string, EnergySolarForecast>;
export interface DeviceConsumptionEnergyPreference { export interface DeviceConsumptionEnergyPreference {
// This is an ever increasing value // This is an ever increasing value
stat_consumption: string; stat_consumption: string;
stat_rate?: string;
name?: string; name?: string;
included_in_stat?: string; included_in_stat?: string;
} }
@@ -131,17 +130,11 @@ export interface FlowToGridSourceEnergyPreference {
number_energy_price: number | null; number_energy_price: number | null;
} }
export interface GridPowerSourceEnergyPreference {
// W meter
stat_rate: string;
}
export interface GridSourceTypeEnergyPreference { export interface GridSourceTypeEnergyPreference {
type: "grid"; type: "grid";
flow_from: FlowFromGridSourceEnergyPreference[]; flow_from: FlowFromGridSourceEnergyPreference[];
flow_to: FlowToGridSourceEnergyPreference[]; flow_to: FlowToGridSourceEnergyPreference[];
power?: GridPowerSourceEnergyPreference[];
cost_adjustment_day: number; cost_adjustment_day: number;
} }
@@ -150,7 +143,6 @@ export interface SolarSourceTypeEnergyPreference {
type: "solar"; type: "solar";
stat_energy_from: string; stat_energy_from: string;
stat_rate?: string;
config_entry_solar_forecast: string[] | null; config_entry_solar_forecast: string[] | null;
} }
@@ -158,7 +150,6 @@ export interface BatterySourceTypeEnergyPreference {
type: "battery"; type: "battery";
stat_energy_from: string; stat_energy_from: string;
stat_energy_to: string; stat_energy_to: string;
stat_rate?: string;
} }
export interface GasSourceTypeEnergyPreference { export interface GasSourceTypeEnergyPreference {
type: "gas"; type: "gas";
@@ -360,35 +351,6 @@ export const getReferencedStatisticIds = (
return statIDs; return statIDs;
}; };
export const getReferencedStatisticIdsPower = (
prefs: EnergyPreferences
): string[] => {
const statIDs: (string | undefined)[] = [];
for (const source of prefs.energy_sources) {
if (source.type === "gas" || source.type === "water") {
continue;
}
if (source.type === "solar") {
statIDs.push(source.stat_rate);
continue;
}
if (source.type === "battery") {
statIDs.push(source.stat_rate);
continue;
}
if (source.power) {
statIDs.push(...source.power.map((p) => p.stat_rate));
}
}
statIDs.push(...prefs.device_consumption.map((d) => d.stat_rate));
return statIDs.filter(Boolean) as string[];
};
export const enum CompareMode { export const enum CompareMode {
NONE = "", NONE = "",
PREVIOUS = "previous", PREVIOUS = "previous",
@@ -436,10 +398,9 @@ const getEnergyData = async (
"gas", "gas",
"device", "device",
]); ]);
const powerStatIds = getReferencedStatisticIdsPower(prefs);
const waterStatIds = getReferencedStatisticIds(prefs, info, ["water"]); const waterStatIds = getReferencedStatisticIds(prefs, info, ["water"]);
const allStatIDs = [...energyStatIds, ...waterStatIds, ...powerStatIds]; const allStatIDs = [...energyStatIds, ...waterStatIds];
const dayDifference = differenceInDays(end || new Date(), start); const dayDifference = differenceInDays(end || new Date(), start);
const period = const period =
@@ -450,8 +411,6 @@ const getEnergyData = async (
: dayDifference > 2 : dayDifference > 2
? "day" ? "day"
: "hour"; : "hour";
const finePeriod =
dayDifference > 64 ? "day" : dayDifference > 8 ? "hour" : "5minute";
const statsMetadata: Record<string, StatisticsMetaData> = {}; const statsMetadata: Record<string, StatisticsMetaData> = {};
const statsMetadataArray = allStatIDs.length const statsMetadataArray = allStatIDs.length
@@ -473,9 +432,6 @@ const getEnergyData = async (
? (gasUnit as (typeof VOLUME_UNITS)[number]) ? (gasUnit as (typeof VOLUME_UNITS)[number])
: undefined, : undefined,
}; };
const powerUnits: StatisticsUnitConfiguration = {
power: "kW",
};
const waterUnit = getEnergyWaterUnit(hass, prefs, statsMetadata); const waterUnit = getEnergyWaterUnit(hass, prefs, statsMetadata);
const waterUnits: StatisticsUnitConfiguration = { const waterUnits: StatisticsUnitConfiguration = {
volume: waterUnit, volume: waterUnit,
@@ -486,12 +442,6 @@ const getEnergyData = async (
"change", "change",
]) ])
: {}; : {};
const _powerStats: Statistics | Promise<Statistics> = powerStatIds.length
? fetchStatistics(hass!, start, end, powerStatIds, finePeriod, powerUnits, [
"mean",
])
: {};
const _waterStats: Statistics | Promise<Statistics> = waterStatIds.length const _waterStats: Statistics | Promise<Statistics> = waterStatIds.length
? fetchStatistics(hass!, start, end, waterStatIds, period, waterUnits, [ ? fetchStatistics(hass!, start, end, waterStatIds, period, waterUnits, [
"change", "change",
@@ -598,7 +548,6 @@ const getEnergyData = async (
const [ const [
energyStats, energyStats,
powerStats,
waterStats, waterStats,
energyStatsCompare, energyStatsCompare,
waterStatsCompare, waterStatsCompare,
@@ -606,14 +555,13 @@ const getEnergyData = async (
fossilEnergyConsumptionCompare, fossilEnergyConsumptionCompare,
] = await Promise.all([ ] = await Promise.all([
_energyStats, _energyStats,
_powerStats,
_waterStats, _waterStats,
_energyStatsCompare, _energyStatsCompare,
_waterStatsCompare, _waterStatsCompare,
_fossilEnergyConsumption, _fossilEnergyConsumption,
_fossilEnergyConsumptionCompare, _fossilEnergyConsumptionCompare,
]); ]);
const stats = { ...energyStats, ...waterStats, ...powerStats }; const stats = { ...energyStats, ...waterStats };
if (compare) { if (compare) {
statsCompare = { ...energyStatsCompare, ...waterStatsCompare }; statsCompare = { ...energyStatsCompare, ...waterStatsCompare };
} }

View File

@@ -344,8 +344,7 @@ export const getEntities = (
includeUnitOfMeasurement?: string[], includeUnitOfMeasurement?: string[],
includeEntities?: string[], includeEntities?: string[],
excludeEntities?: string[], excludeEntities?: string[],
value?: string, value?: string
idPrefix = ""
): EntityComboBoxItem[] => { ): EntityComboBoxItem[] => {
let items: EntityComboBoxItem[] = []; let items: EntityComboBoxItem[] = [];
@@ -396,9 +395,10 @@ export const getEntities = (
const secondary = [areaName, entityName ? deviceName : undefined] const secondary = [areaName, entityName ? deviceName : undefined]
.filter(Boolean) .filter(Boolean)
.join(isRTL ? " ◂ " : " ▸ "); .join(isRTL ? " ◂ " : " ▸ ");
const a11yLabel = [deviceName, entityName].filter(Boolean).join(" - ");
return { return {
id: `${idPrefix}${entityId}`, id: entityId,
primary: primary, primary: primary,
secondary: secondary, secondary: secondary,
domain_name: domainName, domain_name: domainName,
@@ -411,6 +411,7 @@ export const getEntities = (
friendlyName, friendlyName,
entityId, entityId,
].filter(Boolean) as string[], ].filter(Boolean) as string[],
a11y_label: a11yLabel,
stateObj: stateObj, stateObj: stateObj,
}; };
}); });

View File

@@ -59,7 +59,6 @@ import type {
} from "./entity_registry"; } from "./entity_registry";
import { mdiHomeAssistant } from "../resources/home-assistant-logo-svg"; import { mdiHomeAssistant } from "../resources/home-assistant-logo-svg";
import { getTriggerDomain, getTriggerObjectId } from "./trigger";
/** Icon to use when no icon specified for service. */ /** Icon to use when no icon specified for service. */
export const DEFAULT_SERVICE_ICON = mdiRoomService; export const DEFAULT_SERVICE_ICON = mdiRoomService;
@@ -134,19 +133,14 @@ const resources: {
all?: Promise<Record<string, ServiceIcons>>; all?: Promise<Record<string, ServiceIcons>>;
domains: Record<string, ServiceIcons | Promise<ServiceIcons>>; domains: Record<string, ServiceIcons | Promise<ServiceIcons>>;
}; };
triggers: {
all?: Promise<Record<string, TriggerIcons>>;
domains: Record<string, TriggerIcons | Promise<TriggerIcons>>;
};
} = { } = {
entity: {}, entity: {},
entity_component: {}, entity_component: {},
services: { domains: {} }, services: { domains: {} },
triggers: { domains: {} },
}; };
interface IconResources< interface IconResources<
T extends ComponentIcons | PlatformIcons | ServiceIcons | TriggerIcons, T extends ComponentIcons | PlatformIcons | ServiceIcons,
> { > {
resources: Record<string, T>; resources: Record<string, T>;
} }
@@ -190,22 +184,12 @@ type ServiceIcons = Record<
{ service: string; sections?: Record<string, string> } { service: string; sections?: Record<string, string> }
>; >;
type TriggerIcons = Record< export type IconCategory = "entity" | "entity_component" | "services";
string,
{ trigger: string; sections?: Record<string, string> }
>;
export type IconCategory =
| "entity"
| "entity_component"
| "services"
| "triggers";
interface CategoryType { interface CategoryType {
entity: PlatformIcons; entity: PlatformIcons;
entity_component: ComponentIcons; entity_component: ComponentIcons;
services: ServiceIcons; services: ServiceIcons;
triggers: TriggerIcons;
} }
export const getHassIcons = async <T extends IconCategory>( export const getHassIcons = async <T extends IconCategory>(
@@ -274,59 +258,42 @@ export const getComponentIcons = async (
return resources.entity_component.resources.then((res) => res[domain]); return resources.entity_component.resources.then((res) => res[domain]);
}; };
export const getCategoryIcons = async < export const getServiceIcons = async (
T extends Exclude<IconCategory, "entity" | "entity_component">,
>(
hass: HomeAssistant, hass: HomeAssistant,
category: T,
domain?: string, domain?: string,
force = false force = false
): Promise<CategoryType[T] | Record<string, CategoryType[T]> | undefined> => { ): Promise<ServiceIcons | Record<string, ServiceIcons> | undefined> => {
if (!domain) { if (!domain) {
if (!force && resources[category].all) { if (!force && resources.services.all) {
return resources[category].all as Promise< return resources.services.all;
Record<string, CategoryType[T]>
>;
} }
resources[category].all = getHassIcons(hass, category).then((res) => { resources.services.all = getHassIcons(hass, "services", domain).then(
resources[category].domains = res.resources as any; (res) => {
return res?.resources as Record<string, CategoryType[T]>; resources.services.domains = res.resources;
}) as any; return res?.resources;
return resources[category].all as Promise<Record<string, CategoryType[T]>>; }
);
return resources.services.all;
} }
if (!force && domain in resources[category].domains) { if (!force && domain in resources.services.domains) {
return resources[category].domains[domain] as Promise<CategoryType[T]>; return resources.services.domains[domain];
} }
if (resources[category].all && !force) { if (resources.services.all && !force) {
await resources[category].all; await resources.services.all;
if (domain in resources[category].domains) { if (domain in resources.services.domains) {
return resources[category].domains[domain] as Promise<CategoryType[T]>; return resources.services.domains[domain];
} }
} }
if (!isComponentLoaded(hass, domain)) { if (!isComponentLoaded(hass, domain)) {
return undefined; return undefined;
} }
const result = getHassIcons(hass, category, domain); const result = getHassIcons(hass, "services", domain);
resources[category].domains[domain] = result.then( resources.services.domains[domain] = result.then(
(res) => res?.resources[domain] (res) => res?.resources[domain]
) as any; );
return resources[category].domains[domain] as Promise<CategoryType[T]>; return resources.services.domains[domain];
}; };
export const getServiceIcons = async (
hass: HomeAssistant,
domain?: string,
force = false
): Promise<ServiceIcons | Record<string, ServiceIcons> | undefined> =>
getCategoryIcons(hass, "services", domain, force);
export const getTriggerIcons = async (
hass: HomeAssistant,
domain?: string,
force = false
): Promise<TriggerIcons | Record<string, TriggerIcons> | undefined> =>
getCategoryIcons(hass, "triggers", domain, force);
// Cache for sorted range keys // Cache for sorted range keys
const sortedRangeCache = new WeakMap<Record<string, string>, number[]>(); const sortedRangeCache = new WeakMap<Record<string, string>, number[]>();
@@ -506,26 +473,6 @@ export const attributeIcon = async (
return icon; return icon;
}; };
export const triggerIcon = async (
hass: HomeAssistant,
trigger: string
): Promise<string | undefined> => {
let icon: string | undefined;
const domain = getTriggerDomain(trigger);
const triggerName = getTriggerObjectId(trigger);
const triggerIcons = await getTriggerIcons(hass, domain);
if (triggerIcons) {
const trgrIcon = triggerIcons[triggerName] as TriggerIcons[string];
icon = trgrIcon?.trigger;
}
if (!icon) {
icon = await domainIcon(hass, domain);
}
return icon;
};
export const serviceIcon = async ( export const serviceIcon = async (
hass: HomeAssistant, hass: HomeAssistant,
service: string service: string

View File

@@ -108,8 +108,7 @@ export const getLabels = (
includeDeviceClasses?: string[], includeDeviceClasses?: string[],
deviceFilter?: HaDevicePickerDeviceFilterFunc, deviceFilter?: HaDevicePickerDeviceFilterFunc,
entityFilter?: HaEntityPickerEntityFilterFunc, entityFilter?: HaEntityPickerEntityFilterFunc,
excludeLabels?: string[], excludeLabels?: string[]
idPrefix = ""
): PickerComboBoxItem[] => { ): PickerComboBoxItem[] => {
if (!labels || labels.length === 0) { if (!labels || labels.length === 0) {
return []; return [];
@@ -263,7 +262,7 @@ export const getLabels = (
} }
const items = outputLabels.map<PickerComboBoxItem>((label) => ({ const items = outputLabels.map<PickerComboBoxItem>((label) => ({
id: `${idPrefix}${label.label_id}`, id: label.label_id,
primary: label.name, primary: label.name,
secondary: label.description ?? "", secondary: label.description ?? "",
icon: label.icon || undefined, icon: label.icon || undefined,

View File

@@ -222,7 +222,6 @@ export interface StopAction extends BaseAction {
export interface SequenceAction extends BaseAction { export interface SequenceAction extends BaseAction {
sequence: (ManualScriptConfig | Action)[]; sequence: (ManualScriptConfig | Action)[];
metadata?: {};
} }
export interface ParallelAction extends BaseAction { export interface ParallelAction extends BaseAction {
@@ -480,7 +479,6 @@ export const migrateAutomationAction = (
} }
if (typeof action === "object" && action !== null && "sequence" in action) { if (typeof action === "object" && action !== null && "sequence" in action) {
delete (action as SequenceAction).metadata;
for (const sequenceAction of (action as SequenceAction).sequence) { for (const sequenceAction of (action as SequenceAction).sequence) {
migrateAutomationAction(sequenceAction); migrateAutomationAction(sequenceAction);
} }

View File

@@ -28,7 +28,6 @@ export interface TodoItem {
status: TodoItemStatus | null; status: TodoItemStatus | null;
description?: string | null; description?: string | null;
due?: string | null; due?: string | null;
completed?: string | null;
} }
export const enum TodoListEntityFeature { export const enum TodoListEntityFeature {

View File

@@ -73,8 +73,7 @@ export type TranslationCategory =
| "application_credentials" | "application_credentials"
| "issues" | "issues"
| "selector" | "selector"
| "services" | "services";
| "triggers";
export const subscribeTranslationPreferences = ( export const subscribeTranslationPreferences = (
hass: HomeAssistant, hass: HomeAssistant,

View File

@@ -1,20 +1,57 @@
import { mdiMapClock, mdiShape } from "@mdi/js"; import {
mdiAvTimer,
mdiCalendar,
mdiClockOutline,
mdiCodeBraces,
mdiDevices,
mdiFormatListBulleted,
mdiGestureDoubleTap,
mdiMapClock,
mdiMapMarker,
mdiMapMarkerRadius,
mdiMessageAlert,
mdiMicrophoneMessage,
mdiNfcVariant,
mdiNumeric,
mdiShape,
mdiStateMachine,
mdiSwapHorizontal,
mdiWeatherSunny,
mdiWebhook,
} from "@mdi/js";
import { computeDomain } from "../common/entity/compute_domain"; import { mdiHomeAssistant } from "../resources/home-assistant-logo-svg";
import { computeObjectId } from "../common/entity/compute_object_id";
import type { HomeAssistant } from "../types";
import type { import type {
AutomationElementGroupCollection, AutomationElementGroupCollection,
Trigger, Trigger,
TriggerList, TriggerList,
} from "./automation"; } from "./automation";
import type { Selector, TargetSelector } from "./selector";
export const TRIGGER_ICONS = {
calendar: mdiCalendar,
device: mdiDevices,
event: mdiGestureDoubleTap,
state: mdiStateMachine,
geo_location: mdiMapMarker,
homeassistant: mdiHomeAssistant,
mqtt: mdiSwapHorizontal,
numeric_state: mdiNumeric,
sun: mdiWeatherSunny,
conversation: mdiMicrophoneMessage,
tag: mdiNfcVariant,
template: mdiCodeBraces,
time: mdiClockOutline,
time_pattern: mdiAvTimer,
webhook: mdiWebhook,
persistent_notification: mdiMessageAlert,
zone: mdiMapMarkerRadius,
list: mdiFormatListBulleted,
};
export const TRIGGER_COLLECTIONS: AutomationElementGroupCollection[] = [ export const TRIGGER_COLLECTIONS: AutomationElementGroupCollection[] = [
{ {
groups: { groups: {
device: {}, device: {},
dynamicGroups: {},
entity: { icon: mdiShape, members: { state: {}, numeric_state: {} } }, entity: { icon: mdiShape, members: { state: {}, numeric_state: {} } },
time_location: { time_location: {
icon: mdiMapClock, icon: mdiMapClock,
@@ -46,33 +83,3 @@ export const TRIGGER_COLLECTIONS: AutomationElementGroupCollection[] = [
export const isTriggerList = (trigger: Trigger): trigger is TriggerList => export const isTriggerList = (trigger: Trigger): trigger is TriggerList =>
"triggers" in trigger; "triggers" in trigger;
export interface TriggerDescription {
target?: TargetSelector["target"];
fields: Record<
string,
{
example?: string | boolean | number;
default?: unknown;
required?: boolean;
selector?: Selector;
context?: Record<string, string>;
}
>;
}
export type TriggerDescriptions = Record<string, TriggerDescription>;
export const subscribeTriggers = (
hass: HomeAssistant,
callback: (triggers: TriggerDescriptions) => void
) =>
hass.connection.subscribeMessage<TriggerDescriptions>(callback, {
type: "trigger_platforms/subscribe",
});
export const getTriggerDomain = (trigger: string) =>
trigger.includes(".") ? computeDomain(trigger) : trigger;
export const getTriggerObjectId = (trigger: string) =>
trigger.includes(".") ? computeObjectId(trigger) : "_";

View File

@@ -2,8 +2,7 @@ import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../common/dom/fire_event"; import { fireEvent } from "../../common/dom/fire_event";
import "../../components/ha-wa-dialog"; import { createCloseHeading } from "../../components/ha-dialog";
import "../../components/ha-dialog-footer";
import "../../components/ha-formfield"; import "../../components/ha-formfield";
import "../../components/ha-switch"; import "../../components/ha-switch";
import "../../components/ha-button"; import "../../components/ha-button";
@@ -29,8 +28,6 @@ class DialogConfigEntrySystemOptions extends LitElement {
@state() private _submitting = false; @state() private _submitting = false;
@state() private _open = false;
public async showDialog( public async showDialog(
params: ConfigEntrySystemOptionsDialogParams params: ConfigEntrySystemOptionsDialogParams
): Promise<void> { ): Promise<void> {
@@ -38,14 +35,9 @@ class DialogConfigEntrySystemOptions extends LitElement {
this._error = undefined; this._error = undefined;
this._disableNewEntities = params.entry.pref_disable_new_entities; this._disableNewEntities = params.entry.pref_disable_new_entities;
this._disablePolling = params.entry.pref_disable_polling; this._disablePolling = params.entry.pref_disable_polling;
this._open = true;
} }
public closeDialog(): void { public closeDialog(): void {
this._open = false;
}
private _dialogClosed(): void {
this._error = ""; this._error = "";
this._params = undefined; this._params = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName }); fireEvent(this, "dialog-closed", { dialog: this.localName });
@@ -57,19 +49,18 @@ class DialogConfigEntrySystemOptions extends LitElement {
} }
return html` return html`
<ha-wa-dialog <ha-dialog
.hass=${this.hass} open
.open=${this._open} @closed=${this.closeDialog}
header-title=${this.hass.localize( .heading=${createCloseHeading(
"ui.dialogs.config_entry_system_options.title", this.hass,
{ this.hass.localize("ui.dialogs.config_entry_system_options.title", {
integration: integration:
this.hass.localize( this.hass.localize(
`component.${this._params.entry.domain}.title` `component.${this._params.entry.domain}.title`
) || this._params.entry.domain, ) || this._params.entry.domain,
} })
)} )}
@closed=${this._dialogClosed}
> >
${this._error ? html` <div class="error">${this._error}</div> ` : ""} ${this._error ? html` <div class="error">${this._error}</div> ` : ""}
<ha-formfield <ha-formfield
@@ -91,10 +82,10 @@ class DialogConfigEntrySystemOptions extends LitElement {
</p>`} </p>`}
> >
<ha-switch <ha-switch
autofocus
.checked=${!this._disableNewEntities} .checked=${!this._disableNewEntities}
@change=${this._disableNewEntitiesChanged} @change=${this._disableNewEntitiesChanged}
.disabled=${this._submitting} .disabled=${this._submitting}
dialogInitialFocus
></ha-switch> ></ha-switch>
</ha-formfield> </ha-formfield>
@@ -122,27 +113,22 @@ class DialogConfigEntrySystemOptions extends LitElement {
.disabled=${this._submitting} .disabled=${this._submitting}
></ha-switch> ></ha-switch>
</ha-formfield> </ha-formfield>
<ha-button
<ha-dialog-footer slot="footer"> appearance="plain"
<ha-button slot="primaryAction"
appearance="plain" @click=${this.closeDialog}
slot="secondaryAction" .disabled=${this._submitting}
@click=${this.closeDialog} >
.disabled=${this._submitting} ${this.hass.localize("ui.common.cancel")}
> </ha-button>
${this.hass.localize("ui.common.cancel")} <ha-button
</ha-button> slot="primaryAction"
<ha-button @click=${this._updateEntry}
slot="primaryAction" .disabled=${this._submitting}
@click=${this._updateEntry} >
.disabled=${this._submitting} ${this.hass.localize("ui.dialogs.config_entry_system_options.update")}
> </ha-button>
${this.hass.localize( </ha-dialog>
"ui.dialogs.config_entry_system_options.update"
)}
</ha-button>
</ha-dialog-footer>
</ha-wa-dialog>
`; `;
} }

View File

@@ -102,17 +102,6 @@ class DialogEditSidebar extends LitElement {
this.hass.locale this.hass.locale
); );
// Add default hidden panels that are missing in hidden
for (const panel of panels) {
if (
panel.default_visible === false &&
!this._order.includes(panel.url_path) &&
!this._hidden.includes(panel.url_path)
) {
this._hidden.push(panel.url_path);
}
}
const items = [ const items = [
...beforeSpacer, ...beforeSpacer,
...panels.filter((panel) => this._hidden!.includes(panel.url_path)), ...panels.filter((panel) => this._hidden!.includes(panel.url_path)),

View File

@@ -20,44 +20,23 @@
<meta name="color-scheme" content="dark light" /> <meta name="color-scheme" content="dark light" />
<%= renderTemplate("_style_base.html.template") %> <%= renderTemplate("_style_base.html.template") %>
<style> <style>
@keyframes fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
::view-transition-group(launch-screen) {
animation-duration: var(--ha-animation-base-duration, 350ms);
animation-timing-function: ease-out;
}
::view-transition-old(launch-screen) {
animation: fade-out var(--ha-animation-base-duration, 350ms) ease-out;
}
html { html {
background-color: var(--primary-background-color, #fafafa); background-color: var(--primary-background-color, #fafafa);
color: var(--primary-text-color, #212121); color: var(--primary-text-color, #212121);
height: 100vh; height: 100vh;
} }
@media (prefers-color-scheme: dark) {
html {
background-color: var(--primary-background-color, #111111);
color: var(--primary-text-color, #e1e1e1);
}
}
#ha-launch-screen { #ha-launch-screen {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%; height: 100%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
view-transition-name: launch-screen;
background-color: var(--primary-background-color, #fafafa);
z-index: 100;
}
#ha-launch-screen.removing {
opacity: 0;
} }
#ha-launch-screen svg { #ha-launch-screen svg {
width: 112px; width: 112px;
@@ -80,14 +59,6 @@
opacity: .66; opacity: .66;
} }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
html {
background-color: var(--primary-background-color, #111111);
color: var(--primary-text-color, #e1e1e1);
}
/* body selector to avoid minification causing bad jinja2 */
body #ha-launch-screen {
background-color: var(--primary-background-color, #111111);
}
.ohf-logo { .ohf-logo {
filter: invert(1); filter: invert(1);
} }

View File

@@ -11,10 +11,14 @@ class HaInitPage extends LitElement {
@state() private _retryInSeconds = 60; @state() private _retryInSeconds = 60;
@state() private _loadingTimeout = false;
private _showProgressIndicatorTimeout?: number; private _showProgressIndicatorTimeout?: number;
private _retryInterval?: number; private _retryInterval?: number;
private _loadingTimeoutHandle?: number;
protected render() { protected render() {
return this.error return this.error
? html` ? html`
@@ -51,8 +55,35 @@ class HaInitPage extends LitElement {
The upgrade may need a long time to complete, please be The upgrade may need a long time to complete, please be
patient. patient.
` `
: this._loadingTimeout
? html`
<p>Loading is taking longer than expected.</p>
<p class="hint">
This could be caused by a slow connection or cached data.
</p>
`
: "Loading data"} : "Loading data"}
</div> </div>
${this._loadingTimeout && !this.migration
? html`
<div class="button-row">
<ha-button
size="small"
appearance="plain"
@click=${this._retry}
>
Retry now
</ha-button>
<ha-button
size="small"
appearance="plain"
@click=${this._clearCacheAndRetry}
>
Clear cache and retry
</ha-button>
</div>
`
: ""}
`; `;
} }
@@ -64,10 +95,16 @@ class HaInitPage extends LitElement {
if (this._retryInterval) { if (this._retryInterval) {
clearInterval(this._retryInterval); clearInterval(this._retryInterval);
} }
if (this._loadingTimeoutHandle) {
clearTimeout(this._loadingTimeoutHandle);
}
} }
protected willUpdate(changedProperties: PropertyValues<this>) { protected willUpdate(changedProperties: PropertyValues<this>) {
if (changedProperties.has("error") && this.error) { if (
(changedProperties.has("error") && this.error) ||
(changedProperties.has("_loadingTimeout") && this._loadingTimeout)
) {
import("../components/ha-button"); import("../components/ha-button");
} }
} }
@@ -77,12 +114,22 @@ class HaInitPage extends LitElement {
import("../components/ha-spinner"); import("../components/ha-spinner");
}, 5000); }, 5000);
this._retryInterval = window.setInterval(() => { // Only start retry interval for error state
const remainingSeconds = this._retryInSeconds--; if (this.error) {
if (remainingSeconds <= 0) { this._retryInterval = window.setInterval(() => {
this._retry(); const remainingSeconds = this._retryInSeconds--;
} if (remainingSeconds <= 0) {
}, 1000); this._retry();
}
}, 1000);
}
// Start loading timeout for normal loading (not error, not migration)
if (!this.error && !this.migration) {
this._loadingTimeoutHandle = window.setTimeout(() => {
this._loadingTimeout = true;
}, 30000); // 30 seconds
}
} }
private _retry() { private _retry() {
@@ -92,6 +139,25 @@ class HaInitPage extends LitElement {
location.reload(); location.reload();
} }
private async _clearCacheAndRetry() {
// Deregister service worker and clear caches
if ("serviceWorker" in navigator) {
try {
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
await registration.unregister();
}
if ("caches" in window) {
const cacheNames = await caches.keys();
await Promise.all(cacheNames.map((name) => caches.delete(name)));
}
} catch (err: any) {
// Ignore errors, we'll reload anyway
}
}
location.reload();
}
static styles = css` static styles = css`
:host { :host {
flex: 0; flex: 0;
@@ -111,12 +177,23 @@ class HaInitPage extends LitElement {
.retry-text { .retry-text {
margin-top: 0; margin-top: 0;
} }
.hint {
margin-top: 8px;
font-size: 0.9em;
opacity: 0.7;
}
p, p,
#loading-text { #loading-text {
max-width: 350px; max-width: 350px;
color: var(--primary-text-color); color: var(--primary-text-color);
text-align: center; text-align: center;
} }
.button-row {
display: flex;
flex-direction: column;
gap: 8px;
margin-top: 16px;
}
`; `;
} }

View File

@@ -35,7 +35,6 @@ const COMPONENTS = {
light: () => import("../panels/light/ha-panel-light"), light: () => import("../panels/light/ha-panel-light"),
security: () => import("../panels/security/ha-panel-security"), security: () => import("../panels/security/ha-panel-security"),
climate: () => import("../panels/climate/ha-panel-climate"), climate: () => import("../panels/climate/ha-panel-climate"),
home: () => import("../panels/home/ha-panel-home"),
}; };
@customElement("partial-panel-resolver") @customElement("partial-panel-resolver")

View File

@@ -1,56 +1,82 @@
import type { ReactiveElement } from "lit"; import type { ReactiveElement } from "lit";
import { listenMediaQuery } from "../common/dom/media_query";
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
import {
setupMediaQueryListeners,
setupTimeListeners,
} from "../common/condition/listeners";
import type { Condition } from "../panels/lovelace/common/validate-condition"; import type { Condition } from "../panels/lovelace/common/validate-condition";
import { checkConditionsMet } from "../panels/lovelace/common/validate-condition";
type Constructor<T> = abstract new (...args: any[]) => T; type Constructor<T> = abstract new (...args: any[]) => T;
/** /**
* Base config type that can be used with conditional listeners * Extract media queries from conditions recursively
*/ */
export interface ConditionalConfig { export function extractMediaQueries(conditions: Condition[]): string[] {
visibility?: Condition[]; return conditions.reduce<string[]>((array, c) => {
[key: string]: any; if ("conditions" in c && c.conditions) {
array.push(...extractMediaQueries(c.conditions));
}
if (c.condition === "screen" && c.media_query) {
array.push(c.media_query);
}
return array;
}, []);
}
/**
* Helper to setup media query listeners for conditional visibility
*/
export function setupMediaQueryListeners(
conditions: Condition[],
hass: HomeAssistant,
addListener: (unsub: () => void) => void,
onUpdate: (conditionsMet: boolean) => void
): void {
const mediaQueries = extractMediaQueries(conditions);
if (mediaQueries.length === 0) return;
// Optimization for single media query
const hasOnlyMediaQuery =
conditions.length === 1 &&
conditions[0].condition === "screen" &&
!!conditions[0].media_query;
mediaQueries.forEach((mediaQuery) => {
const unsub = listenMediaQuery(mediaQuery, (matches) => {
if (hasOnlyMediaQuery) {
onUpdate(matches);
} else {
const conditionsMet = checkConditionsMet(conditions, hass);
onUpdate(conditionsMet);
}
});
addListener(unsub);
});
} }
/** /**
* Mixin to handle conditional listeners for visibility control * Mixin to handle conditional listeners for visibility control
* *
* Provides lifecycle management for listeners that control conditional * Provides lifecycle management for listeners (media queries, time-based, state changes, etc.)
* visibility of components. * that control conditional visibility of components.
* *
* Usage: * Usage:
* 1. Extend your component with ConditionalListenerMixin<YourConfigType>(ReactiveElement) * 1. Extend your component with ConditionalListenerMixin(ReactiveElement)
* 2. Ensure component has config.visibility or _config.visibility property with conditions * 2. Override setupConditionalListeners() to setup your listeners
* 3. Ensure component has _updateVisibility() or _updateElement() method * 3. Use addConditionalListener() to register unsubscribe functions
* 4. Override setupConditionalListeners() if custom behavior needed (e.g., filter conditions) * 4. Call clearConditionalListeners() and setupConditionalListeners() when config changes
* *
* The mixin automatically: * The mixin automatically:
* - Sets up listeners when component connects to DOM * - Sets up listeners when component connects to DOM
* - Cleans up listeners when component disconnects from DOM * - Cleans up listeners when component disconnects from DOM
* - Handles conditional visibility based on defined conditions
*/ */
export const ConditionalListenerMixin = < export const ConditionalListenerMixin = <
TConfig extends ConditionalConfig = ConditionalConfig, T extends Constructor<ReactiveElement>,
>( >(
superClass: Constructor<ReactiveElement> superClass: T
) => { ) => {
abstract class ConditionalListenerClass extends superClass { abstract class ConditionalListenerClass extends superClass {
private __listeners: (() => void)[] = []; private __listeners: (() => void)[] = [];
protected _config?: TConfig;
public config?: TConfig;
public hass?: HomeAssistant;
protected _updateElement?(config: TConfig): void;
protected _updateVisibility?(conditionsMet?: boolean): void;
public connectedCallback() { public connectedCallback() {
super.connectedCallback(); super.connectedCallback();
this.setupConditionalListeners(); this.setupConditionalListeners();
@@ -61,72 +87,17 @@ export const ConditionalListenerMixin = <
this.clearConditionalListeners(); this.clearConditionalListeners();
} }
/**
* Clear conditional listeners
*
* This method is called when the component is disconnected from the DOM.
* It clears all the listeners that were set up by the setupConditionalListeners() method.
*/
protected clearConditionalListeners(): void { protected clearConditionalListeners(): void {
this.__listeners.forEach((unsub) => unsub()); this.__listeners.forEach((unsub) => unsub());
this.__listeners = []; this.__listeners = [];
} }
/**
* Add a conditional listener to the list of listeners
*
* This method is called when a new listener is added.
* It adds the listener to the list of listeners.
*
* @param unsubscribe - The unsubscribe function to call when the listener is no longer needed
* @returns void
*/
protected addConditionalListener(unsubscribe: () => void): void { protected addConditionalListener(unsubscribe: () => void): void {
this.__listeners.push(unsubscribe); this.__listeners.push(unsubscribe);
} }
/** protected setupConditionalListeners(): void {
* Setup conditional listeners for visibility control // Override in subclass
*
* Default implementation:
* - Checks config.visibility or _config.visibility for conditions (if not provided)
* - Sets up appropriate listeners based on condition types
* - Calls _updateVisibility() or _updateElement() when conditions change
*
* Override this method to customize behavior (e.g., filter conditions first)
* and call super.setupConditionalListeners(customConditions) to reuse the base implementation
*
* @param conditions - Optional conditions array. If not provided, will check config.visibility or _config.visibility
*/
protected setupConditionalListeners(conditions?: Condition[]): void {
const config = this.config || this._config;
const finalConditions = conditions || config?.visibility;
if (!finalConditions || !this.hass) {
return;
}
const onUpdate = (conditionsMet: boolean) => {
if (this._updateVisibility) {
this._updateVisibility(conditionsMet);
} else if (this._updateElement && config) {
this._updateElement(config);
}
};
setupMediaQueryListeners(
finalConditions,
this.hass,
(unsub) => this.addConditionalListener(unsub),
onUpdate
);
setupTimeListeners(
finalConditions,
this.hass,
(unsub) => this.addConditionalListener(unsub),
onUpdate
);
} }
} }
return ConditionalListenerClass; return ConditionalListenerClass;

View File

@@ -104,6 +104,7 @@ export class HaConfigApplicationCredentials extends LitElement {
), ),
sortable: true, sortable: true,
filterable: true, filterable: true,
direction: "asc",
}, },
actions: { actions: {
title: "", title: "",

View File

@@ -588,11 +588,7 @@ export default class HaAutomationActionRow extends LitElement {
...this._clipboard, ...this._clipboard,
action: deepClone(this.action), action: deepClone(this.action),
}; };
let action = this.action; copyToClipboard(dump(this.action));
if ("sequence" in action) {
action = { ...this.action, metadata: {} };
}
copyToClipboard(dump(action));
} }
private _onDisable = () => { private _onDisable = () => {

View File

@@ -14,13 +14,11 @@ import "../../../../components/ha-sortable";
import "../../../../components/ha-svg-icon"; import "../../../../components/ha-svg-icon";
import { import {
ACTION_BUILDING_BLOCKS, ACTION_BUILDING_BLOCKS,
getService,
isService,
VIRTUAL_ACTIONS, VIRTUAL_ACTIONS,
} from "../../../../data/action"; } from "../../../../data/action";
import { import type { AutomationClipboard } from "../../../../data/automation";
getValueFromDynamic,
isDynamic,
type AutomationClipboard,
} from "../../../../data/automation";
import type { Action } from "../../../../data/script"; import type { Action } from "../../../../data/script";
import type { HomeAssistant } from "../../../../types"; import type { HomeAssistant } from "../../../../types";
import { import {
@@ -219,9 +217,9 @@ export default class HaAutomationAction extends LitElement {
actions = this.actions.concat(deepClone(this._clipboard!.action)); actions = this.actions.concat(deepClone(this._clipboard!.action));
} else if (action in VIRTUAL_ACTIONS) { } else if (action in VIRTUAL_ACTIONS) {
actions = this.actions.concat(VIRTUAL_ACTIONS[action]); actions = this.actions.concat(VIRTUAL_ACTIONS[action]);
} else if (isDynamic(action)) { } else if (isService(action)) {
actions = this.actions.concat({ actions = this.actions.concat({
action: getValueFromDynamic(action), action: getService(action),
metadata: {}, metadata: {},
}); });
} else { } else {

View File

@@ -5,7 +5,6 @@ import {
mdiPlus, mdiPlus,
} from "@mdi/js"; } from "@mdi/js";
import Fuse from "fuse.js"; import Fuse from "fuse.js";
import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit"; import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { LitElement, css, html, nothing } from "lit"; import { LitElement, css, html, nothing } from "lit";
import { import {
@@ -41,39 +40,32 @@ import "../../../components/ha-md-list";
import type { HaMdList } from "../../../components/ha-md-list"; import type { HaMdList } from "../../../components/ha-md-list";
import "../../../components/ha-md-list-item"; import "../../../components/ha-md-list-item";
import "../../../components/ha-service-icon"; import "../../../components/ha-service-icon";
import { TRIGGER_ICONS } from "../../../components/ha-trigger-icon";
import "../../../components/ha-wa-dialog"; import "../../../components/ha-wa-dialog";
import "../../../components/search-input"; import "../../../components/search-input";
import { import {
ACTION_BUILDING_BLOCKS_GROUP, ACTION_BUILDING_BLOCKS_GROUP,
ACTION_COLLECTIONS, ACTION_COLLECTIONS,
ACTION_ICONS, ACTION_ICONS,
SERVICE_PREFIX,
getService,
isService,
} from "../../../data/action"; } from "../../../data/action";
import { import type {
DYNAMIC_PREFIX, AutomationElementGroup,
getValueFromDynamic, AutomationElementGroupCollection,
isDynamic,
type AutomationElementGroup,
type AutomationElementGroupCollection,
} from "../../../data/automation"; } from "../../../data/automation";
import { import {
CONDITION_BUILDING_BLOCKS_GROUP, CONDITION_BUILDING_BLOCKS_GROUP,
CONDITION_COLLECTIONS, CONDITION_COLLECTIONS,
CONDITION_ICONS, CONDITION_ICONS,
} from "../../../data/condition"; } from "../../../data/condition";
import { getServiceIcons, getTriggerIcons } from "../../../data/icons"; import { getServiceIcons } from "../../../data/icons";
import type { IntegrationManifest } from "../../../data/integration"; import type { IntegrationManifest } from "../../../data/integration";
import { import {
domainToName, domainToName,
fetchIntegrationManifests, fetchIntegrationManifests,
} from "../../../data/integration"; } from "../../../data/integration";
import type { TriggerDescriptions } from "../../../data/trigger"; import { TRIGGER_COLLECTIONS, TRIGGER_ICONS } from "../../../data/trigger";
import {
TRIGGER_COLLECTIONS,
getTriggerDomain,
getTriggerObjectId,
subscribeTriggers,
} from "../../../data/trigger";
import type { HassDialog } from "../../../dialogs/make-dialog-manager"; import type { HassDialog } from "../../../dialogs/make-dialog-manager";
import { KeyboardShortcutMixin } from "../../../mixins/keyboard-shortcut-mixin"; import { KeyboardShortcutMixin } from "../../../mixins/keyboard-shortcut-mixin";
import { HaFuse } from "../../../resources/fuse"; import { HaFuse } from "../../../resources/fuse";
@@ -119,7 +111,7 @@ const ENTITY_DOMAINS_OTHER = new Set([
const ENTITY_DOMAINS_MAIN = new Set(["notify"]); const ENTITY_DOMAINS_MAIN = new Set(["notify"]);
const ACTION_SERVICE_KEYWORDS = ["dynamicGroups", "helpers", "other"]; const ACTION_SERVICE_KEYWORDS = ["serviceGroups", "helpers", "other"];
@customElement("add-automation-element-dialog") @customElement("add-automation-element-dialog")
class DialogAddAutomationElement class DialogAddAutomationElement
@@ -150,8 +142,6 @@ class DialogAddAutomationElement
@state() private _narrow = false; @state() private _narrow = false;
@state() private _triggerDescriptions: TriggerDescriptions = {};
@query(".items ha-md-list ha-md-list-item") @query(".items ha-md-list ha-md-list-item")
private _itemsListFirstElement?: HaMdList; private _itemsListFirstElement?: HaMdList;
@@ -162,8 +152,6 @@ class DialogAddAutomationElement
private _removeKeyboardShortcuts?: () => void; private _removeKeyboardShortcuts?: () => void;
private _unsub?: Promise<UnsubscribeFunc>;
public showDialog(params): void { public showDialog(params): void {
this._params = params; this._params = params;
@@ -175,17 +163,6 @@ class DialogAddAutomationElement
this._calculateUsedDomains(); this._calculateUsedDomains();
getServiceIcons(this.hass); getServiceIcons(this.hass);
} }
if (this._params?.type === "trigger") {
this.hass.loadBackendTranslation("triggers");
this._fetchManifests();
getTriggerIcons(this.hass);
this._unsub = subscribeTriggers(this.hass, (triggers) => {
this._triggerDescriptions = {
...this._triggerDescriptions,
...triggers,
};
});
}
this._fullScreen = matchMedia( this._fullScreen = matchMedia(
"all and (max-width: 450px), all and (max-height: 500px)" "all and (max-width: 450px), all and (max-height: 500px)"
).matches; ).matches;
@@ -199,10 +176,6 @@ class DialogAddAutomationElement
public closeDialog() { public closeDialog() {
this.removeKeyboardShortcuts(); this.removeKeyboardShortcuts();
if (this._unsub) {
this._unsub.then((unsub) => unsub());
this._unsub = undefined;
}
if (this._params) { if (this._params) {
fireEvent(this, "dialog-closed", { dialog: this.localName }); fireEvent(this, "dialog-closed", { dialog: this.localName });
} }
@@ -344,11 +317,6 @@ class DialogAddAutomationElement
); );
const items = flattenGroups(groups).flat(); const items = flattenGroups(groups).flat();
if (type === "trigger") {
items.push(
...this._triggers(localize, this._triggerDescriptions, manifests)
);
}
if (type === "action") { if (type === "action") {
items.push(...this._services(localize, services, manifests)); items.push(...this._services(localize, services, manifests));
} }
@@ -371,7 +339,6 @@ class DialogAddAutomationElement
domains: Set<string> | undefined, domains: Set<string> | undefined,
localize: LocalizeFunc, localize: LocalizeFunc,
services: HomeAssistant["services"], services: HomeAssistant["services"],
triggerDescriptions: TriggerDescriptions,
manifests?: DomainManifestLookup manifests?: DomainManifestLookup
): { ): {
titleKey?: LocalizeKeys; titleKey?: LocalizeKeys;
@@ -395,32 +362,7 @@ class DialogAddAutomationElement
services, services,
manifests, manifests,
domains, domains,
collection.groups.dynamicGroups collection.groups.serviceGroups
? undefined
: collection.groups.helpers
? "helper"
: "other"
)
);
collectionGroups = collectionGroups.filter(
([key]) => !ACTION_SERVICE_KEYWORDS.includes(key)
);
}
if (
type === "trigger" &&
Object.keys(collection.groups).some((item) =>
ACTION_SERVICE_KEYWORDS.includes(item)
)
) {
groups.push(
...this._triggerGroups(
localize,
triggerDescriptions,
manifests,
domains,
collection.groups.dynamicGroups
? undefined ? undefined
: collection.groups.helpers : collection.groups.helpers
? "helper" ? "helper"
@@ -487,19 +429,10 @@ class DialogAddAutomationElement
services: HomeAssistant["services"], services: HomeAssistant["services"],
manifests?: DomainManifestLookup manifests?: DomainManifestLookup
): ListItem[] => { ): ListItem[] => {
if (type === "action" && isDynamic(group)) { if (type === "action" && isService(group)) {
return this._services(localize, services, manifests, group); return this._services(localize, services, manifests, group);
} }
if (type === "trigger" && isDynamic(group)) {
return this._triggers(
localize,
this._triggerDescriptions,
manifests,
group
);
}
const groups = this._getGroups(type, group, collectionIndex); const groups = this._getGroups(type, group, collectionIndex);
const result = Object.entries(groups).map(([key, options]) => const result = Object.entries(groups).map(([key, options]) =>
@@ -581,7 +514,7 @@ class DialogAddAutomationElement
brand-fallback brand-fallback
></ha-domain-icon> ></ha-domain-icon>
`, `,
key: `${DYNAMIC_PREFIX}${domain}`, key: `${SERVICE_PREFIX}${domain}`,
name: domainToName(localize, domain, manifest), name: domainToName(localize, domain, manifest),
description: "", description: "",
}); });
@@ -592,102 +525,6 @@ class DialogAddAutomationElement
); );
}; };
private _triggerGroups = (
localize: LocalizeFunc,
triggers: TriggerDescriptions,
manifests: DomainManifestLookup | undefined,
domains: Set<string> | undefined,
type: "helper" | "other" | undefined
): ListItem[] => {
if (!triggers || !manifests) {
return [];
}
const result: ListItem[] = [];
const addedDomains = new Set<string>();
Object.keys(triggers).forEach((trigger) => {
const domain = getTriggerDomain(trigger);
if (addedDomains.has(domain)) {
return;
}
addedDomains.add(domain);
const manifest = manifests[domain];
const domainUsed = !domains ? true : domains.has(domain);
if (
(type === undefined &&
(ENTITY_DOMAINS_MAIN.has(domain) ||
(manifest?.integration_type === "entity" &&
domainUsed &&
!ENTITY_DOMAINS_OTHER.has(domain)))) ||
(type === "helper" && manifest?.integration_type === "helper") ||
(type === "other" &&
!ENTITY_DOMAINS_MAIN.has(domain) &&
(ENTITY_DOMAINS_OTHER.has(domain) ||
(!domainUsed && manifest?.integration_type === "entity") ||
!["helper", "entity"].includes(manifest?.integration_type || "")))
) {
result.push({
icon: html`
<ha-domain-icon
.hass=${this.hass}
.domain=${domain}
brand-fallback
></ha-domain-icon>
`,
key: `${DYNAMIC_PREFIX}${domain}`,
name: domainToName(localize, domain, manifest),
description: "",
});
}
});
return result.sort((a, b) =>
stringCompare(a.name, b.name, this.hass.locale.language)
);
};
private _triggers = memoizeOne(
(
localize: LocalizeFunc,
triggers: TriggerDescriptions,
_manifests: DomainManifestLookup | undefined,
group?: string
): ListItem[] => {
if (!triggers) {
return [];
}
const result: ListItem[] = [];
for (const trigger of Object.keys(triggers)) {
const domain = getTriggerDomain(trigger);
const triggerName = getTriggerObjectId(trigger);
if (group && group !== `${DYNAMIC_PREFIX}${domain}`) {
continue;
}
result.push({
icon: html`
<ha-trigger-icon
.hass=${this.hass}
.trigger=${trigger}
></ha-trigger-icon>
`,
key: `${DYNAMIC_PREFIX}${trigger}`,
name:
localize(`component.${domain}.triggers.${triggerName}.name`) ||
trigger,
description:
localize(
`component.${domain}.triggers.${triggerName}.description`
) || trigger,
});
}
return result;
}
);
private _services = memoizeOne( private _services = memoizeOne(
( (
localize: LocalizeFunc, localize: LocalizeFunc,
@@ -702,8 +539,8 @@ class DialogAddAutomationElement
let domain: string | undefined; let domain: string | undefined;
if (isDynamic(group)) { if (isService(group)) {
domain = getValueFromDynamic(group!); domain = getService(group!);
} }
const addDomain = (dmn: string) => { const addDomain = (dmn: string) => {
@@ -717,7 +554,7 @@ class DialogAddAutomationElement
.service=${`${dmn}.${service}`} .service=${`${dmn}.${service}`}
></ha-service-icon> ></ha-service-icon>
`, `,
key: `${DYNAMIC_PREFIX}${dmn}.${service}`, key: `${SERVICE_PREFIX}${dmn}.${service}`,
name: `${domain ? "" : `${domainToName(localize, dmn)}: `}${ name: `${domain ? "" : `${domainToName(localize, dmn)}: `}${
this.hass.localize(`component.${dmn}.services.${service}.name`) || this.hass.localize(`component.${dmn}.services.${service}.name`) ||
services[dmn][service]?.name || services[dmn][service]?.name ||
@@ -831,15 +668,14 @@ class DialogAddAutomationElement
this._domains, this._domains,
this.hass.localize, this.hass.localize,
this.hass.services, this.hass.services,
this._triggerDescriptions,
this._manifests this._manifests
); );
const groupName = isDynamic(this._selectedGroup) const groupName = isService(this._selectedGroup)
? domainToName( ? domainToName(
this.hass.localize, this.hass.localize,
getValueFromDynamic(this._selectedGroup!), getService(this._selectedGroup!),
this._manifests?.[getValueFromDynamic(this._selectedGroup!)] this._manifests?.[getService(this._selectedGroup!)]
) )
: this.hass.localize( : this.hass.localize(
`ui.panel.config.automation.editor.${this._params!.type}s.groups.${this._selectedGroup}.label` as LocalizeKeys `ui.panel.config.automation.editor.${this._params!.type}s.groups.${this._selectedGroup}.label` as LocalizeKeys

View File

@@ -452,10 +452,7 @@ class HaAutomationPicker extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label <ha-label style=${color ? `--color: ${color}` : ""}>
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -28,6 +28,7 @@ import type HaAutomationConditionEditor from "../action/ha-automation-action-edi
import { getAutomationActionType } from "../action/ha-automation-action-row"; import { getAutomationActionType } from "../action/ha-automation-action-row";
import { getRepeatType } from "../action/types/ha-automation-action-repeat"; import { getRepeatType } from "../action/types/ha-automation-action-repeat";
import { overflowStyles, sidebarEditorStyles } from "../styles"; import { overflowStyles, sidebarEditorStyles } from "../styles";
import "../trigger/ha-automation-trigger-editor";
import "./ha-automation-sidebar-card"; import "./ha-automation-sidebar-card";
@customElement("ha-automation-sidebar-action") @customElement("ha-automation-sidebar-action")

View File

@@ -17,6 +17,7 @@ import "../../../../components/ha-dialog-header";
import "../../../../components/ha-icon-button"; import "../../../../components/ha-icon-button";
import "../../../../components/ha-md-button-menu"; import "../../../../components/ha-md-button-menu";
import "../../../../components/ha-md-divider"; import "../../../../components/ha-md-divider";
import "../../../../components/ha-md-menu-item";
import type { HomeAssistant } from "../../../../types"; import type { HomeAssistant } from "../../../../types";
import "../ha-automation-editor-warning"; import "../ha-automation-editor-warning";

View File

@@ -6,9 +6,6 @@ import {
} from "@mdi/js"; } from "@mdi/js";
import { html, LitElement, nothing } from "lit"; import { html, LitElement, nothing } from "lit";
import { customElement, property, query } from "lit/decorators"; import { customElement, property, query } from "lit/decorators";
import "../../../../components/ha-md-divider";
import "../../../../components/ha-md-menu-item";
import "../../../../components/ha-svg-icon";
import type { OptionSidebarConfig } from "../../../../data/automation"; import type { OptionSidebarConfig } from "../../../../data/automation";
import type { HomeAssistant } from "../../../../types"; import type { HomeAssistant } from "../../../../types";
import { isMac } from "../../../../util/is_mac"; import { isMac } from "../../../../util/is_mac";

View File

@@ -15,15 +15,8 @@ import { customElement, property, query, state } from "lit/decorators";
import { keyed } from "lit/directives/keyed"; import { keyed } from "lit/directives/keyed";
import { fireEvent } from "../../../../common/dom/fire_event"; import { fireEvent } from "../../../../common/dom/fire_event";
import { handleStructError } from "../../../../common/structs/handle-errors"; import { handleStructError } from "../../../../common/structs/handle-errors";
import type { import type { TriggerSidebarConfig } from "../../../../data/automation";
LegacyTrigger, import { isTriggerList } from "../../../../data/trigger";
TriggerSidebarConfig,
} from "../../../../data/automation";
import {
getTriggerDomain,
getTriggerObjectId,
isTriggerList,
} from "../../../../data/trigger";
import type { HomeAssistant } from "../../../../types"; import type { HomeAssistant } from "../../../../types";
import { isMac } from "../../../../util/is_mac"; import { isMac } from "../../../../util/is_mac";
import { overflowStyles, sidebarEditorStyles } from "../styles"; import { overflowStyles, sidebarEditorStyles } from "../styles";
@@ -70,7 +63,8 @@ export default class HaAutomationSidebarTrigger extends LitElement {
protected render() { protected render() {
const rowDisabled = const rowDisabled =
"enabled" in this.config.config && this.config.config.enabled === false; this.disabled ||
("enabled" in this.config.config && this.config.config.enabled === false);
const type = isTriggerList(this.config.config) const type = isTriggerList(this.config.config)
? "list" ? "list"
: this.config.config.trigger; : this.config.config.trigger;
@@ -79,18 +73,9 @@ export default class HaAutomationSidebarTrigger extends LitElement {
"ui.panel.config.automation.editor.triggers.trigger" "ui.panel.config.automation.editor.triggers.trigger"
); );
const domain = const title = this.hass.localize(
"trigger" in this.config.config && `ui.panel.config.automation.editor.triggers.type.${type}.label`
getTriggerDomain(this.config.config.trigger); );
const triggerName =
"trigger" in this.config.config &&
getTriggerObjectId(this.config.config.trigger);
const title =
this.hass.localize(
`ui.panel.config.automation.editor.triggers.type.${type as LegacyTrigger["trigger"]}.label`
) ||
this.hass.localize(`component.${domain}.triggers.${triggerName}.name`);
return html` return html`
<ha-automation-sidebar-card <ha-automation-sidebar-card
@@ -284,7 +269,6 @@ export default class HaAutomationSidebarTrigger extends LitElement {
class="sidebar-editor" class="sidebar-editor"
.hass=${this.hass} .hass=${this.hass}
.trigger=${this.config.config} .trigger=${this.config.config}
.description=${this.config.description}
@value-changed=${this._valueChangedSidebar} @value-changed=${this._valueChangedSidebar}
@yaml-changed=${this._yamlChangedSidebar} @yaml-changed=${this._yamlChangedSidebar}
.uiSupported=${this.config.uiSupported} .uiSupported=${this.config.uiSupported}

View File

@@ -9,12 +9,10 @@ import "../../../../components/ha-yaml-editor";
import type { HaYamlEditor } from "../../../../components/ha-yaml-editor"; import type { HaYamlEditor } from "../../../../components/ha-yaml-editor";
import type { Trigger } from "../../../../data/automation"; import type { Trigger } from "../../../../data/automation";
import { migrateAutomationTrigger } from "../../../../data/automation"; import { migrateAutomationTrigger } from "../../../../data/automation";
import type { TriggerDescription } from "../../../../data/trigger";
import { isTriggerList } from "../../../../data/trigger"; import { isTriggerList } from "../../../../data/trigger";
import { haStyle } from "../../../../resources/styles"; import { haStyle } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types"; import type { HomeAssistant } from "../../../../types";
import "../ha-automation-editor-warning"; import "../ha-automation-editor-warning";
import "./types/ha-automation-trigger-platform";
@customElement("ha-automation-trigger-editor") @customElement("ha-automation-trigger-editor")
export default class HaAutomationTriggerEditor extends LitElement { export default class HaAutomationTriggerEditor extends LitElement {
@@ -33,8 +31,6 @@ export default class HaAutomationTriggerEditor extends LitElement {
@property({ type: Boolean, attribute: "show-id" }) public showId = false; @property({ type: Boolean, attribute: "show-id" }) public showId = false;
@property({ attribute: false }) public description?: TriggerDescription;
@query("ha-yaml-editor") public yamlEditor?: HaYamlEditor; @query("ha-yaml-editor") public yamlEditor?: HaYamlEditor;
protected render() { protected render() {
@@ -91,18 +87,11 @@ export default class HaAutomationTriggerEditor extends LitElement {
` `
: nothing} : nothing}
<div @value-changed=${this._onUiChanged}> <div @value-changed=${this._onUiChanged}>
${this.description ${dynamicElement(`ha-automation-trigger-${type}`, {
? html`<ha-automation-trigger-platform hass: this.hass,
.hass=${this.hass} trigger: this.trigger,
.trigger=${this.trigger} disabled: this.disabled,
.description=${this.description} })}
.disabled=${this.disabled}
></ha-automation-trigger-platform>`
: dynamicElement(`ha-automation-trigger-${type}`, {
hass: this.hass,
trigger: this.trigger,
disabled: this.disabled,
})}
</div> </div>
`} `}
</div> </div>

View File

@@ -40,11 +40,9 @@ import "../../../../components/ha-md-button-menu";
import "../../../../components/ha-md-divider"; import "../../../../components/ha-md-divider";
import "../../../../components/ha-md-menu-item"; import "../../../../components/ha-md-menu-item";
import "../../../../components/ha-svg-icon"; import "../../../../components/ha-svg-icon";
import { TRIGGER_ICONS } from "../../../../components/ha-trigger-icon";
import type { import type {
AutomationClipboard, AutomationClipboard,
Trigger, Trigger,
TriggerList,
TriggerSidebarConfig, TriggerSidebarConfig,
} from "../../../../data/automation"; } from "../../../../data/automation";
import { isTrigger, subscribeTrigger } from "../../../../data/automation"; import { isTrigger, subscribeTrigger } from "../../../../data/automation";
@@ -52,8 +50,7 @@ import { describeTrigger } from "../../../../data/automation_i18n";
import { validateConfig } from "../../../../data/config"; import { validateConfig } from "../../../../data/config";
import { fullEntitiesContext } from "../../../../data/context"; import { fullEntitiesContext } from "../../../../data/context";
import type { EntityRegistryEntry } from "../../../../data/entity_registry"; import type { EntityRegistryEntry } from "../../../../data/entity_registry";
import type { TriggerDescriptions } from "../../../../data/trigger"; import { TRIGGER_ICONS, isTriggerList } from "../../../../data/trigger";
import { isTriggerList } from "../../../../data/trigger";
import { import {
showAlertDialog, showAlertDialog,
showPromptDialog, showPromptDialog,
@@ -75,7 +72,6 @@ import "./types/ha-automation-trigger-list";
import "./types/ha-automation-trigger-mqtt"; import "./types/ha-automation-trigger-mqtt";
import "./types/ha-automation-trigger-numeric_state"; import "./types/ha-automation-trigger-numeric_state";
import "./types/ha-automation-trigger-persistent_notification"; import "./types/ha-automation-trigger-persistent_notification";
import "./types/ha-automation-trigger-platform";
import "./types/ha-automation-trigger-state"; import "./types/ha-automation-trigger-state";
import "./types/ha-automation-trigger-sun"; import "./types/ha-automation-trigger-sun";
import "./types/ha-automation-trigger-tag"; import "./types/ha-automation-trigger-tag";
@@ -141,9 +137,6 @@ export default class HaAutomationTriggerRow extends LitElement {
@state() private _warnings?: string[]; @state() private _warnings?: string[];
@property({ attribute: false })
public triggerDescriptions: TriggerDescriptions = {};
@property({ type: Boolean }) public narrow = false; @property({ type: Boolean }) public narrow = false;
@query("ha-automation-trigger-editor") @query("ha-automation-trigger-editor")
@@ -185,24 +178,18 @@ export default class HaAutomationTriggerRow extends LitElement {
} }
private _renderRow() { private _renderRow() {
const type = this._getType(this.trigger, this.triggerDescriptions); const type = this._getType(this.trigger);
const supported = this._uiSupported(type); const supported = this._uiSupported(type);
const yamlMode = this._yamlMode || !supported; const yamlMode = this._yamlMode || !supported;
return html` return html`
${type === "list" <ha-svg-icon
? html`<ha-svg-icon slot="leading-icon"
slot="leading-icon" class="trigger-icon"
class="trigger-icon" .path=${TRIGGER_ICONS[type]}
.path=${TRIGGER_ICONS[type]} ></ha-svg-icon>
></ha-svg-icon>`
: html`<ha-trigger-icon
slot="leading-icon"
.hass=${this.hass}
.trigger=${(this.trigger as Exclude<Trigger, TriggerList>).trigger}
></ha-trigger-icon>`}
<h3 slot="header"> <h3 slot="header">
${describeTrigger(this.trigger, this.hass, this._entityReg)} ${describeTrigger(this.trigger, this.hass, this._entityReg)}
</h3> </h3>
@@ -406,9 +393,6 @@ export default class HaAutomationTriggerRow extends LitElement {
<ha-automation-trigger-editor <ha-automation-trigger-editor
.hass=${this.hass} .hass=${this.hass}
.trigger=${this.trigger} .trigger=${this.trigger}
.description=${"trigger" in this.trigger
? this.triggerDescriptions[this.trigger.trigger]
: undefined}
.disabled=${this.disabled} .disabled=${this.disabled}
.yamlMode=${this._yamlMode} .yamlMode=${this._yamlMode}
.uiSupported=${supported} .uiSupported=${supported}
@@ -568,7 +552,6 @@ export default class HaAutomationTriggerRow extends LitElement {
} }
public openSidebar(trigger?: Trigger): void { public openSidebar(trigger?: Trigger): void {
trigger = trigger || this.trigger;
fireEvent(this, "open-sidebar", { fireEvent(this, "open-sidebar", {
save: (value) => { save: (value) => {
fireEvent(this, "value-changed", { value }); fireEvent(this, "value-changed", { value });
@@ -593,14 +576,8 @@ export default class HaAutomationTriggerRow extends LitElement {
duplicate: this._duplicateTrigger, duplicate: this._duplicateTrigger,
cut: this._cutTrigger, cut: this._cutTrigger,
insertAfter: this._insertAfter, insertAfter: this._insertAfter,
config: trigger, config: trigger || this.trigger,
uiSupported: this._uiSupported( uiSupported: this._uiSupported(this._getType(trigger || this.trigger)),
this._getType(trigger, this.triggerDescriptions)
),
description:
"trigger" in trigger
? this.triggerDescriptions[trigger.trigger]
: undefined,
yamlMode: this._yamlMode, yamlMode: this._yamlMode,
} satisfies TriggerSidebarConfig); } satisfies TriggerSidebarConfig);
this._selected = true; this._selected = true;
@@ -782,18 +759,8 @@ export default class HaAutomationTriggerRow extends LitElement {
}); });
} }
private _getType = memoizeOne( private _getType = memoizeOne((trigger: Trigger) =>
(trigger: Trigger, triggerDescriptions: TriggerDescriptions) => { isTriggerList(trigger) ? "list" : trigger.trigger
if (isTriggerList(trigger)) {
return "list";
}
if (trigger.trigger in triggerDescriptions) {
return "platform";
}
return trigger.trigger;
}
); );
private _uiSupported = memoizeOne( private _uiSupported = memoizeOne(

View File

@@ -4,7 +4,6 @@ import type { PropertyValues } from "lit";
import { html, LitElement, nothing } from "lit"; import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import { repeat } from "lit/directives/repeat"; import { repeat } from "lit/directives/repeat";
import { ensureArray } from "../../../../common/array/ensure-array";
import { storage } from "../../../../common/decorators/storage"; import { storage } from "../../../../common/decorators/storage";
import { fireEvent } from "../../../../common/dom/fire_event"; import { fireEvent } from "../../../../common/dom/fire_event";
import { stopPropagation } from "../../../../common/dom/stop_propagation"; import { stopPropagation } from "../../../../common/dom/stop_propagation";
@@ -13,16 +12,12 @@ import "../../../../components/ha-button";
import "../../../../components/ha-button-menu"; import "../../../../components/ha-button-menu";
import "../../../../components/ha-sortable"; import "../../../../components/ha-sortable";
import "../../../../components/ha-svg-icon"; import "../../../../components/ha-svg-icon";
import { import type {
getValueFromDynamic, AutomationClipboard,
isDynamic, Trigger,
type AutomationClipboard, TriggerList,
type Trigger,
type TriggerList,
} from "../../../../data/automation"; } from "../../../../data/automation";
import type { TriggerDescriptions } from "../../../../data/trigger"; import { isTriggerList } from "../../../../data/trigger";
import { isTriggerList, subscribeTriggers } from "../../../../data/trigger";
import { SubscribeMixin } from "../../../../mixins/subscribe-mixin";
import type { HomeAssistant } from "../../../../types"; import type { HomeAssistant } from "../../../../types";
import { import {
PASTE_VALUE, PASTE_VALUE,
@@ -31,9 +26,10 @@ import {
import { automationRowsStyles } from "../styles"; import { automationRowsStyles } from "../styles";
import "./ha-automation-trigger-row"; import "./ha-automation-trigger-row";
import type HaAutomationTriggerRow from "./ha-automation-trigger-row"; import type HaAutomationTriggerRow from "./ha-automation-trigger-row";
import { ensureArray } from "../../../../common/array/ensure-array";
@customElement("ha-automation-trigger") @customElement("ha-automation-trigger")
export default class HaAutomationTrigger extends SubscribeMixin(LitElement) { export default class HaAutomationTrigger extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant; @property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public triggers!: Trigger[]; @property({ attribute: false }) public triggers!: Trigger[];
@@ -66,23 +62,6 @@ export default class HaAutomationTrigger extends SubscribeMixin(LitElement) {
private _triggerKeys = new WeakMap<Trigger, string>(); private _triggerKeys = new WeakMap<Trigger, string>();
@state() private _triggerDescriptions: TriggerDescriptions = {};
protected hassSubscribe() {
return [
subscribeTriggers(this.hass, (triggers) => this._addTriggers(triggers)),
];
}
private _addTriggers(triggers: TriggerDescriptions) {
this._triggerDescriptions = { ...this._triggerDescriptions, ...triggers };
}
protected firstUpdated(changedProps: PropertyValues) {
super.firstUpdated(changedProps);
this.hass.loadBackendTranslation("triggers");
}
protected render() { protected render() {
return html` return html`
<ha-sortable <ha-sortable
@@ -106,7 +85,6 @@ export default class HaAutomationTrigger extends SubscribeMixin(LitElement) {
.first=${idx === 0} .first=${idx === 0}
.last=${idx === this.triggers.length - 1} .last=${idx === this.triggers.length - 1}
.trigger=${trg} .trigger=${trg}
.triggerDescriptions=${this._triggerDescriptions}
@duplicate=${this._duplicateTrigger} @duplicate=${this._duplicateTrigger}
@insert-after=${this._insertAfter} @insert-after=${this._insertAfter}
@move-down=${this._moveDown} @move-down=${this._moveDown}
@@ -178,10 +156,6 @@ export default class HaAutomationTrigger extends SubscribeMixin(LitElement) {
let triggers: Trigger[]; let triggers: Trigger[];
if (value === PASTE_VALUE) { if (value === PASTE_VALUE) {
triggers = this.triggers.concat(deepClone(this._clipboard!.trigger)); triggers = this.triggers.concat(deepClone(this._clipboard!.trigger));
} else if (isDynamic(value)) {
triggers = this.triggers.concat({
trigger: getValueFromDynamic(value),
});
} else { } else {
const trigger = value as Exclude<Trigger, TriggerList>["trigger"]; const trigger = value as Exclude<Trigger, TriggerList>["trigger"];
const elClass = customElements.get( const elClass = customElements.get(

View File

@@ -1,416 +0,0 @@
import { mdiHelpCircle } from "@mdi/js";
import type { PropertyValues } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { fireEvent } from "../../../../../common/dom/fire_event";
import { computeDomain } from "../../../../../common/entity/compute_domain";
import "../../../../../components/ha-checkbox";
import "../../../../../components/ha-selector/ha-selector";
import "../../../../../components/ha-settings-row";
import type { PlatformTrigger } from "../../../../../data/automation";
import type { IntegrationManifest } from "../../../../../data/integration";
import { fetchIntegrationManifest } from "../../../../../data/integration";
import type { TargetSelector } from "../../../../../data/selector";
import {
getTriggerDomain,
getTriggerObjectId,
type TriggerDescription,
} from "../../../../../data/trigger";
import type { HomeAssistant } from "../../../../../types";
import { documentationUrl } from "../../../../../util/documentation-url";
const showOptionalToggle = (field: TriggerDescription["fields"][string]) =>
field.selector &&
!field.required &&
!("boolean" in field.selector && field.default);
@customElement("ha-automation-trigger-platform")
export class HaPlatformTrigger extends LitElement {
@property({ attribute: false }) public hass!: HomeAssistant;
@property({ attribute: false }) public trigger!: PlatformTrigger;
@property({ attribute: false }) public description?: TriggerDescription;
@property({ type: Boolean }) public disabled = false;
@state() private _checkedKeys = new Set();
@state() private _manifest?: IntegrationManifest;
public static get defaultConfig(): PlatformTrigger {
return { trigger: "" };
}
protected willUpdate(changedProperties: PropertyValues<this>) {
super.willUpdate(changedProperties);
if (!this.hasUpdated) {
this.hass.loadBackendTranslation("triggers");
this.hass.loadBackendTranslation("selector");
}
if (!changedProperties.has("trigger")) {
return;
}
const oldValue = changedProperties.get("trigger") as
| undefined
| this["trigger"];
// Fetch the manifest if we have a trigger selected and the trigger domain changed.
// If no trigger is selected, clear the manifest.
if (this.trigger?.trigger) {
const domain = getTriggerDomain(this.trigger.trigger);
const oldDomain = getTriggerDomain(oldValue?.trigger || "");
if (domain !== oldDomain) {
this._fetchManifest(domain);
}
} else {
this._manifest = undefined;
}
}
protected render() {
const domain = getTriggerDomain(this.trigger.trigger);
const triggerName = getTriggerObjectId(this.trigger.trigger);
const description = this.hass.localize(
`component.${domain}.triggers.${triggerName}.description`
);
const triggerDesc = this.description;
const shouldRenderDataYaml = !triggerDesc?.fields;
const hasOptional = Boolean(
triggerDesc?.fields &&
Object.values(triggerDesc.fields).some((field) =>
showOptionalToggle(field)
)
);
return html`
<div class="description">
${description ? html`<p>${description}</p>` : nothing}
${this._manifest
? html`<a
href=${this._manifest.is_built_in
? documentationUrl(
this.hass,
`/integrations/${this._manifest.domain}`
)
: this._manifest.documentation}
title=${this.hass.localize(
"ui.components.service-control.integration_doc"
)}
target="_blank"
rel="noreferrer"
>
<ha-icon-button
.path=${mdiHelpCircle}
class="help-icon"
></ha-icon-button>
</a>`
: nothing}
</div>
${triggerDesc && "target" in triggerDesc
? html`<ha-settings-row narrow>
${hasOptional
? html`<div slot="prefix" class="checkbox-spacer"></div>`
: nothing}
<span slot="heading"
>${this.hass.localize(
"ui.components.service-control.target"
)}</span
>
<span slot="description"
>${this.hass.localize(
"ui.components.service-control.target_secondary"
)}</span
><ha-selector
.hass=${this.hass}
.selector=${this._targetSelector(triggerDesc.target)}
.disabled=${this.disabled}
@value-changed=${this._targetChanged}
.value=${this.trigger?.target}
></ha-selector
></ha-settings-row>`
: nothing}
${shouldRenderDataYaml
? html`<ha-yaml-editor
.hass=${this.hass}
.label=${this.hass.localize(
"ui.components.service-control.action_data"
)}
.name=${"data"}
.readOnly=${this.disabled}
.defaultValue=${this.trigger?.options}
@value-changed=${this._dataChanged}
></ha-yaml-editor>`
: Object.entries(triggerDesc.fields).map(([fieldName, dataField]) =>
this._renderField(
fieldName,
dataField,
hasOptional,
domain,
triggerName
)
)}
`;
}
private _targetSelector = memoizeOne(
(targetSelector: TargetSelector["target"] | null | undefined) =>
targetSelector ? { target: { ...targetSelector } } : { target: {} }
);
private _renderField = (
fieldName: string,
dataField: TriggerDescription["fields"][string],
hasOptional: boolean,
domain: string | undefined,
triggerName: string | undefined
) => {
const selector = dataField?.selector ?? { text: null };
const showOptional = showOptionalToggle(dataField);
return dataField.selector
? html`<ha-settings-row narrow>
${!showOptional
? hasOptional
? html`<div slot="prefix" class="checkbox-spacer"></div>`
: nothing
: html`<ha-checkbox
.key=${fieldName}
.checked=${this._checkedKeys.has(fieldName) ||
(this.trigger?.options &&
this.trigger.options[fieldName] !== undefined)}
.disabled=${this.disabled}
@change=${this._checkboxChanged}
slot="prefix"
></ha-checkbox>`}
<span slot="heading"
>${this.hass.localize(
`component.${domain}.triggers.${triggerName}.fields.${fieldName}.name`
) || triggerName}</span
>
<span slot="description"
>${this.hass.localize(
`component.${domain}.triggers.${triggerName}.fields.${fieldName}.description`
)}</span
>
<ha-selector
.disabled=${this.disabled ||
(showOptional &&
!this._checkedKeys.has(fieldName) &&
(!this.trigger?.options ||
this.trigger.options[fieldName] === undefined))}
.hass=${this.hass}
.selector=${selector}
.context=${this._generateContext(dataField)}
.key=${fieldName}
@value-changed=${this._dataChanged}
.value=${this.trigger?.options
? this.trigger.options[fieldName]
: undefined}
.placeholder=${dataField.default}
.localizeValue=${this._localizeValueCallback}
></ha-selector>
</ha-settings-row>`
: nothing;
};
private _generateContext(
field: TriggerDescription["fields"][string]
): Record<string, any> | undefined {
if (!field.context) {
return undefined;
}
const context = {};
for (const [context_key, data_key] of Object.entries(field.context)) {
context[context_key] =
data_key === "target"
? this.trigger.target
: this.trigger.options?.[data_key];
}
return context;
}
private _dataChanged(ev: CustomEvent) {
ev.stopPropagation();
if (ev.detail.isValid === false) {
// Don't clear an object selector that returns invalid YAML
return;
}
const key = (ev.currentTarget as any).key;
const value = ev.detail.value;
if (
this.trigger?.options?.[key] === value ||
((!this.trigger?.options || !(key in this.trigger.options)) &&
(value === "" || value === undefined))
) {
return;
}
const options = { ...this.trigger?.options, [key]: value };
if (
value === "" ||
value === undefined ||
(typeof value === "object" && !Object.keys(value).length)
) {
delete options[key];
}
fireEvent(this, "value-changed", {
value: {
...this.trigger,
options,
},
});
}
private _targetChanged(ev: CustomEvent): void {
ev.stopPropagation();
fireEvent(this, "value-changed", {
value: {
...this.trigger,
target: ev.detail.value,
},
});
}
private _checkboxChanged(ev) {
const checked = ev.currentTarget.checked;
const key = ev.currentTarget.key;
let options;
if (checked) {
this._checkedKeys.add(key);
const field =
this.description &&
Object.entries(this.description).find(([k, _value]) => k === key)?.[1];
let defaultValue = field?.default;
if (
defaultValue == null &&
field?.selector &&
"constant" in field.selector
) {
defaultValue = field.selector.constant?.value;
}
if (
defaultValue == null &&
field?.selector &&
"boolean" in field.selector
) {
defaultValue = false;
}
if (defaultValue != null) {
options = {
...this.trigger?.options,
[key]: defaultValue,
};
}
} else {
this._checkedKeys.delete(key);
options = { ...this.trigger?.options };
delete options[key];
}
if (options) {
fireEvent(this, "value-changed", {
value: {
...this.trigger,
options,
},
});
}
this.requestUpdate("_checkedKeys");
}
private _localizeValueCallback = (key: string) => {
if (!this.trigger?.trigger) {
return "";
}
return this.hass.localize(
`component.${computeDomain(this.trigger.trigger)}.selector.${key}`
);
};
private async _fetchManifest(integration: string) {
this._manifest = undefined;
try {
this._manifest = await fetchIntegrationManifest(this.hass, integration);
} catch (_err: any) {
// eslint-disable-next-line no-console
console.log(`Unable to fetch integration manifest for ${integration}`);
// Ignore if loading manifest fails. Probably bad JSON in manifest
}
}
static styles = css`
ha-settings-row {
padding: 0 var(--ha-space-4);
}
ha-settings-row[narrow] {
padding-bottom: var(--ha-space-2);
}
ha-settings-row {
--settings-row-content-width: 100%;
--settings-row-prefix-display: contents;
border-top: var(
--service-control-items-border-top,
1px solid var(--divider-color)
);
}
ha-service-picker,
ha-entity-picker,
ha-yaml-editor {
display: block;
margin: 0 var(--ha-space-4);
}
ha-yaml-editor {
padding: var(--ha-space-4) 0;
}
p {
margin: 0 var(--ha-space-4);
padding: var(--ha-space-4) 0;
}
:host([hide-picker]) p {
padding-top: 0;
}
.checkbox-spacer {
width: 32px;
}
ha-checkbox {
margin-left: calc(var(--ha-space-4) * -1);
margin-inline-start: calc(var(--ha-space-4) * -1);
margin-inline-end: initial;
}
.help-icon {
color: var(--secondary-text-color);
}
.description {
justify-content: space-between;
display: flex;
align-items: center;
padding-right: 2px;
padding-inline-end: 2px;
padding-inline-start: initial;
}
.description p {
direction: ltr;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-automation-trigger-platform": HaPlatformTrigger;
}
}

View File

@@ -372,14 +372,16 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
clickable clickable
id="backup_id" id="backup_id"
has-filters has-filters
.filters=${Object.values(this._filters).filter((filter) => .filters=${
Array.isArray(filter) Object.values(this._filters).filter((filter) =>
? filter.length Array.isArray(filter)
: filter && ? filter.length
Object.values(filter).some((val) => : filter &&
Array.isArray(val) ? val.length : val Object.values(filter).some((val) =>
) Array.isArray(val) ? val.length : val
).length} )
).length
}
selectable selectable
.selected=${this._selected.length} .selected=${this._selected.length}
.initialGroupColumn=${this._activeGrouping} .initialGroupColumn=${this._activeGrouping}
@@ -421,28 +423,30 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
</div> </div>
<div slot="selection-bar"> <div slot="selection-bar">
${!this.narrow ${
? html` !this.narrow
<ha-button ? html`
appearance="plain" <ha-button
@click=${this._deleteSelected} appearance="plain"
variant="danger" @click=${this._deleteSelected}
> variant="danger"
${this.hass.localize( >
"ui.panel.config.backup.backups.delete_selected" ${this.hass.localize(
)} "ui.panel.config.backup.backups.delete_selected"
</ha-button> )}
` </ha-button>
: html` `
<ha-icon-button : html`
.label=${this.hass.localize( <ha-icon-button
"ui.panel.config.backup.backups.delete_selected" .label=${this.hass.localize(
)} "ui.panel.config.backup.backups.delete_selected"
.path=${mdiDelete} )}
class="warning" .path=${mdiDelete}
@click=${this._deleteSelected} class="warning"
></ha-icon-button> @click=${this._deleteSelected}
`} ></ha-icon-button>
`
}
</div> </div>
<ha-filter-states <ha-filter-states
@@ -455,39 +459,43 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
expanded expanded
.narrow=${this.narrow} .narrow=${this.narrow}
></ha-filter-states> ></ha-filter-states>
${!this._needsOnboarding ${
? html` !this._needsOnboarding
<ha-fab ? html`
slot="fab" <ha-fab
?disabled=${backupInProgress} slot="fab"
.label=${this.hass.localize( ?disabled=${backupInProgress}
"ui.panel.config.backup.backups.new_backup" .label=${this.hass.localize(
)} "ui.panel.config.backup.backups.new_backup"
extended )}
@click=${this._newBackup} extended
> @click=${this._newBackup}
${backupInProgress >
? html`<div slot="icon" class="loading"> ${backupInProgress
<ha-spinner .size=${"small"}></ha-spinner> ? html`<div slot="icon" class="loading">
</div>` <ha-spinner .size=${"small"}></ha-spinner>
: html`<ha-svg-icon </div>`
slot="icon" : html`<ha-svg-icon
.path=${mdiPlus} slot="icon"
></ha-svg-icon>`} .path=${mdiPlus}
</ha-fab> ></ha-svg-icon>`}
` </ha-fab>
: nothing} `
: nothing
}
</hass-tabs-subpage-data-table> </hass-tabs-subpage-data-table>
<ha-md-menu id="overflow-menu" positioning="fixed"> <ha-md-menu id="overflow-menu" positioning="fixed">
<ha-md-menu-item .clickAction=${this._downloadBackup}> <ha-md-menu-item .clickAction=${this._downloadBackup}>
<ha-svg-icon slot="start" .path=${mdiDownload}></ha-svg-icon> <ha-svg-icon slot="start" .path=${mdiDownload}></ha-svg-icon>
${this.hass.localize("ui.common.download")} ${this.hass.localize("ui.common.download")}
</ha-md-menu-item> </ha-md-menu-item>
<ha-md-menu-item class="warning" .clickAction=${this._deleteBackup}> <ha-md-menu-item class="warning" .clickAction=${this._deleteBackup}>
<ha-svg-icon slot="start" .path=${mdiDelete}></ha-svg-icon> <ha-svg-icon slot="start" .path=${mdiDelete}></ha-svg-icon>
${this.hass.localize("ui.common.delete")} ${this.hass.localize("ui.common.delete")}
</ha-md-menu-item> </ha-md-menu-item>
</ha-md-menu> </ha-md-menu>
>
</ha-icon-overflow-menu>
`; `;
} }
@@ -561,15 +569,15 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
navigate(`/config/backup/details/${id}`); navigate(`/config/backup/details/${id}`);
} }
private _downloadBackup = async (ev): Promise<void> => { private async _downloadBackup(ev): Promise<void> {
const backup = ev.parentElement.anchorElement.backup; const backup = ev.parentElement.anchorElement.backup;
if (!backup) { if (!backup) {
return; return;
} }
downloadBackup(this.hass, this, backup, this.config); downloadBackup(this.hass, this, backup, this.config);
}; }
private _deleteBackup = async (ev): Promise<void> => { private async _deleteBackup(ev): Promise<void> {
const backup = ev.parentElement.anchorElement.backup; const backup = ev.parentElement.anchorElement.backup;
if (!backup) { if (!backup) {
return; return;
@@ -601,7 +609,7 @@ class HaConfigBackupBackups extends SubscribeMixin(LitElement) {
return; return;
} }
fireEvent(this, "ha-refresh-backup-info"); fireEvent(this, "ha-refresh-backup-info");
}; }
private async _deleteSelected() { private async _deleteSelected() {
const confirm = await showConfirmationDialog(this, { const confirm = await showConfirmationDialog(this, {

View File

@@ -182,11 +182,13 @@ class HaBlueprintOverview extends LitElement {
sortable: true, sortable: true,
filterable: true, filterable: true,
groupable: true, groupable: true,
direction: "asc",
}, },
path: { path: {
title: localize("ui.panel.config.blueprint.overview.headers.file_name"), title: localize("ui.panel.config.blueprint.overview.headers.file_name"),
sortable: true, sortable: true,
filterable: true, filterable: true,
direction: "asc",
flex: 2, flex: 2,
}, },
fullpath: { fullpath: {

View File

@@ -1,4 +1,4 @@
import { mdiPlus, mdiTag } from "@mdi/js"; import { mdiTag, mdiPlus } from "@mdi/js";
import type { UnsubscribeFunc } from "home-assistant-js-websocket"; import type { UnsubscribeFunc } from "home-assistant-js-websocket";
import type { TemplateResult } from "lit"; import type { TemplateResult } from "lit";
import { html, LitElement } from "lit"; import { html, LitElement } from "lit";
@@ -194,9 +194,8 @@ export class HaCategoryPicker extends SubscribeMixin(LitElement) {
.hass=${this.hass} .hass=${this.hass}
.autofocus=${this.autofocus} .autofocus=${this.autofocus}
.label=${this.label} .label=${this.label}
.notFoundLabel=${this._notFoundLabel} .notFoundLabel=${this.hass.localize(
.emptyLabel=${this.hass.localize( "ui.components.category-picker.no_match"
"ui.components.category-picker.no_categories"
)} )}
.placeholder=${placeholder} .placeholder=${placeholder}
.value=${this.value} .value=${this.value}
@@ -255,11 +254,6 @@ export class HaCategoryPicker extends SubscribeMixin(LitElement) {
fireEvent(this, "change"); fireEvent(this, "change");
}, 0); }, 0);
} }
private _notFoundLabel = (search: string) =>
this.hass.localize("ui.components.category-picker.no_match", {
term: html`<b>${search}</b>`,
});
} }
declare global { declare global {

View File

@@ -1,5 +1,6 @@
import { mdiOpenInNew } from "@mdi/js";
import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit"; import type { CSSResultGroup, PropertyValues, TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import { isComponentLoaded } from "../../../common/config/is_component_loaded"; import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import "../../../components/ha-analytics"; import "../../../components/ha-analytics";
@@ -16,8 +17,6 @@ import {
import { haStyle } from "../../../resources/styles"; import { haStyle } from "../../../resources/styles";
import type { HomeAssistant } from "../../../types"; import type { HomeAssistant } from "../../../types";
import { documentationUrl } from "../../../util/documentation-url"; import { documentationUrl } from "../../../util/documentation-url";
import { isDevVersion } from "../../../common/config/version";
import type { HaSwitch } from "../../../components/ha-switch";
@customElement("ha-config-analytics") @customElement("ha-config-analytics")
class ConfigAnalytics extends LitElement { class ConfigAnalytics extends LitElement {
@@ -35,22 +34,10 @@ class ConfigAnalytics extends LitElement {
: undefined; : undefined;
return html` return html`
<ha-card <ha-card outlined>
outlined
.header=${this.hass.localize("ui.panel.config.analytics.header") ||
"Home Assistant analytics"}
>
<div class="card-content"> <div class="card-content">
${error ? html`<div class="error">${error}</div>` : nothing} ${error ? html`<div class="error">${error}</div>` : ""}
<p> <p>${this.hass.localize("ui.panel.config.analytics.intro")}</p>
${this.hass.localize("ui.panel.config.analytics.intro")}
<a
href=${documentationUrl(this.hass, "/integrations/analytics/")}
target="_blank"
rel="noreferrer"
>${this.hass.localize("ui.panel.config.analytics.learn_more")} </a
>.
</p>
<ha-analytics <ha-analytics
translation_key_panel="config" translation_key_panel="config"
@analytics-preferences-changed=${this._preferencesChanged} @analytics-preferences-changed=${this._preferencesChanged}
@@ -58,50 +45,26 @@ class ConfigAnalytics extends LitElement {
.analytics=${this._analyticsDetails} .analytics=${this._analyticsDetails}
></ha-analytics> ></ha-analytics>
</div> </div>
</ha-card> <div class="card-actions">
${isDevVersion(this.hass.config.version) <ha-button @click=${this._save}>
? html`<ha-card ${this.hass.localize(
outlined "ui.panel.config.core.section.core.core_config.save_button"
.header=${this.hass.localize(
"ui.panel.config.analytics.preferences.snapshots.header"
)} )}
> </ha-button>
<div class="card-content"> </div>
<p> </ha-card>
${this.hass.localize( <div class="footer">
"ui.panel.config.analytics.preferences.snapshots.info" <ha-button
)} size="small"
<a appearance="plain"
href=${documentationUrl(this.hass, "/device-database/")} href=${documentationUrl(this.hass, "/integrations/analytics/")}
target="_blank" target="_blank"
rel="noreferrer" rel="noreferrer"
>${this.hass.localize( >
"ui.panel.config.analytics.preferences.snapshots.learn_more" <ha-svg-icon slot="end" .path=${mdiOpenInNew}></ha-svg-icon>
)} </a ${this.hass.localize("ui.panel.config.analytics.learn_more")}
>. </ha-button>
</p> </div>
<ha-settings-row>
<span slot="heading" data-for="snapshots">
${this.hass.localize(
`ui.panel.config.analytics.preferences.snapshots.title`
)}
</span>
<span slot="description" data-for="snapshots">
${this.hass.localize(
`ui.panel.config.analytics.preferences.snapshots.description`
)}
</span>
<ha-switch
@change=${this._handleDeviceRowClick}
.checked=${!!this._analyticsDetails?.preferences.snapshots}
.disabled=${this._analyticsDetails === undefined}
name="snapshots"
>
</ha-switch>
</ha-settings-row>
</div>
</ha-card>`
: nothing}
`; `;
} }
@@ -133,25 +96,11 @@ class ConfigAnalytics extends LitElement {
} }
} }
private _handleDeviceRowClick(ev: Event) {
const target = ev.target as HaSwitch;
this._analyticsDetails = {
...this._analyticsDetails!,
preferences: {
...this._analyticsDetails!.preferences,
snapshots: target.checked,
},
};
this._save();
}
private _preferencesChanged(event: CustomEvent): void { private _preferencesChanged(event: CustomEvent): void {
this._analyticsDetails = { this._analyticsDetails = {
...this._analyticsDetails!, ...this._analyticsDetails!,
preferences: event.detail.preferences, preferences: event.detail.preferences,
}; };
this._save();
} }
static get styles(): CSSResultGroup { static get styles(): CSSResultGroup {
@@ -178,9 +127,6 @@ class ConfigAnalytics extends LitElement {
padding: 32px 0 16px; padding: 32px 0 16px;
text-align: center; text-align: center;
} }
ha-card:not(:first-of-type) {
margin-top: 24px;
}
ha-button[size="small"] ha-svg-icon { ha-button[size="small"] ha-svg-icon {
--mdc-icon-size: 16px; --mdc-icon-size: 16px;

View File

@@ -771,10 +771,7 @@ export class HaConfigDeviceDashboard extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label <ha-label style=${color ? `--color: ${color}` : ""}>
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -26,7 +26,6 @@ import type {
EnergySource, EnergySource,
FlowFromGridSourceEnergyPreference, FlowFromGridSourceEnergyPreference,
FlowToGridSourceEnergyPreference, FlowToGridSourceEnergyPreference,
GridPowerSourceEnergyPreference,
GridSourceTypeEnergyPreference, GridSourceTypeEnergyPreference,
} from "../../../../data/energy"; } from "../../../../data/energy";
import { import {
@@ -48,7 +47,6 @@ import { documentationUrl } from "../../../../util/documentation-url";
import { import {
showEnergySettingsGridFlowFromDialog, showEnergySettingsGridFlowFromDialog,
showEnergySettingsGridFlowToDialog, showEnergySettingsGridFlowToDialog,
showEnergySettingsGridPowerDialog,
} from "../dialogs/show-dialogs-energy"; } from "../dialogs/show-dialogs-energy";
import "./ha-energy-validation-result"; import "./ha-energy-validation-result";
import { energyCardStyles } from "./styles"; import { energyCardStyles } from "./styles";
@@ -228,58 +226,6 @@ export class EnergyGridSettings extends LitElement {
> >
</div> </div>
<h3>
${this.hass.localize("ui.panel.config.energy.grid.grid_power")}
</h3>
${gridSource.power?.map((power) => {
const entityState = this.hass.states[power.stat_rate];
return html`
<div class="row" .source=${power}>
${entityState?.attributes.icon
? html`<ha-icon
.icon=${entityState.attributes.icon}
></ha-icon>`
: html`<ha-svg-icon
.path=${mdiTransmissionTower}
></ha-svg-icon>`}
<span class="content"
>${getStatisticLabel(
this.hass,
power.stat_rate,
this.statsMetadata?.[power.stat_rate]
)}</span
>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.grid.edit_power"
)}
@click=${this._editPowerSource}
.path=${mdiPencil}
></ha-icon-button>
<ha-icon-button
.label=${this.hass.localize(
"ui.panel.config.energy.grid.delete_power"
)}
@click=${this._deletePowerSource}
.path=${mdiDelete}
></ha-icon-button>
</div>
`;
})}
<div class="row border-bottom">
<ha-svg-icon .path=${mdiTransmissionTower}></ha-svg-icon>
<ha-button
@click=${this._addPowerSource}
appearance="filled"
size="small"
>
<ha-svg-icon .path=${mdiPlus} slot="start"></ha-svg-icon
>${this.hass.localize(
"ui.panel.config.energy.grid.add_power"
)}</ha-button
>
</div>
<h3> <h3>
${this.hass.localize( ${this.hass.localize(
"ui.panel.config.energy.grid.grid_carbon_footprint" "ui.panel.config.energy.grid.grid_carbon_footprint"
@@ -553,97 +499,6 @@ export class EnergyGridSettings extends LitElement {
await this._savePreferences(cleanedPreferences); await this._savePreferences(cleanedPreferences);
} }
private _addPowerSource() {
const gridSource = this.preferences.energy_sources.find(
(src) => src.type === "grid"
) as GridSourceTypeEnergyPreference | undefined;
showEnergySettingsGridPowerDialog(this, {
grid_source: gridSource,
saveCallback: async (power) => {
let preferences: EnergyPreferences;
if (!gridSource) {
preferences = {
...this.preferences,
energy_sources: [
...this.preferences.energy_sources,
{
...emptyGridSourceEnergyPreference(),
power: [power],
},
],
};
} else {
preferences = {
...this.preferences,
energy_sources: this.preferences.energy_sources.map((src) =>
src.type === "grid"
? { ...src, power: [...(gridSource.power || []), power] }
: src
),
};
}
await this._savePreferences(preferences);
},
});
}
private _editPowerSource(ev) {
const origSource: GridPowerSourceEnergyPreference =
ev.currentTarget.closest(".row").source;
const gridSource = this.preferences.energy_sources.find(
(src) => src.type === "grid"
) as GridSourceTypeEnergyPreference | undefined;
showEnergySettingsGridPowerDialog(this, {
source: { ...origSource },
grid_source: gridSource,
saveCallback: async (source) => {
const power =
energySourcesByType(this.preferences).grid![0].power || [];
const preferences: EnergyPreferences = {
...this.preferences,
energy_sources: this.preferences.energy_sources.map((src) =>
src.type === "grid"
? {
...src,
power: power.map((p) => (p === origSource ? source : p)),
}
: src
),
};
await this._savePreferences(preferences);
},
});
}
private async _deletePowerSource(ev) {
const sourceToDelete: GridPowerSourceEnergyPreference =
ev.currentTarget.closest(".row").source;
if (
!(await showConfirmationDialog(this, {
title: this.hass.localize("ui.panel.config.energy.delete_source"),
}))
) {
return;
}
const power =
energySourcesByType(this.preferences).grid![0].power?.filter(
(p) => p !== sourceToDelete
) || [];
const preferences: EnergyPreferences = {
...this.preferences,
energy_sources: this.preferences.energy_sources.map((source) =>
source.type === "grid" ? { ...source, power } : source
),
};
const cleanedPreferences = this._removeEmptySources(preferences);
await this._savePreferences(cleanedPreferences);
}
private _removeEmptySources(preferences: EnergyPreferences) { private _removeEmptySources(preferences: EnergyPreferences) {
// Check if grid sources became an empty type and remove if so // Check if grid sources became an empty type and remove if so
preferences.energy_sources = preferences.energy_sources.reduce< preferences.energy_sources = preferences.energy_sources.reduce<
@@ -652,8 +507,7 @@ export class EnergyGridSettings extends LitElement {
if ( if (
source.type !== "grid" || source.type !== "grid" ||
source.flow_from.length > 0 || source.flow_from.length > 0 ||
source.flow_to.length > 0 || source.flow_to.length > 0
(source.power && source.power.length > 0)
) { ) {
acc.push(source); acc.push(source);
} }

View File

@@ -18,7 +18,6 @@ import type { HomeAssistant } from "../../../../types";
import type { EnergySettingsBatteryDialogParams } from "./show-dialogs-energy"; import type { EnergySettingsBatteryDialogParams } from "./show-dialogs-energy";
const energyUnitClasses = ["energy"]; const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@customElement("dialog-energy-battery-settings") @customElement("dialog-energy-battery-settings")
export class DialogEnergyBatterySettings export class DialogEnergyBatterySettings
@@ -33,14 +32,10 @@ export class DialogEnergyBatterySettings
@state() private _energy_units?: string[]; @state() private _energy_units?: string[];
@state() private _power_units?: string[];
@state() private _error?: string; @state() private _error?: string;
private _excludeList?: string[]; private _excludeList?: string[];
private _excludeListPower?: string[];
public async showDialog( public async showDialog(
params: EnergySettingsBatteryDialogParams params: EnergySettingsBatteryDialogParams
): Promise<void> { ): Promise<void> {
@@ -51,9 +46,6 @@ export class DialogEnergyBatterySettings
this._energy_units = ( this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy") await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units; ).units;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
const allSources: string[] = []; const allSources: string[] = [];
this._params.battery_sources.forEach((entry) => { this._params.battery_sources.forEach((entry) => {
allSources.push(entry.stat_energy_from); allSources.push(entry.stat_energy_from);
@@ -64,9 +56,6 @@ export class DialogEnergyBatterySettings
id !== this._source?.stat_energy_from && id !== this._source?.stat_energy_from &&
id !== this._source?.stat_energy_to id !== this._source?.stat_energy_to
); );
this._excludeListPower = this._params.battery_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
} }
public closeDialog() { public closeDialog() {
@@ -83,6 +72,8 @@ export class DialogEnergyBatterySettings
return nothing; return nothing;
} }
const pickableUnit = this._energy_units?.join(", ") || "";
return html` return html`
<ha-dialog <ha-dialog
open open
@@ -94,6 +85,12 @@ export class DialogEnergyBatterySettings
@closed=${this.closeDialog} @closed=${this.closeDialog}
> >
${this._error ? html`<p class="error">${this._error}</p>` : ""} ${this._error ? html`<p class="error">${this._error}</p>` : ""}
<div>
${this.hass.localize(
"ui.panel.config.energy.battery.dialog.entity_para",
{ unit: pickableUnit }
)}
</div>
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
@@ -108,10 +105,6 @@ export class DialogEnergyBatterySettings
this._source.stat_energy_from, this._source.stat_energy_from,
]} ]}
@value-changed=${this._statisticToChanged} @value-changed=${this._statisticToChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.energy_helper_into",
{ unit: this._energy_units?.join(", ") || "" }
)}
dialogInitialFocus dialogInitialFocus
></ha-statistic-picker> ></ha-statistic-picker>
@@ -128,25 +121,6 @@ export class DialogEnergyBatterySettings
this._source.stat_energy_to, this._source.stat_energy_to,
]} ]}
@value-changed=${this._statisticFromChanged} @value-changed=${this._statisticFromChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.energy_helper_out",
{ unit: this._energy_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-statistic-picker
.hass=${this.hass}
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.battery.dialog.power_helper",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker> ></ha-statistic-picker>
<ha-button <ha-button
@@ -176,10 +150,6 @@ export class DialogEnergyBatterySettings
this._source = { ...this._source!, stat_energy_from: ev.detail.value }; this._source = { ...this._source!, stat_energy_from: ev.detail.value };
} }
private _powerChanged(ev: CustomEvent<{ value: string }>) {
this._source = { ...this._source!, stat_rate: ev.detail.value };
}
private async _save() { private async _save() {
try { try {
await this._params!.saveCallback(this._source!); await this._params!.saveCallback(this._source!);
@@ -198,11 +168,7 @@ export class DialogEnergyBatterySettings
--mdc-dialog-max-width: 430px; --mdc-dialog-max-width: 430px;
} }
ha-statistic-picker { ha-statistic-picker {
display: block; width: 100%;
margin-bottom: var(--ha-space-4);
}
ha-statistic-picker:last-of-type {
margin-bottom: 0;
} }
`, `,
]; ];

View File

@@ -21,7 +21,6 @@ import type { HomeAssistant } from "../../../../types";
import type { EnergySettingsDeviceDialogParams } from "./show-dialogs-energy"; import type { EnergySettingsDeviceDialogParams } from "./show-dialogs-energy";
const energyUnitClasses = ["energy"]; const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@customElement("dialog-energy-device-settings") @customElement("dialog-energy-device-settings")
export class DialogEnergyDeviceSettings export class DialogEnergyDeviceSettings
@@ -36,14 +35,10 @@ export class DialogEnergyDeviceSettings
@state() private _energy_units?: string[]; @state() private _energy_units?: string[];
@state() private _power_units?: string[];
@state() private _error?: string; @state() private _error?: string;
private _excludeList?: string[]; private _excludeList?: string[];
private _excludeListPower?: string[];
private _possibleParents: DeviceConsumptionEnergyPreference[] = []; private _possibleParents: DeviceConsumptionEnergyPreference[] = [];
public async showDialog( public async showDialog(
@@ -55,15 +50,9 @@ export class DialogEnergyDeviceSettings
this._energy_units = ( this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy") await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units; ).units;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
this._excludeList = this._params.device_consumptions this._excludeList = this._params.device_consumptions
.map((entry) => entry.stat_consumption) .map((entry) => entry.stat_consumption)
.filter((id) => id !== this._device?.stat_consumption); .filter((id) => id !== this._device?.stat_consumption);
this._excludeListPower = this._params.device_consumptions
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._device?.stat_rate) as string[];
} }
private _computePossibleParents() { private _computePossibleParents() {
@@ -104,6 +93,8 @@ export class DialogEnergyDeviceSettings
return nothing; return nothing;
} }
const pickableUnit = this._energy_units?.join(", ") || "";
return html` return html`
<ha-dialog <ha-dialog
open open
@@ -117,6 +108,12 @@ export class DialogEnergyDeviceSettings
@closed=${this.closeDialog} @closed=${this.closeDialog}
> >
${this._error ? html`<p class="error">${this._error}</p>` : ""} ${this._error ? html`<p class="error">${this._error}</p>` : ""}
<div>
${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
{ unit: pickableUnit }
)}
</div>
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
@@ -128,28 +125,9 @@ export class DialogEnergyDeviceSettings
)} )}
.excludeStatistics=${this._excludeList} .excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged} @value-changed=${this._statisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
{ unit: this._energy_units?.join(", ") || "" }
)}
dialogInitialFocus dialogInitialFocus
></ha-statistic-picker> ></ha-statistic-picker>
<ha-statistic-picker
.hass=${this.hass}
.includeUnitClass=${powerUnitClasses}
.value=${this._device?.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.device_consumption_power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.selected_stat_intro",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<ha-textfield <ha-textfield
.label=${this.hass.localize( .label=${this.hass.localize(
"ui.panel.config.energy.device_consumption.dialog.display_name" "ui.panel.config.energy.device_consumption.dialog.display_name"
@@ -232,20 +210,6 @@ export class DialogEnergyDeviceSettings
this._computePossibleParents(); this._computePossibleParents();
} }
private _powerStatisticChanged(ev: CustomEvent<{ value: string }>) {
if (!this._device) {
return;
}
const newDevice = {
...this._device,
stat_rate: ev.detail.value,
} as DeviceConsumptionEnergyPreference;
if (!newDevice.stat_rate) {
delete newDevice.stat_rate;
}
this._device = newDevice;
}
private _nameChanged(ev) { private _nameChanged(ev) {
const newDevice = { const newDevice = {
...this._device!, ...this._device!,
@@ -281,19 +245,15 @@ export class DialogEnergyDeviceSettings
return [ return [
haStyleDialog, haStyleDialog,
css` css`
ha-statistic-picker {
display: block;
margin-bottom: var(--ha-space-2);
}
ha-statistic-picker { ha-statistic-picker {
width: 100%; width: 100%;
} }
ha-select { ha-select {
margin-top: var(--ha-space-4); margin-top: 16px;
width: 100%; width: 100%;
} }
ha-textfield { ha-textfield {
margin-top: var(--ha-space-4); margin-top: 16px;
width: 100%; width: 100%;
} }
`, `,

View File

@@ -104,6 +104,8 @@ export class DialogEnergyGridFlowSettings
return nothing; return nothing;
} }
const pickableUnit = this._energy_units?.join(", ") || "";
const unitPriceFixed = `${this.hass.config.currency}/kWh`; const unitPriceFixed = `${this.hass.config.currency}/kWh`;
const externalSource = const externalSource =
@@ -133,11 +135,19 @@ export class DialogEnergyGridFlowSettings
@closed=${this.closeDialog} @closed=${this.closeDialog}
> >
${this._error ? html`<p class="error">${this._error}</p>` : ""} ${this._error ? html`<p class="error">${this._error}</p>` : ""}
<p> <div>
${this.hass.localize( <p>
`ui.panel.config.energy.grid.flow_dialog.${this._params.direction}.paragraph` ${this.hass.localize(
)} `ui.panel.config.energy.grid.flow_dialog.${this._params.direction}.paragraph`
</p> )}
</p>
<p>
${this.hass.localize(
`ui.panel.config.energy.grid.flow_dialog.${this._params.direction}.entity_para`,
{ unit: pickableUnit }
)}
</p>
</div>
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
@@ -153,10 +163,6 @@ export class DialogEnergyGridFlowSettings
)} )}
.excludeStatistics=${this._excludeList} .excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged} @value-changed=${this._statisticChanged}
.helper=${this.hass.localize(
`ui.panel.config.energy.grid.flow_dialog.${this._params.direction}.entity_para`,
{ unit: this._energy_units?.join(", ") || "" }
)}
dialogInitialFocus dialogInitialFocus
></ha-statistic-picker> ></ha-statistic-picker>
@@ -355,10 +361,6 @@ export class DialogEnergyGridFlowSettings
ha-dialog { ha-dialog {
--mdc-dialog-max-width: 430px; --mdc-dialog-max-width: 430px;
} }
ha-statistic-picker {
display: block;
margin: var(--ha-space-4) 0;
}
ha-formfield { ha-formfield {
display: block; display: block;
} }

View File

@@ -1,153 +0,0 @@
import { mdiTransmissionTower } from "@mdi/js";
import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/entity/ha-statistic-picker";
import "../../../../components/ha-dialog";
import "../../../../components/ha-button";
import type { GridPowerSourceEnergyPreference } from "../../../../data/energy";
import { energyStatisticHelpUrl } from "../../../../data/energy";
import { getSensorDeviceClassConvertibleUnits } from "../../../../data/sensor";
import type { HassDialog } from "../../../../dialogs/make-dialog-manager";
import { haStyleDialog } from "../../../../resources/styles";
import type { HomeAssistant } from "../../../../types";
import type { EnergySettingsGridPowerDialogParams } from "./show-dialogs-energy";
const powerUnitClasses = ["power"];
@customElement("dialog-energy-grid-power-settings")
export class DialogEnergyGridPowerSettings
extends LitElement
implements HassDialog<EnergySettingsGridPowerDialogParams>
{
@property({ attribute: false }) public hass!: HomeAssistant;
@state() private _params?: EnergySettingsGridPowerDialogParams;
@state() private _source?: GridPowerSourceEnergyPreference;
@state() private _power_units?: string[];
@state() private _error?: string;
private _excludeListPower?: string[];
public async showDialog(
params: EnergySettingsGridPowerDialogParams
): Promise<void> {
this._params = params;
this._source = params.source ? { ...params.source } : { stat_rate: "" };
const initialSourceIdPower = this._source.stat_rate;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
this._excludeListPower = [
...(this._params.grid_source?.power?.map((entry) => entry.stat_rate) ||
[]),
].filter((id) => id && id !== initialSourceIdPower) as string[];
}
public closeDialog() {
this._params = undefined;
this._source = undefined;
this._error = undefined;
this._excludeListPower = undefined;
fireEvent(this, "dialog-closed", { dialog: this.localName });
return true;
}
protected render() {
if (!this._params || !this._source) {
return nothing;
}
return html`
<ha-dialog
open
.heading=${html`<ha-svg-icon
.path=${mdiTransmissionTower}
style="--mdc-icon-size: 32px;"
></ha-svg-icon
>${this.hass.localize(
"ui.panel.config.energy.grid.power_dialog.header"
)}`}
@closed=${this.closeDialog}
>
${this._error ? html`<p class="error">${this._error}</p>` : ""}
<ha-statistic-picker
.hass=${this.hass}
.helpMissingEntityUrl=${energyStatisticHelpUrl}
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.grid.power_dialog.power_stat"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.grid.power_dialog.power_helper",
{ unit: this._power_units?.join(", ") || "" }
)}
dialogInitialFocus
></ha-statistic-picker>
<ha-button
appearance="plain"
@click=${this.closeDialog}
slot="primaryAction"
>
${this.hass.localize("ui.common.cancel")}
</ha-button>
<ha-button
@click=${this._save}
.disabled=${!this._source.stat_rate}
slot="primaryAction"
>
${this.hass.localize("ui.common.save")}
</ha-button>
</ha-dialog>
`;
}
private _powerStatisticChanged(ev: CustomEvent<{ value: string }>) {
this._source = {
...this._source!,
stat_rate: ev.detail.value,
};
}
private async _save() {
try {
await this._params!.saveCallback(this._source!);
this.closeDialog();
} catch (err: any) {
this._error = err.message;
}
}
static get styles(): CSSResultGroup {
return [
haStyleDialog,
css`
ha-dialog {
--mdc-dialog-max-width: 430px;
}
ha-statistic-picker {
display: block;
margin: var(--ha-space-4) 0;
}
`,
];
}
}
declare global {
interface HTMLElementTagNameMap {
"dialog-energy-grid-power-settings": DialogEnergyGridPowerSettings;
}
}

View File

@@ -28,7 +28,6 @@ import { brandsUrl } from "../../../../util/brands-url";
import type { EnergySettingsSolarDialogParams } from "./show-dialogs-energy"; import type { EnergySettingsSolarDialogParams } from "./show-dialogs-energy";
const energyUnitClasses = ["energy"]; const energyUnitClasses = ["energy"];
const powerUnitClasses = ["power"];
@customElement("dialog-energy-solar-settings") @customElement("dialog-energy-solar-settings")
export class DialogEnergySolarSettings export class DialogEnergySolarSettings
@@ -47,14 +46,10 @@ export class DialogEnergySolarSettings
@state() private _energy_units?: string[]; @state() private _energy_units?: string[];
@state() private _power_units?: string[];
@state() private _error?: string; @state() private _error?: string;
private _excludeList?: string[]; private _excludeList?: string[];
private _excludeListPower?: string[];
public async showDialog( public async showDialog(
params: EnergySettingsSolarDialogParams params: EnergySettingsSolarDialogParams
): Promise<void> { ): Promise<void> {
@@ -67,15 +62,9 @@ export class DialogEnergySolarSettings
this._energy_units = ( this._energy_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "energy") await getSensorDeviceClassConvertibleUnits(this.hass, "energy")
).units; ).units;
this._power_units = (
await getSensorDeviceClassConvertibleUnits(this.hass, "power")
).units;
this._excludeList = this._params.solar_sources this._excludeList = this._params.solar_sources
.map((entry) => entry.stat_energy_from) .map((entry) => entry.stat_energy_from)
.filter((id) => id !== this._source?.stat_energy_from); .filter((id) => id !== this._source?.stat_energy_from);
this._excludeListPower = this._params.solar_sources
.map((entry) => entry.stat_rate)
.filter((id) => id && id !== this._source?.stat_rate) as string[];
} }
public closeDialog() { public closeDialog() {
@@ -92,6 +81,8 @@ export class DialogEnergySolarSettings
return nothing; return nothing;
} }
const pickableUnit = this._energy_units?.join(", ") || "";
return html` return html`
<ha-dialog <ha-dialog
open open
@@ -103,6 +94,12 @@ export class DialogEnergySolarSettings
@closed=${this.closeDialog} @closed=${this.closeDialog}
> >
${this._error ? html`<p class="error">${this._error}</p>` : ""} ${this._error ? html`<p class="error">${this._error}</p>` : ""}
<div>
${this.hass.localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: pickableUnit }
)}
</div>
<ha-statistic-picker <ha-statistic-picker
.hass=${this.hass} .hass=${this.hass}
@@ -114,28 +111,9 @@ export class DialogEnergySolarSettings
)} )}
.excludeStatistics=${this._excludeList} .excludeStatistics=${this._excludeList}
@value-changed=${this._statisticChanged} @value-changed=${this._statisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: this._energy_units?.join(", ") || "" }
)}
dialogInitialFocus dialogInitialFocus
></ha-statistic-picker> ></ha-statistic-picker>
<ha-statistic-picker
.hass=${this.hass}
.includeUnitClass=${powerUnitClasses}
.value=${this._source.stat_rate}
.label=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.solar_production_power"
)}
.excludeStatistics=${this._excludeListPower}
@value-changed=${this._powerStatisticChanged}
.helper=${this.hass.localize(
"ui.panel.config.energy.solar.dialog.entity_para",
{ unit: this._power_units?.join(", ") || "" }
)}
></ha-statistic-picker>
<h3> <h3>
${this.hass.localize( ${this.hass.localize(
"ui.panel.config.energy.solar.dialog.solar_production_forecast" "ui.panel.config.energy.solar.dialog.solar_production_forecast"
@@ -289,10 +267,6 @@ export class DialogEnergySolarSettings
this._source = { ...this._source!, stat_energy_from: ev.detail.value }; this._source = { ...this._source!, stat_energy_from: ev.detail.value };
} }
private _powerStatisticChanged(ev: CustomEvent<{ value: string }>) {
this._source = { ...this._source!, stat_rate: ev.detail.value };
}
private async _save() { private async _save() {
try { try {
if (!this._forecast) { if (!this._forecast) {
@@ -313,10 +287,6 @@ export class DialogEnergySolarSettings
ha-dialog { ha-dialog {
--mdc-dialog-max-width: 430px; --mdc-dialog-max-width: 430px;
} }
ha-statistic-picker {
display: block;
margin-bottom: var(--ha-space-4);
}
img { img {
height: 24px; height: 24px;
margin-right: 16px; margin-right: 16px;

View File

@@ -7,7 +7,6 @@ import type {
FlowFromGridSourceEnergyPreference, FlowFromGridSourceEnergyPreference,
FlowToGridSourceEnergyPreference, FlowToGridSourceEnergyPreference,
GasSourceTypeEnergyPreference, GasSourceTypeEnergyPreference,
GridPowerSourceEnergyPreference,
GridSourceTypeEnergyPreference, GridSourceTypeEnergyPreference,
SolarSourceTypeEnergyPreference, SolarSourceTypeEnergyPreference,
WaterSourceTypeEnergyPreference, WaterSourceTypeEnergyPreference,
@@ -42,12 +41,6 @@ export interface EnergySettingsGridFlowToDialogParams {
saveCallback: (source: FlowToGridSourceEnergyPreference) => Promise<void>; saveCallback: (source: FlowToGridSourceEnergyPreference) => Promise<void>;
} }
export interface EnergySettingsGridPowerDialogParams {
source?: GridPowerSourceEnergyPreference;
grid_source?: GridSourceTypeEnergyPreference;
saveCallback: (source: GridPowerSourceEnergyPreference) => Promise<void>;
}
export interface EnergySettingsSolarDialogParams { export interface EnergySettingsSolarDialogParams {
info: EnergyInfo; info: EnergyInfo;
source?: SolarSourceTypeEnergyPreference; source?: SolarSourceTypeEnergyPreference;
@@ -159,14 +152,3 @@ export const showEnergySettingsGridFlowToDialog = (
dialogParams: { ...dialogParams, direction: "to" }, dialogParams: { ...dialogParams, direction: "to" },
}); });
}; };
export const showEnergySettingsGridPowerDialog = (
element: HTMLElement,
dialogParams: EnergySettingsGridPowerDialogParams
): void => {
fireEvent(element, "show-dialog", {
dialogTag: "dialog-energy-grid-power-settings",
dialogImport: () => import("./dialog-energy-grid-power-settings"),
dialogParams: dialogParams,
});
};

View File

@@ -792,10 +792,7 @@ export class HaConfigEntities extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label <ha-label style=${color ? `--color: ${color}` : ""}>
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -634,10 +634,7 @@ export class HaConfigHelpers extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label <ha-label style=${color ? `--color: ${color}` : ""}>
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -8,7 +8,6 @@ import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one"; import memoizeOne from "memoize-one";
import { relativeTime } from "../../../../../common/datetime/relative_time"; import { relativeTime } from "../../../../../common/datetime/relative_time";
import { getDeviceContext } from "../../../../../common/entity/context/get_device_context";
import { navigate } from "../../../../../common/navigate"; import { navigate } from "../../../../../common/navigate";
import { throttle } from "../../../../../common/util/throttle"; import { throttle } from "../../../../../common/util/throttle";
import "../../../../../components/chart/ha-network-graph"; import "../../../../../components/chart/ha-network-graph";
@@ -195,17 +194,11 @@ export class BluetoothNetworkVisualization extends LitElement {
]; ];
const links: NetworkLink[] = []; const links: NetworkLink[] = [];
Object.values(scanners).forEach((scanner) => { Object.values(scanners).forEach((scanner) => {
const scannerDevice = this._sourceDevices[scanner.source] as const scannerDevice = this._sourceDevices[scanner.source];
| DeviceRegistryEntry
| undefined;
const area = scannerDevice
? getDeviceContext(scannerDevice, this.hass).area
: undefined;
nodes.push({ nodes.push({
id: scanner.source, id: scanner.source,
name: name:
scannerDevice?.name_by_user || scannerDevice?.name || scanner.name, scannerDevice?.name_by_user || scannerDevice?.name || scanner.name,
context: area?.name,
category: 1, category: 1,
value: 5, value: 5,
symbol: "circle", symbol: "circle",
@@ -238,16 +231,10 @@ export class BluetoothNetworkVisualization extends LitElement {
}); });
return; return;
} }
const device = this._sourceDevices[node.address] as const device = this._sourceDevices[node.address];
| DeviceRegistryEntry
| undefined;
const area = device
? getDeviceContext(device, this.hass).area
: undefined;
nodes.push({ nodes.push({
id: node.address, id: node.address,
name: this._getBluetoothDeviceName(node.address), name: this._getBluetoothDeviceName(node.address),
context: area?.name,
value: device ? 1 : 0, value: device ? 1 : 0,
category: device ? 2 : 3, category: device ? 2 : 3,
symbolSize: 20, symbolSize: 20,
@@ -307,20 +294,15 @@ export class BluetoothNetworkVisualization extends LitElement {
const btDevice = this._data.find((d) => d.address === address); const btDevice = this._data.find((d) => d.address === address);
if (btDevice) { if (btDevice) {
tooltipText = `<b>${name}</b><br><b>${this.hass.localize("ui.panel.config.bluetooth.address")}:</b> ${address}<br><b>${this.hass.localize("ui.panel.config.bluetooth.rssi")}:</b> ${btDevice.rssi}<br><b>${this.hass.localize("ui.panel.config.bluetooth.source")}:</b> ${btDevice.source}<br><b>${this.hass.localize("ui.panel.config.bluetooth.updated")}:</b> ${relativeTime(new Date(btDevice.time * 1000), this.hass.locale)}`; tooltipText = `<b>${name}</b><br><b>${this.hass.localize("ui.panel.config.bluetooth.address")}:</b> ${address}<br><b>${this.hass.localize("ui.panel.config.bluetooth.rssi")}:</b> ${btDevice.rssi}<br><b>${this.hass.localize("ui.panel.config.bluetooth.source")}:</b> ${btDevice.source}<br><b>${this.hass.localize("ui.panel.config.bluetooth.updated")}:</b> ${relativeTime(new Date(btDevice.time * 1000), this.hass.locale)}`;
const device = this._sourceDevices[address];
if (device) {
const area = getDeviceContext(device, this.hass).area;
if (area) {
tooltipText += `<br><b>${this.hass.localize("ui.panel.config.bluetooth.area")}: </b>${area.name}`;
}
}
} else { } else {
const device = this._sourceDevices[address]; const device = this._sourceDevices[address];
if (device) { if (device) {
tooltipText = `<b>${name}</b><br><b>${this.hass.localize("ui.panel.config.bluetooth.address")}:</b> ${address}`; tooltipText = `<b>${name}</b><br><b>${this.hass.localize("ui.panel.config.bluetooth.address")}:</b> ${address}`;
const area = getDeviceContext(device, this.hass).area; if (device.area_id) {
if (area) { const area = this.hass.areas[device.area_id];
tooltipText += `<br><b>${this.hass.localize("ui.panel.config.bluetooth.area")}: </b>${area.name}`; if (area) {
tooltipText += `<br><b>${this.hass.localize("ui.panel.config.bluetooth.area")}: </b>${area.name}`;
}
} }
} }
} }

View File

@@ -426,10 +426,6 @@ class DialogZHAReconfigureDevice extends LitElement {
return [ return [
haStyleDialog, haStyleDialog,
css` css`
ha-dialog {
--mdc-dialog-max-width: 800px;
}
.wrapper { .wrapper {
display: grid; display: grid;
grid-template-columns: 3fr 1fr 2fr; grid-template-columns: 3fr 1fr 2fr;

View File

@@ -19,8 +19,6 @@ import "../../../../../layouts/hass-tabs-subpage";
import type { HomeAssistant, Route } from "../../../../../types"; import type { HomeAssistant, Route } from "../../../../../types";
import { formatAsPaddedHex } from "./functions"; import { formatAsPaddedHex } from "./functions";
import { zhaTabs } from "./zha-config-dashboard"; import { zhaTabs } from "./zha-config-dashboard";
import type { DeviceRegistryEntry } from "../../../../../data/device_registry";
import { getDeviceContext } from "../../../../../common/entity/context/get_device_context";
@customElement("zha-network-visualization-page") @customElement("zha-network-visualization-page")
export class ZHANetworkVisualizationPage extends LitElement { export class ZHANetworkVisualizationPage extends LitElement {
@@ -119,11 +117,8 @@ export class ZHANetworkVisualizationPage extends LitElement {
} else { } else {
label += `<br><b>${this.hass.localize("ui.panel.config.zha.visualization.device_not_in_db")}</b>`; label += `<br><b>${this.hass.localize("ui.panel.config.zha.visualization.device_not_in_db")}</b>`;
} }
const haDevice = this.hass.devices[device.device_reg_id] as if (device.area_id) {
| DeviceRegistryEntry const area = this.hass.areas[device.area_id];
| undefined;
if (haDevice) {
const area = getDeviceContext(haDevice, this.hass).area;
if (area) { if (area) {
label += `<br><b>${this.hass.localize("ui.panel.config.zha.visualization.area")}: </b>${area.name}`; label += `<br><b>${this.hass.localize("ui.panel.config.zha.visualization.area")}: </b>${area.name}`;
} }
@@ -209,17 +204,10 @@ export class ZHANetworkVisualizationPage extends LitElement {
category = 2; // End Device category = 2; // End Device
} }
const haDevice = this.hass.devices[device.device_reg_id] as
| DeviceRegistryEntry
| undefined;
const area = haDevice
? getDeviceContext(haDevice, this.hass).area
: undefined;
// Create node // Create node
nodes.push({ nodes.push({
id: device.ieee, id: device.ieee,
name: device.user_given_name || device.name || device.ieee, name: device.user_given_name || device.name || device.ieee,
context: area?.name,
category, category,
value: isCoordinator ? 3 : device.device_type === "Router" ? 2 : 1, value: isCoordinator ? 3 : device.device_type === "Router" ? 2 : 1,
symbolSize: isCoordinator symbolSize: isCoordinator

View File

@@ -5,7 +5,6 @@ import type {
import { css, html, LitElement } from "lit"; import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one"; import memoizeOne from "memoize-one";
import { getDeviceContext } from "../../../../../common/entity/context/get_device_context";
import { navigate } from "../../../../../common/navigate"; import { navigate } from "../../../../../common/navigate";
import { debounce } from "../../../../../common/util/debounce"; import { debounce } from "../../../../../common/util/debounce";
import "../../../../../components/chart/ha-network-graph"; import "../../../../../components/chart/ha-network-graph";
@@ -125,7 +124,7 @@ export class ZWaveJSNetworkVisualization extends SubscribeMixin(LitElement) {
return tip; return tip;
} }
const { id, name } = data as any; const { id, name } = data as any;
const device = this._devices[id] as DeviceRegistryEntry | undefined; const device = this._devices[id];
const nodeStatus = this._nodeStatuses[id]; const nodeStatus = this._nodeStatuses[id];
let tip = `${(params as any).marker} ${name}`; let tip = `${(params as any).marker} ${name}`;
tip += `<br><b>${this.hass.localize("ui.panel.config.zwave_js.visualization.node_id")}:</b> ${id}`; tip += `<br><b>${this.hass.localize("ui.panel.config.zwave_js.visualization.node_id")}:</b> ${id}`;
@@ -139,12 +138,6 @@ export class ZWaveJSNetworkVisualization extends SubscribeMixin(LitElement) {
tip += `<br><b>Z-Wave Plus:</b> ${this.hass.localize("ui.panel.config.zwave_js.visualization.version")} ${nodeStatus.zwave_plus_version}`; tip += `<br><b>Z-Wave Plus:</b> ${this.hass.localize("ui.panel.config.zwave_js.visualization.version")} ${nodeStatus.zwave_plus_version}`;
} }
} }
if (device) {
const area = getDeviceContext(device, this.hass).area;
if (area) {
tip += `<br><b>${this.hass.localize("ui.panel.config.zwave_js.visualization.area")}:</b> ${area.name}`;
}
}
return tip; return tip;
}; };
@@ -204,16 +197,10 @@ export class ZWaveJSNetworkVisualization extends SubscribeMixin(LitElement) {
if (node.is_controller_node) { if (node.is_controller_node) {
controllerNode = node.node_id; controllerNode = node.node_id;
} }
const device = this._devices[node.node_id] as const device = this._devices[node.node_id];
| DeviceRegistryEntry
| undefined;
const area = device
? getDeviceContext(device, this.hass).area
: undefined;
nodes.push({ nodes.push({
id: String(node.node_id), id: String(node.node_id),
name: device?.name_by_user ?? device?.name ?? String(node.node_id), name: device?.name_by_user ?? device?.name ?? String(node.node_id),
context: area?.name,
value: node.is_controller_node ? 3 : node.is_routing ? 2 : 1, value: node.is_controller_node ? 3 : node.is_routing ? 2 : 1,
category: category:
node.status === NodeStatus.Dead node.status === NodeStatus.Dead

View File

@@ -320,9 +320,9 @@ export class HaConfigLovelaceDashboards extends LitElement {
if (this.hass.panels.light) { if (this.hass.panels.light) {
result.push({ result.push({
icon: this.hass.panels.light.icon || "mdi:lamps", icon: "mdi:lamps",
title: this.hass.localize("panel.light"), title: this.hass.localize("panel.light"),
show_in_sidebar: true, show_in_sidebar: false,
mode: "storage", mode: "storage",
url_path: "light", url_path: "light",
filename: "", filename: "",
@@ -334,9 +334,9 @@ export class HaConfigLovelaceDashboards extends LitElement {
if (this.hass.panels.security) { if (this.hass.panels.security) {
result.push({ result.push({
icon: this.hass.panels.security.icon || "mdi:security", icon: "mdi:security",
title: this.hass.localize("panel.security"), title: this.hass.localize("panel.security"),
show_in_sidebar: true, show_in_sidebar: false,
mode: "storage", mode: "storage",
url_path: "security", url_path: "security",
filename: "", filename: "",
@@ -348,9 +348,9 @@ export class HaConfigLovelaceDashboards extends LitElement {
if (this.hass.panels.climate) { if (this.hass.panels.climate) {
result.push({ result.push({
icon: this.hass.panels.climate.icon || "mdi:home-thermometer", icon: "mdi:home-thermometer",
title: this.hass.localize("panel.climate"), title: this.hass.localize("panel.climate"),
show_in_sidebar: true, show_in_sidebar: false,
mode: "storage", mode: "storage",
url_path: "climate", url_path: "climate",
filename: "", filename: "",
@@ -360,20 +360,6 @@ export class HaConfigLovelaceDashboards extends LitElement {
}); });
} }
if (this.hass.panels.home) {
result.push({
icon: this.hass.panels.home.icon || "mdi:home",
title: this.hass.localize("panel.home"),
show_in_sidebar: true,
mode: "storage",
url_path: "home",
filename: "",
default: false,
require_admin: false,
type: this._localizeType("built_in"),
});
}
result.push( result.push(
...dashboards ...dashboards
.sort((a, b) => .sort((a, b) =>
@@ -484,18 +470,13 @@ export class HaConfigLovelaceDashboards extends LitElement {
} }
private _canDelete(urlPath: string) { private _canDelete(urlPath: string) {
return ![ return !["lovelace", "energy", "light", "security", "climate"].includes(
"lovelace", urlPath
"energy", );
"light",
"security",
"climate",
"home",
].includes(urlPath);
} }
private _canEdit(urlPath: string) { private _canEdit(urlPath: string) {
return !["light", "security", "climate", "home"].includes(urlPath); return !["light", "security", "climate"].includes(urlPath);
} }
private _handleDelete = async (item: DataTableItem) => { private _handleDelete = async (item: DataTableItem) => {

View File

@@ -1,11 +1,13 @@
import { html, LitElement, nothing } from "lit"; import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state, query } from "lit/decorators";
import memoizeOne from "memoize-one"; import memoizeOne from "memoize-one";
import { mdiClose } from "@mdi/js";
import { fireEvent } from "../../../../common/dom/fire_event"; import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/ha-wa-dialog"; import "../../../../components/ha-md-dialog";
import "../../../../components/ha-dialog-footer"; import type { HaMdDialog } from "../../../../components/ha-md-dialog";
import "../../../../components/ha-alert"; import "../../../../components/ha-dialog-header";
import "../../../../components/ha-form/ha-form"; import "../../../../components/ha-form/ha-form";
import "../../../../components/ha-icon-button";
import "../../../../components/ha-button"; import "../../../../components/ha-button";
import type { SchemaUnion } from "../../../../components/ha-form/types"; import type { SchemaUnion } from "../../../../components/ha-form/types";
import type { LovelaceResourcesMutableParams } from "../../../../data/lovelace/resource"; import type { LovelaceResourcesMutableParams } from "../../../../data/lovelace/resource";
@@ -41,7 +43,7 @@ export class DialogLovelaceResourceDetail extends LitElement {
@state() private _submitting = false; @state() private _submitting = false;
@state() private _open = false; @query("ha-md-dialog") private _dialog?: HaMdDialog;
public showDialog(params: LovelaceResourceDetailsDialogParams): void { public showDialog(params: LovelaceResourceDetailsDialogParams): void {
this._params = params; this._params = params;
@@ -56,11 +58,6 @@ export class DialogLovelaceResourceDetail extends LitElement {
url: "", url: "",
}; };
} }
this._open = true;
}
public closeDialog(): void {
this._open = false;
} }
private _dialogClosed(): void { private _dialogClosed(): void {
@@ -68,6 +65,10 @@ export class DialogLovelaceResourceDetail extends LitElement {
fireEvent(this, "dialog-closed", { dialog: this.localName }); fireEvent(this, "dialog-closed", { dialog: this.localName });
} }
public closeDialog(): void {
this._dialog?.close();
}
protected render() { protected render() {
if (!this._params) { if (!this._params) {
return nothing; return nothing;
@@ -80,45 +81,56 @@ export class DialogLovelaceResourceDetail extends LitElement {
"ui.panel.config.lovelace.resources.detail.new_resource" "ui.panel.config.lovelace.resources.detail.new_resource"
); );
const ariaLabel = this._params.resource?.url
? this.hass!.localize(
"ui.panel.config.lovelace.resources.detail.edit_resource"
)
: this.hass!.localize(
"ui.panel.config.lovelace.resources.detail.new_resource"
);
return html` return html`
<ha-wa-dialog <ha-md-dialog
.hass=${this.hass} open
.open=${this._open} disable-cancel-action
prevent-scrim-close
header-title=${dialogTitle}
@closed=${this._dialogClosed} @closed=${this._dialogClosed}
.ariaLabel=${ariaLabel}
> >
<ha-alert <ha-dialog-header slot="headline">
alert-type="warning" <ha-icon-button
.title=${this.hass!.localize( slot="navigationIcon"
"ui.panel.config.lovelace.resources.detail.warning_header" .label=${this.hass.localize("ui.common.close") ?? "Close"}
)} .path=${mdiClose}
>
${this.hass!.localize(
"ui.panel.config.lovelace.resources.detail.warning_text"
)}
</ha-alert>
<ha-form
autofocus
.schema=${this._schema(this._data)}
.data=${this._data}
.hass=${this.hass}
.error=${this._error}
.computeLabel=${this._computeLabel}
@value-changed=${this._valueChanged}
></ha-form>
<ha-dialog-footer slot="footer">
<ha-button
appearance="plain"
slot="secondaryAction"
@click=${this.closeDialog} @click=${this.closeDialog}
></ha-icon-button>
<span slot="title" .title=${dialogTitle}> ${dialogTitle} </span>
</ha-dialog-header>
<div slot="content">
<ha-alert
alert-type="warning"
.title=${this.hass!.localize(
"ui.panel.config.lovelace.resources.detail.warning_header"
)}
> >
${this.hass!.localize(
"ui.panel.config.lovelace.resources.detail.warning_text"
)}
</ha-alert>
<ha-form
.schema=${this._schema(this._data)}
.data=${this._data}
.hass=${this.hass}
.error=${this._error}
.computeLabel=${this._computeLabel}
@value-changed=${this._valueChanged}
></ha-form>
</div>
<div slot="actions">
<ha-button appearance="plain" @click=${this.closeDialog}>
${this.hass!.localize("ui.common.cancel")} ${this.hass!.localize("ui.common.cancel")}
</ha-button> </ha-button>
<ha-button <ha-button
slot="primaryAction"
@click=${this._updateResource} @click=${this._updateResource}
.disabled=${urlInvalid || !this._data?.res_type || this._submitting} .disabled=${urlInvalid || !this._data?.res_type || this._submitting}
> >
@@ -130,8 +142,8 @@ export class DialogLovelaceResourceDetail extends LitElement {
"ui.panel.config.lovelace.resources.detail.create" "ui.panel.config.lovelace.resources.detail.create"
)} )}
</ha-button> </ha-button>
</ha-dialog-footer> </div>
</ha-wa-dialog> </ha-md-dialog>
`; `;
} }

View File

@@ -41,6 +41,7 @@ class DialogRepairsIssueSubtitle extends LitElement {
:host { :host {
display: block; display: block;
font-size: var(--ha-font-size-m); font-size: var(--ha-font-size-m);
margin-bottom: 8px;
color: var(--secondary-text-color); color: var(--secondary-text-color);
text-overflow: ellipsis; text-overflow: ellipsis;
overflow: hidden; overflow: hidden;

View File

@@ -1,14 +1,15 @@
import { mdiOpenInNew } from "@mdi/js"; import { mdiClose, mdiOpenInNew } from "@mdi/js";
import type { CSSResultGroup } from "lit"; import type { CSSResultGroup } from "lit";
import { css, html, LitElement, nothing } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators"; import { customElement, property, state, query } from "lit/decorators";
import { fireEvent } from "../../../common/dom/fire_event"; import { fireEvent } from "../../../common/dom/fire_event";
import { isNavigationClick } from "../../../common/dom/is-navigation-click"; import { isNavigationClick } from "../../../common/dom/is-navigation-click";
import "../../../components/ha-alert"; import "../../../components/ha-alert";
import "../../../components/ha-wa-dialog"; import "../../../components/ha-md-dialog";
import type { HaMdDialog } from "../../../components/ha-md-dialog";
import "../../../components/ha-button"; import "../../../components/ha-button";
import "../../../components/ha-svg-icon"; import "../../../components/ha-svg-icon";
import "../../../components/ha-dialog-footer"; import "../../../components/ha-dialog-header";
import "./dialog-repairs-issue-subtitle"; import "./dialog-repairs-issue-subtitle";
import "../../../components/ha-markdown"; import "../../../components/ha-markdown";
import type { RepairsIssue } from "../../../data/repairs"; import type { RepairsIssue } from "../../../data/repairs";
@@ -25,12 +26,11 @@ class DialogRepairsIssue extends LitElement {
@state() private _params?: RepairsIssueDialogParams; @state() private _params?: RepairsIssueDialogParams;
@state() private _open = false; @query("ha-md-dialog") private _dialog?: HaMdDialog;
public showDialog(params: RepairsIssueDialogParams): void { public showDialog(params: RepairsIssueDialogParams): void {
this._params = params; this._params = params;
this._issue = this._params.issue; this._issue = this._params.issue;
this._open = true;
} }
private _dialogClosed() { private _dialogClosed() {
@@ -44,7 +44,7 @@ class DialogRepairsIssue extends LitElement {
} }
public closeDialog() { public closeDialog() {
this._open = false; this._dialog?.close();
} }
protected render() { protected render() {
@@ -62,19 +62,32 @@ class DialogRepairsIssue extends LitElement {
) || this.hass!.localize("ui.panel.config.repairs.dialog.title"); ) || this.hass!.localize("ui.panel.config.repairs.dialog.title");
return html` return html`
<ha-wa-dialog <ha-md-dialog
.hass=${this.hass} open
.open=${this._open}
header-title=${dialogTitle}
aria-describedby="dialog-repairs-issue-description"
@closed=${this._dialogClosed} @closed=${this._dialogClosed}
aria-labelledby="dialog-repairs-issue-title"
aria-describedby="dialog-repairs-issue-description"
> >
<dialog-repairs-issue-subtitle <ha-dialog-header slot="headline">
slot="headerSubtitle" <ha-icon-button
.hass=${this.hass} slot="navigationIcon"
.issue=${this._issue} .label=${this.hass.localize("ui.common.close") ?? "Close"}
></dialog-repairs-issue-subtitle> .path=${mdiClose}
<div class="dialog-content"> @click=${this.closeDialog}
></ha-icon-button>
<span
slot="title"
id="dialog-repairs-issue-title"
.title=${dialogTitle}
>${dialogTitle}</span
>
<dialog-repairs-issue-subtitle
slot="subtitle"
.hass=${this.hass}
.issue=${this._issue}
></dialog-repairs-issue-subtitle>
</ha-dialog-header>
<div slot="content" class="dialog-content">
${this._issue.breaks_in_ha_version ${this._issue.breaks_in_ha_version
? html` ? html`
<ha-alert alert-type="warning"> <ha-alert alert-type="warning">
@@ -109,12 +122,8 @@ class DialogRepairsIssue extends LitElement {
` `
: ""} : ""}
</div> </div>
<ha-dialog-footer slot="footer"> <div slot="actions">
<ha-button <ha-button appearance="plain" @click=${this._ignoreIssue}>
slot="secondaryAction"
appearance="plain"
@click=${this._ignoreIssue}
>
${this._issue!.ignored ${this._issue!.ignored
? this.hass!.localize("ui.panel.config.repairs.dialog.unignore") ? this.hass!.localize("ui.panel.config.repairs.dialog.unignore")
: this.hass!.localize("ui.panel.config.repairs.dialog.ignore")} : this.hass!.localize("ui.panel.config.repairs.dialog.ignore")}
@@ -122,7 +131,6 @@ class DialogRepairsIssue extends LitElement {
${this._issue.learn_more_url ${this._issue.learn_more_url
? html` ? html`
<ha-button <ha-button
slot="primaryAction"
appearance="filled" appearance="filled"
rel="noopener noreferrer" rel="noopener noreferrer"
href=${learnMoreUrlIsHomeAssistant href=${learnMoreUrlIsHomeAssistant
@@ -141,8 +149,8 @@ class DialogRepairsIssue extends LitElement {
</ha-button> </ha-button>
` `
: ""} : ""}
</ha-dialog-footer> </div>
</ha-wa-dialog> </ha-md-dialog>
`; `;
} }
@@ -164,7 +172,7 @@ class DialogRepairsIssue extends LitElement {
padding-top: 0; padding-top: 0;
} }
ha-alert { ha-alert {
margin-bottom: var(--ha-space-4); margin-bottom: 16px;
display: block; display: block;
} }
.dismissed { .dismissed {

View File

@@ -473,10 +473,7 @@ class HaSceneDashboard extends SubscribeMixin(LitElement) {
.indeterminate=${partial} .indeterminate=${partial}
reducedTouchTarget reducedTouchTarget
></ha-checkbox> ></ha-checkbox>
<ha-label <ha-label style=${color ? `--color: ${color}` : ""}>
style=${color ? `--color: ${color}` : ""}
.description=${label.description}
>
${label.icon ${label.icon
? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>` ? html`<ha-icon slot="icon" .icon=${label.icon}></ha-icon>`
: nothing} : nothing}

View File

@@ -65,15 +65,13 @@ export default class HaScriptFieldRow extends LitElement {
private _selectorRowElement?: HaAutomationRow; private _selectorRowElement?: HaAutomationRow;
protected render() { protected render() {
const hasSelector =
this.field.selector && typeof this.field.selector === "object";
return html` return html`
<ha-card outlined> <ha-card outlined>
<ha-automation-row <ha-automation-row
.disabled=${this.disabled} .disabled=${this.disabled}
@click=${this._toggleSidebar} @click=${this._toggleSidebar}
.selected=${this._selected} .selected=${this._selected}
.leftChevron=${hasSelector} left-chevron
@toggle-collapsed=${this._toggleCollapse} @toggle-collapsed=${this._toggleCollapse}
.collapsed=${this._collapsed} .collapsed=${this._collapsed}
.highlight=${this.highlight} .highlight=${this.highlight}
@@ -142,124 +140,117 @@ export default class HaScriptFieldRow extends LitElement {
<slot name="icons" slot="icons"></slot> <slot name="icons" slot="icons"></slot>
</ha-automation-row> </ha-automation-row>
</ha-card> </ha-card>
${hasSelector <div
? html` class=${classMap({
<div "selector-row": true,
class=${classMap({ "parent-selected": this._selected,
"selector-row": true, hidden: this._collapsed,
"parent-selected": this._selected, })}
hidden: this._collapsed, >
})} <ha-card>
<ha-automation-row
.selected=${this._selectorRowSelected}
@click=${this._toggleSelectorSidebar}
.collapsed=${this._selectorRowCollapsed}
@toggle-collapsed=${this._toggleSelectorRowCollapse}
.leftChevron=${SELECTOR_SELECTOR_BUILDING_BLOCKS.includes(
Object.keys(this.field.selector)[0]
)}
.highlight=${this.highlight}
>
<h3 slot="header">
${this.hass.localize(
`ui.components.selectors.selector.types.${Object.keys(this.field.selector)[0]}` as LocalizeKeys
)}
${this.hass.localize(
"ui.panel.config.script.editor.field.selector"
)}
</h3>
<ha-md-button-menu
quick
slot="icons"
@click=${preventDefaultStopPropagation}
@keydown=${stopPropagation}
@closed=${stopPropagation}
positioning="fixed"
anchor-corner="end-end"
menu-corner="start-end"
> >
<ha-card> <ha-icon-button
<ha-automation-row slot="trigger"
.selected=${this._selectorRowSelected} .label=${this.hass.localize("ui.common.menu")}
@click=${this._toggleSelectorSidebar} .path=${mdiDotsVertical}
.collapsed=${this._selectorRowCollapsed} ></ha-icon-button>
@toggle-collapsed=${this._toggleSelectorRowCollapse} <ha-md-menu-item
.leftChevron=${SELECTOR_SELECTOR_BUILDING_BLOCKS.includes( .clickAction=${this._toggleYamlMode}
Object.keys(this.field.selector)[0] selector-row
>
<ha-svg-icon
slot="start"
.path=${mdiPlaylistEdit}
></ha-svg-icon>
<div class="overflow-label">
${this.hass.localize(
`ui.panel.config.automation.editor.edit_${!this._yamlMode ? "yaml" : "ui"}`
)} )}
.highlight=${this.highlight} <span
> class="shortcut-placeholder ${isMac ? "mac" : ""}"
<h3 slot="header"> ></span>
${this.hass.localize( </div>
`ui.components.selectors.selector.types.${Object.keys(this.field.selector)[0]}` as LocalizeKeys </ha-md-menu-item>
)} <ha-md-menu-item
${this.hass.localize( .clickAction=${this._onDelete}
"ui.panel.config.script.editor.field.selector" .disabled=${this.disabled}
)} class="warning"
</h3> >
<ha-md-button-menu <ha-svg-icon slot="start" .path=${mdiDelete}></ha-svg-icon>
quick <div class="overflow-label">
slot="icons" ${this.hass.localize(
@click=${preventDefaultStopPropagation} "ui.panel.config.automation.editor.actions.delete"
@keydown=${stopPropagation} )}
@closed=${stopPropagation} ${!this.narrow
positioning="fixed" ? html`<span class="shortcut">
anchor-corner="end-end"
menu-corner="start-end"
>
<ha-icon-button
slot="trigger"
.label=${this.hass.localize("ui.common.menu")}
.path=${mdiDotsVertical}
></ha-icon-button>
<ha-md-menu-item
.clickAction=${this._toggleYamlMode}
selector-row
>
<ha-svg-icon
slot="start"
.path=${mdiPlaylistEdit}
></ha-svg-icon>
<div class="overflow-label">
${this.hass.localize(
`ui.panel.config.automation.editor.edit_${!this._yamlMode ? "yaml" : "ui"}`
)}
<span <span
class="shortcut-placeholder ${isMac ? "mac" : ""}" >${isMac
></span> ? html`<ha-svg-icon
</div> slot="start"
</ha-md-menu-item> .path=${mdiAppleKeyboardCommand}
<ha-md-menu-item ></ha-svg-icon>`
.clickAction=${this._onDelete} : this.hass.localize(
.disabled=${this.disabled} "ui.panel.config.automation.editor.ctrl"
class="warning" )}</span
> >
<ha-svg-icon <span>+</span>
slot="start" <span
.path=${mdiDelete} >${this.hass.localize(
></ha-svg-icon> "ui.panel.config.automation.editor.del"
<div class="overflow-label"> )}</span
${this.hass.localize( >
"ui.panel.config.automation.editor.actions.delete" </span>`
)} : nothing}
${!this.narrow </div>
? html`<span class="shortcut"> </ha-md-menu-item>
<span </ha-md-button-menu>
>${isMac </ha-automation-row>
? html`<ha-svg-icon </ha-card>
slot="start" ${typeof this.field.selector === "object" &&
.path=${mdiAppleKeyboardCommand} SELECTOR_SELECTOR_BUILDING_BLOCKS.includes(
></ha-svg-icon>` Object.keys(this.field.selector)[0]
: this.hass.localize( )
"ui.panel.config.automation.editor.ctrl" ? html`
)}</span <ha-script-field-selector-editor
> class=${this._selectorRowCollapsed ? "hidden" : ""}
<span>+</span> .selected=${this._selectorRowSelected}
<span .hass=${this.hass}
>${this.hass.localize( .field=${this.field}
"ui.panel.config.automation.editor.del" .disabled=${this.disabled}
)}</span indent
> @value-changed=${this._selectorValueChanged}
</span>` .narrow=${this.narrow}
: nothing} ></ha-script-field-selector-editor>
</div> `
</ha-md-menu-item> : nothing}
</ha-md-button-menu> </div>
</ha-automation-row>
</ha-card>
${typeof this.field.selector === "object" &&
SELECTOR_SELECTOR_BUILDING_BLOCKS.includes(
Object.keys(this.field.selector)[0]
)
? html`
<ha-script-field-selector-editor
class=${this._selectorRowCollapsed ? "hidden" : ""}
.selected=${this._selectorRowSelected}
.hass=${this.hass}
.field=${this.field}
.disabled=${this.disabled}
indent
@value-changed=${this._selectorValueChanged}
.narrow=${this.narrow}
></ha-script-field-selector-editor>
`
: nothing}
</div>
`
: nothing}
`; `;
} }

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