Compare commits

...
Author SHA1 Message Date
Aidan Timson ff8790b796 Format the time format selector example 2026-12-01 15:48:00 +00:00
Aidan TimsonandCopilot Autofix powered by AI 0512959140 Fix locale handling in DateTimeFormat
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
2026-12-01 15:48:00 +00:00
Aidan Timson cab8a642eb Add a shared 12 or 24 hour time format selector 2026-12-01 15:48:00 +00:00
Aidan Timson 11122efc45 Track each time card feature write by id 2026-12-01 15:47:21 +00:00
Aidan Timson 1d81e9db8b Avoid toSpliced in the time card feature 2026-12-01 15:33:29 +00:00
Aidan Timson f46d7815f3 Confirm one sent time per report in the time card feature 2026-12-01 15:32:52 +00:00
Aidan Timson 5d138d57a6 Match reported times to sent ones in the time card feature 2026-12-01 15:32:52 +00:00
Aidan Timson cc2c29f647 Keep time selections until the entity updates and follow entity switches 2026-12-01 15:32:51 +00:00
Aidan Timson b088c25052 Fix time zone, pending writes and RTL in the time card feature 2026-12-01 15:32:51 +00:00
Aidan Timson 78aaa5849a Add time format option to the time card feature editor 2026-12-01 15:32:51 +00:00
Aidan Timson ec2aa13888 Add time card feature 2026-12-01 15:32:51 +00:00
Aidan Timson d27dee64f7 Return the service call from the time and datetime setters 2026-12-01 15:32:51 +00:00
WendelinandClaude Opus 5.5 4fbaf8c0a8 Group discovered devices by integration in the add dialog (#56315)
* Group discovered devices by integration in the add dialog

An integration with more than one discovered device now shows one row
with a count, which opens a page with all its discovered devices.
Discovered flows also show the integration's name instead of its domain
when it has no translated title.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Use nextRender to focus after the discovered group changes

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Remove an unneeded comment

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Remove the count badge from discovered groups

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-01 16:29:25 +01:00
19 changed files with 930 additions and 92 deletions

No files matched your search

@@ -82,6 +82,7 @@ const SELECTOR_FALLBACK_VALUES = {
},
ui_action: undefined,
ui_clock_date_format: undefined,
ui_clock_time_format: undefined,
ui_color: undefined,
ui_condition: undefined,
ui_state_content: undefined,
@@ -117,6 +117,7 @@ const SELECTOR_INITIAL_VALUES = {
},
ui_action: undefined,
ui_clock_date_format: undefined,
ui_clock_time_format: undefined,
ui_color: undefined,
ui_condition: () => [],
ui_state_content: undefined,
@@ -0,0 +1,105 @@
import type { ContextType } from "@lit/context";
import { css, html, LitElement } from "lit";
import { customElement, property, state } from "lit/decorators";
import memoizeOne from "memoize-one";
import { consume } from "../../common/decorators/consume";
import { useAmPm } from "../../common/datetime/use_am_pm";
import { fireEvent } from "../../common/dom/fire_event";
import { internationalizationContext } from "../../data/context";
import type { UiClockTimeFormatSelector } from "../../data/selector";
import type { FrontendLocaleData } from "../../data/translation";
import { TimeFormat } from "../../data/translation";
import "../ha-select";
import type { HaSelectOption, HaSelectSelectEvent } from "../ha-select";
type ClockTimeFormatOption = TimeFormat | "auto";
const CLOCK_TIME_FORMAT_OPTIONS: ClockTimeFormatOption[] = [
"auto",
...Object.values(TimeFormat),
];
// 9:30 PM or 21:30, to show what each format looks like
const EXAMPLE_TIME = new Date(2000, 0, 1, 21, 30);
const formatExample = (locale: FrontendLocaleData, timeFormat?: TimeFormat) => {
const formatLocale = timeFormat
? { ...locale, time_format: timeFormat }
: locale;
return new Intl.DateTimeFormat(locale.language, {
hour: "numeric",
minute: "2-digit",
hourCycle: useAmPm(formatLocale) ? "h12" : "h23",
}).format(EXAMPLE_TIME);
};
@customElement("ha-selector-ui_clock_time_format")
export class HaSelectorUiClockTimeFormat extends LitElement {
@property({ attribute: false }) public selector!: UiClockTimeFormatSelector;
@property() public value?: TimeFormat;
@property() public label?: string;
@property() public helper?: string;
@property({ type: Boolean }) public disabled = false;
@state()
@consume({ context: internationalizationContext, subscribe: true })
private _i18n!: ContextType<typeof internationalizationContext>;
private _options = memoizeOne(
(i18n: ContextType<typeof internationalizationContext>): HaSelectOption[] =>
CLOCK_TIME_FORMAT_OPTIONS.map((value) => ({
value,
label:
value === "auto"
? i18n.localize("ui.components.clock-time-format-picker.auto")
: i18n.localize(
`ui.components.clock-time-format-picker.formats.${value}`
),
secondary: formatExample(
i18n.locale,
value === "auto" ? undefined : value
),
}))
);
protected render() {
return html`
<ha-select
.label=${this.label}
.helper=${this.helper}
.value=${this.value ?? "auto"}
.options=${this._options(this._i18n)}
.disabled=${this.disabled}
@selected=${this._selected}
></ha-select>
`;
}
private _selected(ev: HaSelectSelectEvent<ClockTimeFormatOption>): void {
ev.stopPropagation();
const value = ev.detail.value;
fireEvent(this, "value-changed", {
value: value === "auto" ? undefined : value,
});
}
static styles = css`
ha-select {
display: block;
width: 100%;
}
`;
}
declare global {
interface HTMLElementTagNameMap {
"ha-selector-ui_clock_time_format": HaSelectorUiClockTimeFormat;
}
}
@@ -68,6 +68,7 @@ const LOAD_ELEMENTS = {
color_temp: () => import("./ha-selector-color-temp"),
ui_action: () => import("./ha-selector-ui-action"),
ui_clock_date_format: () => import("./ha-selector-ui-clock-date-format"),
ui_clock_time_format: () => import("./ha-selector-ui-clock-time-format"),
ui_color: () => import("./ha-selector-ui-color"),
ui_condition: () => import("./ha-selector-ui-condition"),
ui_state_content: () => import("./ha-selector-ui-state-content"),
+1 -2
View File
@@ -4,9 +4,8 @@ export const setDateTimeValue = (
callService: HomeAssistantApi["callService"],
entityId: string,
datetime: Date
) => {
) =>
callService("datetime", "set_value", {
entity_id: entityId,
datetime: datetime.toISOString(),
});
};
+2 -1
View File
@@ -38,7 +38,8 @@ export const setInputDateTimeValue = (
date: string | undefined = undefined
) => {
const param = { entity_id: entityId, time, date };
callService("input_datetime", "set_datetime", param);
return callService("input_datetime", "set_datetime", param);
};
export const fetchInputDateTime = (hass: HomeAssistant) =>
+6
View File
@@ -88,6 +88,7 @@ export type Selector =
| SerialPortSelector
| UiActionSelector
| UiClockDateFormatSelector
| UiClockTimeFormatSelector
| UiColorSelector
| UiConditionSelector
| UiStateContentSelector
@@ -669,6 +670,11 @@ export interface UiClockDateFormatSelector {
ui_clock_date_format: {} | null;
}
// 12 or 24 hour clock, as a TimeFormat. Undefined follows the user's setting.
export interface UiClockTimeFormatSelector {
ui_clock_time_format: {} | null;
}
export interface UiColorExtraOption {
value: string;
label: string;
+2 -1
View File
@@ -6,5 +6,6 @@ export const setTimeValue = (
time: string | undefined = undefined
) => {
const param = { entity_id: entityId, time: time };
callService("time", "set_value", param);
return callService("time", "set_value", param);
};
@@ -28,6 +28,7 @@ import {
} from "../../../common/integrations/protocolIntegrationPicked";
import { navigate } from "../../../common/navigate";
import { caseInsensitiveStringCompare } from "../../../common/string/compare";
import { nextRender } from "../../../common/util/render-status";
import type {
LocalizeFunc,
LocalizeKeys,
@@ -109,6 +110,7 @@ import {
} from "./add-integration-list";
import "./ha-integration-list-item";
import "./ha-integration-list-title";
import type { HaDomainIntegrations } from "./ha-domain-integrations";
import type { HaIntegrationListItem } from "./ha-integration-list-item";
import type { AddIntegrationDialogParams } from "./show-add-integration-dialog";
import { showYamlIntegrationDialog } from "./show-add-integration-dialog";
@@ -169,6 +171,9 @@ class AddIntegrationDialog extends LitElement {
@state() private _showDiscovered = false;
// The discovered devices of one integration
@state() private _discoveredDomain?: string;
@state() private _openedDirectly = false;
@state() private _navigateToResult = false;
@@ -186,6 +191,9 @@ class AddIntegrationDialog extends LitElement {
@query("ha-input-search") private _searchInput?: HaInputSearch;
@query("ha-domain-integrations")
private _domainIntegrations?: HaDomainIntegrations;
// The focused row is gone after drilling
private _focusAfterDrill?: "in" | "out";
@@ -274,6 +282,7 @@ class AddIntegrationDialog extends LitElement {
this._prevPickedBrand = undefined;
this._flowsInProgress = undefined;
this._showDiscovered = false;
this._discoveredDomain = undefined;
this._openedDirectly = false;
this._navigateToResult = false;
this._filter = undefined;
@@ -900,24 +909,47 @@ class AddIntegrationDialog extends LitElement {
findIntegration(this._integrations, this._pickedBrand)
: undefined;
const showingPickedBrand = Boolean(
this._pickedBrand && (!this._integrations || pickedIntegration)
);
const showingDiscoveredGroup =
!showingPickedBrand && !!this._discoveredDomain;
const showingBrandView =
(this._pickedBrand && (!this._integrations || pickedIntegration)) ||
this._showDiscovered;
showingPickedBrand || showingDiscoveredGroup || this._showDiscovered;
const flowsInProgress = showingBrandView
? this._getFlowsForCurrentView(pickedIntegration)
: [];
const brandDomain = showingPickedBrand
? this._pickedBrand
: showingDiscoveredGroup
? this._discoveredDomain
: undefined;
const brandIntegration = showingPickedBrand
? pickedIntegration
: showingDiscoveredGroup
? findIntegration(this._integrations, this._discoveredDomain!)
: undefined;
const headerTitle = showingBrandView
? this._getBrandHeading(pickedIntegration, flowsInProgress)
: this._narrow && this._drilled
? this._browsingTitle()
: this.hass.localize(
"ui.panel.config.integrations.add_device_or_integration"
);
const flowsInProgress = showingPickedBrand
? this._getFlowsForBrand(pickedIntegration)
: showingDiscoveredGroup
? this._getFlowsForDiscoveredGroup(this._discoveredDomain!)
: this._showDiscovered
? this._flowsInProgress || []
: [];
const headerSubtitle =
!showingBrandView && this._narrow && this._drilled
const headerTitle = showingDiscoveredGroup
? brandIntegration?.name ||
domainToName(this.hass.localize, this._discoveredDomain!)
: showingBrandView
? this._getBrandHeading(pickedIntegration, flowsInProgress)
: this._narrow && this._drilled
? this._browsingTitle()
: this.hass.localize(
"ui.panel.config.integrations.add_device_or_integration"
);
const headerSubtitle = showingDiscoveredGroup
? this.hass.localize("ui.panel.config.integrations.discovered")
: !showingBrandView && this._narrow && this._drilled
? this._subcategory
? integrationCategoryName(this.hass.localize, this._category!)
: this.hass.localize(
@@ -938,7 +970,7 @@ class AddIntegrationDialog extends LitElement {
showingBrandView
? html`
${
!this._openedDirectly
!this._openedDirectly || this._discoveredDomain
? html`
<ha-icon-button-prev
slot="headerNavigationIcon"
@@ -947,7 +979,12 @@ class AddIntegrationDialog extends LitElement {
`
: nothing
}
${this._renderBrandView(pickedIntegration, flowsInProgress)}
${this._renderBrandView(
brandDomain,
brandIntegration,
flowsInProgress,
!showingPickedBrand && !showingDiscoveredGroup
)}
`
: html`
${
@@ -991,13 +1028,15 @@ class AddIntegrationDialog extends LitElement {
);
}
private _getFlowsForCurrentView(
private _getFlowsForDiscoveredGroup(domain: string) {
return (this._flowsInProgress || []).filter(
(flow) => flow.handler === domain
);
}
private _getFlowsForBrand(
integration: Brand | Integration | undefined
): DataEntryFlowProgress[] {
if (this._showDiscovered) {
// Show all discovered flows
return this._flowsInProgress || [];
}
if (!this._pickedBrand || !integration) {
return [];
}
@@ -1044,23 +1083,39 @@ class AddIntegrationDialog extends LitElement {
}
private _renderBrandView(
domain: string | undefined,
integration: Brand | Integration | undefined,
flowsInProgress: DataEntryFlowProgress[]
flowsInProgress: DataEntryFlowProgress[],
groupFlows: boolean
): TemplateResult {
return html`<ha-domain-integrations
.hass=${this.hass}
.domain=${this._pickedBrand}
.domain=${domain}
.integration=${integration}
.flowsInProgress=${flowsInProgress}
.navigateToResult=${this._navigateToResult}
.showManageLink=${this._showDiscovered || this._showDiscoveredView}
.boxed=${!integration}
.groupFlows=${groupFlows}
.brands=${this._integrations}
@close-dialog=${this.closeDialog}
@supported-by=${this._handleSupportedByEvent}
@select-brand=${this._handleSelectBrandEvent}
@discovered-group-picked=${this._handleDiscoveredGroupPicked}
></ha-domain-integrations>`;
}
private async _handleDiscoveredGroupPicked(
ev: HASSDomEvent<HASSDomEvents["discovered-group-picked"]>
) {
this._discoveredDomain = ev.detail.domain;
// The picked row is gone, and the back button renders after this element
await nextRender();
if (this._discoveredDomain) {
this._backButton?.focus();
}
}
private _handleSelectBrandEvent(ev: CustomEvent) {
this._prevPickedBrand = this._pickedBrand;
this._pickedBrand = ev.detail.brand;
@@ -1178,7 +1233,12 @@ class AddIntegrationDialog extends LitElement {
${
this._showDiscoveredView && !this._filter
? html`<div class="discovered">
${this._renderBrandView(undefined, this._flowsInProgress || [])}
${this._renderBrandView(
undefined,
undefined,
this._flowsInProgress || [],
true
)}
</div>`
: rows
? html`${
@@ -2063,12 +2123,25 @@ class AddIntegrationDialog extends LitElement {
}
private _prevClicked() {
if (this._showDiscovered) {
this._showDiscovered = false;
if (this._pickedBrand) {
this._pickedBrand = this._prevPickedBrand;
this._prevPickedBrand = undefined;
return;
}
this._pickedBrand = this._prevPickedBrand;
this._prevPickedBrand = undefined;
if (this._discoveredDomain) {
const domain = this._discoveredDomain;
this._discoveredDomain = undefined;
this._focusFlowGroupAfterBack(domain);
return;
}
this._showDiscovered = false;
}
private async _focusFlowGroupAfterBack(domain: string) {
await nextRender();
if (this._open && !this._discoveredDomain) {
this._domainIntegrations?.focusFlowGroup(domain);
}
}
static styles = [
@@ -1,7 +1,8 @@
import "@home-assistant/webawesome/dist/components/divider/divider";
import { mdiPlus } from "@mdi/js";
import type { TemplateResult } from "lit";
import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators";
import { customElement, property, queryAll } from "lit/decorators";
import { isComponentLoaded } from "../../../common/config/is_component_loaded";
import type { HASSDomCurrentTargetEvent } from "../../../common/dom/fire_event";
import { fireEvent } from "../../../common/dom/fire_event";
@@ -13,8 +14,10 @@ import {
import { navigate } from "../../../common/navigate";
import { caseInsensitiveStringCompare } from "../../../common/string/compare";
import "../../../components/ha-button";
import "../../../components/ha-icon-next";
import "../../../components/ha-svg-icon";
import "../../../components/item/ha-list-item-button";
import type { HaListItemButton } from "../../../components/item/ha-list-item-button";
import "../../../components/list/ha-list-base";
import { localizeConfigFlowTitle } from "../../../data/config_flow";
import type { DataEntryFlowProgress } from "../../../data/data_entry_flow";
@@ -22,7 +25,8 @@ import {
domainToName,
fetchIntegrationManifest,
} from "../../../data/integration";
import type { Brand, Integration } from "../../../data/integrations";
import type { Brand, Brands, Integration } from "../../../data/integrations";
import { findIntegration } from "../../../data/integrations";
import { showConfigFlowDialog } from "../../../dialogs/config-flow/show-dialog-config-flow";
import { haStyle } from "../../../resources/styles";
import type { HomeAssistant } from "../../../types";
@@ -33,7 +37,7 @@ import { showYamlIntegrationDialog } from "./show-add-integration-dialog";
export const standardToDomain = { zigbee: "zha", zwave: "zwave_js" } as const;
@customElement("ha-domain-integrations")
class HaDomainIntegrations extends LitElement {
export class HaDomainIntegrations extends LitElement {
public hass!: HomeAssistant;
@property() public domain!: string;
@@ -51,6 +55,15 @@ class HaDomainIntegrations extends LitElement {
@property({ type: Boolean, reflect: true }) public boxed = false;
/** An integration with more than one discovered device gets one row. */
@property({ attribute: false }) public groupFlows = false;
/** Names integrations that have no translated title, like most that aren't set up. */
@property({ attribute: false }) public brands?: Brands;
@queryAll("ha-list-item-button.flow-group")
private _flowGroups!: NodeListOf<HaListItemButton & { domain: string }>;
protected render() {
// Only show manage link if not already on the integrations dashboard
const manage =
@@ -63,36 +76,11 @@ class HaDomainIntegrations extends LitElement {
? html`<h3>
${this.hass.localize("ui.panel.config.integrations.discovered")}
</h3>
${this.flowsInProgress.map(
(flow) =>
html`<ha-list-item-button
.flow=${flow}
@click=${this._flowInProgressPicked}
>
<img
alt=""
slot="start"
loading="lazy"
src=${brandsUrl(
{
domain: flow.handler,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<span slot="headline"
>${localizeConfigFlowTitle(this.hass.localize, flow)}</span
>
<span slot="supporting-text"
>${domainToName(this.hass.localize, flow.handler)}</span
>
<ha-svg-icon slot="end" .path=${mdiPlus}></ha-svg-icon>
</ha-list-item-button>`
)}
${
this.groupFlows
? this._renderFlowGroups(this.flowsInProgress)
: this.flowsInProgress.map((flow) => this._renderFlow(flow))
}
<wa-divider></wa-divider>
${
this.integration &&
@@ -303,6 +291,87 @@ class HaDomainIntegrations extends LitElement {
</div>`;
}
public async focusFlowGroup(domain: string) {
await this.updateComplete;
[...this._flowGroups].find((row) => row.domain === domain)?.focus();
}
private _renderFlowGroups(flows: DataEntryFlowProgress[]) {
const groups = new Map<string, DataEntryFlowProgress[]>();
flows.forEach((flow) => {
groups.set(flow.handler, [...(groups.get(flow.handler) || []), flow]);
});
if (groups.size === 1) {
return flows.map((flow) => this._renderFlow(flow));
}
return [...groups.entries()].map(([domain, group]) =>
group.length === 1
? this._renderFlow(group[0])
: html`<ha-list-item-button
class="flow-group"
.domain=${domain}
@click=${this._flowGroupPicked}
>
${this._renderIcon(domain)}
<span slot="headline">${this._domainName(domain)}</span>
<span slot="supporting-text"
>${this.hass.localize(
"ui.panel.config.integrations.discovered_devices",
{ count: group.length }
)}</span
>
<ha-icon-next slot="end"></ha-icon-next>
</ha-list-item-button>`
);
}
private _renderFlow(flow: DataEntryFlowProgress) {
return html`<ha-list-item-button
.flow=${flow}
@click=${this._flowInProgressPicked}
>
${this._renderIcon(flow.handler)}
<span slot="headline"
>${localizeConfigFlowTitle(this.hass.localize, flow)}</span
>
<span slot="supporting-text">${this._domainName(flow.handler)}</span>
<ha-svg-icon slot="end" .path=${mdiPlus}></ha-svg-icon>
</ha-list-item-button>`;
}
private _domainName(domain: string) {
return (
findIntegration(this.brands, domain)?.name ||
domainToName(this.hass.localize, domain)
);
}
private _renderIcon(domain: string): TemplateResult {
return html`<img
alt=""
slot="start"
loading="lazy"
src=${brandsUrl(
{
domain,
type: "icon",
darkOptimized: this.hass.themes?.darkMode,
},
this.hass.auth.data.hassUrl
)}
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>`;
}
private _flowGroupPicked(
ev: HASSDomCurrentTargetEvent<HTMLElement & { domain: string }>
) {
fireEvent(this, "discovered-group-picked", {
domain: ev.currentTarget.domain,
});
}
private async _integrationPicked(
ev: HASSDomCurrentTargetEvent<HTMLElement & { domain: string }>
) {
@@ -496,4 +565,8 @@ declare global {
interface HTMLElementTagNameMap {
"ha-domain-integrations": HaDomainIntegrations;
}
interface HASSDomEvents {
"discovered-group-picked": { domain: string };
}
}
@@ -0,0 +1,477 @@
import { TZDate } from "@date-fns/tz";
import type { HassEntity } from "home-assistant-js-websocket";
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 { consume } from "../../../common/decorators/consume";
import {
consumeEntityState,
consumeLocalize,
} from "../../../common/decorators/consume-context-entry";
import { transform } from "../../../common/decorators/transform";
import { resolveTimeZone } from "../../../common/datetime/resolve-time-zone";
import { useAmPm } from "../../../common/datetime/use_am_pm";
import { computeDomain } from "../../../common/entity/compute_domain";
import type { LocalizeFunc } from "../../../common/translations/localize";
import "../../../components/ha-control-select-menu";
import type { SelectOption } from "../../../components/ha-control-select-menu";
import type { HaDropdownSelectEvent } from "../../../components/ha-dropdown";
import {
apiContext,
configContext,
internationalizationContext,
} from "../../../data/context";
import { setDateTimeValue } from "../../../data/datetime";
import { UNAVAILABLE, UNKNOWN } from "../../../data/entity/entity";
import { setInputDateTimeValue } from "../../../data/input_datetime";
import { setTimeValue } from "../../../data/time";
import type { FrontendLocaleData, TimeFormat } from "../../../data/translation";
import type {
HomeAssistant,
HomeAssistantApi,
HomeAssistantConfig,
HomeAssistantInternationalization,
} from "../../../types";
import type { LovelaceCardFeature, LovelaceCardFeatureEditor } from "../types";
import { cardFeatureStyles } from "./common/card-feature-styles";
import type {
LovelaceCardFeatureContext,
TimeSetCardFeatureConfig,
} from "./types";
interface TimeParts {
hours: number;
minutes: number;
seconds: number;
}
type Period = "AM" | "PM";
const TIME_REGEX = /^(\d{1,2}):(\d{2})(?::(\d{2}))?/;
const supportsTimeSetCardFeatureFromState = (stateObj: HassEntity) => {
const domain = computeDomain(stateObj.entity_id);
return (
domain === "time" ||
domain === "datetime" ||
(domain === "input_datetime" && Boolean(stateObj.attributes.has_time))
);
};
export const supportsTimeSetCardFeature = (
hass: HomeAssistant,
context: LovelaceCardFeatureContext
) => {
const stateObj = context.entity_id
? hass.states[context.entity_id]
: undefined;
if (!stateObj) return false;
return supportsTimeSetCardFeatureFromState(stateObj);
};
// A datetime is shown in the time zone picked in the user's profile, like the
// tile's state, so the time is read and changed in that time zone too.
const toZonedDate = (value: string, timeZone?: string): Date => {
const date = new Date(value);
if (!timeZone) {
return date;
}
const zoned = new TZDate(date, timeZone);
// TZDate is invalid where Intl lacks "longOffset" (Chrome < 95, Safari < 15.4)
return isNaN(zoned.getHours()) ? date : zoned;
};
const parseTime = (
stateObj: HassEntity,
timeZone?: string
): TimeParts | undefined => {
if (stateObj.state === UNKNOWN || stateObj.state === UNAVAILABLE) {
return undefined;
}
if (computeDomain(stateObj.entity_id) === "datetime") {
const dateObj = toZonedDate(stateObj.state, timeZone);
if (isNaN(dateObj.getTime())) {
return undefined;
}
return {
hours: dateObj.getHours(),
minutes: dateObj.getMinutes(),
seconds: dateObj.getSeconds(),
};
}
// input_datetime with a date has a "YYYY-MM-DD HH:MM:SS" state
const match = TIME_REGEX.exec(stateObj.state.split(" ").pop() ?? "");
if (!match) {
return undefined;
}
return {
hours: Number(match[1]),
minutes: Number(match[2]),
seconds: match[3] ? Number(match[3]) : 0,
};
};
const pad = (value: number) => value.toString().padStart(2, "0");
// Seconds are kept as they are, so a time is matched on hours and minutes
const timeKey = (time: TimeParts) => `${time.hours}:${time.minutes}`;
// Each write has its own id, as the same time can be sent more than once
interface Write {
id: number;
key: string;
}
const MINUTE_OPTIONS: SelectOption[] = Array.from({ length: 60 }, (_, i) => ({
value: i.toString(),
label: pad(i),
}));
const HOUR_OPTIONS_24: SelectOption[] = Array.from({ length: 24 }, (_, i) => ({
value: i.toString(),
label: pad(i),
}));
const HOUR_OPTIONS_12: SelectOption[] = [
12,
...Array.from({ length: 11 }, (_, i) => i + 1),
].map((hour) => ({ value: hour.toString(), label: hour.toString() }));
@customElement("hui-time-set-card-feature")
class HuiTimeSetCardFeature extends LitElement implements LovelaceCardFeature {
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
@state()
@consumeEntityState({ entityIdPath: ["context", "entity_id"] })
private _stateObj?: HassEntity;
@state()
@consumeLocalize()
private _localize!: LocalizeFunc;
@state()
@consume({ context: internationalizationContext, subscribe: true })
@transform<HomeAssistantInternationalization, FrontendLocaleData>({
transformer: ({ locale }) => locale,
})
private _locale?: FrontendLocaleData;
@state()
@consume({ context: configContext, subscribe: true })
@transform<HomeAssistantConfig, string>({
transformer: ({ config }) => config.time_zone,
})
private _serverTimeZone?: string;
@consume({ context: apiContext, subscribe: true })
private _api!: HomeAssistantApi;
@state() private _config?: TimeSetCardFeatureConfig;
// The newest selection and the write that sent it, shown instead of the
// entity's time until every write is confirmed, so reports from earlier
// writes don't overwrite it
@state() private _selection?: {
entityId: string;
time: TimeParts;
writeId: number;
};
// Writes the entity hasn't reported back yet, oldest first
private _unconfirmed: Write[] = [];
private _nextWriteId = 0;
// The entity and time last reported, to skip updates that don't change it
private _reported?: string;
private get _timeZone(): string | undefined {
return this._locale && this._serverTimeZone
? resolveTimeZone(this._locale.time_zone, this._serverTimeZone)
: undefined;
}
static getStubConfig(): TimeSetCardFeatureConfig {
return {
type: "time-set",
};
}
public static async getConfigElement(): Promise<LovelaceCardFeatureEditor> {
await import("../editor/config-elements/hui-time-set-card-feature-editor");
return document.createElement("hui-time-set-card-feature-editor");
}
public setConfig(config: TimeSetCardFeatureConfig): void {
if (!config) {
throw new Error("Invalid configuration");
}
this._config = config;
}
protected willUpdate(changedProps: PropertyValues): void {
super.willUpdate(changedProps);
if (!changedProps.has("_stateObj") || !this._stateObj) {
return;
}
const current = parseTime(this._stateObj, this._timeZone);
const key = current ? timeKey(current) : undefined;
const reported = `${this._stateObj.entity_id} ${key}`;
if (reported === this._reported) {
return;
}
this._reported = reported;
if (!this._selection) {
return;
}
// Home Assistant applies writes in order, so a report confirms the oldest
// unconfirmed write with that time, and any written before it
const index = key
? this._unconfirmed.findIndex((write) => write.key === key)
: -1;
this._unconfirmed = index === -1 ? [] : this._unconfirmed.slice(index + 1);
// Once every write is confirmed, or the time changed elsewhere, show the
// entity's time
if (this._unconfirmed.length === 0) {
this._selection = undefined;
}
}
// Worked out from the current entity on each use, as the entity can change
// after willUpdate when the card switches to another one
private get _time(): TimeParts | undefined {
if (!this._stateObj) {
return undefined;
}
return this._selection?.entityId === this._stateObj.entity_id
? this._selection.time
: parseTime(this._stateObj, this._timeZone);
}
private _useAmPm = memoizeOne(
(locale: FrontendLocaleData, timeFormat?: TimeFormat) =>
useAmPm(timeFormat ? { ...locale, time_format: timeFormat } : locale)
);
private _periodOptions = memoizeOne((language: string): SelectOption[] => {
const formatter = new Intl.DateTimeFormat(language, {
hour: "numeric",
hourCycle: "h12",
});
const periodLabel = (hours: number, fallback: Period) =>
formatter
.formatToParts(new Date(2000, 0, 1, hours))
.find((part) => part.type === "dayPeriod")?.value ?? fallback;
return [
{ value: "AM", label: periodLabel(0, "AM") },
{ value: "PM", label: periodLabel(12, "PM") },
];
});
private _hourSelected(ev: HaDropdownSelectEvent): void {
const hour = Number(ev.detail.item.value);
if (
!this._locale ||
!this._useAmPm(this._locale, this._config?.time_format)
) {
this._setTime({ hours: hour });
return;
}
const isPm = (this._time?.hours ?? 0) >= 12;
this._setTime({ hours: (hour % 12) + (isPm ? 12 : 0) });
}
private _minuteSelected(ev: HaDropdownSelectEvent): void {
this._setTime({ minutes: Number(ev.detail.item.value) });
}
private _periodSelected(ev: HaDropdownSelectEvent<Period>): void {
const hours = (this._time?.hours ?? 0) % 12;
this._setTime({
hours: ev.detail.item.value === "PM" ? hours + 12 : hours,
});
}
private async _setTime(change: Partial<TimeParts>) {
if (!this._stateObj) return;
const stateObj = this._stateObj;
const oldTime = this._time;
const time: TimeParts = {
hours: 0,
minutes: 0,
seconds: 0,
...oldTime,
...change,
};
if (
oldTime &&
time.hours === oldTime.hours &&
time.minutes === oldTime.minutes
) {
return;
}
const writeId = this._nextWriteId++;
this._selection = { entityId: stateObj.entity_id, time, writeId };
this._unconfirmed = [
...this._unconfirmed,
{ id: writeId, key: timeKey(time) },
];
const domain = computeDomain(stateObj.entity_id);
const value = `${pad(time.hours)}:${pad(time.minutes)}:${pad(time.seconds)}`;
try {
if (domain === "datetime") {
const dateObj = toZonedDate(stateObj.state, this._timeZone);
dateObj.setHours(time.hours, time.minutes, time.seconds);
await setDateTimeValue(
this._api.callService,
stateObj.entity_id,
new Date(dateObj.getTime())
);
} else if (domain === "input_datetime") {
await setInputDateTimeValue(
this._api.callService,
stateObj.entity_id,
value,
stateObj.attributes.has_date
? stateObj.state.split(" ")[0]
: undefined
);
} else {
await setTimeValue(this._api.callService, stateObj.entity_id, value);
}
} catch {
this._unconfirmed = this._unconfirmed.filter(
(write) => write.id !== writeId
);
// When the write behind the shown selection fails, show the entity's
// time again
if (this._selection?.writeId === writeId) {
this._selection = undefined;
}
}
}
protected render() {
if (
!this._config ||
!this.context ||
!this._stateObj ||
!this._locale ||
!supportsTimeSetCardFeatureFromState(this._stateObj)
) {
return nothing;
}
const disabled = [UNAVAILABLE, UNKNOWN].includes(this._stateObj.state);
const useAMPM = this._useAmPm(this._locale, this._config.time_format);
const time = this._time;
const hour = time
? (useAMPM ? time.hours % 12 || 12 : time.hours).toString()
: undefined;
return html`
<ha-control-select-menu
?hide-label=${hour !== undefined}
.label=${this._localize("ui.card.time.hour")}
.value=${hour}
.options=${useAMPM ? HOUR_OPTIONS_12 : HOUR_OPTIONS_24}
.disabled=${disabled}
@wa-select=${this._hourSelected}
></ha-control-select-menu>
<span class="separator" aria-hidden="true">:</span>
<ha-control-select-menu
?hide-label=${time !== undefined}
.label=${this._localize("ui.card.time.minute")}
.value=${time?.minutes.toString()}
.options=${MINUTE_OPTIONS}
.disabled=${disabled}
@wa-select=${this._minuteSelected}
></ha-control-select-menu>
${
useAMPM
? html`
<ha-control-select-menu
?hide-label=${time !== undefined}
.label=${this._localize("ui.card.time.period")}
.value=${time ? (time.hours >= 12 ? "PM" : "AM") : undefined}
.options=${this._periodOptions(this._locale.language)}
.disabled=${disabled}
@wa-select=${this._periodSelected}
></ha-control-select-menu>
`
: nothing
}
`;
}
static styles = [
cardFeatureStyles,
css`
:host {
display: flex;
align-items: center;
gap: var(--ha-space-1);
/* Times read hour first in every language, like ha-base-time-input */
direction: ltr;
}
ha-control-select-menu {
flex: 1;
min-width: 0;
/* Leave room for "12" or "PM" when the card is narrow */
--control-select-menu-padding: 6px var(--ha-space-1);
}
.separator {
color: var(--secondary-text-color);
font-size: var(--ha-font-size-l);
}
`,
];
}
declare global {
interface HTMLElementTagNameMap {
"hui-time-set-card-feature": HuiTimeSetCardFeature;
}
}
@@ -41,6 +41,7 @@ import { supportsSelectOptionsCardFeature } from "./hui-select-options-card-feat
import { supportsTemperatureForecastCardFeature } from "./hui-temperature-forecast-card-feature";
import { supportsTargetHumidityCardFeature } from "./hui-target-humidity-card-feature";
import { supportsTargetTemperatureCardFeature } from "./hui-target-temperature-card-feature";
import { supportsTimeSetCardFeature } from "./hui-time-set-card-feature";
import { supportsTimerActionsCardFeature } from "./hui-timer-actions-card-feature";
import { supportsTimerPresetsCardFeature } from "./hui-timer-presets-card-feature";
import { supportsTimerProgressCardFeature } from "./hui-timer-progress-card-feature";
@@ -109,6 +110,7 @@ export const UI_FEATURE_TYPES = [
"trend-graph",
"target-humidity",
"target-temperature",
"time-set",
"timer-actions",
"timer-presets",
"timer-progress",
@@ -169,6 +171,7 @@ export const SUPPORTS_FEATURE_TYPES: Record<UiFeatureType, SupportsFeature> = {
"target-humidity": supportsTargetHumidityCardFeature,
"target-temperature": supportsTargetTemperatureCardFeature,
"temperature-forecast": supportsTemperatureForecastCardFeature,
"time-set": supportsTimeSetCardFeature,
"timer-actions": supportsTimerActionsCardFeature,
"timer-presets": supportsTimerPresetsCardFeature,
"timer-progress": supportsTimerProgressCardFeature,
@@ -1,6 +1,7 @@
import type { AlarmMode } from "../../../data/alarm_control_panel";
import type { HvacMode } from "../../../data/climate";
import type { FanSpeedStyle } from "../../../data/fan";
import type { TimeFormat } from "../../../data/translation";
import type { OperationMode } from "../../../data/water_heater";
import type { ForecastPrecipitationType } from "../../../data/weather";
@@ -213,6 +214,11 @@ export interface TargetTemperatureCardFeatureConfig {
style?: "buttons" | "slider";
}
export interface TimeSetCardFeatureConfig {
type: "time-set";
time_format?: TimeFormat;
}
export interface ToggleCardFeatureConfig {
type: "toggle";
}
@@ -408,6 +414,7 @@ export type LovelaceCardFeatureConfig =
| TrendGraphCardFeatureConfig
| TargetHumidityCardFeatureConfig
| TargetTemperatureCardFeatureConfig
| TimeSetCardFeatureConfig
| TimerActionsCardFeatureConfig
| TimerPresetsCardFeatureConfig
| TimerProgressCardFeatureConfig
@@ -19,6 +19,14 @@ const NUMERIC_INPUT_VARIANTS: TileVariant[] = [TILE_VARIANT, ["numeric-input"]];
const DATE_VARIANTS: TileVariant[] = [TILE_VARIANT, ["date-set"]];
const TIME_VARIANTS: TileVariant[] = [TILE_VARIANT, ["time-set"]];
const DATETIME_VARIANTS: TileVariant[] = [
TILE_VARIANT,
["date-set"],
["time-set"],
];
const BUTTON_VARIANTS: TileVariant[] = [TILE_VARIANT, ["button"]];
const DOMAIN_VARIANTS: Record<string, TileVariant[]> = {
@@ -89,15 +97,16 @@ const DOMAIN_VARIANTS: Record<string, TileVariant[]> = {
select: SELECT_VARIANTS,
input_number: NUMERIC_INPUT_VARIANTS,
number: NUMERIC_INPUT_VARIANTS,
input_datetime: DATE_VARIANTS,
input_datetime: DATETIME_VARIANTS,
date: DATE_VARIANTS,
time: TIME_VARIANTS,
update: [TILE_VARIANT, ["update-actions"]],
water_heater: [
TILE_VARIANT,
["water-heater-operation-modes"],
["target-temperature"],
],
datetime: DATE_VARIANTS,
datetime: DATETIME_VARIANTS,
button: BUTTON_VARIANTS,
input_button: BUTTON_VARIANTS,
scene: BUTTON_VARIANTS,
@@ -36,6 +36,7 @@ import "../card-features/hui-numeric-input-card-feature";
import "../card-features/hui-select-options-card-feature";
import "../card-features/hui-target-humidity-card-feature";
import "../card-features/hui-target-temperature-card-feature";
import "../card-features/hui-time-set-card-feature";
import "../card-features/hui-timer-actions-card-feature";
import "../card-features/hui-timer-presets-card-feature";
import "../card-features/hui-timer-progress-card-feature";
@@ -103,6 +104,7 @@ const TYPES = new Set<LovelaceCardFeatureConfig["type"]>([
"target-humidity",
"target-temperature",
"temperature-forecast",
"time-set",
"timer-actions",
"timer-presets",
"timer-progress",
@@ -65,6 +65,7 @@ import { supportsNumericInputCardFeature } from "../../card-features/hui-numeric
import { supportsSelectOptionsCardFeature } from "../../card-features/hui-select-options-card-feature";
import { supportsTargetHumidityCardFeature } from "../../card-features/hui-target-humidity-card-feature";
import { supportsTargetTemperatureCardFeature } from "../../card-features/hui-target-temperature-card-feature";
import { supportsTimeSetCardFeature } from "../../card-features/hui-time-set-card-feature";
import { supportsTimerActionsCardFeature } from "../../card-features/hui-timer-actions-card-feature";
import { supportsTimerPresetsCardFeature } from "../../card-features/hui-timer-presets-card-feature";
import { supportsTimerProgressCardFeature } from "../../card-features/hui-timer-progress-card-feature";
@@ -135,6 +136,7 @@ const UI_FEATURE_TYPES = [
"target-humidity",
"target-temperature",
"temperature-forecast",
"time-set",
"timer-actions",
"timer-presets",
"timer-progress",
@@ -181,6 +183,7 @@ const EDITABLES_FEATURE_TYPES = new Set<UiFeatureTypes>([
"select-options",
"target-humidity",
"target-temperature",
"time-set",
"timer-actions",
"timer-presets",
"trend-graph",
@@ -239,6 +242,7 @@ const SUPPORTS_FEATURE_TYPES: Record<
"target-humidity": supportsTargetHumidityCardFeature,
"target-temperature": supportsTargetTemperatureCardFeature,
"temperature-forecast": supportsTemperatureForecastCardFeature,
"time-set": supportsTimeSetCardFeature,
"timer-actions": supportsTimerActionsCardFeature,
"timer-presets": supportsTimerPresetsCardFeature,
"timer-progress": supportsTimerProgressCardFeature,
@@ -63,10 +63,6 @@ const cardConfigStruct = assign(
})
);
type ClockCardFormData = Omit<ClockCardConfig, "time_format"> & {
time_format?: ClockCardConfig["time_format"] | "auto";
};
@customElement("hui-clock-card-editor")
export class HuiClockCardEditor
extends LitElement
@@ -125,15 +121,7 @@ export class HuiClockCardEditor
value: "digital",
},
selector: {
select: {
mode: "dropdown",
options: ["auto", ...Object.values(TimeFormat)].map((value) => ({
value,
label: localize(
`ui.panel.lovelace.editor.card.clock.time_formats.${value}`
),
})),
},
ui_clock_time_format: {},
},
},
{
@@ -231,14 +219,13 @@ export class HuiClockCardEditor
] as const satisfies readonly HaFormSchema[]
);
private _data = memoizeOne((config: ClockCardConfig): ClockCardFormData => {
private _data = memoizeOne((config: ClockCardConfig): ClockCardConfig => {
const dateConfig = getClockCardDateConfig(config);
const data: ClockCardFormData = {
const data: ClockCardConfig = {
...config,
clock_style: config.clock_style ?? "digital",
clock_size: config.clock_size ?? "small",
time_format: config.time_format ?? "auto",
show_seconds: config.show_seconds ?? false,
no_background: config.no_background ?? false,
// Analog clock options
@@ -275,14 +262,14 @@ export class HuiClockCardEditor
`;
}
private _valueChanged(ev: ValueChangedEvent<ClockCardFormData>): void {
private _valueChanged(ev: ValueChangedEvent<ClockCardConfig>): void {
const config = ev.detail.value;
if (!config.date_format || config.date_format.length === 0) {
delete config.date_format;
}
if (config.time_format === "auto") {
if (!config.time_format) {
delete config.time_format;
}
@@ -0,0 +1,76 @@
import { html, LitElement, nothing } from "lit";
import { customElement, property, state } from "lit/decorators";
import { fireEvent } from "../../../../common/dom/fire_event";
import "../../../../components/ha-form/ha-form";
import type {
HaFormSchema,
SchemaUnion,
} from "../../../../components/ha-form/types";
import type { HomeAssistant, ValueChangedEvent } from "../../../../types";
import type {
LovelaceCardFeatureContext,
TimeSetCardFeatureConfig,
} from "../../card-features/types";
import type { LovelaceCardFeatureEditor } from "../../types";
const SCHEMA = [
{
name: "time_format",
selector: {
ui_clock_time_format: {},
},
},
] as const satisfies readonly HaFormSchema[];
@customElement("hui-time-set-card-feature-editor")
export class HuiTimeSetCardFeatureEditor
extends LitElement
implements LovelaceCardFeatureEditor
{
@property({ attribute: false }) public hass?: HomeAssistant;
@property({ attribute: false }) public context?: LovelaceCardFeatureContext;
@state() private _config?: TimeSetCardFeatureConfig;
public setConfig(config: TimeSetCardFeatureConfig): void {
this._config = config;
}
protected render() {
if (!this.hass || !this._config) {
return nothing;
}
return html`
<ha-form
.hass=${this.hass}
.data=${this._config}
.schema=${SCHEMA}
.computeLabel=${this._computeLabelCallback}
@value-changed=${this._valueChanged}
></ha-form>
`;
}
private _valueChanged(ev: ValueChangedEvent<TimeSetCardFeatureConfig>) {
const { time_format, ...rest } = ev.detail.value;
const config: TimeSetCardFeatureConfig = time_format
? { ...rest, time_format }
: rest;
fireEvent(this, "config-changed", { config });
}
private _computeLabelCallback = (schema: SchemaUnion<typeof SCHEMA>) =>
this.hass!.localize(
`ui.panel.lovelace.editor.features.types.time-set.${schema.name}`
);
}
declare global {
interface HTMLElementTagNameMap {
"hui-time-set-card-feature-editor": HuiTimeSetCardFeatureEditor;
}
}
+19 -7
View File
@@ -340,6 +340,11 @@
"text": {
"empty_value": "(empty value)"
},
"time": {
"hour": "Hour",
"minute": "Minute",
"period": "AM or PM"
},
"timer": {
"actions": {
"start": "Start",
@@ -948,6 +953,15 @@
},
"style": "Time format style"
},
"clock-time-format-picker": {
"auto": "Use user settings",
"formats": {
"language": "[%key:ui::panel::profile::time_format::formats::language%]",
"system": "[%key:ui::panel::profile::time_format::formats::system%]",
"24": "[%key:ui::panel::profile::time_format::formats::24%]",
"12": "[%key:ui::panel::profile::time_format::formats::12%]"
}
},
"filter-entity-types": {
"caption": "Type",
"no_device_class": "No type",
@@ -8130,6 +8144,7 @@
"description": "Manage integrations with services or devices",
"integration": "integration",
"discovered": "Discovered",
"discovered_devices": "{count} {count, plural,\n one {device}\n other {devices}\n}",
"manage_discovered": "Manage discovered devices",
"manage_discovered_description": "Ignore or configure previously discovered devices",
"disabled": "Disabled",
@@ -11976,13 +11991,6 @@
}
},
"time_format": "[%key:ui::panel::profile::time_format::dropdown_label%]",
"time_formats": {
"auto": "Use user settings",
"language": "[%key:ui::panel::profile::time_format::formats::language%]",
"system": "[%key:ui::panel::profile::time_format::formats::system%]",
"24": "[%key:ui::panel::profile::time_format::formats::24%]",
"12": "[%key:ui::panel::profile::time_format::formats::12%]"
},
"time_zone": "[%key:ui::panel::profile::time_zone::dropdown_label%]",
"time_zones": {
"auto": "Use user settings"
@@ -12451,6 +12459,10 @@
"reset": "Reset"
}
},
"time-set": {
"label": "Set time",
"time_format": "[%key:ui::panel::profile::time_format::dropdown_label%]"
},
"timer-actions": {
"label": "Timer actions",
"customize": "[%key:ui::panel::lovelace::editor::features::types::counter-actions::customize%]",