diff --git a/src/data/group.ts b/src/data/group.ts index e6a004b1a8..4b154672fe 100644 --- a/src/data/group.ts +++ b/src/data/group.ts @@ -43,3 +43,20 @@ export const subscribePreviewGroupSensor = ( flow_type, user_input, }); + +export const subscribePreviewGroupBinarySensor = ( + hass: HomeAssistant, + flow_id: string, + flow_type: "config_flow" | "options_flow", + user_input: Record, + callback: (preview: { + state: string; + attributes: Record; + }) => void +): Promise => + hass.connection.subscribeMessage(callback, { + type: "group/binary_sensor/start_preview", + flow_id, + flow_type, + user_input, + }); diff --git a/src/dialogs/config-flow/previews/flow-preview-group_binary_sensor.ts b/src/dialogs/config-flow/previews/flow-preview-group_binary_sensor.ts new file mode 100644 index 0000000000..927481aa42 --- /dev/null +++ b/src/dialogs/config-flow/previews/flow-preview-group_binary_sensor.ts @@ -0,0 +1,88 @@ +import { HassEntity, UnsubscribeFunc } from "home-assistant-js-websocket"; +import { LitElement, html } from "lit"; +import { customElement, property, state } from "lit/decorators"; +import { FlowType } from "../../../data/data_entry_flow"; +import { subscribePreviewGroupBinarySensor } from "../../../data/group"; +import { HomeAssistant } from "../../../types"; +import "./entity-preview-row"; + +@customElement("flow-preview-group_binary_sensor") +class FlowPreviewGroupBinarySensor extends LitElement { + @property({ attribute: false }) public hass!: HomeAssistant; + + @property() public flowType!: FlowType; + + public handler!: string; + + public stepId!: string; + + @property() public flowId!: string; + + @property() public stepData!: Record; + + @state() private _preview?: HassEntity; + + private _unsub?: Promise; + + disconnectedCallback(): void { + super.disconnectedCallback(); + if (this._unsub) { + this._unsub.then((unsub) => unsub()); + this._unsub = undefined; + } + } + + willUpdate(changedProps) { + if (changedProps.has("stepData")) { + this._subscribePreview(); + } + } + + protected render() { + return html``; + } + + private _setPreview = (preview: { + state: string; + attributes: Record; + }) => { + const now = new Date().toISOString(); + this._preview = { + entity_id: "binary_sensor.flow_preview", + last_changed: now, + last_updated: now, + context: { id: "", parent_id: null, user_id: null }, + ...preview, + }; + }; + + private async _subscribePreview() { + if (this._unsub) { + (await this._unsub)(); + this._unsub = undefined; + } + if (this.flowType === "repair_flow") { + return; + } + try { + this._unsub = subscribePreviewGroupBinarySensor( + this.hass, + this.flowId, + this.flowType, + this.stepData, + this._setPreview + ); + } catch (err) { + this._preview = undefined; + } + } +} + +declare global { + interface HTMLElementTagNameMap { + "flow-preview-group_binary_sensor": FlowPreviewGroupBinarySensor; + } +}