Optimize scenes config (#5652)

This commit is contained in:
Bram Kragten 2020-04-30 20:40:43 +02:00 committed by GitHub
parent 8484f7595a
commit 3ba9c931b9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 92 additions and 60 deletions

View File

@ -10,6 +10,14 @@ import {
import { HomeAssistant } from "../../../types"; import { HomeAssistant } from "../../../types";
import "./ha-scene-dashboard"; import "./ha-scene-dashboard";
import "./ha-scene-editor"; import "./ha-scene-editor";
import { debounce } from "../../../common/util/debounce";
const equal = (a: SceneEntity[], b: SceneEntity[]): boolean => {
if (a.length !== b.length) {
return false;
}
return a.every((scene, index) => scene === b[index]);
};
@customElement("ha-config-scene") @customElement("ha-config-scene")
class HaConfigScene extends HassRouterPage { class HaConfigScene extends HassRouterPage {
@ -36,15 +44,18 @@ class HaConfigScene extends HassRouterPage {
}, },
}; };
private _computeScenes = memoizeOne((states: HassEntities) => { private _debouncedUpdateScenes = debounce((pageEl) => {
const scenes: SceneEntity[] = []; const newScenes = this._getScenes(this.hass.states);
Object.values(states).forEach((state) => { if (!equal(newScenes, pageEl.scenes)) {
if (computeStateDomain(state) === "scene" && !state.attributes.hidden) { pageEl.scenes = newScenes;
scenes.push(state as SceneEntity); }
} }, 10);
});
return scenes; private _getScenes = memoizeOne((states: HassEntities): SceneEntity[] => {
return Object.values(states).filter(
(entity) =>
computeStateDomain(entity) === "scene" && !entity.attributes.hidden
) as SceneEntity[];
}); });
protected updatePageEl(pageEl, changedProps: PropertyValues) { protected updatePageEl(pageEl, changedProps: PropertyValues) {
@ -55,7 +66,11 @@ class HaConfigScene extends HassRouterPage {
pageEl.showAdvanced = this.showAdvanced; pageEl.showAdvanced = this.showAdvanced;
if (this.hass) { if (this.hass) {
pageEl.scenes = this._computeScenes(this.hass.states); if (!pageEl.scenes || !changedProps) {
pageEl.scenes = this._getScenes(this.hass.states);
} else if (changedProps && changedProps.has("hass")) {
this._debouncedUpdateScenes(pageEl);
}
} }
if ( if (
@ -64,13 +79,7 @@ class HaConfigScene extends HassRouterPage {
) { ) {
pageEl.creatingNew = undefined; pageEl.creatingNew = undefined;
const sceneId = this.routeTail.path.substr(1); const sceneId = this.routeTail.path.substr(1);
pageEl.creatingNew = sceneId === "new"; pageEl.sceneId = sceneId === "new" ? null : sceneId;
pageEl.scene =
sceneId === "new"
? undefined
: pageEl.scenes.find(
(entity: SceneEntity) => entity.attributes.id === sceneId
);
} }
} }
} }

View File

@ -46,7 +46,10 @@ import {
SceneEntity, SceneEntity,
SCENE_IGNORED_DOMAINS, SCENE_IGNORED_DOMAINS,
} from "../../../data/scene"; } from "../../../data/scene";
import { showConfirmationDialog } from "../../../dialogs/generic/show-dialog-box"; import {
showConfirmationDialog,
showAlertDialog,
} from "../../../dialogs/generic/show-dialog-box";
import { SubscribeMixin } from "../../../mixins/subscribe-mixin"; import { SubscribeMixin } from "../../../mixins/subscribe-mixin";
import { haStyle } from "../../../resources/styles"; import { haStyle } from "../../../resources/styles";
import { HomeAssistant, Route } from "../../../types"; import { HomeAssistant, Route } from "../../../types";
@ -73,13 +76,13 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
@property() public route!: Route; @property() public route!: Route;
@property() public scene?: SceneEntity; @property() public sceneId?: string;
@property() public creatingNew?: boolean; @property() public scenes!: SceneEntity[];
@property() public showAdvanced!: boolean; @property() public showAdvanced!: boolean;
@property() private _dirty?: boolean; @property() private _dirty = false;
@property() private _errors?: string; @property() private _errors?: string;
@ -93,6 +96,8 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
@property() private _entityRegistryEntries: EntityRegistryEntry[] = []; @property() private _entityRegistryEntries: EntityRegistryEntry[] = [];
@property() private _scene?: SceneEntity;
private _storedStates: SceneEntities = {}; private _storedStates: SceneEntities = {};
private _unsubscribeEvents?: () => void; private _unsubscribeEvents?: () => void;
@ -172,8 +177,8 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
this._deviceEntityLookup, this._deviceEntityLookup,
this._deviceRegistryEntries this._deviceRegistryEntries
); );
const name = this.scene const name = this._scene
? computeStateName(this.scene) ? computeStateName(this._scene)
: this.hass.localize("ui.panel.config.scene.editor.default_name"); : this.hass.localize("ui.panel.config.scene.editor.default_name");
return html` return html`
@ -184,7 +189,7 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
.backCallback=${() => this._backTapped()} .backCallback=${() => this._backTapped()}
.tabs=${configSections.automation} .tabs=${configSections.automation}
> >
${this.creatingNew ${!this.sceneId
? "" ? ""
: html` : html`
<paper-icon-button <paper-icon-button
@ -212,7 +217,7 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
<ha-card> <ha-card>
<div class="card-content"> <div class="card-content">
<paper-input <paper-input
.value=${this.scene ? computeStateName(this.scene) : ""} .value=${this._scene ? computeStateName(this._scene) : ""}
@value-changed=${this._nameChanged} @value-changed=${this._nameChanged}
label=${this.hass.localize( label=${this.hass.localize(
"ui.panel.config.scene.editor.name" "ui.panel.config.scene.editor.name"
@ -250,8 +255,8 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
></paper-icon-button> ></paper-icon-button>
</div> </div>
${device.entities.map((entityId) => { ${device.entities.map((entityId) => {
const stateObj = this.hass.states[entityId]; const entityStateObj = this.hass.states[entityId];
if (!stateObj) { if (!entityStateObj) {
return html``; return html``;
} }
return html` return html`
@ -261,11 +266,11 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
class="device-entity" class="device-entity"
> >
<state-badge <state-badge
.stateObj=${stateObj} .stateObj=${entityStateObj}
slot="item-icon" slot="item-icon"
></state-badge> ></state-badge>
<paper-item-body> <paper-item-body>
${computeStateName(stateObj)} ${computeStateName(entityStateObj)}
</paper-item-body> </paper-item-body>
</paper-icon-item> </paper-icon-item>
`; `;
@ -313,8 +318,8 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
)} )}
> >
${entities.map((entityId) => { ${entities.map((entityId) => {
const stateObj = this.hass.states[entityId]; const entityStateObj = this.hass.states[entityId];
if (!stateObj) { if (!entityStateObj) {
return html``; return html``;
} }
return html` return html`
@ -324,11 +329,11 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
class="device-entity" class="device-entity"
> >
<state-badge <state-badge
.stateObj=${stateObj} .stateObj=${entityStateObj}
slot="item-icon" slot="item-icon"
></state-badge> ></state-badge>
<paper-item-body> <paper-item-body>
${computeStateName(stateObj)} ${computeStateName(entityStateObj)}
</paper-item-body> </paper-item-body>
<paper-icon-button <paper-icon-button
icon="hass:delete" icon="hass:delete"
@ -386,19 +391,19 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
protected updated(changedProps: PropertyValues): void { protected updated(changedProps: PropertyValues): void {
super.updated(changedProps); super.updated(changedProps);
const oldscene = changedProps.get("scene") as SceneEntity; const oldscene = changedProps.get("sceneId");
if ( if (
changedProps.has("scene") && changedProps.has("sceneId") &&
this.scene && this.sceneId &&
this.hass && this.hass &&
// Only refresh config if we picked a new scene. If same ID, don't fetch it. // Only refresh config if we picked a new scene. If same ID, don't fetch it.
(!oldscene || oldscene.attributes.id !== this.scene.attributes.id) (!oldscene || oldscene !== this.sceneId)
) { ) {
this._loadConfig(); this._loadConfig();
} }
if (changedProps.has("creatingNew") && this.creatingNew && this.hass) { if (changedProps.has("sceneId") && !this.sceneId && this.hass) {
this._dirty = false; this._dirty = false;
const initData = getSceneEditorInitData(); const initData = getSceneEditorInitData();
this._config = { this._config = {
@ -436,6 +441,29 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
} }
} }
} }
if (
changedProps.has("scenes") &&
this.sceneId &&
this._config &&
!this._scene
) {
this._setScene();
}
}
private async _setScene() {
const scene = this.scenes.find(
(entity: SceneEntity) => entity.attributes.id === this.sceneId
);
if (!scene) {
return;
}
this._scene = scene;
const { context } = await activateScene(this.hass, this._scene.entity_id);
this._activateContextId = context.id;
this._unsubscribeEvents = await this.hass!.connection.subscribeEvents<
HassEvent
>((event) => this._stateChanged(event), "state_changed");
} }
private _showMoreInfo(ev: Event) { private _showMoreInfo(ev: Event) {
@ -446,20 +474,20 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
private async _loadConfig() { private async _loadConfig() {
let config: SceneConfig; let config: SceneConfig;
try { try {
config = await getSceneConfig(this.hass, this.scene!.attributes.id!); config = await getSceneConfig(this.hass, this.sceneId!);
} catch (err) { } catch (err) {
alert( showAlertDialog(this, {
err.status_code === 404 text:
? this.hass.localize( err.status_code === 404
"ui.panel.config.scene.editor.load_error_not_editable" ? this.hass.localize(
) "ui.panel.config.scene.editor.load_error_not_editable"
: this.hass.localize( )
"ui.panel.config.scene.editor.load_error_unknown", : this.hass.localize(
"err_no", "ui.panel.config.scene.editor.load_error_unknown",
err.status_code "err_no",
) err.status_code
); ),
history.back(); }).then(() => history.back());
return; return;
} }
@ -469,13 +497,7 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
this._initEntities(config); this._initEntities(config);
const { context } = await activateScene(this.hass, this.scene!.entity_id); this._setScene();
this._activateContextId = context.id;
this._unsubscribeEvents = await this.hass!.connection.subscribeEvents<
HassEvent
>((event) => this._stateChanged(event), "state_changed");
this._dirty = false; this._dirty = false;
this._config = config; this._config = config;
@ -564,6 +586,7 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
event.context.id !== this._activateContextId && event.context.id !== this._activateContextId &&
this._entities.includes(event.data.entity_id) this._entities.includes(event.data.entity_id)
) { ) {
console.log(event);
this._dirty = true; this._dirty = true;
} }
} }
@ -598,7 +621,7 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
} }
private async _delete(): Promise<void> { private async _delete(): Promise<void> {
await deleteScene(this.hass, this.scene!.attributes.id!); await deleteScene(this.hass, this.sceneId!);
applyScene(this.hass, this._storedStates); applyScene(this.hass, this._storedStates);
history.back(); history.back();
} }
@ -634,13 +657,13 @@ export class HaSceneEditor extends SubscribeMixin(LitElement) {
} }
private async _saveScene(): Promise<void> { private async _saveScene(): Promise<void> {
const id = this.creatingNew ? "" + Date.now() : this.scene!.attributes.id!; const id = !this.sceneId ? "" + Date.now() : this.sceneId!;
this._config = { ...this._config, entities: this._calculateStates() }; this._config = { ...this._config, entities: this._calculateStates() };
try { try {
await saveScene(this.hass, id, this._config); await saveScene(this.hass, id, this._config);
this._dirty = false; this._dirty = false;
if (this.creatingNew) { if (!this.sceneId) {
navigate(this, `/config/scene/edit/${id}`, true); navigate(this, `/config/scene/edit/${id}`, true);
} }
} catch (err) { } catch (err) {