Subscribe to frontend user data (#25445)

This commit is contained in:
Wendelin 2025-05-12 16:01:56 +02:00 committed by GitHub
parent a7a8c25d24
commit ec3fdc0ea7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 93 additions and 70 deletions

View File

@ -1,5 +1,4 @@
import type { Connection } from "home-assistant-js-websocket"; import type { Connection } from "home-assistant-js-websocket";
import { getOptimisticCollection } from "./collection";
export interface CoreFrontendUserData { export interface CoreFrontendUserData {
showAdvanced?: boolean; showAdvanced?: boolean;
@ -42,30 +41,15 @@ export const saveFrontendUserData = async <
value, value,
}); });
export const getOptimisticFrontendUserDataCollection = <
UserDataKey extends ValidUserDataKey,
>(
conn: Connection,
userDataKey: UserDataKey
) =>
getOptimisticCollection(
(_conn, data) =>
saveFrontendUserData(
conn,
userDataKey,
// @ts-ignore
data
),
conn,
`_frontendUserData-${userDataKey}`,
() => fetchFrontendUserData(conn, userDataKey)
);
export const subscribeFrontendUserData = <UserDataKey extends ValidUserDataKey>( export const subscribeFrontendUserData = <UserDataKey extends ValidUserDataKey>(
conn: Connection, conn: Connection,
userDataKey: UserDataKey, userDataKey: UserDataKey,
onChange: (state: FrontendUserData[UserDataKey] | null) => void onChange: (data: { value: FrontendUserData[UserDataKey] | null }) => void
) => ) =>
getOptimisticFrontendUserDataCollection(conn, userDataKey).subscribe( conn.subscribeMessage<{ value: FrontendUserData[UserDataKey] | null }>(
onChange onChange,
{
type: "frontend/subscribe_user_data",
key: userDataKey,
}
); );

View File

@ -1,5 +1,9 @@
import type { HomeAssistant } from "../types"; import type { HomeAssistant } from "../types";
import { fetchFrontendUserData, saveFrontendUserData } from "./frontend"; import {
fetchFrontendUserData,
saveFrontendUserData,
subscribeFrontendUserData,
} from "./frontend";
export enum NumberFormat { export enum NumberFormat {
language = "language", language = "language",
@ -77,6 +81,11 @@ export type TranslationCategory =
export const fetchTranslationPreferences = (hass: HomeAssistant) => export const fetchTranslationPreferences = (hass: HomeAssistant) =>
fetchFrontendUserData(hass.connection, "language"); fetchFrontendUserData(hass.connection, "language");
export const subscribeTranslationPreferences = (
hass: HomeAssistant,
callback: (data: { value: FrontendLocaleData | null }) => void
) => subscribeFrontendUserData(hass.connection, "language", callback);
export const saveTranslationPreferences = ( export const saveTranslationPreferences = (
hass: HomeAssistant, hass: HomeAssistant,
data: FrontendLocaleData data: FrontendLocaleData

View File

@ -1,11 +1,12 @@
import type { TemplateResult } from "lit"; import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import "../../components/ha-alert";
import "../../components/ha-card"; import "../../components/ha-card";
import "../../components/ha-settings-row"; import "../../components/ha-settings-row";
import "../../components/ha-switch"; import "../../components/ha-switch";
import type { CoreFrontendUserData } from "../../data/frontend"; import type { CoreFrontendUserData } from "../../data/frontend";
import { getOptimisticFrontendUserDataCollection } from "../../data/frontend"; import { saveFrontendUserData } from "../../data/frontend";
import type { HomeAssistant } from "../../types"; import type { HomeAssistant } from "../../types";
@customElement("ha-advanced-mode-row") @customElement("ha-advanced-mode-row")
@ -16,8 +17,13 @@ class AdvancedModeRow extends LitElement {
@property({ attribute: false }) public coreUserData?: CoreFrontendUserData; @property({ attribute: false }) public coreUserData?: CoreFrontendUserData;
@state() private _error?: string;
protected render(): TemplateResult { protected render(): TemplateResult {
return html` return html`
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing}
<ha-settings-row .narrow=${this.narrow}> <ha-settings-row .narrow=${this.narrow}>
<span slot="heading"> <span slot="heading">
${this.hass.localize("ui.panel.profile.advanced_mode.title")} ${this.hass.localize("ui.panel.profile.advanced_mode.title")}
@ -41,16 +47,24 @@ class AdvancedModeRow extends LitElement {
} }
private async _advancedToggled(ev) { private async _advancedToggled(ev) {
getOptimisticFrontendUserDataCollection(this.hass.connection, "core").save({ try {
saveFrontendUserData(this.hass.connection, "core", {
...this.coreUserData, ...this.coreUserData,
showAdvanced: ev.currentTarget.checked, showAdvanced: ev.currentTarget.checked,
}); });
} catch (err: any) {
this._error = err.message || err;
}
} }
static styles = css` static styles = css`
a { a {
color: var(--primary-color); color: var(--primary-color);
} }
ha-alert {
margin: 0 16px;
display: block;
}
`; `;
} }

View File

@ -1,11 +1,12 @@
import type { TemplateResult } from "lit"; import type { TemplateResult } from "lit";
import { css, html, LitElement } from "lit"; import { css, html, LitElement, nothing } from "lit";
import { customElement, property } from "lit/decorators"; import { customElement, property, state } from "lit/decorators";
import "../../components/ha-alert";
import "../../components/ha-card"; import "../../components/ha-card";
import "../../components/ha-settings-row"; import "../../components/ha-settings-row";
import "../../components/ha-switch"; import "../../components/ha-switch";
import type { CoreFrontendUserData } from "../../data/frontend"; import type { CoreFrontendUserData } from "../../data/frontend";
import { getOptimisticFrontendUserDataCollection } from "../../data/frontend"; import { saveFrontendUserData } from "../../data/frontend";
import type { HomeAssistant } from "../../types"; import type { HomeAssistant } from "../../types";
@customElement("ha-entity-id-picker-row") @customElement("ha-entity-id-picker-row")
@ -16,8 +17,13 @@ class EntityIdPickerRow extends LitElement {
@property({ attribute: false }) public coreUserData?: CoreFrontendUserData; @property({ attribute: false }) public coreUserData?: CoreFrontendUserData;
@state() private _error?: string;
protected render(): TemplateResult { protected render(): TemplateResult {
return html` return html`
${this._error
? html`<ha-alert alert-type="error">${this._error}</ha-alert>`
: nothing}
<ha-settings-row .narrow=${this.narrow}> <ha-settings-row .narrow=${this.narrow}>
<span slot="heading"> <span slot="heading">
${this.hass.localize("ui.panel.profile.entity_id_picker.title")}</span ${this.hass.localize("ui.panel.profile.entity_id_picker.title")}</span
@ -35,16 +41,24 @@ class EntityIdPickerRow extends LitElement {
} }
private async _toggled(ev) { private async _toggled(ev) {
getOptimisticFrontendUserDataCollection(this.hass.connection, "core").save({ try {
saveFrontendUserData(this.hass.connection, "core", {
...this.coreUserData, ...this.coreUserData,
showEntityIdPicker: ev.currentTarget.checked, showEntityIdPicker: ev.currentTarget.checked,
}); });
} catch (err: any) {
this._error = err.message || err;
}
} }
static styles = css` static styles = css`
a { a {
color: var(--primary-color); color: var(--primary-color);
} }
ha-alert {
margin: 0 16px;
display: block;
}
`; `;
} }

View File

@ -4,32 +4,32 @@ import type { CSSResultGroup, TemplateResult } from "lit";
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 { fireEvent } from "../../common/dom/fire_event"; import { fireEvent } from "../../common/dom/fire_event";
import { nextRender } from "../../common/util/render-status";
import "../../components/ha-card"; import "../../components/ha-card";
import "../../layouts/hass-tabs-subpage";
import { profileSections } from "./ha-panel-profile";
import { isExternal } from "../../data/external"; import { isExternal } from "../../data/external";
import type { CoreFrontendUserData } from "../../data/frontend"; import type { CoreFrontendUserData } from "../../data/frontend";
import { getOptimisticFrontendUserDataCollection } from "../../data/frontend"; import { subscribeFrontendUserData } from "../../data/frontend";
import { showConfirmationDialog } from "../../dialogs/generic/show-dialog-box"; import { showConfirmationDialog } from "../../dialogs/generic/show-dialog-box";
import { isMobileClient } from "../../util/is_mobile"; import "../../layouts/hass-tabs-subpage";
import { haStyle } from "../../resources/styles"; import { haStyle } from "../../resources/styles";
import type { HomeAssistant, Route } from "../../types"; import type { HomeAssistant, Route } from "../../types";
import { isMobileClient } from "../../util/is_mobile";
import "./ha-advanced-mode-row"; import "./ha-advanced-mode-row";
import "./ha-enable-shortcuts-row"; import "./ha-enable-shortcuts-row";
import "./ha-entity-id-picker-row"; import "./ha-entity-id-picker-row";
import "./ha-force-narrow-row"; import "./ha-force-narrow-row";
import { profileSections } from "./ha-panel-profile";
import "./ha-pick-dashboard-row"; import "./ha-pick-dashboard-row";
import "./ha-pick-date-format-row";
import "./ha-pick-first-weekday-row"; import "./ha-pick-first-weekday-row";
import "./ha-pick-language-row"; import "./ha-pick-language-row";
import "./ha-pick-number-format-row"; import "./ha-pick-number-format-row";
import "./ha-pick-theme-row"; import "./ha-pick-theme-row";
import "./ha-pick-time-format-row"; import "./ha-pick-time-format-row";
import "./ha-pick-date-format-row";
import "./ha-pick-time-zone-row"; import "./ha-pick-time-zone-row";
import "./ha-push-notifications-row"; import "./ha-push-notifications-row";
import "./ha-set-suspend-row"; import "./ha-set-suspend-row";
import "./ha-set-vibrate-row"; import "./ha-set-vibrate-row";
import { nextRender } from "../../common/util/render-status";
@customElement("ha-profile-section-general") @customElement("ha-profile-section-general")
class HaProfileSectionGeneral extends LitElement { class HaProfileSectionGeneral extends LitElement {
@ -41,15 +41,16 @@ class HaProfileSectionGeneral extends LitElement {
@property({ attribute: false }) public route!: Route; @property({ attribute: false }) public route!: Route;
private _unsubCoreData?: UnsubscribeFunc; private _unsubCoreData?: Promise<UnsubscribeFunc>;
private _getCoreData() { private _getCoreData() {
this._unsubCoreData = getOptimisticFrontendUserDataCollection( this._unsubCoreData = subscribeFrontendUserData(
this.hass.connection, this.hass.connection,
"core" "core",
).subscribe((coreUserData) => { ({ value }) => {
this._coreUserData = coreUserData; this._coreUserData = value;
}); }
);
} }
public connectedCallback() { public connectedCallback() {
@ -70,7 +71,7 @@ class HaProfileSectionGeneral extends LitElement {
public disconnectedCallback() { public disconnectedCallback() {
super.disconnectedCallback(); super.disconnectedCallback();
if (this._unsubCoreData) { if (this._unsubCoreData) {
this._unsubCoreData(); this._unsubCoreData.then((unsub) => unsub());
this._unsubCoreData = undefined; this._unsubCoreData = undefined;
} }
} }

View File

@ -8,6 +8,7 @@ import {
subscribeServices, subscribeServices,
} from "home-assistant-js-websocket"; } from "home-assistant-js-websocket";
import { fireEvent } from "../common/dom/fire_event"; import { fireEvent } from "../common/dom/fire_event";
import { promiseTimeout } from "../common/util/promise-timeout";
import { subscribeAreaRegistry } from "../data/area_registry"; import { subscribeAreaRegistry } from "../data/area_registry";
import { broadcastConnectionStatus } from "../data/connection-status"; import { broadcastConnectionStatus } from "../data/connection-status";
import { subscribeDeviceRegistry } from "../data/device_registry"; import { subscribeDeviceRegistry } from "../data/device_registry";
@ -22,6 +23,8 @@ import {
TimeFormat, TimeFormat,
TimeZone, TimeZone,
} from "../data/translation"; } from "../data/translation";
import { subscribeEntityRegistryDisplay } from "../data/ws-entity_registry_display";
import { subscribeFloorRegistry } from "../data/ws-floor_registry";
import { subscribePanels } from "../data/ws-panels"; import { subscribePanels } from "../data/ws-panels";
import { translationMetadata } from "../resources/translations-metadata"; import { translationMetadata } from "../resources/translations-metadata";
import type { Constructor, HomeAssistant, ServiceCallResponse } from "../types"; import type { Constructor, HomeAssistant, ServiceCallResponse } from "../types";
@ -30,9 +33,6 @@ import { fetchWithAuth } from "../util/fetch-with-auth";
import { getState } from "../util/ha-pref-storage"; import { getState } from "../util/ha-pref-storage";
import hassCallApi, { hassCallApiRaw } from "../util/hass-call-api"; import hassCallApi, { hassCallApiRaw } from "../util/hass-call-api";
import type { HassBaseEl } from "./hass-base-mixin"; import type { HassBaseEl } from "./hass-base-mixin";
import { promiseTimeout } from "../common/util/promise-timeout";
import { subscribeFloorRegistry } from "../data/ws-floor_registry";
import { subscribeEntityRegistryDisplay } from "../data/ws-entity_registry_display";
export const connectionMixin = <T extends Constructor<HassBaseEl>>( export const connectionMixin = <T extends Constructor<HassBaseEl>>(
superClass: T superClass: T
@ -280,9 +280,9 @@ export const connectionMixin = <T extends Constructor<HassBaseEl>>(
subscribeConfig(conn, (config) => this._updateHass({ config })); subscribeConfig(conn, (config) => this._updateHass({ config }));
subscribeServices(conn, (services) => this._updateHass({ services })); subscribeServices(conn, (services) => this._updateHass({ services }));
subscribePanels(conn, (panels) => this._updateHass({ panels })); subscribePanels(conn, (panels) => this._updateHass({ panels }));
subscribeFrontendUserData(conn, "core", (userData) => subscribeFrontendUserData(conn, "core", ({ value: userData }) => {
this._updateHass({ userData }) this._updateHass({ userData });
); });
clearInterval(this.__backendPingInterval); clearInterval(this.__backendPingInterval);
this.__backendPingInterval = setInterval(() => { this.__backendPingInterval = setInterval(() => {

View File

@ -8,17 +8,18 @@ import {
} from "../common/util/compute_rtl"; } from "../common/util/compute_rtl";
import { debounce } from "../common/util/debounce"; import { debounce } from "../common/util/debounce";
import type { import type {
DateFormat,
FirstWeekday, FirstWeekday,
NumberFormat, NumberFormat,
TimeFormat, TimeFormat,
DateFormat,
TranslationCategory,
TimeZone, TimeZone,
TranslationCategory,
} from "../data/translation"; } from "../data/translation";
import { import {
getHassTranslations, getHassTranslations,
getHassTranslationsPre109, getHassTranslationsPre109,
saveTranslationPreferences, saveTranslationPreferences,
subscribeTranslationPreferences,
} from "../data/translation"; } from "../data/translation";
import { translationMetadata } from "../resources/translations-metadata"; import { translationMetadata } from "../resources/translations-metadata";
import type { Constructor, HomeAssistant } from "../types"; import type { Constructor, HomeAssistant } from "../types";
@ -119,7 +120,10 @@ export default <T extends Constructor<HassBaseEl>>(superClass: T) =>
protected hassConnected() { protected hassConnected() {
super.hassConnected(); super.hassConnected();
getUserLocale(this.hass!).then((locale) => {
subscribeTranslationPreferences(this.hass!, async ({ value }) => {
const locale = await getUserLocale(value);
if (locale?.language && this.hass!.language !== locale.language) { if (locale?.language && this.hass!.language !== locale.language) {
// We just got language from backend, no need to save back // We just got language from backend, no need to save back
this._selectLanguage(locale.language, false); this._selectLanguage(locale.language, false);

View File

@ -1,7 +1,5 @@
import type { FrontendLocaleData } from "../data/translation"; import type { FrontendLocaleData } from "../data/translation";
import { fetchTranslationPreferences } from "../data/translation";
import { translationMetadata } from "../resources/translations-metadata"; import { translationMetadata } from "../resources/translations-metadata";
import type { HomeAssistant } from "../types";
const BASE_URL = `${__STATIC_PATH__}translations`; const BASE_URL = `${__STATIC_PATH__}translations`;
const STORAGE = window.localStorage || {}; const STORAGE = window.localStorage || {};
@ -68,15 +66,14 @@ export function findAvailableLanguage(language: string) {
* Get user selected locale data from backend * Get user selected locale data from backend
*/ */
export async function getUserLocale( export async function getUserLocale(
hass: HomeAssistant data: FrontendLocaleData | null
): Promise<Partial<FrontendLocaleData>> { ): Promise<Partial<FrontendLocaleData>> {
const result = await fetchTranslationPreferences(hass); const language = data?.language;
const language = result?.language; const number_format = data?.number_format;
const number_format = result?.number_format; const time_format = data?.time_format;
const time_format = result?.time_format; const date_format = data?.date_format;
const date_format = result?.date_format; const time_zone = data?.time_zone;
const time_zone = result?.time_zone; const first_weekday = data?.first_weekday;
const first_weekday = result?.first_weekday;
if (language) { if (language) {
const availableLanguage = findAvailableLanguage(language); const availableLanguage = findAvailableLanguage(language);
if (availableLanguage) { if (availableLanguage) {