`}_discoveryFilterState(t){const e=this.host._settings,s=void 0!==t.draftGroupLights?t.draftGroupLights:!1!==e.group_lights,i=e.exclude_integrations,o=void 0!==t.draftExcluded?null===t.draftExcluded?[...ki]:t.draftExcluded:i?[...i]:[...ki],a=void 0!==t.draftExcluded?null===t.draftExcluded:!i,n=void 0!==t.draftGroupLights||void 0!==t.draftExcluded;return{groupLights:s,excluded:o.sort(),usesProductList:a,dirty:n}}_registryIntegrations(){const t=new Set,e=this.host._fullRegistryHass;for(const s of Object.values(e?.entities||{}))s?.platform&&t.add(String(s.platform));for(const s of Object.values(e?.devices||{})){const e=s?.identifiers?.[0],i=Array.isArray(e)?e[0]:null;i&&t.add(String(i))}return[...t].sort()}_discoveryFilterPreview(t){const e=this._discoveryFilterState(t),s=[e.groupLights?1:0,e.usesProductList?"p":e.excluded.join(","),this.host._cfgEpoch,this.host._regSignature].join("|");if(this._discoveryPreviewMemo?.key===s)return this._discoveryPreviewMemo.value;const i={hass:this.host.hass,registry:this.host._haRegistry,areaToSpace:Object.fromEntries(Object.entries(this.host._areaToSpace).map(([t,e])=>[t,e.space])),markers:this.host._markers,showAll:this.host._showAll,firstSpaceId:this.host._model[0]?.id||"",loc:t=>this.host._t(t),iconRules:this.host._iconRules},o=(t,e)=>new Set(Zi({...i,settings:t,excluded:e})),a=(t,e)=>new Set(Qi({...i,settings:t,excluded:e}).map(t=>t.bindingRef||t.id)),n=xi(this.host._settings),r={...this.host._settings,group_lights:e.groupLights},l=new Set(e.excluded),h=o(this.host._settings,n),c=o(r,l),d=a(this.host._settings,n),p=a(r,l);let u=0,_=0,m=0;const g=t=>t.includes("light.");for(const t of h)c.has(t)||(u++,g(t)&&m++);for(const t of c)h.has(t)||(_++,g(t)&&m++);for(const t of p)d.has(t)||(u++,g(t)&&m++);for(const t of d)p.has(t)||(_++,g(t)&&m++);const f={appear:u,hide:_,lights:m};return this._discoveryPreviewMemo={key:s,value:f},f}async _saveDiscoveryFilters(t){const e=this.host._serverCfg;if(!e)return;const s=this._discoveryFilterState(t),i={...e.settings};s.groupLights?delete i.group_lights:i.group_lights=!1,s.usesProductList?delete i.exclude_integrations:i.exclude_integrations=s.excluded,this.host._serverCfg={...e,settings:i},this.host._deviceInboxMemo=null,this._discoveryPreviewMemo=null,this.host._regSignature="",this.host._deviceInbox&&(this.host._deviceInbox={...t,draftGroupLights:void 0,draftExcluded:void 0}),this._saveConfig(),this.host._maybeRebuildDevices(),this.host.requestUpdate()}_renderDiscoveryFilters(t){const e=this._discoveryFilterState(t),s=e=>this.host._deviceInbox={...t,...e},i=t.filtersOpen&&e.dirty?this._discoveryFilterPreview(t):null,o=this._registryIntegrations().filter(t=>!e.excluded.includes(t));return h``}_discoveryFilterState(t){const e=this.host._settings,s=void 0!==t.draftGroupLights?t.draftGroupLights:!1!==e.group_lights,i=e.exclude_integrations,o=void 0!==t.draftExcluded?null===t.draftExcluded?[...xi]:t.draftExcluded:i?[...i]:[...xi],a=void 0!==t.draftExcluded?null===t.draftExcluded:!i,n=void 0!==t.draftGroupLights||void 0!==t.draftExcluded;return{groupLights:s,excluded:o.sort(),usesProductList:a,dirty:n}}_registryIntegrations(){const t=new Set,e=this.host._fullRegistryHass;for(const s of Object.values(e?.entities||{}))s?.platform&&t.add(String(s.platform));for(const s of Object.values(e?.devices||{})){const e=s?.identifiers?.[0],i=Array.isArray(e)?e[0]:null;i&&t.add(String(i))}return[...t].sort()}_discoveryFilterPreview(t){const e=this._discoveryFilterState(t),s=[e.groupLights?1:0,e.usesProductList?"p":e.excluded.join(","),this.host._cfgEpoch,this.host._regSignature].join("|");if(this._discoveryPreviewMemo?.key===s)return this._discoveryPreviewMemo.value;const i={hass:this.host.hass,registry:this.host._haRegistry,areaToSpace:Object.fromEntries(Object.entries(this.host._areaToSpace).map(([t,e])=>[t,e.space])),markers:this.host._markers,showAll:this.host._showAll,firstSpaceId:this.host._model[0]?.id||"",loc:t=>this.host._t(t),iconRules:this.host._iconRules},o=(t,e)=>new Set(Qi({...i,settings:t,excluded:e})),a=(t,e)=>new Set(to({...i,settings:t,excluded:e}).map(t=>t.bindingRef||t.id)),n=Si(this.host._settings),r={...this.host._settings,group_lights:e.groupLights},l=new Set(e.excluded),h=o(this.host._settings,n),c=o(r,l),d=a(this.host._settings,n),p=a(r,l);let u=0,_=0,m=0;const g=t=>t.includes("light.");for(const t of h)c.has(t)||(u++,g(t)&&m++);for(const t of c)h.has(t)||(_++,g(t)&&m++);for(const t of p)d.has(t)||(u++,g(t)&&m++);for(const t of d)p.has(t)||(_++,g(t)&&m++);const f={appear:u,hide:_,lights:m};return this._discoveryPreviewMemo={key:s,value:f},f}async _saveDiscoveryFilters(t){const e=this.host._serverCfg;if(!e)return;const s=this._discoveryFilterState(t),i={...e.settings};s.groupLights?delete i.group_lights:i.group_lights=!1,s.usesProductList?delete i.exclude_integrations:i.exclude_integrations=s.excluded,this.host._serverCfg={...e,settings:i},this.host._deviceInboxMemo=null,this._discoveryPreviewMemo=null,this.host._regSignature="",this.host._deviceInbox&&(this.host._deviceInbox={...t,draftGroupLights:void 0,draftExcluded:void 0}),this._saveConfig(),this.host._maybeRebuildDevices(),this.host.requestUpdate()}_renderDiscoveryFilters(t){const e=this._discoveryFilterState(t),s=e=>this.host._deviceInbox={...t,...e},i=t.filtersOpen&&e.dirty?this._discoveryFilterPreview(t):null,o=this._registryIntegrations().filter(t=>!e.excluded.includes(t));return h`s({filtersOpen:t.target.open})}>
${this.host._t("device_inbox.filters_title")}
- `}}export{Ic as EDITOR_RUNTIME_FINGERPRINT,Tc as HouseplanEditorRuntime};
+ `}}export{Lc as EDITOR_RUNTIME_FINGERPRINT,Oc as HouseplanEditorRuntime};
diff --git a/custom_components/houseplan/frontend/houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js b/custom_components/houseplan/frontend/houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js
similarity index 97%
rename from custom_components/houseplan/frontend/houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js
rename to custom_components/houseplan/frontend/houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js
index 777087cb..9df90a24 100644
--- a/custom_components/houseplan/frontend/houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js
+++ b/custom_components/houseplan/frontend/houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js
@@ -1,5 +1,5 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{l as t,a_ as s,A as e,x as o,b as a,ch as l,ci as i,cj as h,ck as c,aX as n,cl as r,cq as p,cm as _,cn as d,co as u,cp as g,dh as m,aW as b,aY as $,di as v}from"./houseplan-card-B_QYG0Py.js";import{i as f,c as y,e as w,r as D,a as k,b as S,g as C,t as M}from"./backdrop-pick-D6LhKf2N.js";const F=1e3,x=t=>{if(!t.trim())return null;const s=Number(t.replace(",","."));return Number.isFinite(s)?s:null},T="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";class L{constructor(t){this.host=t,this._toggleServerPlans=async()=>{const t=this.host._spaceDialog;if(t)if(t.pickSaved)this.host._spaceDialog={...t,pickSaved:!1};else{this.host._spaceDialog={...t,pickSaved:!0,savedBusy:!0};try{const t=await this.host.hass.callWS({type:"houseplan/plans/list"}),s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,saved:t?.plans||[],savedBusy:!1})}catch(t){const s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,saved:[],savedBusy:!1}),this.host._showToast(this.host._t("toast.plans_list_failed",{err:this.host._errText(t)}))}}}}_help(l){const i=`${l}.aria`,h=t(this.host.hass,this.host._config?.language);return s(h,l)&&s(h,i)?a``:e}_openSpaceDialog(t,s){if(!this.host._serverStorage||!this.host._serverCfg)return void this.host._showToast(this.host._t("toast.integration_missing"));if("edit"===t){const e=this.host._serverCfg.spaces.find(t=>t.id===s);if(!e)return;const o=l(e),a=e.settings?.custom_fill&&"object"==typeof e.settings.custom_fill?i(e.settings.custom_fill):null,p="none"===o.fill?{...a||h,a:0}:a;return void(this.host._spaceDialog={mode:t,spaceId:s,title:e.title,planUrl:e.plan_url||null,planFile:null,source:e.plan_url?"file":"draw",showBorders:o.showBorders,showNames:o.showNames,zeroWallStyle:r(e),displayTouched:!0,hideDecor:o.hideDecor,hideOpenings:o.hideOpenings,roomColor:o.color,roomOpacity:o.opacity,fillMode:"none"===o.fill?"custom":o.fill,customFill:p,glowEnabled:o.glow,bgColor:o.bgColor,bgMode:"static"===e.settings?.bg_mode||"daynight"===e.settings?.bg_mode?e.settings.bg_mode:null,northDeg:n({},e.settings),sunRays:"boolean"==typeof e.settings?.sun_rays?e.settings.sun_rays:null,tempMin:o.tempMin,tempMax:o.tempMax,showLqi:o.showLqi??this.host._config?.show_signal??!0,cardFontScale:o.cardFontScale,labelTemp:o.labelTemp,labelHum:o.labelHum,labelLqi:o.labelLqi,labelLight:o.labelLight,cellCm:Number(e.cell_cm)>0?Number(e.cell_cm):5,cellCmInput:c(Number(e.cell_cm)>0?Number(e.cell_cm):5,this.host._imperial),cellCmTouched:!1,busy:!1})}const e=p(this.host._imperial);this.host._spaceDialog={mode:t,title:"",planUrl:null,planFile:null,...f(),hideDecor:!1,hideOpenings:!1,zeroWallStyle:"dashed",roomColor:g,roomOpacity:u,fillMode:"custom",customFill:{...h,a:0},glowEnabled:!0,bgColor:null,bgMode:"daynight",northDeg:null,sunRays:null,tempMin:d,tempMax:_,showLqi:this.host._config?.show_signal??!0,cardFontScale:1,labelTemp:!1,labelHum:!1,labelLqi:!1,labelLight:!1,cellCm:e,cellCmInput:c(e,this.host._imperial),cellCmTouched:!1,busy:!1}}async _pickPlanFile(t){const s=t.target,e=s.files?.[0];if(!e||!this.host._spaceDialog)return;s.value="";const o=await y(e);if("reject"===o.kind)return void this.host._showToast(this.host._t("toast.plan_formats"));if("guard"===o.kind)return void(this.host._backdropGuard=o.state);const a=await w(e,o.ext,e.name);this.host._spaceDialog&&(this.host._spaceDialog={...this.host._spaceDialog,planFile:a})}_renderBackdropGuard(){return D(this.host,t=>{this.host._spaceDialog&&(this.host._spaceDialog={...this.host._spaceDialog,planFile:t})},()=>{this.host._backdropGuard=null},this.host.hass)??e}_useServerPlan(t){const s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,planUrl:t,planFile:null,pickSaved:!1,savedAspect:void 0},this.host._aspectJob=this._readPlanAspect(t))}async _readPlanAspect(t){for(let s=0;s<40;s++){const s=this.host._display(t);if(s){const e=await new Promise(t=>{const e=new Image;e.onload=()=>t(e.naturalWidth&&e.naturalHeight?e.naturalWidth/e.naturalHeight:0),e.onerror=()=>t(0),e.src=s}),o=this.host._spaceDialog;return o&&o.planUrl===t&&Number.isFinite(e)&&e>0?(this.host._spaceDialog={...o,savedAspect:e},e):0}if(await new Promise(t=>setTimeout(t,150)),this.host._spaceDialog?.planUrl!==t)return 0}return 0}async _deleteServerPlan(t){const s=this.host._spaceDialog,e=s?.saved?.find(s=>s.name===t);if(!s||!e||e.used_by.length||e.url===s.planUrl)return;const o=await this.host._confirmDanger({key:"delete-plan",kind:"destructive",title:this.host._t("confirm.delete_plan_title"),message:this.host._t("confirm.delete_plan_body"),objectName:t,confirmLabel:this.host._t("btn.delete"),cancelLabel:this.host._t("btn.cancel")}),a=this.host._spaceDialog,l=a?.saved?.find(s=>s.name===t);if(o&&a&&l&&l.url===e.url&&l.modified===e.modified&&!l.used_by.length&&l.url!==a.planUrl)try{await this.host.hass.callWS({type:"houseplan/plans/delete",name:t});const s=this.host._spaceDialog;s?.saved&&(this.host._spaceDialog={...s,saved:s.saved.filter(s=>s.name!==t)})}catch(t){this.host._showToast(this.host._t("toast.plan_delete_failed",{err:this.host._errText(t)}))}}_renderServerPlans(t){if(t.savedBusy)return a`
${this.host._t("space.loading")}
`;const s=t.saved||[];if(!s.length)return a`
${this.host._t("space.no_saved")}
`;return a`
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{l as t,a_ as s,A as e,x as o,b as a,ci as l,cj as i,ck as h,cl as c,aX as n,cm as r,cr as p,cn as d,co as _,cp as u,cq as g,di as m,aW as b,aY as $,dj as v}from"./houseplan-card-6Hf8VPda.js";import{i as f,c as y,e as w,r as D,a as k,b as S,g as C,t as M}from"./backdrop-pick-BsRoeWMx.js";const F=1e3,x=t=>{if(!t.trim())return null;const s=Number(t.replace(",","."));return Number.isFinite(s)?s:null},T="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";class L{constructor(t){this.host=t,this._toggleServerPlans=async()=>{const t=this.host._spaceDialog;if(t)if(t.pickSaved)this.host._spaceDialog={...t,pickSaved:!1};else{this.host._spaceDialog={...t,pickSaved:!0,savedBusy:!0};try{const t=await this.host.hass.callWS({type:"houseplan/plans/list"}),s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,saved:t?.plans||[],savedBusy:!1})}catch(t){const s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,saved:[],savedBusy:!1}),this.host._showToast(this.host._t("toast.plans_list_failed",{err:this.host._errText(t)}))}}}}_help(l){const i=`${l}.aria`,h=t(this.host.hass,this.host._config?.language);return s(h,l)&&s(h,i)?a``:e}_openSpaceDialog(t,s){if(!this.host._serverStorage||!this.host._serverCfg)return void this.host._showToast(this.host._t("toast.integration_missing"));if("edit"===t){const e=this.host._serverCfg.spaces.find(t=>t.id===s);if(!e)return;const o=l(e),a=e.settings?.custom_fill&&"object"==typeof e.settings.custom_fill?i(e.settings.custom_fill):null,p="none"===o.fill?{...a||h,a:0}:a;return void(this.host._spaceDialog={mode:t,spaceId:s,title:e.title,planUrl:e.plan_url||null,planFile:null,source:e.plan_url?"file":"draw",showBorders:o.showBorders,showNames:o.showNames,zeroWallStyle:r(e),displayTouched:!0,hideDecor:o.hideDecor,hideOpenings:o.hideOpenings,roomColor:o.color,roomOpacity:o.opacity,fillMode:"none"===o.fill?"custom":o.fill,customFill:p,glowEnabled:o.glow,bgColor:o.bgColor,bgMode:"static"===e.settings?.bg_mode||"daynight"===e.settings?.bg_mode?e.settings.bg_mode:null,northDeg:n({},e.settings),sunRays:"boolean"==typeof e.settings?.sun_rays?e.settings.sun_rays:null,tempMin:o.tempMin,tempMax:o.tempMax,showLqi:o.showLqi??this.host._config?.show_signal??!0,cardFontScale:o.cardFontScale,labelTemp:o.labelTemp,labelHum:o.labelHum,labelLqi:o.labelLqi,labelLight:o.labelLight,cellCm:Number(e.cell_cm)>0?Number(e.cell_cm):5,cellCmInput:c(Number(e.cell_cm)>0?Number(e.cell_cm):5,this.host._imperial),cellCmTouched:!1,busy:!1})}const e=p(this.host._imperial);this.host._spaceDialog={mode:t,title:"",planUrl:null,planFile:null,...f(),hideDecor:!1,hideOpenings:!1,zeroWallStyle:"dashed",roomColor:g,roomOpacity:u,fillMode:"custom",customFill:{...h,a:0},glowEnabled:!0,bgColor:null,bgMode:"daynight",northDeg:null,sunRays:null,tempMin:_,tempMax:d,showLqi:this.host._config?.show_signal??!0,cardFontScale:1,labelTemp:!1,labelHum:!1,labelLqi:!1,labelLight:!1,cellCm:e,cellCmInput:c(e,this.host._imperial),cellCmTouched:!1,busy:!1}}async _pickPlanFile(t){const s=t.target,e=s.files?.[0];if(!e||!this.host._spaceDialog)return;s.value="";const o=await y(e);if("reject"===o.kind)return void this.host._showToast(this.host._t("toast.plan_formats"));if("guard"===o.kind)return void(this.host._backdropGuard=o.state);const a=await w(e,o.ext,e.name);this.host._spaceDialog&&(this.host._spaceDialog={...this.host._spaceDialog,planFile:a})}_renderBackdropGuard(){return D(this.host,t=>{this.host._spaceDialog&&(this.host._spaceDialog={...this.host._spaceDialog,planFile:t})},()=>{this.host._backdropGuard=null},this.host.hass)??e}_useServerPlan(t){const s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,planUrl:t,planFile:null,pickSaved:!1,savedAspect:void 0},this.host._aspectJob=this._readPlanAspect(t))}async _readPlanAspect(t){for(let s=0;s<40;s++){const s=this.host._display(t);if(s){const e=await new Promise(t=>{const e=new Image;e.onload=()=>t(e.naturalWidth&&e.naturalHeight?e.naturalWidth/e.naturalHeight:0),e.onerror=()=>t(0),e.src=s}),o=this.host._spaceDialog;return o&&o.planUrl===t&&Number.isFinite(e)&&e>0?(this.host._spaceDialog={...o,savedAspect:e},e):0}if(await new Promise(t=>setTimeout(t,150)),this.host._spaceDialog?.planUrl!==t)return 0}return 0}async _deleteServerPlan(t){const s=this.host._spaceDialog,e=s?.saved?.find(s=>s.name===t);if(!s||!e||e.used_by.length||e.url===s.planUrl)return;const o=await this.host._confirmDanger({key:"delete-plan",kind:"destructive",title:this.host._t("confirm.delete_plan_title"),message:this.host._t("confirm.delete_plan_body"),objectName:t,confirmLabel:this.host._t("btn.delete"),cancelLabel:this.host._t("btn.cancel")}),a=this.host._spaceDialog,l=a?.saved?.find(s=>s.name===t);if(o&&a&&l&&l.url===e.url&&l.modified===e.modified&&!l.used_by.length&&l.url!==a.planUrl)try{await this.host.hass.callWS({type:"houseplan/plans/delete",name:t});const s=this.host._spaceDialog;s?.saved&&(this.host._spaceDialog={...s,saved:s.saved.filter(s=>s.name!==t)})}catch(t){this.host._showToast(this.host._t("toast.plan_delete_failed",{err:this.host._errText(t)}))}}_renderServerPlans(t){if(t.savedBusy)return a`
diff --git a/custom_components/houseplan/frontend/houseplan-assets/hp-zigbee-topology-overlay-DVdGoL1j.js b/custom_components/houseplan/frontend/houseplan-assets/hp-zigbee-topology-overlay-B947ne3H.js
similarity index 93%
rename from custom_components/houseplan/frontend/houseplan-assets/hp-zigbee-topology-overlay-DVdGoL1j.js
rename to custom_components/houseplan/frontend/houseplan-assets/hp-zigbee-topology-overlay-B947ne3H.js
index 457a69d4..e0bca90e 100644
--- a/custom_components/houseplan/frontend/houseplan-assets/hp-zigbee-topology-overlay-DVdGoL1j.js
+++ b/custom_components/houseplan/frontend/houseplan-assets/hp-zigbee-topology-overlay-B947ne3H.js
@@ -1,4 +1,4 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{t as e,l as t,A as i,dQ as r,w as o,b as s,q as n}from"./houseplan-card-B_QYG0Py.js";import{t as a,a as h,r as d}from"./zigbee-topology-BnpLzLg7.js";import{zigbeeTopologyRuntimeSnapshot as p,subscribeZigbeeTopology as l}from"./zigbee-topology-runtime-JzXR8tg6.js";function c(e,t,i,r,o,s=9,n=4.5){const a=t.x-e.x,h=t.y-e.y,d=Math.hypot(a,h),p=d-Math.max(0,i)-Math.max(0,r);if(!Number.isFinite(d)||d<=0||p<4)return null;const l=a/d,c=h/d,_="toward-neighbor"===o,u=_?{x:t.x-l*Math.max(0,r),y:t.y-c*Math.max(0,r)}:{x:e.x+l*Math.max(0,i),y:e.y+c*Math.max(0,i)},m=Math.min(s,Math.max(4,.45*p)),v=Math.min(n,.5*m),b=_?-1:1,g=u.x+l*m*b,y=u.y+c*m*b,x=-c;return{tip:u,points:[u,{x:g+x*v,y:y+l*v},{x:g-x*v,y:y-l*v}]}}const _={revision:0,topologies:[],states:{}},u="data-hp-zigbee-topology-endpoint";class m extends e{constructor(){super(...arguments),this.devices=[],this.currentSpace="",this._runtime=_,this._hovered="",this._desiredEndpointIds=new Set,this._endpointSetDirty=!1,this._endpointElements=new Set,this._pointerOver=e=>{if(!this._mouseAllowed(e))return void this._clear();const t=this._deviceFromEvent(e),i=t?.dataset.id||"";i&&i!==this._hovered&&(this._hovered=i,this.requestUpdate())},this._pointerOut=e=>{const t=this._deviceFromEvent(e);if(!t||t.dataset.id!==this._hovered)return;const i=e.relatedTarget instanceof Element?e.relatedTarget.closest('[data-hp="device"]'):null;i?.dataset.id!==this._hovered&&this._clear()},this._pointerDown=e=>{"mouse"!==e.pointerType&&this._clear()}}connectedCallback(){super.connectedCallback();const e=this.getRootNode();e.host&&"undefined"!=typeof MutationObserver&&(this._hoverGateObserver=new MutationObserver(()=>{e.host.hasAttribute("data-pointer-hover")||this._clear()}),this._hoverGateObserver.observe(e.host,{attributes:!0,attributeFilter:["data-pointer-hover"]})),queueMicrotask(()=>this._connectParent())}disconnectedCallback(){this._release?.(),this._release=void 0,this._disconnectParent(),this._hoverGateObserver?.disconnect(),this._hoverGateObserver=void 0,this._hovered="",this._desiredEndpointIds.clear(),super.disconnectedCallback()}updated(e){e.has("hass")&&(this._release?.(),this._acceptRuntime(p(this.hass)),this._release=l(this.hass,()=>{this._acceptRuntime(p(this.hass))}));const t=e.has("currentSpace")||e.has("devices")||e.has("registry");t&&(this._mappedMemo=void 0,this.devices.some(e=>e.id===this._hovered&&e.space===this.currentSpace)||this._clear()),this._connectParent(),(this._endpointSetDirty||t)&&this._syncEndpointOwnership()}_acceptRuntime(e){e.revision===this._runtime.revision&&e.topologies===this._runtime.topologies&&e.states===this._runtime.states||(this._setDesiredEndpointIds([]),this._clearEndpointOwnership(),this._endpointSetDirty=!1,this._runtime=e,this._mappedMemo=void 0,this.requestUpdate())}_connectParent(){const e=this.parentElement;e&&e!==this._parent&&(this._disconnectParent(),this._parent=e,e.addEventListener("pointerover",this._pointerOver),e.addEventListener("pointerout",this._pointerOut),e.addEventListener("pointerdown",this._pointerDown,!0),"undefined"!=typeof MutationObserver&&(this._markerObserver=new MutationObserver(()=>this._syncEndpointOwnership()),this._markerObserver.observe(e,{childList:!0})),this._syncEndpointOwnership())}_disconnectParent(){this._parent?.removeEventListener("pointerover",this._pointerOver),this._parent?.removeEventListener("pointerout",this._pointerOut),this._parent?.removeEventListener("pointerdown",this._pointerDown,!0),this._markerObserver?.disconnect(),this._markerObserver=void 0,this._clearEndpointOwnership(),this._parent=void 0}_deviceFromEvent(e){for(const t of e.composedPath())if(t instanceof HTMLElement&&"device"===t.dataset.hp)return t;return null}_mouseAllowed(e){const t=this.getRootNode();return"mouse"===e.pointerType&&t.host?.hasAttribute?.("data-pointer-hover")}_clear(){this._setDesiredEndpointIds([]),this._clearEndpointOwnership(),this._endpointSetDirty=!1,this._hovered&&(this._hovered="",this.requestUpdate())}_setDesiredEndpointIds(e){const t=new Set(e);t.size===this._desiredEndpointIds.size&&[...t].every(e=>this._desiredEndpointIds.has(e))||(this._desiredEndpointIds=t,this._endpointSetDirty=!0)}_marker(e){return[...this._parent?.querySelectorAll('.dev[data-hp="device"][data-id]')||[]].find(t=>t.dataset.id===e)||null}_clearEndpointOwnership(){for(const e of this._endpointElements)e.removeAttribute(u);for(const e of this._parent?.querySelectorAll(`[${u}]`)||[])e.removeAttribute(u);this._endpointElements.clear()}_syncEndpointOwnership(){const e=new Set;for(const t of this._desiredEndpointIds){const i=this._marker(t);i&&e.add(i)}for(const t of this._endpointElements)e.has(t)||t.removeAttribute(u);for(const t of this._parent?.querySelectorAll(`[${u}]`)||[])e.has(t)||t.removeAttribute(u);for(const t of e)this._endpointElements.has(t)&&t.hasAttribute(u)||t.setAttribute(u,"");this._endpointElements=e,this._endpointSetDirty=!1}_position(e,t,i){const r=this._marker(e);if(!r)return null;const o=Number.parseFloat(r.style.left),s=Number.parseFloat(r.style.top),n=r.getBoundingClientRect();return Number.isFinite(o)&&Number.isFinite(s)?{x:o*t/100,y:s*i/100,width:n.width,height:n.height}:null}_targetText(e){if("remote-space"===e.kind){const i=this.spaces?.find(t=>t.id===e.spaceId)?.title;return"string"==typeof i&&i.trim()||a(t(this.hass),"route_other_space")}return a(t(this.hass),"unplaced-coordinator"===e.kind?"route_coordinator_not_on_plan":"route_device_not_on_plan")}_markerClearance(e){return.61*Math.max(e.width,e.height)+3}_points(e){return e.map(e=>`${e.x.toFixed(2)},${e.y.toFixed(2)}`).join(" ")}render(){if(!this._hovered||!this.registry||!this._runtime.topologies.length)return this._setDesiredEndpointIds([]),i;const e=this._mappedMemo,n=e&&e.runtime===this._runtime&&e.devices===this.devices&&e.registry===this.registry?e.mapped:h(this._runtime.topologies,this.devices,this.registry);e&&n===e.mapped||(this._mappedMemo={runtime:this._runtime,devices:this.devices,registry:this.registry,mapped:n});const p=d(n,this.currentSpace,this._hovered),l=this.clientWidth||this._parent?.clientWidth||1,_=this.clientHeight||this._parent?.clientHeight||1,u=this._position(this._hovered,l,_);if(!u)return this._setDesiredEndpointIds([]),i;const m=p.lines.map(e=>({...e,point:this._position(e.neighborMarkerId,l,_)})).filter(e=>!!e.point).map(e=>{const t=void 0===e.lqi?"rgba(145,155,165,.85)":r(e.lqi),i=e.routeDirection?c(u,e.point,this._markerClearance(u),this._markerClearance(e.point),e.routeDirection):null;return{...e,color:t,arrow:i}}),v=u.x>l/2,b=this._markerClearance(u)+18,g=p.parentTargets.map((e,t)=>{const i=30*(t-(p.parentTargets.length-1)/2),r={x:u.x+(v?-b:b),y:Math.max(14,Math.min(_-14,u.y+i))};return{target:e,point:r,arrow:c(u,r,this._markerClearance(u),0,"toward-neighbor")}});return this._setDesiredEndpointIds(m.length||g.length||p.remoteCount?[this._hovered,...m.map(e=>e.neighborMarkerId)]:[]),s`
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{t as e,l as t,A as i,dR as r,w as o,b as s,q as n}from"./houseplan-card-6Hf8VPda.js";import{t as a,a as h,r as d}from"./zigbee-topology-C3YPlOFO.js";import{zigbeeTopologyRuntimeSnapshot as p,subscribeZigbeeTopology as l}from"./zigbee-topology-runtime-Cjiy8VeA.js";function c(e,t,i,r,o,s=9,n=4.5){const a=t.x-e.x,h=t.y-e.y,d=Math.hypot(a,h),p=d-Math.max(0,i)-Math.max(0,r);if(!Number.isFinite(d)||d<=0||p<4)return null;const l=a/d,c=h/d,_="toward-neighbor"===o,u=_?{x:t.x-l*Math.max(0,r),y:t.y-c*Math.max(0,r)}:{x:e.x+l*Math.max(0,i),y:e.y+c*Math.max(0,i)},m=Math.min(s,Math.max(4,.45*p)),b=Math.min(n,.5*m),v=_?-1:1,g=u.x+l*m*v,y=u.y+c*m*v,x=-c;return{tip:u,points:[u,{x:g+x*b,y:y+l*b},{x:g-x*b,y:y-l*b}]}}const _={revision:0,topologies:[],states:{}},u="data-hp-zigbee-topology-endpoint";class m extends e{constructor(){super(...arguments),this.devices=[],this.currentSpace="",this._runtime=_,this._hovered="",this._desiredEndpointIds=new Set,this._endpointSetDirty=!1,this._endpointElements=new Set,this._pointerOver=e=>{if(!this._mouseAllowed(e))return void this._clear();const t=this._deviceFromEvent(e),i=t?.dataset.id||"";i&&i!==this._hovered&&(this._hovered=i,this.requestUpdate())},this._pointerOut=e=>{const t=this._deviceFromEvent(e);if(!t||t.dataset.id!==this._hovered)return;const i=e.relatedTarget instanceof Element?e.relatedTarget.closest('[data-hp="device"]'):null;i?.dataset.id!==this._hovered&&this._clear()},this._pointerDown=e=>{"mouse"!==e.pointerType&&this._clear()}}connectedCallback(){super.connectedCallback();const e=this.getRootNode();e.host&&"undefined"!=typeof MutationObserver&&(this._hoverGateObserver=new MutationObserver(()=>{e.host.hasAttribute("data-pointer-hover")||this._clear()}),this._hoverGateObserver.observe(e.host,{attributes:!0,attributeFilter:["data-pointer-hover"]})),queueMicrotask(()=>this._connectParent())}disconnectedCallback(){this._release?.(),this._release=void 0,this._disconnectParent(),this._hoverGateObserver?.disconnect(),this._hoverGateObserver=void 0,this._hovered="",this._desiredEndpointIds.clear(),super.disconnectedCallback()}updated(e){e.has("hass")&&(this._release?.(),this._acceptRuntime(p(this.hass)),this._release=l(this.hass,()=>{this._acceptRuntime(p(this.hass))}));const t=e.has("currentSpace")||e.has("devices")||e.has("registry");t&&(this._mappedMemo=void 0,this.devices.some(e=>e.id===this._hovered&&e.space===this.currentSpace)||this._clear()),this._connectParent(),(this._endpointSetDirty||t)&&this._syncEndpointOwnership()}_acceptRuntime(e){e.revision===this._runtime.revision&&e.topologies===this._runtime.topologies&&e.states===this._runtime.states||(this._setDesiredEndpointIds([]),this._clearEndpointOwnership(),this._endpointSetDirty=!1,this._runtime=e,this._mappedMemo=void 0,this.requestUpdate())}_connectParent(){const e=this.parentElement;e&&e!==this._parent&&(this._disconnectParent(),this._parent=e,e.addEventListener("pointerover",this._pointerOver),e.addEventListener("pointerout",this._pointerOut),e.addEventListener("pointerdown",this._pointerDown,!0),"undefined"!=typeof MutationObserver&&(this._markerObserver=new MutationObserver(()=>this._syncEndpointOwnership()),this._markerObserver.observe(e,{childList:!0})),this._syncEndpointOwnership())}_disconnectParent(){this._parent?.removeEventListener("pointerover",this._pointerOver),this._parent?.removeEventListener("pointerout",this._pointerOut),this._parent?.removeEventListener("pointerdown",this._pointerDown,!0),this._markerObserver?.disconnect(),this._markerObserver=void 0,this._clearEndpointOwnership(),this._parent=void 0}_deviceFromEvent(e){for(const t of e.composedPath())if(t instanceof HTMLElement&&"device"===t.dataset.hp)return t;return null}_mouseAllowed(e){const t=this.getRootNode();return"mouse"===e.pointerType&&t.host?.hasAttribute?.("data-pointer-hover")}_clear(){this._setDesiredEndpointIds([]),this._clearEndpointOwnership(),this._endpointSetDirty=!1,this._hovered&&(this._hovered="",this.requestUpdate())}_setDesiredEndpointIds(e){const t=new Set(e);t.size===this._desiredEndpointIds.size&&[...t].every(e=>this._desiredEndpointIds.has(e))||(this._desiredEndpointIds=t,this._endpointSetDirty=!0)}_marker(e){return[...this._parent?.querySelectorAll('.dev[data-hp="device"][data-id]')||[]].find(t=>t.dataset.id===e)||null}_clearEndpointOwnership(){for(const e of this._endpointElements)e.removeAttribute(u);for(const e of this._parent?.querySelectorAll(`[${u}]`)||[])e.removeAttribute(u);this._endpointElements.clear()}_syncEndpointOwnership(){const e=new Set;for(const t of this._desiredEndpointIds){const i=this._marker(t);i&&e.add(i)}for(const t of this._endpointElements)e.has(t)||t.removeAttribute(u);for(const t of this._parent?.querySelectorAll(`[${u}]`)||[])e.has(t)||t.removeAttribute(u);for(const t of e)this._endpointElements.has(t)&&t.hasAttribute(u)||t.setAttribute(u,"");this._endpointElements=e,this._endpointSetDirty=!1}_position(e,t,i){const r=this._marker(e);if(!r)return null;const o=Number.parseFloat(r.style.left),s=Number.parseFloat(r.style.top),n=r.getBoundingClientRect();return Number.isFinite(o)&&Number.isFinite(s)?{x:o*t/100,y:s*i/100,width:n.width,height:n.height}:null}_targetText(e){if("remote-space"===e.kind){const i=this.spaces?.find(t=>t.id===e.spaceId)?.title;return"string"==typeof i&&i.trim()||a(t(this.hass),"route_other_space")}return a(t(this.hass),"unplaced-coordinator"===e.kind?"route_coordinator_not_on_plan":"route_device_not_on_plan")}_markerClearance(e){return.61*Math.max(e.width,e.height)+3}_points(e){return e.map(e=>`${e.x.toFixed(2)},${e.y.toFixed(2)}`).join(" ")}render(){if(!this._hovered||!this.registry||!this._runtime.topologies.length)return this._setDesiredEndpointIds([]),i;const e=this._mappedMemo,n=e&&e.runtime===this._runtime&&e.devices===this.devices&&e.registry===this.registry?e.mapped:h(this._runtime.topologies,this.devices,this.registry);e&&n===e.mapped||(this._mappedMemo={runtime:this._runtime,devices:this.devices,registry:this.registry,mapped:n});const p=d(n,this.currentSpace,this._hovered),l=this.clientWidth||this._parent?.clientWidth||1,_=this.clientHeight||this._parent?.clientHeight||1,u=this._position(this._hovered,l,_);if(!u)return this._setDesiredEndpointIds([]),i;const m=p.lines.map(e=>({...e,point:this._position(e.neighborMarkerId,l,_)})).filter(e=>!!e.point).map(e=>{const t=void 0===e.lqi?"rgba(145,155,165,.85)":r(e.lqi),i=e.routeDirection?c(u,e.point,this._markerClearance(u),this._markerClearance(e.point),e.routeDirection):null;return{...e,color:t,arrow:i}}),b=u.x>l/2,v=this._markerClearance(u)+18,g=p.parentTargets.map((e,t)=>{const i=30*(t-(p.parentTargets.length-1)/2),r={x:u.x+(b?-v:v),y:Math.max(14,Math.min(_-14,u.y+i))};return{target:e,point:r,arrow:c(u,r,this._markerClearance(u),0,"toward-neighbor")}});return this._setDesiredEndpointIds(m.length||g.length||p.remoteCount?[this._hovered,...m.map(e=>e.neighborMarkerId)]:[]),s`
${m.length||g.length?o`
`)}
- ${g.map(e=>s`
s`
${this._targetText(e.target)}
`)}
${p.remoteCount?s`
`${Number(e[0].toFixed(4))} ${Number(e[1].toFixed(4))}`;function j(e){let t=0;for(let n=0;nArray.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1])).map(e=>[Number(e[0]),Number(e[1])]),n=t[t.length-1];return t.length>1&&t[0][0]===n[0]&&t[0][1]===n[1]&&t.pop(),t}(e);if(n.length<3)return[];const o=!t;return j(n)>0===o?n:[...n].reverse()}function O(e,t,o){return e.length?`M ${e.map(e=>C(n(e,o,t))).join(" L ")} Z`:""}function A(e,t,n){const o=t[1]-e[1],i=-(t[0]-e[0]),a=n.rotDeg*Math.PI/180;return o*Math.sin(a)+i*Math.cos(a)}function B(t,o,i=e){if(!Number.isFinite(o)||o<0)throw new Error("invalid floor edge height");const a=(t||[]).map(e=>(e||[]).map((e,t)=>function(e,t){const n=N(e,t);if(!n.length)return n;let o=0;for(let e=1;e0)).filter(e=>e.length>=3&&Math.abs(j(e))>=1e-9)).filter(e=>e.length&&j(e[0])>0);a.sort((e,t)=>{const n=e[0][0],o=t[0][0];return n[0]-o[0]||n[1]-o[1]||Math.abs(j(t[0]))-Math.abs(j(e[0]))});const r=[],s=[];let l=0;for(let e=0;ee.depth-t.depth||e.component-t.component||e.edge-t.edge),{footprintPath:r.join(" "),sides:s,componentCount:a.length,edgeCount:l}}function R(e,t){return e^=Math.round(64*(Number.isFinite(t)?t:0)),Math.imul(e,16777619)>>>0}const H=Object.freeze({revision:1,leafThicknessRatio:.04,frameThicknessRatio:.055,gateTurnDeg:10,gateTopRatio:.88,windowBottomRatio:.27,windowTopRatio:.78,doorTopRatio:.92});H.leafThicknessRatio,H.frameThicknessRatio;const F=e=>e.every(Number.isFinite);function T(e,t){return Object.freeze([Object.is(e,-0)?0:e,Object.is(t,-0)?0:t])}function L(e,t){return[e[0]+t[0],e[1]+t[1]]}function V(e,t){return[e[0]-t[0],e[1]-t[1]]}function G(e,t){return[e[0]*t,e[1]*t]}function W(e,t,n,o){const i=e[0]*n,a=e[1]*o,r=t*Math.PI/180;return[i*Math.cos(r)-a*Math.sin(r),i*Math.sin(r)+a*Math.cos(r)]}function E(e,t,n,i,a,r,s){const l=e.flipH?-1:1,c="gate"===e.type?1:e.flipV?-1:1,d=o(e.type,e.flipV,e.angle,e.face);return{leaf:t,hinge:L([e.x+d.ox,e.y+d.oy],W(n,e.angle,l,c)),closedVector:W(i,e.angle,l,c),quarterVector:W([-i[1],i[0]],e.angle,l,c),turnDeg:a,bottom:r,top:s}}const q=e=>`${Number(e[0].toFixed(4))} ${Number(e[1].toFixed(4))}`;function D(e,t,o,i,a={}){const r=o.map(e=>n(e.point,e.z,i));return Object.freeze({kind:e,material:t,d:`M ${r.map(q).join(" L ")} Z`,depth:Math.max(...r.map(e=>e[1])),...a})}function _(e,t,n,o,i,a,r,s={}){return D(e,t,[{point:n,z:i},{point:o,z:i},{point:o,z:a},{point:n,z:a}],r,s)}function U(t,o,i=e){const a=Math.max(0,Math.min(1,Number.isFinite(o)?o:0));return t.leaves.map(e=>{const o=function(e,t){const n=e.turnDeg*t*Math.PI/180;return[e.hinge[0]+e.closedVector[0]*Math.cos(n)+e.quarterVector[0]*Math.sin(n),e.hinge[1]+e.closedVector[1]*Math.cos(n)+e.quarterVector[1]*Math.sin(n)]}(e,a),r=n(e.hinge,e.bottom,i),s=n(o,e.bottom,i),l=n(o,e.top,i),c=n(e.hinge,e.top,i),d="window"===t.type?"light-window":"matte-leaf",f="window"===t.type?Object.freeze([_("window-insert","light-window",e.hinge,o,e.bottom,e.top,i)]):function(e,t,n,o){const i=V(t,e.hinge),a=Math.hypot(i[0],i[1]);if(!(a>1e-9&&n>0))return Object.freeze([]);const r=T(-i[1]*n/(2*a),i[0]*n/(2*a)),s=L(e.hinge,r),l=L(t,r),c=V(e.hinge,r),d=V(t,r),f=[_("leaf-back","matte-leaf",d,c,e.bottom,e.top,o),_("leaf-front","matte-leaf",s,l,e.bottom,e.top,o),_("leaf-edge","matte-leaf",c,s,e.bottom,e.top,o,{edge:"hinge"}),_("leaf-edge","matte-leaf",l,d,e.bottom,e.top,o,{edge:"tip"}),D("leaf-top","matte-leaf",[{point:s,z:e.top},{point:c,z:e.top},{point:d,z:e.top},{point:l,z:e.top}],o)];return Object.freeze(f.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||String(e.edge||"").localeCompare(String(t.edge||""))))}(e,o,t.leafThickness,i);return Object.freeze({id:t.id,sourceIndex:t.sourceIndex,type:t.type,leaf:e.leaf,d:`M ${q(r)} L ${q(s)} L ${q(l)} L ${q(c)} Z`,shadowD:`M ${q(n(e.hinge,0,i))} L ${q(n(o,0,i))}`,depth:Math.max(r[1],s[1]),material:d,thickness:"window"===t.type?0:t.leafThickness,surfaces:f})})}const K=1e-9,Z=e=>e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function J(e){let t=0;for(let n=0;n=3&&e.every(Z)&&Math.abs(J(e))>K}function X(e,t,n){const o=n[0]-t[0],i=n[1]-t[1],a=o*o+i*i,r=a?Math.max(0,Math.min(1,((e[0]-t[0])*o+(e[1]-t[1])*i)/a)):0;return Math.hypot(e[0]-t[0]-r*o,e[1]-t[1]-r*i)}function Y(e,t,n=1e-7){for(let o=0;oe[1]!=r[1]>e[1]&&e[0]<(r[0]-a[0])*(e[1]-a[1])/(r[1]-a[1])+a[0]&&(n=!n)}return n}function te(e){return Math.max(0,Math.abs(J(e.outer))-(e.holes||[]).reduce((e,t)=>e+Math.abs(J(t)),0))}function ne(e){return!!e.id&&Q(e.outer)&&(e.holes||[]).every(Q)&&te(e)>K}function oe(e,t){if(!ne(t)||Y(e,t.outer)||!ee(e,t.outer))return!1;for(const n of t.holes||[])if(Y(e,n)||ee(e,n))return!1;return!0}function ie(e){if(!ne(e))return null;if(e.safePoint&&oe(e.safePoint,e))return[e.safePoint[0],e.safePoint[1]];const t=e.outer.map(e=>e[0]),n=e.outer.map(e=>e[1]),o=Math.min(...t),i=Math.max(...t),a=Math.min(...n),r=Math.max(...n),s=[[(o+i)/2,(a+r)/2],[t.reduce((e,t)=>e+t,0)/t.length,n.reduce((e,t)=>e+t,0)/n.length]];for(let t=0;t{if(!oe(t,e))return;const n=function(e,t){let n=1/0;for(const o of[t.outer,...t.holes||[]])for(let t=0;tc+K&&(l=t,c=n)};s.forEach(d);for(let e=1;e<16;e++)for(let t=1;t<16;t++)d([o+(i-o)*e/16,a+(r-a)*t/16]);return l}function ae(e){if(!Z(e.floorAnchor))return null;const t=e.roomsValidated?e.rooms:e.rooms.filter(ne),n=e.preferredRoomId&&t.find(t=>t.id===e.preferredRoomId)||null;let o=null;return"device"===e.kind?(n&&oe(e.floorAnchor,n)&&(o=n),o||(o=t.filter(t=>oe(e.floorAnchor,t)).sort((e,t)=>te(e)-te(t)||((e,t)=>et?1:0)(e.id,t.id))[0]||null)):o=n,o?{id:o.id,area:te(o),safePoint:e.roomsValidated&&o.safePoint?[o.safePoint[0],o.safePoint[1]]:ie(o)}:null}function re(t,o,i,a=e,r=[0,0]){if(!Z(t)||!Z(o)||o[0]<0||o[1]<0||!Number.isFinite(i)||!Z(r))throw new Error("invalid isometric overlay footprint");return[[t[0]-o[0],t[1]-o[1]],[t[0]+o[0],t[1]-o[1]],[t[0]+o[0],t[1]+o[1]],[t[0]-o[0],t[1]+o[1]]].map(e=>{const t=n(e,i,a);return[t[0]+r[0],t[1]+r[1]]})}function se(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function le(e,t,n,o){const i=se(e,t,n),a=se(e,t,o),r=se(n,o,e),s=se(n,o,t);return(i>K&&a<-K||i<-K&&a>K)&&(r>K&&s<-K||r<-K&&s>K)||(Math.abs(i)<=K&&X(n,e,t)<=K||Math.abs(a)<=K&&X(o,e,t)<=K||Math.abs(r)<=K&&X(e,n,o)<=K||Math.abs(s)<=K&&X(t,n,o)<=K)}function ce(e,t,n,o){return le(e,t,n,o)?0:Math.min(X(e,n,o),X(t,n,o),X(n,e,t),X(o,e,t))}const de=new WeakMap;function fe(e){if(!e.length)return null;let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const a of e){if(!Z(a))return null;t=Math.min(t,a[0]),n=Math.min(n,a[1]),o=Math.max(o,a[0]),i=Math.max(i,a[1])}return[t,n,o,i]}function ue(e,t){if(!t)return fe(e.outer);if(de.has(e))return de.get(e)??null;const n=fe(e.outer);return de.set(e,n),n}function he(e,t,n){return e[0]<=t[2]+n&&e[2]>=t[0]-n&&e[1]<=t[3]+n&&e[3]>=t[1]-n}function pe(e,t,n,o){return Math.min(t[0],n[0])<=e[2]+o&&Math.max(t[0],n[0])>=e[0]-o&&Math.min(t[1],n[1])<=e[3]+o&&Math.max(t[1],n[1])>=e[1]-o}function me(e,t,n,o,i){const a=ue(n,i);if(!a||!he(t,a,o))return!1;if(e.some(e=>function(e,t){return!!ee(e,t.outer)&&!(t.holes||[]).some(t=>ee(e,t))}(e,n)))return!0;if(n.outer.some(n=>n[0]>=t[0]&&n[0]<=t[2]&&n[1]>=t[1]&&n[1]<=t[3]&&ee(n,e)))return!0;for(const i of[n.outer,...n.holes||[]])for(let n=0;n"wall-side"===e.layer?0:"wall-top"===e.layer?1:2,Me=e=>{if("wall-side"===e.layer)return`${e.face.polygon}:${e.face.ring}:${e.face.edge}`;if("wall-top"===e.layer)return String(e.face.component);const t=e.surface;return`${t.sourceIndex}:${t.leaf??-1}:${t.kind}:${t.jamb??-1}:${t.edge??""}:${t.id}:${t.material}`};function be(e,t){const n=[...e.sides.map(e=>({layer:"wall-side",depth:e.depth,face:e})),...e.topFaces.map(e=>({layer:"wall-top",depth:e.depth,face:e})),...t.map(e=>({layer:"opening",depth:e.depth,surface:e}))];return n.sort((e,t)=>e.depth-t.depth||xe(e)-xe(t)||Me(e).localeCompare(Me(t))),Object.freeze(n)}const Se=Object.freeze({textLatinAdvance:.72,textWideAsciiAdvance:1,textWideAdvance:1.1,textSpaceAdvance:.4,textWidthSafety:1.08,deviceShellInset:.134375,deviceShellGap:.1,deviceSectionGap:.08,deviceBadgeMinWidth:.7875,deviceBadgeHeight:.7875,deviceBadgeInlinePadding:.28,deviceValueInlinePadding:.32,deviceAuxiliaryExtent:.7,deviceLqiFontSize:.38,deviceLqiTop:.734375,deviceLqiBelowBottomBadgeTop:1.571875,devicePadding:.08,roomNameLineHeight:1.25,roomAreaLinkWidth:1.1,roomMetricsTopGap:.15,roomMetricFontSize:.75,roomMetricLineHeight:1.25,roomMetricIconWidth:1.05,roomMetricInnerGap:.12,roomMetricRowGap:.55,roomMetricMinWidth:11,roomPadding:.4,openingLockHalfSize:.62,roomMetricTextCharacters:Object.freeze({temperature:10,humidity:8,lqi:6,light:24})});function $e(e){return[...String(e)].reduce((e,t)=>/\s/.test(t)?e+Se.textSpaceAdvance:/[MW@#%&]/.test(t)?e+Se.textWideAsciiAdvance:e+(t.codePointAt(0)>255?Se.textWideAdvance:Se.textLatinAdvance),0)*Se.textWidthSafety}function ke(e,t){return $e(e)*z(t||e)}function ze(e,t){return[Math.max(Math.abs(e.left),Math.abs(e.right))+t,Math.max(Math.abs(e.top),Math.abs(e.bottom))+t]}function Ie(e){if("opening-lock"===e.kind){const t=(Number.isFinite(e.size)&&e.size>0?e.size:0)*Se.openingLockHalfSize;return[t,t]}if("room-label"===e.kind){const t=Number.isFinite(e.font)&&e.font>0?e.font:0,n=v(e.room.settings?.name_scale),o=v(e.room.settings?.label_scale),i=($e(e.room.name||"")+(e.room.area?Se.roomAreaLinkWidth:0))*n,a=Se.roomNameLineHeight*n,r=[e.display.labelTemp?Se.roomMetricTextCharacters.temperature:0,e.display.labelHum?Se.roomMetricTextCharacters.humidity:0,e.display.labelLqi&&e.room.area?Se.roomMetricTextCharacters.lqi:0,e.display.labelLight?Se.roomMetricTextCharacters.light:0].filter(e=>e>0),s=Se.roomMetricFontSize*o,l=r.length?Math.max(Se.roomMetricMinWidth,r.reduce((e,t)=>e+Se.roomMetricIconWidth+Se.roomMetricInnerGap+t*Se.textLatinAdvance*Se.textWidthSafety,0)+(r.length-1)*Se.roomMetricRowGap)*s:0,c=r.length?s*Se.roomMetricLineHeight:0,d=ze({left:-Math.max(i,l)/2,right:Math.max(i,l)/2,top:-a/2,bottom:r.length?a/2+Se.roomMetricsTopGap+c:a/2},Se.roomPadding);return[d[0]*t,d[1]*t]}const t=Number.isFinite(e.core)&&e.core>0?e.core:0,n=e.presentation,o=null==n.valueText?1:Math.max(1,ke(n.valueText,n.valueFullText||n.valueText)+Se.deviceValueInlinePadding),i=[];n.valueBadge&&i.push(Math.max(Se.deviceBadgeMinWidth,ke(n.valueBadge.text,n.valueBadge.fullText||n.valueBadge.text)+Se.deviceBadgeInlinePadding));for(const e of x(n)){const t=e.text+e.suffix;i.push(Math.max(Se.deviceBadgeMinWidth,ke(t,t)+Se.deviceBadgeInlinePadding))}const a=n.valueBadge?.position||"right";let r;if(!i.length||"left"!==a&&"right"!==a)if(i.length){const e=i.reduce((e,t)=>e+t,0)+(i.length-1)*Se.deviceSectionGap,t=Math.max(o,e),n=1+Se.deviceShellGap+Se.deviceBadgeHeight;r="bottom"===a?{left:-t/2-Se.deviceShellInset,right:t/2+Se.deviceShellInset,top:-.5-Se.deviceShellInset,bottom:-.5+n+Se.deviceShellInset}:{left:-t/2-Se.deviceShellInset,right:t/2+Se.deviceShellInset,top:.5-n-Se.deviceShellInset,bottom:.5+Se.deviceShellInset}}else r={left:-.5-Se.deviceShellInset,right:-.5+o+Se.deviceShellInset,top:-.5-Se.deviceShellInset,bottom:.5+Se.deviceShellInset};else{const e=Math.max(...i),t=i.length*Se.deviceBadgeHeight+(i.length-1)*Se.deviceSectionGap,n=o+Se.deviceShellGap+e,s=Math.max(1,t);r="right"===a?{left:-.5-Se.deviceShellInset,right:-.5+n+Se.deviceShellInset,top:-s/2-Se.deviceShellInset,bottom:s/2+Se.deviceShellInset}:{left:.5-n-Se.deviceShellInset,right:.5+Se.deviceShellInset,top:-s/2-Se.deviceShellInset,bottom:s/2+Se.deviceShellInset}}const s=Se.deviceAuxiliaryExtent;if(r.left=Math.min(r.left,-s),r.right=Math.max(r.right,s),r.top=Math.min(r.top,-s),r.bottom=Math.max(r.bottom,s),n.pulse.animated){const e=Math.max(1,n.pulse.diameterScale)/2;r.left=Math.min(r.left,-e),r.right=Math.max(r.right,e),r.top=Math.min(r.top,-e),r.bottom=Math.max(r.bottom,e)}if(null!=n.lqiText){const e="bottom"===n.valueBadge?.position?Se.deviceLqiBelowBottomBadgeTop:Se.deviceLqiTop,t=$e(n.lqiText)*Se.deviceLqiFontSize/2;r.left=Math.min(r.left,-t),r.right=Math.max(r.right,t),r.bottom=Math.max(r.bottom,e+Se.deviceLqiFontSize)}const l=ze(r,Se.devicePadding);return[l[0]*t,l[1]*t]}function Pe(e,t){return e.flatMap((e,n)=>e.orphanReason?[]:[{id:String(e.id||n),sourceIndex:n,type:e.type,x:e.rx,y:e.ry,angle:Number(e.angle)||0,length:e.rlen>0?e.rlen:.9*t,flipH:!!e.flip_h,flipV:!!e.flip_v}])}function Ce(e){return{id:e.id,x:e.x,y:e.y,w:e.w,h:e.h,poly:e.poly,wall_ids:e.wall_ids}}function je(e,t){const n=e?.partitionHost;if(!n)return null;const o="gate"===t.type?!t.flipV:t.flipV;return{sourceIndex:t.sourceIndex,hostId:n.host.id,t:n.t,depth:n.depth,face:p(n,o)}}function Ne(n,o=H){const i=Pe(n.openings,n.coordinateScale),r=i.map(e=>je(n.openings[e.sourceIndex],e)),p=a(t,n.cellCm),m=a(s,n.cellCm),g=a(l,n.cellCm);return{key:`${n.space.id}|${function(e){let t=2166136261;const n=e=>{if("number"!=typeof e)if("string"!=typeof e)if("boolean"!=typeof e)if(Array.isArray(e)){t=R(t,e.length);for(const t of e)n(t)}else{if(e&&"object"==typeof e){const t=e;for(const e of Object.keys(t).sort())n(e),n(t[e]);return}t=R(t,-1)}else t=R(t,e?1:0);else for(const n of e)t=R(t,n.codePointAt(0)||0);else t=R(t,e)};return n(e),t.toString(36)}({rooms:n.space.rooms.map(Ce),walls:n.walls,openCuts:n.openCuts,openings:i,openingHosts:r,openingGeometryPolicy:o,partitions:n.space.partitions,columns:n.space.wall_columns,cellCm:n.cellCm,gridPitch:n.gridPitch,wallKeyPitch:n.wallKeyPitch,camera:e,wallHeight:p,raisedHeight:g,floorEdgeHeight:m,algorithm:4})}`,build:()=>{n.onBuild();const a=c(n.space,n.cellCm,n.gridPitch,2e-4*n.gridPitch,n.partitionCuts()).all,s=n.roomOpenings(),l=n.walls.length||a.length?d(n.space.rooms,n.walls,n.openCuts,s,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale,a):null;if(l&&("failed-core"===l.status||"not-applicable"===l.status))throw new Error("wall boolean geometry failed");const m=l?.paperGeom??f(n.space.rooms,n.walls,n.openCuts,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale);if(!m)throw new Error("floor boolean geometry failed");const g=l?.openingIndex||u(n.space.rooms,n.walls,n.openCuts,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale),w=i.map((e,i)=>{const a=r[i],s="gate"===e.type?!e.flipV:e.flipV,l=a?a.face:n.walls.length||"gate"===e.type?h(g,{x:e.x,y:e.y,angle:e.angle,length:e.length,flip_v:s}):{ox:0,oy:0,cm:0,side:-1};return function(e,n=t,o=H){const i=e.face.cm??0;if(!F([e.x,e.y,e.angle,e.length,e.face.ox,e.face.oy,i,n])||!(e.length>0)||!(n>0)||-1!==e.face.side&&1!==e.face.side||i<0)throw new Error("invalid isometric opening input");const a=e.length/2,r=e.angle*Math.PI/180,s=T(Math.cos(r),Math.sin(r)),l=T(-Math.sin(r),Math.cos(r)),c=T(e.x,e.y),d=T(e.x-s[0]*a,e.y-s[1]*a),f=T(e.x+s[0]*a,e.y+s[1]*a),u=T(e.face.ox,e.face.oy),h=T(d[0]+u[0],d[1]+u[1]),p=T(f[0]+u[0],f[1]+u[1]),m=T(d[0]-u[0],d[1]-u[1]),g=T(f[0]-u[0],f[1]-u[1]),w=Object.freeze({center:c,tangent:s,normal:l,start:d,end:f}),y=Object.freeze({side:e.face.side,cm:i,depth:2*Math.hypot(e.face.ox,e.face.oy),offset:u,selectedStart:h,selectedEnd:p,oppositeStart:m,oppositeEnd:g}),v="passage"===e.type?[]:[Object.freeze({jamb:0,center:d,selected:h,opposite:m}),Object.freeze({jamb:1,center:f,selected:p,opposite:g})];let x;if("passage"===e.type)x=[];else if("gate"===e.type){const t=e.face.side*o.gateTurnDeg;x=[E(e,0,[-a,0],[a,0],t,0,n*o.gateTopRatio),E(e,1,[a,0],[-a,0],-t,0,n*o.gateTopRatio)]}else x="window"===e.type?[E(e,0,[-a,0],[a,0],-90,n*o.windowBottomRatio,n*o.windowTopRatio),E(e,1,[a,0],[-a,0],90,n*o.windowBottomRatio,n*o.windowTopRatio)]:[E(e,0,[-a,0],[e.length,0],-90,0,n*o.doorTopRatio)];return Object.freeze({id:e.id,sourceIndex:e.sourceIndex,type:e.type,wallHeight:n,leafThickness:n*o.leafThicknessRatio,frameThickness:n*o.frameThicknessRatio,axis:w,face:y,reveals:Object.freeze(v),leaves:Object.freeze(x.map(e=>Object.freeze({...e,hinge:T(e.hinge[0],e.hinge[1]),closedVector:T(e.closedVector[0],e.closedVector[1]),quarterVector:T(e.quarterVector[0],e.quarterVector[1])})))})}({...e,face:l},p,o)}),y=Object.freeze(w);return{walls:l?.components.flatMap(e=>e.geom)||[],floor:m,openings:y,openingSurfaces:Object.freeze(y.flatMap(t=>function(t,n=e){if("passage"===t.type)return Object.freeze([]);const o=[];if(t.face.depth>1e-9)for(const e of t.reveals)o.push(_("jamb-reveal","reveal",e.selected,e.opposite,0,t.wallHeight,n,{jamb:e.jamb}));if("window"!==t.type||!t.leaves.length)return Object.freeze(o.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||(e.jamb??0)-(t.jamb??0)));const i=Math.min(...t.leaves.map(e=>e.bottom)),a=Math.max(...t.leaves.map(e=>e.top)),r=Math.min(t.frameThickness,Math.hypot(t.axis.end[0]-t.axis.start[0],t.axis.end[1]-t.axis.start[1])/4,(a-i)/4),s=L(t.axis.start,G(t.axis.tangent,r)),l=V(t.axis.end,G(t.axis.tangent,r)),c=t.face.depth>1e-9?[t.face.offset,T(-t.face.offset[0],-t.face.offset[1])]:[t.face.offset];for(const e of c){const c=L(t.axis.start,e),d=L(t.axis.end,e),f=L(s,e),u=L(l,e);o.push(_("window-frame-side","light-frame",c,f,i,a,n,{jamb:0}),_("window-frame-side","light-frame",u,d,i,a,n,{jamb:1}),_("window-frame-top","light-frame",f,u,Math.max(i,a-r),a,n))}return t.face.depth>1e-9&&o.push(D("window-sill","light-sill",[{point:t.face.selectedStart,z:i},{point:t.face.selectedEnd,z:i},{point:t.face.oppositeEnd,z:i},{point:t.face.oppositeStart,z:i}],n)),Object.freeze(o.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||(e.jamb??0)-(t.jamb??0)))}(t).map(e=>Object.freeze({...e,id:t.id,sourceIndex:t.sourceIndex,type:t.type}))))}}}}const Oe=e=>Array.isArray(e)?e:[];function Ae(e,t){const o=e=>Oe(e).flatMap(e=>Array.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1])?[n([Number(e[0]),Number(e[1])],t)]:[]);return Oe(e).flatMap(e=>{const t=Oe(e);if(!t.length)return[];const n=o(t[0]);if(n.length<3)return[];return[{outer:n,holes:t.slice(1).map(o).filter(e=>e.length>=3)}]})}function Be(o){const i=a(t,o.cellCm),r=a(s,o.cellCm),c=a(l,o.cellCm),d=S(o.cache,o.source.key);let f=d.hit?d.value:void 0;if(!f){const a=o.source.build(),s=function(o,i=e,a=t){if(!Number.isFinite(a)||a<0)throw new Error("invalid wall height");const r=[],s=[],l=[],c=[];let d=0;for(let e=0;e<(o||[]).length;e++){const t=o[e],f=[];let u=-1/0;for(let o=0;o<(t||[]).length;o++){const s=N(t[o],o>0);if(s.length<3||Math.abs(j(s))<1e-9)continue;const h=O(s,i,a);r.push(h),f.push(h),u=Math.max(u,...s.map(e=>n(e,a,i)[1])),d+=s.length;for(let t=0;te.depth-t.depth||e.polygon-t.polygon||e.ring-t.ring||e.edge-t.edge),s.sort((e,t)=>e.depth-t.depth||e.component-t.component),{topPath:r.join(" "),topFaces:s,sides:l,contactPath:c.join(" "),edgeCount:d}}(a.walls,e,i),l=Ae(a.walls,i);f={geometry:s,floor:B(a.floor,r),wallSilhouettes:Object.freeze([...l,...s.sides.map(e=>({outer:e.points}))]),openings:a.openings,openingSurfaces:a.openingSurfaces},$(o.cache,o.source.key,f,8)}const u=function(e){let t=1/0,n=1/0,o=-1/0,i=-1/0;const a=(e,a=0)=>{t=Math.min(t,e[0]-a),n=Math.min(n,e[1]-a),o=Math.max(o,e[0]+a),i=Math.max(i,e[1]+a)};for(const t of e)if("passage"!==t.type){a(t.axis.start),a(t.axis.end),a(t.face.selectedStart),a(t.face.selectedEnd),a(t.face.oppositeStart),a(t.face.oppositeEnd);for(const e of t.leaves){const n=Math.hypot(e.closedVector[0],e.closedVector[1])+t.leafThickness/2;a(e.hinge,n)}}return F([t,n,o,i])?{x:t,y:n,w:o-t,h:i-n}:null}(f.openings),h=u?Re(o.liveFrame,u):o.liveFrame,p=k({rect:h,wallHeight:i,openingHeight:i,floorDepth:r,raisedHeight:c});return{key:o.source.key,...f,frame:p}}const Re=(e,t)=>{const n=Math.min(e.x,t.x),o=Math.min(e.y,t.y);return{x:n,y:o,w:Math.max(e.x+e.w,t.x+t.w)-n,h:Math.max(e.y+e.h,t.y+t.h)-o}},He=e=>{if(!e.length||!e.every(e=>Number.isFinite(e[0])&&Number.isFinite(e[1])))return null;const t=e.map(e=>e[0]),n=e.map(e=>e[1]),o=Math.min(...t),i=Math.min(...n);return{x:o,y:i,w:Math.max(...t)-o,h:Math.max(...n)-i}},Fe=(e,t)=>{const n=e.placement,o=t?n.visualScene:n.raisedScene,[i,a]=e.screenHalfSize,r=t?n.footprint:n.footprint.map(e=>[e[0]-n.nudgeScene[0],e[1]-n.nudgeScene[1]]);return[n.floorScene,...r,[o[0]-i,o[1]-a],[o[0]+i,o[1]-a],[o[0]+i,o[1]+a],[o[0]-i,o[1]+a]]},Te=(e,t)=>void 0===t?e:e.filter(e=>e.placement.owner?.id===t);function Le(e,t){return e?He(Te(e.entries,t).flatMap(e=>Fe(e,!0))):null}function Ve(e){const t=Te(e.entries,e.ownerId),n=He(t.flatMap(e=>Fe(e,!1))),o=n?Re(e.baseBounds,n):e.baseBounds,i=e.targetView(o);if(!(i&&i.w>0&&i.h>0&&[i.x,i.y,i.w,i.h].every(Number.isFinite)))return null;const a=e.stageSize;if(!(n&&a&&a.width>0&&a.height>0))return{bounds:o,view:i};const r=e=>Math.max(e.w/a.width,e.h/a.height),s=t=>{const o=48*t,i={x:n.x-o,y:n.y-o,w:n.w+2*o,h:n.h+2*o},a=Re(e.baseBounds,i),r=e.targetView(a);return r&&[r.x,r.y,r.w,r.h].every(Number.isFinite)&&r.w>0&&r.h>0?{bounds:a,view:r}:null};let l=0,c=Math.max(r(i),Number.EPSILON),d=s(c);for(let e=0;d&&r(d.view)>c*(1+1e-10)&&e<24;e++)l=c,c*=2,d=s(c);if(!d)return null;for(let e=0;e<40;e++){const e=(l+c)/2,t=s(e);if(!t)return null;r(t.view)<=e?(c=e,d=t):l=e}return d}const Ge=new WeakMap,We=2048,Ee=new WeakMap,qe=new WeakMap,De=new WeakMap;function _e(e,t){if(e.size!==t.size)return!1;for(const[n,o]of t)if(e.get(n)!==o)return!1;return!0}function Ue(e){const t=Ge.get(e.rooms);if(t)return t;const n=e.rooms.flatMap((e,t)=>{const n=w(e);return n&&n.length>=3?[{room:e,index:t,poly:n}]:[]}),o=Object.freeze(n.map(({room:e,index:t,poly:o})=>{const i=y(o,n.filter(e=>e.index!==t).map(e=>e.poly)),a={id:e.id||`room-index-${t}`,outer:o.map(e=>[e[0],e[1]]),holes:i.map(e=>e.map(e=>[e[0],e[1]]))};return{room:e,overlayRoom:{...a,safePoint:ie(a)||void 0}}}));return Ge.set(e.rooms,o),o}function Ke(o){const s=o.stageSize&&o.stageSize.width>0&&o.stageSize.height>0?Math.max(o.view.w/o.stageSize.width,o.view.h/o.stageSize.height):Math.max(o.view.w,o.view.h)/1e3,l=Ue(o.space),c=l.map(e=>e.overlayRoom),d=a(t,o.cellCm),f=a(i,o.cellCm),u=new Map,h=new Map,p=new Map,m=[];let g=Ee.get(o.wallSilhouettes);g||(g=new Map,Ee.set(o.wallSilhouettes,g));let w=qe.get(l);w||(w=new Map,qe.set(l,w));const y=o.iconPct*r(o.space)*o.kioskIconScale/100,v=o.deviceBasePct*r(o.space)*o.kioskIconScale/100,x=(a,r,l,u,h,p=!1)=>{const m=`${!1===o.resolveCollisions?"fit":"live"}\0${a}\0${r}`,y=[l[0],l[1],u[0],u[1],h||"",d,f,o.layers.shadows?1:0,p?1:0].join("|"),v=`${y}|${s}`,x=S(g,m);if(x.hit&&x.value.signature===v)return x.value.placement;if(x.hit&&x.value.shapeSignature===y&&s<=x.value.unitsPerPixel){const e=x.value.placement,t=e.nudgeDistanceCss*x.value.unitsPerPixel/s;if(!e.nearWallBefore||e.cleared&&t<=48)return e}const M=`${a}\0${r}`,b=[l[0],l[1],h||""].join("|"),k=S(w,M),z=k.hit&&k.value.signature===b?k.value.owner:ae({kind:a,floorAnchor:l,rooms:c,roomsValidated:!0,preferredRoomId:h});k.hit&&k.value.signature===b||$(w,M,{signature:b,owner:z},We);const I=function(o){const a=o.camera||e,r=o.wallHeight??t,s=o.visualOffset??i,l=o.sceneUnitsPerCssPixel??1,c=o.safetyGapCssPx??4,d=o.maxNudgeCssPx??48;if(!Z(o.floorAnchor)||!Z(o.footprintHalfSize)||o.footprintHalfSize[0]<0||o.footprintHalfSize[1]<0||!Number.isFinite(r)||r<0||!Number.isFinite(s)||s<0||!Number.isFinite(l)||l<=0||!Number.isFinite(c)||c<0||!Number.isFinite(d)||d<0)throw new Error("invalid isometric overlay input");const f=[o.floorAnchor[0],o.floorAnchor[1]],u=n(f,0,a),h=(p=o.kind,!o.showBorders||"device"!==p&&"room-label"!==p&&"opening-lock"!==p?"floor":"raised");var p;if("floor"===h)return{plane:h,owner:null,floorAnchor:f,floorScene:u,raisedScene:u,visualScene:u,footprint:[],nudgeScene:[0,0],nudgeCss:[0,0],nudgeDistanceCss:0,nudged:!1,nearWallBefore:!1,nearWallAfter:!1,cleared:!0,capped:!1,grounding:{center:u,visible:!1},tether:ye(u,u,!1),status:"ok",reason:null};const m=r+s,g=n(f,m,a),w=o.ownerAlreadyResolved?o.resolvedOwner??null:ae(o),y=o.wallGeometryValidated??o.wallSilhouettes.every(ge),v=c*l,x=re(f,o.footprintHalfSize,m,a),M=e=>{const t=fe(e);return!!t&&o.wallSilhouettes.some(n=>me(e,t,n,v,!0===o.wallGeometryValidated))},b=!y||M(x);let S=0,$=[0,0],k=null,z=!1,I=y?"ok":"degraded",P=y?null:"invalid-wall-geometry";if(y&&b)if(w)if(w.safePoint){const e=o.rooms.find(e=>e.id===w.id)||null,t=n(w.safePoint,m,a),i=t[0]-g[0],r=t[1]-g[1],s=Math.hypot(i,r);if(s<=K)I="degraded",P="invalid-safe-point";else{const t=i/s,n=r/s,a=Math.min(d,s/l),c=a*l/s,u=[f[0]+(w.safePoint[0]-f[0])*c,f[1]+(w.safePoint[1]-f[1])*c],h=[t*a*l,n*a*l],p=fe([...x,...x.map(e=>[e[0]+h[0],e[1]+h[1]])]),m=p?o.wallSilhouettes.filter(e=>{const t=ue(e,!0===o.wallGeometryValidated);return!!t&&he(p,t,v)}):o.wallSilhouettes,g=!!e&&we(f,u,e),y=e=>{const i=[t*e*l,n*e*l],a=x.map(e=>[e[0]+i[0],e[1]+i[1]]),r=fe(a);return!!r&&m.some(e=>me(a,r,e,v,!0===o.wallGeometryValidated))},M=o.nudgeHintCss;if(Number.isFinite(M)&&M>=0&&M<=a){const t=M*l/s,n=[f[0]+(w.safePoint[0]-f[0])*t,f[1]+(w.safePoint[1]-f[1])*t];(g||e&&we(f,n,e))&&!y(M)&&(S=M,k=!1)}if(null===k){let t=null,n=0,o=!1;const i=Math.ceil(a);for(let r=1;r<=i;r++){const i=Math.min(a,r),c=i*l/s,d=[f[0]+(w.safePoint[0]-f[0])*c,f[1]+(w.safePoint[1]-f[1])*c];if(!(g||e&&we(f,d,e))){o=!0;break}if(!y(i)){t=i;break}n=i}if(null!==t){let e=n,o=t;for(let t=0;t<14;t++){const t=(e+o)/2;y(t)?e=t:o=t}S=o}else S=n,z=!0,I="degraded",P=o?"owner-boundary":"nudge-cap"}$=[t*S*l,n*S*l]}}else I="degraded",P="invalid-safe-point";else I="degraded",P="missing-owner";const C=[g[0]+$[0],g[1]+$[1]],j=re(f,o.footprintHalfSize,m,a,$),N=!y||(k??M(j)),O=S>K,A=O||b||N||!!o.hovered||!!o.focused||!!o.selected;return{plane:h,owner:w,floorAnchor:f,floorScene:u,raisedScene:g,visualScene:C,footprint:j,nudgeScene:$,nudgeCss:[$[0]/l,$[1]/l],nudgeDistanceCss:S,nudged:O,nearWallBefore:b,nearWallAfter:N,cleared:!N,capped:z,grounding:{center:u,visible:!1!==o.filtersSupported},tether:ye(u,C,A),status:I,reason:P}}({kind:a,floorAnchor:l,rooms:c,roomsValidated:!0,preferredRoomId:h,ownerAlreadyResolved:!0,resolvedOwner:z,nudgeHintCss:x.hit&&x.value.shapeSignature===y?x.value.placement.nudgeDistanceCss*x.value.unitsPerPixel/s:void 0,showBorders:!0,wallSilhouettes:!1===o.resolveCollisions?[]:o.wallSilhouettes,wallGeometryValidated:!0,footprintHalfSize:u,wallHeight:d,visualOffset:f,sceneUnitsPerCssPixel:s,filtersSupported:o.layers.shadows,hovered:!0,selected:p});return $(g,m,{signature:v,shapeSignature:y,unitsPerPixel:s,placement:I},We),I};for(const e of o.devices){const t=o.positionOf(e),n=o.presentationOf(e,o.showLqi),i=v*n.scale,a=Ie({kind:"device",core:i,presentation:n}),r=e.marker?.room_id||l.find(t=>!!e.area&&t.room.area===e.area)?.overlayRoom.id||null,s=x("device",e.id,[t.x,t.y],a,r,o.selectedDeviceId===e.id);u.set(e.id,s),m.push({id:e.id,kind:"device",placement:s,groundRadius:Math.max(.32*i,2),screenHalfSize:a})}for(const{room:e,overlayRoom:t}of l){if(!o.display.showNames||!e.name)continue;const n=o.labelPositionOf(e,o.space.id),i=.5*y*(o.labelScaleOf(e)*o.kioskFontScale*o.display.cardFontScale),a=Ie({kind:"room-label",font:i,room:e,display:o.display}),r=x("room-label",t.id,[n.x,n.y],a,t.id,o.focusedRoomId===e.id);h.set(e,r),m.push({id:t.id,kind:"room-label",placement:r,groundRadius:Math.max(.75*i,2),screenHalfSize:a})}const M=o.openings.filter(e=>!e.orphanReason&&("door"===e.type||"gate"===e.type)&&"string"==typeof e.lock&&!!e.lock&&o.openingEntityAvailable(e.lock));if(M.length){const e=o.openingWallIndex();for(const t of M){const n=Je(t,e,o.cellCm),i=n.floorAnchor,a=.62*y,r=Ie({kind:"opening-lock",size:a}),s=x("opening-lock",String(t.id),i,r,n.preferredRoomId,o.selectedOpeningId===t.id);p.set(String(t.id),s),m.push({id:String(t.id),kind:"opening-lock",placement:s,groundRadius:Math.max(.28*a,2),screenHalfSize:r})}}const b={devices:u,rooms:h,locks:p,entries:Object.freeze(m)},k=!1===o.resolveCollisions?"fit":"live";let z=De.get(o.wallSilhouettes);z||(z=new Map,De.set(o.wallSilhouettes,z));const I=z.get(k);return I&&function(e,t){return e.length===t.length&&t.every((t,n)=>{const o=e[n];return o.id===t.id&&o.kind===t.kind&&o.placement===t.placement&&o.groundRadius===t.groundRadius&&o.screenHalfSize[0]===t.screenHalfSize[0]&&o.screenHalfSize[1]===t.screenHalfSize[1]})}(I.entries,b.entries)&&_e(I.devices,b.devices)&&_e(I.rooms,b.rooms)&&_e(I.locks,b.locks)?I:(z.set(k,b),b)}function Ze(e,t,n){return Je(e,t,n).floorAnchor}function Je(e,t,n){const o=!e.flip_v,i="gate"===e.type?e.partitionHost?p(e.partitionHost,o):h(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen,flip_v:o}):null,[a,r]=m({x:e.rx,y:e.ry,angle:e.angle,flipV:!!e.flip_v,gateFace:i},n);if(e.partitionHost)return{floorAnchor:a,preferredRoomId:null};const s=g(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen},!0),l=r?"negative":"positive";return{floorAnchor:a,preferredRoomId:s[l]?.roomId||null}}function Qe(e){let t=!1;try{t="undefined"!=typeof CSS&&"function"==typeof CSS.supports&&CSS.supports("filter","blur(1px)")}catch{t=!1}let n=!1;try{n="function"==typeof matchMedia&&matchMedia("(forced-colors: active)").matches}catch{n=!0}return function(e){const t=!!e.showBorders;return{structural:t,panels:t&&!e.hideOpenings,shadows:t&&e.filtersSupported&&!e.forcedColors,materialNuance:t&&e.filtersSupported&&!e.forcedColors,floorSymbols:!e.hideOpenings&&!t}}({showBorders:e.showBorders,hideOpenings:e.hideOpenings,filtersSupported:t,forcedColors:n})}function Xe(e,t,n,o){if(!e.panels||!t)return[];return t.openings.flatMap(e=>{const t=n[e.sourceIndex];return t?U(e,o(t)):[]}).sort((e,t)=>e.depth-t.depth||e.sourceIndex-t.sourceIndex||e.leaf-t.leaf)}function Ye(e){const t=Qe(e.display),n=t.panels?Xe(t,e.scene,e.openings,e.amountOf):[],o=e.overlays(t),i=t=>({layers:t,panels:n,overlays:o,underlay:at(t,e.scene?.floor,e.cellCm),shadows:rt(t,n,e.scene?.geometry,e.cellCm),walls:st(e.projection,t,e.scene,n,e.cellCm),grounds:ot(o,t,e.cellCm),raised:it(o)});try{return i(t)}catch(e){if(!t.shadows&&!t.materialNuance)throw e;return i({...t,shadows:!1,materialNuance:!1})}}const et=()=>b``;function tt(e){return`translate(${a(4,e)} ${a(8,e)})`}function nt(e,t,n){const o=I(n);return b`
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{dt as e,du as t,a$ as n,dv as o,dw as i,m as a,dx as r,dy as s,dz as l,dA as c,a4 as d,dB as f,ah as u,bT as h,bS as p,dC as m,ai as g,P as w,dD as y,cM as v,dE as x,A as M,w as b,dF as S,dG as $,dH as k,dI as z,dJ as I}from"./houseplan-card-6Hf8VPda.js";import{i as P}from"./guard-loEtwhSf.js";const C=e=>`${Number(e[0].toFixed(4))} ${Number(e[1].toFixed(4))}`;function j(e){let t=0;for(let n=0;nArray.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1])).map(e=>[Number(e[0]),Number(e[1])]),n=t[t.length-1];return t.length>1&&t[0][0]===n[0]&&t[0][1]===n[1]&&t.pop(),t}(e);if(n.length<3)return[];const o=!t;return j(n)>0===o?n:[...n].reverse()}function O(e,t,o){return e.length?`M ${e.map(e=>C(n(e,o,t))).join(" L ")} Z`:""}function A(e,t,n){const o=t[1]-e[1],i=-(t[0]-e[0]),a=n.rotDeg*Math.PI/180;return o*Math.sin(a)+i*Math.cos(a)}function B(t,o,i=e){if(!Number.isFinite(o)||o<0)throw new Error("invalid floor edge height");const a=(t||[]).map(e=>(e||[]).map((e,t)=>function(e,t){const n=N(e,t);if(!n.length)return n;let o=0;for(let e=1;e0)).filter(e=>e.length>=3&&Math.abs(j(e))>=1e-9)).filter(e=>e.length&&j(e[0])>0);a.sort((e,t)=>{const n=e[0][0],o=t[0][0];return n[0]-o[0]||n[1]-o[1]||Math.abs(j(t[0]))-Math.abs(j(e[0]))});const r=[],s=[];let l=0;for(let e=0;ee.depth-t.depth||e.component-t.component||e.edge-t.edge),{footprintPath:r.join(" "),sides:s,componentCount:a.length,edgeCount:l}}function H(e,t){return e^=Math.round(64*(Number.isFinite(t)?t:0)),Math.imul(e,16777619)>>>0}const R=Object.freeze({revision:1,leafThicknessRatio:.04,frameThicknessRatio:.055,gateTurnDeg:10,gateTopRatio:.88,windowBottomRatio:.27,windowTopRatio:.78,doorTopRatio:.92});R.leafThicknessRatio,R.frameThicknessRatio;const F=e=>e.every(Number.isFinite);function T(e,t){return Object.freeze([Object.is(e,-0)?0:e,Object.is(t,-0)?0:t])}function L(e,t){return[e[0]+t[0],e[1]+t[1]]}function V(e,t){return[e[0]-t[0],e[1]-t[1]]}function G(e,t){return[e[0]*t,e[1]*t]}function W(e,t,n,o){const i=e[0]*n,a=e[1]*o,r=t*Math.PI/180;return[i*Math.cos(r)-a*Math.sin(r),i*Math.sin(r)+a*Math.cos(r)]}function E(e,t,n,i,a,r,s){const l=e.flipH?-1:1,c="gate"===e.type?1:e.flipV?-1:1,d=o(e.type,e.flipV,e.angle,e.face);return{leaf:t,hinge:L([e.x+d.ox,e.y+d.oy],W(n,e.angle,l,c)),closedVector:W(i,e.angle,l,c),quarterVector:W([-i[1],i[0]],e.angle,l,c),turnDeg:a,bottom:r,top:s}}const q=e=>`${Number(e[0].toFixed(4))} ${Number(e[1].toFixed(4))}`;function D(e,t,o,i,a={}){const r=o.map(e=>n(e.point,e.z,i));return Object.freeze({kind:e,material:t,d:`M ${r.map(q).join(" L ")} Z`,depth:Math.max(...r.map(e=>e[1])),...a})}function _(e,t,n,o,i,a,r,s={}){return D(e,t,[{point:n,z:i},{point:o,z:i},{point:o,z:a},{point:n,z:a}],r,s)}function U(t,o,i=e){const a=Math.max(0,Math.min(1,Number.isFinite(o)?o:0));return t.leaves.map(e=>{const o=function(e,t){const n=e.turnDeg*t*Math.PI/180;return[e.hinge[0]+e.closedVector[0]*Math.cos(n)+e.quarterVector[0]*Math.sin(n),e.hinge[1]+e.closedVector[1]*Math.cos(n)+e.quarterVector[1]*Math.sin(n)]}(e,a),r=n(e.hinge,e.bottom,i),s=n(o,e.bottom,i),l=n(o,e.top,i),c=n(e.hinge,e.top,i),d="window"===t.type?"light-window":"matte-leaf",f="window"===t.type?Object.freeze([_("window-insert","light-window",e.hinge,o,e.bottom,e.top,i)]):function(e,t,n,o){const i=V(t,e.hinge),a=Math.hypot(i[0],i[1]);if(!(a>1e-9&&n>0))return Object.freeze([]);const r=T(-i[1]*n/(2*a),i[0]*n/(2*a)),s=L(e.hinge,r),l=L(t,r),c=V(e.hinge,r),d=V(t,r),f=[_("leaf-back","matte-leaf",d,c,e.bottom,e.top,o),_("leaf-front","matte-leaf",s,l,e.bottom,e.top,o),_("leaf-edge","matte-leaf",c,s,e.bottom,e.top,o,{edge:"hinge"}),_("leaf-edge","matte-leaf",l,d,e.bottom,e.top,o,{edge:"tip"}),D("leaf-top","matte-leaf",[{point:s,z:e.top},{point:c,z:e.top},{point:d,z:e.top},{point:l,z:e.top}],o)];return Object.freeze(f.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||String(e.edge||"").localeCompare(String(t.edge||""))))}(e,o,t.leafThickness,i);return Object.freeze({id:t.id,sourceIndex:t.sourceIndex,type:t.type,leaf:e.leaf,d:`M ${q(r)} L ${q(s)} L ${q(l)} L ${q(c)} Z`,shadowD:`M ${q(n(e.hinge,0,i))} L ${q(n(o,0,i))}`,depth:Math.max(r[1],s[1]),material:d,thickness:"window"===t.type?0:t.leafThickness,surfaces:f})})}const K=1e-9,Z=e=>e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function J(e){let t=0;for(let n=0;n=3&&e.every(Z)&&Math.abs(J(e))>K}function X(e,t,n){const o=n[0]-t[0],i=n[1]-t[1],a=o*o+i*i,r=a?Math.max(0,Math.min(1,((e[0]-t[0])*o+(e[1]-t[1])*i)/a)):0;return Math.hypot(e[0]-t[0]-r*o,e[1]-t[1]-r*i)}function Y(e,t,n=1e-7){for(let o=0;oe[1]!=r[1]>e[1]&&e[0]<(r[0]-a[0])*(e[1]-a[1])/(r[1]-a[1])+a[0]&&(n=!n)}return n}function te(e){return Math.max(0,Math.abs(J(e.outer))-(e.holes||[]).reduce((e,t)=>e+Math.abs(J(t)),0))}function ne(e){return!!e.id&&Q(e.outer)&&(e.holes||[]).every(Q)&&te(e)>K}function oe(e,t){if(!ne(t)||Y(e,t.outer)||!ee(e,t.outer))return!1;for(const n of t.holes||[])if(Y(e,n)||ee(e,n))return!1;return!0}function ie(e){if(!ne(e))return null;if(e.safePoint&&oe(e.safePoint,e))return[e.safePoint[0],e.safePoint[1]];const t=e.outer.map(e=>e[0]),n=e.outer.map(e=>e[1]),o=Math.min(...t),i=Math.max(...t),a=Math.min(...n),r=Math.max(...n),s=[[(o+i)/2,(a+r)/2],[t.reduce((e,t)=>e+t,0)/t.length,n.reduce((e,t)=>e+t,0)/n.length]];for(let t=0;t{if(!oe(t,e))return;const n=function(e,t){let n=1/0;for(const o of[t.outer,...t.holes||[]])for(let t=0;tc+K&&(l=t,c=n)};s.forEach(d);for(let e=1;e<16;e++)for(let t=1;t<16;t++)d([o+(i-o)*e/16,a+(r-a)*t/16]);return l}function ae(e){if(!Z(e.floorAnchor))return null;const t=e.roomsValidated?e.rooms:e.rooms.filter(ne),n=e.preferredRoomId&&t.find(t=>t.id===e.preferredRoomId)||null;let o=null;return"device"===e.kind?(n&&oe(e.floorAnchor,n)&&(o=n),o||(o=t.filter(t=>oe(e.floorAnchor,t)).sort((e,t)=>te(e)-te(t)||((e,t)=>et?1:0)(e.id,t.id))[0]||null)):o=n,o?{id:o.id,area:te(o),safePoint:e.roomsValidated&&o.safePoint?[o.safePoint[0],o.safePoint[1]]:ie(o)}:null}function re(t,o,i,a=e,r=[0,0]){if(!Z(t)||!Z(o)||o[0]<0||o[1]<0||!Number.isFinite(i)||!Z(r))throw new Error("invalid isometric overlay footprint");return[[t[0]-o[0],t[1]-o[1]],[t[0]+o[0],t[1]-o[1]],[t[0]+o[0],t[1]+o[1]],[t[0]-o[0],t[1]+o[1]]].map(e=>{const t=n(e,i,a);return[t[0]+r[0],t[1]+r[1]]})}function se(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function le(e,t,n,o){const i=se(e,t,n),a=se(e,t,o),r=se(n,o,e),s=se(n,o,t);return(i>K&&a<-K||i<-K&&a>K)&&(r>K&&s<-K||r<-K&&s>K)||(Math.abs(i)<=K&&X(n,e,t)<=K||Math.abs(a)<=K&&X(o,e,t)<=K||Math.abs(r)<=K&&X(e,n,o)<=K||Math.abs(s)<=K&&X(t,n,o)<=K)}function ce(e,t,n,o){return le(e,t,n,o)?0:Math.min(X(e,n,o),X(t,n,o),X(n,e,t),X(o,e,t))}const de=new WeakMap;function fe(e){if(!e.length)return null;let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const a of e){if(!Z(a))return null;t=Math.min(t,a[0]),n=Math.min(n,a[1]),o=Math.max(o,a[0]),i=Math.max(i,a[1])}return[t,n,o,i]}function ue(e,t){if(!t)return fe(e.outer);if(de.has(e))return de.get(e)??null;const n=fe(e.outer);return de.set(e,n),n}function he(e,t,n){return e[0]<=t[2]+n&&e[2]>=t[0]-n&&e[1]<=t[3]+n&&e[3]>=t[1]-n}function pe(e,t,n,o){return Math.min(t[0],n[0])<=e[2]+o&&Math.max(t[0],n[0])>=e[0]-o&&Math.min(t[1],n[1])<=e[3]+o&&Math.max(t[1],n[1])>=e[1]-o}function me(e,t,n,o,i){const a=ue(n,i);if(!a||!he(t,a,o))return!1;if(e.some(e=>function(e,t){return!!ee(e,t.outer)&&!(t.holes||[]).some(t=>ee(e,t))}(e,n)))return!0;if(n.outer.some(n=>n[0]>=t[0]&&n[0]<=t[2]&&n[1]>=t[1]&&n[1]<=t[3]&&ee(n,e)))return!0;for(const i of[n.outer,...n.holes||[]])for(let n=0;n"wall-side"===e.layer?0:"wall-top"===e.layer?1:2,Me=e=>{if("wall-side"===e.layer)return`${e.face.polygon}:${e.face.ring}:${e.face.edge}`;if("wall-top"===e.layer)return String(e.face.component);const t=e.surface;return`${t.sourceIndex}:${t.leaf??-1}:${t.kind}:${t.jamb??-1}:${t.edge??""}:${t.id}:${t.material}`};function be(e,t){const n=[...e.sides.map(e=>({layer:"wall-side",depth:e.depth,face:e})),...e.topFaces.map(e=>({layer:"wall-top",depth:e.depth,face:e})),...t.map(e=>({layer:"opening",depth:e.depth,surface:e}))];return n.sort((e,t)=>e.depth-t.depth||xe(e)-xe(t)||Me(e).localeCompare(Me(t))),Object.freeze(n)}const Se=Object.freeze({textLatinAdvance:.72,textWideAsciiAdvance:1,textWideAdvance:1.1,textSpaceAdvance:.4,textWidthSafety:1.08,deviceShellInset:.134375,deviceShellGap:.1,deviceSectionGap:.08,deviceBadgeMinWidth:.7875,deviceBadgeHeight:.7875,deviceBadgeInlinePadding:.28,deviceValueInlinePadding:.32,deviceAuxiliaryExtent:.7,deviceLqiFontSize:.38,deviceLqiTop:.734375,deviceLqiBelowBottomBadgeTop:1.571875,devicePadding:.08,roomNameLineHeight:1.25,roomAreaLinkWidth:1.1,roomMetricsTopGap:.15,roomMetricFontSize:.75,roomMetricLineHeight:1.25,roomMetricIconWidth:1.05,roomMetricInnerGap:.12,roomMetricRowGap:.55,roomMetricMinWidth:11,roomPadding:.4,openingLockHalfSize:.62,roomMetricTextCharacters:Object.freeze({temperature:10,humidity:8,lqi:6,light:24})});function $e(e){return[...String(e)].reduce((e,t)=>/\s/.test(t)?e+Se.textSpaceAdvance:/[MW@#%&]/.test(t)?e+Se.textWideAsciiAdvance:e+(t.codePointAt(0)>255?Se.textWideAdvance:Se.textLatinAdvance),0)*Se.textWidthSafety}function ke(e,t){return $e(e)*z(t||e)}function ze(e,t){return[Math.max(Math.abs(e.left),Math.abs(e.right))+t,Math.max(Math.abs(e.top),Math.abs(e.bottom))+t]}function Ie(e){if("opening-lock"===e.kind){const t=(Number.isFinite(e.size)&&e.size>0?e.size:0)*Se.openingLockHalfSize;return[t,t]}if("room-label"===e.kind){const t=Number.isFinite(e.font)&&e.font>0?e.font:0,n=v(e.room.settings?.name_scale),o=v(e.room.settings?.label_scale),i=($e(e.room.name||"")+(e.room.area?Se.roomAreaLinkWidth:0))*n,a=Se.roomNameLineHeight*n,r=[e.display.labelTemp?Se.roomMetricTextCharacters.temperature:0,e.display.labelHum?Se.roomMetricTextCharacters.humidity:0,e.display.labelLqi&&e.room.area?Se.roomMetricTextCharacters.lqi:0,e.display.labelLight?Se.roomMetricTextCharacters.light:0].filter(e=>e>0),s=Se.roomMetricFontSize*o,l=r.length?Math.max(Se.roomMetricMinWidth,r.reduce((e,t)=>e+Se.roomMetricIconWidth+Se.roomMetricInnerGap+t*Se.textLatinAdvance*Se.textWidthSafety,0)+(r.length-1)*Se.roomMetricRowGap)*s:0,c=r.length?s*Se.roomMetricLineHeight:0,d=ze({left:-Math.max(i,l)/2,right:Math.max(i,l)/2,top:-a/2,bottom:r.length?a/2+Se.roomMetricsTopGap+c:a/2},Se.roomPadding);return[d[0]*t,d[1]*t]}const t=Number.isFinite(e.core)&&e.core>0?e.core:0,n=e.presentation,o=null==n.valueText?1:Math.max(1,ke(n.valueText,n.valueFullText||n.valueText)+Se.deviceValueInlinePadding),i=[];n.valueBadge&&i.push(Math.max(Se.deviceBadgeMinWidth,ke(n.valueBadge.text,n.valueBadge.fullText||n.valueBadge.text)+Se.deviceBadgeInlinePadding));for(const e of x(n)){const t=e.text+e.suffix;i.push(Math.max(Se.deviceBadgeMinWidth,ke(t,t)+Se.deviceBadgeInlinePadding))}const a=n.valueBadge?.position||"right";let r;if(!i.length||"left"!==a&&"right"!==a)if(i.length){const e=i.reduce((e,t)=>e+t,0)+(i.length-1)*Se.deviceSectionGap,t=Math.max(o,e),n=1+Se.deviceShellGap+Se.deviceBadgeHeight;r="bottom"===a?{left:-t/2-Se.deviceShellInset,right:t/2+Se.deviceShellInset,top:-.5-Se.deviceShellInset,bottom:-.5+n+Se.deviceShellInset}:{left:-t/2-Se.deviceShellInset,right:t/2+Se.deviceShellInset,top:.5-n-Se.deviceShellInset,bottom:.5+Se.deviceShellInset}}else r={left:-.5-Se.deviceShellInset,right:-.5+o+Se.deviceShellInset,top:-.5-Se.deviceShellInset,bottom:.5+Se.deviceShellInset};else{const e=Math.max(...i),t=i.length*Se.deviceBadgeHeight+(i.length-1)*Se.deviceSectionGap,n=o+Se.deviceShellGap+e,s=Math.max(1,t);r="right"===a?{left:-.5-Se.deviceShellInset,right:-.5+n+Se.deviceShellInset,top:-s/2-Se.deviceShellInset,bottom:s/2+Se.deviceShellInset}:{left:.5-n-Se.deviceShellInset,right:.5+Se.deviceShellInset,top:-s/2-Se.deviceShellInset,bottom:s/2+Se.deviceShellInset}}const s=Se.deviceAuxiliaryExtent;if(r.left=Math.min(r.left,-s),r.right=Math.max(r.right,s),r.top=Math.min(r.top,-s),r.bottom=Math.max(r.bottom,s),n.pulse.animated){const e=Math.max(1,n.pulse.diameterScale)/2;r.left=Math.min(r.left,-e),r.right=Math.max(r.right,e),r.top=Math.min(r.top,-e),r.bottom=Math.max(r.bottom,e)}if(null!=n.lqiText){const e="bottom"===n.valueBadge?.position?Se.deviceLqiBelowBottomBadgeTop:Se.deviceLqiTop,t=$e(n.lqiText)*Se.deviceLqiFontSize/2;r.left=Math.min(r.left,-t),r.right=Math.max(r.right,t),r.bottom=Math.max(r.bottom,e+Se.deviceLqiFontSize)}const l=ze(r,Se.devicePadding);return[l[0]*t,l[1]*t]}function Pe(e,t){return e.flatMap((e,n)=>e.orphanReason?[]:[{id:String(e.id||n),sourceIndex:n,type:e.type,x:e.rx,y:e.ry,angle:Number(e.angle)||0,length:e.rlen>0?e.rlen:.9*t,flipH:!!e.flip_h,flipV:!!e.flip_v}])}function Ce(e){return{id:e.id,x:e.x,y:e.y,w:e.w,h:e.h,poly:e.poly,wall_ids:e.wall_ids}}function je(e,t){const n=e?.partitionHost;if(!n)return null;const o="gate"===t.type?!t.flipV:t.flipV;return{sourceIndex:t.sourceIndex,hostId:n.host.id,t:n.t,depth:n.depth,face:p(n,o)}}function Ne(n,o=R){const i=Pe(n.openings,n.coordinateScale),r=i.map(e=>je(n.openings[e.sourceIndex],e)),p=a(t,n.cellCm),m=a(s,n.cellCm),g=a(l,n.cellCm);return{key:`${n.space.id}|${function(e){let t=2166136261;const n=e=>{if("number"!=typeof e)if("string"!=typeof e)if("boolean"!=typeof e)if(Array.isArray(e)){t=H(t,e.length);for(const t of e)n(t)}else{if(e&&"object"==typeof e){const t=e;for(const e of Object.keys(t).sort())n(e),n(t[e]);return}t=H(t,-1)}else t=H(t,e?1:0);else for(const n of e)t=H(t,n.codePointAt(0)||0);else t=H(t,e)};return n(e),t.toString(36)}({rooms:n.space.rooms.map(Ce),walls:n.walls,openCuts:n.openCuts,openings:i,openingHosts:r,openingGeometryPolicy:o,partitions:n.space.partitions,columns:n.space.wall_columns,cellCm:n.cellCm,gridPitch:n.gridPitch,wallKeyPitch:n.wallKeyPitch,camera:e,wallHeight:p,raisedHeight:g,floorEdgeHeight:m,algorithm:4})}`,build:()=>{n.onBuild();const a=c(n.space,n.cellCm,n.gridPitch,2e-4*n.gridPitch,n.partitionCuts()).all,s=n.roomOpenings(),l=n.walls.length||a.length?d(n.space.rooms,n.walls,n.openCuts,s,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale,a):null;if(l&&("failed-core"===l.status||"not-applicable"===l.status))throw new Error("wall boolean geometry failed");const m=l?.paperGeom??f(n.space.rooms,n.walls,n.openCuts,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale);if(!m)throw new Error("floor boolean geometry failed");const g=l?.openingIndex||u(n.space.rooms,n.walls,n.openCuts,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale),w=i.map((e,i)=>{const a=r[i],s="gate"===e.type?!e.flipV:e.flipV,l=a?a.face:n.walls.length||"gate"===e.type?h(g,{x:e.x,y:e.y,angle:e.angle,length:e.length,flip_v:s}):{ox:0,oy:0,cm:0,side:-1};return function(e,n=t,o=R){const i=e.face.cm??0;if(!F([e.x,e.y,e.angle,e.length,e.face.ox,e.face.oy,i,n])||!(e.length>0)||!(n>0)||-1!==e.face.side&&1!==e.face.side||i<0)throw new Error("invalid isometric opening input");const a=e.length/2,r=e.angle*Math.PI/180,s=T(Math.cos(r),Math.sin(r)),l=T(-Math.sin(r),Math.cos(r)),c=T(e.x,e.y),d=T(e.x-s[0]*a,e.y-s[1]*a),f=T(e.x+s[0]*a,e.y+s[1]*a),u=T(e.face.ox,e.face.oy),h=T(d[0]+u[0],d[1]+u[1]),p=T(f[0]+u[0],f[1]+u[1]),m=T(d[0]-u[0],d[1]-u[1]),g=T(f[0]-u[0],f[1]-u[1]),w=Object.freeze({center:c,tangent:s,normal:l,start:d,end:f}),y=Object.freeze({side:e.face.side,cm:i,depth:2*Math.hypot(e.face.ox,e.face.oy),offset:u,selectedStart:h,selectedEnd:p,oppositeStart:m,oppositeEnd:g}),v="passage"===e.type?[]:[Object.freeze({jamb:0,center:d,selected:h,opposite:m}),Object.freeze({jamb:1,center:f,selected:p,opposite:g})];let x;if("passage"===e.type)x=[];else if("gate"===e.type){const t=e.face.side*o.gateTurnDeg;x=[E(e,0,[-a,0],[a,0],t,0,n*o.gateTopRatio),E(e,1,[a,0],[-a,0],-t,0,n*o.gateTopRatio)]}else x="window"===e.type?[E(e,0,[-a,0],[a,0],-90,n*o.windowBottomRatio,n*o.windowTopRatio),E(e,1,[a,0],[-a,0],90,n*o.windowBottomRatio,n*o.windowTopRatio)]:[E(e,0,[-a,0],[e.length,0],-90,0,n*o.doorTopRatio)];return Object.freeze({id:e.id,sourceIndex:e.sourceIndex,type:e.type,wallHeight:n,leafThickness:n*o.leafThicknessRatio,frameThickness:n*o.frameThicknessRatio,axis:w,face:y,reveals:Object.freeze(v),leaves:Object.freeze(x.map(e=>Object.freeze({...e,hinge:T(e.hinge[0],e.hinge[1]),closedVector:T(e.closedVector[0],e.closedVector[1]),quarterVector:T(e.quarterVector[0],e.quarterVector[1])})))})}({...e,face:l},p,o)}),y=Object.freeze(w);return{walls:l?.components.flatMap(e=>e.geom)||[],floor:m,openings:y,openingSurfaces:Object.freeze(y.flatMap(t=>function(t,n=e){if("passage"===t.type)return Object.freeze([]);const o=[];if(t.face.depth>1e-9)for(const e of t.reveals)o.push(_("jamb-reveal","reveal",e.selected,e.opposite,0,t.wallHeight,n,{jamb:e.jamb}));if("window"!==t.type||!t.leaves.length)return Object.freeze(o.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||(e.jamb??0)-(t.jamb??0)));const i=Math.min(...t.leaves.map(e=>e.bottom)),a=Math.max(...t.leaves.map(e=>e.top)),r=Math.min(t.frameThickness,Math.hypot(t.axis.end[0]-t.axis.start[0],t.axis.end[1]-t.axis.start[1])/4,(a-i)/4),s=L(t.axis.start,G(t.axis.tangent,r)),l=V(t.axis.end,G(t.axis.tangent,r)),c=t.face.depth>1e-9?[t.face.offset,T(-t.face.offset[0],-t.face.offset[1])]:[t.face.offset];for(const e of c){const c=L(t.axis.start,e),d=L(t.axis.end,e),f=L(s,e),u=L(l,e);o.push(_("window-frame-side","light-frame",c,f,i,a,n,{jamb:0}),_("window-frame-side","light-frame",u,d,i,a,n,{jamb:1}),_("window-frame-top","light-frame",f,u,Math.max(i,a-r),a,n))}return t.face.depth>1e-9&&o.push(D("window-sill","light-sill",[{point:t.face.selectedStart,z:i},{point:t.face.selectedEnd,z:i},{point:t.face.oppositeEnd,z:i},{point:t.face.oppositeStart,z:i}],n)),Object.freeze(o.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||(e.jamb??0)-(t.jamb??0)))}(t).map(e=>Object.freeze({...e,id:t.id,sourceIndex:t.sourceIndex,type:t.type}))))}}}}const Oe=e=>Array.isArray(e)?e:[];function Ae(e,t){const o=e=>Oe(e).flatMap(e=>Array.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1])?[n([Number(e[0]),Number(e[1])],t)]:[]);return Oe(e).flatMap(e=>{const t=Oe(e);if(!t.length)return[];const n=o(t[0]);if(n.length<3)return[];return[{outer:n,holes:t.slice(1).map(o).filter(e=>e.length>=3)}]})}function Be(o){const i=a(t,o.cellCm),r=a(s,o.cellCm),c=a(l,o.cellCm),d=S(o.cache,o.source.key);let f=d.hit?d.value:void 0;if(!f){const a=o.source.build(),s=function(o,i=e,a=t){if(!Number.isFinite(a)||a<0)throw new Error("invalid wall height");const r=[],s=[],l=[],c=[];let d=0;for(let e=0;e<(o||[]).length;e++){const t=o[e],f=[];let u=-1/0;for(let o=0;o<(t||[]).length;o++){const s=N(t[o],o>0);if(s.length<3||Math.abs(j(s))<1e-9)continue;const h=O(s,i,a);r.push(h),f.push(h),u=Math.max(u,...s.map(e=>n(e,a,i)[1])),d+=s.length;for(let t=0;te.depth-t.depth||e.polygon-t.polygon||e.ring-t.ring||e.edge-t.edge),s.sort((e,t)=>e.depth-t.depth||e.component-t.component),{topPath:r.join(" "),topFaces:s,sides:l,contactPath:c.join(" "),edgeCount:d}}(a.walls,e,i),l=Ae(a.walls,i);f={geometry:s,floor:B(a.floor,r),wallSilhouettes:Object.freeze([...l,...s.sides.map(e=>({outer:e.points}))]),openings:a.openings,openingSurfaces:a.openingSurfaces},$(o.cache,o.source.key,f,8)}const u=function(e){let t=1/0,n=1/0,o=-1/0,i=-1/0;const a=(e,a=0)=>{t=Math.min(t,e[0]-a),n=Math.min(n,e[1]-a),o=Math.max(o,e[0]+a),i=Math.max(i,e[1]+a)};for(const t of e)if("passage"!==t.type){a(t.axis.start),a(t.axis.end),a(t.face.selectedStart),a(t.face.selectedEnd),a(t.face.oppositeStart),a(t.face.oppositeEnd);for(const e of t.leaves){const n=Math.hypot(e.closedVector[0],e.closedVector[1])+t.leafThickness/2;a(e.hinge,n)}}return F([t,n,o,i])?{x:t,y:n,w:o-t,h:i-n}:null}(f.openings),h=u?He(o.liveFrame,u):o.liveFrame,p=k({rect:h,wallHeight:i,openingHeight:i,floorDepth:r,raisedHeight:c});return{key:o.source.key,...f,frame:p}}const He=(e,t)=>{const n=Math.min(e.x,t.x),o=Math.min(e.y,t.y);return{x:n,y:o,w:Math.max(e.x+e.w,t.x+t.w)-n,h:Math.max(e.y+e.h,t.y+t.h)-o}},Re=e=>{if(!e.length||!e.every(e=>Number.isFinite(e[0])&&Number.isFinite(e[1])))return null;const t=e.map(e=>e[0]),n=e.map(e=>e[1]),o=Math.min(...t),i=Math.min(...n);return{x:o,y:i,w:Math.max(...t)-o,h:Math.max(...n)-i}},Fe=(e,t)=>{const n=e.placement,o=t?n.visualScene:n.raisedScene,[i,a]=e.screenHalfSize,r=t?n.footprint:n.footprint.map(e=>[e[0]-n.nudgeScene[0],e[1]-n.nudgeScene[1]]);return[n.floorScene,...r,[o[0]-i,o[1]-a],[o[0]+i,o[1]-a],[o[0]+i,o[1]+a],[o[0]-i,o[1]+a]]},Te=(e,t)=>void 0===t?e:e.filter(e=>e.placement.owner?.id===t);function Le(e,t){return e?Re(Te(e.entries,t).flatMap(e=>Fe(e,!0))):null}function Ve(e){const t=Te(e.entries,e.ownerId),n=Re(t.flatMap(e=>Fe(e,!1))),o=n?He(e.baseBounds,n):e.baseBounds,i=e.targetView(o);if(!(i&&i.w>0&&i.h>0&&[i.x,i.y,i.w,i.h].every(Number.isFinite)))return null;const a=e.stageSize;if(!(n&&a&&a.width>0&&a.height>0))return{bounds:o,view:i};const r=e=>Math.max(e.w/a.width,e.h/a.height),s=t=>{const o=48*t,i={x:n.x-o,y:n.y-o,w:n.w+2*o,h:n.h+2*o},a=He(e.baseBounds,i),r=e.targetView(a);return r&&[r.x,r.y,r.w,r.h].every(Number.isFinite)&&r.w>0&&r.h>0?{bounds:a,view:r}:null};let l=0,c=Math.max(r(i),Number.EPSILON),d=s(c);for(let e=0;d&&r(d.view)>c*(1+1e-10)&&e<24;e++)l=c,c*=2,d=s(c);if(!d)return null;for(let e=0;e<40;e++){const e=(l+c)/2,t=s(e);if(!t)return null;r(t.view)<=e?(c=e,d=t):l=e}return d}const Ge=new WeakMap,We=2048,Ee=new WeakMap,qe=new WeakMap,De=new WeakMap;function _e(e,t){if(e.size!==t.size)return!1;for(const[n,o]of t)if(e.get(n)!==o)return!1;return!0}function Ue(e){const t=Ge.get(e.rooms);if(t)return t;const n=e.rooms.flatMap((e,t)=>{const n=w(e);return n&&n.length>=3?[{room:e,index:t,poly:n}]:[]}),o=Object.freeze(n.map(({room:e,index:t,poly:o})=>{const i=y(o,n.filter(e=>e.index!==t).map(e=>e.poly)),a={id:e.id||`room-index-${t}`,outer:o.map(e=>[e[0],e[1]]),holes:i.map(e=>e.map(e=>[e[0],e[1]]))};return{room:e,overlayRoom:{...a,safePoint:ie(a)||void 0}}}));return Ge.set(e.rooms,o),o}function Ke(o){const s=o.stageSize&&o.stageSize.width>0&&o.stageSize.height>0?Math.max(o.view.w/o.stageSize.width,o.view.h/o.stageSize.height):Math.max(o.view.w,o.view.h)/1e3,l=Ue(o.space),c=l.map(e=>e.overlayRoom),d=a(t,o.cellCm),f=a(i,o.cellCm),u=new Map,h=new Map,p=new Map,m=[];let g=Ee.get(o.wallSilhouettes);g||(g=new Map,Ee.set(o.wallSilhouettes,g));let w=qe.get(l);w||(w=new Map,qe.set(l,w));const y=o.iconPct*r(o.space)*o.kioskIconScale/100,v=o.deviceBasePct*r(o.space)*o.kioskIconScale/100,x=(a,r,l,u,h,p=!1)=>{const m=`${!1===o.resolveCollisions?"fit":"live"}\0${a}\0${r}`,y=[l[0],l[1],u[0],u[1],h||"",d,f,o.layers.shadows?1:0,p?1:0].join("|"),v=`${y}|${s}`,x=S(g,m);if(x.hit&&x.value.signature===v)return x.value.placement;if(x.hit&&x.value.shapeSignature===y&&s<=x.value.unitsPerPixel){const e=x.value.placement,t=e.nudgeDistanceCss*x.value.unitsPerPixel/s;if(!e.nearWallBefore||e.cleared&&t<=48)return e}const M=`${a}\0${r}`,b=[l[0],l[1],h||""].join("|"),k=S(w,M),z=k.hit&&k.value.signature===b?k.value.owner:ae({kind:a,floorAnchor:l,rooms:c,roomsValidated:!0,preferredRoomId:h});k.hit&&k.value.signature===b||$(w,M,{signature:b,owner:z},We);const I=function(o){const a=o.camera||e,r=o.wallHeight??t,s=o.visualOffset??i,l=o.sceneUnitsPerCssPixel??1,c=o.safetyGapCssPx??4,d=o.maxNudgeCssPx??48;if(!Z(o.floorAnchor)||!Z(o.footprintHalfSize)||o.footprintHalfSize[0]<0||o.footprintHalfSize[1]<0||!Number.isFinite(r)||r<0||!Number.isFinite(s)||s<0||!Number.isFinite(l)||l<=0||!Number.isFinite(c)||c<0||!Number.isFinite(d)||d<0)throw new Error("invalid isometric overlay input");const f=[o.floorAnchor[0],o.floorAnchor[1]],u=n(f,0,a),h=(p=o.kind,!o.showBorders||"device"!==p&&"room-label"!==p&&"opening-lock"!==p?"floor":"raised");var p;if("floor"===h)return{plane:h,owner:null,floorAnchor:f,floorScene:u,raisedScene:u,visualScene:u,footprint:[],nudgeScene:[0,0],nudgeCss:[0,0],nudgeDistanceCss:0,nudged:!1,nearWallBefore:!1,nearWallAfter:!1,cleared:!0,capped:!1,grounding:{center:u,visible:!1},tether:ye(u,u,!1),status:"ok",reason:null};const m=r+s,g=n(f,m,a),w=o.ownerAlreadyResolved?o.resolvedOwner??null:ae(o),y=o.wallGeometryValidated??o.wallSilhouettes.every(ge),v=c*l,x=re(f,o.footprintHalfSize,m,a),M=e=>{const t=fe(e);return!!t&&o.wallSilhouettes.some(n=>me(e,t,n,v,!0===o.wallGeometryValidated))},b=!y||M(x);let S=0,$=[0,0],k=null,z=!1,I=y?"ok":"degraded",P=y?null:"invalid-wall-geometry";if(y&&b)if(w)if(w.safePoint){const e=o.rooms.find(e=>e.id===w.id)||null,t=n(w.safePoint,m,a),i=t[0]-g[0],r=t[1]-g[1],s=Math.hypot(i,r);if(s<=K)I="degraded",P="invalid-safe-point";else{const t=i/s,n=r/s,a=Math.min(d,s/l),c=a*l/s,u=[f[0]+(w.safePoint[0]-f[0])*c,f[1]+(w.safePoint[1]-f[1])*c],h=[t*a*l,n*a*l],p=fe([...x,...x.map(e=>[e[0]+h[0],e[1]+h[1]])]),m=p?o.wallSilhouettes.filter(e=>{const t=ue(e,!0===o.wallGeometryValidated);return!!t&&he(p,t,v)}):o.wallSilhouettes,g=!!e&&we(f,u,e),y=e=>{const i=[t*e*l,n*e*l],a=x.map(e=>[e[0]+i[0],e[1]+i[1]]),r=fe(a);return!!r&&m.some(e=>me(a,r,e,v,!0===o.wallGeometryValidated))},M=o.nudgeHintCss;if(Number.isFinite(M)&&M>=0&&M<=a){const t=M*l/s,n=[f[0]+(w.safePoint[0]-f[0])*t,f[1]+(w.safePoint[1]-f[1])*t];(g||e&&we(f,n,e))&&!y(M)&&(S=M,k=!1)}if(null===k){let t=null,n=0,o=!1;const i=Math.ceil(a);for(let r=1;r<=i;r++){const i=Math.min(a,r),c=i*l/s,d=[f[0]+(w.safePoint[0]-f[0])*c,f[1]+(w.safePoint[1]-f[1])*c];if(!(g||e&&we(f,d,e))){o=!0;break}if(!y(i)){t=i;break}n=i}if(null!==t){let e=n,o=t;for(let t=0;t<14;t++){const t=(e+o)/2;y(t)?e=t:o=t}S=o}else S=n,z=!0,I="degraded",P=o?"owner-boundary":"nudge-cap"}$=[t*S*l,n*S*l]}}else I="degraded",P="invalid-safe-point";else I="degraded",P="missing-owner";const C=[g[0]+$[0],g[1]+$[1]],j=re(f,o.footprintHalfSize,m,a,$),N=!y||(k??M(j)),O=S>K,A=O||b||N||!!o.hovered||!!o.focused||!!o.selected;return{plane:h,owner:w,floorAnchor:f,floorScene:u,raisedScene:g,visualScene:C,footprint:j,nudgeScene:$,nudgeCss:[$[0]/l,$[1]/l],nudgeDistanceCss:S,nudged:O,nearWallBefore:b,nearWallAfter:N,cleared:!N,capped:z,grounding:{center:u,visible:!1!==o.filtersSupported},tether:ye(u,C,A),status:I,reason:P}}({kind:a,floorAnchor:l,rooms:c,roomsValidated:!0,preferredRoomId:h,ownerAlreadyResolved:!0,resolvedOwner:z,nudgeHintCss:x.hit&&x.value.shapeSignature===y?x.value.placement.nudgeDistanceCss*x.value.unitsPerPixel/s:void 0,showBorders:!0,wallSilhouettes:!1===o.resolveCollisions?[]:o.wallSilhouettes,wallGeometryValidated:!0,footprintHalfSize:u,wallHeight:d,visualOffset:f,sceneUnitsPerCssPixel:s,filtersSupported:o.layers.shadows,hovered:!0,selected:p});return $(g,m,{signature:v,shapeSignature:y,unitsPerPixel:s,placement:I},We),I};for(const e of o.devices){const t=o.positionOf(e),n=o.presentationOf(e,o.showLqi),i=v*n.scale,a=Ie({kind:"device",core:i,presentation:n}),r=e.marker?.room_id||l.find(t=>!!e.area&&t.room.area===e.area)?.overlayRoom.id||null,s=x("device",e.id,[t.x,t.y],a,r,o.selectedDeviceId===e.id);u.set(e.id,s),m.push({id:e.id,kind:"device",placement:s,groundRadius:Math.max(.32*i,2),screenHalfSize:a})}for(const{room:e,overlayRoom:t}of l){if(!o.display.showNames||!e.name)continue;const n=o.labelPositionOf(e,o.space.id),i=.5*y*(o.labelScaleOf(e)*o.kioskFontScale*o.display.cardFontScale),a=Ie({kind:"room-label",font:i,room:e,display:o.display}),r=x("room-label",t.id,[n.x,n.y],a,t.id,o.focusedRoomId===e.id);h.set(e,r),m.push({id:t.id,kind:"room-label",placement:r,groundRadius:Math.max(.75*i,2),screenHalfSize:a})}const M=o.openings.filter(e=>!e.orphanReason&&("door"===e.type||"gate"===e.type)&&"string"==typeof e.lock&&!!e.lock&&o.openingEntityAvailable(e.lock));if(M.length){const e=o.openingWallIndex();for(const t of M){const n=Je(t,e,o.cellCm),i=n.floorAnchor,a=.62*y,r=Ie({kind:"opening-lock",size:a}),s=x("opening-lock",String(t.id),i,r,n.preferredRoomId,o.selectedOpeningId===t.id);p.set(String(t.id),s),m.push({id:String(t.id),kind:"opening-lock",placement:s,groundRadius:Math.max(.28*a,2),screenHalfSize:r})}}const b={devices:u,rooms:h,locks:p,entries:Object.freeze(m)},k=!1===o.resolveCollisions?"fit":"live";let z=De.get(o.wallSilhouettes);z||(z=new Map,De.set(o.wallSilhouettes,z));const I=z.get(k);return I&&function(e,t){return e.length===t.length&&t.every((t,n)=>{const o=e[n];return o.id===t.id&&o.kind===t.kind&&o.placement===t.placement&&o.groundRadius===t.groundRadius&&o.screenHalfSize[0]===t.screenHalfSize[0]&&o.screenHalfSize[1]===t.screenHalfSize[1]})}(I.entries,b.entries)&&_e(I.devices,b.devices)&&_e(I.rooms,b.rooms)&&_e(I.locks,b.locks)?I:(z.set(k,b),b)}function Ze(e,t,n){return Je(e,t,n).floorAnchor}function Je(e,t,n){const o=!e.flip_v,i="gate"===e.type?e.partitionHost?p(e.partitionHost,o):h(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen,flip_v:o}):null,[a,r]=m({x:e.rx,y:e.ry,angle:e.angle,flipV:!!e.flip_v,gateFace:i},n);if(e.partitionHost)return{floorAnchor:a,preferredRoomId:null};const s=g(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen},!0),l=r?"negative":"positive";return{floorAnchor:a,preferredRoomId:s[l]?.roomId||null}}function Qe(e){let t=!1;try{t="undefined"!=typeof CSS&&"function"==typeof CSS.supports&&CSS.supports("filter","blur(1px)")}catch{t=!1}let n=!1;try{n="function"==typeof matchMedia&&matchMedia("(forced-colors: active)").matches}catch{n=!0}return function(e){const t=!!e.showBorders;return{structural:t,panels:t&&!e.hideOpenings,shadows:t&&e.filtersSupported&&!e.forcedColors,materialNuance:t&&e.filtersSupported&&!e.forcedColors,floorSymbols:!e.hideOpenings&&!t}}({showBorders:e.showBorders,hideOpenings:e.hideOpenings,filtersSupported:t,forcedColors:n})}function Xe(e,t,n,o){if(!e.panels||!t)return[];return t.openings.flatMap(e=>{const t=n[e.sourceIndex];return t?U(e,o(t)):[]}).sort((e,t)=>e.depth-t.depth||e.sourceIndex-t.sourceIndex||e.leaf-t.leaf)}function Ye(e){const t=Qe(e.display),n=t.panels?Xe(t,e.scene,e.openings,e.amountOf):[],o=e.overlays(t),i=t=>({layers:t,panels:n,overlays:o,underlay:at(t,e.scene?.floor,e.cellCm),shadows:rt(t,n,e.scene?.geometry,e.cellCm),walls:st(e.projection,t,e.scene,n,e.cellCm),grounds:ot(o,t,e.cellCm),raised:it(o)});try{return i(t)}catch(e){if(!t.shadows&&!t.materialNuance)throw e;return i({...t,shadows:!1,materialNuance:!1})}}const et=()=>b``;function tt(e){return`translate(${a(4,e)} ${a(8,e)})`}function nt(e,t,n){const o=I(n);return b`
${"walls"===t&&e.materialNuance?b`
diff --git a/custom_components/houseplan/frontend/houseplan-assets/live-interaction-runtime-Bn789cLD.js b/custom_components/houseplan/frontend/houseplan-assets/live-interaction-runtime-B4GlJv_x.js
similarity index 96%
rename from custom_components/houseplan/frontend/houseplan-assets/live-interaction-runtime-Bn789cLD.js
rename to custom_components/houseplan/frontend/houseplan-assets/live-interaction-runtime-B4GlJv_x.js
index e1ec7ebb..949e30c9 100644
--- a/custom_components/houseplan/frontend/houseplan-assets/live-interaction-runtime-Bn789cLD.js
+++ b/custom_components/houseplan/frontend/houseplan-assets/live-interaction-runtime-B4GlJv_x.js
@@ -1 +1 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{dQ as e}from"./houseplan-card-B_QYG0Py.js";const t=new WeakMap,n=e=>{let n=t.get(e);return n||(n={painted:null,pending:null,raf:0},t.set(e,n)),n},o=e=>`${e.x} ${e.y} ${e.w} ${e.h}`;const r=e=>0===e.translateXPercent&&0===e.translateYPercent&&1===e.scaleX&&1===e.scaleY,a=e=>[e.x,e.y,e.w,e.h].every(Number.isFinite)&&e.w>0&&e.h>0,s=(e,t)=>{if(!t)return e.style.removeProperty("transform"),e.style.removeProperty("transform-origin"),void e.style.removeProperty("will-change");e.style.transformOrigin="0 0",e.style.willChange="transform",e.style.transform=`translate(${t.translateXPercent}%,${t.translateYPercent}%) scale(${t.scaleX},${t.scaleY})`};function i(e,t,n){if(!a(t.view)||!a(n.view)||!a(n.floor))return;const i=o(n.view),l=o(n.floor);for(const t of e.querySelectorAll('[data-hp-live-viewbox="camera"]'))t.setAttribute("viewBox",i);for(const t of e.querySelectorAll('[data-hp-live-viewbox="floor"]'))t.setAttribute("viewBox",l);const c=(f=t.view,u=n.view,{translateXPercent:(f.x-u.x)/u.w*100,translateYPercent:(f.y-u.y)/u.h*100,scaleX:f.w/u.w,scaleY:f.h/u.h});var f,u;for(const t of e.querySelectorAll('[data-hp-live-layer="camera"]'))s(t,r(c)?null:c);const d=e.querySelector("[data-hp-live-zoom]");if(d){d.hidden=n.zoom<=1;const e=d.querySelector("[data-hp-live-zoom-value]");e&&(e.textContent=`${Math.round(100*n.zoom)}%`)}}const l=e=>{const t=e._viewOr(e._baseVb());return{view:{...t},floor:{...e._floorView(t)},zoom:e._zoom}};const c=new WeakMap,f=(e,t,n,o)=>{if(!n)return;const r=document.createElement("span");if(r.className="m",t){r.append(`${t} `);const e=document.createElement("b");e.textContent=n,o&&(e.style.color=o),r.append(e)}else r.textContent=n;e.append(r)},u=(e,t,n)=>{const o=e.querySelector(t);o&&(o.setAttribute("d",n),o.toggleAttribute("hidden",!n))};function d(t){const n=t,o=n.renderRoot;if(!o)return;((t,n)=>{const o=n.querySelector("[data-hp-live-tip]");if(!o)return;const r=t._tip;if(!r)return o.hidden=!0,void o.replaceChildren();o.style.left=`${r.x+12}px`,o.style.top=`${r.y+12}px`,o.replaceChildren();const a=document.createElement("b");a.textContent=r.title,o.append(a),f(o,"",r.meta),f(o,t._t("tip.temp_avg"),null==r.temp?"":`${r.temp}°`),f(o,t._t("tip.hum_avg"),null==r.hum?"":`${r.hum}%`),f(o,t._t("tip.lqi"),null==r.lqi?"":String(r.lqi),null==r.lqi?void 0:e(r.lqi)),o.hidden=!1})(n,o);const r=n._hoverRoom,a=c.get(t),s=r?.space||"",i=r?.room||null;if(a?.room===i&&a?.space===s)return;c.set(t,{room:i,space:s});const l=r&&n._spaceModel(),d=l?n._roomHoverPaths(l):null;u(o,'[data-hp-live-room-hover="fill"]',d?.fillD||""),u(o,'[data-hp-live-room-hover="halo"]',d?.outlineD||""),u(o,'[data-hp-live-room-hover="outline"]',d?.outlineD||"")}function m(e){c.delete(e)}class p{constructor(e){this.host=e,this.deferredHass=!1}hass(e,t,n,o){const r=function(e,t,n){if(e===t)return"none";if(!e||!t||!n)return"structural";if(e.connection!==t.connection||e.entities!==t.entities||e.devices!==t.devices||e.areas!==t.areas||e.themes!==t.themes||e.user!==t.user||e.config!==t.config||e.floors!==t.floors||e.services!==t.services||e.panels!==t.panels||e.language!==t.language||e.locale?.language!==t.locale?.language||e.locale?.number_format!==t.locale?.number_format||e.locale?.time_format!==t.locale?.time_format||e.locale?.date_format!==t.locale?.date_format)return"structural";const o=new Set(["states","connection","entities","devices","areas","themes","user","config","floors","services","panels","language","locale"]);for(const n of new Set([...Object.keys(e),...Object.keys(t)]))if(!o.has(n)&&e[n]!==t[n])return"structural";for(const o of n.entityIds)if(e.states?.[o]!==t.states?.[o])return"state";return"none"}(e,t,n),a="state"===r&&this.active();a&&(this.deferredHass=!0);const s="none"!==r&&!a;return s||this.host._renderLife.observe(e,t,n,o),s}clear(){this.deferredHass=!1}take(){const e=this.deferredHass;return this.deferredHass=!1,e}viewport(e=!1){!function(e,t=!1){const o=e,r=n(e),a=l(o);if(t)return r.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(r.raf),r.raf=0,r.pending=null,r.painted||(r.painted=a),void i(o.renderRoot,r.painted,a);r.pending=a,r.raf||"function"!=typeof requestAnimationFrame||(r.raf=requestAnimationFrame(()=>{r.raf=0;const e=r.pending;r.pending=null;const t=o.renderRoot;e&&t&&(r.painted||(r.painted=e),i(t,r.painted,e))}))}(this.host,e)}hover(){d(this.host)}active(){const e=this.host;return e._pointers.size>0||e._cameraTransition.active||!!e._deviceDrag||!!e._physicalDrag||!!e._physicalRotate||!!e._decorMove||!!e._decorDraft||!!e._dtDrag||!!e._bdDrag||!!e._opDrag||!!e._resize?.dragging}commit(){!function(e){const t=e,o=n(e);o.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o.raf),o.raf=0,o.pending=null,o.painted=l(t);const r=t.renderRoot;if(r){for(const e of r.querySelectorAll('[data-hp-live-layer="camera"]'))s(e,null);i(r,o.painted,o.painted)}}(this.host),m(this.host),d(this.host)}dispose(){!function(e){const n=t.get(e);n?.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(n.raf),t.delete(e)}(this.host),m(this.host)}}export{p as LiveRuntime};
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{dR as e}from"./houseplan-card-6Hf8VPda.js";const t=new WeakMap,n=e=>{let n=t.get(e);return n||(n={painted:null,pending:null,raf:0},t.set(e,n)),n},o=e=>`${e.x} ${e.y} ${e.w} ${e.h}`;const r=e=>0===e.translateXPercent&&0===e.translateYPercent&&1===e.scaleX&&1===e.scaleY,a=e=>[e.x,e.y,e.w,e.h].every(Number.isFinite)&&e.w>0&&e.h>0,s=(e,t)=>{if(!t)return e.style.removeProperty("transform"),e.style.removeProperty("transform-origin"),void e.style.removeProperty("will-change");e.style.transformOrigin="0 0",e.style.willChange="transform",e.style.transform=`translate(${t.translateXPercent}%,${t.translateYPercent}%) scale(${t.scaleX},${t.scaleY})`};function i(e,t,n){if(!a(t.view)||!a(n.view)||!a(n.floor))return;const i=o(n.view),l=o(n.floor);for(const t of e.querySelectorAll('[data-hp-live-viewbox="camera"]'))t.setAttribute("viewBox",i);for(const t of e.querySelectorAll('[data-hp-live-viewbox="floor"]'))t.setAttribute("viewBox",l);const c=(f=t.view,u=n.view,{translateXPercent:(f.x-u.x)/u.w*100,translateYPercent:(f.y-u.y)/u.h*100,scaleX:f.w/u.w,scaleY:f.h/u.h});var f,u;for(const t of e.querySelectorAll('[data-hp-live-layer="camera"]'))s(t,r(c)?null:c);const d=e.querySelector("[data-hp-live-zoom]");if(d){d.hidden=n.zoom<=1;const e=d.querySelector("[data-hp-live-zoom-value]");e&&(e.textContent=`${Math.round(100*n.zoom)}%`)}}const l=e=>{const t=e._viewOr(e._baseVb());return{view:{...t},floor:{...e._floorView(t)},zoom:e._zoom}};const c=new WeakMap,f=(e,t,n,o)=>{if(!n)return;const r=document.createElement("span");if(r.className="m",t){r.append(`${t} `);const e=document.createElement("b");e.textContent=n,o&&(e.style.color=o),r.append(e)}else r.textContent=n;e.append(r)},u=(e,t,n)=>{const o=e.querySelector(t);o&&(o.setAttribute("d",n),o.toggleAttribute("hidden",!n))};function d(t){const n=t,o=n.renderRoot;if(!o)return;((t,n)=>{const o=n.querySelector("[data-hp-live-tip]");if(!o)return;const r=t._tip;if(!r)return o.hidden=!0,void o.replaceChildren();o.style.left=`${r.x+12}px`,o.style.top=`${r.y+12}px`,o.replaceChildren();const a=document.createElement("b");a.textContent=r.title,o.append(a),f(o,"",r.meta),f(o,t._t("tip.temp_avg"),null==r.temp?"":`${r.temp}°`),f(o,t._t("tip.hum_avg"),null==r.hum?"":`${r.hum}%`),f(o,t._t("tip.lqi"),null==r.lqi?"":String(r.lqi),null==r.lqi?void 0:e(r.lqi)),o.hidden=!1})(n,o);const r=n._hoverRoom,a=c.get(t),s=r?.space||"",i=r?.room||null;if(a?.room===i&&a?.space===s)return;c.set(t,{room:i,space:s});const l=r&&n._spaceModel(),d=l?n._roomHoverPaths(l):null;u(o,'[data-hp-live-room-hover="fill"]',d?.fillD||""),u(o,'[data-hp-live-room-hover="halo"]',d?.outlineD||""),u(o,'[data-hp-live-room-hover="outline"]',d?.outlineD||"")}function m(e){c.delete(e)}class p{constructor(e){this.host=e,this.deferredHass=!1}hass(e,t,n,o){const r=function(e,t,n){if(e===t)return"none";if(!e||!t||!n)return"structural";if(e.connection!==t.connection||e.entities!==t.entities||e.devices!==t.devices||e.areas!==t.areas||e.themes!==t.themes||e.user!==t.user||e.config!==t.config||e.floors!==t.floors||e.services!==t.services||e.panels!==t.panels||e.language!==t.language||e.locale?.language!==t.locale?.language||e.locale?.number_format!==t.locale?.number_format||e.locale?.time_format!==t.locale?.time_format||e.locale?.date_format!==t.locale?.date_format)return"structural";const o=new Set(["states","connection","entities","devices","areas","themes","user","config","floors","services","panels","language","locale"]);for(const n of new Set([...Object.keys(e),...Object.keys(t)]))if(!o.has(n)&&e[n]!==t[n])return"structural";for(const o of n.entityIds)if(e.states?.[o]!==t.states?.[o])return"state";return"none"}(e,t,n),a="state"===r&&this.active();a&&(this.deferredHass=!0);const s="none"!==r&&!a;return s||this.host._renderLife.observe(e,t,n,o),s}clear(){this.deferredHass=!1}take(){const e=this.deferredHass;return this.deferredHass=!1,e}viewport(e=!1){!function(e,t=!1){const o=e,r=n(e),a=l(o);if(t)return r.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(r.raf),r.raf=0,r.pending=null,r.painted||(r.painted=a),void i(o.renderRoot,r.painted,a);r.pending=a,r.raf||"function"!=typeof requestAnimationFrame||(r.raf=requestAnimationFrame(()=>{r.raf=0;const e=r.pending;r.pending=null;const t=o.renderRoot;e&&t&&(r.painted||(r.painted=e),i(t,r.painted,e))}))}(this.host,e)}hover(){d(this.host)}active(){const e=this.host;return e._pointers.size>0||e._cameraTransition.active||!!e._deviceDrag||!!e._physicalDrag||!!e._physicalRotate||!!e._decorMove||!!e._decorDraft||!!e._dtDrag||!!e._bdDrag||!!e._opDrag||!!e._resize?.dragging}commit(){!function(e){const t=e,o=n(e);o.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o.raf),o.raf=0,o.pending=null,o.painted=l(t);const r=t.renderRoot;if(r){for(const e of r.querySelectorAll('[data-hp-live-layer="camera"]'))s(e,null);i(r,o.painted,o.painted)}}(this.host),m(this.host),d(this.host)}dispose(){!function(e){const n=t.get(e);n?.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(n.raf),t.delete(e)}(this.host),m(this.host)}}export{p as LiveRuntime};
diff --git a/dist/houseplan-assets/zigbee-topology-BnpLzLg7.js b/custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-C3YPlOFO.js
similarity index 98%
rename from dist/houseplan-assets/zigbee-topology-BnpLzLg7.js
rename to custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-C3YPlOFO.js
index c437e46b..e18783bd 100644
--- a/dist/houseplan-assets/zigbee-topology-BnpLzLg7.js
+++ b/custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-C3YPlOFO.js
@@ -1 +1 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{s as e,F as n}from"./houseplan-card-B_QYG0Py.js";var t={title:"Zigbee links",toggle:"Show Zigbee links when hovering over a device",hint:"Shows observed direct neighbours only. Nothing is fetched while you hover.",help:"Shows which Zigbee devices each device talks to directly. Line colour is link quality (LQI) on the same scale as the device's LQI reading: red at 40 and below, green at 180 and above. A dashed line means quality was not reported. An arrow points to the next device on the way to the coordinator: one arrow leads out, incoming arrows are the devices that route through this one. A line without an arrow is a spare neighbour. This is the route tree House Plan builds, not the path a packet takes right now: a label at the end of an arrow means its target is not on this plan, and no arrow at all means the route is unknown. Data comes from the last load and goes stale; links are shown with a mouse only.",help_aria:"Help: Zigbee links",admin_only:"Topology data is available to Home Assistant administrators only.",save_first:"Save this setting before loading topology data.",zha:"ZHA",zha_read:"Read ZHA data",zha_hint:"Reads ZHA's cached topology; it does not start a radio scan.",z2m:"Zigbee2MQTT",z2m_topics:"Base topics (one per line)",z2m_update:"Update map",z2m_warning:"A network-map scan can take 10 seconds to 2 minutes and may temporarily reduce Zigbee responsiveness.",status_idle:"Data not loaded",status_loading:"Loading…",status_ready:"Received {time}",status_stale:"Received {time} · stale",status_partial:"Received {time} · some nodes were omitted",status_no_links:"Received {time} · no observed links found",error_permission:"Administrator permission is required.",error_unsupported:"This provider or Home Assistant API is unavailable.",error_timeout:"The provider did not respond in time.",error_invalid_topic:"Check the Zigbee2MQTT base topic.",error_invalid_payload:"The provider returned unsupported topology data.",error_provider:"Topology data could not be loaded.",remote_count:"+{n} in other spaces",route_device_not_on_plan:"device is not on the plan",route_coordinator_not_on_plan:"coordinator is not on the plan",route_other_space:"another space"};const i={en:t,ru:{title:"Связи Zigbee",toggle:"Показывать связи Zigbee при наведении на устройство",hint:"Показываются только наблюдаемые прямые соседи. Наведение ничего не запрашивает.",help:"Показывает, с какими устройствами Zigbee каждое связано напрямую. Цвет линии — качество связи (LQI) по той же шкале, что у показателя LQI устройства: красный при 40 и ниже, зелёный при 180 и выше. Пунктир — качество не сообщено. Стрелка ведёт к следующему устройству по пути к координатору: исходящая одна, входящие — те, кто ходит через это устройство. Линия без стрелки — запасной сосед. Это дерево маршрутов, которое строит House Plan, а не путь пакета в эту секунду: подпись на конце стрелки значит, что цель не на этом плане, а отсутствие стрелки — что путь неизвестен. Данные из последней загрузки и устаревают, связи видны только при работе мышью.",help_aria:"Справка: связи Zigbee",admin_only:"Данные топологии доступны только администраторам Home Assistant.",save_first:"Сохраните настройку перед загрузкой данных топологии.",zha:"ZHA",zha_read:"Прочитать данные ZHA",zha_hint:"Читает сохранённую топологию ZHA и не запускает радио-сканирование.",z2m:"Zigbee2MQTT",z2m_topics:"Базовые топики (по одному в строке)",z2m_update:"Обновить карту",z2m_warning:"Сканирование карты сети занимает от 10 секунд до 2 минут и временно может снизить отзывчивость Zigbee.",status_idle:"Данные не загружены",status_loading:"Загрузка…",status_ready:"Получено: {time}",status_stale:"Получено: {time} · данные устарели",status_partial:"Получено: {time} · часть узлов не показана",status_no_links:"Получено: {time} · наблюдаемые связи не найдены",error_permission:"Нужны права администратора.",error_unsupported:"Провайдер или API Home Assistant недоступен.",error_timeout:"Провайдер не ответил вовремя.",error_invalid_topic:"Проверьте базовый топик Zigbee2MQTT.",error_invalid_payload:"Провайдер вернул неподдерживаемые данные топологии.",error_provider:"Не удалось загрузить данные топологии.",remote_count:"+{n} в других пространствах",route_device_not_on_plan:"устройства нет на плане",route_coordinator_not_on_plan:"координатора нет на плане",route_other_space:"другое пространство"},de:{title:"Zigbee-Verbindungen",toggle:"Zigbee-Verbindungen beim Darüberfahren über ein Gerät anzeigen",hint:"Es werden nur beobachtete direkte Nachbarn angezeigt. Beim Darüberfahren werden keine Daten abgerufen.",help:"Zeigt, mit welchen Zigbee-Geräten jedes Gerät direkt verbunden ist. Die Linienfarbe ist die Verbindungsqualität (LQI) auf derselben Skala wie der LQI-Wert des Geräts: rot bei 40 und darunter, grün bei 180 und darüber. Eine gestrichelte Linie bedeutet, dass die Qualität nicht gemeldet wurde. Ein Pfeil zeigt auf das nächste Gerät auf dem Weg zum Koordinator: ein Pfeil führt hinaus, eingehende Pfeile sind die Geräte, die über dieses Gerät routen. Eine Linie ohne Pfeil ist ein Ersatznachbar. Das ist der Routenbaum, den House Plan bildet, nicht der Weg eines Pakets in diesem Moment: eine Beschriftung am Pfeilende bedeutet, dass das Ziel nicht auf diesem Plan liegt, und ein fehlender Pfeil, dass die Route unbekannt ist. Die Daten stammen aus dem letzten Laden und veralten; Verbindungen sind nur mit der Maus sichtbar.",help_aria:"Hilfe: Zigbee-Verbindungen",admin_only:"Topologiedaten sind nur für Home-Assistant-Administratoren verfügbar.",save_first:"Speichere diese Einstellung, bevor Topologiedaten geladen werden.",zha:"ZHA",zha_read:"ZHA-Daten lesen",zha_hint:"Liest den ZHA-Topologiecache; es wird kein Funkscan gestartet.",z2m:"Zigbee2MQTT",z2m_topics:"Basistopics (eines pro Zeile)",z2m_update:"Karte aktualisieren",z2m_warning:"Ein Netzwerkscan kann 10 Sekunden bis 2 Minuten dauern und Zigbee vorübergehend verlangsamen.",status_idle:"Daten nicht geladen",status_loading:"Wird geladen…",status_ready:"Empfangen: {time}",status_stale:"Empfangen: {time} · veraltet",status_partial:"Empfangen: {time} · einige Knoten fehlen",status_no_links:"Empfangen: {time} · keine beobachteten Verbindungen gefunden",error_permission:"Administratorrechte sind erforderlich.",error_unsupported:"Dieser Anbieter oder die Home-Assistant-API ist nicht verfügbar.",error_timeout:"Der Anbieter hat nicht rechtzeitig geantwortet.",error_invalid_topic:"Prüfe das Zigbee2MQTT-Basistopic.",error_invalid_payload:"Der Anbieter hat nicht unterstützte Topologiedaten geliefert.",error_provider:"Topologiedaten konnten nicht geladen werden.",remote_count:"+{n} in anderen Bereichen",route_device_not_on_plan:"Gerät ist nicht im Plan",route_coordinator_not_on_plan:"Koordinator ist nicht im Plan",route_other_space:"anderer Bereich"},fr:{title:"Liens Zigbee",toggle:"Afficher les liens Zigbee au survol d’un appareil",hint:"Seuls les voisins directs observés sont affichés. Le survol ne lance aucune requête.",help:"Montre avec quels appareils Zigbee chaque appareil communique directement. La couleur de la ligne est la qualité du lien (LQI) sur la même échelle que l'indicateur LQI de l'appareil : rouge à 40 et en dessous, vert à 180 et au-dessus. Une ligne pointillée signifie que la qualité n'a pas été communiquée. Une flèche pointe vers l'appareil suivant sur le chemin du coordinateur : une flèche part, les flèches entrantes sont les appareils qui passent par celui-ci. Une ligne sans flèche est un voisin de secours. C'est l'arbre de routes que construit House Plan, pas le trajet d'un paquet à cet instant : une étiquette au bout d'une flèche signifie que sa cible n'est pas sur ce plan, et l'absence de flèche que la route est inconnue. Les données proviennent du dernier chargement et vieillissent ; les liens ne sont visibles qu'à la souris.",help_aria:"Aide : liens Zigbee",admin_only:"Les données de topologie sont réservées aux administrateurs Home Assistant.",save_first:"Enregistrez ce réglage avant de charger les données de topologie.",zha:"ZHA",zha_read:"Lire les données ZHA",zha_hint:"Lit la topologie en cache de ZHA sans lancer d’analyse radio.",z2m:"Zigbee2MQTT",z2m_topics:"Topics de base (un par ligne)",z2m_update:"Actualiser la carte",z2m_warning:"L’analyse de la carte réseau peut durer de 10 secondes à 2 minutes et réduire temporairement la réactivité de Zigbee.",status_idle:"Données non chargées",status_loading:"Chargement…",status_ready:"Reçu : {time}",status_stale:"Reçu : {time} · obsolète",status_partial:"Reçu : {time} · certains nœuds sont omis",status_no_links:"Reçu : {time} · aucun lien observé trouvé",error_permission:"Les droits administrateur sont requis.",error_unsupported:"Ce fournisseur ou l’API Home Assistant n’est pas disponible.",error_timeout:"Le fournisseur n’a pas répondu à temps.",error_invalid_topic:"Vérifiez le topic de base Zigbee2MQTT.",error_invalid_payload:"Le fournisseur a renvoyé des données de topologie non prises en charge.",error_provider:"Impossible de charger les données de topologie.",remote_count:"+{n} dans d’autres espaces",route_device_not_on_plan:"appareil absent du plan",route_coordinator_not_on_plan:"coordinateur absent du plan",route_other_space:"autre espace"}};function r(e,n){const r=i[e]?.[n]??t[n];return"string"==typeof r&&r.trim().length>0}function o(n,r,o){return e(i[n]?.[r]??t[r]??r,o)}const s=3e5,a=2097152,d=6e3;function l(e){return null!==e&&"object"==typeof e?e:null}function u(e){if("string"!=typeof e&&"number"!=typeof e)return null;let n=String(e).trim().toLowerCase();return n=/^0x[0-9a-f]{16}$/.test(n)?n.slice(2):n.replace(/[:-]/g,""),/^[0-9a-f]{16}$/.test(n)?n:null}function c(e,n,t){return`${e}:${n}:${t}`}function p(e){const n=String(e||"").toLowerCase().replace(/[ _-]/g,"");return n.includes("coordinator")?"coordinator":n.includes("router")?"router":n.includes("enddevice")||"end"===n?"end":"unknown"}const h=["parent","child","sibling","none","previous_child"];function g(e){const n=l(e),t=function(e){const n=Number(e);return Number.isFinite(n)&&n>=0&&n<=255?Math.round(n):void 0}(n?.lqi??n?.linkquality??n?.link_quality),i=function(e){if("number"==typeof e)return h[e];if("string"!=typeof e)return;const n=e.trim().toLowerCase().replace(/[\s_-]+/g,"");return"previouschild"===n?"previous_child":n.slice(0,40)||void 0}(n?.relationship);return{...void 0===t?{}:{lqi:t},...i?{relationship:i}:{}}}function f(e,n){return Array.isArray(e)&&e.length<=n?e:null}function _(e){if("string"==typeof e)return e.length<=a;try{return JSON.stringify(e).length<=a}catch{return!1}}function b(e,n,t,i,r){if(t===i)return void n.push({code:"self_link",nodeKey:t});const o=t=d){t.push({code:"invalid_payload"});break}const n=l(e),i=u(n?.ieee??n?.ieee_address);if(!i){t.push({code:"invalid_payload",nodeKey:s});continue}const a=c("zha","zha",i);r.has(a)||r.set(a,{key:a,ieee:i,role:p(n?.device_type)}),b(o,t,s,a,e)}else null!=n?.neighbors&&t.push({code:"invalid_payload",nodeKey:s})}return{provider:"zha",instanceId:"zha",obtainedAt:n,freshness:"provider-cache",nodes:[...r.values()],links:[...o.values()],warnings:t}}function v(e,n){const t=l(e),i=u(t?.ieeeAddr??t?.ieee_address??t?.ieee??e);if(i)return i;for(const i of[t?.id,t?.networkAddress,t?.network_address,e])if(null!=i){const e=n.get(String(i));if(e)return e}return null}function y(e,t,i=Date.now()){const r=[],o=n(t)||"invalid",s=_(e)?function(e){let n=e;if("string"==typeof n){if(n.length>a)return null;try{n=JSON.parse(n)}catch{return null}}const t=l(n),i=l(t?.data);if(n=i?.value??t?.value??t?.data??n,"string"==typeof n){if(n.length>a)return null;try{n=JSON.parse(n)}catch{return null}}return n}(e):null,h=l(s),g=f(h?.nodes,1e3),m=f(h?.links,d);if(!g||!m)return{provider:"z2m",instanceId:o,obtainedAt:i,freshness:"fresh-scan",nodes:[],links:[],warnings:[{code:"invalid_payload"}]};const y=new Map,k=new Map;for(const e of g){const n=l(e),t=u(n?.ieeeAddr??n?.ieee_address??n?.ieee);if(!t){r.push({code:"invalid_payload"});continue}const i=c("z2m",o,t);y.set(i,{key:i,ieee:t,role:p(n?.type??n?.device_type),..."boolean"==typeof n?.failed?{available:!n.failed}:{}});for(const e of[n?.id,n?.networkAddress,n?.network_address])null!=e&&k.set(String(e),t)}const w=new Map;for(const e of m){const n=l(e),t=u(n?.sourceIeeeAddr)??v(n?.source,k),i=u(n?.targetIeeeAddr)??v(n?.target,k);if(!t||!i){r.push({code:"invalid_payload"});continue}const s=c("z2m",o,t),a=c("z2m",o,i);y.has(s)||y.set(s,{key:s,ieee:t,role:"unknown"}),y.has(a)||y.set(a,{key:a,ieee:i,role:"unknown"}),b(w,r,s,a,e)}return{provider:"z2m",instanceId:o,obtainedAt:i,freshness:"fresh-scan",nodes:[...y.values()],links:[...w.values()],warnings:r}}function k(e){if("string"!=typeof e)return null;const n=u(e);if(n)return n;const t=e.toLowerCase().match(/^zigbee2mqtt(?:_bridge)?_(.+)$/);return t?u(t[1]):null}function w(e,n){if(e.deviceId&&n.devices[e.deviceId])return[e.deviceId];const t=new Set;for(const[i,r]of Object.entries(n.devices)){const n=l(r);(Array.isArray(n?.identifiers)?n.identifiers:[]).some(n=>Array.isArray(n)&&k(n[1])===e.ieee)&&t.add(i)}if(t.size)return[...t];for(const i of Object.values(n.entities)){const n=l(i);"string"==typeof n?.device_id&&"string"==typeof n.unique_id&&(k(n.unique_id)===e.ieee&&t.add(n.device_id))}return[...t]}function z(e){return!e.hidden&&!e.virtual&&"ha_disabled"!==e.bindingStatus?.kind&&"orphaned"!==e.bindingStatus?.kind&&"unverified"!==e.bindingStatus?.kind}function A(e){const n=new Map,t=new Map,i=e.nodes.filter(e=>"coordinator"===e.role).map(e=>e.key).sort();if(1!==i.length)return{distances:n,parents:t};const r=i[0],o=function(e){const n=new Set(e.nodes.map(e=>e.key)),t=new Map;for(const e of[...n].sort())t.set(e,[]);for(const i of[...e.links].sort((e,n)=>`${e.a}\0${e.b}`.localeCompare(`${n.a}\0${n.b}`)))n.has(i.a)&&n.has(i.b)&&(t.get(i.a).push({neighborKey:i.b,observation:i.aToB}),t.get(i.b).push({neighborKey:i.a,observation:i.bToA}));for(const e of t.values())e.sort((e,n)=>e.neighborKey.localeCompare(n.neighborKey));return t}(e);if(!o.has(r))return{distances:n,parents:t};n.set(r,0);const s=[r];for(let e=0;en.get(e)===i-1).sort((e,n)=>{const t="parent"===e.observation?.relationship?1:0,i="parent"===n.observation?.relationship?1:0;if(t!==i)return i-t;const r=e.observation?.lqi??-1;return(n.observation?.lqi??-1)-r||e.neighborKey.localeCompare(n.neighborKey)});r[0]&&t.set(e,r[0].neighborKey)}return{coordinatorKey:r,distances:n,parents:t}}function Z(e,n,t){const i=new Map,r=[];for(const o of e.nodes){if(!1===o.available){r.push({code:"provider_scan_failure",nodeKey:o.key});continue}const e=w(o,t);if(1!==e.length){r.push({code:"unmatched_device",nodeKey:o.key});continue}const s=e[0];let a=n.filter(e=>z(e)&&"device"===e.bindingKind&&e.bindingRef===s);a.length||(a=n.filter(e=>z(e)&&"entity"===e.bindingKind&&!!e.bindingRef&&t.entities[e.bindingRef]?.device_id===s)),1===a.length?i.set(o.key,{markerId:a[0].id,space:a[0].space}):r.push({code:a.length>1?"ambiguous_placement":"unmatched_device",nodeKey:o.key})}return{placements:i,warnings:r}}function T(e,n,t){return e.map(e=>({topology:e,placements:Z(e,n,t).placements,routes:A(e)}))}function q(e,n,t){const i=new Map,r=new Set,o=new Map;let s=0;for(const{topology:a,placements:d,routes:l}of e){const e=new Set([...d].filter(([,e])=>e.markerId===t&&e.space===n).map(([e])=>e));if(e.size){for(const t of e){const e=l.parents.get(t);if(!e)continue;const i=d.get(e);if(i?.space===n)continue;let r;r=i?{kind:"remote-space",spaceId:i.space}:"coordinator"===a.nodes.find(n=>n.key===e)?.role?{kind:"unplaced-coordinator"}:{kind:"unplaced-device"};const s="remote-space"===r.kind?`${r.kind}:${r.spaceId}`:r.kind;o.set(s,r)}for(const o of a.links){const a=e.has(o.a),u=e.has(o.b);if(!a&&!u)continue;const c=a?o.a:o.b,p=a?o.b:o.a,h=d.get(p);if(!h||h.markerId===t){s++;continue}const g=l.parents.get(c)===p;if(h.space!==n){g||r.add(h.markerId);continue}const f=a?o.aToB:o.bToA,_=g?"toward-neighbor":l.parents.get(p)===c?"toward-origin":void 0,b=i.get(h.markerId);b?(void 0===b.line.lqi&&void 0!==f?.lqi&&(b.line.lqi=f.lqi),_&&b.directions.add(_)):i.set(h.markerId,{line:{neighborMarkerId:h.markerId,lqi:f?.lqi},directions:new Set(_?[_]:[])})}}}return{lines:[...i.values()].map(({line:e,directions:n})=>1===n.size?{...e,routeDirection:[...n][0]}:e),remoteCount:r.size,omittedCount:s,parentTargets:[...o.values()]}}export{s as T,T as a,y as b,r as h,Z as m,m as n,q as r,o as t};
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{s as e,F as n}from"./houseplan-card-6Hf8VPda.js";var t={title:"Zigbee links",toggle:"Show Zigbee links when hovering over a device",hint:"Shows observed direct neighbours only. Nothing is fetched while you hover.",help:"Shows which Zigbee devices each device talks to directly. Line colour is link quality (LQI) on the same scale as the device's LQI reading: red at 40 and below, green at 180 and above. A dashed line means quality was not reported. An arrow points to the next device on the way to the coordinator: one arrow leads out, incoming arrows are the devices that route through this one. A line without an arrow is a spare neighbour. This is the route tree House Plan builds, not the path a packet takes right now: a label at the end of an arrow means its target is not on this plan, and no arrow at all means the route is unknown. Data comes from the last load and goes stale; links are shown with a mouse only.",help_aria:"Help: Zigbee links",admin_only:"Topology data is available to Home Assistant administrators only.",save_first:"Save this setting before loading topology data.",zha:"ZHA",zha_read:"Read ZHA data",zha_hint:"Reads ZHA's cached topology; it does not start a radio scan.",z2m:"Zigbee2MQTT",z2m_topics:"Base topics (one per line)",z2m_update:"Update map",z2m_warning:"A network-map scan can take 10 seconds to 2 minutes and may temporarily reduce Zigbee responsiveness.",status_idle:"Data not loaded",status_loading:"Loading…",status_ready:"Received {time}",status_stale:"Received {time} · stale",status_partial:"Received {time} · some nodes were omitted",status_no_links:"Received {time} · no observed links found",error_permission:"Administrator permission is required.",error_unsupported:"This provider or Home Assistant API is unavailable.",error_timeout:"The provider did not respond in time.",error_invalid_topic:"Check the Zigbee2MQTT base topic.",error_invalid_payload:"The provider returned unsupported topology data.",error_provider:"Topology data could not be loaded.",remote_count:"+{n} in other spaces",route_device_not_on_plan:"device is not on the plan",route_coordinator_not_on_plan:"coordinator is not on the plan",route_other_space:"another space"};const i={en:t,ru:{title:"Связи Zigbee",toggle:"Показывать связи Zigbee при наведении на устройство",hint:"Показываются только наблюдаемые прямые соседи. Наведение ничего не запрашивает.",help:"Показывает, с какими устройствами Zigbee каждое связано напрямую. Цвет линии — качество связи (LQI) по той же шкале, что у показателя LQI устройства: красный при 40 и ниже, зелёный при 180 и выше. Пунктир — качество не сообщено. Стрелка ведёт к следующему устройству по пути к координатору: исходящая одна, входящие — те, кто ходит через это устройство. Линия без стрелки — запасной сосед. Это дерево маршрутов, которое строит House Plan, а не путь пакета в эту секунду: подпись на конце стрелки значит, что цель не на этом плане, а отсутствие стрелки — что путь неизвестен. Данные из последней загрузки и устаревают, связи видны только при работе мышью.",help_aria:"Справка: связи Zigbee",admin_only:"Данные топологии доступны только администраторам Home Assistant.",save_first:"Сохраните настройку перед загрузкой данных топологии.",zha:"ZHA",zha_read:"Прочитать данные ZHA",zha_hint:"Читает сохранённую топологию ZHA и не запускает радио-сканирование.",z2m:"Zigbee2MQTT",z2m_topics:"Базовые топики (по одному в строке)",z2m_update:"Обновить карту",z2m_warning:"Сканирование карты сети занимает от 10 секунд до 2 минут и временно может снизить отзывчивость Zigbee.",status_idle:"Данные не загружены",status_loading:"Загрузка…",status_ready:"Получено: {time}",status_stale:"Получено: {time} · данные устарели",status_partial:"Получено: {time} · часть узлов не показана",status_no_links:"Получено: {time} · наблюдаемые связи не найдены",error_permission:"Нужны права администратора.",error_unsupported:"Провайдер или API Home Assistant недоступен.",error_timeout:"Провайдер не ответил вовремя.",error_invalid_topic:"Проверьте базовый топик Zigbee2MQTT.",error_invalid_payload:"Провайдер вернул неподдерживаемые данные топологии.",error_provider:"Не удалось загрузить данные топологии.",remote_count:"+{n} в других пространствах",route_device_not_on_plan:"устройства нет на плане",route_coordinator_not_on_plan:"координатора нет на плане",route_other_space:"другое пространство"},de:{title:"Zigbee-Verbindungen",toggle:"Zigbee-Verbindungen beim Darüberfahren über ein Gerät anzeigen",hint:"Es werden nur beobachtete direkte Nachbarn angezeigt. Beim Darüberfahren werden keine Daten abgerufen.",help:"Zeigt, mit welchen Zigbee-Geräten jedes Gerät direkt verbunden ist. Die Linienfarbe ist die Verbindungsqualität (LQI) auf derselben Skala wie der LQI-Wert des Geräts: rot bei 40 und darunter, grün bei 180 und darüber. Eine gestrichelte Linie bedeutet, dass die Qualität nicht gemeldet wurde. Ein Pfeil zeigt auf das nächste Gerät auf dem Weg zum Koordinator: ein Pfeil führt hinaus, eingehende Pfeile sind die Geräte, die über dieses Gerät routen. Eine Linie ohne Pfeil ist ein Ersatznachbar. Das ist der Routenbaum, den House Plan bildet, nicht der Weg eines Pakets in diesem Moment: eine Beschriftung am Pfeilende bedeutet, dass das Ziel nicht auf diesem Plan liegt, und ein fehlender Pfeil, dass die Route unbekannt ist. Die Daten stammen aus dem letzten Laden und veralten; Verbindungen sind nur mit der Maus sichtbar.",help_aria:"Hilfe: Zigbee-Verbindungen",admin_only:"Topologiedaten sind nur für Home-Assistant-Administratoren verfügbar.",save_first:"Speichere diese Einstellung, bevor Topologiedaten geladen werden.",zha:"ZHA",zha_read:"ZHA-Daten lesen",zha_hint:"Liest den ZHA-Topologiecache; es wird kein Funkscan gestartet.",z2m:"Zigbee2MQTT",z2m_topics:"Basistopics (eines pro Zeile)",z2m_update:"Karte aktualisieren",z2m_warning:"Ein Netzwerkscan kann 10 Sekunden bis 2 Minuten dauern und Zigbee vorübergehend verlangsamen.",status_idle:"Daten nicht geladen",status_loading:"Wird geladen…",status_ready:"Empfangen: {time}",status_stale:"Empfangen: {time} · veraltet",status_partial:"Empfangen: {time} · einige Knoten fehlen",status_no_links:"Empfangen: {time} · keine beobachteten Verbindungen gefunden",error_permission:"Administratorrechte sind erforderlich.",error_unsupported:"Dieser Anbieter oder die Home-Assistant-API ist nicht verfügbar.",error_timeout:"Der Anbieter hat nicht rechtzeitig geantwortet.",error_invalid_topic:"Prüfe das Zigbee2MQTT-Basistopic.",error_invalid_payload:"Der Anbieter hat nicht unterstützte Topologiedaten geliefert.",error_provider:"Topologiedaten konnten nicht geladen werden.",remote_count:"+{n} in anderen Bereichen",route_device_not_on_plan:"Gerät ist nicht im Plan",route_coordinator_not_on_plan:"Koordinator ist nicht im Plan",route_other_space:"anderer Bereich"},fr:{title:"Liens Zigbee",toggle:"Afficher les liens Zigbee au survol d’un appareil",hint:"Seuls les voisins directs observés sont affichés. Le survol ne lance aucune requête.",help:"Montre avec quels appareils Zigbee chaque appareil communique directement. La couleur de la ligne est la qualité du lien (LQI) sur la même échelle que l'indicateur LQI de l'appareil : rouge à 40 et en dessous, vert à 180 et au-dessus. Une ligne pointillée signifie que la qualité n'a pas été communiquée. Une flèche pointe vers l'appareil suivant sur le chemin du coordinateur : une flèche part, les flèches entrantes sont les appareils qui passent par celui-ci. Une ligne sans flèche est un voisin de secours. C'est l'arbre de routes que construit House Plan, pas le trajet d'un paquet à cet instant : une étiquette au bout d'une flèche signifie que sa cible n'est pas sur ce plan, et l'absence de flèche que la route est inconnue. Les données proviennent du dernier chargement et vieillissent ; les liens ne sont visibles qu'à la souris.",help_aria:"Aide : liens Zigbee",admin_only:"Les données de topologie sont réservées aux administrateurs Home Assistant.",save_first:"Enregistrez ce réglage avant de charger les données de topologie.",zha:"ZHA",zha_read:"Lire les données ZHA",zha_hint:"Lit la topologie en cache de ZHA sans lancer d’analyse radio.",z2m:"Zigbee2MQTT",z2m_topics:"Topics de base (un par ligne)",z2m_update:"Actualiser la carte",z2m_warning:"L’analyse de la carte réseau peut durer de 10 secondes à 2 minutes et réduire temporairement la réactivité de Zigbee.",status_idle:"Données non chargées",status_loading:"Chargement…",status_ready:"Reçu : {time}",status_stale:"Reçu : {time} · obsolète",status_partial:"Reçu : {time} · certains nœuds sont omis",status_no_links:"Reçu : {time} · aucun lien observé trouvé",error_permission:"Les droits administrateur sont requis.",error_unsupported:"Ce fournisseur ou l’API Home Assistant n’est pas disponible.",error_timeout:"Le fournisseur n’a pas répondu à temps.",error_invalid_topic:"Vérifiez le topic de base Zigbee2MQTT.",error_invalid_payload:"Le fournisseur a renvoyé des données de topologie non prises en charge.",error_provider:"Impossible de charger les données de topologie.",remote_count:"+{n} dans d’autres espaces",route_device_not_on_plan:"appareil absent du plan",route_coordinator_not_on_plan:"coordinateur absent du plan",route_other_space:"autre espace"}};function r(e,n){const r=i[e]?.[n]??t[n];return"string"==typeof r&&r.trim().length>0}function o(n,r,o){return e(i[n]?.[r]??t[r]??r,o)}const s=3e5,a=2097152,d=6e3;function l(e){return null!==e&&"object"==typeof e?e:null}function u(e){if("string"!=typeof e&&"number"!=typeof e)return null;let n=String(e).trim().toLowerCase();return n=/^0x[0-9a-f]{16}$/.test(n)?n.slice(2):n.replace(/[:-]/g,""),/^[0-9a-f]{16}$/.test(n)?n:null}function c(e,n,t){return`${e}:${n}:${t}`}function p(e){const n=String(e||"").toLowerCase().replace(/[ _-]/g,"");return n.includes("coordinator")?"coordinator":n.includes("router")?"router":n.includes("enddevice")||"end"===n?"end":"unknown"}const h=["parent","child","sibling","none","previous_child"];function g(e){const n=l(e),t=function(e){const n=Number(e);return Number.isFinite(n)&&n>=0&&n<=255?Math.round(n):void 0}(n?.lqi??n?.linkquality??n?.link_quality),i=function(e){if("number"==typeof e)return h[e];if("string"!=typeof e)return;const n=e.trim().toLowerCase().replace(/[\s_-]+/g,"");return"previouschild"===n?"previous_child":n.slice(0,40)||void 0}(n?.relationship);return{...void 0===t?{}:{lqi:t},...i?{relationship:i}:{}}}function f(e,n){return Array.isArray(e)&&e.length<=n?e:null}function _(e){if("string"==typeof e)return e.length<=a;try{return JSON.stringify(e).length<=a}catch{return!1}}function b(e,n,t,i,r){if(t===i)return void n.push({code:"self_link",nodeKey:t});const o=t=d){t.push({code:"invalid_payload"});break}const n=l(e),i=u(n?.ieee??n?.ieee_address);if(!i){t.push({code:"invalid_payload",nodeKey:s});continue}const a=c("zha","zha",i);r.has(a)||r.set(a,{key:a,ieee:i,role:p(n?.device_type)}),b(o,t,s,a,e)}else null!=n?.neighbors&&t.push({code:"invalid_payload",nodeKey:s})}return{provider:"zha",instanceId:"zha",obtainedAt:n,freshness:"provider-cache",nodes:[...r.values()],links:[...o.values()],warnings:t}}function v(e,n){const t=l(e),i=u(t?.ieeeAddr??t?.ieee_address??t?.ieee??e);if(i)return i;for(const i of[t?.id,t?.networkAddress,t?.network_address,e])if(null!=i){const e=n.get(String(i));if(e)return e}return null}function y(e,t,i=Date.now()){const r=[],o=n(t)||"invalid",s=_(e)?function(e){let n=e;if("string"==typeof n){if(n.length>a)return null;try{n=JSON.parse(n)}catch{return null}}const t=l(n),i=l(t?.data);if(n=i?.value??t?.value??t?.data??n,"string"==typeof n){if(n.length>a)return null;try{n=JSON.parse(n)}catch{return null}}return n}(e):null,h=l(s),g=f(h?.nodes,1e3),m=f(h?.links,d);if(!g||!m)return{provider:"z2m",instanceId:o,obtainedAt:i,freshness:"fresh-scan",nodes:[],links:[],warnings:[{code:"invalid_payload"}]};const y=new Map,k=new Map;for(const e of g){const n=l(e),t=u(n?.ieeeAddr??n?.ieee_address??n?.ieee);if(!t){r.push({code:"invalid_payload"});continue}const i=c("z2m",o,t);y.set(i,{key:i,ieee:t,role:p(n?.type??n?.device_type),..."boolean"==typeof n?.failed?{available:!n.failed}:{}});for(const e of[n?.id,n?.networkAddress,n?.network_address])null!=e&&k.set(String(e),t)}const w=new Map;for(const e of m){const n=l(e),t=u(n?.sourceIeeeAddr)??v(n?.source,k),i=u(n?.targetIeeeAddr)??v(n?.target,k);if(!t||!i){r.push({code:"invalid_payload"});continue}const s=c("z2m",o,t),a=c("z2m",o,i);y.has(s)||y.set(s,{key:s,ieee:t,role:"unknown"}),y.has(a)||y.set(a,{key:a,ieee:i,role:"unknown"}),b(w,r,s,a,e)}return{provider:"z2m",instanceId:o,obtainedAt:i,freshness:"fresh-scan",nodes:[...y.values()],links:[...w.values()],warnings:r}}function k(e){if("string"!=typeof e)return null;const n=u(e);if(n)return n;const t=e.toLowerCase().match(/^zigbee2mqtt(?:_bridge)?_(.+)$/);return t?u(t[1]):null}function w(e,n){if(e.deviceId&&n.devices[e.deviceId])return[e.deviceId];const t=new Set;for(const[i,r]of Object.entries(n.devices)){const n=l(r);(Array.isArray(n?.identifiers)?n.identifiers:[]).some(n=>Array.isArray(n)&&k(n[1])===e.ieee)&&t.add(i)}if(t.size)return[...t];for(const i of Object.values(n.entities)){const n=l(i);"string"==typeof n?.device_id&&"string"==typeof n.unique_id&&(k(n.unique_id)===e.ieee&&t.add(n.device_id))}return[...t]}function z(e){return!e.hidden&&!e.virtual&&"ha_disabled"!==e.bindingStatus?.kind&&"orphaned"!==e.bindingStatus?.kind&&"unverified"!==e.bindingStatus?.kind}function A(e){const n=new Map,t=new Map,i=e.nodes.filter(e=>"coordinator"===e.role).map(e=>e.key).sort();if(1!==i.length)return{distances:n,parents:t};const r=i[0],o=function(e){const n=new Set(e.nodes.map(e=>e.key)),t=new Map;for(const e of[...n].sort())t.set(e,[]);for(const i of[...e.links].sort((e,n)=>`${e.a}\0${e.b}`.localeCompare(`${n.a}\0${n.b}`)))n.has(i.a)&&n.has(i.b)&&(t.get(i.a).push({neighborKey:i.b,observation:i.aToB}),t.get(i.b).push({neighborKey:i.a,observation:i.bToA}));for(const e of t.values())e.sort((e,n)=>e.neighborKey.localeCompare(n.neighborKey));return t}(e);if(!o.has(r))return{distances:n,parents:t};n.set(r,0);const s=[r];for(let e=0;en.get(e)===i-1).sort((e,n)=>{const t="parent"===e.observation?.relationship?1:0,i="parent"===n.observation?.relationship?1:0;if(t!==i)return i-t;const r=e.observation?.lqi??-1;return(n.observation?.lqi??-1)-r||e.neighborKey.localeCompare(n.neighborKey)});r[0]&&t.set(e,r[0].neighborKey)}return{coordinatorKey:r,distances:n,parents:t}}function Z(e,n,t){const i=new Map,r=[];for(const o of e.nodes){if(!1===o.available){r.push({code:"provider_scan_failure",nodeKey:o.key});continue}const e=w(o,t);if(1!==e.length){r.push({code:"unmatched_device",nodeKey:o.key});continue}const s=e[0];let a=n.filter(e=>z(e)&&"device"===e.bindingKind&&e.bindingRef===s);a.length||(a=n.filter(e=>z(e)&&"entity"===e.bindingKind&&!!e.bindingRef&&t.entities[e.bindingRef]?.device_id===s)),1===a.length?i.set(o.key,{markerId:a[0].id,space:a[0].space}):r.push({code:a.length>1?"ambiguous_placement":"unmatched_device",nodeKey:o.key})}return{placements:i,warnings:r}}function T(e,n,t){return e.map(e=>({topology:e,placements:Z(e,n,t).placements,routes:A(e)}))}function q(e,n,t){const i=new Map,r=new Set,o=new Map;let s=0;for(const{topology:a,placements:d,routes:l}of e){const e=new Set([...d].filter(([,e])=>e.markerId===t&&e.space===n).map(([e])=>e));if(e.size){for(const t of e){const e=l.parents.get(t);if(!e)continue;const i=d.get(e);if(i?.space===n)continue;let r;r=i?{kind:"remote-space",spaceId:i.space}:"coordinator"===a.nodes.find(n=>n.key===e)?.role?{kind:"unplaced-coordinator"}:{kind:"unplaced-device"};const s="remote-space"===r.kind?`${r.kind}:${r.spaceId}`:r.kind;o.set(s,r)}for(const o of a.links){const a=e.has(o.a),u=e.has(o.b);if(!a&&!u)continue;const c=a?o.a:o.b,p=a?o.b:o.a,h=d.get(p);if(!h||h.markerId===t){s++;continue}const g=l.parents.get(c)===p;if(h.space!==n){g||r.add(h.markerId);continue}const f=a?o.aToB:o.bToA,_=g?"toward-neighbor":l.parents.get(p)===c?"toward-origin":void 0,b=i.get(h.markerId);b?(void 0===b.line.lqi&&void 0!==f?.lqi&&(b.line.lqi=f.lqi),_&&b.directions.add(_)):i.set(h.markerId,{line:{neighborMarkerId:h.markerId,lqi:f?.lqi},directions:new Set(_?[_]:[])})}}}return{lines:[...i.values()].map(({line:e,directions:n})=>1===n.size?{...e,routeDirection:[...n][0]}:e),remoteCount:r.size,omittedCount:s,parentTargets:[...o.values()]}}export{s as T,T as a,y as b,r as h,Z as m,m as n,q as r,o as t};
diff --git a/custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js b/custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js
similarity index 93%
rename from custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js
rename to custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js
index f9b59aba..b0cb0a1f 100644
--- a/custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js
+++ b/custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js
@@ -1 +1 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{n as t,b as n}from"./zigbee-topology-BnpLzLg7.js";import{F as e}from"./houseplan-card-B_QYG0Py.js";const o=new WeakMap;function i(t){const n=function(t){const n=t?.connection||t;return!n||"object"!=typeof n&&"function"!=typeof n?null:n}(t);if(!n)return null;let e=o.get(n);return e||(e={revision:0,topologies:[],states:{},listeners:new Set,inflight:new Map},o.set(n,e)),e}function r(t,n,e){t.states={...t.states,[n]:e},function(t){t.revision++;for(const n of t.listeners)n()}(t)}function s(t){const n=t?.code;if("permission"===n||"unsupported"===n||"timeout"===n||"invalid_topic"===n||"invalid_payload"===n)return n;const e=String(t?.message||"").toLowerCase();return e.includes("unauthor")||e.includes("permission")?"permission":e.includes("unknown_command")||e.includes("not found")?"unsupported":"provider"}function a(t){return Object.assign(new Error(t),{code:t})}function c(t,n,e){const o=t.inflight.get(n);if(o)return o;r(t,n,{phase:"loading"});const i=e().then(n=>{if(!n.nodes.length&&n.warnings.some(t=>"invalid_payload"===t.code))throw a("invalid_payload");!function(t,n){t.topologies=[...t.topologies.filter(t=>!(t.provider===n.provider&&t.instanceId===n.instanceId)),n],r(t,"zha"===n.provider?"zha":`z2m:${n.instanceId}`,{phase:"ready",obtainedAt:n.obtainedAt,partial:n.warnings.length>0})}(t,n)}).catch(e=>{r(t,n,{phase:"error",error:s(e)})}).finally(()=>t.inflight.delete(n));return t.inflight.set(n,i),i}function l(t){const n=i(t);return n?{revision:n.revision,topologies:n.topologies,states:n.states}:{revision:0,topologies:[],states:{}}}function u(t,n){const e=i(t);return e?(e.listeners.add(n),()=>e.listeners.delete(n)):()=>{}}function f(t){if(!0!==t?.user?.is_admin)throw a("permission")}function p(n){const e=i(n);return e?c(e,"zha",async()=>{if(f(n),"function"!=typeof n?.callWS)throw a("unsupported");return t(await n.callWS({type:"zha/devices"}))}):Promise.resolve()}function d(t){return null!==t&&"object"==typeof t?t:null}function h(t){const n=d(t),e=n?.payload??t;if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return null}}async function m(t,n){let e;try{return await Promise.race([t,new Promise((t,o)=>{e=globalThis.setTimeout(()=>o(a("timeout")),Math.max(1,n))})])}finally{void 0!==e&&globalThis.clearTimeout(e)}}function g(t,o,r=15e4){const s=i(t);if(!s)return Promise.resolve();const l=e(o);return c(s,`z2m:${l||String(o)}`,async()=>{if(f(t),!l)throw a("invalid_topic");const e=t.connection,o=e?.subscribeMessage;if("function"!=typeof o||"function"!=typeof t?.callService)throw a("unsupported");const i=function(){const t=globalThis.crypto;return"function"==typeof t?.randomUUID?`houseplan-${t.randomUUID()}`:`houseplan-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),s=Date.now()+Math.max(1,r);let c=!1,u=null,p=null,g=null;const y=new Promise(t=>{u=t}),w=new Promise((t,n)=>{p=t,g=n}),b=[];try{const r=await o.call(e,t=>{!0===d(t)?.retain&&h(t)&&u?.()},{type:"mqtt/subscribe",topic:`${l}/bridge/info`});"function"==typeof r&&b.push(r);const f=await o.call(e,t=>{if(!0===d(t)?.retain)return;const n=h(t);null!==n?n&&function(t){const n=d(t),e=n?.transaction??d(n?.data)?.transaction;return"string"==typeof e||"number"==typeof e?String(e):null}(n)===i&&p?.(n):c&&g?.(a("invalid_payload"))},{type:"mqtt/subscribe",topic:`${l}/bridge/response/networkmap`});"function"==typeof f&&b.push(f),await m(y,Math.min(4e3,Math.max(1,s-Date.now()))),c=!0,await t.callService("mqtt","publish",{topic:`${l}/bridge/request/networkmap`,payload:JSON.stringify({type:"raw",routes:!1,transaction:i}),qos:0,retain:!1});const v=await m(w,s-Date.now()),_=d(v)?.status;if(_&&"ok"!==_)throw a("provider");return n(v,l)}finally{for(const t of b)try{t()}catch{}}})}export{p as readZhaTopology,g as refreshZ2mTopology,u as subscribeZigbeeTopology,l as zigbeeTopologyRuntimeSnapshot};
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{n as t,b as n}from"./zigbee-topology-C3YPlOFO.js";import{F as e}from"./houseplan-card-6Hf8VPda.js";const o=new WeakMap;function i(t){const n=function(t){const n=t?.connection||t;return!n||"object"!=typeof n&&"function"!=typeof n?null:n}(t);if(!n)return null;let e=o.get(n);return e||(e={revision:0,topologies:[],states:{},listeners:new Set,inflight:new Map},o.set(n,e)),e}function r(t,n,e){t.states={...t.states,[n]:e},function(t){t.revision++;for(const n of t.listeners)n()}(t)}function s(t){const n=t?.code;if("permission"===n||"unsupported"===n||"timeout"===n||"invalid_topic"===n||"invalid_payload"===n)return n;const e=String(t?.message||"").toLowerCase();return e.includes("unauthor")||e.includes("permission")?"permission":e.includes("unknown_command")||e.includes("not found")?"unsupported":"provider"}function a(t){return Object.assign(new Error(t),{code:t})}function c(t,n,e){const o=t.inflight.get(n);if(o)return o;r(t,n,{phase:"loading"});const i=e().then(n=>{if(!n.nodes.length&&n.warnings.some(t=>"invalid_payload"===t.code))throw a("invalid_payload");!function(t,n){t.topologies=[...t.topologies.filter(t=>!(t.provider===n.provider&&t.instanceId===n.instanceId)),n],r(t,"zha"===n.provider?"zha":`z2m:${n.instanceId}`,{phase:"ready",obtainedAt:n.obtainedAt,partial:n.warnings.length>0})}(t,n)}).catch(e=>{r(t,n,{phase:"error",error:s(e)})}).finally(()=>t.inflight.delete(n));return t.inflight.set(n,i),i}function l(t){const n=i(t);return n?{revision:n.revision,topologies:n.topologies,states:n.states}:{revision:0,topologies:[],states:{}}}function u(t,n){const e=i(t);return e?(e.listeners.add(n),()=>e.listeners.delete(n)):()=>{}}function f(t){if(!0!==t?.user?.is_admin)throw a("permission")}function p(n){const e=i(n);return e?c(e,"zha",async()=>{if(f(n),"function"!=typeof n?.callWS)throw a("unsupported");return t(await n.callWS({type:"zha/devices"}))}):Promise.resolve()}function d(t){return null!==t&&"object"==typeof t?t:null}function h(t){const n=d(t),e=n?.payload??t;if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return null}}async function m(t,n){let e;try{return await Promise.race([t,new Promise((t,o)=>{e=globalThis.setTimeout(()=>o(a("timeout")),Math.max(1,n))})])}finally{void 0!==e&&globalThis.clearTimeout(e)}}function g(t,o,r=15e4){const s=i(t);if(!s)return Promise.resolve();const l=e(o);return c(s,`z2m:${l||String(o)}`,async()=>{if(f(t),!l)throw a("invalid_topic");const e=t.connection,o=e?.subscribeMessage;if("function"!=typeof o||"function"!=typeof t?.callService)throw a("unsupported");const i=function(){const t=globalThis.crypto;return"function"==typeof t?.randomUUID?`houseplan-${t.randomUUID()}`:`houseplan-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),s=Date.now()+Math.max(1,r);let c=!1,u=null,p=null,g=null;const y=new Promise(t=>{u=t}),w=new Promise((t,n)=>{p=t,g=n}),b=[];try{const r=await o.call(e,t=>{!0===d(t)?.retain&&h(t)&&u?.()},{type:"mqtt/subscribe",topic:`${l}/bridge/info`});"function"==typeof r&&b.push(r);const f=await o.call(e,t=>{if(!0===d(t)?.retain)return;const n=h(t);null!==n?n&&function(t){const n=d(t),e=n?.transaction??d(n?.data)?.transaction;return"string"==typeof e||"number"==typeof e?String(e):null}(n)===i&&p?.(n):c&&g?.(a("invalid_payload"))},{type:"mqtt/subscribe",topic:`${l}/bridge/response/networkmap`});"function"==typeof f&&b.push(f),await m(y,Math.min(4e3,Math.max(1,s-Date.now()))),c=!0,await t.callService("mqtt","publish",{topic:`${l}/bridge/request/networkmap`,payload:JSON.stringify({type:"raw",routes:!1,transaction:i}),qos:0,retain:!1});const v=await m(w,s-Date.now()),_=d(v)?.status;if(_&&"ok"!==_)throw a("provider");return n(v,l)}finally{for(const t of b)try{t()}catch{}}})}export{p as readZhaTopology,g as refreshZ2mTopology,u as subscribeZigbeeTopology,l as zigbeeTopologyRuntimeSnapshot};
diff --git a/custom_components/houseplan/frontend/houseplan-card.js b/custom_components/houseplan/frontend/houseplan-card.js
index c167f81e..6a070b8c 100644
--- a/custom_components/houseplan/frontend/houseplan-card.js
+++ b/custom_components/houseplan/frontend/houseplan-card.js
@@ -1 +1 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";try{await import("./houseplan-assets/houseplan-card-B_QYG0Py.js")}catch(e){if(!customElements.get("houseplan-card")){const l=String(navigator.language||"en").toLowerCase();const m=l.startsWith("ru")?"House Plan обновился — перезагрузите страницу (Ctrl+F5).":l.startsWith("de")?"House Plan wurde aktualisiert — bitte laden Sie die Seite neu (Strg+F5).":l.startsWith("fr")?"House Plan a été mis à jour — veuillez recharger la page (Ctrl+F5).":"House Plan was updated — please reload the page (Ctrl+F5).";customElements.define("houseplan-card",class extends HTMLElement{setConfig(){}getCardSize(){return 1}connectedCallback(){this.style.cssText="display:block;box-sizing:border-box;padding:16px;border:1px solid var(--divider-color,#e0e0e0);border-radius:var(--ha-card-border-radius,12px);background:var(--card-background-color,#fff);color:var(--primary-text-color,#212121);font:14px/1.4 var(--paper-font-body1_-_font-family,sans-serif)";this.textContent=m}})}console.error("[houseplan] stale entry: the main chunk is unavailable",e)}
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";try{await import("./houseplan-assets/houseplan-card-6Hf8VPda.js")}catch(e){if(!customElements.get("houseplan-card")){const l=String(navigator.language||"en").toLowerCase();const m=l.startsWith("ru")?"House Plan обновился — перезагрузите страницу (Ctrl+F5).":l.startsWith("de")?"House Plan wurde aktualisiert — bitte laden Sie die Seite neu (Strg+F5).":l.startsWith("fr")?"House Plan a été mis à jour — veuillez recharger la page (Ctrl+F5).":"House Plan was updated — please reload the page (Ctrl+F5).";customElements.define("houseplan-card",class extends HTMLElement{setConfig(){}getCardSize(){return 1}connectedCallback(){this.style.cssText="display:block;box-sizing:border-box;padding:16px;border:1px solid var(--divider-color,#e0e0e0);border-radius:var(--ha-card-border-radius,12px);background:var(--card-background-color,#fff);color:var(--primary-text-color,#212121);font:14px/1.4 var(--paper-font-body1_-_font-family,sans-serif)";this.textContent=m}})}console.error("[houseplan] stale entry: the main chunk is unavailable",e)}
diff --git a/demo/benchmark_wall_draw_click.mjs b/demo/benchmark_wall_draw_click.mjs
index 3cd0ab0e..77eb387e 100644
--- a/demo/benchmark_wall_draw_click.mjs
+++ b/demo/benchmark_wall_draw_click.mjs
@@ -4,6 +4,7 @@ import { dirname, resolve } from 'node:path';
import { launch, finish } from './serve.mjs';
import {
installWallDrawClickHarness, resetWallDrawClickHarness, runWallDrawClickChain,
+ runWallDrawFinishProfile,
} from './wall-draw-click-harness.mjs';
const outputArg = process.argv.find((arg) => arg.startsWith('--output='));
@@ -20,6 +21,15 @@ const run = async (remote) => {
};
const base = await run(false);
const remote = await run(true);
+const runFinish = async (remoteVariant) => {
+ await resetWallDrawClickHarness(page, remoteVariant);
+ // Warm the distinct finalizer path, then measure it from the same fixture.
+ await runWallDrawFinishProfile(page);
+ await resetWallDrawClickHarness(page, remoteVariant);
+ return runWallDrawFinishProfile(page);
+};
+const baseFinish = await runFinish(false);
+const remoteFinish = await runFinish(true);
const sorted = [...base.result.times].sort((a, b) => a - b);
const medianMs = sorted[Math.floor(sorted.length / 2)];
const maxMs = Math.max(...base.result.times);
@@ -48,13 +58,33 @@ const structural = fixtureShape && remoteFixtureShape
&& base.result.terminal.configWrites === 0 && base.result.terminal.history === 0
&& base.result.terminalPartitionCount === base.fixture.savedPartitions + 7
&& base.result.activeCleared;
+const finishStructural = baseFinish.terminal.fullSpacePhysicalChecks === 0
+ && baseFinish.terminal.localPhysicalChecks === 1
+ && baseFinish.terminal.configWrites === 1
+ && baseFinish.terminal.history === 0
+ && baseFinish.terminal.wallFinishBarriers === 1
+ && baseFinish.terminal.wallGenericFallbacks === 0
+ && baseFinish.surviving.length === 1
+ && baseFinish.terminalPartitionCount === base.fixture.savedPartitions + 1
+ && baseFinish.optimizeChanged === false
+ && baseFinish.activeCleared
+ && remoteFinish.terminal.fullSpacePhysicalChecks === 0
+ && remoteFinish.terminal.localPhysicalChecks === 1
+ && remoteFinish.terminal.configWrites === 1
+ && remoteFinish.terminal.wallFinishBarriers === 1
+ && remoteFinish.surviving.length === 1
+ && remoteFinish.optimizeChanged === false;
const budgets = {
medianMs: 150,
maxMs: 250,
remoteMedianMs: medianMs * 1.5 + 20,
+ finishMs: 250,
+ remoteFinishMs: baseFinish.finishMs * 1.5 + 20,
};
const timing = medianMs <= budgets.medianMs && maxMs <= budgets.maxMs
- && remoteMedianMs <= budgets.remoteMedianMs;
+ && remoteMedianMs <= budgets.remoteMedianMs
+ && baseFinish.finishMs <= budgets.finishMs
+ && remoteFinish.finishMs <= budgets.remoteFinishMs;
const report = {
issue: 461, profile: 'wall-draw-click-v1',
fixture: base.fixture, remoteFixture: remote.fixture,
@@ -63,13 +93,16 @@ const report = {
medianMs: Math.round(medianMs * 10) / 10,
maxMs: Math.round(maxMs * 10) / 10,
remoteMedianMs: Math.round(remoteMedianMs * 10) / 10,
+ finishMs: Math.round(baseFinish.finishMs * 10) / 10,
+ remoteFinishMs: Math.round(remoteFinish.finishMs * 10) / 10,
},
budgets: Object.fromEntries(Object.entries(budgets)
.map(([key, value]) => [key, Math.round(value * 10) / 10])),
counters: base.result.metrics,
- structural,
+ finishCounters: baseFinish.terminal,
+ structural: structural && finishStructural,
timingPass: timing,
- pass: structural && timing,
+ pass: structural && finishStructural && timing,
};
if (output) {
mkdirSync(dirname(output), { recursive: true });
diff --git a/demo/smoke_writer_fixed_point.mjs b/demo/smoke_writer_fixed_point.mjs
new file mode 100644
index 00000000..4b8f1e5b
--- /dev/null
+++ b/demo/smoke_writer_fixed_point.mjs
@@ -0,0 +1,93 @@
+/** #477 production-bundle wall finish and room-reference transaction smoke. */
+import { launch, checkAll, finish } from './serve.mjs';
+import {
+ installWallDrawClickHarness, resetWallDrawClickHarness, runWallDrawFinishProfile,
+} from './wall-draw-click-harness.mjs';
+
+const { page, browser } = await launch({ width: 1100, height: 850 }, 1);
+await installWallDrawClickHarness(page);
+await resetWallDrawClickHarness(page, false);
+const chain = await runWallDrawFinishProfile(page);
+
+const chainHistory = await page.evaluate(async (chainIds) => {
+ const card = window.__card;
+ const optimizeNoop = () => {
+ card._previewAlignDialog(false);
+ const changed = card._alignDialog?.changed;
+ card._alignDialog = null;
+ return changed === false;
+ };
+ card._undoGeometry();
+ await card.updateComplete;
+ const afterUndo = {
+ optimizeNoop: optimizeNoop(),
+ partitions: (card._curSpaceCfg.partitions || [])
+ .filter((partition) => chainIds.includes(partition.id)).length,
+ };
+ card._redoGeometry();
+ await card.updateComplete;
+ const afterRedo = {
+ optimizeNoop: optimizeNoop(),
+ partitions: (card._curSpaceCfg.partitions || [])
+ .filter((partition) => chainIds.includes(partition.id)).length,
+ };
+ return { afterUndo, afterRedo };
+}, chain.chainIds);
+
+await resetWallDrawClickHarness(page, false);
+const references = await page.evaluate(async () => {
+ const card = window.__card;
+ card._serverCfg.markers = [
+ { id: 'direct', binding: 'virtual', space: 'edited', room_id: 'base-0', future: { keep: 1 } },
+ { id: 'vacuum-cross-space', binding: 'virtual', space: 'other-1', vacuum: {
+ segment_map: { 1: 'base-0', 2: 'base-1' }, future: { keep: 2 },
+ } },
+ ];
+ const state = () => ({
+ room: card._curSpaceCfg.rooms.some((room) => room.id === 'base-0'),
+ direct: card._serverCfg.markers[0].room_id,
+ segments: { ...(card._serverCfg.markers[1].vacuum?.segment_map || {}) },
+ directFuture: card._serverCfg.markers[0].future.keep,
+ vacuumFuture: card._serverCfg.markers[1].vacuum.future.keep,
+ });
+ card._roomDeleteDialog = { roomId: 'base-0', name: 'base-0' };
+ card._confirmRoomDelete(false);
+ await card.updateComplete;
+ const deleted = state();
+ card._undoGeometry();
+ await card.updateComplete;
+ const undone = state();
+ card._redoGeometry();
+ await card.updateComplete;
+ const redone = state();
+ return { deleted, undone, redone };
+});
+
+const result = {
+ finishedChainMerged: chain.chainIds.length === 3 && chain.surviving.length === 1,
+ finishedChainOptimizeNoop: chain.optimizeChanged === false,
+ finishUsesOneBoundedCheck: chain.terminal.fullSpacePhysicalChecks === 0
+ && chain.terminal.localPhysicalChecks === 1,
+ finishAddsNoHistory: chain.terminal.history === 0,
+ finishedChainUndoOptimizeNoop: chainHistory.afterUndo.optimizeNoop,
+ finishedChainUndoHasOnePartition: chainHistory.afterUndo.partitions === 1,
+ finishedChainRedoOptimizeNoop: chainHistory.afterRedo.optimizeNoop,
+ finishedChainRedoHasOnePartition: chainHistory.afterRedo.partitions === 1,
+ deleteClearsExactReferences: references.deleted.room === false
+ && references.deleted.direct === undefined
+ && references.deleted.segments[1] === undefined
+ && references.deleted.segments[2] === 'base-1',
+ undoRestoresGeometryAndReferences: references.undone.room === true
+ && references.undone.direct === 'base-0'
+ && references.undone.segments[1] === 'base-0'
+ && references.undone.segments[2] === 'base-1',
+ redoReappliesGeometryAndReferences: references.redone.room === false
+ && references.redone.direct === undefined
+ && references.redone.segments[1] === undefined
+ && references.redone.segments[2] === 'base-1',
+ unrelatedMarkerFieldsSurvive: [references.deleted, references.undone, references.redone]
+ .every((state) => state.directFuture === 1 && state.vacuumFuture === 2),
+};
+
+checkAll(result);
+await finish(browser, result);
diff --git a/demo/wall-draw-click-harness.mjs b/demo/wall-draw-click-harness.mjs
index a6892442..49dceb0e 100644
--- a/demo/wall-draw-click-harness.mjs
+++ b/demo/wall-draw-click-harness.mjs
@@ -9,12 +9,19 @@ export async function installWallDrawClickHarness(page) {
junction: card._junctionLimitViolations.bind(card),
save: card._saveConfigDebounced,
genericCommit: card._editorRuntime._commitPhysicalGeometry.bind(card._editorRuntime),
+ finalize: card._editorRuntime._finalizeWallChainPartitions.bind(card._editorRuntime),
+ };
+ card._editorRuntime._finalizeWallChainPartitions = (...args) => {
+ if (window.__wallDrawMetrics) window.__wallDrawMetrics.wallFinishBarriers += 1;
+ return window.__wallDrawOriginals.finalize(...args);
};
card._editorRuntime._commitPhysicalGeometry = (name, before, ...rest) => {
const metrics = window.__wallDrawMetrics;
if (metrics && name === card._t('history.wall_segment')) {
- metrics.wallGenericFallbacks += 1;
- if (!metrics.fallbackSample) {
+ const finishCommit = rest[1] === false;
+ if (finishCommit) metrics.wallFinishCommits += 1;
+ else metrics.wallGenericFallbacks += 1;
+ if (!finishCommit && !metrics.fallbackSample) {
const space = card._serverCfg?.spaces?.find((item) => item.id === before?.spaceId);
const stable = (value) => JSON.stringify(value ?? null);
const arrays = [
@@ -88,6 +95,8 @@ export async function resetWallDrawClickHarness(page, remoteVariant = false) {
junctionPasses: 0, junctionArtifactPasses: 0,
configWrites: 0, localProofMaxObjects: 0,
wallGenericFallbacks: 0, fallbackSample: null,
+ wallFinishCommits: 0,
+ wallFinishBarriers: 0,
};
card.requestUpdate(); await card.updateComplete;
return {
@@ -150,3 +159,61 @@ export async function runWallDrawClickChain(page) {
};
}, WALL_DRAW_CLICK_POINTS);
}
+
+/** A separate completed straight chain: unlike terminal clicks, finish owns
+ * the bounded lossless merge/reconcile barrier introduced by #477. */
+export async function runWallDrawFinishProfile(page) {
+ return page.evaluate(async (normalizedPoints) => {
+ const card = window.__card;
+ const metrics = window.__wallDrawMetrics;
+ const stage = (card.shadowRoot || card.renderRoot).querySelector('.stage');
+ const eventAt = (normalized) => {
+ const point = normalized.map((value) => value * 1000);
+ const rect = stage.getBoundingClientRect();
+ const view = card._viewOr(card._baseVb());
+ return new MouseEvent('click', {
+ clientX: rect.left + ((point[0] - view.x) / view.w) * rect.width,
+ clientY: rect.top + ((point[1] - view.y) / view.h) * rect.height,
+ bubbles: true,
+ });
+ };
+ const snapshots = () => ({
+ fullSpacePhysicalChecks: metrics.fullSpacePhysicalChecks,
+ localPhysicalChecks: metrics.localPhysicalChecks,
+ junctionPasses: metrics.junctionPasses,
+ junctionArtifactPasses: metrics.junctionArtifactPasses,
+ configWrites: metrics.configWrites,
+ wallGenericFallbacks: metrics.wallGenericFallbacks,
+ wallFinishCommits: metrics.wallFinishCommits,
+ wallFinishBarriers: metrics.wallFinishBarriers,
+ history: card._geometryHistory.size,
+ });
+ const delta = (after, before) => Object.fromEntries(
+ Object.keys(after).map((key) => [key, after[key] - before[key]]),
+ );
+
+ for (const point of normalizedPoints) card._markupClick(eventAt(point));
+ const chainIds = [...card._activeWallChainPartitionIds];
+ const before = snapshots();
+ const started = performance.now();
+ card._activateMarkupTool('select');
+ const finishMs = performance.now() - started;
+ const terminal = delta(snapshots(), before);
+ card._previewAlignDialog(false);
+ const optimizeChanged = card._alignDialog?.changed;
+ card._alignDialog = null;
+ await card.updateComplete;
+ const surviving = (card._curSpaceCfg.partitions || []).filter(
+ (partition) => chainIds.includes(partition.id),
+ );
+ return {
+ finishMs, terminal, optimizeChanged,
+ chainIds, surviving,
+ terminalPartitionCount: card._curSpaceCfg.partitions?.length || 0,
+ activeCleared: !card._activeWallChainId
+ && card._activeWallChainPartitionIds.length === 0 && card._path.length === 0,
+ metrics: { ...metrics },
+ };
+ }, [[152, 200], [176, 200], [200, 200], [224, 200]]
+ .map(([x, y]) => [x / 240, y / 240]));
+}
diff --git a/dist/houseplan-assets.json b/dist/houseplan-assets.json
index 953d5957..706b37bf 100644
--- a/dist/houseplan-assets.json
+++ b/dist/houseplan-assets.json
@@ -1,232 +1,232 @@
{
"schema": 1,
- "fingerprint": "646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00",
+ "fingerprint": "5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f",
"entry": "houseplan-card.js",
"initialViewFiles": [
- "houseplan-assets/houseplan-card-B_QYG0Py.js",
+ "houseplan-assets/houseplan-card-6Hf8VPda.js",
"houseplan-card.js"
],
- "initialViewGzipBytes": 288573,
+ "initialViewGzipBytes": 288587,
"lazyFiles": [
- "houseplan-assets/backdrop-pick-D6LhKf2N.js",
- "houseplan-assets/de-BolUcHuX.js",
- "houseplan-assets/editor-DC4i4Aam.js",
- "houseplan-assets/fr-CyV9xY4W.js",
- "houseplan-assets/furniture-plan-art.generated-DPM3xdWV.js",
- "houseplan-assets/guard-DU4QQi6u.js",
- "houseplan-assets/houseplan-editor-runtime-DqX68E_8.js",
- "houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js",
- "houseplan-assets/hp-zigbee-topology-overlay-DVdGoL1j.js",
- "houseplan-assets/iso-scene-render-DczF6NiN.js",
- "houseplan-assets/live-interaction-runtime-Bn789cLD.js",
- "houseplan-assets/zigbee-topology-BnpLzLg7.js",
- "houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js"
+ "houseplan-assets/backdrop-pick-BsRoeWMx.js",
+ "houseplan-assets/de-CK49IrCl.js",
+ "houseplan-assets/editor-B6aLEVVy.js",
+ "houseplan-assets/fr-HLiHJMys.js",
+ "houseplan-assets/furniture-plan-art.generated-BITfBkG8.js",
+ "houseplan-assets/guard-loEtwhSf.js",
+ "houseplan-assets/houseplan-editor-runtime-D88CnwaV.js",
+ "houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js",
+ "houseplan-assets/hp-zigbee-topology-overlay-B947ne3H.js",
+ "houseplan-assets/iso-scene-render-C-qelLiZ.js",
+ "houseplan-assets/live-interaction-runtime-B4GlJv_x.js",
+ "houseplan-assets/zigbee-topology-C3YPlOFO.js",
+ "houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js"
],
- "lazyGzipBytes": 270606,
+ "lazyGzipBytes": 272667,
"lazyEditorFiles": [
- "houseplan-assets/backdrop-pick-D6LhKf2N.js",
- "houseplan-assets/editor-DC4i4Aam.js",
- "houseplan-assets/furniture-plan-art.generated-DPM3xdWV.js",
- "houseplan-assets/guard-DU4QQi6u.js",
- "houseplan-assets/houseplan-editor-runtime-DqX68E_8.js",
- "houseplan-assets/zigbee-topology-BnpLzLg7.js"
+ "houseplan-assets/backdrop-pick-BsRoeWMx.js",
+ "houseplan-assets/editor-B6aLEVVy.js",
+ "houseplan-assets/furniture-plan-art.generated-BITfBkG8.js",
+ "houseplan-assets/guard-loEtwhSf.js",
+ "houseplan-assets/houseplan-editor-runtime-D88CnwaV.js",
+ "houseplan-assets/zigbee-topology-C3YPlOFO.js"
],
- "lazyEditorGzipBytes": 193161,
+ "lazyEditorGzipBytes": 195229,
"lazyOnboardingFiles": [
- "houseplan-assets/backdrop-pick-D6LhKf2N.js",
- "houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js"
+ "houseplan-assets/backdrop-pick-BsRoeWMx.js",
+ "houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js"
],
- "lazyOnboardingGzipBytes": 14328,
+ "lazyOnboardingGzipBytes": 14325,
"lazyLocaleFiles": [
- "houseplan-assets/de-BolUcHuX.js",
- "houseplan-assets/fr-CyV9xY4W.js"
+ "houseplan-assets/de-CK49IrCl.js",
+ "houseplan-assets/fr-HLiHJMys.js"
],
- "lazyLocaleGzipBytes": 49760,
+ "lazyLocaleGzipBytes": 49757,
"lazyIsometricFiles": [
- "houseplan-assets/guard-DU4QQi6u.js",
- "houseplan-assets/iso-scene-render-DczF6NiN.js"
+ "houseplan-assets/guard-loEtwhSf.js",
+ "houseplan-assets/iso-scene-render-C-qelLiZ.js"
],
- "lazyIsometricGzipBytes": 13459,
+ "lazyIsometricGzipBytes": 13457,
"lazyFurnitureArtFiles": [
- "houseplan-assets/furniture-plan-art.generated-DPM3xdWV.js"
+ "houseplan-assets/furniture-plan-art.generated-BITfBkG8.js"
],
- "lazyFurnitureArtGzipBytes": 10253,
+ "lazyFurnitureArtGzipBytes": 10254,
"files": [
{
- "path": "houseplan-assets/backdrop-pick-D6LhKf2N.js",
- "sha256": "e164e525884bfa62ae90ed5b1a944d359c41a6bc9734e1afff07790fcf23aa27",
+ "path": "houseplan-assets/backdrop-pick-BsRoeWMx.js",
+ "sha256": "db0666adc29fd1b0a633b8d400b1d77f0ac5a0a2d18916f55877395bf5321786",
"rawBytes": 21592,
"gzipBytes": 7358,
"isEntry": false,
"imports": [
- "houseplan-assets/houseplan-card-B_QYG0Py.js"
+ "houseplan-assets/houseplan-card-6Hf8VPda.js"
],
"dynamicImports": []
},
{
- "path": "houseplan-assets/de-BolUcHuX.js",
- "sha256": "06484d80baa36816150b95cf26964d7a73c43534204f57267fe21e4dcd13964a",
+ "path": "houseplan-assets/de-CK49IrCl.js",
+ "sha256": "c158129bf778b06a67ec712f3b83ad0c5f8eda91ca7d8604a833e08b87b2f41a",
"rawBytes": 83541,
- "gzipBytes": 25129,
+ "gzipBytes": 25128,
"isEntry": false,
"imports": [],
"dynamicImports": []
},
{
- "path": "houseplan-assets/editor-DC4i4Aam.js",
- "sha256": "37892b28acd7508c762c898cbb0f92d7b926f1b0aa31935431e61500dd5f5a57",
+ "path": "houseplan-assets/editor-B6aLEVVy.js",
+ "sha256": "e212d1f48224c6c210708c00278036c9ef79b435aeca29f7237255281ae17e0f",
"rawBytes": 3837,
"gzipBytes": 1588,
"isEntry": false,
"imports": [
- "houseplan-assets/houseplan-card-B_QYG0Py.js"
+ "houseplan-assets/houseplan-card-6Hf8VPda.js"
],
"dynamicImports": []
},
{
- "path": "houseplan-assets/fr-CyV9xY4W.js",
- "sha256": "0c7b378ce233e3e6a1d5e4c48c21a955305613ceed5f6f00a83e6761383aae3c",
+ "path": "houseplan-assets/fr-HLiHJMys.js",
+ "sha256": "6b0c6767d9dacced69d67369d1cbce10c06c55720ffb5fa0af4be0559546e183",
"rawBytes": 85540,
- "gzipBytes": 24631,
+ "gzipBytes": 24629,
"isEntry": false,
"imports": [],
"dynamicImports": []
},
{
- "path": "houseplan-assets/furniture-plan-art.generated-DPM3xdWV.js",
- "sha256": "d4b70f684b4820e261fe9aa06fa47de277c475d78740334bce686d9e24b4e93d",
+ "path": "houseplan-assets/furniture-plan-art.generated-BITfBkG8.js",
+ "sha256": "9eb0bcf4ca44eb4520b2690a02fe4aed33039fd348bfe6cd946d6418a320329c",
"rawBytes": 33655,
- "gzipBytes": 10253,
+ "gzipBytes": 10254,
"isEntry": false,
"imports": [],
"dynamicImports": []
},
{
- "path": "houseplan-assets/guard-DU4QQi6u.js",
- "sha256": "e8fe75271f7bc89eac6bd5650b3c7af013ceef14ea513b83162e4950997c1b59",
+ "path": "houseplan-assets/guard-loEtwhSf.js",
+ "sha256": "81f6584a86659bd65a49f93fb307278e2a7f85f4e2b1029c48664f8254072e24",
"rawBytes": 518,
- "gzipBytes": 371,
+ "gzipBytes": 370,
"isEntry": false,
"imports": [
- "houseplan-assets/houseplan-card-B_QYG0Py.js"
+ "houseplan-assets/houseplan-card-6Hf8VPda.js"
],
"dynamicImports": []
},
{
- "path": "houseplan-assets/houseplan-card-B_QYG0Py.js",
- "sha256": "3c346bdeb12782170d057dbe671bee8f9389d537f89cb502b0760911669980fb",
- "rawBytes": 1037058,
- "gzipBytes": 287775,
+ "path": "houseplan-assets/houseplan-card-6Hf8VPda.js",
+ "sha256": "e88a9712a1adf1b26a380770ee0c1e1e27fd3edc32ffaf3340bf66de591c88a4",
+ "rawBytes": 1037072,
+ "gzipBytes": 287791,
"isEntry": false,
"imports": [],
"dynamicImports": [
- "houseplan-assets/de-BolUcHuX.js",
- "houseplan-assets/editor-DC4i4Aam.js",
- "houseplan-assets/fr-CyV9xY4W.js",
- "houseplan-assets/furniture-plan-art.generated-DPM3xdWV.js",
- "houseplan-assets/houseplan-editor-runtime-DqX68E_8.js",
- "houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js",
- "houseplan-assets/hp-zigbee-topology-overlay-DVdGoL1j.js",
- "houseplan-assets/iso-scene-render-DczF6NiN.js",
- "houseplan-assets/live-interaction-runtime-Bn789cLD.js"
+ "houseplan-assets/de-CK49IrCl.js",
+ "houseplan-assets/editor-B6aLEVVy.js",
+ "houseplan-assets/fr-HLiHJMys.js",
+ "houseplan-assets/furniture-plan-art.generated-BITfBkG8.js",
+ "houseplan-assets/houseplan-editor-runtime-D88CnwaV.js",
+ "houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js",
+ "houseplan-assets/hp-zigbee-topology-overlay-B947ne3H.js",
+ "houseplan-assets/iso-scene-render-C-qelLiZ.js",
+ "houseplan-assets/live-interaction-runtime-B4GlJv_x.js"
]
},
{
- "path": "houseplan-assets/houseplan-editor-runtime-DqX68E_8.js",
- "sha256": "a7abbe810557d33a4b71d33c428b57e46ee306768b275b5d525bb652156eb936",
- "rawBytes": 624431,
- "gzipBytes": 166163,
+ "path": "houseplan-assets/houseplan-editor-runtime-D88CnwaV.js",
+ "sha256": "129e119dbe29339c85f865f9d3d07c5aa644fe0844c31471dd14a8de2d9979de",
+ "rawBytes": 631884,
+ "gzipBytes": 168230,
"isEntry": false,
"imports": [
- "houseplan-assets/backdrop-pick-D6LhKf2N.js",
- "houseplan-assets/furniture-plan-art.generated-DPM3xdWV.js",
- "houseplan-assets/guard-DU4QQi6u.js",
- "houseplan-assets/houseplan-card-B_QYG0Py.js",
- "houseplan-assets/zigbee-topology-BnpLzLg7.js"
+ "houseplan-assets/backdrop-pick-BsRoeWMx.js",
+ "houseplan-assets/furniture-plan-art.generated-BITfBkG8.js",
+ "houseplan-assets/guard-loEtwhSf.js",
+ "houseplan-assets/houseplan-card-6Hf8VPda.js",
+ "houseplan-assets/zigbee-topology-C3YPlOFO.js"
],
"dynamicImports": [
- "houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js"
+ "houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js"
]
},
{
- "path": "houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js",
- "sha256": "e87e2fd96e1182695603cb6ad8e5a74997db9b7a1cfa26cee69c6ab110601f51",
+ "path": "houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js",
+ "sha256": "b31c2c3b0f4339b3b5b3f99bec4e7baf23970b9dfde272552ea644e0aebb108f",
"rawBytes": 28071,
- "gzipBytes": 6970,
+ "gzipBytes": 6967,
"isEntry": false,
"imports": [
- "houseplan-assets/backdrop-pick-D6LhKf2N.js",
- "houseplan-assets/houseplan-card-B_QYG0Py.js"
+ "houseplan-assets/backdrop-pick-BsRoeWMx.js",
+ "houseplan-assets/houseplan-card-6Hf8VPda.js"
],
"dynamicImports": []
},
{
- "path": "houseplan-assets/hp-zigbee-topology-overlay-DVdGoL1j.js",
- "sha256": "e1146c384c2481dcd855192c1fd4ed149b217ea109233e6baca117cd072a418e",
+ "path": "houseplan-assets/hp-zigbee-topology-overlay-B947ne3H.js",
+ "sha256": "7eb8abce7234d875879c5278f37e4301538493166c8d61901a00b49cf2b5e408",
"rawBytes": 11034,
"gzipBytes": 3733,
"isEntry": false,
"imports": [
- "houseplan-assets/houseplan-card-B_QYG0Py.js",
- "houseplan-assets/zigbee-topology-BnpLzLg7.js",
- "houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js"
+ "houseplan-assets/houseplan-card-6Hf8VPda.js",
+ "houseplan-assets/zigbee-topology-C3YPlOFO.js",
+ "houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js"
],
"dynamicImports": []
},
{
- "path": "houseplan-assets/iso-scene-render-DczF6NiN.js",
- "sha256": "4fdc508e34c4fd9faac86fede3072beaaecf13564f07a30f278accdbb7d6b9fc",
+ "path": "houseplan-assets/iso-scene-render-C-qelLiZ.js",
+ "sha256": "08f55bbd3d072732295ffc44481183510b8453b23989db5db63321a06b1a4e48",
"rawBytes": 38562,
- "gzipBytes": 13088,
+ "gzipBytes": 13087,
"isEntry": false,
"imports": [
- "houseplan-assets/guard-DU4QQi6u.js",
- "houseplan-assets/houseplan-card-B_QYG0Py.js"
+ "houseplan-assets/guard-loEtwhSf.js",
+ "houseplan-assets/houseplan-card-6Hf8VPda.js"
],
"dynamicImports": []
},
{
- "path": "houseplan-assets/live-interaction-runtime-Bn789cLD.js",
- "sha256": "57f2f09b46377f3697d126a6eb2a318ed8a230e84223182f7f18559add3730c8",
+ "path": "houseplan-assets/live-interaction-runtime-B4GlJv_x.js",
+ "sha256": "2da392adb2a7ff906c8dea15d69fae7f49a374abdc0af786aac8210d535164b7",
"rawBytes": 5196,
- "gzipBytes": 2129,
+ "gzipBytes": 2128,
"isEntry": false,
"imports": [
- "houseplan-assets/houseplan-card-B_QYG0Py.js"
+ "houseplan-assets/houseplan-card-6Hf8VPda.js"
],
"dynamicImports": []
},
{
- "path": "houseplan-assets/zigbee-topology-BnpLzLg7.js",
- "sha256": "871f706f545fba4a31208097a9b26605615a9f185eb27c1baa06b38b797446de",
+ "path": "houseplan-assets/zigbee-topology-C3YPlOFO.js",
+ "sha256": "79a28a1224372b312984fcc3b9d4583dc75a2c2c8893b80573b4305cd82abc8e",
"rawBytes": 18961,
- "gzipBytes": 7428,
+ "gzipBytes": 7429,
"isEntry": false,
"imports": [
- "houseplan-assets/houseplan-card-B_QYG0Py.js"
+ "houseplan-assets/houseplan-card-6Hf8VPda.js"
],
"dynamicImports": []
},
{
- "path": "houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js",
- "sha256": "03ad74129781c6009c82696618a2e0f77a577e793a83932b098a6ddade7b35f6",
+ "path": "houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js",
+ "sha256": "7c39b1f4733576a20e9ac5dbfe4f951814bba902da879bfcd9229f41e84f4f12",
"rawBytes": 3941,
- "gzipBytes": 1765,
+ "gzipBytes": 1766,
"isEntry": false,
"imports": [
- "houseplan-assets/houseplan-card-B_QYG0Py.js",
- "houseplan-assets/zigbee-topology-BnpLzLg7.js"
+ "houseplan-assets/houseplan-card-6Hf8VPda.js",
+ "houseplan-assets/zigbee-topology-C3YPlOFO.js"
],
"dynamicImports": []
},
{
"path": "houseplan-card.js",
- "sha256": "e53e42ad8703704c7bd3a16f88f791baf2615be5c53825abdf718dbca1866c11",
+ "sha256": "af3f3f8e2bac0be17fcae57b873c0849f7d2fc91df234fae702e347c9addde3e",
"rawBytes": 1183,
- "gzipBytes": 798,
+ "gzipBytes": 796,
"isEntry": true,
"imports": [
- "houseplan-assets/houseplan-card-B_QYG0Py.js"
+ "houseplan-assets/houseplan-card-6Hf8VPda.js"
],
"dynamicImports": []
}
diff --git a/dist/houseplan-assets/backdrop-pick-D6LhKf2N.js b/dist/houseplan-assets/backdrop-pick-BsRoeWMx.js
similarity index 94%
rename from dist/houseplan-assets/backdrop-pick-D6LhKf2N.js
rename to dist/houseplan-assets/backdrop-pick-BsRoeWMx.js
index 51f335ec..4ec2656b 100644
--- a/dist/houseplan-assets/backdrop-pick-D6LhKf2N.js
+++ b/dist/houseplan-assets/backdrop-pick-BsRoeWMx.js
@@ -1,6 +1,6 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{D as e,b as t,A as i,q as o,t as n,dr as r}from"./houseplan-card-B_QYG0Py.js";function s(e){const t=e.visualViewport;return t&&Number.isFinite(t.width)&&Number.isFinite(t.height)?{left:Number(t.offsetLeft)||0,top:Number(t.offsetTop)||0,width:Math.max(0,Number(t.width)||0),height:Math.max(0,Number(t.height)||0)}:{left:0,top:0,width:e.innerWidth,height:e.innerHeight}}function a(e,t,i,o=7,n=8){const r=i.left+n,s=i.top+n,a=Math.max(r,i.left+i.width-n),l=Math.max(s,i.top+i.height-n),h=Math.max(0,a-r),c=Math.max(0,l-s),d=Math.min(Math.max(0,t.width),h),u=Math.min(Math.max(0,t.height),c);let p=e.left;p+d>a&&(p=e.right-d),p=Math.min(Math.max(r,p),Math.max(r,a-d));const g=e.bottom+o,_=e.top-o-u;let m="bottom",f=g;return g+u>l&&_>=s?(m="top",f=Math.min(Math.max(s,_),Math.max(s,l-u))):f=Math.min(Math.max(s,g),Math.max(s,l-u)),{left:Math.round(p),top:Math.round(f),side:m,maxWidth:Math.round(h),maxHeight:Math.round(c)}}class l{constructor(e,t,i){this.owner=e,this.name=t,this.keydown=i,this.host=null,this.root=null}window(){return this.owner.ownerDocument.defaultView}dialog(){return this.owner.closest("hp-dialog")}usesPopover(e=!1){const t=this.window();return!e&&!!t&&function(e){const t=e.HTMLElement?.prototype;return"function"==typeof t?.showPopover&&"function"==typeof t?.hidePopover}(t)}get hasFallback(){return!!this.host}containsPath(e){return e.includes(this.owner)||!!this.host&&e.includes(this.host)}ownsActiveElement(){let e=this.owner.ownerDocument.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return!(!e||e!==this.owner&&!this.owner.shadowRoot?.contains(e)&&!this.root?.contains(e))}renderFallback(i,o){const n=this.ensureFallback();return n?(e(t`${i}`,n),n):null}surface(e,t){return t?this.owner.shadowRoot?.querySelector(e)||null:this.root?.querySelector(e)||null}destroy(){this.root&&e(i,this.root),this.host?.remove(),this.host=null,this.root=null}ensureFallback(){if(this.root?.isConnected)return this.root;const e=this.dialog()?.overlayPortal()||this.owner.ownerDocument.body;if(!e)return null;const t=this.owner.ownerDocument.createElement("div");return t.dataset.hpOverlay=this.name,t.style.display="contents",this.keydown&&t.addEventListener("keydown",this.keydown,!0),e.append(t),this.host=t,this.root=t.attachShadow({mode:"open"}),this.root}}let h=0;class c extends n{constructor(){super(...arguments),this.text="",this.ariaLabel="",this.pointerHover=!1,this._open=!1,this._openTimer=0,this._closeTimer=0,this._positionRaf=0,this._forceFallback=!1,this._hoverOwned=!1,this._overlayDispose=null,this._scrollDialog=null,this._descriptionId="hp-help-description-"+ ++h,this._surfacePointerEnter=()=>{const e=this._window();this._closeTimer&&e?.clearTimeout(this._closeTimer),this._closeTimer=0},this._surfacePointerLeave=()=>{this._scheduleClose()},this._outsidePointerDown=e=>{if(!this._open)return;const t=e.composedPath();this._floating.containsPath(t)||this._closeHelp(!1,"outside")},this._dialogScroll=e=>{const t=this._floating.containsPath(e.composedPath()),i=e.target,o=this._dialog(),n=i instanceof Node&&(i===o||i instanceof Element&&i.contains(this));var r;this._open&&(r=n,!t&&r)&&this._closeHelp(!1,"scroll")},this._keyDown=e=>{if(!this._open||e.defaultPrevented)return;if("Escape"===e.key)return e.preventDefault(),e.stopImmediatePropagation(),void this._closeHelp(this._floating.ownsActiveElement(),"escape");const t=this.renderRoot.querySelector(".trigger");if(!t||!e.composedPath().includes(t))return;const i=this._surface();if(!i||i.scrollHeight<=i.clientHeight)return;const o=Math.max(40,.8*i.clientHeight),n={ArrowDown:40,ArrowUp:-40,PageDown:o,PageUp:-o};if("Home"===e.key)i.scrollTop=0;else if("End"===e.key)i.scrollTop=i.scrollHeight;else{if(!(e.key in n))return;i.scrollBy({top:n[e.key],behavior:"auto"})}e.preventDefault(),e.stopImmediatePropagation()},this._floating=new l(this,"help",this._keyDown),this._queuePosition=()=>{if(!this._open||this._positionRaf)return;const e=this._window();e&&(this._positionRaf=e.requestAnimationFrame(()=>{this._positionRaf=0,this._position()||this._closeHelp()}))}}connectedCallback(){super.connectedCallback(),this.addEventListener("keydown",this._keyDown,!0)}willUpdate(){this.toggleAttribute("data-has-content",this._hasContent())}disconnectedCallback(){const e=this.ownerDocument.defaultView;this._unsubscribeOpenListeners(),this.removeEventListener("keydown",this._keyDown,!0),this._clearTimers(),this._positionRaf&&e?.cancelAnimationFrame(this._positionRaf),this._positionRaf=0,this._closeHelp(!1,"disconnect"),super.disconnectedCallback()}updated(e){if(e.has("pointerHover")&&!this.pointerHover){const e=this._window();this._openTimer&&e?.clearTimeout(this._openTimer),this._openTimer=0,this._hoverOwned&&this._closeHelp(!1,"outside")}this._hasContent()||!this._open?this._open&&e.has("text")&&(this._usesPopover()||this._renderFallback(),this._queuePosition()):this._closeHelp()}_window(){return this._floating.window()}_dialog(){return this._floating.dialog()}_usesPopover(){return this._floating.usesPopover(this._forceFallback)}_hasContent(){return e=this.text,t=this.ariaLabel,"string"==typeof e&&e.trim().length>0&&"string"==typeof t&&t.trim().length>0;var e,t}_clearTimers(){const e=this._window();this._openTimer&&e?.clearTimeout(this._openTimer),this._closeTimer&&e?.clearTimeout(this._closeTimer),this._openTimer=0,this._closeTimer=0}_scheduleOpen(){const e=this._window();this.pointerHover&&e&&!this._open&&!this._openTimer&&(this._closeTimer&&e.clearTimeout(this._closeTimer),this._closeTimer=0,this._openTimer=e.setTimeout(()=>{this._openTimer=0,this.isConnected&&(this._hoverOwned=!0,this._openHelp())},300))}_scheduleClose(){const e=this._window(),t=this.renderRoot.querySelector(".trigger");e&&!t?.matches(":focus-visible")&&(this._openTimer&&e.clearTimeout(this._openTimer),this._closeTimer&&e.clearTimeout(this._closeTimer),this._openTimer=0,this._closeTimer=e.setTimeout(()=>{this._closeTimer=0,this.isConnected&&this._closeHelp()},150))}_triggerPointerEnter(e){this.pointerHover&&"mouse"===e.pointerType&&this._scheduleOpen()}_triggerPointerLeave(e){"mouse"===e.pointerType&&this._scheduleClose()}_triggerFocus(){queueMicrotask(()=>{const e=this.renderRoot.querySelector(".trigger");e?.matches(":focus-visible")&&(this._hoverOwned=!1,this._openHelp())})}_triggerBlur(){this._scheduleClose()}_triggerClick(){this._open?this._closeHelp():(this._hoverOwned=!1,this._openHelp())}_subscribeOpenListeners(){this.ownerDocument.addEventListener("pointerdown",this._outsidePointerDown,!0),this.ownerDocument.addEventListener("keydown",this._keyDown,!0);const e=this._window();e?.addEventListener("resize",this._queuePosition),e?.addEventListener("orientationchange",this._queuePosition),e?.visualViewport?.addEventListener("resize",this._queuePosition),e?.visualViewport?.addEventListener("scroll",this._queuePosition),this._scrollDialog=this._dialog(),this._scrollDialog?.addEventListener("scroll",this._dialogScroll,!0)}_unsubscribeOpenListeners(){this.ownerDocument.removeEventListener("pointerdown",this._outsidePointerDown,!0),this.ownerDocument.removeEventListener("keydown",this._keyDown,!0);const e=this._window();e?.removeEventListener("resize",this._queuePosition),e?.removeEventListener("orientationchange",this._queuePosition),e?.visualViewport?.removeEventListener("resize",this._queuePosition),e?.visualViewport?.removeEventListener("scroll",this._queuePosition),this._scrollDialog?.removeEventListener("scroll",this._dialogScroll,!0),this._scrollDialog=null}async _openHelp(){!this._open&&this._hasContent()&&(this._clearTimers(),this._forceFallback=!1,this._open=!0,this._subscribeOpenListeners(),await this.updateComplete,this._open&&(this._usesPopover()||this._renderFallback(),this._position()?this._overlayDispose=this._dialog()?.registerOverlay({owner:this,group:"transient",close:e=>this._closeHelp("escape"===e&&this._floating.ownsActiveElement(),e)})||null:this._closeHelp()))}_closeHelp(e=!1,t="exclusive"){if(!this._open&&!this._floating.hasFallback)return;this._clearTimers();const i=this._overlayDispose;this._overlayDispose=null,i?.();const o=this.renderRoot.querySelector(".tooltip");if(o?.hidePopover)try{o.matches(":popover-open")&&o.hidePopover()}catch{}this._open=!1,this._hoverOwned=!1,this._unsubscribeOpenListeners(),this._floating.destroy(),e&&this.updateComplete.then(()=>this.renderRoot.querySelector(".trigger")?.focus())}_tooltipTemplate(e){return t`
- `}export{l as F,d as a,m as b,B as c,f as d,H as e,s as f,p as g,u as i,a as p,S as r,_ as s,g as t};
+ `}export{l as F,c as a,m as b,B as c,f as d,H as e,s as f,p as g,u as i,a as p,S as r,_ as s,g as t};
diff --git a/custom_components/houseplan/frontend/houseplan-assets/de-BolUcHuX.js b/dist/houseplan-assets/de-CK49IrCl.js
similarity index 99%
rename from custom_components/houseplan/frontend/houseplan-assets/de-BolUcHuX.js
rename to dist/houseplan-assets/de-CK49IrCl.js
index fae5ecd3..97675407 100644
--- a/custom_components/houseplan/frontend/houseplan-assets/de-BolUcHuX.js
+++ b/dist/houseplan-assets/de-CK49IrCl.js
@@ -1 +1 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";var e={"editor.context_actions":"Aktionen: {object}","editor.tool_options":"Werkzeugoptionen: {tool}","editor.palette":"Palette: {tool}","editor.open_group":"Werkzeuggruppe: {group}","editor.group_active":"{group} — aktiv: {item}","editor.disabled_action":"{action} ist nicht verfügbar: {reason}","editor.loading":"Editor wird geladen…","editor.loading_aria":"Der Plan-Editor wird geladen","editor.load_failed":"Der Editor konnte nicht geladen werden.","editor.refresh_advice":"Seite aktualisieren und erneut versuchen.","editor.retry_advice":"Verbindung prüfen und erneut drücken.","version_mismatch.title":"Die House Plan-Versionen stimmen nicht überein","version_mismatch.body":"Falls Home Assistant noch neu startet, warten Sie den Abschluss ab und laden Sie dann diese Seite neu.","version_mismatch.frontend":"Karte","version_mismatch.backend":"Integration","version_mismatch.reload":"Seite neu laden","color_picker.title":"Farbwähler","color_picker.hue":"Farbton","color_picker.saturation":"Sättigung","color_picker.value":"Helligkeit","color_picker.hex":"Hex-Farbe","color_picker.invalid_hex":"Geben Sie eine 3- oder 6-stellige Hex-Farbe ein","color_picker.confirm":"OK","btn.properties":"Eigenschaften","btn.keep_as_walls":"Als Wände behalten","btn.delete_room_keep_walls":"Raum löschen, Wände behalten","btn.delete_room_with_walls":"Raum und Wände löschen","title.markup_select":"Wände und Säulen auswählen und bearbeiten","title.markup_column":"Säule: Klicken Sie auf einen Rasterpunkt, um eine quadratische Säule zu platzieren","markup.partition":"Trennwand","markup.column":"Säule","markup.hint_column":"Klicken Sie auf einen Rasterpunkt, um eine quadratische Säule zu platzieren","history.wall_segment":"Wandsegment hinzufügen","history.column_add":"Säule hinzufügen","history.physical_edit":"Physisches Objekt ändern","history.physical_delete":"Physisches Objekt löschen","history.physical_move":"Physisches Objekt verschieben","history.wall_face_batch":"Räume aus Wänden erstellen","toast.column_duplicate":"Eine Säule mit demselben Zentrum und äußerer Größe existiert bereits","physical.partition_properties":"Eigenschaften der Trennwand","physical.column_properties":"Eigenschaften der Säule","physical.shape":"Form","physical.square":"Quadrat","physical.circle":"Kreis","physical.diameter":"Durchmesser","physical.side":"Seite","physical.rotation":"Drehwinkel","physical.length":"Länge","physical.allowed_range":"Erlaubt: {min}–{max} {unit}","physical.column_size_title":"Außenmaß der per Klick platzierten quadratischen Säule (1–150 cm).","card.title":"Hausplan","count.devices":"{n} Entwicklung","empty.no_spaces":"Noch keine Bereiche.","empty.add_first":"Ersten Bereich hinzufügen und einen Grundriss hochladen.","empty.install":"Installieren Sie die House Plan-Integration und fügen Sie sie unter „Geräte & Dienste“ hinzu.","btn.add_space":"Bereich hinzufügen","btn.cancel":"Abbrechen","btn.save":"Speichern","btn.close":"Schließen","btn.delete":"Löschen","btn.copy":"Kopieren","btn.edit":"Bearbeiten","btn.open_in_ha":"In HA öffnen","btn.reset":"Zurücksetzen","btn.attach":"Anhängen…","btn.upload":"Hochladen…","btn.replace":"Ersetzen…","title.zoom_in":"Zoomen","title.zoom_out":"Herauszoomen","title.zoom_fit":"Alles anpassen","title.configure_space":"Bereich konfigurieren","title.add_space":"Bereich hinzufügen","title.markup_add":"Wände: eine durchgehende Kette zeichnen; jedes bestätigte Segment wird einzeln gespeichert. Umschalt sperrt auf 45°","title.markup_merge":"Zusammenführen: Klicken Sie auf einen Raum und dann auf den Nachbarraum, mit dem er eine Wand teilt","title.markup_split":"Raum teilen: Klicken Sie auf den Raum und dann auf zwei Punkte an seinen Wänden","title.markup_delroom":"Raum löschen: Klicken Sie in einen Raum und bestätigen Sie","title.need_plan":"Einen Grundriss hochladen","markup.add":"Wände","markup.merge":"Zusammenführen","markup.split":"Teilen","markup.resize":"Größe ändern","title.markup_resize":"Räume vergrößern/verkleinern: Ziehen Sie einen verfügbaren horizontalen oder vertikalen Wandgriff","markup.hint_resize":"Ziehen Sie einen verfügbaren Wandgriff · die Wand stoppt an der ersten unsicheren Position · Esc bricht ab · Strg+Z — rückgängig","resize.disabled.diagonal":"Diese Wand ist geneigt; Größe ändern unterstützt nur horizontale und vertikale Wände","resize.disabled.side-angle":"Eine angrenzende Wand ist geneigt; Größe ändern erfordert, dass beide angrenzenden Wände diese Wand im rechten Winkel treffen","resize.disabled.duplicate-physical-wall":"Eine separate Trennwand oder ein Pfeiler überlappt diese Wand; entfernen oder verschieben Sie sie, bevor Sie die Größe ändern","resize.disabled.partial-shared":"Ein angrenzender Raum nutzt nur einen Teil dieser Wand, daher kann sie nicht sicher als gemeinsame Wand verschoben werden","resize.disabled.unequal-shared":"Der angrenzende Raum nutzt andere Endpunkte oder Wandlängen, daher können die Wände nicht gemeinsam sicher bewegt werden","resize.disabled.multiple-rooms":"Das Verschieben dieser Wand würde mehr als zwei Räume betreffen","resize.disabled.thickness-conflict":"Die Wandstärke kann nicht sicher beibehalten werden","resize.disabled.opening-conflict":"Eine Öffnung an dieser Wand kann nicht sicher verschoben werden","resize.disabled.invalid-geometry":"Diese Wand kann nicht ohne Änderung der Planstruktur geändert werden","resize.limit_stopped":"Wand gestoppt: der nächste Schritt würde ein Anschlusslimit verletzen","resize.commit_failed":"Größenänderung wurde abgebrochen, da der endgültige Plan die Geometrieprüfung nicht bestanden hat","resize.preview_failed":"Größenänderung am letzten sicheren Punkt gestoppt, da die Plan-Geometrie nicht beibehalten werden konnte","markup.opening":"Öffnung","markup.delete_room":"Raum löschen","history.undo":"Rückgängig","history.redo":"Wiederholen","history.undo_named":"Rückgängig: {name} (Strg+Z)","history.redo_named":"Wiederholen: {name} (Strg+Shift+Z / Strg+Y)","history.undo_empty":"Nichts zu widerrufen","history.redo_empty":"Nichts zu wiederholen","history.undone":"Rückgängig gemacht: {name}","history.redone":"Wiederholt: {name}","history.add_room":"Raum erstellen","history.split_room":"Raum teilen","history.merge_rooms":"Räume zusammenführen","history.resize_room":"Raumgröße ändern","history.wall_thickness":"Wandstärke ändern","history.add_opening":"Tür- oder Fensteröffnung hinzufügen","history.edit_opening":"Öffnung bearbeiten","history.move_opening":"Öffnung verschieben","history.delete_opening":"Öffnung löschen","history.delete_room_keep_walls":"Raum löschen, Wände behalten","history.delete_room_with_walls":"Raum und Wände löschen","history.decor_add":"Dekorobjekt hinzufügen","history.decor_edit":"Dekorobjekt bearbeiten","history.decor_move":"Dekorobjekt verschieben","history.decor_transform":"Dekorobjekt transformieren","history.decor_delete":"Dekorobjekt löschen","history.backdrop_transform":"Plan-Hintergrund transformieren","history.device_move":"{name} verschieben","history.device_stale":"Der Positionsverlauf ist nicht mehr anwendbar und wurde gelöscht","opening.new":"Neue Öffnung","opening.edit":"Öffnung","opening.door":"Tür","opening.window":"Fenster","opening.gate":"Tor","opening.passage":"Offener Durchgang","opening.passage_binding_warning":"Das Speichern entfernt den Öffnungs-/Schließsensor und das Schloss.","opening.invalid_passage_fields":"Der offene Durchgang auf dem Plan „{room}“ hat nicht unterstützte Einstellungen: {fields}.","opening.type_label":"Typ","opening.length_label":"Länge, cm","opening.contact_label":"Öffnungs-/Schließsensor","opening.lock_label":"Schloss","opening.none":"— keine —","opening.search_ph":"Suche: Name oder Entitäts-ID…","opening.invert":"Geöffnet/geschlossen invertieren","opening.flip_h":"Scharnier an der anderen Zarge","opening.flip_v":"Öffnet zur anderen Seite","opening.open":"Offen","opening.closed":"Geschlossen","opening.locked":"Verriegelt","opening.unlocked":"Entriegelt","opening.state_unknown":"nicht verfügbar","opening.no_entities":"Keine Sensoren gebunden — ein statisches Symbol auf dem Plan.","toast.opening_no_wall":"Neben eine Raumwand oder eine unabhängige Wand klicken","opening.host_partition":"Unabhängige Wand","opening.partition_orphan":"Die unabhängige Wand für diese Öffnung existiert nicht mehr","opening.partition_jamb_margin":"Mindestens {distance} zwischen der Öffnung und dem Wandende lassen","opening.rebind_partition":"An eine andere unabhängige Wand anfügen","confirm.delete_partition_openings_title":"Wand und Öffnungen löschen?","confirm.delete_partition_openings_body":"Diese Wand enthält {count} Öffnung(en). Sie werden zusammen gelöscht.","confirm.delete_partition_openings_item":"• {type}, {length}","markup.hint_points":"Punkte: {n} · Shift — 45° Schritte · Esc — Kette beenden · Ctrl+Z — Punkt rückgängig machen · Schließen eines Bereichs erstellt einen Raum","markup.hint_start":"Klicken Sie auf einen Rasterpunkt, um eine Wandkette zu starten","tip.lqi":"durchschnittliches Zigbee-Signal:","tip.area":"Bereich: {value}","info.device_header":"Gerät im Plan","info.model":"Modell","info.state":"Status","info.link":"Verbindung","info.manuals":"Handbücher","info.none":"Keine zusätzlichen Informationen","marker.new_device":"Neues Gerät","marker.name_label":"Name (im Plan angezeigt)","marker.name_ph":"Name","marker.binding_label":"An ein HA-Gerät binden","marker.binding_disabled":"in Home Assistant deaktiviert","marker.virtual_option":"Virtuelles Gerät (keine Bindung)","marker.search_ph":"Gerät/Gruppe suchen…","marker.nothing_found":"Nichts gefunden","marker.room_label":"Raum","marker.room_override":" (Platzierung überschreiben)","marker.room_choose":"— Raum auswählen —","marker.room_auto":"— nach Gerätebereich (auto) —","marker.icon_label":"Symbol","marker.icon_ph":"mdi:… (leer = automatisch)","marker.display_label":"Anzeige","display.badge":"Symbol + Zustand","display.icon_ripple":"Symbol + Zustand und Aktivität","display.static_icon":"Immer statisches Symbol","marker.display_hint_badge":"Das Symbol und die dynamische Platte zeigen den Gerätezustand ohne den üblichen Aktivitätspuls. Rote Alarme bleiben sichtbar.","marker.display_hint_icon_ripple":"Das Symbol, die dynamische Platte und der Puls zeigen einen kurzen Puls für Ereignisse und einen kontinuierlichen Puls für Arbeit, Bewegung oder Anwesenheit. Rote Alarme haben eine separate Priorität.","marker.display_hint_value":"Ein ausgewählter oder automatisch ermittelter Home Assistant-Wert ersetzt das Symbol, während die Platte weiterhin den Zustand anzeigt. Rote Alarme bleiben sichtbar.","marker.display_hint_static_icon":"Die themenabhängige Hülle und das Symbol bleiben immer gleich. Zustand, Aktivität, Nichtverfügbarkeit und Alarme verändern nicht das Erscheinungsbild.","marker.static_alarm_warning":"Dieses Gerät kann Alarme melden. Die statische Anzeige verbirgt die visuelle Alarmanzeige des Markers.","marker.preview.title":"Anzeigevorschau","marker.preview.actual":"Jetzt","marker.preview.example":"Beispiel","marker.preview.integration":"Bereitgestellt von","marker.preview.source":"Anzeigquelle","marker.preview.current_state":"Aktueller Zustand","marker.preview.result":"Auf dem Plan","marker.preview.details":"Quelldetails","marker.preview.select_source":"Ein Home-Assistant-Gerät oder eine Entität auswählen, um die tatsächliche Anzeige zu sehen.","marker.preview.unknown_provider":"Unbekannte Integration","marker.preview.virtual_provider":"House Plan · virtuelles Gerät","marker.preview.no_source":"Keine aktive Quelle","marker.preview.no_state":"Kein aktueller Zustand","marker.preview.mixed_states":"Mehrere verschiedene Zustände","marker.preview.multiple_sources":"{n}-Quellen","marker.preview.more_sources":"+{n} mehr","marker.preview.scaled":"Die Vorschau wird auf {n}% skaliert, um zu passen. Die gespeicherte Größe bleibt unverändert.","marker.preview.demo_short":"Kurze Aktivität anzeigen","marker.preview.demo_continuous":"Kontinuierliche Aktivität anzeigen","marker.preview.stop_continuous":"Kontinuierliche Aktivität stoppen","marker.preview.demo_short_notice":"Kurzes Aktivitätsbeispiel; der tatsächliche Gerätezustand bleibt unverändert.","marker.preview.demo_continuous_notice":"Kontinuierliches Aktivitätsbeispiel; der tatsächliche Gerätezustand bleibt unverändert.","marker.preview.demo_already_visible":"Der aktuelle Zustand zeigt bereits eine echte Aktivitäts- oder Alarmeffekt.","marker.preview.reduced_motion":"Systemweit reduzierte Bewegungen sind aktiviert, daher wird gewöhnliche Aktivität als Punkt angezeigt.","marker.preview.reason.neutral":"Neutrale dunkle Platte","marker.preview.reason.working":"Gelbe Platte: Das Gerät arbeitet jetzt","marker.preview.reason.working_activity":"Gelbe Platte und Aktivitätseffekt: das Gerät funktioniert jetzt","marker.preview.reason.open":"Orange Platte: physisch geöffnet oder entriegelt","marker.preview.reason.cover_icon_state":"Neutrale Platte; die Abdeckungseinheit steuert den angezeigten Zustand und das Symbol","marker.preview.reason.presence":"Aktivitätseffekt, während Präsenz erkannt wird","marker.preview.reason.event":"Kurzer Aktivitätseffekt nach einem erkannten Ereignis","marker.preview.reason.transition":"Aktivitätseffekt, während das Gerät sich bewegt oder den Zustand ändert","marker.preview.reason.media_neutral":"Mediengeräte bleiben im verfügbaren Zustand auf einer neutralen dunklen Platte","marker.preview.reason.unavailable":"Gedämpfte neutrale Platte: nicht verfügbar oder ausgeschaltet","marker.preview.reason.alarm":"Rote Alarmplatte; Alarmanzeige wird immer angezeigt","marker.preview.reason.live_states_disabled":"Live-Zustandsstil ist für diese Karte deaktiviert","marker.preview.reason.value_no_state":"Kein nutzbarer Zustandswert; stattdessen wird das Symbol angezeigt","marker.preview.reason.value_ambiguous_sources":"Mehrere mögliche Wertequellen; stattdessen wird das Symbol angezeigt","marker.preview.reason.value_non_scalar":"Die Quelle lieferte keinen einfachen Wert; stattdessen wird das Symbol angezeigt","marker.preview.reason.value_virtual":"Ein virtuelles Gerät hat keinen Home Assistant-Wert; stattdessen wird das Symbol angezeigt","marker.preview.reason.vacuum_live_plan_only":"Echtzeitposition und -spur des Staubsaugers sind nur im vollständigen Plan verfügbar","marker.preview.reason.hidden_design_preview":"Das Gerät ist im Plan ausgeblendet; diese Designvorschau bleibt sichtbar","marker.preview.reason.composite_power_source":"Der Status stammt vom Power-Entity des Geräts; Hilfsschalter werden ignoriert","marker.preview.reason.activity_display_disabled":"Der gewählte Anzeigemodus zeigt gewöhnliche Aktivitätseffekte nicht an","marker.preview.reason.ha_disabled":"Die Home Assistant-Verbindung ist deaktiviert und wird im Plan ausgeblendet","marker.preview.reason.orphaned":"Die gespeicherte Home Assistant-Verbindung konnte nicht mehr gefunden werden","marker.preview.reason.static_icon":"Statischer Modus: Der Gerätestatus ändert das Symbol nicht","marker.activity_color":"Aktivitätspulsfarbe","marker.ripple_size":"Aktivitätspulsgröße","marker.activity_alarm_note":"Farbe und Größe betreffen nur gewöhnliche Aktivität und ändern keine roten Alarme.","marker.pulse_a11y_alarm":"Alarm","marker.pulse_a11y_event":"Kürzliches Ereignis","marker.pulse_a11y_presence":"Anwesenheit erkannt","marker.pulse_a11y_transition":"Statusänderung","marker.pulse_a11y_running":"Arbeitet","marker.state_a11y_neutral":"Standardzustand","marker.state_a11y_working":"Funktionierend","marker.state_a11y_open":"Offen","marker.state_a11y_locked":"Verschlossen","marker.state_a11y_unlocked":"Entriegelt","marker.state_a11y_alarm":"Alarm","marker.state_a11y_unavailable":"Nicht verfügbar","marker.lqi_a11y_low":"LQI {value}, schwaches Signal","marker.lqi_a11y_mid":"LQI {value}, mittleres Signal","marker.lqi_a11y_high":"LQI {value}, starkes Signal","marker.size_label":"Symbolgröße / Drehung","marker.angle_label":"Drehen","marker.model_label":"Modell","marker.model_ph":"z.B. Aqara T&H","marker.link_label":"Link","marker.desc_label":"Beschreibung","marker.desc_ph":"Notizen, Spezifikationen…","marker.manuals_label":"Handbücher (PDF usw.)","marker.sub_device":"Gerät","marker.sub_z2m_group":"· Z2M Gruppe","marker.sub_group":"Gruppe","marker.sub_helper":"Helfer","space.new":"Neuer Bereich","space.copy_title":"Bereich kopieren","space.copy_name":"Name des neuen Bereichs","space.copy_fallback":"Bereich","space.copy_create":"Kopie erstellen","space.copy_optimize_title":"Vor dem Kopieren optimieren?","space.copy_optimize_body":"Vor dem Erstellen von „{name}“ muss House Plan den gesamten Plan einschließlich anderer Bereiche optimieren. Fortfahren?","space.copy_optimize_confirm":"Optimieren und kopieren","space.copy_error_changed":"Der Plan wurde während der Bestätigung geändert. Bitte prüfen und erneut versuchen.","space.copy_error_source_missing":"Der Quellbereich existiert nicht mehr. Öffnen Sie seine Einstellungen erneut.","space.copy_error_source_invalid":"House Plan konnte nicht alle Wände dieses Bereichs prüfen. Korrigieren Sie den Quellbereich.","space.copy_error_spaces_limit":"House Plan enthält bereits die maximale Anzahl an Bereichen.","space.copy_error_partitions_limit":"Dieser Bereich enthält zu viele Wände zum Kopieren.","space.copy_error_openings_limit":"Dieser Bereich enthält zu viele Öffnungen zum Kopieren.","space.copy_error_decor_limit":"Dieser Bereich enthält zu viele Hintergrundobjekte zum Kopieren.","space.copy_error_columns_limit":"Dieser Bereich enthält zu viele Säulen zum Kopieren.","space.copy_error_opening_host":"Eine Öffnung ist keiner Wand mehr zugeordnet. Korrigieren oder löschen Sie sie vor dem Kopieren.","space.copy_error_geometry":"Die Kopie würde eine unsichere Wandgeometrie erzeugen. Korrigieren Sie den Quellbereich.","space.copy_error_optimize_geometry":"Das Kopieren wurde gestoppt, weil die Optimierung des gesamten Plans für einen Bereich unsicher ist.","space.header":"Bereich","space.title_label":"Titel","space.title_ph":"z.B. Garage","space.plan_label":"Grundriss (Hintergrund)","space.no_plan":"Kein Planbild","space.plan_alt":"Grundriss","room.new":"Neuer Raum","room.name_label":"Anzeigename","room.name_ph":"z.B. Terrasse","room.area_label":"Home Assistant Bereich (nicht zugewiesen)","room.no_area_option":"— kein Bereich —","room.default_name":"Raum","device.unnamed":"unbenannt","device.light_group":"Lichtgruppe","device.fallback":"Gerät","device.virtual":"Virtuelles Gerät","confirm.delete_room_title":'Raum "{name}" löschen?',"confirm.delete_room_body":"Festlegen, ob die ausschließlich zu diesem Raum gehörenden physischen Wände erhalten bleiben. Mit einem anderen Raum geteilte Wände bleiben immer erhalten.","confirm.remove_marker_title":"Gerät aus dem Plan löschen?","confirm.remove_marker_body":"Das Gerät verschwindet vollständig und trägt nicht mehr zu den Plandaten bei. Es kann später erneut hinzugefügt werden.","confirm.erase_decor":"Das Objekt „{kind}“ löschen? Diese Aktion kann im Editor rückgängig gemacht werden.","confirm.delete_space_title":"Bereich löschen?","confirm.delete_space_body":"Der Bereich, alle seine Räume und die gesamte Planmarkierung werden gelöscht.","confirm.delete_space_vac_routes":"Zuordnungen von Roboterkarten werden ebenfalls entfernt: {count}.","space.delete_blocked":"Dieser Bereich wird noch von {n} Gerät(en) verwendet. Die Geräte zuerst in einen anderen Bereich verschieben oder löschen.","toast.pos_save_failed":"Position nicht gespeichert: {err}","toast.no_entity":"Das Gerät hat keine geeignete Entität","toast.ha_disabled_action":"Ein deaktiviertes Home Assistant-Objekt kann im Plan nicht verwendet werden.","toast.ha_disabled_show_device":"Ein in Home Assistant deaktiviertes Gerät kann im Plan nicht angezeigt werden. Aktivieren Sie es zuerst in Home Assistant.","toast.ha_disabled_show_entity":"Eine in Home Assistant deaktivierte Entität kann im Plan nicht angezeigt werden. Aktivieren Sie sie zuerst in Home Assistant.","toast.ha_disabled_add":"Ein deaktiviertes Home Assistant-Objekt kann nicht dem Plan hinzugefügt werden. Aktivieren Sie es zuerst in Home Assistant.","toast.ha_binding_unverified":"Der Status des Objekts konnte über das Home Assistant-Register nicht überprüft werden. Anzeige und Aktionen sind vorübergehend nicht verfügbar.","toast.markup_needs_server":"Markup ist verfügbar, nachdem die Konfiguration auf den Server verschoben wurde.","toast.space_order_changed":"Reihenfolge geändert. Wenn eine Karte ihr Stockwerk nach Nummer festlegt, überprüfen Sie diese Paneele.","toast.conflict":"Die Konfiguration wurde in einem anderen Fenster geändert — Daten aktualisiert, wiederholen Sie Ihre letzte Aktion.","toast.cfg_save_failed":"Speichern der Konfiguration fehlgeschlagen: {err}","toast.room_overlap":"Die Umrisse überlappen den Raum „{name}“ — Räume dürfen sich nicht überlappen","toast.contour_cannot_close":"Die Kontur kann nicht geschlossen werden, da sie entartet ist oder sich selbst schneidet","toast.merge_not_adjacent":"Es können nur Räume zusammengeführt werden, die eine Wand teilen","toast.rooms_merged":"Räume zu „{name}“ zusammengeführt","toast.split_pick_wall":"Beginnen Sie den Schnitt an der Wand des Raumes","toast.split_bad_cut":"Der Schnitt muss wand-zu-wand innerhalb des Raumes verlaufen, ohne Wände oder sich selbst zu kreuzen","merge.header":"Räume zusammenführen","merge.hint":"Der zusammengeführte Raum behält einen Namen und eine Fläche. Die andere Fläche wird freigegeben — ihre Geräte verlassen den Plan, bis ein anderer Raum sie beansprucht.","merge.keep":"Behalten","merge.no_area":"keine Fläche","toast.room_saved":"Raum gespeichert ({n}). Hinzugefügte Geräte: {added}. Zeichnen Sie die nächste Kontur oder verlassen Sie die Markierung.","toast.room_saved_no_area":"Raum gespeichert ({n}, keine Fläche). Zeichnen Sie die nächste Kontur oder verlassen Sie die Markierung.","toast.marker_needs_server":"Die Gerätebearbeitung ist verfügbar, nachdem die Konfiguration auf den Server verschoben wurde","toast.virtual_name_required":"Einen Namen für das virtuelle Gerät eingeben","toast.marker_saved":"Gerät gespeichert","toast.marker_removed":"Gerät aus dem Plan gelöscht","toast.integration_missing":"Die House Plan-Integration ist nicht installiert — Verwaltung nicht verfügbar","toast.plan_formats":"Unterstützte Formate: SVG, PNG, JPG, WebP","toast.plan_required":"Grundriss hochladen — erforderlich","toast.space_added_onboard":"Bereich hinzugefügt. Räume einzeichnen: Rasterpunkte anklicken und die Kontur schließen.","toast.space_added":"Bereich hinzugefügt","toast.space_copied":"Bereich „{name}“ erstellt","toast.space_saved":"Bereich gespeichert","toast.space_deleted":"Bereich gelöscht","toast.delete_failed":"Löschen fehlgeschlagen: {err}","toast.error":"Fehler: {err}","toast.toggle_target_unavailable":"Ziel „{name}“ ist nicht verfügbar — keine Aktion durchgeführt","toast.toggle_targets_unavailable":"Ziele nicht verfügbar: {names}. Keine Aktion durchgeführt","toast.file_failed":'Datei "{name}" wurde nicht hochgeladen: {err}',"toast.files_attached":"Dateien angehängt: {n}","err.unknown":"unbekannter Fehler","err.code":"Code {code}","err.too_large":"Datei größer als {mb} MB","err.bad_ext":"nicht unterstützter Typ (PDF/Bild erwartet)","err.unauthorized":"Administratorrechte erforderlich","editor.title":"Titel","editor.default_floor":"Anfangsbereich","editor.default_floor_missing":"Anfangsbereich „{id}“ existiert nicht mehr. Wählen Sie einen anderen Bereich.","editor.floor":"Fester Bereich","editor.floor_none":"— nicht fest —","editor.floor_index":"YAML-Index {index} (beibehalten)","fixed_floor.loading":"Lade den festen Bereich…","fixed_floor.invalid_title":"Der feste Bereich ist nicht verfügbar","fixed_floor.invalid_body":"Überprüfen Sie die Etage in der Kartenkonfiguration. Der konfigurierte Wert ist: {value}","editor.icon_size":"Symbolgröße, % der Planbreite","editor.show_temperature":"Temperatur anzeigen","editor.live_states":"Live-Zustände (ein/aus, offen…)","editor.light_pools":"Lichtkegel und Wandschatten","editor.show_signal":"Zigbee-Signal anzeigen (LQI)","editor.language":"Schnittstellensprache","editor.lang_auto":"Automatisch (HA-Profil)","title.icon_rules":"Symbolregeln: welche MDI-Symbole Geräte nach Namen erhalten","rules.title":"Symbolregeln","rules.hint":'Regeln werden von oben anhand von "Gerätename + Modell" (Großschreibungs-unempfindliches Regex) überprüft; das erste Match gewinnt. Wenn nichts übereinstimmt, entscheidet die Entität-Geräteklasse, dann das generische Chip-Symbol.',"rules.pattern_ph":"regex, z. B. Stecker|Steckdose","rules.icon_ph":"mdi:power-socket-de","rules.add":"Regel hinzufügen","rules.reset":"Zurücksetzen auf Standardeinstellungen","rules.test_ph":"Versuch mal einen Gerätenamen...","rules.invalid":"ungültiges regex","rules.saved":"Icon-Regeln gespeichert","btn.up":"Nach oben","btn.down":"Nach unten","tap.info":"Gerätekarte","tap.more_info":"HA Mehr-Info-Dialog","tap.toggle":"Zustand umschalten","marker.tap_label":"Tap-Aktion für dieses Gerät","tap.toggle_note":"Der aufgelöste Zustand ist unten dargestellt. Sichere Geräte werden niemals aus dem Plan umgeschaltet.","import.title":"Bereiche aus HA-Etagen erstellen","import.hint":"Home Assistant kennt diese Etagen bereits. Die Etagen auswählen, die zu Planbereichen werden sollen; anschließend für jeden Bereich einen Grundriss hochladen. Die Räume werden danach von Hand eingezeichnet.","import.start":"{n} Bereich(e) erstellen","import.manual":"Von Grund auf neu starten","import.progress":"Etage {i} von {n}","import.done":"Bereiche erstellt. Räume einzeichnen: Rasterpunkte anklicken und die Kontur schließen.","btn.skip":"Überspringen","space.scale_label":"Maßstab (Rasterzellen-Größe)","space.cell_cm.help":"Verknüpft das Raster mit realen Abmessungen: Davon hängen Längen und Flächen, Wandstärken, Öffnungsgrößen und der Leuchtradius ab. Eine spätere Änderung verändert die berechneten Abmessungen des gesamten Bereichs, verschiebt aber keine Punkte im Plan.","space.cell_cm.help.aria":"Hilfe: Maßstab des Bereichs","space.scale_unit":"cm pro Zelle","space.scale_unit_imperial":"Zoll pro Zelle","space.display_section":"Anzeige","space.show_borders":"Raumgrenzen immer anzeigen","space.zero_wall_style":"Wände ohne Dicke","space.zero_wall_style.help":"Gestrichelte Wände ohne Dicke lassen Glow und Sonnenstrahlen durch, durchgezogene blockieren sie als Barriere ohne Fläche. Die Auswahl gilt für alle solchen Wände im Bereich, auch wenn ihre Linie in der Ansicht ausgeblendet ist.","space.zero_wall_style.help.aria":"Hilfe: Darstellung der Wände ohne Dicke","space.zero_wall_dashed":"Gestrichelt","space.zero_wall_solid":"Durchgezogen","space.show_names":"Raumnamen anzeigen (zum Verschieben ziehen)","space.room_color":"Farbe der Begrenzung & des Namens","space.opacity":"Deckkraft","space.fill_label":"Raumausfüllung","space.fill_mode.help":"„Eigene Farbe“ gestaltet den Bereich; „Licht“, „Temperatur“ und „LQI“ verwenden aktuelle Daten aus Home Assistant. Glow wird separat aktiviert.","space.fill_mode.help.aria":"Hilfe: Modus der Raumausfüllung","fill.none":"Keine","fill.lqi":"Zigbee-Signal","fill.light":"Lichter","fill.custom":"Benutzerdefinierte Farbe","space.custom_fill":"Füllfarbe","space.source_file":"Ich habe einen Grundriss als Bild","space.source_draw":"Kein Bild – ich werde die Räume von Hand umreißen","fill.temp":"Temperatur","tip.temp_avg":"Durchschnittstemperatur:","tip.hum_avg":"Durchschnittliche Luftfeuchtigkeit:","space_card.button":"Grundriss öffnen","space_card.not_found":"Bereich „{id}“ nicht gefunden","space_card.loading":"Laden…","continuity.restore_plan":"Grundriss wiederherstellen…","continuity.restore_connection":"Geräteverbindung wiederherstellen…","continuity.retry":"Erneut versuchen","editor.space":"Bereich","editor.framing":"Bildausschnitt","editor.fit_content":"Alle sichtbaren Inhalte","editor.fit_house":"Eng an der Hausgeometrie","editor.show_button":"Schaltfläche anzeigen","editor.button_label":"Beschriftung der Schaltfläche","editor.button_target":"Ziel-Dashboard-Pfad","marker.sub_entity":"Entität","title.general_settings":"Allgemeine Einstellungen","gs.title":"Allgemeine Einstellungen","gs.light_group":"Füllung: Licht","gs.light_on":"Lichter an","gs.light_off":"Alle Lichter aus","gs.temp_group":"Füllung: Temperatur","gs.temp_cold":"Kalt","gs.temp_ok":"Angenehm","gs.temp_hot":"Heiß","gs.lqi_group":"Füllung: Zigbee-Signal","gs.lqi_low":"Schwaches Signal","gs.lqi_high":"Starkes Signal","gs.reset":"Auf Standard zurücksetzen","gs.saved":"Allgemeine Einstellungen gespeichert","space.show_lqi":"Zigbee-Signal (LQI) neben Geräten anzeigen","space.hide_decor":"Dekorationsschicht ausblenden","space.hide_decor_tip":"Linien, Formen, Beschriftungen und Möbel bleiben an ihrem Platz — im Hintergrundeditor sichtbar, aber nicht auf dem Plan.","space.hide_openings":"Öffnungen ausblenden","space.hide_openings_tip":"Tür-, Fenster- und Tor-Symbole werden nicht gezeichnet, aber die Öffnungen funktionieren weiterhin: Licht fällt hindurch, die Sonne kommt durch ein Fenster herein, Kontaktsensoren öffnen sie weiterhin. Der Planeditor zeigt sie immer an.","gs.light_none":"Keine Lichtquellen","mode.plan":"Planeditor","mode.devices":"Geräteeditor","display.value":"Wert + Zustand","marker.subarea":"kein Bereich, manuell","device.new":"Neues Gerät — Editor öffnen, um zu schließen","opening.unlock_action":"Entsperren","opening.lock_action":"Sperren","opening.lock_pending":"Wird ausgeführt…","title.close_editor":"Editor schließen (zur Ansicht zurück)","title.add_device":"Gerät zum Plan hinzufügen","devbar.add":"Hinzufügen","devbar.rules":"Symbolregeln","device_inbox.button":"Geräte","device_inbox.title":"Geräte auf dem Plan","device_inbox.search":"Geräte, Entitäten und Integrationen suchen…","device_inbox.add_virtual":"Virtuelles Gerät hinzufügen","device_inbox.tab_on_plan":"Auf Plan","device_inbox.tab_available":"Verfügbar","device_inbox.tab_hidden":"Versteckt","device_inbox.tab_readd":"Wieder verfügbar","device_inbox.only_new":"Nur neu","device_inbox.show_entities":"Entitäten anzeigen","device_inbox.show_hidden":"Versteckte auf Plan anzeigen","device_inbox.show_hidden.help":"Zeigt ausgeblendete und deaktivierte Marker vorübergehend als Bearbeitungs-Geister auf dem Plan. Die gespeicherte Sichtbarkeit der Geräte bleibt unverändert.","device_inbox.show_hidden.help.aria":"Hilfe: ausgeblendete Geräte auf dem Plan anzeigen","device_inbox.new":"Neu","device_inbox.find":"Auf dem Plan finden","device_inbox.edit":"Bearbeiten","device_inbox.hide":"Ausblenden","device_inbox.show":"Anzeigen","device_inbox.add":"Hinzufügen","device_inbox.readd":"Wieder hinzufügen","device_inbox.hide_available":"Aus der Liste ausblenden","device_inbox.show_more":"Mehr anzeigen","device_inbox.more_actions":"Weitere Aktionen","device_inbox.find_hidden_hint":"Zuerst „Versteckte auf Plan anzeigen“ aktivieren","device_inbox.show_disabled":"Diese Bindung in Home Assistant aktivieren, bevor sie angezeigt wird","device_inbox.empty_on_plan":"Es befinden sich noch keine passenden Geräte auf dem Plan.","device_inbox.empty_available":"Es sind keine Geräte zum Hinzufügen verfügbar.","device_inbox.empty_hidden":"Es gibt keine versteckten Geräte.","device_inbox.empty_readd":"Es sind keine entfernten Geräte verfügbar, um sie erneut hinzuzufügen.","device_inbox.reason_visible_auto":"Automatisch erkannt","device_inbox.reason_visible_explicit":"Explizit hinzugefügt","device_inbox.reason_manual_hidden":"Vom Benutzer versteckt","device_inbox.reason_automatic_hidden":"Automatisch versteckt","device_inbox.reason_service_entry":"Nur Service-Registry-Eintrag","device_inbox.reason_excluded_integration":"Integration „{integration}“ durch Erkennungsfilter ausgeschlossen","device_inbox.reason_excluded_domain":"Nicht-räumlicher Entitätstyp","device_inbox.reason_grouped_light":"Dargestellt durch eine Raumlichtgruppe","device_inbox.reason_represented_by_parent":"Dargestellt durch sein übergeordnetes Gerät","device_inbox.reason_removed":"Zuvor aus dem Plan entfernt","device_inbox.reason_available":"Zum Hinzufügen zum Plan verfügbar","device_inbox.reason_no_bound_room":"HA-Bereich ist nicht mit einem Planraum verknüpft","device_inbox.status_ha_disabled":"In Home Assistant deaktiviert","device_inbox.status_orphaned":"Bindung ist in Home Assistant nicht mehr vorhanden","device_inbox.status_unverified":"Home Assistant-Register vorübergehend nicht verfügbar","device_inbox.saved":"Geräteliste aktualisiert","device_inbox.filters_excluded":"Ausgeschlossene Integrationen","device_inbox.filters_group_lights":"Raumleuchten zu einem Marker gruppieren","device_inbox.filters_preview_appear":"erscheint: {count}","device_inbox.filters_preview_hide":"verschwindet: {count}","device_inbox.filters_preview_lights":"betroffene Leuchten: {count}","device_inbox.filters_reset":"Empfohlene wiederherstellen","device_inbox.filters_save":"Filter speichern","device_inbox.filters_search_ph":"Integration hinzufügen…","device_inbox.filters_title":"Erkennungsfilter","space.roomcard_section":"Raumkarte zeigt:","space.label_temp":"Temperatur","space.label_hum":"Luftfeuchtigkeit","space.label_lqi":"Durchschnittliches Zigbee-Signal","space.label_light":"Lichter ein/aus","roomcard.light_on":"Ein","roomcard.light_off":"Aus","roomcard.light_partial":"{on} von {total}","toast.split_pick_inside":"Zwischenliegende Schnittpunkte müssen innerhalb des Raumes liegen","mode.decor":"Hintergrundeditor","decor.select":"Auswählen","decor.line":"Linie","decor.rect":"Rechteck","decor.ellipse":"Oval","decor.text":"Text","decor.erase":"Löschen","decor.erase_confirm_title":"Objekt löschen?","decor.color":"Farbe","decor.width":"Linienbreite","decor.line_style":"Linienstil","decor.line_style_solid":"Durchgehend","decor.line_style_dashed":"Gepunktet","decor.fill":"Füllen","decor.fill_color":"Füllfarbe","decor.length":"Länge","decor.size":"Größe","decor.flip_h":"Horizontal spiegeln","decor.flip_v":"Vertikal spiegeln","decor.angle":"Rotationswinkel, °","decor.text_size":"Textgröße","decor.backdrop_properties":"Eigenschaften des Planhintergrunds","decor.text_title":"Textbeschriftung","decor.object_title":"{kind} bearbeiten","decor.text_label":"Text","decor.live_group":"HA-Variable einfügen","decor.live_entity":"Entität","decor.live_entity_ph":"Wählen Sie eine Entität","decor.live_attr":"Wert","decor.live_attr_ph":"Wählen Sie Status oder Attribut","decor.live_state":"Status","decor.backdrop":"Hintergrundbild","decor.backdrop_hint":"Ziehen zum Verschieben; eine Ecke ziehen zum Größenändern; den oberen Griff zum Drehen verwenden. Shift ändert das Verhältnis oder befreit den Winkel.","decor.backdrop_reset":"Bild zurücksetzen","decor.backdrop_reset_done":"Das Bild ist wieder an seinem ursprünglichen Platz und in seiner ursprünglichen Größe","marker.icon_auto":"Auto: {icon} (nach Symbolregeln; wählen Sie eines zur Überschreibung)","marker.icon_pin_auto":"Anheften","mode.plan_tip":"Planungseditor — die Geometrie des Hauses: Räume zeichnen und teilen/zusammenführen, sie mit HA-Bereichen verbinden, Türen, Fenster und Tore platzieren, Raumkarten verschieben, Maßstab festlegen","mode.devices_tip":"Geräteeditor — alles über Symbole: ziehen zum Positionieren, klicken zum Bearbeiten von Bindung/Symbol/Anzeige, virtuelle Geräte hinzufügen, Symbolregeln","mode.decor_tip":"Hintergrundeditor — rein visuelle Dekoration unter dem Plan: Linien, Rechtecke, Ellipsen und Textbeschriftungen, die niemals auf Klicks reagieren","space.glow_enabled":"Lichtquellen-Glühen","gs.glow_group":"Glow von Lichtquellen","gs.glow_base":"Grunddunkelheit des Hauses","gs.glow_light":"Standardlichtfarbe / Intensität","gs.wall_group":"Wände","gs.wall_fill":"Wandfüllung","gs.glow_radius":"Glow-Radius","gs.glow_radius.help":"Legt den allgemeinen Radius des Lichtscheins in Metern oder Fuß fest; ein gerätespezifischer Radius überschreibt diesen Wert.","gs.glow_radius.help.aria":"Hilfe: allgemeiner Glow-Radius","gs.unit_m":"m","gs.unit_ft":"ft","marker.controls_label":"Steuert andere Lichtquellen","marker.controls.help":"Mit der Aktion „Zustand umschalten“ werden die aufgeführten Quellen zusammen mit diesem Marker umgeschaltet. Ihr Glow bleibt an ihren eigenen Markern, und die Verknüpfung allein macht den steuernden Marker nicht zur Lichtquelle.","marker.controls.help.aria":"Hilfe: andere Lichtquellen steuern","marker.controls_filter":"Suchlichter und Schalter…","info.controls":"Steuerungen","marker.glow_radius_label":"Leuchtradius","marker.glow_radius.help":"Legt den Leuchtradius in Metern oder Fuß fest; ein leerer Wert verwendet den Radius aus den allgemeinen Einstellungen.","marker.glow_radius.help.aria":"Hilfe: Leuchtradius","markup.wallthick":"Dicke","markup.select":"Auswählen","title.markup_wallthick":"Dicke — klicken Sie auf eine Wand, um ihre Dicke von 0 bis 100 cm festzulegen.","markup.hint_wallthick":"klicken Sie auf eine Wand · Esc schließt ohne Anwendung","wallthick.field":"Dicke","wallthick.unit_cm":"cm","wallthick.unit_in":"in","wallthick.apply_room":"Auf alle Wände dieses Raums anwenden","markup.draw_wall_title":"Dicke jedes neuen Wandsegments (0–100 cm). Gemeinsame Wände behalten den bestehenden Wert.","room.queue_progress":"Raum {current} von {total}","toast.wall_rooms_saved":"Erstellte Räume: {n}","toast.wall_chain_saved":"Wandkette gespeichert","toast.wallthick_pick":"Eine Wand anklicken","toast.wallthick_set":"Wandstärke eingestellt","toast.wallthick_cleared":"Wandstärke entfernt","toast.physical_range":"Einen Wert von {min} bis {max} {unit} eingeben","toast.zero_wall_opening_conflict":"Entfernen Sie zuerst die Öffnung an diesem Wandsegment.","toast.zero_wall_ambiguous":"Das Wandsegment ist mehrdeutig. Vereinfachen oder passen Sie den Anschluss an.","toast.zero_wall_migration_blocked":"Der Bereich wurde nicht konvertiert: {reason}. Es wurden keine Daten geändert.","toast.physical_angle":"Einen Drehwinkel von 0° bis unter 90° eingeben","toast.physical_limit":"Der Bereich hat das Limit für diesen Geometrietyp erreicht","toast.geometry_unsafe":"Änderung abgebrochen: Wandgeometrie konnte nicht sicher erstellt werden.","junction.limit_angle":"Der Winkel zwischen den Wänden ist zu spitz: {actual}°, mindestens {limit}°.","junction.limit_valence":"Zu viele Wände treffen in einem Knoten aufeinander: {actual}, maximal {limit}.","junction.limit_length":"Das Wandsegment ist zu kurz: {actual} cm, mindestens {limit} cm.","junction.limit_distance":"Wände und Knoten sind zu dicht beieinander: {actual} cm, Minimum {limit} cm.","junction.limit_clearance":"Kein Wohnbereich ist übrig: {actual} cm², Minimum {limit} cm².","junction.limit_check_failed":"Die Überprüfung der Verbindungen konnte nicht durchgeführt werden — die Änderung wurde nicht gespeichert.","toast.wall_model_migration_blocked":"Das Wandmodell konnte nicht aktualisiert werden: {reason}. Der Plan wurde nicht geändert. Führen Sie „Pläne optimieren“ aus; wenn der Fehler erneut auftritt, beheben Sie die widersprüchliche Wandgeometrie.","toast.wall_model_client_outdated":"Aktualisieren Sie die Karte und laden Sie die Seite neu, bevor Sie den Plan bearbeiten.","wall_model.reason.invalid-room":"ungültiger Raumkontur","wall_model.reason.zero-length":"Wandsegment mit null Länge","wall_model.reason.third-owner":"Wand, die von mehr als zwei Räumen geteilt wird","wall_model.reason.duplicate-id":"widersprüchliche Wandkennungen","wall_model.reason.thickness-conflict":"widersprüchliche Wandstärkenwerte","wall_model.reason.opening-host":"Öffnung kann nicht einer Wand zugewiesen werden","toast.delete_room_pick":"Klicken Sie in den Raum, den Sie löschen möchten","toast.plan_snap_ambiguous":"Zoomen Sie hinein, um den Wandknoten auszuwählen","toast.wall_repair_ambiguous":"Der Raumumriss hat mehr als eine mögliche Verbindung. Zoomen Sie hinein und verbinden Sie ihn explizit.","toast.wall_repair_too_large":"Die Lücke ist größer als 2 cm. Verbinden Sie die Wände, bevor Sie den Raum erstellen.","toast.wall_repair_changed":"Die Wandgeometrie hat sich geändert. Versuchen Sie erneut, den Raum zu erstellen.","toast.opening_on_zero_wall":"Öffnungen können nicht auf einer Wand mit null Dicke sitzen.","marker.from_ha_option":"Wählen Sie aus der HA-Liste.","marker.show_entities":"Entitäten anzeigen.","marker.show_entities_tip":"Fügt nicht nur Geräte zur Liste hinzu, sondern auch alle ihre Entitäten.","marker.pick_ph":"Wählen Sie ein Gerät…","room.open_area":"Öffnen Sie den HA-Bereich.","room.fit_action":"Raum {name} einpassen","view.volumetric":"Volumetrische Ansicht.","view.flat":"Flache Ansicht.","kiosk.title":"Die Größen dieses Bildschirms.","kiosk.hint":"Nur auf diesem Gerät gespeichert – jedes Wandtablet oder TV kann seine eigenen komfortablen Größen haben.","kiosk.icon_scale":"Gerätesymbolgröße.","kiosk.font_scale":"Textgröße der Raumkarte.","editor.kiosk":"Wandgeräte- (Kiosk-)Modus.","editor.cycle":"Bereiche automatisch alle N Sekunden wechseln (Kiosk, 0 = aus)","room.settings_title":"Raumeinstellungen.","room.settings_section":"Raumeinstellungen (überschreibt den Bereich)","room.fill_label":"Diesen Raum ausfüllen","fill.inherit":"Als den Bereich","room.custom_fill_space":"Bereichsfarbe","room.custom_fill_own":"Raumfarbe","room.temp_src_label":"Temperaturquelle","room.hum_src_label":"Luftfeuchtigkeitsquelle","room.src_average":"Durchschnitt über die Sensoren des Raums (Standard)","room.src_pick":"Ein bestimmtes HA-Gerät oder Entität","room.src_ph":"Quelle wählen…","toast.room_updated":"Raum aktualisiert","space.card_font":"Schriftgröße der Raumkarte (gesamter Bereich)","room.sizes_section":"Schriftgrößen","room.name_scale":"Raumname Größe","room.label_scale":"Metrikgröße","preview.room_name":"Wohnzimmer","toast.cfg_reload_failed":"Der Plan konnte nicht vom Server neu geladen werden: {err}","toast.locale_load_failed":"Das Sprachpaket konnte nicht geladen werden. Bis zum Neuladen der Seite wird Englisch verwendet.","toast.furniture_art_load_failed":"Die Möbelzeichnungen konnten nicht geladen werden. Laden Sie die Seite neu, um sie anzuzeigen.","room.settings_short":"Raumeinstellungen","room.unnamed":"Unbenannter Raum","marker.use_climate_temp":"Geräte-Temperatur im Raum berücksichtigen","marker.use_climate_temp_tip":"Fügt die aktuelle Temperatur einer Klimaanlage oder eines Thermostats zum Raumdurchschnitt hinzu. Das externe Wert-Label unten separat konfigurieren.","marker.value_badge_title":"Wert-Label","marker.value_badge.help":"Zeigt einen ausgewählten Wert neben dem Symbol an. Dies beeinflusst nicht die Raumkennzahlen, Licht, Glanz oder die Tippaktion.","marker.value_badge.help.aria":"Hilfe: Gerätewert-Badge","marker.value_badge_enabled":"Zeige ein Wert-Badge","marker.value_badge_source":"Wert","marker.value_badge_source.help":"Wählen Sie einen bestimmten Zustand, ein unterstütztes Attribut oder einen abgeleiteten Wert dieses Geräts.","marker.value_badge_source.help.aria":"Hilfe: Quelle des Wert-Badges","marker.value_badge_position":"Position","marker.value_badge_position.help":"Die gewählte Seite bleibt fest und dreht sich nicht automatisch an einem Planrand.","marker.value_badge_position.help.aria":"Hilfe: Position des Wert-Badges","marker.value_badge_right":"Rechts","marker.value_badge_bottom":"Unten","marker.value_badge_left":"Links","marker.value_badge_top":"Oben","marker.value_badge_empty":"Für dieses Gerät stehen keine Werte zur Verfügung","marker.value_badge_static":"Ein statisches Symbol zeigt keine Live-Werte an. Die Einstellung wird beibehalten.","marker.value_badge_missing":"Quelle nicht verfügbar","marker.value_badge_missing_hint":"Die gespeicherte Quelle ist derzeit nicht verfügbar. Behalten Sie sie bei, deaktivieren Sie das Badge oder wählen Sie einen anderen Wert.","marker.value_badge_duplicate":"Derselbe Wert wird bereits im Symbol angezeigt.","marker.value_badge_state":"Status · {name}","marker.value_badge_marker_state":"Lichtquellstatus · {name}","marker.value_badge_lqi":"Durchschnittliche Zigbee-Signalqualität","marker.value_badge_attr_current_temperature":"Aktuelle Temperatur · {name}","marker.value_badge_attr_temperature":"Zieltemperatur · {name}","marker.value_badge_attr_current_humidity":"Aktuelle Luftfeuchtigkeit · {name}","marker.value_badge_attr_humidity":"Luftfeuchtigkeit · {name}","marker.value_badge_attr_current_position":"Position · {name}","marker.value_badge_attr_percentage":"Geschwindigkeit · {name}","marker.value_badge_attr_brightness":"Helligkeit · {name}","marker.value_badge_attr_volume_level":"Lautstärke · {name}","marker.value_badge_attr_battery_level":"Batterie · {name}","marker.value_badge_attr_fan_speed":"Lüftergeschwindigkeit · {name}","marker.value_source":"Wertquelle","marker.value_source.help":"Wähle den Wert, der das Symbol ersetzt. Die Tipp-Aktion bleibt unverändert.","marker.value_source.help.aria":"Hilfe: Wertquelle in der Gerätefläche","marker.value_source_auto":"Automatisch (wie bisher)","marker.value_source_missing_hint":"Die gespeicherte Quelle ist derzeit nicht verfügbar. Bis sie wieder verfügbar ist oder ein anderer Wert gewählt wird, zeigt die Fläche —.","marker.light_role_label":"Ist dieses Gerät eine Lichtquelle?","marker.light_role.help":"„Auto“ verwendet die ermittelte Rolle des verknüpften Geräts, „Immer“ erzwingt eine eigene Quelle und „Nie“ schließt sie aus; oben verknüpfte Lichter bleiben unabhängig.","marker.light_role.help.aria":"Hilfe: ob dieses Gerät eine Lichtquelle ist","marker.light_role_auto_yes":"Automatisch (Lichtquelle)","marker.light_role_auto_no":"Automatisch (keine Lichtquelle)","marker.light_role_always":"Immer eine Lichtquelle","marker.light_role_never":"Nie eine Lichtquelle","marker.light_entity_label":"Führende Lichtereinheit","marker.light_entity.help":"Für ein Verbundgerät wählen Sie die Entität, deren Zustand, Farbe und Helligkeit diese Planquelle darstellen. Der automatische Rückgriff bleibt mit älteren Plänen kompatibel.","marker.light_entity.help.aria":"Hilfe: führende Lichtentität","marker.light_entity_auto":"Automatisch ({entity})","marker.light_entity_none":"keine steuerbare Entität","marker.light_entity_missing":"Die gespeicherte Entität {entity} ist nicht verfügbar. House Plan verwendet vorübergehend {fallback}; die gespeicherte Auswahl wird wiederhergestellt, wenn sie zurückkehrt.","marker.toggle_entity_label":"Zu toggelnde Entität","marker.toggle_entity.help":"Für ein Verbundgerät wählen Sie das genaue eigene Licht oder den Schalter, der durch Tippen bedient wird. Automatisch behält die vorherigen Zielregeln bei und ist unabhängig von der führenden Lichtentität.","marker.toggle_entity.help.aria":"Hilfe: zu toggelnde Entität","marker.toggle_entity_auto":"Automatisch ({entity})","marker.toggle_entity_none":"keine eigene steuerbare Entität","marker.toggle_entity_missing":"Die gespeicherte Entität {entity} ist nicht mehr unter den auswählbaren Kanälen dieses Markers. House Plan verwendet vorübergehend {fallback}; die gespeicherte Auswahl wird wiederhergestellt, wenn sie zurückkehrt.","marker.glow_color_label":"Leuchtfarbe und Helligkeit","marker.glow_mode.help":"Verwenden Sie Live-Quellwerte, überschreiben Sie nur deren Farbe oder fixieren Sie sowohl Farbe als auch Helligkeit. Das Minimum beträgt 1 %; um die Quelle zu deaktivieren, wählen Sie „Nie“.","marker.glow_mode.help.aria":"Hilfe: Leuchtfarbe und Helligkeit","marker.glow_mode_auto":"Von Quelle","marker.glow_mode_color":"Farbe einstellen","marker.glow_mode_fixed":"Farbe und Helligkeit einstellen","marker.glow_color":"Leuchtfarbe","marker.glow_brightness":"Helligkeit","marker.glow_disabled_never":"Leuchteinstellungen sind nicht verfügbar, da dieser Marker ausdrücklich keine Lichtquelle ist.","marker.glow_disabled_auto":"Im Automatikmodus wurde keine räumliche Lichtquelle für diesen Marker gefunden.","marker.glow_disabled_no_entity":"Keine aktive steuerbare Home Assistant-Entität ist für diese räumliche Quelle verfügbar.","marker.glow_passive_hint":"Diese Quelle hat keine eigenen Home Assistant-Daten. Stellen Sie ihre Farbe und Helligkeit manuell ein; ihr Radius bleibt verfügbar.","marker.control_broken":"Gespeicherte Quelle fehlt oder ist nicht mehr als Licht markiert","marker.control_missing_label":"Fehlendes Planlicht","marker.control_passive":"passive Quelle","toast.marker_control_cycle":"Dieser Link würde eine kreisförmige Kette von Lichtsteuerungen erzeugen.","toast.marker_binding_required":"Wählen Sie ein Home Assistant-Gerät, bevor Sie eine andere Lichtquelle verlinken.","confirm.unlock_title":"Schloss öffnen?","confirm.unlock_body":"House Plan sendet einen Befehl zum Öffnen an dieses Schloss.","toast.files_migrate_failed":"Anhänge konnten nicht zur neuen Bindung verschoben werden, Links zeigen weiterhin auf die alten Dateien: {err}","space.pick_saved":"Bereits hochgeladen","space.pick_saved_hint":"Auf dem Server gespeicherte Pläne, einschließlich solcher, die Sie zuvor getrennt haben","space.no_saved":"Noch keine Pläne auf dem Server gespeichert.","space.loading":"Laden…","space.used_by":"in Benutzung: {list}","space.in_use":"Ein Bereich verwendet diesen Plan noch — zuerst die Verknüpfung lösen","btn.use":"Verwenden","confirm.delete_plan_title":"Plandatei löschen?","confirm.delete_plan_body":"Die Datei wird vom Server gelöscht. Dieser Vorgang kann nicht rückgängig gemacht werden.","toast.plans_list_failed":"Konnte die gespeicherten Pläne nicht auflisten: {err}","toast.plan_delete_failed":"Konnte den Plan nicht löschen: {err}","marker.hide":"Ausblenden","marker.hide_tip":'Das Gerät wird nach dem Speichern aus dem Plan verschwinden, aber weiterhin zum Signalsignal des Raums zählen. Stellen Sie es über den Katalog "Geräte" im Geräte-Editor wieder her.',"marker.show":"Anzeigen","marker.show_tip":"Das Gerät wird nach dem Speichern wieder im Plan erscheinen.","marker.hidden_ghost":"Vom Benutzer ausgeblendetes Gerät","marker.ha_disabled_device":"Das Gerät ist in Home Assistant deaktiviert und im Plan ausgeblendet.","marker.ha_disabled_entity":"Die Entität ist in Home Assistant deaktiviert und im Plan ausgeblendet.","marker.ha_disabled_all_entities":"Das Gerät hat keine aktiven Home Assistant-Entitäten, daher ist es im Plan ausgeblendet.","marker.ha_registry_limited":"Das vollständige Home Assistant-Register ist für diesen Benutzer nicht verfügbar. Das nicht verifizierte Objekt kann vorerst nicht angezeigt oder verwendet werden.","marker.delete_tip":"Löschen Sie das Gerät vollständig aus dem Plan und allen Aggregaten. Sie können es später wieder hinzufügen.","tap.run":"Führen Sie Automation/Skript/Szene aus","tap.none":"Nichts tun","marker.run_target_label":"Was ausführen","marker.run_search_ph":"Suchen: Automation, Skript oder Szene…","marker.run_target_gone":"Ziel {id} nicht gefunden — erneut auswählen","marker.tap_confirm":"Um Bestätigung bitten","marker.tap_confirm_tip":"Vor der Ausführung ein Bestätigungsdialogfeld anzeigen — eine Vorsichtsmaßnahme gegen versehentliche Berührungen.","marker.toggle_hint_single":"Ziel: {name} ({id}).","marker.virtual_light_target":"Virtuelles Licht: {name}.","marker.virtual_light_current":"Manueller Zustand: {state} → {effect}.","marker.virtual_light_state_on":"ein","marker.virtual_light_state_off":"aus","marker.toggle_hint_group":"Wird {count}-Quelle(n) umschalten: {names}.","marker.toggle_hint_current":"Jetzt: {state} → {effect}.","marker.toggle_hint_group_current":"Derzeit an: {on} von {count} → {effect}.","marker.toggle_hint_skipped":"Wird übersprungen ({count}): {targets}.","marker.toggle_effect_turn_on":"wird eingeschaltet","marker.toggle_effect_turn_off":"wird ausgeschaltet","marker.toggle_effect_open":"wird geöffnet","marker.toggle_effect_close":"wird geschlossen","marker.toggle_effect_stop":"wird gestoppt","marker.toggle_effect_toggle":"Zustand wird umgeschaltet","marker.toggle_skip_missing":"nicht gefunden","marker.toggle_skip_ha_disabled":"in HA deaktiviert","marker.toggle_skip_unavailable":"nicht verfügbar","marker.toggle_skip_unsupported":"Umschalten wird nicht unterstützt","marker.toggle_skip_secure":"aus Sicherheitsgründen blockiert","marker.toggle_none_no_binding":"Dieses Gerät hat keine Bindung, daher gibt es keinen Zustand, der umgeschaltet werden könnte. Tippen bewirkt nichts.","marker.toggle_none_no_actionable_entity":"Dieses Gerät hat keinen Zustand, der umgeschaltet werden könnte. Tippen bewirkt nichts.","marker.toggle_none_configured_targets_missing":"Die konfigurierten Ziele sind nicht verfügbar. Die eigene Entität des Geräts wird nicht ersetzt.","marker.toggle_none_ha_disabled":"Das Ziel ist in Home Assistant deaktiviert und kann im Plan nicht verwendet werden.","marker.toggle_none_unavailable":"Das Ziel ist derzeit nicht verfügbar. Tippen bewirkt nichts.","marker.toggle_none_unsupported":"Home Assistant bietet keine sichere Umschaltfunktion für dieses Gerät. Tippen bewirkt nichts.","marker.toggle_none_secure":"Das Umschalten von Schlössern, Alarmen und gesicherten Toren über den Plan ist aus Sicherheitsgründen gesperrt.","run.automation":"Automatisierung","run.script":"Skript","run.scene":"Szene","confirm.tap_run":'"{name}" ausführen?',"confirm.tap_toggle":'"{name}" umschalten?',"confirm.current_state":"Aktueller Zustand: {state}","confirm.expected_state":"Nach dem Umschalten: {state}","confirm.group_current":"an {on} von {total}","confirm.group_all_on":"alle sind eingeschaltet","confirm.group_all_off":"alle sind ausgeschaltet","confirm.unavailable_targets":"Nicht verfügbar: {count}","confirm.expected_by_ha":"Home Assistant ermittelt den Zustand","confirm.state_on":"Ein","confirm.state_off":"Aus","confirm.state_open":"Offen","confirm.state_closed":"Geschlossen","confirm.state_opening":"Wird geöffnet","confirm.state_closing":"Wird geschlossen","confirm.state_stopped":"Gestoppt","confirm.state_unknown":"Unbekannt","toast.run_started":"Gestartet: {name}","toast.run_target_missing":"Ausführungsziel nicht gefunden — überprüfen Sie die Geräteeinstellungen","toast.run_target_required":"Wählen Sie eine Automatisierung, ein Skript oder eine Szene aus","toast.tap_target_changed":"Das Ziel der Aktion hat sich geändert. Versuchen Sie es erneut.","toast.virtual_light_toggle_failed":"Das virtuelle Licht konnte nicht umgeschaltet werden: {err}","toast.value_badge_source_required":"Einen Wert für den Badge auswählen","btn.run":"Ausführen","vac.section":"Roboterstaubsauger: aktuelle Position","vac.autocal":"Automatisch einrichten","vac.live":"Aktuelle Position im Plan","vac.trail":"Roboterpfad anzeigen","vac.autocal_no_rooms":'Die Integration meldet keine Raumliste — öffnen Sie "Manuell anpassen"',"vac.route_warn_unmapped":"Der Roboter reinigt eine Karte, die keiner Etage zugeordnet ist","vac.route_warn_needs_calibration":"Die Karte ist einer Etage zugeordnet, aber nicht kalibriert","vac.route_warn_ambiguous":"Zwei Karten sind nicht unterscheidbar — keine Etage gewählt","vac.route_warn_missing_space":"Der Raum dieser Karte wurde gelöscht","vac.autocal_no_match":'Raumnamen stimmten nicht überein (mindestens 3 müssen übereinstimmen) — öffnen Sie "Manuell anpassen"',"vac.autocal_done":"Fertig: über {rooms} Räume zugeordnet. Eine Reinigung starten und das Ergebnis prüfen.","vac.cal_need_pos":"Der Roboter meldet keine Koordinaten — starten Sie eine Reinigung und pausieren Sie sie","vac.cal_done":"Kalibrierung gespeichert. Eine Reinigung starten und das Ergebnis prüfen.","vac.cal_cancelled":"Kalibrierung abgebrochen","vac.fit":"Manuell anpassen","vac.fit_hint":"Roboterkarte an die richtige Position ziehen und an den Ecken skalieren","vac.fit_rotate":"90° drehen","vac.fit_mirror":"Spiegeln","vac.trail_never":"Nie","vac.trail_cleaning":"Beim Reinigen","vac.trail_always":"Immer","gs.bg_group":"Bühnenhintergrund","gs.bg_color":"Hintergrund um den Plan","gs.bg_default":"Standardthema","gs.bg_theme":"Standardthema","gs.bg_mode":"Planhintergrund","gs.bg_mode.help":"„Folgt der Sonne“ verwendet sun.sun und ersatzweise die lokale Browserzeit; „Statische Farbe“ zeigt immer die ausgewählte Farbe.","gs.bg_mode.help.aria":"Hilfe: allgemeiner Planhintergrund","gs.bg_static":"Statische Farbe","gs.bg_daynight":"Folgt der Sonne","gs.sun_group":"Sonne","gs.sun_missing":"Die sun.sun-Entität wurde nicht gefunden — der Hintergrund folgt Ihrer lokalen Uhr; Fensterstrahlen sind nicht verfügbar.","gs.north":"Norden auf dem Plan","gs.north.help":"Der Winkel wird im Uhrzeigersinn von der oberen Vertikalen des Plans gemessen; Norden wird für Fensterstrahlen benötigt, nicht für den Hintergrund „Folgt der Sonne“.","gs.north.help.aria":"Hilfe: allgemeine Nordrichtung","gs.north_ph":"nicht gesetzt","gs.north_clear":"Löschen","gs.north_letter":"N","gs.sun_rays":"Sonnenlicht durch Fenster","gs.about_version":"House Plan Card v{v}","gs.about_github":"GitHub · Dokumentation & Probleme","gs.about_telegram":"Telegram-Chat","support.title":"Hilfe & Feedback","space.bg_color":"Hintergrund rund um den Plan","space.bg_inherit":"Allgemein erben","space.bg_inherited":"erbt allgemeine Einstellungen","space.bg_mode":"Planhintergrund","space.bg_mode.help":"Übernehmen Sie den allgemeinen Hintergrund oder überschreiben Sie diesen Bereich mit einer statischen Farbe oder „Folgt der Sonne“.","space.bg_mode.help.aria":"Hilfe: Hintergrund des Bereichs","space.north":"Norden auf dem Plan (überschreiben)","space.north.help":"Überschreibt die allgemeine Nordrichtung für diesen Bereich; der Winkel wird im Uhrzeigersinn von der oberen Vertikalen des Plans gemessen und für Fensterstrahlen verwendet.","space.north.help.aria":"Hilfe: Norden für diesen Bereich","space.north_inherited":"geerbt: {v}","space.sun_rays":"Sonnenlicht durch Fenster","space.sun_inherit":"Allgemein erben","space.sun_on":"Ein","space.sun_off":"Aus","canvas.far_objects":"{n} Objekt(e) weit vom Plan entfernt","canvas.show_far":"Anzeigen","canvas.home_tip":"Der Plan ist dort drüben — klicken, um ihn anzupassen","gs.grid_group":"Planwartung","gs.grid_hint":"Aktualisiert Datenmodelle, richtet Planelemente am Raster aus und fasst redundante Wandfragmente zusammen. Ein exakter Bericht wird angezeigt, bevor etwas gespeichert wird.","gs.align_all":"Pläne optimieren","gs.align_title":"Pläne optimieren","gs.align_none":"Alle Pläne verwenden bereits das aktuelle optimierte Datenmodell.","gs.optimize_no_automatic_changes":"Es gibt keine automatischen Änderungen, die angewendet werden müssen. Überprüfen Sie die unten stehenden Punkte.","gs.align_count":"{n} von {total} Elementen werden sich um höchstens {cm} cm bewegen.","gs.align_where":"Die größte Verschiebung ist in „{s}“.","gs.align_turned":"Öffnungen, deren Winkel korrigiert wurde: {n}.","gs.align_preflight_failed":"Die Geometrie der folgenden Bereiche konnte nicht sicher überprüft werden: {spaces}{more}.","gs.align_preflight_hint":"Pläne wurden nicht geändert. Kopieren Sie die Diagnosen mit dem untenstehenden Button und fügen Sie sie zusammen mit einem Raumexport dem Fehlerbericht bei.","gs.preflight_reason_prepare-exception":"Die Bereichsgeometrie konnte nicht vorbereitet werden (Ausnahme beim Erstellen des Modells)","gs.preflight_reason_wall-null":"Der Wandkörper wurde nicht erstellt (die Vereinigung lieferte leer zurück)","gs.preflight_reason_wall-degraded-extra":"Der Wandkörper wurde mit zusätzlicher Geometrie beschädigt","gs.preflight_reason_wall-failed-core":"Der Kern des Wandkörpers konnte nicht zusammengesetzt werden","gs.preflight_reason_wall-exception":"Die Wandkonstruktion warf eine Ausnahme","gs.preflight_reason_floor-null":"Der Fußbodenumriss wurde nicht erstellt","gs.preflight_reason_floor-exception":"Bodenaufbau hat eine Ausnahme ausgelöst","gs.preflight_copy":"Diagnosen kopieren","gs.preflight_copied":"Diagnosen kopiert","gs.preflight_update_hint":"Die Karten- und Integrationsversionen unterscheiden sich — Hausplan aktualisieren und erneut versuchen.","gs.align_preflight_space":"Bereich {n}","gs.align_preflight_more":", und {n} mehr","gs.optimize_changes":"Modellmigrationen: {m}; aktualisierte Bereiche: {c}; entfernte verrauschte Koordinatenwerte: {p}; zusammengeführte Fragmente realer Wände: {w}; zusammengeführte Fragmente von Wänden ohne Dicke: {s}; unabhängige Wände: {i}.","gs.zero_walls_migrated":"Virtuelle Wandspannweiten konvertiert: {n}.","gs.wall_segments_migrated":"Wandsegmente stabilisiert: {n}.","gs.room_drafts_migrated":"Unvollständige Konturen wurden in normale Wände umgewandelt: {drafts}; Wandsegmente: {segments}.","gs.optimize_lattice_summary":"Rauschen in den Koordinatenwerten kanonisiert: {n}; maximale Bewegung: {cm} cm.","gs.optimize_lattice_space":"{space}: Koordinatenwerte kanonisiert: {n}; außerhalb des Rasters liegende Werte unverändert gelassen: {far}.","gs.optimize_coincident_partitions":"Versteckte unabhängige Wandabschnitte in Raumwände integriert: {n}.","gs.optimize_openings_rehosted":"Öffnungen wieder an Raumwände angebracht: {n}.","gs.optimize_walls_straightened":"Wände begradigt: {n}; maximale Bewegung: {cm} cm.","gs.optimize_walls_straightened_where":"Größte Wandkorrektur: {s}.","gs.optimize_walls_straighten_skipped":"Nahe Achsenwände unverändert gelassen, da sie nicht sicher repariert werden konnten: {n}.","gs.optimize_glow_migration":"Legacy Glow: {spaces} Bereiche → keine Datenfüllung + unabhängiges Glow; {rooms} Räume → geerbte Datenfüllung + unabhängiges Glow.","gs.optimize_references":"Referenzen repariert: Bereiche — {spaces}; Räume — {rooms}; Positionen — {positions}; Geräte aus fehlenden Bereichen gelöst — {detached}.","gs.optimize_reference_more":", und {n} mehr","gs.optimize_orphans_removed":"Vergessene Einträge entfernt: {total} — Raumbezeichnungen: {rooms}; Geräte: {devices}; Gruppenmarkierungen: {groups}. Sie gehörten zu zuvor gelöschten Bereichen.","gs.optimize_live_positions":"Alte Positionen in gelöschten Bereichen gehören zu vorhandenen Objekten: {n}{names}. Sie werden beibehalten.","gs.optimize_live_positions_remove":"Alte Positionen in gelöschten Bereichen gehören zu vorhandenen Objekten: {n}{names}. Sie sind zur Entfernung ausgewählt.","gs.optimize_live_names":": {names}{more}","gs.optimize_live_remove":"Alte Positionen entfernen","gs.optimize_live_keep":"Alte Positionen beibehalten","gs.optimize_live_selected":"Alte Positionen werden nach der Anwendung von Optimieren entfernt.","gs.optimize_unverified":"Positionen konnten nicht sicher überprüft werden: {n}. Sie wurden unverändert belassen.","gs.optimize_registry_limited":"Voller Administratorzugriff auf die Home Assistant-Registries ist für eine sichere Überprüfung erforderlich.","gs.optimize_vacuum_warning":"Raumzuordnungen, die noch überprüft werden müssen: {n}.","gs.optimize_details":"Details","gs.optimize_details_more":"Und {n} weitere Einträge.","gs.optimize_detail_removed":"wird entfernt","gs.optimize_detail_live":"wird beibehalten","gs.optimize_detail_unverified":"nicht überprüft","gs.optimize_detail_room_label":"Raumkennzeichnung","gs.optimize_detail_device":"Gerät","gs.optimize_detail_group":"Gruppenkennzeichen","gs.optimize_detail_unknown":"unbekannter Eigentümer","gs.optimize_detail_item":"{status}: {kind} {id}; alter Bereich {space}","gs.align_warn":"Absichtlich zwischen Rasterknoten platzierte Elemente werden sich bewegen. Nach der Operation ist nur eine Rückgängig-Funktion verfügbar, und zwar nur bis zur nächsten Planbearbeitung.","gs.align_run":"Optimieren","gs.align_done":"Pläne optimiert: {n} Elemente bewegt, {m} Datensätze beibehalten, {r} Verweise repariert","gs.optimize_undo":"Letzte Optimierung rückgängig machen","gs.optimize_undone":"Die letzte Optimierung wurde rückgängig gemacht","decor.furniture":"Möbel","decor.image":"Bild","decor.image_title":"Eigene Bilder","decor.image_upload":"Bild hochladen","decor.image_replace":"Bild ersetzen","decor.image_uploading":"Wird hochgeladen…","decor.image_asset":"Bilddatei","decor.image_pick_hint":"Ein Bild hochladen oder ein vorhandenes auswählen.","decor.image_place_hint":"Auf den Plan klicken, um das Bild zu platzieren.","decor.image_none":"Noch keine Bilder hochgeladen.","decor.image_unavailable":"Bild nicht verfügbar","decor.image_used":"In {n} Objekten verwendet","decor.image_upload_failed":"Bild konnte nicht hochgeladen werden: {err}","decor.image_error_capacity":"Der Speicher für benutzerdefinierte Bilder ist voll.","decor.image_in_use":"Vor dem Löschen alle platzierten Kopien entfernen.","decor.image_delete_title":"Bilddatei löschen?","decor.image_delete_message":"„{name}“ aus House Plan löschen? Dies kann nicht rückgängig gemacht werden.","furn.title":"Möbelbibliothek","furn.symbol":"Symbol","furn.group_furniture":"Möbel","furn.group_appliance":"Geräte","furn.group_sanitary":"Sanitär","furn.group_other":"Sonstiges","furn.width":"Breite","furn.depth":"Tiefe","furn.back_to_categories":"Alle Kategorien","furn.pick_hint":"Wählen Sie eine Kategorie und dann ein Symbol.","furn.place_hint":"Klicken Sie auf den Plan — das Element wird an der nächsten Wand platziert. Mit Shift wird es frei platziert.","furn.cat_air_conditioner":"Klimaanlagen","furn.cat_armchair":"Sessel","furn.cat_bathtub":"Badewannen","furn.cat_bed":"Betten","furn.cat_bidet":"Bidets","furn.cat_boiler":"Warmwasserbereiter","furn.cat_chair":"Stühle","furn.cat_coffee_table":"Couchtische","furn.cat_cooktop":"Kochfelder","furn.cat_dining_table":"Esstische","furn.cat_dishwasher":"Geschirrspüler","furn.cat_dryer":"Wäschetrockner","furn.cat_fireplace":"Kamine","furn.cat_fridge":"Kühlschränke","furn.cat_kitchen_cabinet":"Küchenschränke","furn.cat_kitchen_sink":"Küchenspülen","furn.cat_nightstand":"Schränke","furn.cat_plant":"Pflanzen","furn.cat_rug":"Teppiche","furn.cat_shelving":"Regale","furn.cat_shower":"Duschen","furn.cat_sink":"Waschbecken","furn.cat_sofa":"Sofas","furn.cat_stairs":"Treppen","furn.cat_toilet":"Toiletten","furn.cat_tv":"Fernseher","furn.cat_wardrobe":"Kleiderschränke","furn.cat_washer":"Waschmaschinen","furn.cat_work_table":"Schreibtische","furn.sym_sofa":"Zweisitzer-Sofa","furn.sym_sofa_three_seat":"Dreisitzer-Sofa","furn.sym_sofa_corner_right":"Ecksofa rechts","furn.sym_armchair":"Polstersessel","furn.sym_armchair_office":"Bürostuhl","furn.sym_coffee_table":"Rechteckiger Couchtisch","furn.sym_coffee_table_round":"Runder Couchtisch","furn.sym_coffee_table_oval":"Ovaler Couchtisch","furn.sym_coffee_table_rounded":"Abgerundeter Couchtisch","furn.sym_table_dining":"Rechteckiger Esstisch","furn.sym_table_round":"Rundtisch","furn.sym_table_dining_oval":"Ovaler Esstisch","furn.sym_table_dining_rounded":"Abgerundeter Esstisch","furn.sym_chair":"Stuhl","furn.sym_chair_bar":"Barhocker","furn.sym_desk":"Rechteckiger Schreibtisch","furn.sym_desk_corner":"Eckschreibtisch","furn.sym_bed_double":"Doppelbett","furn.sym_bed_single":"Einzelbett","furn.sym_nightstand":"Nachttisch","furn.sym_cabinet_tv":"TV-Schrank","furn.sym_cabinet_shoe":"Schuhschrank","furn.sym_cabinet_sink":"Waschtischunterschrank","furn.sym_wardrobe":"Kleiderschrank","furn.sym_bookshelf":"Bücherschrank","furn.sym_wall_unit":"Schrankwand","furn.sym_kitchen_floor":"Küchen-Unterschrank","furn.sym_kitchen_floor_corner":"Küchen-Eckunterschrank","furn.sym_kitchen_wall":"Küchen-Hängeschrank","furn.sym_kitchen_wall_corner":"Küchen-Eckhängeschrank","furn.sym_shelf_floor":"Standregal","furn.sym_shelf_wall":"Wandregal","furn.sym_fridge":"Kühlschrank","furn.sym_stove":"Vierflammiges Kochfeld","furn.sym_cooktop_two":"Zweiflammiges Kochfeld","furn.sym_dishwasher":"Geschirrspüler","furn.sym_washer":"Waschmaschine","furn.sym_dryer":"Wäschetrockner","furn.sym_tv":"Fernseher mit Standfuß","furn.sym_tv_wall":"Wandfernseher","furn.sym_ac":"Klimaanlage","furn.sym_water_heater":"Wassererhitzer","furn.sym_toilet":"Stand-WC","furn.sym_toilet_built_in":"Wand-WC","furn.sym_bathtub":"Rechteckige Badewanne","furn.sym_bathtub_corner":"Eckbadewanne","furn.sym_shower":"Dusche","furn.sym_sink":"Waschbecken","furn.sym_kitchen_sink":"Einzel-Küchenspüle","furn.sym_kitchen_sink_double":"Doppel-Küchenspüle","furn.sym_bidet":"Stand-Bidet","furn.sym_bidet_built_in":"Wand-Bidet","furn.sym_stairs":"Treppe","furn.sym_fireplace":"Kamin","furn.sym_plant":"Pflanze","furn.sym_rug":"Teppich","common.yes":"Ja","common.no":"Nein","vac.diag_source":"Quelle","vac.diag_platform":"Integration","vac.diag_status":"Status","vac.diag_position":"Position","vac.diag_rooms":"Räume","vac.diag_rooms_value":"{total} · {matched} Namen stimmen überein · {readiness}","vac.autocal_ready":"Auto-Kalibrierung verfügbar","vac.autocal_not_ready":"3 übereinstimmende Namen erforderlich","vac.diag_path":"Integrationspfad","vac.diag_map":"Karten-ID","vac.source_none":"nicht ausgewählt","vac.source_status_ok":"Bereit","vac.source_status_missing":"Fehlend","vac.source_status_disabled":"In Home Assistant deaktiviert","vac.source_status_unavailable":"Nicht verfügbar","vac.source_status_unverified":"Kann mit den aktuellen Berechtigungen nicht verifizieren","vac.source_status_unsupported":"Keine Positionsdaten","vac.source_status_none":"Keine Quelle","vac.source_banner_missing":"Die gespeicherte Quelle existiert nicht mehr. Sie wurde nicht automatisch ersetzt; wählen Sie eine andere Quelle oder stellen Sie sie in Home Assistant wieder her.","vac.source_banner_disabled":"Die gespeicherte Quelle ist in Home Assistant deaktiviert. Aktivieren Sie sie dort oder wählen Sie eine andere Quelle.","vac.source_banner_unverified":"Die aktuellen Home Assistant-Berechtigungen können diese gespeicherte Quelle nicht verifizieren. Sie bleibt angepinnt und wird nicht automatisch ersetzt.","vac.choose_source":"Quelle wählen","vac.source_auto":"Automatisch","vac.source_auto_hint":"Verwenden Sie eine kompatible Entität von diesem Gerät","vac.all_cameras":"Alle Kameras","vac.all_cameras_warn":"Eine Kamera liefert möglicherweise keine Roboter-Daten. Wählen Sie eine nur, wenn es Ihre Saugroboter-Karte ist.","vac.all_cameras_empty":"Keine anderen Kamera-Entitäten gefunden.","vac.platform_unknown":"unbekannte Integration","vac.cap_position":"Position","vac.cap_rooms_short":"Räume","vac.cap_path":"Pfad","vac.cap_map":"Karten-ID","vac.cap_none":"Keine Roboter-Daten erkannt","vac.xcme_hint":"Aktivieren Sie diese Xiaomi Cloud Map Extractor-Attribute:","vac.documentation":"Dokumentation","vac.residual_title":"Automatische Kalibrierung überprüfen","vac.residual_message":"Die zugeordneten Räume weichen um bis zu {error} voneinander ab. Diese ungefähre Kalibrierung anwenden, manuell verfeinern oder ohne Änderung der gespeicherten Einrichtung abbrechen.","vac.apply_proposal":"Anwenden","gs.backup_group":"Sichern und übertragen","gs.backup_hint":"Laden Sie ein tragbares JSON-Backup herunter oder sehen Sie eine Vorschau und importieren Sie ein Backup, das mit House Plan erstellt wurde.","backup.export_open":"Exportieren","backup.import_open":"Importieren","backup.export_title":"House Plan exportieren","backup.import_title":"House Plan importieren","backup.export_hint":"Wählen Sie, ob das Backup die gesamte House Plan-Konfiguration oder nur den aktuellen Bereich enthalten soll.","backup.full":"Vollständiges Backup","backup.current_space":"Aktueller Bereich","backup.current_space_title":"Aktueller Bereich: {title}","backup.no_current_space":"Kein aktueller Bereich","backup.plan_only":"Nur Plan","backup.plan_only_hint":"Räume, Wände, Öffnungen, Dekor und Raumbezeichnungspositionen ohne Geräte oder Home Assistant-Bindungen beibehalten.","backup.plan_only_preview":"Diese Datei enthält nur den Plan.","backup.privacy_warning":"Das Archiv enthält Namen, Home Assistant-Kennungen und genaue Koordinaten. Interne Pläne und Anhänge werden referenziert, nicht eingebettet; Laufzeitzustände und Staubsaugerspuren sind nicht enthalten.","backup.download":"JSON herunterladen","backup.export_done":"Backup heruntergeladen","backup.reading":"Überprüfe das Backup…","backup.revalidated":"Der Plan wurde nach dieser Vorschau geändert. Die Zusammenfassung wurde aktualisiert; überprüfen Sie sie und bestätigen Sie erneut.","backup.error.support_invalid_message":"Prüfen Sie die Supportnachricht und versuchen Sie es erneut.","backup.error.support_package_too_large":"Das anonymisierte Supportpaket überschreitet das Limit von 8 MiB.","backup.error.support_preview_expired":"Die Vorschau des Supportanhangs ist abgelaufen oder nicht mehr verfügbar.","backup.error.support_rate_limited":"Zu viele Supportberichte oder Vorschauen wurden angefordert. Versuchen Sie es später erneut.","backup.error.support_rejected":"Der Bericht hat die Prüfung des Supportdienstes nicht bestanden.","backup.error.support_unavailable":"Der private Supportdienst ist vorübergehend nicht verfügbar.","backup.error.unauthorized":"Sie haben keine Berechtigung, diesen Plan zu exportieren oder zu importieren.","backup.error.not_ready":"Der Hausplan ist noch nicht fertig. Versuchen Sie es in einem Moment erneut.","backup.error.too_large":"Das Backup überschreitet das 8-MiB-Limit.","backup.error.invalid_json":"Die ausgewählte Datei ist kein gültiges JSON.","backup.error.invalid_format":"Die ausgewählte Datei ist kein House Plan-Backup.","backup.error.invalid_image":"Das Bild ist beschädigt oder entspricht nicht seinem Format.","backup.error.unsupported_export_version":"Dieses Backup-Format wird von der installierten Version nicht unterstützt.","backup.error.unsupported_image":"Verwenden Sie ein unterstütztes PNG-, JPEG-, WebP- oder SVG-Bild.","backup.error.future_model":"Das Backup wurde mit einem neueren House-Plan-Datenmodell erstellt.","backup.error.invalid_config":"Das Backup enthält eine ungültige House-Plan-Konfiguration.","backup.error.wall_model_migration_blocked":"Das Backup-Wandmodell konnte nicht sicher aktualisiert werden. Optimieren Sie zuerst den Quellplan und exportieren Sie ihn dann erneut.","backup.error.invalid_layout":"Das Backup enthält ungültige Objektpositionen.","backup.error.invalid_content":"Das Backup enthält ungültige oder inkonsistente Inhaltsreferenzen.","backup.error.space_not_found":"Der ausgewählte Bereich existiert nicht mehr.","backup.error.capacity_exceeded":"Durch das Hinzufügen dieses Backups würden die Planlimits überschritten.","backup.error.preview_expired":"Die Vorschau ist abgelaufen. Wählen Sie die Backup-Datei erneut aus.","backup.error.preview_owner_mismatch":"Diese Vorschau gehört zu einem anderen Home-Assistant-Benutzer.","backup.error.conflict":"Der Plan hat sich nach der Vorschau geändert. Überprüfen Sie die aktualisierte Zusammenfassung.","backup.error.content_confirmation_required":"Bestätigen Sie, dass nicht verfügbare lokale Inhalte getrennt werden können.","backup.error.commit_failed":"Das Backup konnte nicht sicher angewendet werden. Der vorherige Plan wurde wiederhergestellt oder wartet auf die Wiederherstellung.","backup.error.missing_plan":"Eine referenzierte Plan-Datei ist nach der Vorschau verschwunden. Überprüfen Sie das Backup erneut.","backup.error.missing_content":"Ein referenziertes lokales Anhangselement ist nach der Vorschau verschwunden. Überprüfen Sie das Backup erneut.","backup.error.marker_control_missing":"Ein verknüpftes Planlicht fehlt im Backup.","backup.error.marker_control_not_light":"Ein verknüpftes Planziel ist nicht mehr als Lichtquelle markiert.","backup.error.marker_control_self":"Eine Lichtquelle kann sich nicht selbst steuern.","backup.error.marker_control_cycle":"Das Backup enthält eine kreisförmige Kette von Lichtsteuerungen.","backup.error.duplicate_marker_control":"Das Backup enthält eine doppelte Plan-Licht-Verknüpfung.","backup.error.no_backup":"Es gibt keinen Import- oder Optimierungssnapshot zur Wiederherstellung.","backup.error.in_use":"Das Element wird noch verwendet","backup.error.invalid_data":"Die Anfrage enthält ungültige Daten","backup.error.invalid_light_entity":"Das führende Licht muss eine light.*- oder switch.*-Entität sein","backup.error.invalid_marker_control":"Ungültige Marker-Steuerungsreferenz","backup.error.invalid_name":"Der Name ist ungültig","backup.error.invalid_partition_opening_host":"Die Öffnung muss ihren Trennwand-Träger behalten","backup.error.invalid_partition_opening_jamb_margin":"Die Öffnung lässt keinen physischen Pfosten am Wandende","backup.error.invalid_passage_fields":"Ein offener Durchgang kann keine Tür-Einstellungen tragen","backup.error.invalid_space_id":"Unbekannter Raumbereich","backup.error.invalid_toggle_entity":"Die Schalt-Entität muss light.* oder switch.* sein","backup.error.invalid_value_badge":"Ungültige Wert-Badge-Einstellungen","backup.error.invalid_value_badge_attribute":"Ungültiges Wert-Badge-Attribut","backup.error.invalid_value_badge_position":"Ungültige Wert-Badge-Position","backup.error.invalid_value_badge_source":"Ungültige Wert-Badge-Quelle","backup.error.invalid_vacuum_map_route":"Prüfen Sie die Zuordnung der Roboterkarten zu Räumen.","backup.error.invalid_value_source":"Ungültige Wertquelle","backup.error.invalid_value_source_attribute":"Ungültiges Wertquellen-Attribut","backup.error.io_error":"Eine Dateioperation auf dem Server ist fehlgeschlagen","backup.error.not_toggleable":"Dieses Gerät kann nicht geschaltet werden","backup.error.nothing_to_repair":"Nichts zu reparieren","backup.error.space_in_use":"Der Raumbereich wird noch referenziert","backup.error.value_badge_source_required":"Das Wert-Badge braucht eine Quelle","backup.error.wall_model_client_outdated":"Der Plan wurde anderswo aktualisiert — Seite neu laden","backup.same_source":"Erstellt auf dieser Home Assistant-Instanz","backup.foreign_source":"Erstellt auf einer anderen Home Assistant-Instanz","backup.created":"Erstellt: {value}","backup.versions":"Karte {card}; Integration {integration}; Datenmodell {model}","backup.count_spaces":"Bereiche: {n}","backup.count_rooms":"Räume: {n}","backup.count_walls":"Wände: {n}","backup.count_openings":"Öffnungen: {n}","backup.count_decor":"Dekorationsobjekte: {n}","backup.count_markers":"Geräte: {n}","backup.count_layout":"Positionen: {n}","backup.bindings":"Verknüpfungen — Geräte: {device}, Entitäten: {entity}, virtuell: {virtual}; Positionen ohne Bereich: {legacy}","backup.binding_status":"Zielstatus — aktiv: {active}, deaktiviert: {disabled}, fehlt: {missing}","backup.missing_areas":"Auf dem Ziel fehlende Bereiche: {areas}","backup.dropped_marker_links":"Planlicht-Verknüpfungen außerhalb dieses übertragenen Bereichs wurden ausgelassen: {n}.","backup.room_drafts_migrated":"Alte unvollständige Konturen wurden in normale Wände umgewandelt: {drafts}; Wandsegmente: {segments}.","backup.repaired_target_refs":"Durch den Import dieses Bereichs wiederhergestellte vorhandene Referenzen: {n}.","backup.preserved_unresolved_refs":"Referenzen, die nicht eindeutig wiederhergestellt werden konnten, wurden beibehalten: {n}.","backup.preserved_unresolved_hint":"Es wurden keine Daten geraten oder gelöscht. Führen Sie nach dem Import Optimierungspläne aus, um die verbleibenden Referenzen zu überprüfen.","backup.import_details":"Importieren von Referenzdetails","backup.import_detail.incoming_remapped":"Referenzen innerhalb der importierten Kopie aktualisiert: {n}","backup.import_detail.target_repaired":"Vorhandene Referenzen wiederhergestellt: {n}","backup.import_detail.preserved_unresolved":"Unaufgelöste Referenzen beibehalten: {n}","backup.import_detail.collisions":"Zielkonflikte sicher beibehalten: {n}","backup.import_detail.dropped_links":"Eingehende Links durch Übertragungsregeln ausgelassen: {n}","backup.import_detail.bounded_lineages":"Übermäßig verschachtelte Kennungen begrenzt belassen: {n}","backup.replace_warning":"Dies ersetzt die aktuelle Konfiguration und das Layout. Hochgeladene Dateien werden niemals gelöscht. Eine Rückgängig-Möglichkeit bleibt bis zur nächsten Planbearbeitung verfügbar.","backup.foreign_bookkeeping":"Instanzspezifische bekannte/neue Gerätebuchführung wird nicht importiert.","backup.final_name":"Name des neuen Bereichs","backup.target_settings":"Die globalen Einstellungen der Zielinstanz bleiben unverändert.","backup.duplicates":"Bindungen bereits vorhanden: {n}","backup.skip":"Doppelte Geräte überspringen","backup.virtual_copy":"Sichere statische virtuelle Kopien hinzufügen","backup.content":"Referenzierter Inhalt","backup.decor_images_summary":"Eigene Bilder: {objects} Objekte, {assets} Dateien; fehlende Dateien: {missing}.","backup.content_available":"lokal verfügbar","backup.content_external":"externer Link","backup.content_detach_required":"wird getrennt","backup.confirm_detach":"Ich verstehe, dass nicht verfügbare interne Pläne und Anhänge von der importierten Konfiguration getrennt werden.","backup.confirm_missing_images":"Ich verstehe, dass fehlende eigene Bilder als reparierbare Platzhalter erhalten bleiben und andere nicht verfügbare lokale Dateien getrennt werden.","backup.replace":"Ersetzen","backup.add":"Bereich hinzufügen","backup.space_done":"Bereich importiert: {rooms} Räume, {markers} Geräte, {refs} bestehende Referenzen wiederhergestellt","backup.full_done":"Backup wiederhergestellt: {spaces} Bereiche, {rooms} Räume, {markers} Geräte","backup.undo_import":"Letzten vollständigen Import rückgängig machen","backup.import_undone":"Vollständiger Import rückgängig gemacht","backdrop.large_title":"Großes Bild","backdrop.large_body":"Dieses Bild ist {w}×{h} ({fileMb} MB Datei) und benötigt etwa {decodedMb} MB Speicher zur Anzeige. Auf Tablets kann das die Seite zum Absturz bringen.","backdrop.unknown_body":"Die Bildabmessungen konnten nicht gelesen werden — die Datei ist möglicherweise beschädigt. Fortfahren kann die Seite auf Tablets zum Absturz bringen.","backdrop.reduced_dimensions":"Verkleinerte Kopie: {w}×{h} px.","backdrop.use_downscaled":"Verkleinerte Kopie hochladen","backdrop.reducing":"Wird verkleinert…","backdrop.keep_original":"Original behalten","backdrop.too_large_title":"Bild ist zu groß","backdrop.too_large_body":"Dieses Bild überschreitet die Anzeigegrenzen des Browsers ({w}×{h}, Limit {limit} px pro Seite). Bitte verkleinern Sie es in einem Desktop-Editor und laden Sie es erneut hoch.","backdrop.downscale_failed":"Die verkleinerte Kopie konnte nicht erstellt werden. Der aktuelle Plan wurde nicht geändert."};const n="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";export{e as dictionary,n as fingerprint};
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";var e={"editor.context_actions":"Aktionen: {object}","editor.tool_options":"Werkzeugoptionen: {tool}","editor.palette":"Palette: {tool}","editor.open_group":"Werkzeuggruppe: {group}","editor.group_active":"{group} — aktiv: {item}","editor.disabled_action":"{action} ist nicht verfügbar: {reason}","editor.loading":"Editor wird geladen…","editor.loading_aria":"Der Plan-Editor wird geladen","editor.load_failed":"Der Editor konnte nicht geladen werden.","editor.refresh_advice":"Seite aktualisieren und erneut versuchen.","editor.retry_advice":"Verbindung prüfen und erneut drücken.","version_mismatch.title":"Die House Plan-Versionen stimmen nicht überein","version_mismatch.body":"Falls Home Assistant noch neu startet, warten Sie den Abschluss ab und laden Sie dann diese Seite neu.","version_mismatch.frontend":"Karte","version_mismatch.backend":"Integration","version_mismatch.reload":"Seite neu laden","color_picker.title":"Farbwähler","color_picker.hue":"Farbton","color_picker.saturation":"Sättigung","color_picker.value":"Helligkeit","color_picker.hex":"Hex-Farbe","color_picker.invalid_hex":"Geben Sie eine 3- oder 6-stellige Hex-Farbe ein","color_picker.confirm":"OK","btn.properties":"Eigenschaften","btn.keep_as_walls":"Als Wände behalten","btn.delete_room_keep_walls":"Raum löschen, Wände behalten","btn.delete_room_with_walls":"Raum und Wände löschen","title.markup_select":"Wände und Säulen auswählen und bearbeiten","title.markup_column":"Säule: Klicken Sie auf einen Rasterpunkt, um eine quadratische Säule zu platzieren","markup.partition":"Trennwand","markup.column":"Säule","markup.hint_column":"Klicken Sie auf einen Rasterpunkt, um eine quadratische Säule zu platzieren","history.wall_segment":"Wandsegment hinzufügen","history.column_add":"Säule hinzufügen","history.physical_edit":"Physisches Objekt ändern","history.physical_delete":"Physisches Objekt löschen","history.physical_move":"Physisches Objekt verschieben","history.wall_face_batch":"Räume aus Wänden erstellen","toast.column_duplicate":"Eine Säule mit demselben Zentrum und äußerer Größe existiert bereits","physical.partition_properties":"Eigenschaften der Trennwand","physical.column_properties":"Eigenschaften der Säule","physical.shape":"Form","physical.square":"Quadrat","physical.circle":"Kreis","physical.diameter":"Durchmesser","physical.side":"Seite","physical.rotation":"Drehwinkel","physical.length":"Länge","physical.allowed_range":"Erlaubt: {min}–{max} {unit}","physical.column_size_title":"Außenmaß der per Klick platzierten quadratischen Säule (1–150 cm).","card.title":"Hausplan","count.devices":"{n} Entwicklung","empty.no_spaces":"Noch keine Bereiche.","empty.add_first":"Ersten Bereich hinzufügen und einen Grundriss hochladen.","empty.install":"Installieren Sie die House Plan-Integration und fügen Sie sie unter „Geräte & Dienste“ hinzu.","btn.add_space":"Bereich hinzufügen","btn.cancel":"Abbrechen","btn.save":"Speichern","btn.close":"Schließen","btn.delete":"Löschen","btn.copy":"Kopieren","btn.edit":"Bearbeiten","btn.open_in_ha":"In HA öffnen","btn.reset":"Zurücksetzen","btn.attach":"Anhängen…","btn.upload":"Hochladen…","btn.replace":"Ersetzen…","title.zoom_in":"Zoomen","title.zoom_out":"Herauszoomen","title.zoom_fit":"Alles anpassen","title.configure_space":"Bereich konfigurieren","title.add_space":"Bereich hinzufügen","title.markup_add":"Wände: eine durchgehende Kette zeichnen; jedes bestätigte Segment wird einzeln gespeichert. Umschalt sperrt auf 45°","title.markup_merge":"Zusammenführen: Klicken Sie auf einen Raum und dann auf den Nachbarraum, mit dem er eine Wand teilt","title.markup_split":"Raum teilen: Klicken Sie auf den Raum und dann auf zwei Punkte an seinen Wänden","title.markup_delroom":"Raum löschen: Klicken Sie in einen Raum und bestätigen Sie","title.need_plan":"Einen Grundriss hochladen","markup.add":"Wände","markup.merge":"Zusammenführen","markup.split":"Teilen","markup.resize":"Größe ändern","title.markup_resize":"Räume vergrößern/verkleinern: Ziehen Sie einen verfügbaren horizontalen oder vertikalen Wandgriff","markup.hint_resize":"Ziehen Sie einen verfügbaren Wandgriff · die Wand stoppt an der ersten unsicheren Position · Esc bricht ab · Strg+Z — rückgängig","resize.disabled.diagonal":"Diese Wand ist geneigt; Größe ändern unterstützt nur horizontale und vertikale Wände","resize.disabled.side-angle":"Eine angrenzende Wand ist geneigt; Größe ändern erfordert, dass beide angrenzenden Wände diese Wand im rechten Winkel treffen","resize.disabled.duplicate-physical-wall":"Eine separate Trennwand oder ein Pfeiler überlappt diese Wand; entfernen oder verschieben Sie sie, bevor Sie die Größe ändern","resize.disabled.partial-shared":"Ein angrenzender Raum nutzt nur einen Teil dieser Wand, daher kann sie nicht sicher als gemeinsame Wand verschoben werden","resize.disabled.unequal-shared":"Der angrenzende Raum nutzt andere Endpunkte oder Wandlängen, daher können die Wände nicht gemeinsam sicher bewegt werden","resize.disabled.multiple-rooms":"Das Verschieben dieser Wand würde mehr als zwei Räume betreffen","resize.disabled.thickness-conflict":"Die Wandstärke kann nicht sicher beibehalten werden","resize.disabled.opening-conflict":"Eine Öffnung an dieser Wand kann nicht sicher verschoben werden","resize.disabled.invalid-geometry":"Diese Wand kann nicht ohne Änderung der Planstruktur geändert werden","resize.limit_stopped":"Wand gestoppt: der nächste Schritt würde ein Anschlusslimit verletzen","resize.commit_failed":"Größenänderung wurde abgebrochen, da der endgültige Plan die Geometrieprüfung nicht bestanden hat","resize.preview_failed":"Größenänderung am letzten sicheren Punkt gestoppt, da die Plan-Geometrie nicht beibehalten werden konnte","markup.opening":"Öffnung","markup.delete_room":"Raum löschen","history.undo":"Rückgängig","history.redo":"Wiederholen","history.undo_named":"Rückgängig: {name} (Strg+Z)","history.redo_named":"Wiederholen: {name} (Strg+Shift+Z / Strg+Y)","history.undo_empty":"Nichts zu widerrufen","history.redo_empty":"Nichts zu wiederholen","history.undone":"Rückgängig gemacht: {name}","history.redone":"Wiederholt: {name}","history.add_room":"Raum erstellen","history.split_room":"Raum teilen","history.merge_rooms":"Räume zusammenführen","history.resize_room":"Raumgröße ändern","history.wall_thickness":"Wandstärke ändern","history.add_opening":"Tür- oder Fensteröffnung hinzufügen","history.edit_opening":"Öffnung bearbeiten","history.move_opening":"Öffnung verschieben","history.delete_opening":"Öffnung löschen","history.delete_room_keep_walls":"Raum löschen, Wände behalten","history.delete_room_with_walls":"Raum und Wände löschen","history.decor_add":"Dekorobjekt hinzufügen","history.decor_edit":"Dekorobjekt bearbeiten","history.decor_move":"Dekorobjekt verschieben","history.decor_transform":"Dekorobjekt transformieren","history.decor_delete":"Dekorobjekt löschen","history.backdrop_transform":"Plan-Hintergrund transformieren","history.device_move":"{name} verschieben","history.device_stale":"Der Positionsverlauf ist nicht mehr anwendbar und wurde gelöscht","opening.new":"Neue Öffnung","opening.edit":"Öffnung","opening.door":"Tür","opening.window":"Fenster","opening.gate":"Tor","opening.passage":"Offener Durchgang","opening.passage_binding_warning":"Das Speichern entfernt den Öffnungs-/Schließsensor und das Schloss.","opening.invalid_passage_fields":"Der offene Durchgang auf dem Plan „{room}“ hat nicht unterstützte Einstellungen: {fields}.","opening.type_label":"Typ","opening.length_label":"Länge, cm","opening.contact_label":"Öffnungs-/Schließsensor","opening.lock_label":"Schloss","opening.none":"— keine —","opening.search_ph":"Suche: Name oder Entitäts-ID…","opening.invert":"Geöffnet/geschlossen invertieren","opening.flip_h":"Scharnier an der anderen Zarge","opening.flip_v":"Öffnet zur anderen Seite","opening.open":"Offen","opening.closed":"Geschlossen","opening.locked":"Verriegelt","opening.unlocked":"Entriegelt","opening.state_unknown":"nicht verfügbar","opening.no_entities":"Keine Sensoren gebunden — ein statisches Symbol auf dem Plan.","toast.opening_no_wall":"Neben eine Raumwand oder eine unabhängige Wand klicken","opening.host_partition":"Unabhängige Wand","opening.partition_orphan":"Die unabhängige Wand für diese Öffnung existiert nicht mehr","opening.partition_jamb_margin":"Mindestens {distance} zwischen der Öffnung und dem Wandende lassen","opening.rebind_partition":"An eine andere unabhängige Wand anfügen","confirm.delete_partition_openings_title":"Wand und Öffnungen löschen?","confirm.delete_partition_openings_body":"Diese Wand enthält {count} Öffnung(en). Sie werden zusammen gelöscht.","confirm.delete_partition_openings_item":"• {type}, {length}","markup.hint_points":"Punkte: {n} · Shift — 45° Schritte · Esc — Kette beenden · Ctrl+Z — Punkt rückgängig machen · Schließen eines Bereichs erstellt einen Raum","markup.hint_start":"Klicken Sie auf einen Rasterpunkt, um eine Wandkette zu starten","tip.lqi":"durchschnittliches Zigbee-Signal:","tip.area":"Bereich: {value}","info.device_header":"Gerät im Plan","info.model":"Modell","info.state":"Status","info.link":"Verbindung","info.manuals":"Handbücher","info.none":"Keine zusätzlichen Informationen","marker.new_device":"Neues Gerät","marker.name_label":"Name (im Plan angezeigt)","marker.name_ph":"Name","marker.binding_label":"An ein HA-Gerät binden","marker.binding_disabled":"in Home Assistant deaktiviert","marker.virtual_option":"Virtuelles Gerät (keine Bindung)","marker.search_ph":"Gerät/Gruppe suchen…","marker.nothing_found":"Nichts gefunden","marker.room_label":"Raum","marker.room_override":" (Platzierung überschreiben)","marker.room_choose":"— Raum auswählen —","marker.room_auto":"— nach Gerätebereich (auto) —","marker.icon_label":"Symbol","marker.icon_ph":"mdi:… (leer = automatisch)","marker.display_label":"Anzeige","display.badge":"Symbol + Zustand","display.icon_ripple":"Symbol + Zustand und Aktivität","display.static_icon":"Immer statisches Symbol","marker.display_hint_badge":"Das Symbol und die dynamische Platte zeigen den Gerätezustand ohne den üblichen Aktivitätspuls. Rote Alarme bleiben sichtbar.","marker.display_hint_icon_ripple":"Das Symbol, die dynamische Platte und der Puls zeigen einen kurzen Puls für Ereignisse und einen kontinuierlichen Puls für Arbeit, Bewegung oder Anwesenheit. Rote Alarme haben eine separate Priorität.","marker.display_hint_value":"Ein ausgewählter oder automatisch ermittelter Home Assistant-Wert ersetzt das Symbol, während die Platte weiterhin den Zustand anzeigt. Rote Alarme bleiben sichtbar.","marker.display_hint_static_icon":"Die themenabhängige Hülle und das Symbol bleiben immer gleich. Zustand, Aktivität, Nichtverfügbarkeit und Alarme verändern nicht das Erscheinungsbild.","marker.static_alarm_warning":"Dieses Gerät kann Alarme melden. Die statische Anzeige verbirgt die visuelle Alarmanzeige des Markers.","marker.preview.title":"Anzeigevorschau","marker.preview.actual":"Jetzt","marker.preview.example":"Beispiel","marker.preview.integration":"Bereitgestellt von","marker.preview.source":"Anzeigquelle","marker.preview.current_state":"Aktueller Zustand","marker.preview.result":"Auf dem Plan","marker.preview.details":"Quelldetails","marker.preview.select_source":"Ein Home-Assistant-Gerät oder eine Entität auswählen, um die tatsächliche Anzeige zu sehen.","marker.preview.unknown_provider":"Unbekannte Integration","marker.preview.virtual_provider":"House Plan · virtuelles Gerät","marker.preview.no_source":"Keine aktive Quelle","marker.preview.no_state":"Kein aktueller Zustand","marker.preview.mixed_states":"Mehrere verschiedene Zustände","marker.preview.multiple_sources":"{n}-Quellen","marker.preview.more_sources":"+{n} mehr","marker.preview.scaled":"Die Vorschau wird auf {n}% skaliert, um zu passen. Die gespeicherte Größe bleibt unverändert.","marker.preview.demo_short":"Kurze Aktivität anzeigen","marker.preview.demo_continuous":"Kontinuierliche Aktivität anzeigen","marker.preview.stop_continuous":"Kontinuierliche Aktivität stoppen","marker.preview.demo_short_notice":"Kurzes Aktivitätsbeispiel; der tatsächliche Gerätezustand bleibt unverändert.","marker.preview.demo_continuous_notice":"Kontinuierliches Aktivitätsbeispiel; der tatsächliche Gerätezustand bleibt unverändert.","marker.preview.demo_already_visible":"Der aktuelle Zustand zeigt bereits eine echte Aktivitäts- oder Alarmeffekt.","marker.preview.reduced_motion":"Systemweit reduzierte Bewegungen sind aktiviert, daher wird gewöhnliche Aktivität als Punkt angezeigt.","marker.preview.reason.neutral":"Neutrale dunkle Platte","marker.preview.reason.working":"Gelbe Platte: Das Gerät arbeitet jetzt","marker.preview.reason.working_activity":"Gelbe Platte und Aktivitätseffekt: das Gerät funktioniert jetzt","marker.preview.reason.open":"Orange Platte: physisch geöffnet oder entriegelt","marker.preview.reason.cover_icon_state":"Neutrale Platte; die Abdeckungseinheit steuert den angezeigten Zustand und das Symbol","marker.preview.reason.presence":"Aktivitätseffekt, während Präsenz erkannt wird","marker.preview.reason.event":"Kurzer Aktivitätseffekt nach einem erkannten Ereignis","marker.preview.reason.transition":"Aktivitätseffekt, während das Gerät sich bewegt oder den Zustand ändert","marker.preview.reason.media_neutral":"Mediengeräte bleiben im verfügbaren Zustand auf einer neutralen dunklen Platte","marker.preview.reason.unavailable":"Gedämpfte neutrale Platte: nicht verfügbar oder ausgeschaltet","marker.preview.reason.alarm":"Rote Alarmplatte; Alarmanzeige wird immer angezeigt","marker.preview.reason.live_states_disabled":"Live-Zustandsstil ist für diese Karte deaktiviert","marker.preview.reason.value_no_state":"Kein nutzbarer Zustandswert; stattdessen wird das Symbol angezeigt","marker.preview.reason.value_ambiguous_sources":"Mehrere mögliche Wertequellen; stattdessen wird das Symbol angezeigt","marker.preview.reason.value_non_scalar":"Die Quelle lieferte keinen einfachen Wert; stattdessen wird das Symbol angezeigt","marker.preview.reason.value_virtual":"Ein virtuelles Gerät hat keinen Home Assistant-Wert; stattdessen wird das Symbol angezeigt","marker.preview.reason.vacuum_live_plan_only":"Echtzeitposition und -spur des Staubsaugers sind nur im vollständigen Plan verfügbar","marker.preview.reason.hidden_design_preview":"Das Gerät ist im Plan ausgeblendet; diese Designvorschau bleibt sichtbar","marker.preview.reason.composite_power_source":"Der Status stammt vom Power-Entity des Geräts; Hilfsschalter werden ignoriert","marker.preview.reason.activity_display_disabled":"Der gewählte Anzeigemodus zeigt gewöhnliche Aktivitätseffekte nicht an","marker.preview.reason.ha_disabled":"Die Home Assistant-Verbindung ist deaktiviert und wird im Plan ausgeblendet","marker.preview.reason.orphaned":"Die gespeicherte Home Assistant-Verbindung konnte nicht mehr gefunden werden","marker.preview.reason.static_icon":"Statischer Modus: Der Gerätestatus ändert das Symbol nicht","marker.activity_color":"Aktivitätspulsfarbe","marker.ripple_size":"Aktivitätspulsgröße","marker.activity_alarm_note":"Farbe und Größe betreffen nur gewöhnliche Aktivität und ändern keine roten Alarme.","marker.pulse_a11y_alarm":"Alarm","marker.pulse_a11y_event":"Kürzliches Ereignis","marker.pulse_a11y_presence":"Anwesenheit erkannt","marker.pulse_a11y_transition":"Statusänderung","marker.pulse_a11y_running":"Arbeitet","marker.state_a11y_neutral":"Standardzustand","marker.state_a11y_working":"Funktionierend","marker.state_a11y_open":"Offen","marker.state_a11y_locked":"Verschlossen","marker.state_a11y_unlocked":"Entriegelt","marker.state_a11y_alarm":"Alarm","marker.state_a11y_unavailable":"Nicht verfügbar","marker.lqi_a11y_low":"LQI {value}, schwaches Signal","marker.lqi_a11y_mid":"LQI {value}, mittleres Signal","marker.lqi_a11y_high":"LQI {value}, starkes Signal","marker.size_label":"Symbolgröße / Drehung","marker.angle_label":"Drehen","marker.model_label":"Modell","marker.model_ph":"z.B. Aqara T&H","marker.link_label":"Link","marker.desc_label":"Beschreibung","marker.desc_ph":"Notizen, Spezifikationen…","marker.manuals_label":"Handbücher (PDF usw.)","marker.sub_device":"Gerät","marker.sub_z2m_group":"· Z2M Gruppe","marker.sub_group":"Gruppe","marker.sub_helper":"Helfer","space.new":"Neuer Bereich","space.copy_title":"Bereich kopieren","space.copy_name":"Name des neuen Bereichs","space.copy_fallback":"Bereich","space.copy_create":"Kopie erstellen","space.copy_optimize_title":"Vor dem Kopieren optimieren?","space.copy_optimize_body":"Vor dem Erstellen von „{name}“ muss House Plan den gesamten Plan einschließlich anderer Bereiche optimieren. Fortfahren?","space.copy_optimize_confirm":"Optimieren und kopieren","space.copy_error_changed":"Der Plan wurde während der Bestätigung geändert. Bitte prüfen und erneut versuchen.","space.copy_error_source_missing":"Der Quellbereich existiert nicht mehr. Öffnen Sie seine Einstellungen erneut.","space.copy_error_source_invalid":"House Plan konnte nicht alle Wände dieses Bereichs prüfen. Korrigieren Sie den Quellbereich.","space.copy_error_spaces_limit":"House Plan enthält bereits die maximale Anzahl an Bereichen.","space.copy_error_partitions_limit":"Dieser Bereich enthält zu viele Wände zum Kopieren.","space.copy_error_openings_limit":"Dieser Bereich enthält zu viele Öffnungen zum Kopieren.","space.copy_error_decor_limit":"Dieser Bereich enthält zu viele Hintergrundobjekte zum Kopieren.","space.copy_error_columns_limit":"Dieser Bereich enthält zu viele Säulen zum Kopieren.","space.copy_error_opening_host":"Eine Öffnung ist keiner Wand mehr zugeordnet. Korrigieren oder löschen Sie sie vor dem Kopieren.","space.copy_error_geometry":"Die Kopie würde eine unsichere Wandgeometrie erzeugen. Korrigieren Sie den Quellbereich.","space.copy_error_optimize_geometry":"Das Kopieren wurde gestoppt, weil die Optimierung des gesamten Plans für einen Bereich unsicher ist.","space.header":"Bereich","space.title_label":"Titel","space.title_ph":"z.B. Garage","space.plan_label":"Grundriss (Hintergrund)","space.no_plan":"Kein Planbild","space.plan_alt":"Grundriss","room.new":"Neuer Raum","room.name_label":"Anzeigename","room.name_ph":"z.B. Terrasse","room.area_label":"Home Assistant Bereich (nicht zugewiesen)","room.no_area_option":"— kein Bereich —","room.default_name":"Raum","device.unnamed":"unbenannt","device.light_group":"Lichtgruppe","device.fallback":"Gerät","device.virtual":"Virtuelles Gerät","confirm.delete_room_title":'Raum "{name}" löschen?',"confirm.delete_room_body":"Festlegen, ob die ausschließlich zu diesem Raum gehörenden physischen Wände erhalten bleiben. Mit einem anderen Raum geteilte Wände bleiben immer erhalten.","confirm.remove_marker_title":"Gerät aus dem Plan löschen?","confirm.remove_marker_body":"Das Gerät verschwindet vollständig und trägt nicht mehr zu den Plandaten bei. Es kann später erneut hinzugefügt werden.","confirm.erase_decor":"Das Objekt „{kind}“ löschen? Diese Aktion kann im Editor rückgängig gemacht werden.","confirm.delete_space_title":"Bereich löschen?","confirm.delete_space_body":"Der Bereich, alle seine Räume und die gesamte Planmarkierung werden gelöscht.","confirm.delete_space_vac_routes":"Zuordnungen von Roboterkarten werden ebenfalls entfernt: {count}.","space.delete_blocked":"Dieser Bereich wird noch von {n} Gerät(en) verwendet. Die Geräte zuerst in einen anderen Bereich verschieben oder löschen.","toast.pos_save_failed":"Position nicht gespeichert: {err}","toast.no_entity":"Das Gerät hat keine geeignete Entität","toast.ha_disabled_action":"Ein deaktiviertes Home Assistant-Objekt kann im Plan nicht verwendet werden.","toast.ha_disabled_show_device":"Ein in Home Assistant deaktiviertes Gerät kann im Plan nicht angezeigt werden. Aktivieren Sie es zuerst in Home Assistant.","toast.ha_disabled_show_entity":"Eine in Home Assistant deaktivierte Entität kann im Plan nicht angezeigt werden. Aktivieren Sie sie zuerst in Home Assistant.","toast.ha_disabled_add":"Ein deaktiviertes Home Assistant-Objekt kann nicht dem Plan hinzugefügt werden. Aktivieren Sie es zuerst in Home Assistant.","toast.ha_binding_unverified":"Der Status des Objekts konnte über das Home Assistant-Register nicht überprüft werden. Anzeige und Aktionen sind vorübergehend nicht verfügbar.","toast.markup_needs_server":"Markup ist verfügbar, nachdem die Konfiguration auf den Server verschoben wurde.","toast.space_order_changed":"Reihenfolge geändert. Wenn eine Karte ihr Stockwerk nach Nummer festlegt, überprüfen Sie diese Paneele.","toast.conflict":"Die Konfiguration wurde in einem anderen Fenster geändert — Daten aktualisiert, wiederholen Sie Ihre letzte Aktion.","toast.cfg_save_failed":"Speichern der Konfiguration fehlgeschlagen: {err}","toast.room_overlap":"Die Umrisse überlappen den Raum „{name}“ — Räume dürfen sich nicht überlappen","toast.contour_cannot_close":"Die Kontur kann nicht geschlossen werden, da sie entartet ist oder sich selbst schneidet","toast.merge_not_adjacent":"Es können nur Räume zusammengeführt werden, die eine Wand teilen","toast.rooms_merged":"Räume zu „{name}“ zusammengeführt","toast.split_pick_wall":"Beginnen Sie den Schnitt an der Wand des Raumes","toast.split_bad_cut":"Der Schnitt muss wand-zu-wand innerhalb des Raumes verlaufen, ohne Wände oder sich selbst zu kreuzen","merge.header":"Räume zusammenführen","merge.hint":"Der zusammengeführte Raum behält einen Namen und eine Fläche. Die andere Fläche wird freigegeben — ihre Geräte verlassen den Plan, bis ein anderer Raum sie beansprucht.","merge.keep":"Behalten","merge.no_area":"keine Fläche","toast.room_saved":"Raum gespeichert ({n}). Hinzugefügte Geräte: {added}. Zeichnen Sie die nächste Kontur oder verlassen Sie die Markierung.","toast.room_saved_no_area":"Raum gespeichert ({n}, keine Fläche). Zeichnen Sie die nächste Kontur oder verlassen Sie die Markierung.","toast.marker_needs_server":"Die Gerätebearbeitung ist verfügbar, nachdem die Konfiguration auf den Server verschoben wurde","toast.virtual_name_required":"Einen Namen für das virtuelle Gerät eingeben","toast.marker_saved":"Gerät gespeichert","toast.marker_removed":"Gerät aus dem Plan gelöscht","toast.integration_missing":"Die House Plan-Integration ist nicht installiert — Verwaltung nicht verfügbar","toast.plan_formats":"Unterstützte Formate: SVG, PNG, JPG, WebP","toast.plan_required":"Grundriss hochladen — erforderlich","toast.space_added_onboard":"Bereich hinzugefügt. Räume einzeichnen: Rasterpunkte anklicken und die Kontur schließen.","toast.space_added":"Bereich hinzugefügt","toast.space_copied":"Bereich „{name}“ erstellt","toast.space_saved":"Bereich gespeichert","toast.space_deleted":"Bereich gelöscht","toast.delete_failed":"Löschen fehlgeschlagen: {err}","toast.error":"Fehler: {err}","toast.toggle_target_unavailable":"Ziel „{name}“ ist nicht verfügbar — keine Aktion durchgeführt","toast.toggle_targets_unavailable":"Ziele nicht verfügbar: {names}. Keine Aktion durchgeführt","toast.file_failed":'Datei "{name}" wurde nicht hochgeladen: {err}',"toast.files_attached":"Dateien angehängt: {n}","err.unknown":"unbekannter Fehler","err.code":"Code {code}","err.too_large":"Datei größer als {mb} MB","err.bad_ext":"nicht unterstützter Typ (PDF/Bild erwartet)","err.unauthorized":"Administratorrechte erforderlich","editor.title":"Titel","editor.default_floor":"Anfangsbereich","editor.default_floor_missing":"Anfangsbereich „{id}“ existiert nicht mehr. Wählen Sie einen anderen Bereich.","editor.floor":"Fester Bereich","editor.floor_none":"— nicht fest —","editor.floor_index":"YAML-Index {index} (beibehalten)","fixed_floor.loading":"Lade den festen Bereich…","fixed_floor.invalid_title":"Der feste Bereich ist nicht verfügbar","fixed_floor.invalid_body":"Überprüfen Sie die Etage in der Kartenkonfiguration. Der konfigurierte Wert ist: {value}","editor.icon_size":"Symbolgröße, % der Planbreite","editor.show_temperature":"Temperatur anzeigen","editor.live_states":"Live-Zustände (ein/aus, offen…)","editor.light_pools":"Lichtkegel und Wandschatten","editor.show_signal":"Zigbee-Signal anzeigen (LQI)","editor.language":"Schnittstellensprache","editor.lang_auto":"Automatisch (HA-Profil)","title.icon_rules":"Symbolregeln: welche MDI-Symbole Geräte nach Namen erhalten","rules.title":"Symbolregeln","rules.hint":'Regeln werden von oben anhand von "Gerätename + Modell" (Großschreibungs-unempfindliches Regex) überprüft; das erste Match gewinnt. Wenn nichts übereinstimmt, entscheidet die Entität-Geräteklasse, dann das generische Chip-Symbol.',"rules.pattern_ph":"regex, z. B. Stecker|Steckdose","rules.icon_ph":"mdi:power-socket-de","rules.add":"Regel hinzufügen","rules.reset":"Zurücksetzen auf Standardeinstellungen","rules.test_ph":"Versuch mal einen Gerätenamen...","rules.invalid":"ungültiges regex","rules.saved":"Icon-Regeln gespeichert","btn.up":"Nach oben","btn.down":"Nach unten","tap.info":"Gerätekarte","tap.more_info":"HA Mehr-Info-Dialog","tap.toggle":"Zustand umschalten","marker.tap_label":"Tap-Aktion für dieses Gerät","tap.toggle_note":"Der aufgelöste Zustand ist unten dargestellt. Sichere Geräte werden niemals aus dem Plan umgeschaltet.","import.title":"Bereiche aus HA-Etagen erstellen","import.hint":"Home Assistant kennt diese Etagen bereits. Die Etagen auswählen, die zu Planbereichen werden sollen; anschließend für jeden Bereich einen Grundriss hochladen. Die Räume werden danach von Hand eingezeichnet.","import.start":"{n} Bereich(e) erstellen","import.manual":"Von Grund auf neu starten","import.progress":"Etage {i} von {n}","import.done":"Bereiche erstellt. Räume einzeichnen: Rasterpunkte anklicken und die Kontur schließen.","btn.skip":"Überspringen","space.scale_label":"Maßstab (Rasterzellen-Größe)","space.cell_cm.help":"Verknüpft das Raster mit realen Abmessungen: Davon hängen Längen und Flächen, Wandstärken, Öffnungsgrößen und der Leuchtradius ab. Eine spätere Änderung verändert die berechneten Abmessungen des gesamten Bereichs, verschiebt aber keine Punkte im Plan.","space.cell_cm.help.aria":"Hilfe: Maßstab des Bereichs","space.scale_unit":"cm pro Zelle","space.scale_unit_imperial":"Zoll pro Zelle","space.display_section":"Anzeige","space.show_borders":"Raumgrenzen immer anzeigen","space.zero_wall_style":"Wände ohne Dicke","space.zero_wall_style.help":"Gestrichelte Wände ohne Dicke lassen Glow und Sonnenstrahlen durch, durchgezogene blockieren sie als Barriere ohne Fläche. Die Auswahl gilt für alle solchen Wände im Bereich, auch wenn ihre Linie in der Ansicht ausgeblendet ist.","space.zero_wall_style.help.aria":"Hilfe: Darstellung der Wände ohne Dicke","space.zero_wall_dashed":"Gestrichelt","space.zero_wall_solid":"Durchgezogen","space.show_names":"Raumnamen anzeigen (zum Verschieben ziehen)","space.room_color":"Farbe der Begrenzung & des Namens","space.opacity":"Deckkraft","space.fill_label":"Raumausfüllung","space.fill_mode.help":"„Eigene Farbe“ gestaltet den Bereich; „Licht“, „Temperatur“ und „LQI“ verwenden aktuelle Daten aus Home Assistant. Glow wird separat aktiviert.","space.fill_mode.help.aria":"Hilfe: Modus der Raumausfüllung","fill.none":"Keine","fill.lqi":"Zigbee-Signal","fill.light":"Lichter","fill.custom":"Benutzerdefinierte Farbe","space.custom_fill":"Füllfarbe","space.source_file":"Ich habe einen Grundriss als Bild","space.source_draw":"Kein Bild – ich werde die Räume von Hand umreißen","fill.temp":"Temperatur","tip.temp_avg":"Durchschnittstemperatur:","tip.hum_avg":"Durchschnittliche Luftfeuchtigkeit:","space_card.button":"Grundriss öffnen","space_card.not_found":"Bereich „{id}“ nicht gefunden","space_card.loading":"Laden…","continuity.restore_plan":"Grundriss wiederherstellen…","continuity.restore_connection":"Geräteverbindung wiederherstellen…","continuity.retry":"Erneut versuchen","editor.space":"Bereich","editor.framing":"Bildausschnitt","editor.fit_content":"Alle sichtbaren Inhalte","editor.fit_house":"Eng an der Hausgeometrie","editor.show_button":"Schaltfläche anzeigen","editor.button_label":"Beschriftung der Schaltfläche","editor.button_target":"Ziel-Dashboard-Pfad","marker.sub_entity":"Entität","title.general_settings":"Allgemeine Einstellungen","gs.title":"Allgemeine Einstellungen","gs.light_group":"Füllung: Licht","gs.light_on":"Lichter an","gs.light_off":"Alle Lichter aus","gs.temp_group":"Füllung: Temperatur","gs.temp_cold":"Kalt","gs.temp_ok":"Angenehm","gs.temp_hot":"Heiß","gs.lqi_group":"Füllung: Zigbee-Signal","gs.lqi_low":"Schwaches Signal","gs.lqi_high":"Starkes Signal","gs.reset":"Auf Standard zurücksetzen","gs.saved":"Allgemeine Einstellungen gespeichert","space.show_lqi":"Zigbee-Signal (LQI) neben Geräten anzeigen","space.hide_decor":"Dekorationsschicht ausblenden","space.hide_decor_tip":"Linien, Formen, Beschriftungen und Möbel bleiben an ihrem Platz — im Hintergrundeditor sichtbar, aber nicht auf dem Plan.","space.hide_openings":"Öffnungen ausblenden","space.hide_openings_tip":"Tür-, Fenster- und Tor-Symbole werden nicht gezeichnet, aber die Öffnungen funktionieren weiterhin: Licht fällt hindurch, die Sonne kommt durch ein Fenster herein, Kontaktsensoren öffnen sie weiterhin. Der Planeditor zeigt sie immer an.","gs.light_none":"Keine Lichtquellen","mode.plan":"Planeditor","mode.devices":"Geräteeditor","display.value":"Wert + Zustand","marker.subarea":"kein Bereich, manuell","device.new":"Neues Gerät — Editor öffnen, um zu schließen","opening.unlock_action":"Entsperren","opening.lock_action":"Sperren","opening.lock_pending":"Wird ausgeführt…","title.close_editor":"Editor schließen (zur Ansicht zurück)","title.add_device":"Gerät zum Plan hinzufügen","devbar.add":"Hinzufügen","devbar.rules":"Symbolregeln","device_inbox.button":"Geräte","device_inbox.title":"Geräte auf dem Plan","device_inbox.search":"Geräte, Entitäten und Integrationen suchen…","device_inbox.add_virtual":"Virtuelles Gerät hinzufügen","device_inbox.tab_on_plan":"Auf Plan","device_inbox.tab_available":"Verfügbar","device_inbox.tab_hidden":"Versteckt","device_inbox.tab_readd":"Wieder verfügbar","device_inbox.only_new":"Nur neu","device_inbox.show_entities":"Entitäten anzeigen","device_inbox.show_hidden":"Versteckte auf Plan anzeigen","device_inbox.show_hidden.help":"Zeigt ausgeblendete und deaktivierte Marker vorübergehend als Bearbeitungs-Geister auf dem Plan. Die gespeicherte Sichtbarkeit der Geräte bleibt unverändert.","device_inbox.show_hidden.help.aria":"Hilfe: ausgeblendete Geräte auf dem Plan anzeigen","device_inbox.new":"Neu","device_inbox.find":"Auf dem Plan finden","device_inbox.edit":"Bearbeiten","device_inbox.hide":"Ausblenden","device_inbox.show":"Anzeigen","device_inbox.add":"Hinzufügen","device_inbox.readd":"Wieder hinzufügen","device_inbox.hide_available":"Aus der Liste ausblenden","device_inbox.show_more":"Mehr anzeigen","device_inbox.more_actions":"Weitere Aktionen","device_inbox.find_hidden_hint":"Zuerst „Versteckte auf Plan anzeigen“ aktivieren","device_inbox.show_disabled":"Diese Bindung in Home Assistant aktivieren, bevor sie angezeigt wird","device_inbox.empty_on_plan":"Es befinden sich noch keine passenden Geräte auf dem Plan.","device_inbox.empty_available":"Es sind keine Geräte zum Hinzufügen verfügbar.","device_inbox.empty_hidden":"Es gibt keine versteckten Geräte.","device_inbox.empty_readd":"Es sind keine entfernten Geräte verfügbar, um sie erneut hinzuzufügen.","device_inbox.reason_visible_auto":"Automatisch erkannt","device_inbox.reason_visible_explicit":"Explizit hinzugefügt","device_inbox.reason_manual_hidden":"Vom Benutzer versteckt","device_inbox.reason_automatic_hidden":"Automatisch versteckt","device_inbox.reason_service_entry":"Nur Service-Registry-Eintrag","device_inbox.reason_excluded_integration":"Integration „{integration}“ durch Erkennungsfilter ausgeschlossen","device_inbox.reason_excluded_domain":"Nicht-räumlicher Entitätstyp","device_inbox.reason_grouped_light":"Dargestellt durch eine Raumlichtgruppe","device_inbox.reason_represented_by_parent":"Dargestellt durch sein übergeordnetes Gerät","device_inbox.reason_removed":"Zuvor aus dem Plan entfernt","device_inbox.reason_available":"Zum Hinzufügen zum Plan verfügbar","device_inbox.reason_no_bound_room":"HA-Bereich ist nicht mit einem Planraum verknüpft","device_inbox.status_ha_disabled":"In Home Assistant deaktiviert","device_inbox.status_orphaned":"Bindung ist in Home Assistant nicht mehr vorhanden","device_inbox.status_unverified":"Home Assistant-Register vorübergehend nicht verfügbar","device_inbox.saved":"Geräteliste aktualisiert","device_inbox.filters_excluded":"Ausgeschlossene Integrationen","device_inbox.filters_group_lights":"Raumleuchten zu einem Marker gruppieren","device_inbox.filters_preview_appear":"erscheint: {count}","device_inbox.filters_preview_hide":"verschwindet: {count}","device_inbox.filters_preview_lights":"betroffene Leuchten: {count}","device_inbox.filters_reset":"Empfohlene wiederherstellen","device_inbox.filters_save":"Filter speichern","device_inbox.filters_search_ph":"Integration hinzufügen…","device_inbox.filters_title":"Erkennungsfilter","space.roomcard_section":"Raumkarte zeigt:","space.label_temp":"Temperatur","space.label_hum":"Luftfeuchtigkeit","space.label_lqi":"Durchschnittliches Zigbee-Signal","space.label_light":"Lichter ein/aus","roomcard.light_on":"Ein","roomcard.light_off":"Aus","roomcard.light_partial":"{on} von {total}","toast.split_pick_inside":"Zwischenliegende Schnittpunkte müssen innerhalb des Raumes liegen","mode.decor":"Hintergrundeditor","decor.select":"Auswählen","decor.line":"Linie","decor.rect":"Rechteck","decor.ellipse":"Oval","decor.text":"Text","decor.erase":"Löschen","decor.erase_confirm_title":"Objekt löschen?","decor.color":"Farbe","decor.width":"Linienbreite","decor.line_style":"Linienstil","decor.line_style_solid":"Durchgehend","decor.line_style_dashed":"Gepunktet","decor.fill":"Füllen","decor.fill_color":"Füllfarbe","decor.length":"Länge","decor.size":"Größe","decor.flip_h":"Horizontal spiegeln","decor.flip_v":"Vertikal spiegeln","decor.angle":"Rotationswinkel, °","decor.text_size":"Textgröße","decor.backdrop_properties":"Eigenschaften des Planhintergrunds","decor.text_title":"Textbeschriftung","decor.object_title":"{kind} bearbeiten","decor.text_label":"Text","decor.live_group":"HA-Variable einfügen","decor.live_entity":"Entität","decor.live_entity_ph":"Wählen Sie eine Entität","decor.live_attr":"Wert","decor.live_attr_ph":"Wählen Sie Status oder Attribut","decor.live_state":"Status","decor.backdrop":"Hintergrundbild","decor.backdrop_hint":"Ziehen zum Verschieben; eine Ecke ziehen zum Größenändern; den oberen Griff zum Drehen verwenden. Shift ändert das Verhältnis oder befreit den Winkel.","decor.backdrop_reset":"Bild zurücksetzen","decor.backdrop_reset_done":"Das Bild ist wieder an seinem ursprünglichen Platz und in seiner ursprünglichen Größe","marker.icon_auto":"Auto: {icon} (nach Symbolregeln; wählen Sie eines zur Überschreibung)","marker.icon_pin_auto":"Anheften","mode.plan_tip":"Planungseditor — die Geometrie des Hauses: Räume zeichnen und teilen/zusammenführen, sie mit HA-Bereichen verbinden, Türen, Fenster und Tore platzieren, Raumkarten verschieben, Maßstab festlegen","mode.devices_tip":"Geräteeditor — alles über Symbole: ziehen zum Positionieren, klicken zum Bearbeiten von Bindung/Symbol/Anzeige, virtuelle Geräte hinzufügen, Symbolregeln","mode.decor_tip":"Hintergrundeditor — rein visuelle Dekoration unter dem Plan: Linien, Rechtecke, Ellipsen und Textbeschriftungen, die niemals auf Klicks reagieren","space.glow_enabled":"Lichtquellen-Glühen","gs.glow_group":"Glow von Lichtquellen","gs.glow_base":"Grunddunkelheit des Hauses","gs.glow_light":"Standardlichtfarbe / Intensität","gs.wall_group":"Wände","gs.wall_fill":"Wandfüllung","gs.glow_radius":"Glow-Radius","gs.glow_radius.help":"Legt den allgemeinen Radius des Lichtscheins in Metern oder Fuß fest; ein gerätespezifischer Radius überschreibt diesen Wert.","gs.glow_radius.help.aria":"Hilfe: allgemeiner Glow-Radius","gs.unit_m":"m","gs.unit_ft":"ft","marker.controls_label":"Steuert andere Lichtquellen","marker.controls.help":"Mit der Aktion „Zustand umschalten“ werden die aufgeführten Quellen zusammen mit diesem Marker umgeschaltet. Ihr Glow bleibt an ihren eigenen Markern, und die Verknüpfung allein macht den steuernden Marker nicht zur Lichtquelle.","marker.controls.help.aria":"Hilfe: andere Lichtquellen steuern","marker.controls_filter":"Suchlichter und Schalter…","info.controls":"Steuerungen","marker.glow_radius_label":"Leuchtradius","marker.glow_radius.help":"Legt den Leuchtradius in Metern oder Fuß fest; ein leerer Wert verwendet den Radius aus den allgemeinen Einstellungen.","marker.glow_radius.help.aria":"Hilfe: Leuchtradius","markup.wallthick":"Dicke","markup.select":"Auswählen","title.markup_wallthick":"Dicke — klicken Sie auf eine Wand, um ihre Dicke von 0 bis 100 cm festzulegen.","markup.hint_wallthick":"klicken Sie auf eine Wand · Esc schließt ohne Anwendung","wallthick.field":"Dicke","wallthick.unit_cm":"cm","wallthick.unit_in":"in","wallthick.apply_room":"Auf alle Wände dieses Raums anwenden","markup.draw_wall_title":"Dicke jedes neuen Wandsegments (0–100 cm). Gemeinsame Wände behalten den bestehenden Wert.","room.queue_progress":"Raum {current} von {total}","toast.wall_rooms_saved":"Erstellte Räume: {n}","toast.wall_chain_saved":"Wandkette gespeichert","toast.wallthick_pick":"Eine Wand anklicken","toast.wallthick_set":"Wandstärke eingestellt","toast.wallthick_cleared":"Wandstärke entfernt","toast.physical_range":"Einen Wert von {min} bis {max} {unit} eingeben","toast.zero_wall_opening_conflict":"Entfernen Sie zuerst die Öffnung an diesem Wandsegment.","toast.zero_wall_ambiguous":"Das Wandsegment ist mehrdeutig. Vereinfachen oder passen Sie den Anschluss an.","toast.zero_wall_migration_blocked":"Der Bereich wurde nicht konvertiert: {reason}. Es wurden keine Daten geändert.","toast.physical_angle":"Einen Drehwinkel von 0° bis unter 90° eingeben","toast.physical_limit":"Der Bereich hat das Limit für diesen Geometrietyp erreicht","toast.geometry_unsafe":"Änderung abgebrochen: Wandgeometrie konnte nicht sicher erstellt werden.","junction.limit_angle":"Der Winkel zwischen den Wänden ist zu spitz: {actual}°, mindestens {limit}°.","junction.limit_valence":"Zu viele Wände treffen in einem Knoten aufeinander: {actual}, maximal {limit}.","junction.limit_length":"Das Wandsegment ist zu kurz: {actual} cm, mindestens {limit} cm.","junction.limit_distance":"Wände und Knoten sind zu dicht beieinander: {actual} cm, Minimum {limit} cm.","junction.limit_clearance":"Kein Wohnbereich ist übrig: {actual} cm², Minimum {limit} cm².","junction.limit_check_failed":"Die Überprüfung der Verbindungen konnte nicht durchgeführt werden — die Änderung wurde nicht gespeichert.","toast.wall_model_migration_blocked":"Das Wandmodell konnte nicht aktualisiert werden: {reason}. Der Plan wurde nicht geändert. Führen Sie „Pläne optimieren“ aus; wenn der Fehler erneut auftritt, beheben Sie die widersprüchliche Wandgeometrie.","toast.wall_model_client_outdated":"Aktualisieren Sie die Karte und laden Sie die Seite neu, bevor Sie den Plan bearbeiten.","wall_model.reason.invalid-room":"ungültiger Raumkontur","wall_model.reason.zero-length":"Wandsegment mit null Länge","wall_model.reason.third-owner":"Wand, die von mehr als zwei Räumen geteilt wird","wall_model.reason.duplicate-id":"widersprüchliche Wandkennungen","wall_model.reason.thickness-conflict":"widersprüchliche Wandstärkenwerte","wall_model.reason.opening-host":"Öffnung kann nicht einer Wand zugewiesen werden","toast.delete_room_pick":"Klicken Sie in den Raum, den Sie löschen möchten","toast.plan_snap_ambiguous":"Zoomen Sie hinein, um den Wandknoten auszuwählen","toast.wall_repair_ambiguous":"Der Raumumriss hat mehr als eine mögliche Verbindung. Zoomen Sie hinein und verbinden Sie ihn explizit.","toast.wall_repair_too_large":"Die Lücke ist größer als 2 cm. Verbinden Sie die Wände, bevor Sie den Raum erstellen.","toast.wall_repair_changed":"Die Wandgeometrie hat sich geändert. Versuchen Sie erneut, den Raum zu erstellen.","toast.opening_on_zero_wall":"Öffnungen können nicht auf einer Wand mit null Dicke sitzen.","marker.from_ha_option":"Wählen Sie aus der HA-Liste.","marker.show_entities":"Entitäten anzeigen.","marker.show_entities_tip":"Fügt nicht nur Geräte zur Liste hinzu, sondern auch alle ihre Entitäten.","marker.pick_ph":"Wählen Sie ein Gerät…","room.open_area":"Öffnen Sie den HA-Bereich.","room.fit_action":"Raum {name} einpassen","view.volumetric":"Volumetrische Ansicht.","view.flat":"Flache Ansicht.","kiosk.title":"Die Größen dieses Bildschirms.","kiosk.hint":"Nur auf diesem Gerät gespeichert – jedes Wandtablet oder TV kann seine eigenen komfortablen Größen haben.","kiosk.icon_scale":"Gerätesymbolgröße.","kiosk.font_scale":"Textgröße der Raumkarte.","editor.kiosk":"Wandgeräte- (Kiosk-)Modus.","editor.cycle":"Bereiche automatisch alle N Sekunden wechseln (Kiosk, 0 = aus)","room.settings_title":"Raumeinstellungen.","room.settings_section":"Raumeinstellungen (überschreibt den Bereich)","room.fill_label":"Diesen Raum ausfüllen","fill.inherit":"Als den Bereich","room.custom_fill_space":"Bereichsfarbe","room.custom_fill_own":"Raumfarbe","room.temp_src_label":"Temperaturquelle","room.hum_src_label":"Luftfeuchtigkeitsquelle","room.src_average":"Durchschnitt über die Sensoren des Raums (Standard)","room.src_pick":"Ein bestimmtes HA-Gerät oder Entität","room.src_ph":"Quelle wählen…","toast.room_updated":"Raum aktualisiert","space.card_font":"Schriftgröße der Raumkarte (gesamter Bereich)","room.sizes_section":"Schriftgrößen","room.name_scale":"Raumname Größe","room.label_scale":"Metrikgröße","preview.room_name":"Wohnzimmer","toast.cfg_reload_failed":"Der Plan konnte nicht vom Server neu geladen werden: {err}","toast.locale_load_failed":"Das Sprachpaket konnte nicht geladen werden. Bis zum Neuladen der Seite wird Englisch verwendet.","toast.furniture_art_load_failed":"Die Möbelzeichnungen konnten nicht geladen werden. Laden Sie die Seite neu, um sie anzuzeigen.","room.settings_short":"Raumeinstellungen","room.unnamed":"Unbenannter Raum","marker.use_climate_temp":"Geräte-Temperatur im Raum berücksichtigen","marker.use_climate_temp_tip":"Fügt die aktuelle Temperatur einer Klimaanlage oder eines Thermostats zum Raumdurchschnitt hinzu. Das externe Wert-Label unten separat konfigurieren.","marker.value_badge_title":"Wert-Label","marker.value_badge.help":"Zeigt einen ausgewählten Wert neben dem Symbol an. Dies beeinflusst nicht die Raumkennzahlen, Licht, Glanz oder die Tippaktion.","marker.value_badge.help.aria":"Hilfe: Gerätewert-Badge","marker.value_badge_enabled":"Zeige ein Wert-Badge","marker.value_badge_source":"Wert","marker.value_badge_source.help":"Wählen Sie einen bestimmten Zustand, ein unterstütztes Attribut oder einen abgeleiteten Wert dieses Geräts.","marker.value_badge_source.help.aria":"Hilfe: Quelle des Wert-Badges","marker.value_badge_position":"Position","marker.value_badge_position.help":"Die gewählte Seite bleibt fest und dreht sich nicht automatisch an einem Planrand.","marker.value_badge_position.help.aria":"Hilfe: Position des Wert-Badges","marker.value_badge_right":"Rechts","marker.value_badge_bottom":"Unten","marker.value_badge_left":"Links","marker.value_badge_top":"Oben","marker.value_badge_empty":"Für dieses Gerät stehen keine Werte zur Verfügung","marker.value_badge_static":"Ein statisches Symbol zeigt keine Live-Werte an. Die Einstellung wird beibehalten.","marker.value_badge_missing":"Quelle nicht verfügbar","marker.value_badge_missing_hint":"Die gespeicherte Quelle ist derzeit nicht verfügbar. Behalten Sie sie bei, deaktivieren Sie das Badge oder wählen Sie einen anderen Wert.","marker.value_badge_duplicate":"Derselbe Wert wird bereits im Symbol angezeigt.","marker.value_badge_state":"Status · {name}","marker.value_badge_marker_state":"Lichtquellstatus · {name}","marker.value_badge_lqi":"Durchschnittliche Zigbee-Signalqualität","marker.value_badge_attr_current_temperature":"Aktuelle Temperatur · {name}","marker.value_badge_attr_temperature":"Zieltemperatur · {name}","marker.value_badge_attr_current_humidity":"Aktuelle Luftfeuchtigkeit · {name}","marker.value_badge_attr_humidity":"Luftfeuchtigkeit · {name}","marker.value_badge_attr_current_position":"Position · {name}","marker.value_badge_attr_percentage":"Geschwindigkeit · {name}","marker.value_badge_attr_brightness":"Helligkeit · {name}","marker.value_badge_attr_volume_level":"Lautstärke · {name}","marker.value_badge_attr_battery_level":"Batterie · {name}","marker.value_badge_attr_fan_speed":"Lüftergeschwindigkeit · {name}","marker.value_source":"Wertquelle","marker.value_source.help":"Wähle den Wert, der das Symbol ersetzt. Die Tipp-Aktion bleibt unverändert.","marker.value_source.help.aria":"Hilfe: Wertquelle in der Gerätefläche","marker.value_source_auto":"Automatisch (wie bisher)","marker.value_source_missing_hint":"Die gespeicherte Quelle ist derzeit nicht verfügbar. Bis sie wieder verfügbar ist oder ein anderer Wert gewählt wird, zeigt die Fläche —.","marker.light_role_label":"Ist dieses Gerät eine Lichtquelle?","marker.light_role.help":"„Auto“ verwendet die ermittelte Rolle des verknüpften Geräts, „Immer“ erzwingt eine eigene Quelle und „Nie“ schließt sie aus; oben verknüpfte Lichter bleiben unabhängig.","marker.light_role.help.aria":"Hilfe: ob dieses Gerät eine Lichtquelle ist","marker.light_role_auto_yes":"Automatisch (Lichtquelle)","marker.light_role_auto_no":"Automatisch (keine Lichtquelle)","marker.light_role_always":"Immer eine Lichtquelle","marker.light_role_never":"Nie eine Lichtquelle","marker.light_entity_label":"Führende Lichtereinheit","marker.light_entity.help":"Für ein Verbundgerät wählen Sie die Entität, deren Zustand, Farbe und Helligkeit diese Planquelle darstellen. Der automatische Rückgriff bleibt mit älteren Plänen kompatibel.","marker.light_entity.help.aria":"Hilfe: führende Lichtentität","marker.light_entity_auto":"Automatisch ({entity})","marker.light_entity_none":"keine steuerbare Entität","marker.light_entity_missing":"Die gespeicherte Entität {entity} ist nicht verfügbar. House Plan verwendet vorübergehend {fallback}; die gespeicherte Auswahl wird wiederhergestellt, wenn sie zurückkehrt.","marker.toggle_entity_label":"Zu toggelnde Entität","marker.toggle_entity.help":"Für ein Verbundgerät wählen Sie das genaue eigene Licht oder den Schalter, der durch Tippen bedient wird. Automatisch behält die vorherigen Zielregeln bei und ist unabhängig von der führenden Lichtentität.","marker.toggle_entity.help.aria":"Hilfe: zu toggelnde Entität","marker.toggle_entity_auto":"Automatisch ({entity})","marker.toggle_entity_none":"keine eigene steuerbare Entität","marker.toggle_entity_missing":"Die gespeicherte Entität {entity} ist nicht mehr unter den auswählbaren Kanälen dieses Markers. House Plan verwendet vorübergehend {fallback}; die gespeicherte Auswahl wird wiederhergestellt, wenn sie zurückkehrt.","marker.glow_color_label":"Leuchtfarbe und Helligkeit","marker.glow_mode.help":"Verwenden Sie Live-Quellwerte, überschreiben Sie nur deren Farbe oder fixieren Sie sowohl Farbe als auch Helligkeit. Das Minimum beträgt 1 %; um die Quelle zu deaktivieren, wählen Sie „Nie“.","marker.glow_mode.help.aria":"Hilfe: Leuchtfarbe und Helligkeit","marker.glow_mode_auto":"Von Quelle","marker.glow_mode_color":"Farbe einstellen","marker.glow_mode_fixed":"Farbe und Helligkeit einstellen","marker.glow_color":"Leuchtfarbe","marker.glow_brightness":"Helligkeit","marker.glow_disabled_never":"Leuchteinstellungen sind nicht verfügbar, da dieser Marker ausdrücklich keine Lichtquelle ist.","marker.glow_disabled_auto":"Im Automatikmodus wurde keine räumliche Lichtquelle für diesen Marker gefunden.","marker.glow_disabled_no_entity":"Keine aktive steuerbare Home Assistant-Entität ist für diese räumliche Quelle verfügbar.","marker.glow_passive_hint":"Diese Quelle hat keine eigenen Home Assistant-Daten. Stellen Sie ihre Farbe und Helligkeit manuell ein; ihr Radius bleibt verfügbar.","marker.control_broken":"Gespeicherte Quelle fehlt oder ist nicht mehr als Licht markiert","marker.control_missing_label":"Fehlendes Planlicht","marker.control_passive":"passive Quelle","toast.marker_control_cycle":"Dieser Link würde eine kreisförmige Kette von Lichtsteuerungen erzeugen.","toast.marker_binding_required":"Wählen Sie ein Home Assistant-Gerät, bevor Sie eine andere Lichtquelle verlinken.","confirm.unlock_title":"Schloss öffnen?","confirm.unlock_body":"House Plan sendet einen Befehl zum Öffnen an dieses Schloss.","toast.files_migrate_failed":"Anhänge konnten nicht zur neuen Bindung verschoben werden, Links zeigen weiterhin auf die alten Dateien: {err}","space.pick_saved":"Bereits hochgeladen","space.pick_saved_hint":"Auf dem Server gespeicherte Pläne, einschließlich solcher, die Sie zuvor getrennt haben","space.no_saved":"Noch keine Pläne auf dem Server gespeichert.","space.loading":"Laden…","space.used_by":"in Benutzung: {list}","space.in_use":"Ein Bereich verwendet diesen Plan noch — zuerst die Verknüpfung lösen","btn.use":"Verwenden","confirm.delete_plan_title":"Plandatei löschen?","confirm.delete_plan_body":"Die Datei wird vom Server gelöscht. Dieser Vorgang kann nicht rückgängig gemacht werden.","toast.plans_list_failed":"Konnte die gespeicherten Pläne nicht auflisten: {err}","toast.plan_delete_failed":"Konnte den Plan nicht löschen: {err}","marker.hide":"Ausblenden","marker.hide_tip":'Das Gerät wird nach dem Speichern aus dem Plan verschwinden, aber weiterhin zum Signalsignal des Raums zählen. Stellen Sie es über den Katalog "Geräte" im Geräte-Editor wieder her.',"marker.show":"Anzeigen","marker.show_tip":"Das Gerät wird nach dem Speichern wieder im Plan erscheinen.","marker.hidden_ghost":"Vom Benutzer ausgeblendetes Gerät","marker.ha_disabled_device":"Das Gerät ist in Home Assistant deaktiviert und im Plan ausgeblendet.","marker.ha_disabled_entity":"Die Entität ist in Home Assistant deaktiviert und im Plan ausgeblendet.","marker.ha_disabled_all_entities":"Das Gerät hat keine aktiven Home Assistant-Entitäten, daher ist es im Plan ausgeblendet.","marker.ha_registry_limited":"Das vollständige Home Assistant-Register ist für diesen Benutzer nicht verfügbar. Das nicht verifizierte Objekt kann vorerst nicht angezeigt oder verwendet werden.","marker.delete_tip":"Löschen Sie das Gerät vollständig aus dem Plan und allen Aggregaten. Sie können es später wieder hinzufügen.","tap.run":"Führen Sie Automation/Skript/Szene aus","tap.none":"Nichts tun","marker.run_target_label":"Was ausführen","marker.run_search_ph":"Suchen: Automation, Skript oder Szene…","marker.run_target_gone":"Ziel {id} nicht gefunden — erneut auswählen","marker.tap_confirm":"Um Bestätigung bitten","marker.tap_confirm_tip":"Vor der Ausführung ein Bestätigungsdialogfeld anzeigen — eine Vorsichtsmaßnahme gegen versehentliche Berührungen.","marker.toggle_hint_single":"Ziel: {name} ({id}).","marker.virtual_light_target":"Virtuelles Licht: {name}.","marker.virtual_light_current":"Manueller Zustand: {state} → {effect}.","marker.virtual_light_state_on":"ein","marker.virtual_light_state_off":"aus","marker.toggle_hint_group":"Wird {count}-Quelle(n) umschalten: {names}.","marker.toggle_hint_current":"Jetzt: {state} → {effect}.","marker.toggle_hint_group_current":"Derzeit an: {on} von {count} → {effect}.","marker.toggle_hint_skipped":"Wird übersprungen ({count}): {targets}.","marker.toggle_effect_turn_on":"wird eingeschaltet","marker.toggle_effect_turn_off":"wird ausgeschaltet","marker.toggle_effect_open":"wird geöffnet","marker.toggle_effect_close":"wird geschlossen","marker.toggle_effect_stop":"wird gestoppt","marker.toggle_effect_toggle":"Zustand wird umgeschaltet","marker.toggle_skip_missing":"nicht gefunden","marker.toggle_skip_ha_disabled":"in HA deaktiviert","marker.toggle_skip_unavailable":"nicht verfügbar","marker.toggle_skip_unsupported":"Umschalten wird nicht unterstützt","marker.toggle_skip_secure":"aus Sicherheitsgründen blockiert","marker.toggle_none_no_binding":"Dieses Gerät hat keine Bindung, daher gibt es keinen Zustand, der umgeschaltet werden könnte. Tippen bewirkt nichts.","marker.toggle_none_no_actionable_entity":"Dieses Gerät hat keinen Zustand, der umgeschaltet werden könnte. Tippen bewirkt nichts.","marker.toggle_none_configured_targets_missing":"Die konfigurierten Ziele sind nicht verfügbar. Die eigene Entität des Geräts wird nicht ersetzt.","marker.toggle_none_ha_disabled":"Das Ziel ist in Home Assistant deaktiviert und kann im Plan nicht verwendet werden.","marker.toggle_none_unavailable":"Das Ziel ist derzeit nicht verfügbar. Tippen bewirkt nichts.","marker.toggle_none_unsupported":"Home Assistant bietet keine sichere Umschaltfunktion für dieses Gerät. Tippen bewirkt nichts.","marker.toggle_none_secure":"Das Umschalten von Schlössern, Alarmen und gesicherten Toren über den Plan ist aus Sicherheitsgründen gesperrt.","run.automation":"Automatisierung","run.script":"Skript","run.scene":"Szene","confirm.tap_run":'"{name}" ausführen?',"confirm.tap_toggle":'"{name}" umschalten?',"confirm.current_state":"Aktueller Zustand: {state}","confirm.expected_state":"Nach dem Umschalten: {state}","confirm.group_current":"an {on} von {total}","confirm.group_all_on":"alle sind eingeschaltet","confirm.group_all_off":"alle sind ausgeschaltet","confirm.unavailable_targets":"Nicht verfügbar: {count}","confirm.expected_by_ha":"Home Assistant ermittelt den Zustand","confirm.state_on":"Ein","confirm.state_off":"Aus","confirm.state_open":"Offen","confirm.state_closed":"Geschlossen","confirm.state_opening":"Wird geöffnet","confirm.state_closing":"Wird geschlossen","confirm.state_stopped":"Gestoppt","confirm.state_unknown":"Unbekannt","toast.run_started":"Gestartet: {name}","toast.run_target_missing":"Ausführungsziel nicht gefunden — überprüfen Sie die Geräteeinstellungen","toast.run_target_required":"Wählen Sie eine Automatisierung, ein Skript oder eine Szene aus","toast.tap_target_changed":"Das Ziel der Aktion hat sich geändert. Versuchen Sie es erneut.","toast.virtual_light_toggle_failed":"Das virtuelle Licht konnte nicht umgeschaltet werden: {err}","toast.value_badge_source_required":"Einen Wert für den Badge auswählen","btn.run":"Ausführen","vac.section":"Roboterstaubsauger: aktuelle Position","vac.autocal":"Automatisch einrichten","vac.live":"Aktuelle Position im Plan","vac.trail":"Roboterpfad anzeigen","vac.autocal_no_rooms":'Die Integration meldet keine Raumliste — öffnen Sie "Manuell anpassen"',"vac.route_warn_unmapped":"Der Roboter reinigt eine Karte, die keiner Etage zugeordnet ist","vac.route_warn_needs_calibration":"Die Karte ist einer Etage zugeordnet, aber nicht kalibriert","vac.route_warn_ambiguous":"Zwei Karten sind nicht unterscheidbar — keine Etage gewählt","vac.route_warn_missing_space":"Der Raum dieser Karte wurde gelöscht","vac.autocal_no_match":'Raumnamen stimmten nicht überein (mindestens 3 müssen übereinstimmen) — öffnen Sie "Manuell anpassen"',"vac.autocal_done":"Fertig: über {rooms} Räume zugeordnet. Eine Reinigung starten und das Ergebnis prüfen.","vac.cal_need_pos":"Der Roboter meldet keine Koordinaten — starten Sie eine Reinigung und pausieren Sie sie","vac.cal_done":"Kalibrierung gespeichert. Eine Reinigung starten und das Ergebnis prüfen.","vac.cal_cancelled":"Kalibrierung abgebrochen","vac.fit":"Manuell anpassen","vac.fit_hint":"Roboterkarte an die richtige Position ziehen und an den Ecken skalieren","vac.fit_rotate":"90° drehen","vac.fit_mirror":"Spiegeln","vac.trail_never":"Nie","vac.trail_cleaning":"Beim Reinigen","vac.trail_always":"Immer","gs.bg_group":"Bühnenhintergrund","gs.bg_color":"Hintergrund um den Plan","gs.bg_default":"Standardthema","gs.bg_theme":"Standardthema","gs.bg_mode":"Planhintergrund","gs.bg_mode.help":"„Folgt der Sonne“ verwendet sun.sun und ersatzweise die lokale Browserzeit; „Statische Farbe“ zeigt immer die ausgewählte Farbe.","gs.bg_mode.help.aria":"Hilfe: allgemeiner Planhintergrund","gs.bg_static":"Statische Farbe","gs.bg_daynight":"Folgt der Sonne","gs.sun_group":"Sonne","gs.sun_missing":"Die sun.sun-Entität wurde nicht gefunden — der Hintergrund folgt Ihrer lokalen Uhr; Fensterstrahlen sind nicht verfügbar.","gs.north":"Norden auf dem Plan","gs.north.help":"Der Winkel wird im Uhrzeigersinn von der oberen Vertikalen des Plans gemessen; Norden wird für Fensterstrahlen benötigt, nicht für den Hintergrund „Folgt der Sonne“.","gs.north.help.aria":"Hilfe: allgemeine Nordrichtung","gs.north_ph":"nicht gesetzt","gs.north_clear":"Löschen","gs.north_letter":"N","gs.sun_rays":"Sonnenlicht durch Fenster","gs.about_version":"House Plan Card v{v}","gs.about_github":"GitHub · Dokumentation & Probleme","gs.about_telegram":"Telegram-Chat","support.title":"Hilfe & Feedback","space.bg_color":"Hintergrund rund um den Plan","space.bg_inherit":"Allgemein erben","space.bg_inherited":"erbt allgemeine Einstellungen","space.bg_mode":"Planhintergrund","space.bg_mode.help":"Übernehmen Sie den allgemeinen Hintergrund oder überschreiben Sie diesen Bereich mit einer statischen Farbe oder „Folgt der Sonne“.","space.bg_mode.help.aria":"Hilfe: Hintergrund des Bereichs","space.north":"Norden auf dem Plan (überschreiben)","space.north.help":"Überschreibt die allgemeine Nordrichtung für diesen Bereich; der Winkel wird im Uhrzeigersinn von der oberen Vertikalen des Plans gemessen und für Fensterstrahlen verwendet.","space.north.help.aria":"Hilfe: Norden für diesen Bereich","space.north_inherited":"geerbt: {v}","space.sun_rays":"Sonnenlicht durch Fenster","space.sun_inherit":"Allgemein erben","space.sun_on":"Ein","space.sun_off":"Aus","canvas.far_objects":"{n} Objekt(e) weit vom Plan entfernt","canvas.show_far":"Anzeigen","canvas.home_tip":"Der Plan ist dort drüben — klicken, um ihn anzupassen","gs.grid_group":"Planwartung","gs.grid_hint":"Aktualisiert Datenmodelle, richtet Planelemente am Raster aus und fasst redundante Wandfragmente zusammen. Ein exakter Bericht wird angezeigt, bevor etwas gespeichert wird.","gs.align_all":"Pläne optimieren","gs.align_title":"Pläne optimieren","gs.align_none":"Alle Pläne verwenden bereits das aktuelle optimierte Datenmodell.","gs.optimize_no_automatic_changes":"Es gibt keine automatischen Änderungen, die angewendet werden müssen. Überprüfen Sie die unten stehenden Punkte.","gs.align_count":"{n} von {total} Elementen werden sich um höchstens {cm} cm bewegen.","gs.align_where":"Die größte Verschiebung ist in „{s}“.","gs.align_turned":"Öffnungen, deren Winkel korrigiert wurde: {n}.","gs.align_preflight_failed":"Die Geometrie der folgenden Bereiche konnte nicht sicher überprüft werden: {spaces}{more}.","gs.align_preflight_hint":"Pläne wurden nicht geändert. Kopieren Sie die Diagnosen mit dem untenstehenden Button und fügen Sie sie zusammen mit einem Raumexport dem Fehlerbericht bei.","gs.preflight_reason_prepare-exception":"Die Bereichsgeometrie konnte nicht vorbereitet werden (Ausnahme beim Erstellen des Modells)","gs.preflight_reason_wall-null":"Der Wandkörper wurde nicht erstellt (die Vereinigung lieferte leer zurück)","gs.preflight_reason_wall-degraded-extra":"Der Wandkörper wurde mit zusätzlicher Geometrie beschädigt","gs.preflight_reason_wall-failed-core":"Der Kern des Wandkörpers konnte nicht zusammengesetzt werden","gs.preflight_reason_wall-exception":"Die Wandkonstruktion warf eine Ausnahme","gs.preflight_reason_floor-null":"Der Fußbodenumriss wurde nicht erstellt","gs.preflight_reason_floor-exception":"Bodenaufbau hat eine Ausnahme ausgelöst","gs.preflight_copy":"Diagnosen kopieren","gs.preflight_copied":"Diagnosen kopiert","gs.preflight_update_hint":"Die Karten- und Integrationsversionen unterscheiden sich — Hausplan aktualisieren und erneut versuchen.","gs.align_preflight_space":"Bereich {n}","gs.align_preflight_more":", und {n} mehr","gs.optimize_changes":"Modellmigrationen: {m}; aktualisierte Bereiche: {c}; entfernte verrauschte Koordinatenwerte: {p}; zusammengeführte Fragmente realer Wände: {w}; zusammengeführte Fragmente von Wänden ohne Dicke: {s}; unabhängige Wände: {i}.","gs.zero_walls_migrated":"Virtuelle Wandspannweiten konvertiert: {n}.","gs.wall_segments_migrated":"Wandsegmente stabilisiert: {n}.","gs.room_drafts_migrated":"Unvollständige Konturen wurden in normale Wände umgewandelt: {drafts}; Wandsegmente: {segments}.","gs.optimize_lattice_summary":"Rauschen in den Koordinatenwerten kanonisiert: {n}; maximale Bewegung: {cm} cm.","gs.optimize_lattice_space":"{space}: Koordinatenwerte kanonisiert: {n}; außerhalb des Rasters liegende Werte unverändert gelassen: {far}.","gs.optimize_coincident_partitions":"Versteckte unabhängige Wandabschnitte in Raumwände integriert: {n}.","gs.optimize_openings_rehosted":"Öffnungen wieder an Raumwände angebracht: {n}.","gs.optimize_walls_straightened":"Wände begradigt: {n}; maximale Bewegung: {cm} cm.","gs.optimize_walls_straightened_where":"Größte Wandkorrektur: {s}.","gs.optimize_walls_straighten_skipped":"Nahe Achsenwände unverändert gelassen, da sie nicht sicher repariert werden konnten: {n}.","gs.optimize_glow_migration":"Legacy Glow: {spaces} Bereiche → keine Datenfüllung + unabhängiges Glow; {rooms} Räume → geerbte Datenfüllung + unabhängiges Glow.","gs.optimize_references":"Referenzen repariert: Bereiche — {spaces}; Räume — {rooms}; Positionen — {positions}; Geräte aus fehlenden Bereichen gelöst — {detached}.","gs.optimize_reference_more":", und {n} mehr","gs.optimize_orphans_removed":"Vergessene Einträge entfernt: {total} — Raumbezeichnungen: {rooms}; Geräte: {devices}; Gruppenmarkierungen: {groups}. Sie gehörten zu zuvor gelöschten Bereichen.","gs.optimize_live_positions":"Alte Positionen in gelöschten Bereichen gehören zu vorhandenen Objekten: {n}{names}. Sie werden beibehalten.","gs.optimize_live_positions_remove":"Alte Positionen in gelöschten Bereichen gehören zu vorhandenen Objekten: {n}{names}. Sie sind zur Entfernung ausgewählt.","gs.optimize_live_names":": {names}{more}","gs.optimize_live_remove":"Alte Positionen entfernen","gs.optimize_live_keep":"Alte Positionen beibehalten","gs.optimize_live_selected":"Alte Positionen werden nach der Anwendung von Optimieren entfernt.","gs.optimize_unverified":"Positionen konnten nicht sicher überprüft werden: {n}. Sie wurden unverändert belassen.","gs.optimize_registry_limited":"Voller Administratorzugriff auf die Home Assistant-Registries ist für eine sichere Überprüfung erforderlich.","gs.optimize_vacuum_warning":"Raumzuordnungen, die noch überprüft werden müssen: {n}.","gs.optimize_details":"Details","gs.optimize_details_more":"Und {n} weitere Einträge.","gs.optimize_detail_removed":"wird entfernt","gs.optimize_detail_live":"wird beibehalten","gs.optimize_detail_unverified":"nicht überprüft","gs.optimize_detail_room_label":"Raumkennzeichnung","gs.optimize_detail_device":"Gerät","gs.optimize_detail_group":"Gruppenkennzeichen","gs.optimize_detail_unknown":"unbekannter Eigentümer","gs.optimize_detail_item":"{status}: {kind} {id}; alter Bereich {space}","gs.align_warn":"Absichtlich zwischen Rasterknoten platzierte Elemente werden sich bewegen. Nach der Operation ist nur eine Rückgängig-Funktion verfügbar, und zwar nur bis zur nächsten Planbearbeitung.","gs.align_run":"Optimieren","gs.align_done":"Pläne optimiert: {n} Elemente bewegt, {m} Datensätze beibehalten, {r} Verweise repariert","gs.optimize_undo":"Letzte Optimierung rückgängig machen","gs.optimize_undone":"Die letzte Optimierung wurde rückgängig gemacht","decor.furniture":"Möbel","decor.image":"Bild","decor.image_title":"Eigene Bilder","decor.image_upload":"Bild hochladen","decor.image_replace":"Bild ersetzen","decor.image_uploading":"Wird hochgeladen…","decor.image_asset":"Bilddatei","decor.image_pick_hint":"Ein Bild hochladen oder ein vorhandenes auswählen.","decor.image_place_hint":"Auf den Plan klicken, um das Bild zu platzieren.","decor.image_none":"Noch keine Bilder hochgeladen.","decor.image_unavailable":"Bild nicht verfügbar","decor.image_used":"In {n} Objekten verwendet","decor.image_upload_failed":"Bild konnte nicht hochgeladen werden: {err}","decor.image_error_capacity":"Der Speicher für benutzerdefinierte Bilder ist voll.","decor.image_in_use":"Vor dem Löschen alle platzierten Kopien entfernen.","decor.image_delete_title":"Bilddatei löschen?","decor.image_delete_message":"„{name}“ aus House Plan löschen? Dies kann nicht rückgängig gemacht werden.","furn.title":"Möbelbibliothek","furn.symbol":"Symbol","furn.group_furniture":"Möbel","furn.group_appliance":"Geräte","furn.group_sanitary":"Sanitär","furn.group_other":"Sonstiges","furn.width":"Breite","furn.depth":"Tiefe","furn.back_to_categories":"Alle Kategorien","furn.pick_hint":"Wählen Sie eine Kategorie und dann ein Symbol.","furn.place_hint":"Klicken Sie auf den Plan — das Element wird an der nächsten Wand platziert. Mit Shift wird es frei platziert.","furn.cat_air_conditioner":"Klimaanlagen","furn.cat_armchair":"Sessel","furn.cat_bathtub":"Badewannen","furn.cat_bed":"Betten","furn.cat_bidet":"Bidets","furn.cat_boiler":"Warmwasserbereiter","furn.cat_chair":"Stühle","furn.cat_coffee_table":"Couchtische","furn.cat_cooktop":"Kochfelder","furn.cat_dining_table":"Esstische","furn.cat_dishwasher":"Geschirrspüler","furn.cat_dryer":"Wäschetrockner","furn.cat_fireplace":"Kamine","furn.cat_fridge":"Kühlschränke","furn.cat_kitchen_cabinet":"Küchenschränke","furn.cat_kitchen_sink":"Küchenspülen","furn.cat_nightstand":"Schränke","furn.cat_plant":"Pflanzen","furn.cat_rug":"Teppiche","furn.cat_shelving":"Regale","furn.cat_shower":"Duschen","furn.cat_sink":"Waschbecken","furn.cat_sofa":"Sofas","furn.cat_stairs":"Treppen","furn.cat_toilet":"Toiletten","furn.cat_tv":"Fernseher","furn.cat_wardrobe":"Kleiderschränke","furn.cat_washer":"Waschmaschinen","furn.cat_work_table":"Schreibtische","furn.sym_sofa":"Zweisitzer-Sofa","furn.sym_sofa_three_seat":"Dreisitzer-Sofa","furn.sym_sofa_corner_right":"Ecksofa rechts","furn.sym_armchair":"Polstersessel","furn.sym_armchair_office":"Bürostuhl","furn.sym_coffee_table":"Rechteckiger Couchtisch","furn.sym_coffee_table_round":"Runder Couchtisch","furn.sym_coffee_table_oval":"Ovaler Couchtisch","furn.sym_coffee_table_rounded":"Abgerundeter Couchtisch","furn.sym_table_dining":"Rechteckiger Esstisch","furn.sym_table_round":"Rundtisch","furn.sym_table_dining_oval":"Ovaler Esstisch","furn.sym_table_dining_rounded":"Abgerundeter Esstisch","furn.sym_chair":"Stuhl","furn.sym_chair_bar":"Barhocker","furn.sym_desk":"Rechteckiger Schreibtisch","furn.sym_desk_corner":"Eckschreibtisch","furn.sym_bed_double":"Doppelbett","furn.sym_bed_single":"Einzelbett","furn.sym_nightstand":"Nachttisch","furn.sym_cabinet_tv":"TV-Schrank","furn.sym_cabinet_shoe":"Schuhschrank","furn.sym_cabinet_sink":"Waschtischunterschrank","furn.sym_wardrobe":"Kleiderschrank","furn.sym_bookshelf":"Bücherschrank","furn.sym_wall_unit":"Schrankwand","furn.sym_kitchen_floor":"Küchen-Unterschrank","furn.sym_kitchen_floor_corner":"Küchen-Eckunterschrank","furn.sym_kitchen_wall":"Küchen-Hängeschrank","furn.sym_kitchen_wall_corner":"Küchen-Eckhängeschrank","furn.sym_shelf_floor":"Standregal","furn.sym_shelf_wall":"Wandregal","furn.sym_fridge":"Kühlschrank","furn.sym_stove":"Vierflammiges Kochfeld","furn.sym_cooktop_two":"Zweiflammiges Kochfeld","furn.sym_dishwasher":"Geschirrspüler","furn.sym_washer":"Waschmaschine","furn.sym_dryer":"Wäschetrockner","furn.sym_tv":"Fernseher mit Standfuß","furn.sym_tv_wall":"Wandfernseher","furn.sym_ac":"Klimaanlage","furn.sym_water_heater":"Wassererhitzer","furn.sym_toilet":"Stand-WC","furn.sym_toilet_built_in":"Wand-WC","furn.sym_bathtub":"Rechteckige Badewanne","furn.sym_bathtub_corner":"Eckbadewanne","furn.sym_shower":"Dusche","furn.sym_sink":"Waschbecken","furn.sym_kitchen_sink":"Einzel-Küchenspüle","furn.sym_kitchen_sink_double":"Doppel-Küchenspüle","furn.sym_bidet":"Stand-Bidet","furn.sym_bidet_built_in":"Wand-Bidet","furn.sym_stairs":"Treppe","furn.sym_fireplace":"Kamin","furn.sym_plant":"Pflanze","furn.sym_rug":"Teppich","common.yes":"Ja","common.no":"Nein","vac.diag_source":"Quelle","vac.diag_platform":"Integration","vac.diag_status":"Status","vac.diag_position":"Position","vac.diag_rooms":"Räume","vac.diag_rooms_value":"{total} · {matched} Namen stimmen überein · {readiness}","vac.autocal_ready":"Auto-Kalibrierung verfügbar","vac.autocal_not_ready":"3 übereinstimmende Namen erforderlich","vac.diag_path":"Integrationspfad","vac.diag_map":"Karten-ID","vac.source_none":"nicht ausgewählt","vac.source_status_ok":"Bereit","vac.source_status_missing":"Fehlend","vac.source_status_disabled":"In Home Assistant deaktiviert","vac.source_status_unavailable":"Nicht verfügbar","vac.source_status_unverified":"Kann mit den aktuellen Berechtigungen nicht verifizieren","vac.source_status_unsupported":"Keine Positionsdaten","vac.source_status_none":"Keine Quelle","vac.source_banner_missing":"Die gespeicherte Quelle existiert nicht mehr. Sie wurde nicht automatisch ersetzt; wählen Sie eine andere Quelle oder stellen Sie sie in Home Assistant wieder her.","vac.source_banner_disabled":"Die gespeicherte Quelle ist in Home Assistant deaktiviert. Aktivieren Sie sie dort oder wählen Sie eine andere Quelle.","vac.source_banner_unverified":"Die aktuellen Home Assistant-Berechtigungen können diese gespeicherte Quelle nicht verifizieren. Sie bleibt angepinnt und wird nicht automatisch ersetzt.","vac.choose_source":"Quelle wählen","vac.source_auto":"Automatisch","vac.source_auto_hint":"Verwenden Sie eine kompatible Entität von diesem Gerät","vac.all_cameras":"Alle Kameras","vac.all_cameras_warn":"Eine Kamera liefert möglicherweise keine Roboter-Daten. Wählen Sie eine nur, wenn es Ihre Saugroboter-Karte ist.","vac.all_cameras_empty":"Keine anderen Kamera-Entitäten gefunden.","vac.platform_unknown":"unbekannte Integration","vac.cap_position":"Position","vac.cap_rooms_short":"Räume","vac.cap_path":"Pfad","vac.cap_map":"Karten-ID","vac.cap_none":"Keine Roboter-Daten erkannt","vac.xcme_hint":"Aktivieren Sie diese Xiaomi Cloud Map Extractor-Attribute:","vac.documentation":"Dokumentation","vac.residual_title":"Automatische Kalibrierung überprüfen","vac.residual_message":"Die zugeordneten Räume weichen um bis zu {error} voneinander ab. Diese ungefähre Kalibrierung anwenden, manuell verfeinern oder ohne Änderung der gespeicherten Einrichtung abbrechen.","vac.apply_proposal":"Anwenden","gs.backup_group":"Sichern und übertragen","gs.backup_hint":"Laden Sie ein tragbares JSON-Backup herunter oder sehen Sie eine Vorschau und importieren Sie ein Backup, das mit House Plan erstellt wurde.","backup.export_open":"Exportieren","backup.import_open":"Importieren","backup.export_title":"House Plan exportieren","backup.import_title":"House Plan importieren","backup.export_hint":"Wählen Sie, ob das Backup die gesamte House Plan-Konfiguration oder nur den aktuellen Bereich enthalten soll.","backup.full":"Vollständiges Backup","backup.current_space":"Aktueller Bereich","backup.current_space_title":"Aktueller Bereich: {title}","backup.no_current_space":"Kein aktueller Bereich","backup.plan_only":"Nur Plan","backup.plan_only_hint":"Räume, Wände, Öffnungen, Dekor und Raumbezeichnungspositionen ohne Geräte oder Home Assistant-Bindungen beibehalten.","backup.plan_only_preview":"Diese Datei enthält nur den Plan.","backup.privacy_warning":"Das Archiv enthält Namen, Home Assistant-Kennungen und genaue Koordinaten. Interne Pläne und Anhänge werden referenziert, nicht eingebettet; Laufzeitzustände und Staubsaugerspuren sind nicht enthalten.","backup.download":"JSON herunterladen","backup.export_done":"Backup heruntergeladen","backup.reading":"Überprüfe das Backup…","backup.revalidated":"Der Plan wurde nach dieser Vorschau geändert. Die Zusammenfassung wurde aktualisiert; überprüfen Sie sie und bestätigen Sie erneut.","backup.error.support_invalid_message":"Prüfen Sie die Supportnachricht und versuchen Sie es erneut.","backup.error.support_package_too_large":"Das anonymisierte Supportpaket überschreitet das Limit von 8 MiB.","backup.error.support_preview_expired":"Die Vorschau des Supportanhangs ist abgelaufen oder nicht mehr verfügbar.","backup.error.support_rate_limited":"Zu viele Supportberichte oder Vorschauen wurden angefordert. Versuchen Sie es später erneut.","backup.error.support_rejected":"Der Bericht hat die Prüfung des Supportdienstes nicht bestanden.","backup.error.support_unavailable":"Der private Supportdienst ist vorübergehend nicht verfügbar.","backup.error.unauthorized":"Sie haben keine Berechtigung, diesen Plan zu exportieren oder zu importieren.","backup.error.not_ready":"Der Hausplan ist noch nicht fertig. Versuchen Sie es in einem Moment erneut.","backup.error.too_large":"Das Backup überschreitet das 8-MiB-Limit.","backup.error.invalid_json":"Die ausgewählte Datei ist kein gültiges JSON.","backup.error.invalid_format":"Die ausgewählte Datei ist kein House Plan-Backup.","backup.error.invalid_image":"Das Bild ist beschädigt oder entspricht nicht seinem Format.","backup.error.unsupported_export_version":"Dieses Backup-Format wird von der installierten Version nicht unterstützt.","backup.error.unsupported_image":"Verwenden Sie ein unterstütztes PNG-, JPEG-, WebP- oder SVG-Bild.","backup.error.future_model":"Das Backup wurde mit einem neueren House-Plan-Datenmodell erstellt.","backup.error.invalid_config":"Das Backup enthält eine ungültige House-Plan-Konfiguration.","backup.error.wall_model_migration_blocked":"Das Backup-Wandmodell konnte nicht sicher aktualisiert werden. Optimieren Sie zuerst den Quellplan und exportieren Sie ihn dann erneut.","backup.error.invalid_layout":"Das Backup enthält ungültige Objektpositionen.","backup.error.invalid_content":"Das Backup enthält ungültige oder inkonsistente Inhaltsreferenzen.","backup.error.space_not_found":"Der ausgewählte Bereich existiert nicht mehr.","backup.error.capacity_exceeded":"Durch das Hinzufügen dieses Backups würden die Planlimits überschritten.","backup.error.preview_expired":"Die Vorschau ist abgelaufen. Wählen Sie die Backup-Datei erneut aus.","backup.error.preview_owner_mismatch":"Diese Vorschau gehört zu einem anderen Home-Assistant-Benutzer.","backup.error.conflict":"Der Plan hat sich nach der Vorschau geändert. Überprüfen Sie die aktualisierte Zusammenfassung.","backup.error.content_confirmation_required":"Bestätigen Sie, dass nicht verfügbare lokale Inhalte getrennt werden können.","backup.error.commit_failed":"Das Backup konnte nicht sicher angewendet werden. Der vorherige Plan wurde wiederhergestellt oder wartet auf die Wiederherstellung.","backup.error.missing_plan":"Eine referenzierte Plan-Datei ist nach der Vorschau verschwunden. Überprüfen Sie das Backup erneut.","backup.error.missing_content":"Ein referenziertes lokales Anhangselement ist nach der Vorschau verschwunden. Überprüfen Sie das Backup erneut.","backup.error.marker_control_missing":"Ein verknüpftes Planlicht fehlt im Backup.","backup.error.marker_control_not_light":"Ein verknüpftes Planziel ist nicht mehr als Lichtquelle markiert.","backup.error.marker_control_self":"Eine Lichtquelle kann sich nicht selbst steuern.","backup.error.marker_control_cycle":"Das Backup enthält eine kreisförmige Kette von Lichtsteuerungen.","backup.error.duplicate_marker_control":"Das Backup enthält eine doppelte Plan-Licht-Verknüpfung.","backup.error.no_backup":"Es gibt keinen Import- oder Optimierungssnapshot zur Wiederherstellung.","backup.error.in_use":"Das Element wird noch verwendet","backup.error.invalid_data":"Die Anfrage enthält ungültige Daten","backup.error.invalid_light_entity":"Das führende Licht muss eine light.*- oder switch.*-Entität sein","backup.error.invalid_marker_control":"Ungültige Marker-Steuerungsreferenz","backup.error.invalid_name":"Der Name ist ungültig","backup.error.invalid_partition_opening_host":"Die Öffnung muss ihren Trennwand-Träger behalten","backup.error.invalid_partition_opening_jamb_margin":"Die Öffnung lässt keinen physischen Pfosten am Wandende","backup.error.invalid_passage_fields":"Ein offener Durchgang kann keine Tür-Einstellungen tragen","backup.error.invalid_space_id":"Unbekannter Raumbereich","backup.error.invalid_toggle_entity":"Die Schalt-Entität muss light.* oder switch.* sein","backup.error.invalid_value_badge":"Ungültige Wert-Badge-Einstellungen","backup.error.invalid_value_badge_attribute":"Ungültiges Wert-Badge-Attribut","backup.error.invalid_value_badge_position":"Ungültige Wert-Badge-Position","backup.error.invalid_value_badge_source":"Ungültige Wert-Badge-Quelle","backup.error.invalid_vacuum_map_route":"Prüfen Sie die Zuordnung der Roboterkarten zu Räumen.","backup.error.invalid_value_source":"Ungültige Wertquelle","backup.error.invalid_value_source_attribute":"Ungültiges Wertquellen-Attribut","backup.error.io_error":"Eine Dateioperation auf dem Server ist fehlgeschlagen","backup.error.not_toggleable":"Dieses Gerät kann nicht geschaltet werden","backup.error.nothing_to_repair":"Nichts zu reparieren","backup.error.space_in_use":"Der Raumbereich wird noch referenziert","backup.error.value_badge_source_required":"Das Wert-Badge braucht eine Quelle","backup.error.wall_model_client_outdated":"Der Plan wurde anderswo aktualisiert — Seite neu laden","backup.same_source":"Erstellt auf dieser Home Assistant-Instanz","backup.foreign_source":"Erstellt auf einer anderen Home Assistant-Instanz","backup.created":"Erstellt: {value}","backup.versions":"Karte {card}; Integration {integration}; Datenmodell {model}","backup.count_spaces":"Bereiche: {n}","backup.count_rooms":"Räume: {n}","backup.count_walls":"Wände: {n}","backup.count_openings":"Öffnungen: {n}","backup.count_decor":"Dekorationsobjekte: {n}","backup.count_markers":"Geräte: {n}","backup.count_layout":"Positionen: {n}","backup.bindings":"Verknüpfungen — Geräte: {device}, Entitäten: {entity}, virtuell: {virtual}; Positionen ohne Bereich: {legacy}","backup.binding_status":"Zielstatus — aktiv: {active}, deaktiviert: {disabled}, fehlt: {missing}","backup.missing_areas":"Auf dem Ziel fehlende Bereiche: {areas}","backup.dropped_marker_links":"Planlicht-Verknüpfungen außerhalb dieses übertragenen Bereichs wurden ausgelassen: {n}.","backup.room_drafts_migrated":"Alte unvollständige Konturen wurden in normale Wände umgewandelt: {drafts}; Wandsegmente: {segments}.","backup.repaired_target_refs":"Durch den Import dieses Bereichs wiederhergestellte vorhandene Referenzen: {n}.","backup.preserved_unresolved_refs":"Referenzen, die nicht eindeutig wiederhergestellt werden konnten, wurden beibehalten: {n}.","backup.preserved_unresolved_hint":"Es wurden keine Daten geraten oder gelöscht. Führen Sie nach dem Import Optimierungspläne aus, um die verbleibenden Referenzen zu überprüfen.","backup.import_details":"Importieren von Referenzdetails","backup.import_detail.incoming_remapped":"Referenzen innerhalb der importierten Kopie aktualisiert: {n}","backup.import_detail.target_repaired":"Vorhandene Referenzen wiederhergestellt: {n}","backup.import_detail.preserved_unresolved":"Unaufgelöste Referenzen beibehalten: {n}","backup.import_detail.collisions":"Zielkonflikte sicher beibehalten: {n}","backup.import_detail.dropped_links":"Eingehende Links durch Übertragungsregeln ausgelassen: {n}","backup.import_detail.bounded_lineages":"Übermäßig verschachtelte Kennungen begrenzt belassen: {n}","backup.replace_warning":"Dies ersetzt die aktuelle Konfiguration und das Layout. Hochgeladene Dateien werden niemals gelöscht. Eine Rückgängig-Möglichkeit bleibt bis zur nächsten Planbearbeitung verfügbar.","backup.foreign_bookkeeping":"Instanzspezifische bekannte/neue Gerätebuchführung wird nicht importiert.","backup.final_name":"Name des neuen Bereichs","backup.target_settings":"Die globalen Einstellungen der Zielinstanz bleiben unverändert.","backup.duplicates":"Bindungen bereits vorhanden: {n}","backup.skip":"Doppelte Geräte überspringen","backup.virtual_copy":"Sichere statische virtuelle Kopien hinzufügen","backup.content":"Referenzierter Inhalt","backup.decor_images_summary":"Eigene Bilder: {objects} Objekte, {assets} Dateien; fehlende Dateien: {missing}.","backup.content_available":"lokal verfügbar","backup.content_external":"externer Link","backup.content_detach_required":"wird getrennt","backup.confirm_detach":"Ich verstehe, dass nicht verfügbare interne Pläne und Anhänge von der importierten Konfiguration getrennt werden.","backup.confirm_missing_images":"Ich verstehe, dass fehlende eigene Bilder als reparierbare Platzhalter erhalten bleiben und andere nicht verfügbare lokale Dateien getrennt werden.","backup.replace":"Ersetzen","backup.add":"Bereich hinzufügen","backup.space_done":"Bereich importiert: {rooms} Räume, {markers} Geräte, {refs} bestehende Referenzen wiederhergestellt","backup.full_done":"Backup wiederhergestellt: {spaces} Bereiche, {rooms} Räume, {markers} Geräte","backup.undo_import":"Letzten vollständigen Import rückgängig machen","backup.import_undone":"Vollständiger Import rückgängig gemacht","backdrop.large_title":"Großes Bild","backdrop.large_body":"Dieses Bild ist {w}×{h} ({fileMb} MB Datei) und benötigt etwa {decodedMb} MB Speicher zur Anzeige. Auf Tablets kann das die Seite zum Absturz bringen.","backdrop.unknown_body":"Die Bildabmessungen konnten nicht gelesen werden — die Datei ist möglicherweise beschädigt. Fortfahren kann die Seite auf Tablets zum Absturz bringen.","backdrop.reduced_dimensions":"Verkleinerte Kopie: {w}×{h} px.","backdrop.use_downscaled":"Verkleinerte Kopie hochladen","backdrop.reducing":"Wird verkleinert…","backdrop.keep_original":"Original behalten","backdrop.too_large_title":"Bild ist zu groß","backdrop.too_large_body":"Dieses Bild überschreitet die Anzeigegrenzen des Browsers ({w}×{h}, Limit {limit} px pro Seite). Bitte verkleinern Sie es in einem Desktop-Editor und laden Sie es erneut hoch.","backdrop.downscale_failed":"Die verkleinerte Kopie konnte nicht erstellt werden. Der aktuelle Plan wurde nicht geändert."};const n="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";export{e as dictionary,n as fingerprint};
diff --git a/custom_components/houseplan/frontend/houseplan-assets/editor-DC4i4Aam.js b/dist/houseplan-assets/editor-B6aLEVVy.js
similarity index 93%
rename from custom_components/houseplan/frontend/houseplan-assets/editor-DC4i4Aam.js
rename to dist/houseplan-assets/editor-B6aLEVVy.js
index ba472581..48b6a94f 100644
--- a/custom_components/houseplan/frontend/houseplan-assets/editor-DC4i4Aam.js
+++ b/dist/houseplan-assets/editor-B6aLEVVy.js
@@ -1,4 +1,4 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{t as e,l as o,x as t,dM as s,A as a,dN as i,dO as l,dP as n,dL as r,b as c}from"./houseplan-card-B_QYG0Py.js";class f extends e{constructor(){super(...arguments),this._spaces=null,this._spacesLoading=!1,this._spacesAuthoritative=!1}setConfig(e){this._config=e}async _loadSpaces(){if(!this._spaces&&!this._spacesLoading&&this.hass){this._spacesLoading=!0;try{const e=await this.hass.callWS({type:"houseplan/config/get"});this._spaces=(e?.config?.spaces||[]).map(e=>({value:e.id,label:e.title||e.id})),this._spacesAuthoritative=!0}catch{this._spaces=[],this._spacesAuthoritative=!1}finally{this._spacesLoading=!1}}}get _lang(){return o(this.hass,this._config?.language)}get _floorToken(){const e=this._config?.floor;return"number"==typeof e?`__houseplan_yaml_floor_index__:${String(e)}`:null}get _formData(){const e={...this._config},o=this._floorToken;return o?e.floor=o:Object.prototype.hasOwnProperty.call(e,"floor")||(e.floor=""),e}get _schema(){const e=this._spaces||[],o=this._lang,a=[{value:"",label:t(o,"editor.floor_none")}],i=this._floorToken;i&&a.push({value:i,label:t(o,"editor.floor_index",{index:String(this._config?.floor)})});const l="string"==typeof this._config?.floor?this._config.floor:"";l&&!e.some(e=>e.value===l)&&a.push({value:l,label:l}),a.push(...e);const n="string"==typeof this._config?.default_floor?this._config.default_floor:"",r=[...e];return n&&!e.some(e=>e.value===n)&&r.unshift({value:n,label:n}),[{name:"title",selector:{text:{}}},{name:"floor",selector:{select:{mode:"dropdown",options:a}}},e.length?{name:"default_floor",selector:{select:{mode:"dropdown",options:r}}}:{name:"default_floor",selector:{text:{}}},{name:"language",selector:{select:{mode:"dropdown",options:s(t(o,"editor.lang_auto"),this._config?.language)}}},{name:"icon_size",selector:{number:{min:1,max:6,step:.1,mode:"box"}}},{name:"show_temperature",selector:{boolean:{}}},{name:"live_states",selector:{boolean:{}}},{name:"show_signal",selector:{boolean:{}}},{name:"kiosk",selector:{boolean:{}}},{name:"cycle",selector:{number:{min:0,max:3600,step:5,mode:"box"}}}]}render(){if(!this.hass||!this._config)return a;const e=i(this,l,o(this.hass,this._config.language));if("cold"===e)return n();if("warm"===e)return r;this._loadSpaces();const s=this._lang,f={title:t(s,"editor.title"),floor:t(s,"editor.floor"),default_floor:t(s,"editor.default_floor"),language:t(s,"editor.language"),icon_size:t(s,"editor.icon_size"),show_temperature:t(s,"editor.show_temperature"),live_states:t(s,"editor.live_states"),show_signal:t(s,"editor.show_signal"),kiosk:t(s,"editor.kiosk"),cycle:t(s,"editor.cycle")},h=this._schema,_=function(e,o,t){if(!t||null===o)return null;const s="string"==typeof e?.default_floor?e.default_floor:"";return!s||o.some(e=>e.value===s)?null:s}(this._config,this._spaces,this._spacesAuthoritative),d=e=>c`({value:e.id,label:e.title||e.id})),this._spacesAuthoritative=!0}catch{this._spaces=[],this._spacesAuthoritative=!1}finally{this._spacesLoading=!1}}}get _lang(){return o(this.hass,this._config?.language)}get _floorToken(){const e=this._config?.floor;return"number"==typeof e?`__houseplan_yaml_floor_index__:${String(e)}`:null}get _formData(){const e={...this._config},o=this._floorToken;return o?e.floor=o:Object.prototype.hasOwnProperty.call(e,"floor")||(e.floor=""),e}get _schema(){const e=this._spaces||[],o=this._lang,a=[{value:"",label:t(o,"editor.floor_none")}],i=this._floorToken;i&&a.push({value:i,label:t(o,"editor.floor_index",{index:String(this._config?.floor)})});const l="string"==typeof this._config?.floor?this._config.floor:"";l&&!e.some(e=>e.value===l)&&a.push({value:l,label:l}),a.push(...e);const n="string"==typeof this._config?.default_floor?this._config.default_floor:"",r=[...e];return n&&!e.some(e=>e.value===n)&&r.unshift({value:n,label:n}),[{name:"title",selector:{text:{}}},{name:"floor",selector:{select:{mode:"dropdown",options:a}}},e.length?{name:"default_floor",selector:{select:{mode:"dropdown",options:r}}}:{name:"default_floor",selector:{text:{}}},{name:"language",selector:{select:{mode:"dropdown",options:s(t(o,"editor.lang_auto"),this._config?.language)}}},{name:"icon_size",selector:{number:{min:1,max:6,step:.1,mode:"box"}}},{name:"show_temperature",selector:{boolean:{}}},{name:"live_states",selector:{boolean:{}}},{name:"show_signal",selector:{boolean:{}}},{name:"kiosk",selector:{boolean:{}}},{name:"cycle",selector:{number:{min:0,max:3600,step:5,mode:"box"}}}]}render(){if(!this.hass||!this._config)return a;const e=i(this,l,o(this.hass,this._config.language));if("cold"===e)return n();if("warm"===e)return r;this._loadSpaces();const s=this._lang,f={title:t(s,"editor.title"),floor:t(s,"editor.floor"),default_floor:t(s,"editor.default_floor"),language:t(s,"editor.language"),icon_size:t(s,"editor.icon_size"),show_temperature:t(s,"editor.show_temperature"),live_states:t(s,"editor.live_states"),show_signal:t(s,"editor.show_signal"),kiosk:t(s,"editor.kiosk"),cycle:t(s,"editor.cycle")},h=this._schema,_=function(e,o,t){if(!t||null===o)return null;const s="string"==typeof e?.default_floor?e.default_floor:"";return!s||o.some(e=>e.value===s)?null:s}(this._config,this._spaces,this._spacesAuthoritative),d=e=>c`r===this.ot[t]))return e}else if(this.ot===t)return e;return this.ot=Array.isArray(t)?Array.from(t):t,this.render(t,s)}});export{a as i};
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{dK as r,dL as t,dM as e}from"./houseplan-card-6Hf8VPda.js";const s={},a=r(class extends t{constructor(){super(...arguments),this.ot=s}render(r,t){return t()}update(r,[t,s]){if(Array.isArray(t)){if(Array.isArray(this.ot)&&this.ot.length===t.length&&t.every((r,t)=>r===this.ot[t]))return e}else if(this.ot===t)return e;return this.ot=Array.isArray(t)?Array.from(t):t,this.render(t,s)}});export{a as i};
diff --git a/dist/houseplan-assets/houseplan-card-B_QYG0Py.js b/dist/houseplan-assets/houseplan-card-6Hf8VPda.js
similarity index 95%
rename from dist/houseplan-assets/houseplan-card-B_QYG0Py.js
rename to dist/houseplan-assets/houseplan-card-6Hf8VPda.js
index b4a1fabf..9f93d9c0 100644
--- a/dist/houseplan-assets/houseplan-card-B_QYG0Py.js
+++ b/dist/houseplan-assets/houseplan-card-6Hf8VPda.js
@@ -1,4 +1,4 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";const e=globalThis,t=e.ShadowRoot&&(void 0===e.ShadyCSS||e.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,i=Symbol(),n=new WeakMap;let r=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==i)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const i=this.t;if(t&&void 0===e){const t=void 0!==i&&1===i.length;t&&(e=n.get(i)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),t&&n.set(i,e))}return e}toString(){return this.cssText}};const o=(e,...t)=>{const n=1===e.length?e[0]:t.reduce((t,i,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[n+1],e[0]);return new r(n,e,i)},s=t?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return(e=>new r("string"==typeof e?e:e+"",void 0,i))(t)})(e):e,{is:a,defineProperty:l,getOwnPropertyDescriptor:c,getOwnPropertyNames:h,getOwnPropertySymbols:d,getPrototypeOf:u}=Object,p=globalThis,_=p.trustedTypes,m=_?_.emptyScript:"",g=p.reactiveElementPolyfillSupport,f=(e,t)=>e,v={toAttribute(e,t){switch(t){case Boolean:e=e?m:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch(e){i=null}}return i}},y=(e,t)=>!a(e,t),b={attribute:!0,type:String,converter:v,reflect:!1,useDefault:!1,hasChanged:y};Symbol.metadata??=Symbol("metadata"),p.litPropertyMetadata??=new WeakMap;let w=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=b){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(e,i,t);void 0!==n&&l(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){const{get:n,set:r}=c(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const o=n?.call(this);r?.call(this,t),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??b}static _$Ei(){if(this.hasOwnProperty(f("elementProperties")))return;const e=u(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(f("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(f("properties"))){const e=this.properties,t=[...h(e),...d(e)];for(const i of t)this.createProperty(i,e[i])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const i=this._$Eu(e,t);void 0!==i&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const e of i)t.unshift(s(e))}else void 0!==e&&t.push(s(e));return t}static _$Eu(e,t){const i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const i=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((i,n)=>{if(t)i.adoptedStyleSheets=n.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const t of n){const n=document.createElement("style"),r=e.litNonce;void 0!==r&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}})(i,this.constructor.elementStyles),i}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){const i=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,i);if(void 0!==n&&!0===i.reflect){const r=(void 0!==i.converter?.toAttribute?i.converter:v).toAttribute(t,i.type);this._$Em=e,null==r?this.removeAttribute(n):this.setAttribute(n,r),this._$Em=null}}_$AK(e,t){const i=this.constructor,n=i._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=i.getPropertyOptions(n),r="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:v;this._$Em=n;const o=r.fromAttribute(t,e.type);this[n]=o??this._$Ej?.get(n)??o,this._$Em=null}}requestUpdate(e,t,i,n=!1,r){if(void 0!==e){const o=this.constructor;if(!1===n&&(r=this[e]),i??=o.getPropertyOptions(e),!((i.hasChanged??y)(r,t)||i.useDefault&&i.reflect&&r===this._$Ej?.get(e)&&!this.hasAttribute(o._$Eu(e,i))))return;this.C(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:n,wrapped:r},o){i&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,o??t??this[e]),!0!==r||void 0!==o)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,i]of e){const{wrapped:e}=i,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,i,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};w.elementStyles=[],w.shadowRootOptions={mode:"open"},w[f("elementProperties")]=new Map,w[f("finalized")]=new Map,g?.({ReactiveElement:w}),(p.reactiveElementVersions??=[]).push("2.1.2");const k=globalThis,x=e=>e,S=k.trustedTypes,$=S?S.createPolicy("lit-html",{createHTML:e=>e}):void 0,M="$lit$",R=`lit$${Math.random().toFixed(9).slice(2)}$`,C="?"+R,T=`<${C}>`,D=document,A=()=>D.createComment(""),P=e=>null===e||"object"!=typeof e&&"function"!=typeof e,F=Array.isArray,z="[ \t\n\f\r]",I=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,O=/-->/g,E=/>/g,N=RegExp(`>|${z}(?:([^\\s"'>=/]+)(${z}*=${z}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),H=/'/g,L=/"/g,B=/^(?:script|style|textarea|title)$/i,q=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),j=q(1),W=q(2),U=Symbol.for("lit-noChange"),V=Symbol.for("lit-nothing"),G=new WeakMap,K=D.createTreeWalker(D,129);function Y(e,t){if(!F(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==$?$.createHTML(t):t}const X=(e,t)=>{const i=e.length-1,n=[];let r,o=2===t?"":3===t?"":"")),n]};class Z{constructor({strings:e,_$litType$:t},i){let n;this.parts=[];let r=0,o=0;const s=e.length-1,a=this.parts,[l,c]=X(e,t);if(this.el=Z.createElement(l,i),K.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(n=K.nextNode())&&a.length0){n.textContent=S?S.emptyScript:"";for(let i=0;iF(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==V&&P(this._$AH)?this._$AA.nextSibling.data=e:this.T(D.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:i}=e,n="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=Z.createElement(Y(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new Q(n,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=G.get(e.strings);return void 0===t&&G.set(e.strings,t=new Z(e)),t}k(e){F(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,n=0;for(const r of e)n===t.length?t.push(i=new ee(this.O(A()),this.O(A()),this,this.options)):i=t[n],i._$AI(r),n++;n2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=V}_$AI(e,t=this,i,n){const r=this.strings;let o=!1;if(void 0===r)e=J(this,e,t,0),o=!P(e)||e!==this._$AH&&e!==U,o&&(this._$AH=e);else{const n=e;let s,a;for(e=r[0],s=0;s{const n=i?.renderBefore??t;let r=n._$litPart$;if(void 0===r){const e=i?.renderBefore??null;n._$litPart$=r=new ee(t.insertBefore(A(),e),e,void 0,i??{})}return r._$AI(e),r},ce=globalThis;let he=class extends w{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=le(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return U}};he._$litElement$=!0,he.finalized=!0,ce.litElementHydrateSupport?.({LitElement:he});const de=ce.litElementPolyfillSupport;de?.({LitElement:he}),(ce.litElementVersions??=[]).push("4.2.2");const ue=2,pe=e=>(...t)=>({_$litDirective$:e,values:t});let _e=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};const{I:me}=se,ge=e=>e,fe=(e,t)=>void 0!==e?._$litType$,ve=()=>document.createComment(""),ye=(e,t,i)=>{const n=e._$AA.parentNode,r=void 0===t?e._$AB:t._$AA;if(void 0===i){const t=n.insertBefore(ve(),r),o=n.insertBefore(ve(),r);i=new me(t,o,e,e.options)}else{const t=i._$AB.nextSibling,o=i._$AM,s=o!==e;if(s){let t;i._$AQ?.(e),i._$AM=e,void 0!==i._$AP&&(t=e._$AU)!==o._$AU&&i._$AP(t)}if(t!==r||s){let e=i._$AA;for(;e!==t;){const t=ge(e).nextSibling;ge(n).insertBefore(e,r),e=t}}}return i},be=(e,t,i=e)=>(e._$AI(t,i),e),we={},ke=(e,t=we)=>e._$AH=t,xe=e=>e._$AH,Se=e=>{e._$AR(),e._$AA.remove()},$e=e=>(e=>null!=e?._$litType$?.h)(e)?e._$litType$.h:e.strings,Me=pe(class extends _e{constructor(e){super(e),this.et=new WeakMap}render(e){return[e]}update(e,[t]){const i=fe(this.it)?$e(this.it):null,n=fe(t)?$e(t):null;if(null!==i&&(null===n||i!==n)){const t=xe(e).pop();let n=this.et.get(i);if(void 0===n){const e=document.createDocumentFragment();n=le(V,e),n.setConnected(!1),this.et.set(i,n)}ke(n,[t]),ye(n,void 0,t)}if(null!==n){if(null===i||i!==n){const t=this.et.get(n);if(void 0!==t){const i=xe(t).pop();(e=>{e._$AR()})(e),ye(e,void 0,i),ke(e,[i])}}this.it=t}else this.it=void 0;return this.render(t)}}),Re=new WeakMap;let Ce=0;class Te extends he{constructor(){super(...arguments),this.title="",this.icon="",this.wide=!1,this.alert=!1,this.describedBy="",this.dismissOnScrim=!1,this.hass=null,this._opener=null,this._focusRoot=null,this._useHaDialog=null,this._closing=!1,this._overlays=[],this._titleId="hp-dialog-title-"+ ++Ce,this._focusInitial=()=>{const e=this._focusableElements(),t=e.find(e=>e.hasAttribute("autofocus"))||e[0]||(this._usesHaDialog()?null:this.renderRoot.querySelector(".close"))||this.renderRoot.querySelector(".surface")||this.renderRoot.querySelector("ha-dialog");t?.focus({preventScroll:!0})},this._requestClose=()=>{this._closing||(this._closing=!0,this.dispatchEvent(new CustomEvent("hp-close",{bubbles:!0,composed:!0})))},this._onKeyDown=e=>{if("Escape"===e.key){e.preventDefault(),e.stopImmediatePropagation(),this._pruneOverlays();const t=this._overlays[this._overlays.length-1];return t?void this._closeOverlay(t,"escape"):void this._requestClose()}if("Tab"!==e.key||this._usesHaDialog())return;const t=this.renderRoot.querySelector(".close"),i=t?[t,...this._focusableElements()]:this._focusableElements();if(!i.length)return e.preventDefault(),void this.renderRoot.querySelector(".surface")?.focus({preventScroll:!0});const n=this._deepActiveElement(),r=i[0],o=i[i.length-1];!e.shiftKey||n!==r&&i.includes(n)?e.shiftKey||n!==o||(e.preventDefault(),r.focus()):(e.preventDefault(),o.focus())},this._onFallbackCancel=e=>{e.preventDefault(),this._requestClose()},this._onFallbackClick=e=>{this.dismissOnScrim&&e.target===e.currentTarget&&this._requestClose()}}_usesHaDialog(){return!0===this._useHaDialog&&!this.alert}connectedCallback(){super.connectedCallback(),this._opener=this._deepActiveElement();const e=this.getRootNode();this._focusRoot=e;const t=Re.get(e)||{dialogs:new Set,opener:this._opener};t.dialogs.add(this),Re.set(e,t),null===this._useHaDialog&&(this._useHaDialog=!!customElements.get("ha-dialog")),this.addEventListener("keydown",this._onKeyDown,!0),queueMicrotask(()=>{this._ensureNativeModal()&&this._focusInitial()})}disconnectedCallback(){this.removeEventListener("keydown",this._onKeyDown,!0);const e=[...this._overlays];this._overlays=[];for(const t of e.reverse())t.close("disconnect");const t=this._focusRoot,i=this._opener;this._opener=null,this._focusRoot=null;const n=t?Re.get(t):void 0;n?.dialogs.delete(this),super.disconnectedCallback(),t&&n&&requestAnimationFrame(()=>{const e=Re.get(t);if(!e)return;if(!e.dialogs.size)return e.opener?.isConnected&&e.opener.focus({preventScroll:!0}),void Re.delete(t);const n=i?.closest("hp-dialog");i?.isConnected&&n&&e.dialogs.has(n)&&i.focus({preventScroll:!0})})}firstUpdated(e){super.firstUpdated(e),this._ensureNativeModal(),queueMicrotask(()=>this._focusInitial())}updated(e){super.updated(e),this._ensureNativeModal()}_ensureNativeModal(){if(this._usesHaDialog()||!this.isConnected)return!1;const e=this.renderRoot.querySelector("dialog");if(!e?.isConnected)return!1;try{return!e.matches(":modal")&&(e.open&&e.close(),e.showModal(),!0)}catch{return!1}}_deepActiveElement(){let e=document.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return e&&e!==document.body?e:null}_focusableElements(){const e=["[autofocus]","a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(","),t=[],i=new Set,n=r=>{if(!i.has(r)){if(i.add(r),r instanceof HTMLElement){if(r.matches(e)&&t.push(r),r instanceof HTMLSlotElement){for(const e of r.assignedNodes({flatten:!0}))n(e);return}if(r.shadowRoot){for(const e of r.shadowRoot.childNodes)n(e);return}}for(const e of r.childNodes)n(e)}};for(const e of this.childNodes)n(e);const r=this.overlayPortal();return r&&n(r),t.filter(e=>{let t=e;for(;t;){const e=getComputedStyle(t);if(t.hidden||t.inert||"true"===t.getAttribute("aria-hidden")||"none"===e.display||"hidden"===e.visibility)return!1;if(t=t.assignedSlot||t.parentElement||(t.getRootNode()instanceof ShadowRoot?t.getRootNode().host:null),t===this)break}return!0})}rejectClose(){this._closing=!1,this.requestUpdate()}_pruneOverlays(){this._overlays=this._overlays.filter(e=>e.owner.isConnected)}_closeOverlay(e,t){const i=this._overlays.findIndex(t=>t.token===e.token);i>=0&&this._overlays.splice(i,1),e.close(t)}registerOverlay(e){this._pruneOverlays();const t=this._overlays.find(t=>t.owner===e.owner);t&&this._overlays.splice(this._overlays.indexOf(t),1);const i=e.group||"transient";for(const e of[...this._overlays].reverse())e.group===i&&this._closeOverlay(e,"exclusive");const n={...e,group:i,token:Symbol("hp-overlay")};this._overlays.push(n);let r=!1;return()=>{if(r)return;r=!0;const e=this._overlays.findIndex(e=>e.token===n.token);e>=0&&this._overlays.splice(e,1)}}closeTransientOverlays(e="outside"){this._pruneOverlays();const t=[...this._overlays].filter(e=>"transient"===(e.group||"transient"));for(const i of t.reverse())this._closeOverlay(i,e);return t.length>0}overlayPortal(){return this.renderRoot.querySelector(".overlay-portal")}render(){const e=j`
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";const e=globalThis,t=e.ShadowRoot&&(void 0===e.ShadyCSS||e.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,i=Symbol(),n=new WeakMap;let r=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==i)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const i=this.t;if(t&&void 0===e){const t=void 0!==i&&1===i.length;t&&(e=n.get(i)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),t&&n.set(i,e))}return e}toString(){return this.cssText}};const o=(e,...t)=>{const n=1===e.length?e[0]:t.reduce((t,i,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[n+1],e[0]);return new r(n,e,i)},s=t?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return(e=>new r("string"==typeof e?e:e+"",void 0,i))(t)})(e):e,{is:a,defineProperty:l,getOwnPropertyDescriptor:c,getOwnPropertyNames:h,getOwnPropertySymbols:d,getPrototypeOf:u}=Object,p=globalThis,_=p.trustedTypes,m=_?_.emptyScript:"",g=p.reactiveElementPolyfillSupport,f=(e,t)=>e,v={toAttribute(e,t){switch(t){case Boolean:e=e?m:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch(e){i=null}}return i}},y=(e,t)=>!a(e,t),b={attribute:!0,type:String,converter:v,reflect:!1,useDefault:!1,hasChanged:y};Symbol.metadata??=Symbol("metadata"),p.litPropertyMetadata??=new WeakMap;let w=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=b){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(e,i,t);void 0!==n&&l(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){const{get:n,set:r}=c(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const o=n?.call(this);r?.call(this,t),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??b}static _$Ei(){if(this.hasOwnProperty(f("elementProperties")))return;const e=u(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(f("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(f("properties"))){const e=this.properties,t=[...h(e),...d(e)];for(const i of t)this.createProperty(i,e[i])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const i=this._$Eu(e,t);void 0!==i&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const e of i)t.unshift(s(e))}else void 0!==e&&t.push(s(e));return t}static _$Eu(e,t){const i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const i=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((i,n)=>{if(t)i.adoptedStyleSheets=n.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const t of n){const n=document.createElement("style"),r=e.litNonce;void 0!==r&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}})(i,this.constructor.elementStyles),i}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){const i=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,i);if(void 0!==n&&!0===i.reflect){const r=(void 0!==i.converter?.toAttribute?i.converter:v).toAttribute(t,i.type);this._$Em=e,null==r?this.removeAttribute(n):this.setAttribute(n,r),this._$Em=null}}_$AK(e,t){const i=this.constructor,n=i._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=i.getPropertyOptions(n),r="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:v;this._$Em=n;const o=r.fromAttribute(t,e.type);this[n]=o??this._$Ej?.get(n)??o,this._$Em=null}}requestUpdate(e,t,i,n=!1,r){if(void 0!==e){const o=this.constructor;if(!1===n&&(r=this[e]),i??=o.getPropertyOptions(e),!((i.hasChanged??y)(r,t)||i.useDefault&&i.reflect&&r===this._$Ej?.get(e)&&!this.hasAttribute(o._$Eu(e,i))))return;this.C(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:n,wrapped:r},o){i&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,o??t??this[e]),!0!==r||void 0!==o)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,i]of e){const{wrapped:e}=i,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,i,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};w.elementStyles=[],w.shadowRootOptions={mode:"open"},w[f("elementProperties")]=new Map,w[f("finalized")]=new Map,g?.({ReactiveElement:w}),(p.reactiveElementVersions??=[]).push("2.1.2");const k=globalThis,x=e=>e,S=k.trustedTypes,$=S?S.createPolicy("lit-html",{createHTML:e=>e}):void 0,M="$lit$",R=`lit$${Math.random().toFixed(9).slice(2)}$`,C="?"+R,T=`<${C}>`,D=document,A=()=>D.createComment(""),P=e=>null===e||"object"!=typeof e&&"function"!=typeof e,F=Array.isArray,z="[ \t\n\f\r]",I=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,O=/-->/g,E=/>/g,N=RegExp(`>|${z}(?:([^\\s"'>=/]+)(${z}*=${z}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),H=/'/g,L=/"/g,B=/^(?:script|style|textarea|title)$/i,q=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),j=q(1),W=q(2),U=Symbol.for("lit-noChange"),V=Symbol.for("lit-nothing"),G=new WeakMap,K=D.createTreeWalker(D,129);function Y(e,t){if(!F(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==$?$.createHTML(t):t}const X=(e,t)=>{const i=e.length-1,n=[];let r,o=2===t?"":3===t?"":"")),n]};class Z{constructor({strings:e,_$litType$:t},i){let n;this.parts=[];let r=0,o=0;const s=e.length-1,a=this.parts,[l,c]=X(e,t);if(this.el=Z.createElement(l,i),K.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(n=K.nextNode())&&a.length0){n.textContent=S?S.emptyScript:"";for(let i=0;iF(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==V&&P(this._$AH)?this._$AA.nextSibling.data=e:this.T(D.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:i}=e,n="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=Z.createElement(Y(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new Q(n,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=G.get(e.strings);return void 0===t&&G.set(e.strings,t=new Z(e)),t}k(e){F(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,n=0;for(const r of e)n===t.length?t.push(i=new ee(this.O(A()),this.O(A()),this,this.options)):i=t[n],i._$AI(r),n++;n2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=V}_$AI(e,t=this,i,n){const r=this.strings;let o=!1;if(void 0===r)e=J(this,e,t,0),o=!P(e)||e!==this._$AH&&e!==U,o&&(this._$AH=e);else{const n=e;let s,a;for(e=r[0],s=0;s{const n=i?.renderBefore??t;let r=n._$litPart$;if(void 0===r){const e=i?.renderBefore??null;n._$litPart$=r=new ee(t.insertBefore(A(),e),e,void 0,i??{})}return r._$AI(e),r},ce=globalThis;let he=class extends w{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=le(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return U}};he._$litElement$=!0,he.finalized=!0,ce.litElementHydrateSupport?.({LitElement:he});const de=ce.litElementPolyfillSupport;de?.({LitElement:he}),(ce.litElementVersions??=[]).push("4.2.2");const ue=2,pe=e=>(...t)=>({_$litDirective$:e,values:t});let _e=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};const{I:me}=se,ge=e=>e,fe=(e,t)=>void 0!==e?._$litType$,ve=()=>document.createComment(""),ye=(e,t,i)=>{const n=e._$AA.parentNode,r=void 0===t?e._$AB:t._$AA;if(void 0===i){const t=n.insertBefore(ve(),r),o=n.insertBefore(ve(),r);i=new me(t,o,e,e.options)}else{const t=i._$AB.nextSibling,o=i._$AM,s=o!==e;if(s){let t;i._$AQ?.(e),i._$AM=e,void 0!==i._$AP&&(t=e._$AU)!==o._$AU&&i._$AP(t)}if(t!==r||s){let e=i._$AA;for(;e!==t;){const t=ge(e).nextSibling;ge(n).insertBefore(e,r),e=t}}}return i},be=(e,t,i=e)=>(e._$AI(t,i),e),we={},ke=(e,t=we)=>e._$AH=t,xe=e=>e._$AH,Se=e=>{e._$AR(),e._$AA.remove()},$e=e=>(e=>null!=e?._$litType$?.h)(e)?e._$litType$.h:e.strings,Me=pe(class extends _e{constructor(e){super(e),this.et=new WeakMap}render(e){return[e]}update(e,[t]){const i=fe(this.it)?$e(this.it):null,n=fe(t)?$e(t):null;if(null!==i&&(null===n||i!==n)){const t=xe(e).pop();let n=this.et.get(i);if(void 0===n){const e=document.createDocumentFragment();n=le(V,e),n.setConnected(!1),this.et.set(i,n)}ke(n,[t]),ye(n,void 0,t)}if(null!==n){if(null===i||i!==n){const t=this.et.get(n);if(void 0!==t){const i=xe(t).pop();(e=>{e._$AR()})(e),ye(e,void 0,i),ke(e,[i])}}this.it=t}else this.it=void 0;return this.render(t)}}),Re=new WeakMap;let Ce=0;class Te extends he{constructor(){super(...arguments),this.title="",this.icon="",this.wide=!1,this.alert=!1,this.describedBy="",this.dismissOnScrim=!1,this.hass=null,this._opener=null,this._focusRoot=null,this._useHaDialog=null,this._closing=!1,this._overlays=[],this._titleId="hp-dialog-title-"+ ++Ce,this._focusInitial=()=>{const e=this._focusableElements(),t=e.find(e=>e.hasAttribute("autofocus"))||e[0]||(this._usesHaDialog()?null:this.renderRoot.querySelector(".close"))||this.renderRoot.querySelector(".surface")||this.renderRoot.querySelector("ha-dialog");t?.focus({preventScroll:!0})},this._requestClose=()=>{this._closing||(this._closing=!0,this.dispatchEvent(new CustomEvent("hp-close",{bubbles:!0,composed:!0})))},this._onKeyDown=e=>{if("Escape"===e.key){e.preventDefault(),e.stopImmediatePropagation(),this._pruneOverlays();const t=this._overlays[this._overlays.length-1];return t?void this._closeOverlay(t,"escape"):void this._requestClose()}if("Tab"!==e.key||this._usesHaDialog())return;const t=this.renderRoot.querySelector(".close"),i=t?[t,...this._focusableElements()]:this._focusableElements();if(!i.length)return e.preventDefault(),void this.renderRoot.querySelector(".surface")?.focus({preventScroll:!0});const n=this._deepActiveElement(),r=i[0],o=i[i.length-1];!e.shiftKey||n!==r&&i.includes(n)?e.shiftKey||n!==o||(e.preventDefault(),r.focus()):(e.preventDefault(),o.focus())},this._onFallbackCancel=e=>{e.preventDefault(),this._requestClose()},this._onFallbackClick=e=>{this.dismissOnScrim&&e.target===e.currentTarget&&this._requestClose()}}_usesHaDialog(){return!0===this._useHaDialog&&!this.alert}connectedCallback(){super.connectedCallback(),this._opener=this._deepActiveElement();const e=this.getRootNode();this._focusRoot=e;const t=Re.get(e)||{dialogs:new Set,opener:this._opener};t.dialogs.add(this),Re.set(e,t),null===this._useHaDialog&&(this._useHaDialog=!!customElements.get("ha-dialog")),this.addEventListener("keydown",this._onKeyDown,!0),queueMicrotask(()=>{this._ensureNativeModal()&&this._focusInitial()})}disconnectedCallback(){this.removeEventListener("keydown",this._onKeyDown,!0);const e=[...this._overlays];this._overlays=[];for(const t of e.reverse())t.close("disconnect");const t=this._focusRoot,i=this._opener;this._opener=null,this._focusRoot=null;const n=t?Re.get(t):void 0;n?.dialogs.delete(this),super.disconnectedCallback(),t&&n&&requestAnimationFrame(()=>{const e=Re.get(t);if(!e)return;if(!e.dialogs.size)return e.opener?.isConnected&&e.opener.focus({preventScroll:!0}),void Re.delete(t);const n=i?.closest("hp-dialog");i?.isConnected&&n&&e.dialogs.has(n)&&i.focus({preventScroll:!0})})}firstUpdated(e){super.firstUpdated(e),this._ensureNativeModal(),queueMicrotask(()=>this._focusInitial())}updated(e){super.updated(e),this._ensureNativeModal()}_ensureNativeModal(){if(this._usesHaDialog()||!this.isConnected)return!1;const e=this.renderRoot.querySelector("dialog");if(!e?.isConnected)return!1;try{return!e.matches(":modal")&&(e.open&&e.close(),e.showModal(),!0)}catch{return!1}}_deepActiveElement(){let e=document.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return e&&e!==document.body?e:null}_focusableElements(){const e=["[autofocus]","a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(","),t=[],i=new Set,n=r=>{if(!i.has(r)){if(i.add(r),r instanceof HTMLElement){if(r.matches(e)&&t.push(r),r instanceof HTMLSlotElement){for(const e of r.assignedNodes({flatten:!0}))n(e);return}if(r.shadowRoot){for(const e of r.shadowRoot.childNodes)n(e);return}}for(const e of r.childNodes)n(e)}};for(const e of this.childNodes)n(e);const r=this.overlayPortal();return r&&n(r),t.filter(e=>{let t=e;for(;t;){const e=getComputedStyle(t);if(t.hidden||t.inert||"true"===t.getAttribute("aria-hidden")||"none"===e.display||"hidden"===e.visibility)return!1;if(t=t.assignedSlot||t.parentElement||(t.getRootNode()instanceof ShadowRoot?t.getRootNode().host:null),t===this)break}return!0})}rejectClose(){this._closing=!1,this.requestUpdate()}_pruneOverlays(){this._overlays=this._overlays.filter(e=>e.owner.isConnected)}_closeOverlay(e,t){const i=this._overlays.findIndex(t=>t.token===e.token);i>=0&&this._overlays.splice(i,1),e.close(t)}registerOverlay(e){this._pruneOverlays();const t=this._overlays.find(t=>t.owner===e.owner);t&&this._overlays.splice(this._overlays.indexOf(t),1);const i=e.group||"transient";for(const e of[...this._overlays].reverse())e.group===i&&this._closeOverlay(e,"exclusive");const n={...e,group:i,token:Symbol("hp-overlay")};this._overlays.push(n);let r=!1;return()=>{if(r)return;r=!0;const e=this._overlays.findIndex(e=>e.token===n.token);e>=0&&this._overlays.splice(e,1)}}closeTransientOverlays(e="outside"){this._pruneOverlays();const t=[...this._overlays].filter(e=>"transient"===(e.group||"transient"));for(const i of t.reverse())this._closeOverlay(i,e);return t.length>0}overlayPortal(){return this.renderRoot.querySelector(".overlay-portal")}render(){const e=j`
${this.icon?j``:V}
${this.title}`;return this._usesHaDialog()?this.describedBy?j`
`})}
-
`}const yr={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},br=(e,t=1)=>{const i=Number(e);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):t},wr=e=>{let t=Number(e);return Number.isFinite(t)?(t=(t%360+360)%360,t>180?t-360:t):0};function kr(e,t,i){return wr(t)?[e.x,e.y]:i([e.x,e.y])}function xr(e,t,i,n){const r=Math.abs(i[0]-t[0]),o=Math.abs(i[1]-t[1]);return"line"===e?Math.hypot(r,o)>=n:r>=n&&o>=n}const Sr=(e,t,i)=>{const n=Number(e),r=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(n)&&n>0?n/r*i:0},$r=(e,t,i)=>{const n=Number(e),r=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(n)&&i>0?n/i*r:0},Mr=(e,t,i,n=yr.widthCm)=>{const r=Number(e?.width_cm);if(Number.isFinite(r)&&r>0)return r;const o=Number(e?.width);return Number.isFinite(o)&&o>0?$r(o,t,i):n};function Rr(e){const t=yr;return e.color===t.color&&e.opacity===t.opacity&&e.widthCm===t.widthCm&&e.fill===t.fill&&e.fillColor===t.fillColor&&e.fillOpacity===t.fillOpacity?null:{color:e.color,opacity:br(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),fill:!!e.fill,fill_color:e.fillColor,fill_opacity:br(e.fillOpacity,.25)}}function Cr(e,t){return{color:e.color,opacity:br(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),...t?{fill:e.fill,fill_color:e.fillColor,fill_opacity:br(e.fillOpacity,.25)}:{}}}function Tr(e){const t=e.x+e.w/2,i=e.y+e.h/2,n=wr(e.angle)*Math.PI/180,r=Math.cos(n),o=Math.sin(n),s=(e,n)=>{const s=e-t,a=n-i;return[t+s*r-a*o,i+s*o+a*r]};return[s(e.x,e.y),s(e.x+e.w,e.y),s(e.x+e.w,e.y+e.h),s(e.x,e.y+e.h)]}function Dr(e){const t=Tr(e),i=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],n=[(t[0][0]+t[2][0])/2,(t[0][1]+t[2][1])/2];return{points:[...t,i(t[0],t[1]),i(t[1],t[2]),i(t[2],t[3]),i(t[3],t[0]),n],segments:t.map((e,i)=>({a:e,b:t[(i+1)%4]}))}}function Ar(e,t,i,n,r,o,s,a){const l=wr(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),u=Math.cos(l),p=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:e.w/2,g=i>0?-e.h/2:e.h/2,f=p+m*c+g*d,v=_+m*h+g*u,y=n-f,b=r-v;let w=(y*c+b*h)*(t>0?1:-1),k=(y*d+b*u)*(i>0?1:-1),x=null;if(o){const t=w/Math.max(e.w,a),i=k/Math.max(e.h,a);x=Math.max(a/Math.max(e.w,a),a/Math.max(e.h,a),t,i),w=e.w*x,k=e.h*x}if(s>0)if(o){const t=Math.max(1,Math.round(e.w/s)),i=Math.max(1,Math.round(e.h/s));if(Math.abs(e.w-t*s)<1e-6&&Math.abs(e.h-i*s)<1e-6){const n=(e,t)=>{let i=Math.abs(e),n=Math.abs(t);for(;n;)[i,n]=[n,i%n];return Math.max(1,i)},r=1/n(t,i),o=Math.max(a/e.w,a/e.h),s=Math.max(o,Math.round((x??1)/r)*r);w=e.w*s,k=e.h*s}else{e.w>=e.h?(w=Math.round(w/s)*s,k=w*(e.h/Math.max(e.w,a))):(k=Math.round(k/s)*s,w=k*(e.w/Math.max(e.h,a)))}}else w=Math.round(w/s)*s,k=Math.round(k/s)*s;w=Math.max(a,w),k=Math.max(a,k);return{x:f+(t>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(t>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*u-k/2,w:w,h:k,angle:wr(e.angle)||void 0}}const Pr=(e,t,i)=>{const n=i[0]-t[0],r=i[1]-t[1],o=n*n+r*r;if(o<1e-12)return[...t];const s=Math.max(0,Math.min(1,((e[0]-t[0])*n+(e[1]-t[1])*r)/o));return[t[0]+n*s,t[1]+r*s]};function Fr(e,t,i,n){const r=n(e);let o=null;for(const r of t.points){const t=n(r),s=Math.hypot(t[0]-e[0],t[1]-e[1]);s<=i&&(!o||se.points),segments:e.flatMap(e=>e.segments)}}const Ir=Math.tan(.25*Math.PI/180);function Or(e,t){const i=Math.abs(Number(t[0])-Number(e[0])),n=Math.abs(Number(t[1])-Number(e[1]));if(!([i,n].every(Number.isFinite)&&i>0&&n>0))return null;const r=i>=n?"horizontal":"vertical",o=Math.max(i,n),s=Math.min(i,n);return s/o>Ir?null:{axis:r,major:o,minor:s,angleDegrees:180*Math.atan2(s,o)/Math.PI}}function Er(e,t){const i=Or(e,t);return i?"horizontal"===i.axis?[Number(t[0]),Number(e[1])]:[Number(e[0]),Number(t[1])]:[Number(t[0]),Number(t[1])]}const Nr=e=>`${e[0]},${e[1]}`,Hr=(e,t)=>e[0]===t[0]&&e[1]===t[1],Lr=(e,t)=>{const i=Nr(e),n=Nr(t);return i{let t=0;for(let i=0;i{if(e.length<3)return!1;for(let t=0;t1e-12},jr=(e,t)=>Hr(e,t.from)?[...t.to]:[...e],Wr=(e,t)=>e.map(e=>Array.isArray(e?.poly)?{...e,poly:e.poly.map(e=>jr(e,t))}:e),Ur=(e,t,i)=>{const n=e.flatMap((e,t)=>ei(e)?.some(e=>Hr(e,i.from))?[t]:[]);if(!n.length)return!1;for(const i of n){const n=ei(e[i]),r=ei(t[i]);if(!n||!r)continue;if(!qr(r))return!1;const o=Math.sign(Br(n)),s=Math.sign(Br(r));if(o&&s&&o!==s)return!1}const r=new Set;for(const e of n){const i=ei(t[e]);if(i)for(let n=0;n{let i=0;for(const n of e){const e=ei(n);if(e)for(let n=0;n{const{a:i,b:n,axis:r}=e,o="horizontal"===r?{from:n,to:[n[0],i[1]]}:{from:n,to:[i[0],n[1]]},s="horizontal"===r?{from:i,to:[i[0],n[1]]}:{from:i,to:[n[0],i[1]]};return[{move:o,preservedDegree:Vr(t,i)},{move:s,preservedDegree:Vr(t,n)}].sort((e,t)=>t.preservedDegree-e.preservedDegree||Nr(e.move.to).localeCompare(Nr(t.move.to))||Nr(e.move.from).localeCompare(Nr(t.move.from))).map(e=>e.move)};function Kr(e){const t=JSON.parse(JSON.stringify(e||{}));let i=Array.isArray(t.rooms)?t.rooms:[];const n=new Map;for(const e of i){const t=ei(e);if(t)for(let e=0;ee.key.localeCompare(t.key))){let t=null;for(const n of Gr(e,i)){const e=a.get(Nr(n.from));if(e&&e!==Nr(n.to))continue;const r=Wr(i,n);if(Ur(i,r,n)){t=n,i=r;break}}t?(a.set(Nr(t.from),Nr(t.to)),r++,s=Math.max(s,Math.hypot(t.to[0]-t.from[0],t.to[1]-t.from[1]))):o++}t.rooms=i;for(const e of t.partitions||[]){if(!Array.isArray(e?.a)||!Array.isArray(e?.b))continue;const i=Or(e.a,e.b);if(!i)continue;const n={key:String(e.id||Lr(e.a,e.b)),a:[...e.a],b:[...e.b],axis:i.axis};let a=null;for(const i of Gr(n,[{poly:[e.a,e.b]}])){const n=jr(e.a,i),r=jr(e.b,i),o=Math.hypot(r[0]-n[0],r[1]-n[1]);if(!(o>0))continue;const s=(t.openings||[]).filter(t=>"partition"===t?.host?.kind&&t.host.id===e.id).every(e=>{const t=Number(e.host.t),i=Number(e.length);return Number.isFinite(t)&&t>=0&&t<=1&&Number.isFinite(i)&&i>0&&t*o-i/2>=-1e-12&&t*o+i/2<=o+1e-12});if(s){a=i,e.a=n,e.b=r;break}}a?(r++,s=Math.max(s,Math.hypot(a.to[0]-a.from[0],a.to[1]-a.from[1]))):o++}return{space:t,report:{wallsStraightened:r,wallsStraightenSkipped:o,maxStraightenShift:s},changed:r>0}}const Yr=["rect","ellipse","furniture","image"],Xr=10**9,Zr=240,Jr=1e-4;function Qr(e){if(Array.isArray(e))return e.map(e=>Qr(e));if(null!==e&&"object"==typeof e){const t={};for(const[i,n]of Object.entries(e))t[i]=Qr(n);return t}return e}function eo(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=(e<0||Object.is(e,-0)?-1:1)*(Math.floor(Math.abs(e)*Xr+.5)/Xr);return 0===t?0:t}function to(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=e*Zr,i=Math.round(t);if(Math.abs(t-i)null!==no(e)):[]}function oo(e){return"string"==typeof e&&Yr.includes(e)}function so(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=eo(e[i]))}function ao(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=to(e[i]))}function lo(e){if(Array.isArray(e))for(let t=0;t{for(const r of n){const n=t[r];"number"==typeof n&&Number.isFinite(n)&&i(n,e)}},n=t=>{if(Array.isArray(t))for(let n=0;n{if(Array.isArray(e))for(const t of e)n(t)};for(const i of ro(e.rooms))t(i,["x","y","w","h"]),r(i.poly);for(const t of ro(e.walls))n(t.a),n(t.b);for(const t of ro(e.wall_segments))n(t.a),n(t.b);for(const i of ro(e.openings))t(i,["x","y"]);for(const i of ro(e.decor))"line"===i.kind?t(i,["x1","y1","x2","y2"]):oo(i.kind)?t(i,["x","y","w","h"]):"text"===i.kind&&t(i,["x","y"]);for(const t of ro(e.room_drafts))r(t.points);for(const t of ro(e.partitions))n(t.a),n(t.b);for(const t of ro(e.wall_columns))n(t.center);for(const t of ro(e.open_spans))n(t.a),n(t.b)}const r=no(t);if(!r)return;const o=new Map;if(n)for(const e of ro(n.spaces))null!=e.id&&o.set(String(e.id),e);for(const e of Object.values(r)){const t=no(e);if(!t)continue;const n=null!=t.s&&o.get(String(t.s))||null;for(const e of["x","y"]){const r=t[e];"number"==typeof r&&Number.isFinite(r)&&i(r,n)}}}function uo(e){const t=Number(e?.cell_cm);return t>0?t:5}function po(e,t={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},n=ro(no(e)?.spaces);let r=5;for(const e of n)r=Math.max(r,uo(e));ho(e,t,(e,t)=>{const n=e*Zr,o=Math.abs(n-Math.round(n)),s=to(e),a=o>0&&o=Jr))return;const l=a&&"number"==typeof s?Math.abs(s-e):0;if(a?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*Zr*(t?uo(t):r)),!t?.id||!a)return;const c=String(t.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(t.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*Zr*uo(t))}),i.bySpace.size&&ho(e,t,(e,t)=>{if(!t?.id)return;const n=i.bySpace.get(String(t.id));if(!n)return;const r=e*Zr;Math.abs(r-Math.round(r))>=Jr&&n.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...s}=i;return s}function _o(e){return function(e){const t=e,i=no(t);i&&ao(i,["x","y"]);return t}(Qr(e))}function mo(e){const t=e,i=no(t);if(!i)return t;for(const e of Object.values(i)){const t=no(e);t&&ao(t,["x","y"])}return t}function go(e){return fo(Qr(e))}function fo(e){const t=e,i=no(t);if(!i)return t;for(const e of ro(i.spaces)){so(e,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const t of ro(e.rooms))ao(t,["x","y","w","h"]),co(t.poly);for(const t of ro(e.walls))lo(t.a),lo(t.b);for(const t of ro(e.wall_segments))lo(t.a),lo(t.b);for(const t of ro(e.openings)){ao(t,["x","y"]),so(t,["angle","length"]);const e=no(t.host);e&&so(e,["t"])}for(const t of ro(e.decor))"line"===t.kind?ao(t,["x1","y1","x2","y2"]):oo(t.kind)?(ao(t,["x","y","w","h"]),so(t,["angle"])):"text"===t.kind&&(ao(t,["x","y"]),so(t,["scale","angle"]));for(const t of ro(e.room_drafts))co(t.points);for(const t of ro(e.partitions))lo(t.a),lo(t.b);for(const t of ro(e.wall_columns))lo(t.center),"square"===t.shape&&so(t,["angle"]);for(const t of ro(e.open_spans))lo(t.a),lo(t.b)}for(const e of ro(i.markers))so(e,["angle"]);return t}const vo=15,yo=8;function bo(e,t,i,n,r){const o=i[0]-e[0],s=i[1]-e[1],a=Math.hypot(o,s);if(!(a>0)||a<=r+1e-9)return null;const l=o/a,c=s/a,h=t=>{const n=(t[0]-e[0])*l+(t[1]-e[1])*c,o=(r-n)/(a-n);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[t[0]+(i[0]-t[0])*o,t[1]+(i[1]-t[1])*o]},d=h(t),u=h(n);return d&&u?[[e[0],e[1]],t,d,u,n]:null}const wo=Math.sin(.25*Math.PI/180);function ko(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<3}function xo(e){const t=Number(e)>0?Number(e):5;if(5===t)return 8;const i=5/t*8;return Math.min(80,Math.max(.5,i))}function So(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<2}function $o(e){return Number.isFinite(e)?Math.max(1,Math.min(100,e)):1}function Mo(e,t){return!Number.isFinite(e)||e<0?"":String(t?Math.round(e/2.54*100)/100:Math.round(100*e)/100)}function Ro(e,t,i){if(!Number.isFinite(e)||e<=0)return 0;const n=Number(t)>0?Number(t):5;return $o(e)/n*i}function Co(e,t){return t>0&&Number.isFinite(e)?Math.round(e/t)*t:e}function To(e){return Math.max(1e-6*Math.abs(e),1e-9)}function Do(e,t){if(!(t>0&&Number.isFinite(e)))return e;const i=Co(e,t);return Math.abs(i-e)<=To(t)?i:e}function Ao(e,t){let i=t[0]-e[0],n=t[1]-e[1];const r=Math.hypot(i,n);return r<1e-12?[1,0]:(i/=r,n/=r,(i<-1e-12||Math.abs(i)<=1e-12&&n<0)&&(i=-i,n=-n),[i,n])}function Po(e,t,i){const n=[Do(e[0],i),Do(e[1],i)],r=[Do(t[0],i),Do(t[1],i)],o=Co((n[0]+r[0])/2,i),s=Co((n[1]+r[1])/2,i),[a,l]=Ao(n,r);let c=Math.atan2(l,a);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${s.toFixed(d)}@${h.toFixed(4)}`}function Fo(e,t,i,n){return 1===n?Po(e,t,i):Po([e[0]/n,e[1]/n],[t[0]/n,t[1]/n],i)}function zo(e,t){if(!Array.isArray(e.a)||!Array.isArray(e.b)||e.a.length<2||e.b.length<2)return null;const i=[Number(e.a[0]),Number(e.a[1]),Number(e.b[0]),Number(e.b[1])];if(!i.every(Number.isFinite))return null;const n=t>0?t:1;return[[i[0]*n,i[1]*n],[i[2]*n,i[3]*n]]}function Io(e,t,i,n,r){const o=r>0?r:1;return{key:Fo(e,t,n,o),cm:$o(i),a:[e[0]/o,e[1]/o],b:[t[0]/o,t[1]/o]}}function Oo(e,t){const i=t>0?t:1,n=[];for(const t of e){const e=t.key.lastIndexOf("@");if(e<0)continue;const[r,o]=t.key.slice(0,e).split(",").map(Number),s=Number(t.key.slice(e+1));[r,o,s].every(Number.isFinite)&&n.push({w:t,x:r*i,y:o*i,ang:s})}return n}function Eo(e,t){const[i,n]=Ao(e,t);let r=Math.atan2(n,i);return r<0&&(r+=Math.PI),r}function No(e,t){let i=Math.abs(e-t);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Ho(e,t,i,n,r=1){if(!e?.length)return null;const o=Fo(t,i,n,r),s=e.find(e=>e.key===o);if(s)return s;const a=r>0?r:1,l=To(n)*a,c=(e,t)=>Math.abs(e[0]-t[0])<=l&&Math.abs(e[1]-t[1])<=l;for(const n of e){const e=zo(n,a);if(e&&(c(e[0],t)&&c(e[1],i)||c(e[0],i)&&c(e[1],t)))return n}const h=(t[0]+i[0])/2,d=(t[1]+i[1])/2,u=Eo(t,i),p=Math.max(.5*n,1e-9)*a;for(const t of Oo(e,a))if(No(t.ang,u)&&Math.hypot(t.x-h,t.y-d)<=p)return t.w;return null}function Lo(e,t,i,n,r=1){const o=Ho(e,t,i,n,r);if(o&&o.cm>0)return $o(o.cm);const s=function(e,t,i,n,r){if(!e?.length)return null;const o=r>0?r:1,s=Math.hypot(i[0]-t[0],i[1]-t[1]);if(s<1e-12)return null;const a=Eo(t,i),l=Math.max(.5*n,1e-9)*o;let c=null;for(const n of e){if(!(n.cm>0))continue;const e=zo(n,o);if(!e)continue;const r=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]);if(r<1e-12||!No(Eo(e[0],e[1]),a))continue;if(Ts(t[0],t[1],e[0][0],e[0][1],e[1][0],e[1][1])>l||Ts(i[0],i[1],e[0][0],e[0][1],e[1][0],e[1][1])>l)continue;if(r+l(o.has(e.key)||(e=>{const t=zo(e,n);if(!t)return!1;const[i,o]=t,a=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(a,c);if(h<=l)return!1;if(!s.some(e=>{const t=[e[0],e[1]],n=[e[2],e[3]];return No(Eo(i,o),Eo(t,n))&&Ts(i[0],i[1],t[0],t[1],n[0],n[1])<=l&&Ts(o[0],o[1],t[0],t[1],n[0],n[1])<=l}))return!1;const d=(r||[]).some(e=>{const t=[e[0],e[1]],n=[e[2],e[3]];if(!No(Eo(i,o),Eo(t,n)))return!1;const r=e=>Math.abs((e[0]-i[0])*c-(e[1]-i[1])*a)/h;if(r(t)>l||r(n)>l)return!1;const s=h*h,d=((t[0]-i[0])*a+(t[1]-i[1])*c)/s,u=((n[0]-i[0])*a+(n[1]-i[1])*c)/s;return Math.min(1,Math.max(d,u))-Math.max(0,Math.min(d,u))>l/h});return!d})(e))&&e.cm>=1&&e.cm<=100)}function qo(e,t,i,n=8){const[r,o]=Ao(e,t);let s=Math.atan2(o,r);s<0&&(s+=Math.PI);let a=i*Math.PI/180%Math.PI;a<0&&(a+=Math.PI);let l=Math.abs(s-a);return l>Math.PI/2&&(l=Math.PI-l),l<=n*Math.PI/180}function jo(e,t,i,n,r=1,o="affine",s){if(!e?.length)return[];if(t.length!==i.length)return"fixed-topology"===o&&s?.(),e.slice();const a=r>0?r:1,l=Math.max(.5*n,1e-9)*a,c=Math.max(n*a*1e-6,1e-9),h=[],d=new Map,u=new Map,p=(e,t,i)=>{const n=e.get(t)||new Set;n.add(i),e.set(t,n)};for(let e=0;e[e[0]+(t[0]-e[0])*i,e[1]+(t[1]-e[1])*i],m=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1])<=c,g=(e,t)=>{if("fixed-topology"===o){const i=t.na[0]-t.oa[0],n=t.na[1]-t.oa[1],r=t.nb[0]-t.ob[0],o=t.nb[1]-t.ob[1];return Math.hypot(i-r,n-o)<=c?[e[0]+i,e[1]+n]:m(e,t.oa)?[...t.na]:m(e,t.ob)?[...t.nb]:[...e]}const i=Math.max(0,Math.min(1,((e[0]-t.oa[0])*t.dx+(e[1]-t.oa[1])*t.dy)/t.len2));return _(t.na,t.nb,i)},f=(e,t)=>{const[i,n]=Ao(e,t);return(t[0]-e[0])*i+(t[1]-e[1])*n>=0?[[...e],[...t]]:[[...t],[...e]]},v=[],y=[],b=(e,t,i)=>{if(Math.hypot(t[0]-e[0],t[1]-e[1])<=c)return;const[r,o]=f(e,t),s=$o(i);if(y.some(e=>e.entry.cm===s&&m(e.span[0],r)&&m(e.span[1],o)))return;const l=Io(r,o,s,n,a);v.push(l),y.push({entry:l,span:[r,o]})};for(const t of e){const e=zo(t,a);if(e){const[i,n]=f(e[0],e[1]),r=n[0]-i[0],s=n[1]-i[1],a=r*r+s*s,d=Math.sqrt(a);if(d<=c){v.push({...t,cm:$o(t.cm)});continue}const u=[];for(const e of h){if(!No(Eo(i,n),Eo(e.oa,e.ob)))continue;const t=e=>Math.abs((e[0]-i[0])*s-(e[1]-i[1])*r)/d;if(t(e.oa)>l||t(e.ob)>l)continue;const o=((e.oa[0]-i[0])*r+(e.oa[1]-i[1])*s)/a,h=((e.ob[0]-i[0])*r+(e.ob[1]-i[1])*s)/a,p=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-p)*d>c&&u.push({lo:p,hi:_,move:e})}if(!u.length){"fixed-topology"===o?v.push({...t}):b(i,n,t.cm);continue}const p=[0,1,...u.flatMap(({lo:e,hi:t})=>[e,t])].sort((e,t)=>e-t).filter((e,t,i)=>0===t||Math.abs(e-i[t-1])*d>c),y=[];for(let e=0;e+1a>=e.lo-1e-12&&a<=e.hi+1e-12);if(!l.length){y.push([o,s]);continue}const h=[g(o,l[0].move),g(s,l[0].move)],f=l.slice(1).some(e=>{const t=g(o,e.move),i=g(s,e.move);return!m(h[0],t)||!m(h[1],i)});y.push(f?[o,s]:h)}const w=(e,t)=>{const i=e[1][0]-e[0][0],n=e[1][1]-e[0][1],r=t[1][0]-t[0][0],o=t[1][1]-t[0][1],s=Math.hypot(i,n);return!(s<=c||i*r+n*o<=0)&&Math.abs(i*o-n*r)/s<=c},k=[];for(const e of y){const t=k[k.length-1];t&&m(t[1],e[0])&&w(t,e)?t[1]=e[1]:k.push([[...e[0]],[...e[1]]])}if("fixed-topology"===o&&1===k.length){const[i,n]=k[0];if(m(i,e[0])&&m(n,e[1])||m(i,e[1])&&m(n,e[0])){v.push({...t});continue}}for(const[e,i]of k)b(e,i,t.cm);continue}if("fixed-topology"===o){const e=u.get(t.key);if(1===e?.size){const i=[...e][0];v.push(i===t.key?{...t}:{...t,key:i});continue}const i=[Oo([t],a)[0]];1!==a&&i.push(Oo([t],1)[0]);const n=i.filter(Boolean).some(e=>h.some(t=>{if(!No(e.ang,Eo(t.oa,t.ob)))return!1;const i=((e.x-t.oa[0])*t.dx+(e.y-t.oa[1])*t.dy)/t.len2;return i>=-1e-6&&i<=1.000001&&Ts(e.x,e.y,t.oa[0],t.oa[1],t.ob[0],t.ob[1])<=l}));((e?.size||0)>1||n)&&s?.(),v.push({...t});continue}let i="";const r=d.get(t.key);if(1===r?.size&&(i=[...r][0]),!i){const e=Oo([t],a)[0];if(e){const t=new Set;for(const i of h){if(!No(e.ang,Eo(i.oa,i.ob)))continue;const r=((e.x-i.oa[0])*i.dx+(e.y-i.oa[1])*i.dy)/i.len2;if(r<-1e-6||r>1.000001)continue;if(Ts(e.x,e.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([e.x,e.y],i),[s,c]=Ao(i.na,i.nb),h=Math.max(n*a,1e-6);t.add(Fo([o[0]-s*h,o[1]-c*h],[o[0]+s*h,o[1]+c*h],n,a))}1===t.size&&(i=[...t][0])}}v.push({...t,key:i||t.key,cm:$o(t.cm)})}return v}function Wo(e,t,i,n,r=1,o="affine"){return jo(e,t,i,n,r,o)}function Uo(e,t,i,n,r=1,o="fixed-topology"){let s=!1;const a=jo(e,t,i,n,r,o,()=>{s=!0});return{walls:s?(e||[]).map(e=>({...e})):a,rejected:s}}function Vo(e,t,i,n=1,r=[]){const o=n>0?n:1,s=Math.abs(i),a=Math.max(s*o*Jr,1e-9),l=(r||[]).flatMap(e=>{const t=zo(e,o);return t?t.map(e=>[...e]):[]}),c=e=>e.every((e,t)=>(e=>{if(!(s>0))return!0;const t=e/o/s;return Math.abs(t-Math.round(t))Math.abs(e-i[t])<=a)),h=[],d=e=>JSON.stringify([e.key,e.cm,e.a,e.b]);for(const i of e||[]){const e=zo(i,o);if(!e)continue;const[n,r]=e;if(![n[0],n[1],r[0],r[1]].every(Number.isFinite)||!c(n)||!c(r)){h.push(d(i));continue}const s=r[0]-n[0],l=r[1]-n[1],u=Math.hypot(s,l);if(u<=a){h.push(d(i));continue}const p=s/u,_=l/u,m=[];for(const e of t){const[t,i]=e;if(![t?.[0],t?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const r=e=>Math.abs((e[0]-n[0])*_-(e[1]-n[1])*p);if(r(t)>a||r(i)>a)continue;const o=(t[0]-n[0])*p+(t[1]-n[1])*_,s=(i[0]-n[0])*p+(i[1]-n[1])*_,l=Math.max(0,Math.min(o,s)),c=Math.min(u,Math.max(o,s));c-l>a&&m.push([l,c])}m.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let g=0;for(const[e,t]of m){if(e>g+a)break;if(g=Math.max(g,t),g>=u-a)break}ge.key!==s);return null==n||n<1?a:[...a,Io(t,i,n,r,o)]}function Ko(e,t,i,n,r,o=[],s=1){let a=e?e.slice():[];for(const e of function(e,t,i,n,r=1,o=[]){const s=ms(e,t,i,n,r,o);if(!s)return[];const a=[];for(let e=0;e0||(c=Go(c,t,i,n,r,s)))}return c}function Xo(e){const{a:t,b:i,halfDepth:n}=e;if(!Array.isArray(t)||!Array.isArray(i)||t.length<2||i.length<2||![t[0],t[1],i[0],i[1]].every(Number.isFinite))return null;const r=i[0]-t[0],o=i[1]-t[1],s=Math.hypot(r,o);if(!(s>1e-9&&n>0&&Number.isFinite(n)))return null;const a=-o/s*n,l=r/s*n;return[[t[0]+a,t[1]+l],[i[0]+a,i[1]+l],[i[0]-a,i[1]-l],[t[0]-a,t[1]-l]]}function Zo(e,t,i){return Math.hypot(e[0]-t[0],e[1]-t[1])<=i}function Jo(e,t,i){const n=t.b[0]-t.a[0],r=t.b[1]-t.a[1],o=n*n+r*r;if(!(o>i*i))return!1;const s=((e[0]-t.a[0])*n+(e[1]-t.a[1])*r)/o;if(!(s>0&&s<1))return!1;const a=[t.a[0]+n*s,t.a[1]+r*s];return Math.hypot(e[0]-a[0],e[1]-a[1])<=i}function Qo(e,t,i,n){const r=Math.hypot(t,i);if(!(r>1e-9&&n>0))return;const o=[t/r,i/r],s=e.find(e=>Math.abs(e.u[0]*o[1]-e.u[1]*o[0])<1e-9&&e.u[0]*o[0]+e.u[1]*o[1]>1-1e-9);s?s.halfDepth=Math.max(s.halfDepth,n):e.push({u:o,halfDepth:n})}function es(e,t){try{const i=jt(Ps(e),Ps(t));let n=null,r=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs(ss(t));t.length>=4&&i>r&&(r=i,n=t.slice(0,-1).map(e=>[e[0],e[1]]))}return n}catch{return null}}function ts(e,t=1e-6){const i=(e||[]).map((e,t)=>({segment:e,index:t})).filter(({segment:e})=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const n=Math.max(Number.isFinite(t)?t:0,1e-9),r=i.flatMap(({segment:e})=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of r)o.some(t=>Zo(t,e,n))||o.push(e);const s=[];for(const e of o){const t=[];let r=!1;for(const{segment:o,index:s}of i){const i=Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1]);Zo(e,o.a,n)?t.push({u:[(o.b[0]-o.a[0])/i,(o.b[1]-o.a[1])/i],halfDepth:o.halfDepth,length:i,index:s}):Zo(e,o.b,n)?t.push({u:[(o.a[0]-o.b[0])/i,(o.a[1]-o.b[1])/i],halfDepth:o.halfDepth,length:i,index:s}):Jo(e,o,n)&&(r=!0)}if(r||2!==t.length)continue;const[o,a]=t,l=o.u[0]*a.u[1]-o.u[1]*a.u[0];if(Math.abs(l)<1e-9)continue;const c=l<0?1:-1,h=[-o.u[1],o.u[0]],d=[-a.u[1],a.u[0]],u=[e[0]+h[0]*o.halfDepth*c,e[1]+h[1]*o.halfDepth*c],p=[e[0]-d[0]*a.halfDepth*c,e[1]-d[1]*a.halfDepth*c];if(!cs(u,o.u,p,a.u))continue;const _=[[o,a,p,[d[0]*-c,d[1]*-c]],[a,o,u,[h[0]*c,h[1]*c]]];for(const[t,,i,r]of _){const o=Math.min(2*t.halfDepth,t.length),a=[-t.u[1]*t.halfDepth,t.u[0]*t.halfDepth],l=[[e[0]+a[0],e[1]+a[1]],[e[0]+t.u[0]*o+a[0],e[1]+t.u[1]*o+a[1]],[e[0]+t.u[0]*o-a[0],e[1]+t.u[1]*o-a[1]],[e[0]-a[0],e[1]-a[1]]],c=e=>(e[0]-i[0])*r[0]+(e[1]-i[1])*r[1],h=[];for(let e=0;e=-1e-12&&h.push(t),n>1e-12&&r<-1e-12||n<-1e-12&&r>1e-12){const e=n/(n-r);h.push([t[0]+(i[0]-t[0])*e,t[1]+(i[1]-t[1])*e])}}h.length>=3&&Math.abs(ss(h))>n*n&&s.push({segmentIndex:t.index,wedge:h})}}return s}function is(e,t=1e-6){const i=(e||[]).filter(e=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const n=Math.max(Number.isFinite(t)?t:0,1e-9),r=i.flatMap(e=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of r)o.some(t=>Zo(t,e,n))||o.push(e);const s=[],a=i.map((e,t)=>({roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`join-${t}`,kind:"outer",cm:0,open:!1,half:e.halfDepth})),l=bs(a,n);for(const e of ws(l).fans)s.push(e);const c=e=>!!ks(l,e);for(const e of o){if(c(e))continue;const t=[];for(const r of i)Zo(e,r.a,n)?Qo(t,r.b[0]-r.a[0],r.b[1]-r.a[1],r.halfDepth):Zo(e,r.b,n)?Qo(t,r.a[0]-r.b[0],r.a[1]-r.b[1],r.halfDepth):Jo(e,r,n)&&(Qo(t,r.a[0]-e[0],r.a[1]-e[1],r.halfDepth),Qo(t,r.b[0]-e[0],r.b[1]-e[1],r.halfDepth));if(!(t.length<2)){t.sort((e,t)=>Math.atan2(e.u[1],e.u[0])-Math.atan2(t.u[1],t.u[0])||e.halfDepth-t.halfDepth);for(let i=0;in*n&&s.push(m)}}}return s}function ns(e,t,i,n){if(!(t>0)||!e||e.length<2)return"";if(i&&e.length>=3){let i=e;const r=e[e.length-1];if(e.length>=4&&Math.hypot(e[0][0]-r[0],e[0][1]-r[1])<1e-9&&(i=e.slice(0,-1)),i.length>=3){const e=i.map((e,i)=>n?.[i]||t),r=Js(i,e),o=us(i,e);if(r&&o)return`${ps(r)} ${ps(_s(o))}`}}const r=[];for(let i=0;i=1e-9&&a>0&&r.push({a:o,b:s,halfDepth:a})}const o=r.map(Xo);for(const{segmentIndex:e,wedge:t}of ts(r)){const i=o[e];if(!i)continue;const n=es(i,t);n&&(o[e]=n)}const s=[...o.filter(e=>!!e),...is(r)],a=function(e){let t=null;try{for(const i of e){if(i.length<3)continue;const e=Ps(i);t=t?Bt(t,e):[e]}return t}catch{return null}}(s);return a?Ws(a):s.map(e=>ps(e)).join(" ")}function rs(e,t,i,n,r=1){if(!i.length)return!1;const o=os(n,r),s=(e[0]+t[0])/2,a=(e[1]+t[1])/2,[l,c]=Ao(e,t);for(const e of i){const[t,i]=Ao([e[0],e[1]],[e[2],e[3]]);if(!(Math.abs(l*i-c*t)>.05)&&Ts(s,a,e[0],e[1],e[2],e[3])<=o)return!0}return!1}function os(e,t){return Math.max(e*(t>0?t:1)*.04,1e-9)}function ss(e){let t=0;for(let i=0;ie[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s+0)+o&&(i=!i)}return i}([c[0]+.001*a,c[1]+.001*l],e)||(a=-a,l=-l),[a,l]}function ls(e,t){const i=e[0]*t[1]-e[1]*t[0],n=e[0]*t[0]+e[1]*t[1];return Math.abs(i)<1e-9&&n>0}function cs(e,t,i,n){const r=t[0]*n[1]-t[1]*n[0];if(Math.abs(r)<1e-12)return null;const o=[i[0]-e[0],i[1]-e[1]],s=(o[0]*n[1]-o[1]*n[0])/r;return[e[0]+s*t[0],e[1]+s*t[1]]}function hs(e,t,i){const n=e?.length||0;if(n<3||!Array.isArray(i)||i.length!==n)return 0;const r=(Math.trunc(t)%n+n)%n,o=e[r],s=e[(r+1)%n],a=s[0]-o[0],l=s[1]-o[1],c=Math.hypot(a,l);if(!(c>0))return 0;const h=Math.max(0,Number(i[r])||0);if(!(h>0))return c;const d=[a/c,l/c],u=as(e,r),p=[o[0]+u[0]*h,o[1]+u[1]*h],_=t=>{const r=Math.max(0,Number(i[t])||0);if(!(r>0))return null;const s=e[t],a=e[(t+1)%n],l=a[0]-s[0],c=a[1]-s[1],h=Math.hypot(l,c);if(!(h>0))return null;const u=as(e,t),_=cs(p,d,[s[0]+u[0]*r,s[1]+u[1]*r],[l/h,c/h]);return _?(_[0]-o[0])*d[0]+(_[1]-o[1])*d[1]:null},m=_((r-1+n)%n)??0,g=(_((r+1)%n)??c)-m;return g>0?g:0}function ds(e,t,i,n,r,o,s,a=1){const l=(e||[]).find(e=>e?.id===t),c=ei(l);if(!c||c.length<3)return null;const h=Ss(e,t,i,n,r,o,s,a);if(!h)return c.map(()=>0);const d=4*os(r,a);return c.map((e,t)=>{const i=c[(t+1)%c.length],n=[(e[0]+i[0])/2,(e[1]+i[1])/2];for(let e=0;e!(e>0)))return e.map(e=>[e[0],e[1]]);const r=[];for(let o=0;o0||u>0)){r.push([e[o][0],e[o][1]]);continue}if(d>0!=u>0){const t=e[o],i=d>0?[t[0]+p*d,t[1]+_*d]:[t[0],t[1]],n=u>0?[t[0]+m*u,t[1]+g*u]:[t[0],t[1]];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}if(ls(w,k)){const t=e[o],i=[t[0]+p*d,t[1]+_*d],n=[t[0]+m*u,t[1]+g*u];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}const $=cs(x,w,S,k),M=Math.max(d,u,1e-9),R=ks(i,e[o])?.limit??4*M;if($){const i=Math.hypot($[0]-e[o][0],$[1]-e[o][1]);if(Number.isFinite(i)&&i<=R){r.push($);continue}if(Vs(e,t,o)){r.push($);continue}}d>0&&r.push([e[o][0]+p*d,e[o][1]+_*d]),u>0&&r.push([e[o][0]+m*u,e[o][1]+g*u]),d>0||u>0||r.push([e[o][0],e[o][1]])}return r.length>=3?r:null}function ps(e,t=!0){if(!e.length)return"";let i=`M ${e[0][0]} ${e[0][1]}`;for(let t=1;te?.id===t),a=ei(s);if(!a||a.length<3)return null;const l=os(n,r),c=[];for(const i of e||[]){if(!i||i.id===t)continue;const e=ei(i);if(e)for(const t of Rn(a,e,l))c.push([t[0],t[1]],[t[2],t[3]])}for(const e of i||[])c.push([e[0],e[1]],[e[2],e[3]]);for(const e of o||[]){const t=zo(e,r);t&&c.push(t[0],t[1])}const h=[],d=[];for(let e=0;el)continue;const s=((e[0]-t[0])*(i[0]-t[0])+(e[1]-t[1])*(i[1]-t[1]))/(n*n);s<=r||s>=1-r||(o.some(e=>Math.abs(e-s)*n<=2*l)||o.push(s))}o.sort((e,t)=>e-t);for(const n of o)h.push([t[0]+(i[0]-t[0])*n,t[1]+(i[1]-t[1])*n]),d.push(e)}return{poly:h,parent:d,orig:a}}function gs(e,t,i,n){const r=t.poly.length,o=new Array(r).fill(0);if(!e?.length)return o;const s=new Set,a=[];for(let l=0;l0?(o[l]=$o(c.cm),s.add(c.key)):a.push(l)}if(!a.length)return o;const l=n>0?n:1,c=Math.max(.5*i,1e-9)*l,h=Oo(e,l).filter(e=>e.w.cm>0);for(let e=a.length-1;e>=0;e--){const i=a[e],n=t.poly[i],s=t.poly[(i+1)%r],d=Eo(n,s);let u=null;for(const e of h){const t=zo(e.w,l);if(!t||!No(Eo(t[0],t[1]),d))continue;if(Ts(n[0],n[1],t[0][0],t[0][1],t[1][0],t[1][1])>c||Ts(s[0],s[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;const i=Math.hypot(s[0]-n[0],s[1]-n[1]),r=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]),o=Math.max(0,r-i);(!u||oc||Ts(r[0],r[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;i=!0,o=Math.max(0,Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1])-_)}else{if(Ts(e.x,e.y,n[0],n[1],r[0],r[1])>c)continue;o=Math.hypot(e.x-d,e.y-u)}(!p||i&&!p.exact||i===p.exact&&o0?i:1,o=(e||[]).filter(e=>e&&!e.open&&null!==e.kind&&Number.isFinite(e.half)&&e.half>0&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&[e.a[0],e.a[1],e.b[0],e.b[1]].every(Number.isFinite)&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>n).sort((e,t)=>e.key.localeCompare(t.key)||e.a[0]-t.a[0]||e.a[1]-t.a[1]||e.b[0]-t.b[0]||e.b[1]-t.b[1]||e.half-t.half),s=new Map;for(const e of o){const t=s.get(e.key);t?e.half>t.half&&s.set(e.key,{...t,half:e.half}):s.set(e.key,e)}const a=[...s.values()].flatMap(e=>[{point:[e.a[0],e.a[1]],other:e.b,halfDepth:e.half,kind:e.kind,key:e.key},{point:[e.b[0],e.b[1]],other:e.a,halfDepth:e.half,kind:e.kind,key:e.key}]).sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]||e.other[0]-t.other[0]||e.other[1]-t.other[1]||e.halfDepth-t.halfDepth),l=new Map;for(const e of a){const[t,i]=fs(e.point,n),r=vs(t,i),o=l.get(r)||[];o.push(e),l.set(r,o)}const c=[],h=new Map;for(const e of a){const t=ys(h,e.point,n).filter(t=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])<=n).sort((t,i)=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])-Math.hypot(i.point[0]-e.point[0],i.point[1]-e.point[1])||t.point[0]-i.point[0]||t.point[1]-i.point[1]);let i=t[0];if(!i){i={point:[...e.point],rays:[]},c.push(i);const[t,r]=fs(i.point,n),o=vs(t,r),s=h.get(o)||[];s.push(i),h.set(o,s)}const r=e.other[0]-e.point[0],o=e.other[1]-e.point[1],s=Math.hypot(r,o);if(!(s>n))continue;const a=[r/s,o/s];let l=Math.atan2(a[1],a[0]);l<0&&(l+=2*Math.PI),i.rays.push({u:a,halfDepth:e.halfDepth,length:s,angle:l})}const d=[],u=e=>{const t=1e-9*Math.max(1,r),i=e.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>n);return i.filter((e,n)=>!i.some((i,r)=>r!==n&&i.halfDepth>=e.halfDepth-t&&i.length>=e.length-t&&(i.halfDepth>e.halfDepth+t||i.length>e.length+t||re.length-t.length||e.halfDepth-t.halfDepth).map(e=>({...e}))};for(const e of c){const t=e.rays.sort((e,t)=>e.angle-t.angle||e.length-t.length||e.halfDepth-t.halfDepth),i=[];for(const e of t){const t=i[i.length-1];t&&Math.abs(e.angle-t.angle)<=1e-9?t.supports.push({halfDepth:e.halfDepth,length:e.length}):i.push({u:[...e.u],angle:e.angle,supports:[{halfDepth:e.halfDepth,length:e.length}]})}if(i.length>1&&2*Math.PI-i[i.length-1].angle+i[0].angle<=1e-9){const e=i.pop();i[0].supports.push(...e.supports)}if(i.length<3)continue;const r=i.map(t=>{const i=u(t.supports),r=new Set,o=[];for(const s of i){const i=[e.point[0]+t.u[0]*s.length,e.point[1]+t.u[1]*s.length];for(const t of ys(l,i,n)){if("shared"!==t.kind||Math.hypot(t.point[0]-i[0],t.point[1]-i[1])>n)continue;const s=t.other[0]-t.point[0],a=t.other[1]-t.point[1],l=Math.hypot(s,a);if(!(l>n))continue;const c=s/l,h=a/l;if(Math.hypot(t.other[0]-e.point[0],t.other[1]-e.point[1])<=n)continue;const d=`${t.key}|${t.point[0]}|${t.point[1]}|${t.other[0]}|${t.other[1]}|${t.halfDepth}`;r.has(d)||(r.add(d),o.push({start:[t.point[0],t.point[1]],u:[c,h],length:l,halfDepth:t.halfDepth}))}}return o.sort((e,t)=>e.start[0]-t.start[0]||e.start[1]-t.start[1]||e.u[0]-t.u[0]||e.u[1]-t.u[1]||e.length-t.length||e.halfDepth-t.halfDepth),{u:[...t.u],halfDepth:Math.max(...i.map(e=>e.halfDepth)),length:Math.max(...i.map(e=>e.length)),supports:i,continuations:o}}).filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>n);if(r.length<3)continue;const o=Math.max(...r.map(e=>e.halfDepth));o>0&&Number.isFinite(o)&&d.push({point:[...e.point],rays:r,halfDepth:o,limit:1.25*o})}d.sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]);const p=new Map;for(const e of d){const[t,i]=fs(e.point,n),r=vs(t,i),o=p.get(r)||[];o.push(e),p.set(r,o)}return{epsilon:n,coordinateScale:r,nodes:d,index:p}}function ws(e){const t={fans:[],supports:[]};if(!e?.nodes?.length)return t;const i=Math.max(e.epsilon,1e-9)**2;for(const n of e.nodes){const e=n.rays.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0).map(e=>({...e,thickLength:Math.max(...e.supports.filter(t=>t.halfDepth>=e.halfDepth-1e-12).map(e=>e.length),0),angle:(()=>{const t=Math.atan2(e.u[1],e.u[0]);return t<0?t+2*Math.PI:t})()})).sort((e,t)=>e.angle-t.angle);if(e.length<2)continue;const r=n.point;for(const i of e)for(const e of i.supports){if(!(e.halfDepth>0&&e.length>0))continue;const n=-i.u[1]*e.halfDepth,o=i.u[0]*e.halfDepth,s=[r[0]+i.u[0]*e.length,r[1]+i.u[1]*e.length];t.supports.push([[r[0]+n,r[1]+o],[s[0]+n,s[1]+o],[s[0]-n,s[1]-o],[r[0]-n,r[1]-o]])}for(let n=0;n{const e=s.angle-o.angle;return e>0?e:e+2*Math.PI})();if(a<1e-9)continue;const l=a>Math.PI+1e-9,c=4*Math.max(o.halfDepth,s.halfDepth),h=[r[0]-o.u[1]*o.halfDepth,r[1]+o.u[0]*o.halfDepth],d=[r[0]+s.u[1]*s.halfDepth,r[1]-s.u[0]*s.halfDepth],u=o.u[0]*s.u[1]-o.u[1]*s.u[0],p=e=>{let t=Math.atan2(e[1]-r[1],e[0]-r[0])-o.angle;for(;t<0;)t+=2*Math.PI;return t<=a+1e-9};let _=null;if(Math.abs(u)>1e-9){const e=((d[0]-h[0])*s.u[1]-(d[1]-h[1])*s.u[0])/u,t=((d[0]-h[0])*o.u[1]-(d[1]-h[1])*o.u[0])/u,i=[h[0]+o.u[0]*e,h[1]+o.u[1]*e];(l?e<=1e-9&&t<=1e-9:e>1e-9&&e<=o.thickLength&&t<=s.thickLength)&&Math.hypot(i[0]-r[0],i[1]-r[1])<=c&&p(i)&&(_=i)}const m=e=>{Math.abs(ss(e))>i&&t.fans.push(e)};if(_){const e=1.5*Math.max(o.halfDepth,s.halfDepth);m(bo([r[0],r[1]],h,_,d,e)??[[r[0],r[1]],h,_,d]);continue}if(l){m([[r[0],r[1]],h,d]);continue}const g=(e,t)=>Math.min(t,Math.sqrt(Math.max(c**2-e**2,0)),2*Math.max(o.halfDepth,s.halfDepth)),f=[h[0]+o.u[0]*g(o.halfDepth,o.thickLength),h[1]+o.u[1]*g(o.halfDepth,o.thickLength)],v=[d[0]+s.u[0]*g(s.halfDepth,s.thickLength),d[1]+s.u[1]*g(s.halfDepth,s.thickLength)];m([[r[0],r[1]],h,f,v,d])}}return t}function ks(e,t){return!e||!Array.isArray(t)||t.length<2||!t.slice(0,2).every(Number.isFinite)?null:ys(e.index,t,e.epsilon).filter(i=>Math.hypot(i.point[0]-t[0],i.point[1]-t[1])<=e.epsilon).sort((e,i)=>Math.hypot(e.point[0]-t[0],e.point[1]-t[1])-Math.hypot(i.point[0]-t[0],i.point[1]-t[1])||e.point[0]-i.point[0]||e.point[1]-i.point[1])[0]||null}function xs(e,t,i,n,r,o,s){return bs($s(e,t,i,n,r,o,s),4*os(n,s),s)}function Ss(e,t,i,n,r,o,s,a=1){const l=ms(e,t,n,r,a,i);if(!l)return null;const c=function(e,t,i){const n=(e||[]).find(e=>e?.id===t),r=ei(n);if(!r)return[];const o=[];for(const n of e||[]){if(!n||n.id===t)continue;const e=ei(n);if(e)for(const t of Rn(r,e,i))o.push(t)}return o}(e,t,os(r,a)),h=function(e,t,i,n,r){const o=os(n,r),s=[];for(let a=0;aTs(h,d,e[0],e[1],e[2],e[3])<=o);s.push(u?"shared":"outer")}return s}(l.poly,c,n,r,a),d=gs(i,l,r,a),u=d.map((e,t)=>h[t]&&e>0?Ro(e,o,s)/2:0);return{...l,kinds:h,cms:d,offsets:u}}function $s(e,t,i,n,r,o,s=1){const a=[];for(const l of e||[]){if(!l?.id)continue;const c=Ss(e,l.id,t,i,n,r,o,s);if(c)for(let e=0;e0&&(a=Go(a,e.a,e.b,e.cm,n,s));return a}function Rs(e,t,i,n,r,o,s=1){if(!t?.length)return[];const a=$s(e,t,i,n,r,o,s),l=new Map;for(const e of a){if(e.open||!e.kind||!e.roomId)continue;const t=l.get(e.key)||new Set;t.add(e.roomId),l.set(e.key,t)}const c=e=>{const t=[...l.get(e)||[]].sort();return 1!==t.length&&2!==t.length?`ambiguous:${e}`:`${1===t.length?"outer":"shared"}:${t.join("|")}`},h=[],d=new Set;for(const e of a)!e.open&&e.cm>0&&!d.has(e.key)&&(d.add(e.key),h.push({...e,ownerSignature:c(e.key)}));const u=[];for(const a of e||[]){if(!a?.id)continue;const l=Ss(e,a.id,t,i,n,r,o,s);if(l)for(let e=0;e0)||null===l.kinds[i]){e++;continue}const o=c(Fo(l.poly[i],l.poly[(i+1)%l.poly.length],n,s));let a=e;for(;a+10&&u.push({a:[d[0],d[1]],b:[p[0],p[1]],key:Fo(d,p,n,s),cm:r,len:_,ownerSignature:o}),e=a+1}}}u.sort((e,t)=>t.len-e.len||e.key.localeCompare(t.key));const p=[],_=new Set,m=new Set,g=4*os(n,s);for(const e of u){const t=h.filter(t=>!m.has(t.key)&&t.cm===e.cm&&t.ownerSignature===e.ownerSignature&&No(Eo(t.a,t.b),Eo(e.a,e.b))&&Ts(t.a[0],t.a[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g&&Ts(t.b[0],t.b[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g);if(t.length){for(const e of t)m.add(e.key);_.has(e.key)||(_.add(e.key),p.push(Io(e.a,e.b,e.cm,n,s)))}}for(const e of h)m.has(e.key)||_.has(e.key)||(_.add(e.key),p.push(Io(e.a,e.b,e.cm,n,s)));return p}function Cs(e,t,i,n,r,o,s,a=1){const l=os(r,a),c=(n[0]+n[2])/2,h=(n[1]+n[3])/2,d=Eo([n[0],n[1]],[n[2],n[3]]);let u=null;for(const n of $s(e,t,i,r,o,s,a)){if(!No(Eo(n.a,n.b),d))continue;const e=Ts(c,h,n.a[0],n.a[1],n.b[0],n.b[1]);e>4*l||(!u||e[e[0],e[1]]),o=Math.abs(ss(r));r.length>=3&&o>i&&(t=r,i=o)}return t}function As(e,t,i,n,r,o,s,a=1,l,c){const h=(e||[]).find(e=>e?.id===t),d=ei(h);if(!d||d.length<3)return null;if(!i?.length)return d.map(e=>[e[0],e[1]]);const u=Ss(e,t,i,n,r,o,s,a);if(!u||!u.offsets.some(e=>e>0))return d.map(e=>[e[0],e[1]]);const p=c||xs(e,i,n,r,o,s,a),_=us(u.poly,u.offsets,p);if(!_)return d.map(e=>[e[0],e[1]]);if(!p.nodes.length)return _;const m=void 0===l?Gs(e,i,n,[],r,o,s,a):null,g=l??("ok"===m?.status||"degraded-extra"===m?.status?m.roomGeom:void 0);if(g)try{const e=Ds(jt(Ps(u.poly),g));if(e)return e}catch{}return function(e,t){try{return Ds(qt(Ps(e),Ps(t)))}catch{return null}}(_,u.poly)||d.map(e=>[e[0],e[1]])}function Ps(e){const t=e.map(e=>[e[0],e[1]]);return t.push([e[0][0],e[0][1]]),[t]}function Fs(e){return!(!Array.isArray(e)||!e.length)&&e.every(e=>Array.isArray(e)&&e.length&&e.every(e=>Array.isArray(e)&&e.length>=4&&e.every(e=>Array.isArray(e)&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1])))&&Math.abs($i(e[0]))>1e-9)}function zs(e,t,i,n){const r=n?new Set(n):null;let o=null;for(let n=0;nt.epsilon))continue;const l=Hs([[e.point[0]+a[0]*n.halfDepth,e.point[1]+a[1]*n.halfDepth],[e.point[0]+s.u[0]*r+a[0]*n.halfDepth,e.point[1]+s.u[1]*r+a[1]*n.halfDepth],[e.point[0]+s.u[0]*r-a[0]*n.halfDepth,e.point[1]+s.u[1]*r-a[1]*n.halfDepth],[e.point[0]-a[0]*n.halfDepth,e.point[1]-a[1]*n.halfDepth]],t.coordinateScale);if(!l)continue;const c=Ps(l);o=o?Bt(o,c):c}}return o}function Is(e,t,i){let n=null;for(const r of e.rays)for(const e of r.continuations){const r=[-e.u[1],e.u[0]],o=[e.start[0]+e.u[0]*e.length,e.start[1]+e.u[1]*e.length],s=Hs([[e.start[0]+r[0]*e.halfDepth,e.start[1]+r[1]*e.halfDepth],[o[0]+r[0]*e.halfDepth,o[1]+r[1]*e.halfDepth],[o[0]-r[0]*e.halfDepth,o[1]-r[1]*e.halfDepth],[e.start[0]-r[0]*e.halfDepth,e.start[1]-r[1]*e.halfDepth]],t.coordinateScale);if(!s)continue;const a=qt(Ps(s),i);Array.isArray(a)&&0!==a.length&&(n=n?Bt(n,a):a)}return n}function Os(e,t,i=2*(4*e.halfDepth+2*t.epsilon)){const n=function(e,t=wo){const i=new Set,n=Number.isFinite(t)&&t>=0?t:wo;for(let t=0;te-t)}(e);return n.length?zs(e,t,i,n):null}function Es(e,t,i,n,r){const o=function(e){let t=null;for(const i of e){const e=Ps(i);try{t=t?Bt(t,e):e}catch{}}return t}(function(e,t,i=!1){if(!e)return[];const n=[];for(const r of e.nodes)for(let o=0;o1e-9)||h>=Math.PI-1e-9)continue;const d=[-s.u[1],s.u[0]],u=[-a.u[1],a.u[0]],p=[r.point[0]+d[0]*s.halfDepth,r.point[1]+d[1]*s.halfDepth],_=[r.point[0]-u[0]*a.halfDepth,r.point[1]-u[1]*a.halfDepth],m=cs(p,s.u,_,a.u);if(!m)continue;const g=Math.hypot(m[0]-r.point[0],m[1]-r.point[1]);if(!Number.isFinite(g)||g<=r.limit)continue;const f=t?Math.sqrt(Math.max(0,r.limit*r.limit-s.halfDepth*s.halfDepth)):0,v=t?Math.sqrt(Math.max(0,r.limit*r.limit-a.halfDepth*a.halfDepth)):0,y=Hs([[p[0]+s.u[0]*f,p[1]+s.u[1]*f],[_[0]+a.u[0]*v,_[1]+a.u[1]*v],m],e.coordinateScale);if(y&&n.push(y),i){const t=m[0]-r.point[0],i=m[1]-r.point[1],o=Math.hypot(t,i),s=g-r.limit;if(o>e.epsilon&&s>e.epsilon){const a=Math.min(Math.max(8*e.epsilon,.05*r.halfDepth),.25*s),l=t/o,c=i/o,h=-c,d=l,u=Hs([[m[0]-l*a+h*a,m[1]-c*a+d*a],[m[0]-l*a-h*a,m[1]-c*a-d*a],[m[0]+l*a,m[1]+c*a]],e.coordinateScale);u&&n.push(u)}}}return n}({...t,nodes:[e]},i,n));return o&&r?jt(o,r):o}function Ns(e,t,i,n){if(!e||!t.nodes.length)return e;let r=null;try{r=function(e){let t=null;for(const i of e.nodes){const n=Os(i,e);n&&(t=t?Bt(t,n):n)}return t}(t)}catch{return e}let o=e;for(const e of t.nodes){const s=4*e.halfDepth+2*t.epsilon,a=2*s,l=[[e.point[0]-s,e.point[1]-s],[e.point[0]+s,e.point[1]-s],[e.point[0]+s,e.point[1]+s],[e.point[0]-s,e.point[1]+s]];try{let s=o;const c=Es(e,t,!1,!0,r);c&&(s=jt(s,c));let h=zs(e,t,a);const d=Es(e,t,!0,!0,r);d&&(h=jt(h,d)),r&&(h=Bt(h,r));const u=.02*Math.min(...e.rays.map(e=>e.halfDepth));if(h=Bt(h,Ps([[e.point[0]-u,e.point[1]-u],[e.point[0]+u,e.point[1]-u],[e.point[0]+u,e.point[1]+u],[e.point[0]-u,e.point[1]+u]])),!h)continue;let p=qt(h,Ps(l));n?p=qt(p,n):i&&(p=qt(p,i));const _=Ps(l),m=jt(s,_),g=i?jt(qt(s,_),i):null,f=Is(e,t,_);o=Bt(m,...g?[g]:[],...f?[f]:[],p)}catch{}}if(r)try{let e=r;n?e=qt(e,n):i&&(e=qt(e,i)),o=Bt(o,e)}catch{}return o}function Hs(e,t=1){if(!Array.isArray(e)||e.length<3)return null;const i=Number.isFinite(t)&&t>0?t:1,n=1e-12*Math.max(1,i),r=[];for(const t of e){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),i=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(i))return null;const o=Math.round(e/n)*n,s=Math.round(i/n)*n;if(!Number.isFinite(o)||!Number.isFinite(s))return null;r.push([Object.is(o,-0)?0:o,Object.is(s,-0)?0:s])}return Math.abs(ss(r))>n*n?r:null}function Ls(e,t,i,n){if(Ts(e[0],e[1],t[0],t[1],i[0],i[1])>n)return!1;const r=i[0]-t[0],o=i[1]-t[1],s=(e[0]-t[0])*r+(e[1]-t[1])*o,a=r*r+o*o,l=n*Math.sqrt(a);return s>=-l&&s<=a+l}function Bs(e,t,i){const n=[],r=[];for(let o=0;oi*i))continue;const d=i/Math.sqrt(h),u=[0,1];for(const e of t)for(const t of[e.a,e.b]){if(!Ls(t,s,a,i))continue;const e=((t[0]-s[0])*l+(t[1]-s[1])*c)/h;e>d&&e<1-d&&u.push(e)}u.sort((e,t)=>e-t);const p=u.filter((e,t)=>0===t||Math.abs(e-u[t-1])>d);for(let e=0;e=3&&r.length===n.length?{poly:n,offsets:r}:null}function qs(e,t,i,n,r,o,s,a){const l=(e||[]).map(ei).filter(e=>!!e&&e.length>=3);if(!l.length)return null;let c=Bt(Ps(l[0]));for(let e=1;e"outer"===e.kind&&e.half>0),u=4*os(n,s),p=a||bs(h,u,s);let _=null;for(const e of function(e){const t=[];for(const i of Array.isArray(e)?e:[])if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,-1).map(e=>[e[0],e[1]]);i.length>=3&&t.push(i)}return t}(c)){const t=Bs(e,d,u);if(!t||!t.offsets.some(e=>e>0))continue;const i=Js(t.poly,t.offsets,p),n=us(t.poly,t.offsets,p);if(!i||!n)continue;const r=jt(Ps(i),Ps(n));_=_?Bt(_,r):r}return{centre:c,shell:_||[]}}function js(e,t,i,n,r,o,s=1){try{const a=qs(e,t,i,n,r,o,s,xs(e,t,i,n,r,o,s));if(!a)return[];return a.shell?.length?Bt(a.centre,a.shell):a.centre}catch{return null}}function Ws(e){if(!e)return"";let t="";for(const i of e)if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,e.length-1);i.length<3||(t+=(t?" ":"")+ps(i.map(e=>[e[0],e[1]])))}return t}const Us=15;function Vs(e,t,i){const n=e?.length||0;if(n<3||t?.length!==n)return!1;const r=e[(i-1+n)%n],o=e[i],s=e[(i+1)%n],a=[r[0]-o[0],r[1]-o[1]],l=[s[0]-o[0],s[1]-o[1]],c=Math.hypot(a[0],a[1]),h=Math.hypot(l[0],l[1]);if(!(c>1e-9&&h>1e-9))return!1;const d=Math.max(-1,Math.min(1,(a[0]*l[0]+a[1]*l[1])/(c*h))),u=Math.acos(d);if(!(u>1e-9))return!1;if(u>=Us*Math.PI/180)return!1;const p=Math.max(0,t[(i-1+n)%n]),_=Math.max(0,t[i]);if(!(p>0||_>0))return!1;const m=Math.sin(u);if(!(m>1e-12))return!1;const g=(_+p*d)/m,f=(p+_*d)/m;return Number.isFinite(g)&&Number.isFinite(f)&&g>0&&f>0&&ge>0))continue;for(const e of l.offsets)e>0&&(u=Math.max(u,2*e));const c=Js(l.poly,l.offsets,d),p=us(l.poly,l.offsets,d);c&&h.push({outset:c,inset:p})}for(const e of l){const t=e.map(e=>e[0]),i=e.map(e=>e[1]);if(t.length){const n=Math.min(Math.max(...t)-Math.min(...t),Math.max(...i)-Math.min(...i)),r=Math.min(...e.map((t,i)=>{const n=e[(i+1)%e.length];return Math.hypot(n[0]-t[0],n[1]-t[1])}));u=Math.max(u,e.length>16?n:r)}}const p=function(e,t,i,n,r,o,s,a){if(!t?.length||!i?.length)return[];const l=4*os(n,s),c=new Map;for(const a of $s(e,t,i,n,r,o,s))!a.open&&a.half>0&&!c.has(a.key)&&c.set(a.key,a);const h=[...c.values()];if(h.length<2)return[];const d=a||bs(h,l),u=[];for(const e of i)for(const t of[[e[0],e[1]],[e[2],e[3]]])u.some(e=>Math.hypot(e[0]-t[0],e[1]-t[1])<=l)||u.push(t);const p=[],_=(e,t)=>{let i=0,n=0;if(Math.hypot(e.a[0]-t[0],e.a[1]-t[1])<=l)i=e.b[0]-e.a[0],n=e.b[1]-e.a[1];else{if(!(Math.hypot(e.b[0]-t[0],e.b[1]-t[1])<=l))return null;i=e.a[0]-e.b[0],n=e.a[1]-e.b[1]}const r=Math.hypot(i,n);return r>l?[i/r,n/r]:null};for(const e of u){const t=h.map(t=>({iv:t,u:_(t,e)})).filter(e=>!!e.u);for(let i=0;i0?[e.slice(),u,m,_]:[e.slice(),_,m,u];else{if(!f)continue;{const t=[-r.u[1],r.u[0]],i=[-o.u[1],o.u[0]],n=s<0?1:-1,a=[e[0]+t[0]*r.iv.half*n,e[1]+t[1]*r.iv.half*n],l=[e[0]-i[0]*o.iv.half*n,e[1]-i[1]*o.iv.half*n];y=s>0?[e.slice(),a,l]:[e.slice(),l,a]}}Math.abs(ss(y))>l*l&&p.push(y)}}return p}(e,t,i,r,o,s,a,d),_=n.length?Qs(e,t,i,r,o,s,a):null;let m="exterior";try{const v=qs(e,t,i,r,o,s,a,d);m="paper";const y=v?v.shell?.length?Bt(v.centre,v.shell):v.centre:[],b=e=>{const t=Ps(e.outset);if(!e.inset)return t;const i=Ps(e.inset);return jt(t,i)};m="room-rings";let w=null;for(const e of h)try{const t=b(e);w=w?Bt(w,t):t}catch{}if(m="edge-bodies",v)for(const n of Xs(e,t,i,r,o,s,a))try{const e=qt(Ps(n.quad),v.centre);w=w?Bt(w,e):e}catch{}m="junctions",w=function(e,t,i=1,n=Bt){let r=e;for(const e of t||[]){const t=Hs(e,i);if(t)try{const e=Ps(t);r=r?n(r,e):e}catch{}}return r}(w,p,a),m="facade-clip",w&&v&&(w=qt(w,v.centre)),m="exterior-shell";const k=[];let x=0;if(v?.shell?.length)if(w)try{const e=Bt(w,v.shell);if(!Fs(e))throw new Error("invalid shell union");w=e}catch{if(!Fs(w)||!Fs(v.shell))throw new Error("invalid shell");k.push({id:"exterior-shell",geom:v.shell}),x++}else w=v.shell;if(m="multi-wall-trim",w&&d.nodes.length){const e=e=>e.rays.some(e=>e.supports.some(e=>e.length<2*e.halfDepth)),t=d.nodes.filter(e);if(t.length){w=Ns(w,{...d,nodes:t},v?.centre,y)}}if(m="junction-corners",d.nodes.length){const n=ws(d),l=function(e,t,i,n,r,o,s,a){try{const l=qs(e,t,i,n,r,o,s,{epsilon:a.epsilon,coordinateScale:a.coordinateScale,nodes:[],index:new Map});return l?l.shell?.length?Bt(l.centre,l.shell):l.centre:null}catch{return null}}(e,t,i,r,o,s,a,d);for(const e of n.fans)try{let t=[Ps(e)];if(l&&(t=qt(t,l)),!t?.length)continue;w=w?Bt(w,t):t}catch{}g=w,f=Math.max(d.epsilon,1e-9)**2,w=Array.isArray(g)?g.map(e=>{if(!Array.isArray(e)||!e.length)return e;const[t,...i]=e;return Math.abs(ss(t||[]))<=f?null:[t,...i.filter(e=>Math.abs(ss(e||[]))>f)]}).filter(e=>!!e):g}const S=w||[],$=[...Fs(S)?[{id:"room-primary",geom:S}]:[],...k.map((e,t)=>({id:`room-isolated-${t}`,geom:e.geom}))];m="openings";for(const e of n){if(!(e.length>0))continue;const t=ia(_,e,!0);if(!t.negative&&!t.positive)continue;const i=e.angle*Math.PI/180,n=Math.cos(i),o=Math.sin(i),s=-o,l=n,c=e.length/2,h=1.25*Math.max(u,r*a),d=[[e.x-n*c-s*h,e.y-o*c-l*h],[e.x+n*c-s*h,e.y+o*c-l*h],[e.x+n*c+s*h,e.y+o*c+l*h],[e.x-n*c+s*h,e.y-o*c+l*h]];w&&(w=jt(w,Ps(d)));for(const e of k)e.geom=jt(e.geom,Ps(d))}m="extras";const M=[];let R=0;const C=c.mergeExtra||((e,t)=>e?Bt(e,t):t);for(let e=0;ee.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]))||Math.abs($i(t))<=1e-9){R++;continue}const i=[Ps(t)];try{const t=C(w,i,e);if(!Fs(t))throw new Error("invalid extra union");w=t}catch{R++,Fs(i)&&M.push({id:`extra-${e}`,geom:i})}}M.push(...k),M.sort((e,t)=>Ws(e.geom).localeCompare(Ws(t.geom)));const T=w||[];return{status:R||x?"degraded-extra":"ok",geom:T,components:[...Fs(T)?[{id:"primary",geom:T}]:[],...M.map((e,t)=>({...e,id:`isolated-${t}`}))],roomGeom:S,roomComponents:$,paperGeom:y,depthUnits:u,openingPadUnits:1.25*Math.max(u,r*a),openingIndex:_,multiWallNodes:d,degradedExtraCount:R+x}}catch{return c.onCoreFailure?.(m),{status:"failed-core",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:u,openingIndex:null,multiWallNodes:d,degradedExtraCount:0}}var g,f}function Ks(e,t,i,n=[],r,o,s,a=1,l=[],c={}){if(!t?.length&&!l.length)return null;return Ys(Gs(e,t,i,n,r,o,s,a,l,c))}function Ys(e){if("failed-core"===e.status||"not-applicable"===e.status)return null;const t=e.components.map(e=>({id:e.id,d:Ws(e.geom),fillRule:"evenodd"})).filter(e=>!!e.d),i=t[0]?.d||"",n=Ws(e.paperGeom);if(t.length){const r={status:e.status,d:i,paths:t,components:e.components,roomGeom:e.roomGeom,multiWallNodes:e.multiWallNodes,paperD:n,depthUnits:e.depthUnits,fillRule:"evenodd"};return Object.defineProperties(r,{roomComponents:{value:e.roomComponents||[],enumerable:!1},openingIndex:{value:e.openingIndex,enumerable:!1},openingPadUnits:{value:e.openingPadUnits,enumerable:!1}}),r}return null}function Xs(e,t,i,n,r,o,s=1){if(!t?.length)return[];const a=new Set,l=[];for(const c of e||[]){if(!c?.id)continue;const h=Ss(e,c.id,t,i,n,r,o,s);if(!h)continue;const d=h.poly;for(let e=0;e0))continue;const p=Fo(t,i,n,s);if(a.has(p))continue;a.add(p);const _=Ro(u,r,o),[m,g]=as(d,e),f=-m,v=-g,y=_/2,b=[[t[0]+f*y,t[1]+v*y],[i[0]+f*y,i[1]+v*y],[i[0]+m*y,i[1]+g*y],[t[0]+m*y,t[1]+g*y]];l.push({key:p,kind:c,cm:u,quad:b,a:[t[0],t[1]],b:[i[0],i[1]],depthUnits:_})}}return l}function Zs(e,t=[]){let i=ps(e.quad);const[n,r]=Ao(e.a,e.b),o=n,s=r,a=-s,l=o;for(const n of t){if(!qo(e.a,e.b,n.angle))continue;if(Ts(n.x,n.y,e.a[0],e.a[1],e.b[0],e.b[1])>Math.max(.55*e.depthUnits,.001))continue;const t=n.length/2,r=e.depthUnits,c=n.x,h=n.y;i+=` ${ps(_s([[c-o*t-a*r,h-s*t-l*r],[c+o*t-a*r,h+s*t-l*r],[c+o*t+a*r,h+s*t+l*r],[c-o*t+a*r,h-s*t+l*r]]))}`}return i}function Js(e,t,i){const n=e?.length||0;if(n<3||t.length!==n)return null;if(t.every(e=>!(e>0)))return e.map(e=>[e[0],e[1]]);_s(e),t.slice().reverse();const r=[];for(let o=0;o0||l>0)){r.push([e[o][0],e[o][1]]);continue}if(a>0!=l>0){const t=e[o],i=a>0?[t[0]-c*a,t[1]-h*a]:[t[0],t[1]],n=l>0?[t[0]-d*l,t[1]-u*l]:[t[0],t[1]];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}if(ls(w,k)){const t=e[o],i=[t[0]-c*a,t[1]-h*a],n=[t[0]-d*l,t[1]-u*l];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}const $=cs(x,w,S,k),M=Math.max(a,l,1e-9),R=ks(i,e[o])?.limit??4*M;if($){const i=Math.hypot($[0]-e[o][0],$[1]-e[o][1]);if(Number.isFinite(i)&&i<=R){r.push($);continue}if(Vs(e,t,o)){r.push([e[o][0],e[o][1]]);continue}}a>0&&r.push([e[o][0]-c*a,e[o][1]-h*a]),l>0&&r.push([e[o][0]-d*l,e[o][1]-u*l])}return r.length>=3?r:null}function Qs(e,t,i,n,r,o,s=1){const a=[];for(const l of e||[]){if(!l?.id)continue;const c=Ss(e,l.id,t,i,n,r,o,s);if(!c)continue;const h=Math.abs($i(c.poly));for(let e=0;e[Math.max(t,e.x0),Math.min(i,e.x1)]).filter(e=>e[1]-e[0]>n).sort((e,t)=>e[0]-t[0]||e[1]-t[1]);if(!r.length)return{coverage:0,full:!1};let o=r[0][0],s=r[0][1],a=0,l=o<=t+n;for(let e=1;e=i-n,{coverage:a,full:l}}function ta(e,t){return Number(t.full)-Number(e.full)||e.faceDistance-t.faceDistance||e.area-t.area||e.roomId.localeCompare(t.roomId)}function ia(e,t,i=!1){const n=Number(t?.x),r=Number(t?.y),o=Number(t?.angle),s=Number(t?.length);if(!([n,r,o,s].every(Number.isFinite)&&s>0))return{negative:null,positive:null};const a=o*Math.PI/180,l=Math.cos(a),c=Math.sin(a),h=-c,d=l,u=s/2,p=Math.max(1e-9,e.adjacencyEps),_=new Map;let m=0;for(const t of e.edges){if(i&&!(t.half>0))continue;if(!qo(t.a,t.b,o))continue;const[e,s]=Ao(t.a,t.b);if(Math.abs((n-t.a[0])*s-(r-t.a[1])*e)>p)continue;const a=(t.a[0]-n)*l+(t.a[1]-r)*c,g=(t.b[0]-n)*l+(t.b[1]-r)*c,f=Math.max(-u,Math.min(a,g)),v=Math.min(u,Math.max(a,g));if(v-f<=p)continue;const y=t.inward[0]*h+t.inward[1]*d>=0?1:-1,b=((t.a[0]+t.b[0])/2-n)*h+((t.a[1]+t.b[1])/2-r)*d,w=Math.abs(b+y*t.half),k=`${y}|${t.roomId}`,x={x0:f,x1:v,half:t.half,cm:t.cm,key:t.key,axis:[e,s]},S=_.get(k);S?(S.pieces.push(x),S.faceDistance=Math.min(S.faceDistance,w)):_.set(k,{roomId:t.roomId,side:y,order:m++,pieces:[x],faceDistance:w,area:t.area,coverage:0,full:!1})}for(const e of _.values()){const t=ea(e.pieces,-u,u,p);e.coverage=t.coverage,e.full=t.full}const g=e=>{const t=[..._.values()].filter(t=>t.side===e&&t.coverage>p);return t.sort(ta),t[0]||null};return{negative:g(-1),positive:g(1)}}function na(e,t){const i=ia(e,t),n=[i.negative,i.positive].filter(e=>!!e);if(!n.length)return{ox:0,oy:0,cm:0,side:-1};const r=i.negative&&i.positive?-1:n[0].side,o=t.flip_v?-r:r,s=(-1===o?i.negative:i.positive)||n[0],a=[...s.pieces].sort((e,t)=>(e.x0<=0&&e.x1>=0?0:Math.min(Math.abs(e.x0),Math.abs(e.x1)))-(t.x0<=0&&t.x1>=0?0:Math.min(Math.abs(t.x0),Math.abs(t.x1)))||t.x1-t.x0-(e.x1-e.x0)||e.key.localeCompare(t.key))[0];if(!(a.half>0&&a.cm>0))return{ox:0,oy:0,cm:0,side:o};const l=t.angle*Math.PI/180,c=-Math.sin(l),h=Math.cos(l);return{ox:c*o*a.half,oy:h*o*a.half,cm:a.cm,side:o}}function ra(e,t){const i=1e-9,n=t.filter(e=>Number.isFinite(e.x0)&&Number.isFinite(e.x1)&&Number.isFinite(e.half)&&e.x1>e.x0&&e.half>0);if(!n.length)return"";const r=n.flatMap(e=>[e.x0,e.x1]).sort((e,t)=>e-t),o=[];for(const e of r){const t=o[o.length-1];(void 0===t||e>t+i)&&o.push(e)}const s=[];for(let e=0;e+1t+i))continue;const a=(t+r)/2,l=n.reduce((e,t)=>a>=t.x0-i&&a<=t.x1+i?Math.max(e,t.half):e,0);if(!(l>0))continue;const c=s[s.length-1];c&&t<=c.x1+i&&Math.abs(l-c.half)<=i?c.x1=r:s.push({x0:t,x1:r,half:l})}const a=[];for(const e of s){const t=a[a.length-1],n=t?.[t.length-1];n&&e.x0<=n.x1+i?(e.x0=n.x1,t.push(e)):a.push([e])}return a.map(t=>{const i=t[0],n=t[t.length-1],r=Math.min(.25*Math.min(...t.map(e=>e.half)),.75),o=-e*r,s=[];if(1===e){s.push(`M ${i.x0} ${o} L ${n.x1} ${o}`);for(let e=t.length-1;e>=0;e--){const i=t[e];s.push(`L ${i.x1} ${i.half} L ${i.x0} ${i.half}`)}}else{s.push(`M ${n.x1} ${o} L ${i.x0} ${o}`);for(const e of t)s.push(`L ${e.x0} ${-e.half} L ${e.x1} ${-e.half}`)}return s.push("Z"),s.join(" ")}).join(" ")}function oa(e,t,i,n){if(!n)return i;const r=e.angle*Math.PI/180,o=Math.cos(r),s=Math.sin(r),a=[],l=1e-9;for(const r of i){const[i,c]=r.axis,h=o*i+s*c;if(Math.abs(h)<=l)continue;const d=e.x*i+e.y*c,u=d+h*r.x0,p=d+h*r.x1,_=Math.min(u,p),m=Math.max(u,p),g=`${r.key}|${t}`,f=n.get(g)||[];let v=[[_,m]];for(const[e,t]of f){const i=[];for(const[n,r]of v)t<=n+l||e>=r-l?i.push([n,r]):(e>n+l&&i.push([n,Math.min(r,e)]),te[0]-t[0]||e[1]-t[1]),b=[];for(const e of y){const t=b[b.length-1];t&&e[0]<=t[1]+l?t[1]=Math.max(t[1],e[1]):b.push([e[0],e[1]])}n.set(g,b)}return a}function sa(e,t){const i=new Map;return t.map(t=>function(e,t,i){const n=ia(e,t,!0),r=n.negative,o=n.positive;if(!r&&!o)return null;let s;if(r&&o)s=[{candidate:r,side:-1},{candidate:o,side:1}];else{const e=r||o;s=[{candidate:e,side:-1},{candidate:e,side:1}]}const a=s.map(({candidate:e,side:n})=>({candidate:e,side:n,pieces:oa(t,n,e.pieces,i)})),l=a.map(({candidate:e,side:t,pieces:i})=>({side:t,roomId:e.roomId,d:ra(t,i)})),c=a.flatMap(({pieces:e})=>e);if(!c.length)return null;const h=Math.max(...c.map(e=>e.half));return{faces:l,minY:-h,maxY:h,wallKey:[...new Set(c.map(e=>e.key))].sort().join("|")}}(e,t,i))}const aa=150,la=1e-6;function ca(e){return Number.isFinite(e)?Math.max(1,Math.min(aa,e)):1}function ha(e){return((Number.isFinite(Number(e))?Number(e):0)%90+90)%90}const da=e=>{const t=e.map(e=>[e[0],e[1]]);return!t.length||t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]||t.push([...t[0]]),[t]},ua=(e,t)=>e[0]===t[0]&&e[1]===t[1];function pa(e,t=1e-6){const i=Number.isFinite(t)&&t>0?t:la,n=[];for(const t of e||[]){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),r=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(r))return null;const o=Math.round(e/i)*i,s=Math.round(r/i)*i;if(!Number.isFinite(o)||!Number.isFinite(s))return null;const a=[Object.is(o,-0)?0:o,Object.is(s,-0)?0:s];n.length&&ua(n[n.length-1],a)||n.push(a)}return n.length>1&&ua(n[0],n[n.length-1])&&n.pop(),n.length<3||new Set(n.map(e=>`${e[0]},${e[1]}`)).size<3?null:$i(n)>i*i?n:null}function _a(e){const t=[];for(const i of e||[])for(const e of i||[]){const i=(e||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||t.push(`M ${i.slice(0,-1).map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`)}return t.join(" ")}function ma(e,t,i,n,r){return Xo({a:e,b:t,halfDepth:Ro(i,n,r)/2})}function ga(e,t,i){const n=Number(t)>0?Number(t):5,r=ca(e.cm)/n*i,o=e.center[0],s=e.center[1];if("circle"===e.shape){const e=r/2;return Array.from({length:96},(t,i)=>{const n=i/96*Math.PI*2;return[o+Math.cos(n)*e,s+Math.sin(n)*e]})}const a=r/2,l=ha(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l);return[[-a,-a],[a,-a],[a,a],[-a,a]].map(([e,t])=>[o+e*c-t*h,s+e*h+t*c])}function fa(e,t){const i=Number.isFinite(t)?Math.max(0,Math.min(1,t)):0,n=(e.a[0]+e.b[0])/2,r=(e.a[1]+e.b[1])/2,o=(e.b[0]-e.a[0])*i/2,s=(e.b[1]-e.a[1])*i/2;return{...e,a:[n-o,r-s],b:[n+o,r+s]}}function va(e,t,i=1e-9){if(!t.length)return[e];let n=[da(e)];try{for(const e of t){const t=e.b[0]-e.a[0],r=e.b[1]-e.a[1],o=Math.hypot(t,r);if(!(o>i))continue;const s=t/o,a=r/o,l=-a,c=s,h=1.25*Math.max(Number(e.depth)||0,4*i),d=Math.max(2*i,1e-9*o),u=[[e.a[0]-s*d-l*h,e.a[1]-a*d-c*h],[e.b[0]+s*d-l*h,e.b[1]+a*d-c*h],[e.b[0]+s*d+l*h,e.b[1]+a*d+c*h],[e.a[0]-s*d+l*h,e.a[1]-a*d+c*h]];n=jt(n,da(u))}return Ca(n)}catch{return[e]}}function ya(e,t){try{const i=jt([[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]],[[...t.map(e=>[e[0],e[1]]),[t[0][0],t[0][1]]]]);let n=null,r=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs($i(t));t.length>=4&&i>r&&(r=i,n=t.slice(0,-1).map(e=>[e[0],e[1]]))}return n}catch{return null}}function ba(e,t,i,n=Math.max(2e-4*i,1e-9),r=[]){const o=[],s=new Map;for(const e of r){const t=s.get(e.hostId)||[];t.push(e),s.set(e.hostId,t)}const a=[],l=[],c=[];for(const n of e.partitions||[]){const e={a:n.a,b:n.b,halfDepth:Ro(n.cm,t,i)/2};if(!(e.halfDepth>0))continue;const r=Xo(e);r&&(o.push(e),a.push(r),c.push({id:n.id,body:r}))}const h=o;for(const{segmentIndex:e,wedge:t}of ts(h,n)){const i={list:a,at:e},n=ya(i.list[i.at],t);n&&(i.list[i.at]=n,c[i.at].body=n)}for(const e of c)l.push(...va(e.body,s.get(e.id)||[],n));const d=(e.wall_columns||[]).map(e=>ga(e,t,i)),u=is(o,n).flatMap(e=>va(e,r,n));return{partitions:a,columns:d,patches:u,all:[...l,...u,...d]}}function wa(e){try{const t=e.map(e=>pa(e)).filter(e=>!!e).map(e=>da(e));return t.length?Bt(t[0],...t.slice(1)):null}catch{return null}}const ka=e=>`M ${e.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`;function xa(e){const t=[];for(const i of e||[]){if(Ma([i])<=1e-6)continue;const e=[];for(const t of i||[]){const i=(t||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||e.push(ka(i.slice(0,-1)))}e.length&&t.push(e.join(" "))}return t}function Sa(e,t,i={}){const n=wa(e.filter(e=>e.length>=3)),r=t.some(e=>!pa(e))?null:wa(t);if(!n)return[];if(r)try{return xa(qt(n,r))}catch{}return function(e,t,i){let n=null;for(let r=0;r=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]));return t}function Ca(e){const t=[];for(const i of e||[]){const e=i?.[0];e?.length>=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]))}return t}function Ta(e,t){let i=!1;for(let n=0,r=t.length-1;ne[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s||1e-12)+o&&(i=!i)}return i}function Da(e,t,i){return function(e,t){for(const i of t||[]){const t=i?.[0];if(!t?.length||!Ta(e,t))continue;let n=!1;for(let t=1;tTa(e,t))}function Aa(e,t,i){if(Math.hypot(e.center[0]-t.center[0],e.center[1]-t.center[1])>i)return!1;if(Math.abs(ca(e.cm)-ca(t.cm))>1e-6)return!1;if(e.shape!==t.shape)return!0;if("circle"===e.shape||"circle"===t.shape)return!0;const n=Math.abs(ha(e.angle)-ha(t.angle));return Math.min(n,90-n)<=1e-6}const Pa=2.54;function Fa(e){const t="number"==typeof e?e:NaN;return!Number.isFinite(t)||t<=0||5===t?1:5/t}function za(e,t){return e*Fa(t)}function Ia(e){return e?Pa:1}function Oa(e,t){if(!t)return String(e);const i=e/Pa;return String(Math.round(1e6*i)/1e6)}function Ea(e,t){return t?e*Pa:e}const Na=1e3;function Ha(e,t){const i=Number(e),n=Number.isFinite(i)&&i>0?i:1,r=n>=1?t:t*n,o=n>=1?t/n:t;return{x:(t-r)/2,y:(t-o)/2,w:r,h:o}}const La=.01,Ba=100;function qa(e,t=1e3){const i=Ha(e?.plan_aspect,t),n=Number(e?.plan_scale),r=Number.isFinite(n)&&n>0?Math.min(Ba,Math.max(La,n)):1,o=Number(e?.plan_scale_x),s=Number(e?.plan_scale_y),a=Number.isFinite(o)&&o>0?Math.min(Ba,Math.max(La,o)):r,l=Number.isFinite(s)&&s>0?Math.min(Ba,Math.max(La,s)):r,c=Number(e?.plan_x),h=Number(e?.plan_y),d=wr(e?.plan_angle);return{x:i.x+(Number.isFinite(c)?Qa(c):0)*t,y:i.y+(Number.isFinite(h)?Qa(h):0)*t,w:i.w*a,h:i.h*l,...d?{angle:d}:{}}}function ja(e){if(null==e.x||null==e.y)return{x:e.x,y:e.y,w:e.w,h:e.h};const t=Number(e.w)||0,i=Number(e.h)||0;return{x:t<0?e.x+t:e.x,y:i<0?e.y+i:e.y,w:Math.abs(t),h:Math.abs(i)}}function Wa(e){return e&&Array.isArray(e.spaces)?e.spaces.map(e=>{const t=Na,i=function(e){return Array.isArray(e)&&4===e.length&&e.every(e=>Number.isFinite(e))&&e[2]>1e-6&&e[3]>1e-6?e:[0,0,1,1]}(e.view_box);return{id:e.id,title:e.title,cellCm:Number.isFinite(Number(e.cell_cm))&&Number(e.cell_cm)>0?Number(e.cell_cm):5,vb:[i[0]*Na,i[1]*t,i[2]*Na,i[3]*t],bg:e.plan_url?{href:Fn(e.plan_url),...qa(e,Na)}:null,rooms:(e.rooms||[]).map(e=>{const i={...e,...ja(e)};return{id:i.id,name:i.name,area:i.area??null,open_to:i.open_to||void 0,settings:i.settings||void 0,x:null!=i.x?i.x*Na:void 0,y:null!=i.y?i.y*t:void 0,w:null!=i.w?i.w*Na:void 0,h:null!=i.h?i.h*t:void 0,poly:i.poly?i.poly.map(e=>[e[0]*Na,e[1]*t]):void 0,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0}}),wall_segments:(e.wall_segments||[]).map(e=>({...e,id:String(e.id),a:[Number(e.a?.[0])*Na,Number(e.a?.[1])*t],b:[Number(e.b?.[0])*Na,Number(e.b?.[1])*t],cm:Number(e.cm)})),partitions:(e.partitions||[]).map(e=>({id:e.id,a:[e.a[0]*Na,e.a[1]*t],b:[e.b[0]*Na,e.b[1]*t],cm:Number(e.cm)})),wall_columns:(e.wall_columns||[]).map(e=>({id:e.id,shape:"circle"===e.shape?"circle":"square",center:[e.center[0]*Na,e.center[1]*t],cm:Number(e.cm),..."circle"===e.shape?{}:{angle:ha(e.angle)}}))}}):[]}const Ua=5e3,Va=Ua*Na,Ga=240,Ka=Na/Ga,Ya=1/Ga;function Xa(e){if(!Number.isFinite(e))return e;const t=Math.round(e*Ga/Na)*Na/Ga;return Math.abs(t-e)<=1e-9*Ka?e:t}function Za(e){return{x:Xa(e.x),y:Xa(e.y)}}function Ja(e){return Number.isFinite(e)?Math.min(Va,Math.max(-Va,e)):0}function Qa(e){return Number.isFinite(e)?Math.min(Ua,Math.max(-Ua,e)):0}const el=1/3,tl=200;function il(e){return"house"===e?"house":"content"}function nl(e){let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const o of e){const e=Number(o[0]),s=Number(o[1]);Number.isFinite(e)&&Number.isFinite(s)&&(en&&(n=e),s>r&&(r=s))}return t>n?null:{minX:t,minY:i,maxX:n,maxY:r}}function rl(e){const t=[],i=e=>{if(Array.isArray(e))if(e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1])))t.push([Number(e[0]),Number(e[1])]);else for(const t of e)i(t)};return i(e),nl(t)}function ol(e,t){const i=Number.isFinite(t)&&t>0?t:0;return{minX:e.minX-i,minY:e.minY-i,maxX:e.maxX+i,maxY:e.maxY+i}}function sl(e){return e.poly&&e.poly.length?nl(e.poly):null==e.x||null==e.y?null:nl([[e.x,e.y],[e.x+(e.w||0),e.y+(e.h||0)]])}function al(e,t=1e3,i=1e3){const n=Number(e.x)*t,r=Number(e.y)*i,o=Number(e.w)*t,s=Number(e.h)*i;return![n,r,o,s].every(Number.isFinite)||o<=0||s<=0?null:nl(Tr({x:n,y:r,w:o,h:s,angle:wr(e.angle)||void 0}))}function ll(e,t){const i=[];for(const t of e.rooms||[]){const e=sl(t);e&&i.push(e)}if(e.bg){const t=nl(Tr(e.bg));t&&i.push(t)}for(const e of t||[])if(Array.isArray(e)){const t=nl([e]);t&&i.push(t)}else i.push(e);return i}const cl=e=>{if(!e.length)return 0;const t=[...e].sort((e,t)=>e-t),i=t.length>>1;return t.length%2?t[i]:(t[i-1]+t[i])/2},hl=e=>{let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const o of e)o.minXn&&(n=o.maxX),o.maxY>r&&(r=o.maxY);return t>n||i>r?null:{x:t,y:i,w:n-t,h:r-i}};function dl(e,t){let{x:i,y:n,w:r,h:o}=e;r<30&&(i=i+r/2-100,r=tl),o<30&&(n=n+o/2-100,o=tl);const s="number"==typeof t?{top:t,right:t,bottom:t,left:t}:t,a=Math.max(r,o),l=a*s.top,c=a*s.right,h=a*s.bottom,d=a*s.left;return{x:i-d,y:n-l,w:r+d+c,h:o+l+h}}function ul(e,t={}){const i=t.pad??.05,n=t.k??10,r=t.minSpread??50,o=e.filter(e=>Number.isFinite(e.minX)&&Number.isFinite(e.minY)&&Number.isFinite(e.maxX)&&Number.isFinite(e.maxY)&&Math.abs(e.minX)<=Va&&Math.abs(e.maxX)<=Va&&Math.abs(e.minY)<=Va&&Math.abs(e.maxY)<=Va);if(!o.length)return{core:null,all:null,outliers:0};const s=hl(o);if(o.length<4){const e=dl(s,i);return{core:e,all:e,outliers:0}}const a=o.map(e=>(e.minX+e.maxX)/2),l=o.map(e=>(e.minY+e.maxY)/2),c=cl(a),h=cl(l),d=o.map((e,t)=>Math.max(Math.abs(a[t]-c),Math.abs(l[t]-h))),u=Math.max(((e,t)=>e.length?e[Math.min(e.length-1,Math.max(0,Math.round(t*(e.length-1))))]:0)([...d].sort((e,t)=>e-t),.75),r),p=d.map(e=>e>n*u),_=p.filter(Boolean).length,m=_&&_<=o.length*el?o.filter((e,t)=>!p[t]):o;return{core:dl(hl(m)||s,i),all:dl(s,i),outliers:m===o?0:_}}function pl(e){return ul(e,{pad:0}).all}function _l(e,t,i=.05){const n=ul(ll(e,t),{pad:i});if(n.core)return n.core;const r=e.vb&&4===e.vb.length&&e.vb[2]>0&&e.vb[3]>0?e.vb:[0,0,Na,Na];return{x:r[0],y:r[1],w:r[2],h:r[3]}}function ml(e){const t=_l(e);return{x:t.x+t.w/2,y:t.y+t.h/2}}function gl(e){const t=[];for(const i of e.rooms||[]){const e=sl(i);e&&t.push(e)}const i=ul(t,{pad:0}).core,n=Na*Fa(e.cellCm??5);return i?Math.max(n,Math.min(Va,Math.max(i.w,i.h))):n}function fl(e,t,i,n=1){const r=Number(i),o=Number.isFinite(n)&&n>0?n:1;return!Number.isFinite(r)||r<=0?e*o:e*gl(t)*o/r}const vl=[1,2,5,10,20,50,100,200,500,1e3];function yl(e,t,i=7){if(!(e>0&&t>0&&Number.isFinite(t)))return null;const n=vl.find(n=>e*n*t>=i);if(void 0===n)return null;const r=vl.find(e=>e>=5*n)??5*n;return{fine:n,coarse:r}}function bl(e){if(e.poly&&e.poly.length){const t=e.poly.map(e=>e[0]),i=e.poly.map(e=>e[1]),n=Math.min(...t),r=Math.min(...i);return{x:n,y:r,w:Math.max(...t)-n,h:Math.max(...i)-r}}return{x:e.x??0,y:e.y??0,w:e.w??0,h:e.h??0}}function wl(e,t,i,n,r,o=new Set){const s=t[e.id];return!o.has(e.id)&&s&&s.s===e.space?{x:s.x*Na,y:s.y*Na}:n[e.id]?n[e.id]:Za(ml(r))}function kl(e,t,i,n){const r=i["rl_"+(e.id||"")];if(r&&r.s===t)return{x:r.x*Na,y:r.y*Na};const o=function(e){if(e.poly){const t=e.poly.length;return[e.poly.reduce((e,t)=>e+t[0],0)/t,e.poly.reduce((e,t)=>e+t[1],0)/t]}return[e.x+e.w/2,e.y+.1*Math.min(e.w,e.h)]}(e);return Za({x:o[0],y:o[1]})}function xl(e,t){for(const i of e?.spaces??[])for(const e of i?.decor??[])if("furniture"===e?.kind&&"string"==typeof e.symbol&&t(e.symbol))return!0;return!1}let Sl=0;const $l=new Set;const Ml=new class{constructor(e){this.options=e,this._art=null,this._failed=!1,this._terminal=!1,this._inFlight=null,this._hosts=new Set,this._settled=[]}state(){return this._art?"ready":this._failed?"fallback":"pending"}get terminal(){return this._terminal}art(e,t){if(this._art)return this._art[e];t&&!this._failed&&this._hosts.add(t)}adopt(e,t){return!!this._art||(t!==this.options.expectedFingerprint?((this.options.warn??console.warn)("[houseplan] furniture artwork from another build ignored",{fingerprint:t}),!1):(this._install(e),!0))}ensure(){return"pending"!==this.state()?Promise.resolve():(this._inFlight||(this._inFlight=this._loadWithRetry().finally(()=>{this._inFlight=null})),this._inFlight)}onSettled(e){"pending"===this.state()?this._settled.push(e):Promise.resolve().then(e)}async _loadWithRetry(){let e=new Error("furniture artwork did not load");for(const t of[0,1])try{const i=await this.options.load(t);if(i.FURNITURE_ART_FINGERPRINT!==this.options.expectedFingerprint){this._terminal=!0,e=new Error(`furniture artwork fingerprint mismatch: expected ${this.options.expectedFingerprint}, got ${i.FURNITURE_ART_FINGERPRINT}`);break}if(this._art)return;return void this._install(i.GENERATED_FURNITURE_ART)}catch(t){e=t}this._art||(this._failed=!0,(this.options.warn??console.warn)("[houseplan] furniture artwork unavailable",e),this.options.loadFailed?.(this._terminal),this._flush())}_install(e){this._art=e,this._failed=!1,this._flush()}_flush(){const e=[...this._hosts];this._hosts.clear();for(const t of e)t.isConnected&&t.requestUpdate();const t=this._settled.splice(0);for(const e of t)e()}}({expectedFingerprint:"646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00",load:async e=>0===e?await import("./furniture-plan-art.generated-DPM3xdWV.js"):await import((()=>{const e=new URL("./furniture-plan-art.generated-DPM3xdWV.js",import.meta.url);return e.searchParams.set("hp_retry","art-"+ ++Sl),e.href})()),loadFailed:e=>{for(const t of $l)t(e)}}),Rl=["furniture","appliance","sanitary","other"],Cl=[{id:"sofa",group:"furniture",category:"sofa",w:220,h:90,g:[["r",0,0,1,1],["l",.09,.26,.91,.26],["l",.09,.26,.09,1],["l",.91,.26,.91,1],["l",.5,.26,.5,1]]},{id:"armchair",group:"furniture",category:"armchair",w:90,h:85,g:[["r",0,0,1,1],["l",.14,.28,.86,.28],["l",.14,.28,.14,1],["l",.86,.28,.86,1]]},{id:"coffee_table",group:"furniture",category:"coffee_table",w:110,h:60,g:[["r",0,0,1,1],["r",.08,.14,.84,.72]]},{id:"table_dining",group:"furniture",category:"dining_table",w:140,h:80,g:[["r",0,0,1,1],["r",.06,.11,.88,.78]]},{id:"table_round",group:"furniture",category:"dining_table",w:120,h:120,g:[["e",.5,.5,.5,.5],["e",.5,.5,.41,.41]]},{id:"chair",group:"furniture",category:"chair",w:45,h:45,g:[["r",0,0,1,.18],["r",.06,.18,.88,.8]]},{id:"desk",group:"furniture",category:"work_table",w:120,h:60,g:[["r",0,0,1,1],["r",.63,.07,.31,.86],["l",.63,.5,.94,.5]]},{id:"bed_double",group:"furniture",category:"bed",w:160,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.06,.1,.4,.15],["r",.54,.1,.4,.15],["l",0,.33,1,.33]]},{id:"bed_single",group:"furniture",category:"bed",w:90,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.15,.1,.7,.15],["l",0,.33,1,.33]]},{id:"nightstand",group:"furniture",category:"nightstand",w:45,h:40,g:[["r",0,0,1,1],["r",.12,.14,.76,.33],["r",.12,.53,.76,.33]]},{id:"wardrobe",group:"furniture",category:"wardrobe",w:100,h:60,g:[["r",0,0,1,1],["l",0,.72,1,.72],["l",.5,.72,.5,1]]},{id:"bookshelf",group:"furniture",category:"wardrobe",w:80,h:30,g:[["r",0,0,1,1],["l",.34,0,.34,1],["l",.67,0,.67,1]]},{id:"fridge",group:"appliance",category:"fridge",w:60,h:65,g:[["r",0,0,1,1],["l",0,.36,1,.36],["l",.83,.44,.83,.64]]},{id:"stove",group:"appliance",category:"cooktop",w:60,h:60,g:[["r",0,0,1,1],["e",.29,.31,.15,.15],["e",.71,.31,.15,.15],["e",.29,.71,.15,.15],["e",.71,.71,.15,.15]]},{id:"dishwasher",group:"appliance",category:"dishwasher",w:60,h:60,g:[["r",0,0,1,1],["r",.1,.12,.8,.76],["e",.5,.5,.27,.27],["e",.5,.5,.13,.13]]},{id:"washer",group:"appliance",category:"washer",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["e",.5,.57,.14,.14]]},{id:"dryer",group:"appliance",category:"dryer",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["p",.36,.5,.5,.64,.64,.5]]},{id:"tv",group:"appliance",category:"tv",w:120,h:30,g:[["r",0,0,1,.42],["l",.5,.42,.5,.72],["l",.3,.72,.7,.72]]},{id:"ac",group:"appliance",category:"air_conditioner",w:90,h:25,g:[["r",0,0,1,1],["l",.05,.55,.95,.55],["l",.05,.79,.95,.79]]},{id:"water_heater",group:"appliance",category:"boiler",w:45,h:45,g:[["e",.5,.5,.5,.5],["e",.5,.5,.31,.31]]},{id:"toilet",group:"sanitary",category:"toilet",w:40,h:70,g:[["r",.06,0,.88,.2],["e",.5,.58,.37,.35],["e",.5,.58,.22,.2]]},{id:"bathtub",group:"sanitary",category:"bathtub",w:170,h:75,g:[["r",0,0,1,1],["r",.05,.11,.77,.78],["e",.89,.5,.045,.1]]},{id:"shower",group:"sanitary",category:"shower",w:90,h:90,g:[["r",0,0,1,1],["l",0,0,1,1],["l",1,0,0,1],["e",.5,.5,.08,.08]]},{id:"sink",group:"sanitary",category:"sink",w:60,h:45,g:[["r",0,0,1,1],["e",.5,.6,.34,.3],["e",.5,.15,.07,.07]]},{id:"kitchen_sink",group:"sanitary",category:"kitchen_sink",w:80,h:60,g:[["r",0,0,1,1],["r",.06,.24,.44,.64],["r",.54,.24,.4,.64],["e",.5,.12,.06,.06]]},{id:"bidet",group:"sanitary",category:"bidet",w:40,h:55,g:[["e",.5,.5,.44,.5],["e",.5,.5,.26,.3]]},{id:"stairs",group:"other",category:"stairs",w:100,h:280,g:[["r",0,0,1,1],["l",0,.111,1,.111],["l",0,.222,1,.222],["l",0,.333,1,.333],["l",0,.444,1,.444],["l",0,.556,1,.556],["l",0,.667,1,.667],["l",0,.778,1,.778],["l",0,.889,1,.889],["l",.5,.93,.5,.06],["p",.38,.16,.5,.06,.62,.16]]},{id:"fireplace",group:"other",category:"fireplace",w:120,h:40,g:[["r",0,0,1,1],["p",.22,1,.22,.42,.78,.42,.78,1]]},{id:"plant",group:"other",category:"plant",w:40,h:40,g:[["e",.5,.5,.22,.22],["l",.5,.28,.5,.02],["l",.5,.72,.5,.98],["l",.28,.5,.02,.5],["l",.72,.5,.98,.5],["l",.34,.34,.13,.13],["l",.66,.66,.87,.87],["l",.66,.34,.87,.13],["l",.34,.66,.13,.87]]},{id:"rug",group:"other",category:"rug",w:200,h:140,g:[["r",0,0,1,1],["r",.06,.09,.88,.82]]}],Tl=new Set(["fridge","dishwasher","washer","dryer","ac","water_heater","shower","sink","stairs","fireplace","plant","rug"]),Dl=[...[{id:"coffee_table",group:"furniture",category:"coffee_table",w:120,h:60},{id:"coffee_table_round",group:"furniture",category:"coffee_table",w:80,h:80},{id:"coffee_table_oval",group:"furniture",category:"coffee_table",w:120,h:60},{id:"coffee_table_rounded",group:"furniture",category:"coffee_table",w:120,h:60},{id:"table_dining",group:"furniture",category:"dining_table",w:160,h:90},{id:"table_round",group:"furniture",category:"dining_table",w:110,h:110},{id:"table_dining_oval",group:"furniture",category:"dining_table",w:180,h:100},{id:"table_dining_rounded",group:"furniture",category:"dining_table",w:160,h:90},{id:"desk",group:"furniture",category:"work_table",w:140,h:70},{id:"desk_corner",group:"furniture",category:"work_table",w:160,h:160},{id:"chair",group:"furniture",category:"chair",w:50,h:50},{id:"chair_bar",group:"furniture",category:"chair",w:45,h:48},{id:"armchair",group:"furniture",category:"armchair",w:90,h:90},{id:"armchair_office",group:"furniture",category:"armchair",w:65,h:65},{id:"sofa",group:"furniture",category:"sofa",w:180,h:90},{id:"sofa_three_seat",group:"furniture",category:"sofa",w:240,h:90},{id:"sofa_corner_right",group:"furniture",category:"sofa",w:260,h:170},{id:"bed_single",group:"furniture",category:"bed",w:90,h:200},{id:"bed_double",group:"furniture",category:"bed",w:160,h:200},{id:"nightstand",group:"furniture",category:"nightstand",w:50,h:40},{id:"cabinet_tv",group:"furniture",category:"nightstand",w:140,h:45},{id:"cabinet_shoe",group:"furniture",category:"nightstand",w:80,h:35},{id:"cabinet_sink",group:"furniture",category:"nightstand",w:80,h:50},{id:"bookshelf",group:"furniture",category:"wardrobe",w:100,h:35},{id:"wall_unit",group:"furniture",category:"wardrobe",w:240,h:45},{id:"wardrobe",group:"furniture",category:"wardrobe",w:180,h:60},{id:"kitchen_floor",group:"furniture",category:"kitchen_cabinet",w:60,h:60},{id:"kitchen_floor_corner",group:"furniture",category:"kitchen_cabinet",w:90,h:90},{id:"kitchen_wall",group:"furniture",category:"kitchen_cabinet",w:60,h:35},{id:"kitchen_wall_corner",group:"furniture",category:"kitchen_cabinet",w:60,h:60},{id:"shelf_floor",group:"furniture",category:"shelving",w:100,h:35},{id:"shelf_wall",group:"furniture",category:"shelving",w:100,h:25},{id:"cooktop_two",group:"appliance",category:"cooktop",w:30,h:50},{id:"stove",group:"appliance",category:"cooktop",w:60,h:60},{id:"tv",group:"appliance",category:"tv",w:120,h:28},{id:"tv_wall",group:"appliance",category:"tv",w:120,h:15},{id:"toilet",group:"sanitary",category:"toilet",w:40,h:70},{id:"toilet_built_in",group:"sanitary",category:"toilet",w:40,h:55},{id:"bathtub",group:"sanitary",category:"bathtub",w:170,h:75},{id:"bathtub_corner",group:"sanitary",category:"bathtub",w:140,h:140},{id:"bidet",group:"sanitary",category:"bidet",w:40,h:60},{id:"bidet_built_in",group:"sanitary",category:"bidet",w:40,h:50},{id:"kitchen_sink",group:"sanitary",category:"kitchen_sink",w:60,h:50},{id:"kitchen_sink_double",group:"sanitary",category:"kitchen_sink",w:90,h:50}].map(e=>({id:e.id,group:e.group,category:e.category,w:e.w,h:e.h,designer:!0})),...Cl.filter(e=>Tl.has(e.id))],Al=new Map(Dl.map(e=>[e.id,e]));function Pl(e){return e&&Al.get(e)||null}function Fl(e){return!0===Al.get(e)?.designer}function zl(e){return Dl.filter(t=>t.group===e)}function Il(e){const t=Pl(e);return t?{w:t.w,h:t.h}:{w:60,h:60}}function Ol(e,t,i=Ka,n=1e3){const r=Number(t)>0?Number(t):5;return(Number(e)||0)/r*i/n}const El=5e-4,Nl=Ua;function Hl(e){return Number.isFinite(e)?Math.max(El,Math.min(Nl,e)):El}function Ll(e){return Number.isFinite(e)?Math.max(1,Math.min(1e4,e)):1}const Bl=e=>{const t=Math.round(1e3*e)/1e3;return Object.is(t,-0)?"0":String(t)};function ql(e,t){const i=Pl(e);if(!i)return null;if(i.designer)return Ml.art(e,t)??null;const n=function(e,t,i){if(!e.g)return"";const n=e=>Bl(e*t),r=e=>Bl(e*i),o=[];for(const s of e.g)if("r"===s[0]){const[,e,t,i,a]=s;o.push(`M${n(e)} ${r(t)}H${n(e+i)}V${r(t+a)}H${n(e)}Z`)}else if("l"===s[0]){const[,e,t,i,a]=s;o.push(`M${n(e)} ${r(t)}L${n(i)} ${r(a)}`)}else if("e"===s[0]){const[,e,a,l,c]=s;o.push(`M${n(e-l)} ${r(a)}A${Bl(l*t)} ${Bl(c*i)} 0 0 1 ${n(e+l)} ${r(a)}A${Bl(l*t)} ${Bl(c*i)} 0 0 1 ${n(e-l)} ${r(a)}Z`)}else{const e=s.slice(1);if(e.length<4)continue;let t=`M${n(e[0])} ${r(e[1])}`;for(let i=2;i+10?n:Number.isFinite(r)&&r>0?r:1,s=Number(t),a=o*(Number.isFinite(s)&&s>0?s:1);return Number.isFinite(a)&&a>0?a:o}function Wl(e,t,i,n,r){const o=e+i/2,s=t+n/2,a=(Number(r)||0)*Math.PI/180,l=Math.cos(a),c=Math.sin(a),h=(e,t)=>{const i=e-o,n=t-s;return[o+i*l-n*c,s+i*c+n*l]};return[h(e,t),h(e+i,t),h(e+i,t+n),h(e,t+n)]}function Ul(e,t,i,n,r,o,s){const a=Number.isFinite(s)&&s>0?s:1e-6,l=(Number(e.angle)||0)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),u=Math.cos(l),p=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:t<0?e.w/2:0,g=i>0?-e.h/2:i<0?e.h/2:0,f=p+m*c+g*d,v=_+m*h+g*u,y=n-f,b=r-v,w=t?(y*c+b*h)*(t>0?1:-1):e.w,k=i?(y*d+b*u)*(i>0?1:-1):e.h;let x=t?Math.abs(w):e.w,S=i?Math.abs(k):e.h;if(o&&t&&i){const t=x/Math.max(e.w,a),i=S/Math.max(e.h,a),n=Math.abs(t-1)>=Math.abs(i-1)?t:i,r=Math.max(a/e.w,a/e.h),o=Math.max(r,Number.isFinite(n)?n:r);x=e.w*o,S=e.h*o}x=Math.max(a,Number.isFinite(x)?x:a),S=Math.max(a,Number.isFinite(S)?S:a);const $=!!t&&w<0,M=!!i&&k<0,R=t?(t>0?1:-1)*($?-1:1):0,C=i?(i>0?1:-1)*(M?-1:1):0,T=f+R*(x/2)*c+C*(S/2)*d,D=v+R*(x/2)*h+C*(S/2)*u,A=!!e.flip_h!==$,P=!!e.flip_v!==M;return{x:T-x/2,y:D-S/2,w:x,h:S,...Number(e.angle)?{angle:Number(e.angle)}:{},...A?{flip_h:!0}:{},...P?{flip_v:!0}:{}}}function Vl(e,t,i,n){let r=Number(e)+(Number(i)-Number(t));if([r,t,i].every(Number.isFinite)||(r=0),n){const e=r/45;r=45*(e<0?-Math.round(Math.abs(e)):Math.round(e))}return r=(r%360+360)%360,r>180?r-360:r}function Gl(e,t,i,n,r){const o=e.x*t,s=e.y*i,a=e.w*t,l=e.h*i,c=o+a/2,h=s+l/2,d=o+(e.flip_h?a:0),u=s+(e.flip_v?l:0),p=(e.flip_h?-1:1)*a/n,_=(e.flip_v?-1:1)*l/r,m=Number(e.angle)||0;return(m?`rotate(${m} ${c} ${h}) `:"")+`translate(${d} ${u}) scale(${p} ${_})`}function Kl(e,t,i,n=.1){if("string"==typeof e&&!e.trim())return null;const r=Number(e);if(!Number.isFinite(r)||0===r)return null;const o=r*(t?30.48:100),s=Math.abs(o);return si?null:o}function Yl(e,t,i){const n=Math.abs(Number(e))/(i?30.48:100),r=Number(n.toFixed(6));return String(t?-r:r)}const Xl=15e3,Zl=2e3,Jl=new WeakMap;function Ql(e,t){let i=Jl.get(e);if(!i){const t=new Set;i={hiddenAt:"hidden"===e.visibilityState?Date.now():0,token:0,subscribers:t,onVisibility:()=>{const t=Jl.get(e);if(!t)return;const i=Date.now();if("hidden"===e.visibilityState){t.hiddenAt||(t.hiddenAt=i);const e={kind:"hidden",token:t.token,at:i,hiddenFor:0,long:!1};for(const i of[...t.subscribers])i(e);return}const n=t.hiddenAt?Math.max(0,i-t.hiddenAt):0;t.hiddenAt=0,t.token++;const r={kind:"visible",token:t.token,at:i,hiddenFor:n,long:n>=Xl};for(const e of[...t.subscribers])e(r)},onPageShow:t=>{const i=Jl.get(e);if(!i)return;const n=Date.now();i.token++;const r={kind:"pageshow",token:i.token,at:n,hiddenFor:0,long:!!t.persisted,persisted:!!t.persisted};for(const e of[...i.subscribers])e(r)}},Jl.set(e,i),e.addEventListener("visibilitychange",i.onVisibility),e.defaultView?.addEventListener("pageshow",i.onPageShow)}return i.subscribers.add(t),()=>{const i=Jl.get(e);i&&(i.subscribers.delete(t),i.subscribers.size||(e.removeEventListener("visibilitychange",i.onVisibility),e.defaultView?.removeEventListener("pageshow",i.onPageShow),Jl.delete(e)))}}const ec={now:()=>Date.now(),setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>window.clearTimeout(e),requestAnimationFrame:e=>window.requestAnimationFrame(e),cancelAnimationFrame:e=>window.cancelAnimationFrame(e)};class tc{constructor(e,t=ec){this.onChange=e,this.clock=t,this._state="steady",this._token=0,this._frameFingerprint="",this._hasCompleteFrame=!1,this._overlayPhase="none",this._recoveryReason=null,this._overlayTimer=0,this._overlayRaf=0,this._overlayOpaqueAt=0,this._barrierRafs=new Set,this._trace=[],this._disposed=!1}get state(){return this._state}get token(){return this._token}get frameFingerprint(){return this._frameFingerprint}get hasCompleteFrame(){return this._hasCompleteFrame}get overlayPhase(){return this._overlayPhase}get overlayVisible(){return"none"!==this._overlayPhase}get overlayBlocksInteraction(){return this.overlayVisible}get recoveryReason(){return this._recoveryReason}get trace(){return this._trace.map(e=>({...e,...e.stage?{stage:[...e.stage]}:{}}))}note(e,t={}){this.record(e,void 0,t)}record(e,t,i={}){this._trace.push({at:this.clock.now(),token:this._token,event:e,state:this._state,...t?{reason:t}:{},...i}),this._trace.length>80&&this._trace.splice(0,this._trace.length-80)}changed(){this._disposed||this.onChange()}adoptCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-adopted"),this.changed())}markCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-complete"),this.changed())}refreshCompleteFrame(e){!this._disposed&&this._hasCompleteFrame&&"steady"===this._state&&e&&e!==this._frameFingerprint&&(this._frameFingerprint=e,this.record("frame-refreshed"))}visibility(e){return"hidden"===e.kind?(this.record("visibility-hidden"),this._token):e.long||"visible"!==e.kind&&"pageshow"!==e.kind?this.beginCandidate("pageshow"===e.kind?"pageshow":"long-resume"):(this.record("pageshow"===e.kind?"pageshow-noop":"visibility-visible-quick"),this._token)}beginCandidate(e,t="plan"){return this._token++,this._recoveryReason=t,this._hasCompleteFrame?(this._state="connection"===t?"offline-stale":"holding",this.clearOverlay()):this.overlayVisible?this._state="overlay-visible":(this._state="overlay-pending",this.scheduleOverlay(t)),this.record("candidate-start",e),this.changed(),this._token}connectionLost(){return this.beginCandidate("connection-lost","connection")}candidateReady(e){return!this._disposed&&e===this._token&&(this._state="candidate-ready",this.record("candidate-ready"),this.changed(),!0)}async commitAfterPaint(e,t){if(this._disposed||e!==this._token)return!1;let i=!0;const n=(async()=>{for(await t.updateComplete();i&&!this._disposed&&e===this._token;)if(t.stageValid()&&t.assetsReady()){if(await this.nextFrame(),e!==this._token||!t.stageValid()||!t.assetsReady())continue;if(await this.nextFrame(),e===this._token&&t.stageValid()&&t.assetsReady())return!0}else await this.nextFrame();return!1})();let r=0;const o=new Promise(e=>{r=this.clock.setTimeout(()=>e({ready:!1,timedOut:!0}),Zl)}),s=await Promise.race([n.then(e=>({ready:e,timedOut:!1})),o]);return i=!1,this.clock.clearTimeout(r),!this._disposed&&e===this._token&&(!(!s.ready&&!s.timedOut)&&(s.ready?(this._hasCompleteFrame=!0,this._frameFingerprint=t.frameFingerprint(),this.record("paint-barrier"),this.finishOverlayAfterCommit(),!0):(this.record("paint-barrier-timeout"),this._hasCompleteFrame?(this._state="connection"===this._recoveryReason?"offline-stale":"steady",this.clearOverlay()):(this._state="recovery-error","opaque"!==this._overlayPhase&&this.showOverlayNow()),this.changed(),!1)))}retry(e=this._recoveryReason||"plan"){return this.beginCandidate("retry",e)}nextFrame(){return new Promise(e=>{const t=this.clock.requestAnimationFrame(()=>{this._barrierRafs.delete(t),e()});this._barrierRafs.add(t)})}scheduleOverlay(e){this.clearOverlayTimer(),this._recoveryReason=e,this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._hasCompleteFrame||"overlay-pending"!==this._state&&"candidate-ready"!==this._state||(this._state="overlay-visible",this._overlayPhase="entering",this.record("overlay-enter"),this.changed(),this._overlayRaf=this.clock.requestAnimationFrame(()=>{this._overlayRaf=0,"entering"===this._overlayPhase&&(this._overlayPhase="fading-in",this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,"fading-in"===this._overlayPhase&&(this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-opaque"),this.changed())},150))}))},150)}showOverlayNow(){this.clearOverlayTimer(),this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-error")}finishOverlayAfterCommit(){if(this.clearOverlayTimer(),"none"===this._overlayPhase||"entering"===this._overlayPhase||"fading-in"===this._overlayPhase)return this.clearOverlay(),this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),void this.changed();const e=Math.max(0,this._overlayOpaqueAt+250-this.clock.now());this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="leaving",this.record("overlay-leave"),this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="none",this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),this.changed()},180)},e)}clearOverlayTimer(){this._overlayTimer&&this.clock.clearTimeout(this._overlayTimer),this._overlayTimer=0}clearOverlay(){this.clearOverlayTimer(),this._overlayRaf&&this.clock.cancelAnimationFrame(this._overlayRaf),this._overlayRaf=0,this._overlayPhase="none",this._overlayOpaqueAt=0}dispose(){this._disposed=!0,this._token++,this.clearOverlay();for(const e of this._barrierRafs)this.clock.cancelAnimationFrame(e);this._barrierRafs.clear()}}function ic(e){let t=2166136261,i=2654435769;const n=new WeakSet,r=e=>{for(let n=0;n>>0)+(i>>>2)}},o=e=>{if(null===e)return void r("n");const t=typeof e;if("string"===t)return void r(`s${e.length}:${e}`);if("number"===t)return void r(`d${Number.isNaN(e)?"NaN":String(e)}`);if("boolean"===t)return void r(e?"t":"f");if("undefined"===t)return void r("u");if("object"!==t)return void r(`${t}:${String(e)}`);const i=e;if(n.has(i))r("[cycle]");else{if(n.add(i),Array.isArray(e)){r("[");for(const t of e)o(t);return r("]"),void n.delete(i)}r("{");for(const t of Object.keys(e).sort())r(t),o(e[t]);r("}"),n.delete(i)}};return o(e),`${(t>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function nc(e){return ic(e)}const rc=new WeakMap;class oc{constructor(e,t=()=>Date.now()){this.onUpdate=e,this.now=t,this.fallbackAuthority={},this.referenceOwner={},this.referenced=new Set,this.queued=new Set,this.disposed=!1,this.sharedUpdate=()=>{this.disposed||this.onUpdate()}}bind(e){const t=((e,t)=>{const i=e?.connection||e?.callWS||t;return!i||"object"!=typeof i&&"function"!=typeof i?t:i})(e,this.fallbackAuthority);return this.shared&&this.authority===t||(this.shared&&(this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner)),this.authority=t,this.shared=(e=>{let t=rc.get(e);return t||(t={signed:{},queued:new Set,inFlight:new Map,retry:new Map,listeners:new Set,settlers:new Set,references:new Map},rc.set(e,t)),t})(t),this.disposed||(this.shared.listeners.add(this.sharedUpdate),this.shared.references.set(this.referenceOwner,new Set(this.referenced)))),this.shared}start(e,t){this.disposed=!1,this.referenced=new Set(t());const i=this.bind(e());i.listeners.add(this.sharedUpdate),i.references.set(this.referenceOwner,new Set(this.referenced)),this.stopTimer(),this.resignTimer=setInterval(()=>this.resign(e(),t()),288e5)}dispose(){if(this.disposed=!0,this.stopTimer(),clearTimeout(this.batchTimer),this.shared){this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner);for(const e of this.queued)this.shared.queued.delete(e)}this.queued.clear()}invalidate(e){const t=this.bind(e);clearTimeout(this.batchTimer),this.queued.clear(),t.queued.clear(),t.inFlight.clear(),t.retry.clear(),t.signed={}}stopTimer(){void 0!==this.resignTimer&&clearInterval(this.resignTimer),this.resignTimer=void 0}display(e,t){const i=Fn(t);if(!i.startsWith("/api/houseplan/content/"))return i;const n=this.bind(e);this.referenced.add(i),n.references.set(this.referenceOwner,new Set(this.referenced));const r=n.signed[i],o=r?this.now()-r.at:1/0;return o{const t=[...this.queued];this.queued.clear();for(const e of t)i.queued.delete(e);this.sign(e,t)},30))}sign(e,t){if(!t.length||!e?.callWS)return;const i=this.bind(e);for(const n of function(e,t){const i=Math.max(1,Math.floor(t)),n=[];for(let t=0;t{const n=i.inFlight.get(e);return!(void 0!==n&&t-n<15e3)&&(i.inFlight.set(e,t),!0)});r.length&&e.callWS({type:"houseplan/content/sign",paths:r}).then(e=>{const t=this.now();let n=0,o=!1;for(const s of r){const r=e?.urls?.[s];if("string"==typeof r&&r){const e=i.signed[s];e?.loaded&&e.url!==r?(e.pending={url:r,at:t},this.preloadReplacement(i,s,r,t)):(i.signed[s]={url:r,at:t,loaded:e?.url===r&&!!e.loaded},o=!0),i.retry.delete(s),n++}else this.backOff(i,s)}if(n&&(this.trimShared(i),o))for(const e of[...i.listeners])e()}).catch(()=>{for(const e of r)this.backOff(i,e)}).finally(()=>{for(const e of r)i.inFlight.get(e)===t&&i.inFlight.delete(e);for(const e of[...i.settlers])e()})}}preloadReplacement(e,t,i,n){const r=()=>{const r=e.signed[t];if(r?.pending?.url===i){e.signed[t]={url:i,at:n,loaded:!0},e.retry.delete(t),this.trimShared(e);for(const t of[...e.listeners])t()}},o=()=>{const n=e.signed[t];n?.pending?.url===i&&(delete n.pending,this.backOff(e,t))};if("undefined"==typeof Image)return void r();const s=new Image;s.onload=()=>{("function"==typeof s.decode?s.decode():Promise.resolve()).then(r).catch(o)},s.onerror=o,s.src=i}preloadCurrentImage(e,t,i){if(i.loaded)return Promise.resolve(!0);if(i.preload)return i.preload;if("undefined"==typeof Image)return i.loaded=!0,Promise.resolve(!0);const n=i.url;return i.preload=new Promise(r=>{const o=new Image;let s=!1;const a=o=>{if(s)return;s=!0,clearTimeout(l);const a=e.signed[t];if(a===i&&delete a.preload,o&&a===i&&a.url===n){a.loaded=!0;for(const t of[...e.listeners])t();r(!0)}else o||a!==i||this.backOff(e,t),r(!1)};o.onload=()=>{("function"==typeof o.decode?o.decode():Promise.resolve()).then(()=>a(!0)).catch(()=>a(!1))},o.onerror=()=>a(!1);const l=setTimeout(()=>a(!1),Zl);o.src=n}),i.preload}prepareImage(e,t){const i=Fn(t);if(!i.startsWith("/api/houseplan/content/"))return Promise.resolve(!0);const n=this.bind(e),r=()=>{const t=n.signed[i];if(t&&this.now()-t.atthis.now()&&!n.inFlight.has(i)&&!n.queued.has(i)?Promise.resolve(!1):null},o=r();return o?(s=o,new Promise(e=>{let t=!1;const i=i=>{t||(t=!0,clearTimeout(n),e(i))},n=setTimeout(()=>i(!1),Zl);s.then(i).catch(()=>i(!1))})):new Promise(e=>{let t=!1,i=null;const o=i=>{t||(t=!0,clearTimeout(a),n.settlers.delete(s),e(i))},s=()=>{t||i||(i=r(),i&&i.then(o).catch(()=>o(!1)))},a=setTimeout(()=>o(!1),Zl);n.settlers.add(s),s()});var s}backOff(e,t){const i=e.retry.get(t)?.delay||0,n=Math.min(6e4,i?2*i:2e3);e.retry.set(t,{notBefore:this.now()+n,delay:n})}trimShared(e){const t=Object.entries(e.signed);if(t.length<=512)return;const i=new Set(e.inFlight.keys());for(const t of e.references.values())for(const e of t)i.add(e);for(const[e,n]of t)(n.pending||n.preload)&&i.add(e);t.sort((e,t)=>t[1].at-e[1].at);const n=t.filter(([e])=>i.has(e));for(const e of t){if(n.length>=512)break;i.has(e[0])||n.push(e)}e.signed=Object.fromEntries(n)}resign(e,t){const i=this.bind(e);this.referenced=new Set(t),i.references.set(this.referenceOwner,new Set(this.referenced));const n=this.now(),r=new Set;for(const e of i.references.values())for(const t of e)r.add(t);const o={};for(const[e,t]of Object.entries(i.signed))r.has(e)&&n-t.at!!o[e]&&!o[e].pending))}markLoaded(e,t,i){const n=Fn(t);if(!n.startsWith("/api/houseplan/content/"))return;const r=this.bind(e).signed[n];if(r&&(!i||r.url===i)&&!r.loaded){r.loaded=!0;for(const t of[...this.bind(e).listeners])t()}}isReady(e,t){const i=Fn(t);if(!i.startsWith("/api/houseplan/content/"))return!0;const n=this.bind(e).signed[i];return!!n&&this.now()-n.ate.id===t)}var ac="M11,18H13V16H11V18M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,6A4,4 0 0,0 8,10H10A2,2 0 0,1 12,8A2,2 0 0,1 14,10C14,12 11,11.75 11,15H13C13,12.75 16,12.5 16,10A4,4 0 0,0 12,6Z";function lc(e,t,i){return[e[0]*t+e[1]*i+e[2],e[3]*t+e[4]*i+e[5]]}function cc(e,t){let i=0;for(const[n,r]of t){const t=lc(e,n[0],n[1]);i=Math.max(i,Math.hypot(t[0]-r[0],t[1]-r[1]))}return i}const hc=e=>{if(null==e||""===e)return null;const t=Number(e);return Number.isFinite(t)?t:null},dc=e=>{const t=e,i=hc(Array.isArray(t)?t[0]:t?.x),n=hc(Array.isArray(t)?t[1]:t?.y);return null==i||null==n?null:[i,n]};function uc(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=dc(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}if(t.length<3)return null;let i=0,n=0,r=0;for(let e=0;ee+t[0],0)/t.length,t.reduce((e,t)=>e+t[1],0)/t.length]:[n/(3*i),r/(3*i)]}function pc(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=dc(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}const i=uc(t);if(!i)return null;const n=t.map(e=>e[0]),r=t.map(e=>e[1]);return{centroid:i,bbox:[Math.min(...n),Math.min(...r),Math.max(...n),Math.max(...r)]}}function _c(e){let t=e;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;t=e.path??e.points??t}if(!Array.isArray(t)||!t.length)return[];let i=(t.some(e=>(e=>Array.isArray(e)?e.length>=2&&!Array.isArray(e[0])&&("object"!=typeof e[0]||null==e[0]):!!e&&"object"==typeof e&&("x"in e||"y"in e))(e))?[t]:t.filter(Array.isArray)).map(e=>e.map(dc).filter(e=>null!=e)).filter(e=>e.length>=2);i.length>64&&(i=i.slice(-64));const n=i.reduce((e,t)=>e+t.length,0);if(n<=4e3)return i.map(e=>e.slice());const r=4e3-2*i.length,o=i.map(e=>e.length-2),s=o.reduce((e,t)=>e+t,0),a=o.map(e=>r*e/s),l=a.map(Math.floor);let c=r-l.reduce((e,t)=>e+t,0);const h=a.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction||e.index-t.index);for(let e=0;efunction(e,t){if(t>=e.length)return e.slice();if(t<=2)return[e[0],e[e.length-1]];const i=[];for(let n=0;ne.slice()),i=t[t.length-1];return i?(i.length>2?i.pop():t.pop(),t):[]}const fc=e=>Number.isFinite(e[0])&&Number.isFinite(e[1]),vc=(e,t)=>e[0]===t[0]&&e[1]===t[1];function yc(e){if(!e)return null;const t=e.vacuum_position||e.robot_position||null,i=t&&null!=hc(t.x)&&null!=hc(t.y)?{x:hc(t.x),y:hc(t.y),a:hc(t.a??t.angle??t.theta)}:null,n=_c(e.path?.path??e.path?.points??e.path),r=[],o=e.rooms,s=Array.isArray(o)?o.map((e,t)=>[String(e?.id??t),e]):o&&"object"==typeof o?Object.entries(o):[];for(const[e,t]of s){if(!t||"object"!=typeof t)continue;const i=String(t.name??t.label??"").trim(),n=[[hc(t.cx),hc(t.cy)],[hc(t.center?.x),hc(t.center?.y)],[hc(t.x),hc(t.y)]].find(([e,t])=>null!=e&&null!=t);let o=n?.[0]??null,s=n?.[1]??null;const a=pc(t.outline),l=hc(t.x0),c=hc(t.y0),h=hc(t.x1),d=hc(t.y1),u=(null!=l&&null!=c&&null!=h&&null!=d?[Math.min(l,h),Math.min(c,d),Math.max(l,h),Math.max(c,d)]:null)||a?.bbox||null;if(null!=o&&null!=s||!a||([o,s]=a.centroid),null!=o&&null!=s||!u||(o=(u[0]+u[2])/2,s=(u[1]+u[3])/2),i&&null!=o&&null!=s){const t={id:e,name:i,cx:o,cy:s};u&&([t.x0,t.y0,t.x1,t.y1]=u),r.push(t)}}const a=function(e){return String(e.map_name??e.current_map??e.map_index??e.selected_map??"default")}(e);return i||r.length||n.length?{pos:i,path:n,rooms:r,mapId:a}:null}function bc(e,t,i){return![e,t,i].every(Number.isFinite)||e<0||t<=0||i<=0?Number.POSITIVE_INFINITY:e/t*i}const wc=40;function kc(e,t,i){if(!e||!t)return null;const n=t.attributes||{},r=e.split(".")[0]||"",o=null!=i?.platform?String(i.platform):null,s=!!dc(n.vacuum_position??n.robot_position),a=!(!n.rooms||"object"!=typeof n.rooms),l=_c(n.path?.path??n.path?.points??n.path).length>0,c=[n.map_name,n.current_map,n.map_index,n.selected_map].some(e=>null!=e),h="xiaomi_cloud_map_extractor"===o,d=a||l||c;let u=null;if(s?u="compatible":h?u="known_xcme_incomplete":d?u="partial":"camera"===r&&(u="camera"),!u)return null;const p=s?"camera"===r?300:200:h?100:d?50:0;return{entityId:e,name:String(n.friendly_name||e),platform:o,category:u,hasPosition:s,hasRooms:a,hasPath:l,hasMapId:c,score:p}}const xc=e=>e.toLowerCase().replace(/[\s_\-.,]+/g,"");function Sc(e,t){const i=new Set(t.map(xc).filter(Boolean)),n=new Set;for(const t of e){const e=xc(t.name||"");e&&i.has(e)&&n.add(e)}return n.size}function $c(e,t){const i=new Map(t.map(e=>[xc(e.name),e])),n=[],r=[];for(const t of e){const e=i.get(xc(t.name));e&&(n.push([[t.cx,t.cy],[e.cx,e.cy]]),r.push(t.name))}if(n.length<3)return null;const o=function(e){if(e.length<3)return null;let t=0,i=0,n=0,r=0,o=0,s=0,a=0,l=0,c=0,h=0,d=0,u=0;for(const[[p,_],[m,g]]of e){if(![p,_,m,g].every(Number.isFinite))return null;t+=p*p,i+=p*_,n+=p,r+=_*_,o+=_,s+=1,a+=p*m,l+=_*m,c+=m,h+=p*g,d+=_*g,u+=g}const p=[t,i,n,i,r,o,n,o,s],_=e=>{const[t,i,n,r,o,s,a,l,c]=p,h=t*(o*c-s*l)-i*(r*c-s*a)+n*(r*l-o*a);if(!Number.isFinite(h)||Math.abs(h)<1e-9)return null;const d=[(o*c-s*l)/h,(n*l-i*c)/h,(i*s-n*o)/h,(s*a-r*c)/h,(t*c-n*a)/h,(n*r-t*s)/h,(r*l-o*a)/h,(i*a-t*l)/h,(t*o-i*r)/h];return[d[0]*e[0]+d[1]*e[1]+d[2]*e[2],d[3]*e[0]+d[4]*e[1]+d[5]*e[2],d[6]*e[0]+d[7]*e[1]+d[8]*e[2]]},m=_([a,l,c]),g=_([h,d,u]);if(!m||!g)return null;const f=[m[0],m[1],m[2],g[0],g[1],g[2]];return f.every(Number.isFinite)?f:null}(n);return o?{matrix:o,matched:r,residual:cc(o,n)}:null}function Mc(e,t,i){const n=e[e.length-1];if(n&&n[0]===t[0]&&n[1]===t[1])return e;if(e.push(t),e.length<=600)return e;let r=function(e,t){if(e.length<3)return e.slice();const i=new Uint8Array(e.length);i[0]=i[e.length-1]=1;const n=[[0,e.length-1]];for(;n.length;){const[r,o]=n.pop(),[s,a]=e[r],[l,c]=e[o],h=l-s,d=c-a,u=Math.hypot(h,d)||1e-9;let p=0,_=-1;for(let t=r+1;tp&&(p=i,_=t)}_>0&&p>t&&(i[_]=1,n.push([r,_],[_,o]))}const r=[];for(let t=0;t600&&(r=r.filter((e,t)=>t%2==0||t===r.length-1)),r}function Rc(e){return"cleaning"===e||"returning"===e||"on"===e}const Cc={0:[1,0],90:[0,1],180:[-1,0],270:[0,-1]};function Tc(e){const[t,i]=Cc[e.rot]||[1,0],n=e.mir?-1:1;return[e.s*t*n,-e.s*i,e.ox,e.s*i*n,e.s*t,e.oy]}function Dc(e){const t=e[0]*e[4]-e[1]*e[3];if(!Number.isFinite(t)||Math.abs(t)<1e-12)return null;const i=t<0,n=Math.sqrt(Math.abs(t));let r=180*Math.atan2(-e[1],e[4])/Math.PI;return r=(90*Math.round(r/90)%360+360)%360,{ox:e[2],oy:e[5],s:n,rot:r,mir:i}}function Ac(e,t){const i=[],n=[];for(const t of e)null!=t.x0?(i.push(t.x0,t.x1),n.push(t.y0,t.y1)):(i.push(t.cx),n.push(t.cy));if(!i.length)return{ox:t[0]+t[2]/2,oy:t[1]+t[3]/2,s:t[2]/1e4,rot:0,mir:!0};const r=Math.min(...i),o=Math.max(...i),s=Math.min(...n),a=Math.max(...n),l=Math.max(o-r,a-s)||1,c={ox:0,oy:0,s:.6*Math.min(t[2],t[3])/l,rot:0,mir:!0},h=Tc(c),[d,u]=lc(h,(r+o)/2,(s+a)/2);return c.ox=t[0]+t[2]/2-d,c.oy=t[1]+t[3]/2-u,c}function Pc(e,t,i,n){const[r,o]=lc(Tc(t),i,n),s=Tc({...e,ox:0,oy:0}),[a,l]=lc(s,i,n);return{...e,ox:r-a,oy:o-l}}function Fc(e){const t=e?.trail_mode;return"never"===t||"cleaning"===t||"always"===t?t:!1===e?.trail?"never":"cleaning"}const zc=e=>"number"==typeof e&&Number.isFinite(e);function Ic(e){return Array.isArray(e)&&6===e.length&&e.every(zc)?[e[0],e[1],e[2],e[3],e[4],e[5]]:null}function Oc(e,t,i){return"legacy:"+e+" "+t+" "+i}function Ec(e,t,i,n){const r=t?.map_routes;if(Array.isArray(r))return r.filter(e=>e&&"string"==typeof e.id&&e.id).map(e=>({id:e.id,source:String(e.source??""),map_id:String(e.map_id??""),space:String(e.space??""),calibration:Ic(e.calibration)}));const o="string"==typeof t?.source&&t.source?t.source:n||"";if(!o)return[];const s=t?.calibration;if(!s||"object"!=typeof s)return[];const a=[];for(const t of Object.keys(s)){const n=Ic(s[t]);n&&a.push({id:Oc(e,o,t),source:o,map_id:t,space:i,calibration:n})}return a}const Nc=(e,t)=>e instanceof Map?e.get(t):e?.[t];function Hc(e){const t=[];let i=!1,n="",r="";for(const o of e.routes){const s=Nc(e.observed,o.source);void 0!==s&&(i=!0,n||(n=o.source,r=s),s===o.map_id&&t.push(o))}if(t.length>1)return{kind:"ambiguous",routeIds:t.map(e=>e.id).sort()};if(1===t.length){const i=t[0];if(e.spaceIds&&!e.spaceIds.has(i.space))return{kind:"missing_space",route:i};const n=Ic(i.calibration);return n?{kind:"ready",route:{...i,calibration:n}}:{kind:"needs_calibration",route:i}}if(i)return{kind:"unmapped",source:n,mapId:r};const o=e.observed instanceof Map?[...e.observed.entries()]:Object.entries(e.observed||{});if(o.length){const e=o.slice().sort((e,t)=>e[0].localeCompare(t[0]))[0];return{kind:"unmapped",source:e[0],mapId:e[1]}}return{kind:"none"}}function Lc(e,t,i){const n=new Set;for(const t of e)t.source&&n.add(t.source);for(const e of t)e&&n.add(e);const r={};for(const e of[...n].sort()){const t=i(e);void 0!==t&&(r[e]=t)}return r}function Bc(e,t,i){if(!e)return null;const n="string"==typeof e.route_id?e.route_id:"";if(n)return t.find(e=>e.id===n)||null;const r=function(e,t,i){if(!e||"string"!=typeof e.map_id)return{kind:"orphan_run"};const n=e.map_id,r="string"==typeof i?i:"";let o=t.filter(e=>e.map_id===n);return r&&(o=o.filter(e=>e.source===r)),1===o.length?{kind:"adopted",route:o[0]}:0===o.length?{kind:"orphan_run"}:{kind:"ambiguous_run",routeIds:o.map(e=>e.id).sort()}}(e,t,i);return"adopted"===r.kind?r.route:null}function qc(e){const t="ready"===e.resolution.kind?e.resolution.route:null,i=t&&t.space===e.renderSpace?Ic(t.calibration):null,n=Bc(e.serverCurrent,e.routes,e.rootSource),r=!!t&&!!n&&n.id===t.id,o=Bc(e.serverPrevious,e.routes,e.rootSource);return{live:i,currentRunMatches:r,previous:!!o&&o.space===e.renderSpace&&(e.explicitRoutes||!!t&&o.id===t.id)?Ic(o.calibration):null}}const jc={availability:"available",status:"alarm",activity:"none"},Wc=new Set(["motion","vibration","sound"]),Uc=new Set(["occupancy","presence"]),Vc=new Set(["door","window","garage_door","opening"]),Gc=new Set(["running","power"]),Kc=new Set(["smoke","gas","carbon_monoxide","moisture","safety","tamper","problem"]);const Yc=new Set(["running","working","washing","rinsing","spinning","drying","heating","cooling","cleaning","cooking","playing","recording","pumping","irrigating","humidifying","dehumidifying","fan","preheating","defrosting"]),Xc=new Set([...Yc,"start","started","run","active","in_progress","wash","rinse","spin","dry"]),Zc=new Set(["off","idle","paused","standby","docked","finished","complete","completed","stopped","ready","sleeping","stop","end","done","inactive"]),Jc=new Set(["heat","cool","heat_cool","auto","dry","fan_only"]),Qc=e=>""===e||"unknown"===e||"unavailable"===e||"__missing__"===e,eh=e=>String(e??"").trim().toLowerCase(),th=e=>eh(e).replace(/[\s-]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),ih=new Map([["run_state",0],["job_state",0],["operation_state",0],["activity_state",0],["machine_state",1],["running_state",1],["status",2],["device_status",2],["machine_status",2]]),nh=new Set(["wifi","connection","signal","battery"]);function rh(e,t){const i=e?.entities?.[t]||{};if("config"===i.entity_category)return null;const n=String(t||"").split(".").slice(1).join("."),r=[i.translation_key,i.original_name,i.name],o=[...r,n];r.some(e=>eh(e))||o.push(e?.states?.[t]?.attributes?.friendly_name);const s=o.map(th).filter(Boolean);if(s.some(e=>e.split("_").some(e=>nh.has(e))))return null;let a=null;for(const e of s)for(const[t,i]of ih)(e===t||e.endsWith(`_${t}`))&&(a=null==a?i:Math.min(a,i));return a}const oh=(e,t)=>null!=rh(e,t);function sh(e,t){if(!t.startsWith("switch."))return!1;const i=e?.entities?.[t]||{},n=e?.states?.[t],r=t.slice(7).toLowerCase();if(/(?:^|_)(?:main_)?power$/.test(r))return!0;if([i.translation_key,i.original_name,i.name].map(eh).some(e=>["power","main power","power switch","питание"].includes(e)))return!0;const o=eh(n?.attributes?.friendly_name);return/(?:^|[\s._-])(?:main[\s._-]+)?power$/.test(o)||/(?:^|[\s._-])питание$/.test(o)}function ah(e){for(const t of["hvac_action","action","current_operation","run_state","job_state","operation","activity"]){const i=eh(e?.[t]);if(Yc.has(i)||Zc.has(i))return i}return""}function lh(e,t){const i=e?.states?.[t],n=i?eh(i.state):"__missing__",r=String(t||"").split(".")[0],o=eh(i?.attributes?.device_class),s={eid:t,state:n,availability:Qc(n)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===s.availability)return s;if(function(e,t,i){return"alarm_control_panel"===e?"triggered"===i:"on"===i&&jn(e,t)}(r,o,n))return{...s,status:"alarm"};if("binary_sensor"===r)return Wc.has(o)?{...s,edge:"rising"}:Uc.has(o)?{...s,activity:"on"===n?"presence":"none"}:Vc.has(o)?{...s,status:"on"===n?"open":"neutral",edge:"rising"}:"moving"===o?{...s,activity:"on"===n?"transition":"none"}:Gc.has(o)&&"on"===n?{...s,status:"working",activity:"running"}:s;if("cover"===r)return{...s,activity:"opening"===n||"closing"===n?"transition":"none",edge:"terminal_transition"};if("lock"===r)return{...s,status:"unlocked"===n||"open"===n?"open":"neutral",activity:"locking"===n||"unlocking"===n?"transition":"none",edge:"terminal_transition"};if("valve"===r)return{...s,status:["open","opening","closing"].includes(n)?"open":"neutral",activity:"opening"===n||"closing"===n?"transition":"none",edge:"terminal_transition"};if("climate"===r){const e=ah(i.attributes),t=Array.isArray(i.attributes?.hvac_modes)?i.attributes.hvac_modes.map(eh):[],r=!Zc.has(n)&&(Jc.has(n)||Yc.has(n)||t.includes(n));return(e?Yc.has(e):r)?{...s,status:"working",activity:"running"}:s}if(["light","switch","fan","humidifier"].includes(r))return"on"===n?{...s,status:"working",activity:"running"}:s;if("media_player"===r)return"off"===n?{...s,availability:"unavailable"}:s;if("vacuum"===r)return"cleaning"===n?{...s,status:"working",activity:"running"}:"returning"===n?{...s,status:"working",activity:"transition"}:s;if("script"===r)return"on"===n?{...s,status:"working",activity:"running"}:s;if("automation"===r)return s;if("button"===r||"event"===r)return{...s,edge:"change"};const a=ah(i.attributes);return Yc.has(a)||Yc.has(n)&&!Zc.has(n)?{...s,status:"working",activity:"running"}:s}function ch(e,t,i){const n=i.filter(t=>t.startsWith("switch.")&&!e?.entities?.[t]?.entity_category),r=t.find(t=>sh(e,t));if(!(n.length>1&&!!r))return t.map(t=>lh(e,t));const o=t.find(t=>t!==r&&oh(e,t)),s=lh(e,r);return"unavailable"===s.availability||"off"===s.state?t.map(t=>({eid:t,state:e?.states?.[t]?eh(e.states[t].state):"__missing__",availability:"unavailable",status:"neutral",activity:"none",edge:"none"})):t.map(t=>{if(t===o)return function(e,t){const i=e?.states?.[t],n=i?eh(i.state):"__missing__",r={eid:t,state:n,availability:Qc(n)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===r.availability)return r;const o=ah(i?.attributes);return Yc.has(o)||Xc.has(n)&&!Zc.has(n)?{...r,status:"working",activity:"running"}:r}(e,t);return{...t===r?s:lh(e,t),status:"neutral",activity:"none",edge:"none"}})}function hh(e){if(!e.length)return{availability:"available",status:"neutral",activity:"none"};const t=e.filter(e=>"available"===e.availability);if(!t.length)return{availability:"unavailable",status:"neutral",activity:"none"};if(t.some(e=>"alarm"===e.status))return jc;const i=t.some(e=>"working"===e.status)?"working":t.some(e=>"open"===e.status)?"open":"neutral",n=t.some(e=>"transition"===e.activity)?"transition":t.some(e=>"presence"===e.activity)?"presence":t.some(e=>"running"===e.activity)?"running":"none";return{availability:"available",status:i,activity:n}}function dh(e,t){if(!(e=>!!e&&!Qc(e))(e)||"unavailable"===t.availability||e===t.state)return null;if("rising"===t.edge)return"off"===e&&"on"===t.state?"event":null;if("change"===t.edge)return"event";if("terminal_transition"===t.edge){const i=new Set([e,t.state]);if(i.has("closed")&&i.has("open")||i.has("locked")&&i.has("unlocked"))return"transition"}return null}const uh=(e,t=0)=>{const i=Number(e);return Number.isInteger(i)&&i>=0?i:t},ph=(e,t)=>{const i={rev:0,configRev:uh(t),off:new Set};if(null==e)return{snapshot:i,valid:!1};const n=e.off;return!Number.isInteger(e.rev)||Number(e.rev)<0||!Number.isInteger(e.config_rev)||Number(e.config_rev)<0||!Array.isArray(n)||n.some(e=>"string"!=typeof e||!e)?{snapshot:i,valid:!1}:{snapshot:{rev:Number(e.rev),configRev:Number(e.config_rev),off:new Set(n)},valid:!0}};function _h(e,t=0){return ph(e,t).snapshot}function mh(e,t,i,n){const r=ph(t,i);return n&&r.valid&&r.snapshot.configRev===i?e.configRev===i&&r.snapshot.rev{try{const[i,n]=await Promise.all([e.callWS({type:"config/device_registry/list"}),e.callWS({type:"config/entity_registry/list"})]),r=Rh(i,"id"),o=Rh(n,"entity_id");if(!r||!o)throw new Error("invalid_registry_response");t.devices=r,t.entities=o,t.authoritative=!0,t.access="full",t.lastSuccess=Date.now(),t.error=void 0}catch(e){t.authoritative=!1,t.access="limited",t.error=function(e){if(e&&"object"==typeof e){const t=e;return String(t.message||t.code||t.error||"registry_unavailable")}return String(e||"registry_unavailable")}(e)}finally{t.revision++,t.loading=void 0,function(e){for(const t of[...e.listeners])try{t()}catch{}}(t)}})()),t.loading}function Th(e,t){void 0===t.reloadTimer&&(t.reloadTimer=globalThis.setTimeout(()=>{t.reloadTimer=void 0,Ch(e,t)},80))}async function Dh(e,t){if(t.subscribing||t.unsubDevice&&t.unsubEntity)return t.subscribing;const i=e?.connection?.subscribeEvents;return"function"==typeof i?(t.subscribing=(async()=>{try{t.unsubDevice||(t.unsubDevice=await i.call(e.connection,()=>Th(e,t),"device_registry_updated")),t.unsubEntity||(t.unsubEntity=await i.call(e.connection,()=>Th(e,t),"entity_registry_updated"))}catch{}finally{0===t.refs&&(t.unsubDevice?.(),t.unsubEntity?.(),t.unsubDevice=void 0,t.unsubEntity=void 0),t.subscribing=void 0}})(),t.subscribing):void 0}function Ah(e,t){const i=Mh(e);if(!i)return()=>{};const n=0===i.refs;i.refs++,i.listeners.add(t),("pending"===i.access||n)&&Ch(e,i),Dh(e,i);let r=!1;return()=>{r||(r=!0,i.listeners.delete(t),i.refs=Math.max(0,i.refs-1),i.refs>0||(i.unsubDevice?.(),i.unsubEntity?.(),i.unsubDevice=void 0,i.unsubEntity=void 0,void 0!==i.reloadTimer&&globalThis.clearTimeout(i.reloadTimer),i.reloadTimer=void 0))}}function Ph(e){const t=Mh(e);t&&(Th(e,t),Dh(e,t))}function Fh(e){const t=Mh(e);if(!t)return{revision:0,authoritative:!1,access:"limited",devices:e?.devices||{},entities:e?.entities||{},lastSuccess:0,error:"registry_unavailable"};let i=e?.devices||{},n=e?.entities||{};if(t.authoritative){const r=t.liveDevices!==i||t.liveEntities!==n,o=void 0!==t.liveDevices||void 0!==t.liveEntities;if(r&&(t.liveDevices=i,t.liveEntities=n,t.projectedRevision=void 0,o&&Th(e,t)),t.projectedRevision!==t.revision||!t.projectedDevices||!t.projectedEntities){const e={...t.devices},r={...t.entities};for(const[t,n]of Object.entries(i))Object.prototype.hasOwnProperty.call(e,t)||(e[t]=n);for(const[e,t]of Object.entries(n))Object.prototype.hasOwnProperty.call(r,e)||(r[e]=t);t.projectedDevices=e,t.projectedEntities=r,t.projectedRevision=t.revision}i=t.projectedDevices,n=t.projectedEntities}return{revision:t.revision,authoritative:t.authoritative,access:t.access,devices:i,entities:n,lastSuccess:t.lastSuccess,error:t.error}}function zh(e){if(!e||"object"!=typeof e&&"function"!=typeof e)return 0;let t=kh.get(e);return t||(t=xh++,kh.set(e,t)),t}function Ih(e,t=Fh(e)){return[t.revision,t.access,zh(t.devices),zh(t.entities)].join(":")}function Oh(e){return!!e&&null==e.disabled_by}function Eh(e,t=Fh(e)){const i={},n={},r={};for(const[e,n]of Object.entries(t.devices||{}))Oh(n)&&(i[e]=n);for(const[e,i]of Object.entries(t.entities||{})){if(!Oh(i))continue;const r=i.device_id?t.devices?.[i.device_id]:null;t.authoritative&&i.device_id&&!r||(r&&!Oh(r)||(n[e]=i))}for(const[i,n]of Object.entries(e?.states||{})){const e=t.entities?.[i];if(e&&!Oh(e))continue;const o=e?.device_id?t.devices?.[e.device_id]:null;t.authoritative&&e?.device_id&&!o||(o&&!Oh(o)||(r[i]=n))}return{...e,devices:i,entities:n,states:r}}function Nh(e,t=Fh(e)){return{...e,devices:t.devices||{},entities:t.entities||{}}}function Hh(e,t){const i=[];for(const[n,r]of Object.entries(e||{}))r?.device_id===t&&i.push(n);return i}function Lh(){if($h)return $h;if("undefined"==typeof localStorage)return{};try{const e=JSON.parse(localStorage.getItem(Sh)||"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=Date.now(),i={};for(const[n,r]of Object.entries(e))!r||"active"!==r.kind&&"ha_disabled"!==r.kind||!Number.isFinite(r.ts)||t-r.ts>7776e6||(i[n]=r);return $h=i,$h}catch{return{}}}function Bh(e,t,i=Fh(e)){if(!t||"virtual"===t)return{kind:"active",enabledEntityIds:[],allEntityIds:[]};const n=t.indexOf(":");if(n<1)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const r=t.slice(0,n),o=t.slice(n+1);if("device"!==r&&"entity"!==r||!o)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const s=i.devices||{},a=i.entities||{};if(i.authoritative){if("device"===r){const e=s[o];if(!e)return{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[]};const t=Hh(a,o);if(!Oh(e))return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:t};const i=t.filter(e=>Oh(a[e]));return t.length&&!i.length?{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:t}:{kind:"active",enabledEntityIds:i,allEntityIds:t}}const t=a[o];return t&&!Oh(t)?{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!s[t.device_id]?{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!Oh(s[t.device_id])?{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]}:t||e?.states?.[o]?{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}:{kind:"orphaned",reason:"entity_missing",enabledEntityIds:[],allEntityIds:[]}}const l=function(e){return Lh()[e]||null}(t);if("device"===r){const t=s[o],i=Hh(a,o);if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:i};const n=i.filter(e=>{const t=a[e];return null==t?.disabled_by&&(!t.device_id||null==s[t.device_id]?.disabled_by)});if(i.length&&!n.length&&i.every(e=>null!=a[e]?.disabled_by))return{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:i};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"device",enabledEntityIds:[],allEntityIds:i};if(t||n.some(t=>!!e?.states?.[t]))return{kind:"active",enabledEntityIds:n,allEntityIds:i}}else{const t=a[o];if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]};if(t?.device_id&&null!=s[t.device_id]?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"entity",enabledEntityIds:[],allEntityIds:[o]};if(t||e?.states?.[o])return{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}}return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]}}function qh(e){const t=Fh(e);return{access:t.access,authoritative:t.authoritative,revision:t.revision,lastSuccess:t.lastSuccess,error:t.error}}function jh(e){const t={};for(const[i,n]of Object.entries(e.entities)){if(!n?.device_id||!Oh(n))continue;const r=e.devices?.[n.device_id];r&&!Oh(r)||(t[n.device_id]=t[n.device_id]||[]).push(i)}return t}function Wh(e,t){const i=new Map;for(const n of e){if(!0===n?.removed)continue;const e=n?.binding||"";if(!e.startsWith("entity:"))continue;const r=e.slice(7);if(!r)continue;const o=t?.entities?.[r]?.device_id;if(!o)continue;const s=i.get(o)||new Set;s.add(r),i.set(o,s)}return{byDevice:i}}function Uh(e,t,i,n){const r=n.byDevice.get(t);return r?.size?{partial:!0,entityIds:i.filter(t=>!r.has(t)&&!e?.entities?.[t]?.hidden)}:{partial:!1,entityIds:[...i]}}function Vh(e,t,i){if(t.identifiers?.[0]?.[0])return t.identifiers[0][0];for(const t of i){const i=e.entities[t]?.platform;if(i)return i}return""}function Gh(e,t){if(/_device_temperature$/.test(t))return!1;if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_temperature$/.test(t);const n=i.attributes||{};return"temperature"===n.device_class||/°C|°F/.test(n.unit_of_measurement||"")||/_temperature$/.test(t)}const Kh=["vacuum","lawn_mower","climate","media_player","light","cover","lock","valve","alarm_control_panel","water_heater","fan","humidifier","siren","camera","remote"],Yh=e=>[...e.filter(e=>!e.reg?.hidden),...e.filter(e=>!!e.reg?.hidden)];function Xh(e,t){const i=t.map(t=>({eid:t,reg:e?.entities?.[t]})).filter(e=>!!e.reg);if(!i.length)return[];const n=i.filter(e=>!e.reg.entity_category),r=n.length?n:i;for(const e of Kh){const t=r.filter(t=>t.eid.startsWith(e+"."));if(t.length)return Yh(t).map(e=>e.eid)}const o=r.filter(t=>function(e,t){if(!t.startsWith("binary_sensor."))return!1;const i=eh(e?.states?.[t]?.attributes?.device_class||e?.entities?.[t]?.device_class||e?.entities?.[t]?.original_device_class);return Wc.has(i)||Uc.has(i)||Vc.has(i)||Gc.has(i)||"moving"===i||Kc.has(i)}(e,t.eid));if(o.length)return Yh(o).map(e=>e.eid);const s=r.filter(e=>e.eid.startsWith("switch."));if(s.length){const t=Yh(s),n=t.find(t=>sh(e,t.eid));if(s.length>1&&n){const t=i.filter(t=>t.eid!==n.eid&&"config"!==t.reg?.entity_category&&null!=rh(e,t.eid)),r=t.filter(e=>!e.reg?.entity_category),o=r.length?r:t;for(const t of[0,1,2]){const i=Yh(o.filter(i=>rh(e,i.eid)===t));if(i.length)return[i[0].eid,n.eid]}}return[(n||t[0]).eid]}const a=[];for(const e of Le)a.push(...Yh(r.filter(t=>t.eid.startsWith(e+"."))));return a.push(...Yh(r.filter(e=>!Le.includes(e.eid.split(".")[0])))),a.map(e=>e.eid)}function Zh(e,t,i){const n=t.map(t=>({eid:t,reg:e.entities[t],st:e.states[t]})).filter(e=>e.reg),r=[n.filter(e=>!e.reg.hidden&&!e.reg.entity_category),n.filter(e=>!e.reg.entity_category),n.filter(e=>!e.reg.hidden),n];if("mdi:thermometer"===i||"mdi:air-filter"===i)for(const t of r){const i=t.find(t=>Gh(e,t.eid));if(i)return i.eid}const o=Xh(e,t);return o.find(Mn)||o[0]}function Jh(e,t,i=[]){return[...new Set(Qh(e,t,i))].filter(e=>Mn(e))}function Qh(e,t,i=[]){const n=e?.startsWith("entity:")?new Set([e.slice(7)]):new Set(i);return(t||[]).filter(e=>"string"==typeof e&&!n.has(e))}function ed(e,t){if("string"==typeof t)return e.area===t;const i=e.marker?.room_id;return i?!!t.id&&i===t.id:!!t.area&&e.area===t.area}function td(e){const t=e.marker?.binding?.startsWith("entity:")?e.marker.binding.slice(7):null,i=e.entities.filter(Mn),n=e.primary&&Mn(e.primary)?e.primary:null;return[...new Set([t,n,...i].filter(e=>!!e&&Mn(e)))]}function id(e){const t=td(e),i=e.marker?.light_entity;return i&&t.includes(i)?i:t[0]||null}function nd(e,t){if(!1===t.marker?.is_light)return[];if(!0===t.marker?.is_light){return[{eid:id(t),via:"forced"}]}const i=t.primary||Xh(e,t.entities)[0];return i&&!i.startsWith("light.")?[]:t.entities.filter(t=>t.startsWith("light.")&&!!e.states?.[t]).map(e=>({eid:e,via:"light"}))}const rd=new WeakMap,od=new WeakMap;function sd(e){return e.map(e=>[e.id||"",!0===e.hidden?1:0,e.primary||"",[...e.entities].join(","),void 0===e.controls?"":[...e.controls].join(","),e.marker?.id||"",e.marker?.binding||"",e.marker?.is_light,e.marker?.tap_action||"",!0===e.marker?.removed?1:0,e.marker?.light_entity||"",null==e.marker?.controls?"":[...e.marker.controls].join(",")].join("")).join("")}function ad(e){const t=sd(e),i=rd.get(e);if(i?.fingerprint===t)return i;const n=e.filter(e=>!e.hidden),r=new Map,o=new Map;for(const t of e){o.set(t,Qh(t.marker?.binding,t.marker?.controls??t.controls,t.entities));const e=t.hidden||!0!==t.marker?.is_light?null:t.marker?.id||t.id;e&&r.set(String(e),t)}const s=new Map;for(const t of e){const e=o.get(t)||[],i=new Set(void 0===t.controls?e.filter(Mn):t.controls.filter(Mn)),n=id(t),a=i.size?[...i]:n?[n]:[];for(const i of e){if(!i.startsWith("marker:"))continue;const e=i.slice(7);if(!e||e===String(t.marker?.id||t.id||""))continue;if(!r.has(e))continue;const n=s.get(e)||{markerId:e,controllers:[],driverEids:[]};n.controllers.push({device:t,driverEids:[...a]}),n.driverEids=[...new Set([...n.driverEids,...a])],s.set(e,n)}}const a={fingerprint:t,visible:n,markerById:r,persistedByDevice:o,incomingByMarker:s};return rd.set(e,a),a}function ld(e){return ad(e).incomingByMarker}function cd(e,t){const i=Jh(t.marker?.binding,t.controls??t.marker?.controls,t.entities),n=Qh(t.marker?.binding,t.marker?.controls??t.controls,t.entities);return(null!=t.marker?.is_light||!i.length&&!n.some(e=>e.startsWith("marker:")))&&nd(e,t).length>0}function hd(e,t){return nd(e,t).some(e=>!!e.eid)}function dd(e,t,i,n){const r="always"===e||"auto"===e&&t,o=r&&!i;return{sourceExists:r,fromSourceEnabled:r&&i,manualEnabled:r,radiusEnabled:r,passive:o,effectiveMode:o&&"auto"===n?"fixed":n}}function ud(e,t){const i=Jh(t.marker?.binding,t.controls??t.marker?.controls,t.entities).map(e=>({eid:e,via:"controls"})),n=cd(e,t)?nd(e,t):[];for(const e of n)e.eid&&i.some(t=>t.eid===e.eid)||i.push(e);return i}function pd(e,t,i,n){if(null!=i)return pd(e,t,null,n).filter(e=>ed(e.device,i));const r=sd(t),o=function(e,t){const i=new Set;for(const e of t){for(const t of e.entities)i.add(t);for(const t of e.controls||e.marker?.controls||[])"string"!=typeof t||t.startsWith("marker:")||i.add(t)}return[...i].sort().map(t=>`${t}:${e?.states?.[t]?.state??""}`).join("|")}(e,t),s=fh(n),a=od.get(t);if(a?.graphFingerprint===r&&a.stateFingerprint===o&&a.virtualLightFingerprint===s&&a.registry===e?.entities)return a.sources;const{visible:l,markerById:c,persistedByDevice:h,incomingByMarker:d}=ad(t),u=null==i?l:l.filter(e=>ed(e,i)),p=new Map,_=new Map;for(const t of u){const i=ud(e,t).filter(e=>"controls"!==e.via);for(const n of i){const i=!0===t.marker?.is_light?String(t.marker?.id||t.id||""):"",r=i?`marker:${i}`:`entity:${n.eid}`,o=n.eid?[n.eid]:[],s={key:r,eid:n.eid||"",stateEids:o,serviceEids:o,device:t,via:n.via,castsGlow:!0,passive:!n.eid,on:!n.eid||"on"===e.states?.[n.eid]?.state};p.set(t,[...p.get(t)||[],s]),n.eid&&_.set(n.eid,s)}}const m=new Map;for(const e of t){const t=h.get(e)||[],i=new Set(void 0===e.controls?t.filter(Mn):e.controls);m.set(e,i)}for(const t of p.values())for(const i of t){if(!i.passive)continue;const t=i.key.slice(7),r=d.get(t);i.on=!r||r.driverEids.some(t=>"on"===e.states?.[t]?.state),!r&&vh(i.device.marker)&&(i.on=yh(i.device.marker,n))}const g=new Map,f=e=>{const t=g.get(e.key);(!t||e.castsGlow&&!t.castsGlow)&&g.set(e.key,e)};for(const t of l){const n=h.get(t)||[],r=null==i||ed(t,i);for(const i of n){if(i.startsWith("marker:")){const e=c.get(i.slice(7)),t=e?p.get(e):null;if(t)for(const e of t)f(e);continue}if(!Mn(i)||!m.get(t)?.has(i))continue;const n=_.get(i);n?f(n):r&&f({key:`entity:${i}`,eid:i,stateEids:[i],serviceEids:[i],device:t,via:"controls",castsGlow:!1,passive:!1,on:"on"===e.states?.[i]?.state})}for(const e of p.get(t)||[])f(e)}const v=[...g.values()];return od.set(t,{graphFingerprint:r,stateFingerprint:o,virtualLightFingerprint:s,registry:e?.entities,sources:v}),v}function _d(e){const t=e.filter(e=>e.castsGlow);return t.find(e=>e.on)||t[0]||null}function md(e){return e.length?e.some(e=>e.on)?"on":"off":"none"}function gd(e,t){const i=[];for(const n of t){const t=e.states[n];if(!t)continue;const r=(t.attributes?.unit_of_measurement||"").toLowerCase();if(/_(linkquality|lqi)$/.test(n)||"lqi"===r){const e=parseFloat(t.state);isNaN(e)||i.push(e);continue}const o=t.attributes?.linkquality??t.attributes?.lqi;if(null!=o){const e=parseFloat(o);isNaN(e)||i.push(e)}}return Pi(i)}function fd(e,t){for(const i of t){if(!Gh(e,i))continue;const t=e.states[i];if(!t)continue;const n=parseFloat(t.state);if(!isNaN(n))return Math.round(10*n)/10}return null}function vd(e,t){for(const i of t){if(!i.startsWith("climate."))continue;const t=e.states[i];if(!t||"unavailable"===t.state||"unknown"===t.state)continue;const n=parseFloat(t.attributes?.current_temperature);if(Number.isFinite(n))return Math.round(10*n)/10}return null}function yd(e,t){if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_humidity$/.test(t);const n=i.attributes||{};return"humidity"===n.device_class||"%"===n.unit_of_measurement&&/_humidity$/.test(t)||/_humidity$/.test(t)}function bd(e,t){for(const i of t){if(!yd(e,i))continue;const t=e.states[i];if(!t)continue;const n=parseFloat(t.state);if(!isNaN(n))return Math.round(n)}return null}function wd(e,t){if(!t)return[];const i=[];for(const[t,n]of Object.entries(e.entities)){if(!t.startsWith("light.")||n.hidden||!Oh(n))continue;let r=null;if("group"===n.platform)r=n.area_id||null;else{if(!n.device_id)continue;{const t=e.devices[n.device_id];if(!Oh(t))continue;if("Group"!==t?.model)continue;r=t.area_id||n.area_id||null}}if(!r)continue;const o=e.states[t];i.push({eid:t,name:n.name||o?.attributes?.friendly_name||t,area:r})}return i}function kd(e,t,i,n,r){const o=He(t,i,r);if(o!==Ne)return o;const s=[];for(const t of n){const i=e.states[t]?.attributes?.device_class;i&&s.push(i)}return function(e){for(const t of e){const e=Ee[t];if(e)return e}return null}(s)??Ne}function xd(e,t){return e.map(e=>{if(!Array.isArray(e.controls))return e;const i=e.controls.filter(e=>!("string"==typeof e&&e.startsWith("marker:")&&t.has(e.slice(7))));return i.length===e.controls.length?e:{...e,controls:i.length?i:null}})}function Sd(e,t,i){if(!t||!i||t===i)return[...e];const n=`marker:${t}`,r=`marker:${i}`;return e.map(e=>{const t=Array.isArray(e.controls)?e.controls.map(e=>e===n?r:e):e.controls,i="derived_marker_state"===e.value_badge?.source?.kind&&e.value_badge.source.ref===n?{...e.value_badge,source:{...e.value_badge.source,ref:r}}:e.value_badge,o="derived_marker_state"===e.value_source?.kind&&e.value_source.ref===n?{...e.value_source,ref:r}:e.value_source;return t===e.controls&&i===e.value_badge&&o===e.value_source?e:{...e,controls:t,...void 0!==i?{value_badge:i}:{},...void 0!==o?{value_source:o}:{}}})}function $d(e,t,i){if(!t||t===i)return!0;const n=new Map;for(const t of e)n.set(t.id,(t.controls||[]).filter(e=>"string"==typeof e&&e.startsWith("marker:")).map(e=>e.slice(7)));const r=new Set,o=[i];for(;o.length;){const e=o.pop();if(e===t)return!0;r.has(e)||(r.add(e),o.push(...n.get(e)||[]))}return!1}function Md(e,t,i,n){const r=new Set([t]),o=e.filter(e=>{const o=e.id===t||!n&&e.binding===i;return o&&r.add(e.id),!o});return{markers:n?o:[...o,{id:t,binding:i,removed:!0,hidden:!0}],cleanupIds:r}}function Rd(e){const t=new Set,i=new Set,n=new Set;for(const r of e||[]){const e=String(r.binding||"").indexOf(":");if(e<1)continue;const o=r.binding.slice(0,e),s=r.binding.slice(e+1);s&&(!0===r?.removed?"device"===o?t.add(s):"entity"===o&&i.add(s):"entity"===o&&n.add(s))}return{devices:t,entities:i,liveEntities:n}}function Cd(e,t,i){if(i.liveEntities.has(t))return!1;if(i.entities.has(t))return!0;const n=e?.entities?.[t]?.device_id;return!!n&&i.devices.has(n)}function Td(e,t,i,n,r){const o=Jh(t.binding,t.controls,e.entities).filter(e=>!Cd(i,e,n)).filter(e=>"active"===Bh(i,"entity:"+e,r).kind);e.marker=t,e.controls=o,e.userHidden=!0===t.hidden,e.hidden=e.userHidden||"ha_disabled"===e.bindingStatus?.kind,t.name&&(e.name=t.name),t.icon&&(e.icon=t.icon),null!=t.model&&(e.model=t.model),e.link=t.link??null,e.description=t.description??null,e.pdfs=t.pdfs||[],e.tapAction=t.tap_action??null}function Dd(e){const t=e.hass,i=e.registry||Fh(t),n=Eh(t,i),r=Nh(t,i),{areaToSpace:o,markers:s,settings:a,excluded:l,iconRules:c}=e,h=!1!==a.group_lights,d=Rd(s),u=wd(n,h).filter(e=>!Cd(n,e.eid,d)),p=new Set(u.map(e=>e.area)),_=jh(n),m=Wh(s,r),g=new Set(s.map(e=>e.binding)),f=[];for(const e of Object.values(n.devices)){const r=e.area_id;if(!r||!o[r])continue;if("service"===e.entry_type)continue;if(g.has("device:"+e.id))continue;if("active"!==Bh(t,"device:"+e.id,i).kind)continue;const s=Uh(n,e.id,_[e.id]||[],m);if(s.partial&&!s.entityIds.length)continue;const a=s.entityIds,d=Vh(n,e,a);let u=l.has(d)||"Group"===e.model||/scene/i.test(e.model||"")||/bridge/i.test((e.model||"")+(e.name||""))||"myheat"===d&&!!e.via_device_id;if(!u&&h&&p.has(r)){const t=(e.name_by_user||e.name||"").trim();"mdi:lightbulb"===kd(n,t,e.model,a,c)&&(u=!0)}u&&f.push("device:"+e.id)}return f}function Ad(e,t,i,n){if("string"==typeof e.room_id&&e.room_id.length>0&&null===e.area)return{area:"",space:e.space||n};const r=e.area||t||"";return{area:r,space:r&&i[r]||e.space||n}}function Pd(e){const t=e.hass,i=e.registry||Fh(t),n=Eh(t,i),r=Nh(t,i),{areaToSpace:o,markers:s,settings:a,excluded:l,showAll:c,firstSpaceId:h,loc:d,iconRules:u}=e,p=!1!==a.group_lights,_=Rd(s),m=wd(n,p).filter(e=>!Cd(n,e.eid,_)),g=new Set(m.map(e=>e.area)),f=jh(n),v=function(e){const t={};for(const[i,n]of Object.entries(e.entities||{}))n?.device_id&&(t[n.device_id]=t[n.device_id]||[]).push(i);return t}(r),y=Wh(s,r),b=new Set;for(const e of s){const[t,i]=e.binding.split(":");"device"!==t&&"entity"!==t||!i||b.add(e.binding)}const w=(e,t)=>s.find(i=>i.binding===e+":"+t),k={},x=[];for(const e of Object.values(n.devices)){const r=e.area_id;if(!r||!o[r])continue;if("service"===e.entry_type)continue;if(b.has("device:"+e.id))continue;const s=Bh(t,"device:"+e.id,i);if("active"!==s.kind)continue;const h=w("device",e.id);if(h&&h.hidden&&!a.filter_seeded)continue;const _=Uh(n,e.id,f[e.id]||[],y);if(_.partial&&!_.entityIds.length)continue;const m=_.entityIds,v=_.partial?{kind:"active",enabledEntityIds:m,allEntityIds:m}:s,S=Vh(n,e,m),$=!a.filter_seeded;if($&&!c){if(l.has(S))continue;if("Group"===e.model)continue;if(/scene/i.test(e.model||""))continue;if(/bridge/i.test((e.model||"")+(e.name||"")))continue;if("myheat"===S&&e.via_device_id)continue}const M=(e.name_by_user||e.name||d("device.unnamed")).trim(),R=M+"|"+r;let C=kd(n,M,e.model,m,u);if(m.some(e=>e.startsWith("lock."))&&(C="mdi:lock"),$&&!c&&p&&"mdi:lightbulb"===C&&g.has(r))continue;k[R]=(k[R]||0)+1;const T=k[R]>1?M+" "+k[R]:M,D={id:e.id,name:T,model:e.model||"",area:r,space:o[r],icon:C,entities:m,allEntities:v.allEntityIds,bindingStatus:v,bindingKind:"device",bindingRef:e.id,pdfs:[]};D.primary=Zh(n,m,C),"mdi:thermometer"!==C&&"mdi:air-filter"!==C||(D.temp=fd(n,m)),D.primary&&yd(n,D.primary)&&(D.hum=bd(n,m)),x.push(D)}for(const e of m)o[e.area]&&(b.has("entity:"+e.eid)||x.push({id:"lg_"+e.eid,name:e.name,model:d("device.light_group"),area:e.area,space:o[e.area],icon:"mdi:lightbulb-group",entities:[e.eid],allEntities:[e.eid],bindingStatus:{kind:"active",enabledEntityIds:[e.eid],allEntityIds:[e.eid]},primary:e.eid,bindingKind:"entity",bindingRef:e.eid,pdfs:[]}));for(const e of s){if(e.removed)continue;const[s,l]=e.binding.split(":"),c="device"===s||"entity"===s?Bh(t,e.binding,i):null;if(!e.hidden||a.filter_seeded||"ha_disabled"===c?.kind)if("device"===s){const t=c;if("unverified"===t.kind)continue;const s=r.devices[l],{area:a,space:p}=Ad(e,s?.area_id,o,h),m="active"===t.kind?t.enabledEntityIds:[];let g=s?kd(n,s.name_by_user||s.name||"",s.model,m,u):"mdi:help-circle";m.some(e=>e.startsWith("lock."))&&(g="mdi:lock");const f={id:e.id,name:s?.name_by_user||s?.name||d("device.fallback"),model:s?.model||"",area:a,space:p,icon:g,entities:m,allEntities:t.allEntityIds.length?t.allEntityIds:s&&v[s.id]||[],bindingStatus:t,bindingKind:"device",bindingRef:l};f.primary=Zh(n,m,g),"mdi:thermometer"!==g&&"mdi:air-filter"!==g||(f.temp=fd(n,m)),f.primary&&yd(n,f.primary)&&(f.hum=bd(n,m)),Td(f,e,r,_,i),x.push(f)}else if("entity"===s){if(Cd(r,l,_))continue;const t=c;if("unverified"===t.kind)continue;const s=r.entities[l],a=s?.area_id||s?.device_id&&r.devices[s.device_id]?.area_id||"",{area:d,space:p}=Ad(e,a,o,h),m=n.states[l],g=s?.name||m?.attributes?.friendly_name||l;let f=kd(n,g,"",[l],u);l.startsWith("lock.")&&(f="mdi:lock");const v={id:e.id,name:g,model:"",area:d,space:p,icon:f,entities:"active"===t.kind?[l]:[],allEntities:[l],bindingStatus:t,primary:"active"===t.kind?l:void 0,bindingKind:"entity",bindingRef:l};"mdi:thermometer"!==f&&"mdi:air-filter"!==f||!v.entities.length||(v.temp=fd(n,v.entities)),v.entities.length&&yd(n,l)&&(v.hum=bd(n,v.entities)),Td(v,e,r,_,i),x.push(v)}else{const t=e.area||"",n=e.space||t&&o[t]||h,s={id:e.id,name:e.name||d("device.virtual"),model:e.model||"",area:t,space:n,icon:e.icon||"mdi:map-marker",entities:[],allEntities:[],bindingStatus:{kind:"active",enabledEntityIds:[],allEntityIds:[]},bindingKind:"virtual",virtual:!0};Td(s,e,r,_,i),x.push(s)}}return x}function Fd(e){const{marker:t,siblingMarkers:i=[],...n}=e;return Pd({...n,markers:[...i.filter(e=>e.id!==t.id),t]}).find(e=>e.id===t.id)||null}function zd(e,t,i,n){if(!t)return null;if(function(e,t,i){if(!t)return!1;const n=t.indexOf(":");if(n<1)return!1;const r=t.slice(0,n),o=t.slice(n+1),s=Rd(i);return"device"===r?s.devices.has(o):"entity"===r&&Cd(e,o,s)}(e,t,n))return null;const r=t.indexOf(":");if(r<0)return null;const o=t.slice(0,r),s=t.slice(r+1);if(!s)return null;if("entity"===o){const t=parseFloat(e.states[s]?.state);return Number.isFinite(t)?"temp"===i?Math.round(10*t)/10:Math.round(t):null}if("device"===o){const t=Object.entries(e.entities).filter(([,e])=>e.device_id===s).map(([e])=>e);return"temp"===i?fd(e,t):bd(e,t)}return null}const Id=new RegExp(["water","voda","coolant","flow_?temp","return_?temp","target","setpoint","chip","cpu","processor","board","core_temp","device_temp","batter","akkum","freezer","fridge","oven","kettle","boiler"].join("|"),"i");function Od(e,t){return t.area?t.area:e&&t.id?`@room/${encodeURIComponent(e)}/${encodeURIComponent(t.id)}`:null}function Ed(e){return null==e.area&&e.space&&e.room_id?Od(e.space,{id:e.room_id,area:null}):e.area||null}function Nd(e){const t=e?.exclude_integrations;return t?new Set(t):Pe}function Hd(e,t,i,n=Pe){const r=new Map;if(!e?.entities)return r;const o=Rd(i),s=new Set,a=new Map,l=new Map;for(const e of i||[]){if(e?.removed)continue;const t=(e.binding||"").indexOf(":");if(t<=0)continue;const i=e.binding.slice(0,t),n=e.binding.slice(t+1);if(!n)continue;!0===e.use_climate_temp&&s.add(n);const r=Ed(e);r&&("entity"!==i||a.has(n)?"device"!==i||l.has(n)||l.set(n,r):a.set(n,r))}const c=new Map;for(const[t,i]of Object.entries(e.entities)){if(i.device_id&&o.devices.has(i.device_id)&&!o.liveEntities.has(t)||!i.device_id&&o.entities.has(t)&&!o.liveEntities.has(t))continue;const r=i.device_id?e.devices?.[i.device_id]:null;if(!Oh(i)||r&&!Oh(r))continue;const h=a.get(t)||(i.device_id?l.get(i.device_id):null)||i.area_id||r?.area_id||null;if(!h)continue;if(i.entity_category)continue;if(!(s.size>0&&t.startsWith("climate.")&&(s.has(t)||i.device_id&&s.has(i.device_id)))){if(n.has(i.platform))continue;if(Id.test(t))continue}let d=c.get(h);d||(d=new Map,c.set(h,d));const u=i.device_id||t;let p=d.get(u);if(!p){const n=e.states?.[t];p={name:(r?r.name_by_user||r.name:i.name||n?.attributes?.friendly_name||t)||t,model:r?.model,ents:[]},d.set(u,p)}p.ents.push(t)}for(const[i,n]of c){const o=[],a=[];for(const[i,r]of n){const n=kd(e,r.name,r.model,r.ents,t),l="mdi:thermometer"===n||"mdi:air-filter"===n;if(l){const t=fd(e,r.ents);null!=t&&o.push(t)}if(s.size>0&&(s.has(i)||r.ents.some(e=>s.has(e)))){const t=vd(e,r.ents);null!=t&&o.push(t)}if(l||"mdi:water-percent"===n){const t=bd(e,r.ents);null!=t&&a.push(t)}}(o.length||a.length)&&r.set(i,{temp:o.length?Math.round(o.reduce((e,t)=>e+t,0)/o.length*10)/10:null,hum:a.length?Math.round(a.reduce((e,t)=>e+t,0)/a.length):null})}return r}function Ld(e,t,i){const n=[];for(const r of t){if(r.area!==i||r.virtual)continue;const t=gd(e,r.entities);null!=t&&n.push(t)}return Pi(n)}const Bd={offStates:["off"],unknownUsesToggle:!0},qd={light:Bd,switch:Bd,fan:Bd,humidifier:Bd,input_boolean:Bd,automation:Bd,remote:Bd,group:Bd,climate:{...Bd,featureMasks:{turn_on:256,turn_off:128,toggle:384}},media_player:{...Bd,featureMasks:{turn_on:128,turn_off:256,toggle:384}},siren:{...Bd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},vacuum:{...Bd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},water_heater:{...Bd,featureMasks:{turn_on:8,turn_off:8,toggle:8}},camera:{...Bd,featureMasks:{turn_on:1,turn_off:1,toggle:1}}};function jd(e){return e.slice(0,e.indexOf("."))}function Wd(e,t,i){if(!e?.services||"object"!=typeof e.services)return!1;const n=e.services?.[t];return!!n&&Object.prototype.hasOwnProperty.call(n,i)}function Ud(e,t,i){return Wd(e,t,i)?{domain:t,service:i}:Wd(e,"homeassistant",i)?{domain:"homeassistant",service:i}:null}function Vd(e,t){return e?.entities?.[t]||null}function Gd(e,t,i){const n=e?.states?.[i],r=Vd(t,i);return n?.attributes?.friendly_name||r?.name||r?.original_name||i}function Kd(e,t){const i=Vd(e,t);if(null!=i?.disabled_by)return!0;const n=i?.device_id?e?.devices?.[i.device_id]:null;return null!=n?.disabled_by}function Yd(e,t){const i=e?.attributes?.supported_features;if(null==i||""===i)return!1;const n=Number(i);return Number.isFinite(n)&&(n&t)===t}function Xd(e,t,i){const n=jd(i);if("lock"===n||"alarm_control_panel"===n)return!0;if("cover"!==n)return!1;const r=e?.states?.[i],o=Vd(t,i),s=String(r?.attributes?.device_class||o?.device_class||o?.original_device_class||"");return Bi.has(s)}function Zd(e,t,i,n,r){return{ref:i,entityId:n,name:n?Gd(e,t,n):null,reason:r}}function Jd(e,t,i,n,r,o=null){return{target:null,skipped:Zd(e,t,i,n,r),semantics:o,nextEffect:null,command:null}}function Qd(e,t,i,n,r=i){const o=jd(i);if("cover"!==o&&"valve"!==o)return function(e,t,i,n,r=i){const o=jd(i),s=e?.states?.[i];if(Kd(t,i))return Jd(e,t,r,i,"ha-disabled","power");if(Xd(e,t,i))return Jd(e,t,r,i,"secure");if(!s)return Jd(e,t,r,i,"missing","power");if("unavailable"===s.state)return Jd(e,t,r,i,"unavailable","power");const a=qd[o];if(!a)return Jd(e,t,r,i,"unsupported");let l,c;if("unknown"===s.state||""===s.state){if(!a.unknownUsesToggle)return Jd(e,t,r,i,"unsupported","power");l="toggle",c="toggle"}else a.offStates.includes(String(s.state))?(l="turn-on",c="turn_on"):(l="turn-off",c="turn_off");const h=a.featureMasks?.[c];if(h&&!Yd(s,h))return Jd(e,t,r,i,"unsupported","power");const d=Ud(e,o,c);return d?{target:{entityId:i,name:Gd(e,t,i),state:String(s.state||""),via:n},skipped:null,semantics:"power",nextEffect:l,command:{...d,data:{entity_id:i}}}:Jd(e,t,r,i,"unsupported","power")}(e,t,i,n,r);if(Kd(t,i))return Jd(e,t,r,i,"ha-disabled",o);if(Xd(e,t,i))return Jd(e,t,r,i,"secure",o);const s=e?.states?.[i];if(!s)return Jd(e,t,r,i,"missing",o);if("unavailable"===s.state)return Jd(e,t,r,i,"unavailable",o);const a=function(e,t,i){const n=String(i?.state||""),r="closed"===n?{service:`open_${t}`,effect:"open",feature:1}:"open"===n?{service:`close_${t}`,effect:"close",feature:2}:"opening"===n||"closing"===n?{service:`stop_${t}`,effect:"stop",feature:8}:null;return r&&Yd(i,r.feature)&&Wd(e,t,r.service)?r:Yd(i,3)&&Wd(e,t,"toggle")?{service:"toggle",effect:"toggle"}:null}(e,o,s);if(!a)return Jd(e,t,r,i,"unsupported",o);return{target:{entityId:i,name:Gd(e,t,i),state:String(s.state||""),via:n},skipped:null,semantics:o,nextEffect:a.effect,command:{domain:o,service:a.service,data:{entity_id:i}}}}function eu(e){return"entity"===e.bindingKind?e.bindingRef&&Mn(e.bindingRef)?[e.bindingRef]:[]:"virtual"===e.bindingKind?[]:td(e)}function tu(e){const t=e.marker?.toggle_entity;return t&&eu(e).includes(t)?t:null}function iu(e,t,i){const n=function(e,t){if("entity"===e.bindingKind&&e.bindingRef){const t=e.marker?.light_entity?id(e):null;return[...new Set([t,e.bindingRef].filter(e=>!!e))]}const i=e.entities.length?e.entities:e.allEntities||[],n=e.marker?.light_entity||e.primary&&Mn(e.primary)?id(e):null;return[...new Set([n,...Xh(t,i)].filter(e=>!!e))]}(i,t);if(!n.length)return null;const r="entity"===i.bindingKind?"binding":"device-role";if("binding"===r)return Qd(e,t,n[0],r);let o=null,s=null;for(const i of n){const n=Qd(e,t,i,r);if(n.command)return n;const a=n.skipped?.reason;if("missing"===a||"unavailable"===a||"secure"===a)return n;"ha-disabled"!==a?o||=n:s||=n}return o||s}function nu(e){const t=e.skipped?.reason;return"missing"===t?"unavailable":t||"unsupported"}function ru(e,t){return{origin:e,kind:"none",semantics:null,targets:[],skippedTargets:[],noneReason:t,nextEffect:null,command:null}}function ou(e,t){return"cover"===e||"toggle"===e?"toggle":"more-info"===e||"run"===e||"info"===e||"none"===e?e:(null==e||""===e)&&"light"===t?"toggle":"info"}function su(e,t){return{origin:e,kind:"single",semantics:t.semantics,targets:t.target?[t.target]:[],skippedTargets:t.skipped?[t.skipped]:[],noneReason:t.command?null:nu(t),nextEffect:t.nextEffect,command:t.command}}function au(e,t,i,n=[]){const r=new Map,o=[],s=new Set,a=e=>{const t=`${e.ref}\n${e.entityId||""}\n${e.reason}`;s.has(t)||(s.add(t),o.push(e))};for(const e of n)a(e);for(const n of i){const i=Qd(e,t,n.entityId,n.via,n.ref);i.target?r.set(n.entityId,r.get(n.entityId)||i.target):i.skipped&&a(i.skipped)}const l=[...r.values()];if(!l.length)return{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:o.length&&o.every(e=>"secure"===e.reason)?"secure":"configured-targets-missing",nextEffect:null,command:null};const c=l.some(e=>"on"===e.state)?"turn_off":"turn_on",h=Ud(e,"homeassistant",c);return h?{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:null,nextEffect:"turn_on"===c?"turn-on":"turn-off",command:{...h,data:{entity_id:l.map(e=>e.entityId)}}}:{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:[],skippedTargets:[...o,...l.map(i=>Zd(e,t,i.entityId,i.entityId,"unsupported"))],noneReason:"unsupported",nextEffect:null,command:null}}function lu(e){return String(e.marker?.id||e.id||"")}function cu(e){const{hass:t,device:i}=e,n=e.registryHass||t,r=function(e){return"toggle"===e.tapAction?"explicit-toggle":"cover"===e.tapAction?"legacy-cover":!e.tapAction&&e.primary?.startsWith("light.")?"default-light":null}(i);if(!r)return null;const o=i.marker;if("explicit-toggle"===r&&vh(o)){const t=String(o?.id||i.id||""),n=ld(e.devices).get(t);if(n)return function(e,t){const i=e.registryHass||e.hass;return au(e.hass,i,t.driverEids.map(e=>({entityId:e,via:"control-marker-driver",ref:`marker:${t.markerId}`})))}(e,n);const s=yh(o,e.virtualLights);return{origin:r,kind:"single",semantics:"power",targets:[{entityId:"",name:i.name,state:s?"on":"off",via:"virtual-light"}],skippedTargets:[],noneReason:null,nextEffect:s?"turn-off":"turn-on",command:null,operation:{kind:"virtual-light",markerId:o.id}}}if("explicit-toggle"===r){if(Qh(i.marker?.binding,i.marker?.controls??i.controls,i.entities).length)return function(e,t=null){const{hass:i,device:n,devices:r}=e,o=e.registryHass||i,s=Qh(n.marker?.binding,n.marker?.controls??n.controls,n.entities),a=e.lightSources||pd(i,r,null,e.virtualLights),l=new Map;for(const e of a){if(!e.key.startsWith("marker:"))continue;const t=l.get(e.key)||[];t.push(e),l.set(e.key,t)}const c=ld(r),h=new Map;for(const e of r){const t=String(e.marker?.id||e.id||"");t&&h.set(t,e)}const d=[],u=[];t&&d.push({entityId:t,via:"entity"===n.bindingKind?"binding":"device-role",ref:t});for(const e of s){if(!e.startsWith("marker:")){Mn(e)?d.push({entityId:e,via:"control-entity",ref:e}):u.push(Zd(i,o,e,e.includes(".")?e:null,"unsupported"));continue}const t=l.get(e)||[];if(!t.length){const t=h.get(e.slice(7));if("ha_disabled"===t?.bindingStatus?.kind){const n=t.bindingStatus.allEntityIds[0]||null;u.push({ref:e,entityId:n,name:t.name||(n?Gd(i,o,n):null),reason:"ha-disabled"})}else u.push(Zd(i,o,e,null,"missing"));continue}const r=[...new Set(t.flatMap(e=>e.serviceEids))];if(r.length){for(const t of r)d.push({entityId:t,via:"control-entity",ref:e});continue}const s=t.some(e=>e.passive),a=e.slice(7),p=lu(n),_=c.get(a)?.controllers.find(e=>lu(e.device)===p);if(s&&_?.driverEids.length)for(const t of _.driverEids)d.push({entityId:t,via:"control-marker-driver",ref:e});else u.push(Zd(i,o,e,null,s?"missing":"unsupported"))}return au(i,o,d,u)}(e,tu(i))}if("legacy-cover"===r){const e=i.entities.find(e=>e.startsWith("cover."))||i.allEntities?.find(e=>e.startsWith("cover."));return e?su(r,Qd(t,n,e,"device-role")):ru(r,"no-actionable-entity")}const s=tu(i),a=s?Qd(t,n,s,"entity"===i.bindingKind?"binding":"device-role"):iu(t,n,i);return a?su(r,a):ru(r,i.virtual||"virtual"===i.bindingKind?"no-actionable-entity":"no-binding")}function hu(e){if(!e)return[];const t=Array.isArray(e.data.entity_id)?e.data.entity_id:[e.data.entity_id];return[...new Set(t)].sort()}function du(e){return e?e.operation?e.operation:e.command?{kind:"ha-service",command:e.command}:null:null}const uu=new Set(["missing","ha-disabled","unavailable"]);function pu(e,t){const i=du(e),n=du(t);return!(!i||!n||i.kind!==n.kind)&&("virtual-light"===i.kind&&"virtual-light"===n.kind?i.markerId===n.markerId:"ha-service"===i.kind&&"ha-service"===n.kind&&function(e,t){const i=hu(e),n=hu(t);return i.length===n.length&&i.every((e,t)=>e===n[t])}(i.command,n.command))}function _u(e,t){const i=e.targets[0]||e.skippedTargets[0],n=[];return"group"===e.kind?e.targets.length&&n.push(t.group(e.targets)):i&&n.push(t.single(i)),e.nextEffect&&e.targets.length&&n.push("group"===e.kind?t.groupCurrentNext(e.targets,e.nextEffect):t.currentNext(e.targets[0],e.nextEffect)),e.skippedTargets.length&&n.push(t.skipped(e.skippedTargets)),!e.command&&e.noneReason&&n.push(t.none(e.noneReason)),n}const mu=e=>!!e&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function gu(e,t=5,i=5){return Ro(e.cm,t,i)/2}function fu(e,t,i=1,n=5,r=5,o=0){const s=e.host;if(!s||"partition"!==s.kind||"string"!=typeof s.id||!s.id)return{resolved:null,reason:"invalid-host"};const a=t.find(e=>e.id===s.id);if(!a)return{resolved:null,reason:"missing-partition"};if(!mu(a.a)||!mu(a.b)||!Number.isFinite(s.t)||s.t<0||s.t>1)return{resolved:null,reason:"invalid-position"};const l=a.b[0]-a.a[0],c=a.b[1]-a.a[1],h=Math.hypot(l,c),d=Number(e.length)*i;if(!(h>1e-9&&d>0&&Number.isFinite(d)))return{resolved:null,reason:"invalid-length"};const u=s.t*h;if(u-d/2h-o+1e-9)return{resolved:null,reason:"does-not-fit"};const p=l/h,_=c/h;let m=180*Math.atan2(c,l)/Math.PI;return m>=90?m-=180:m<-90&&(m+=180),{reason:null,resolved:{opening:e,host:s,partition:a,center:[a.a[0]+l*s.t,a.a[1]+c*s.t],angle:m,length:d,depth:Ro(a.cm,n,r),t:s.t,axis:{a:[a.a[0],a.a[1]],b:[a.b[0],a.b[1]],ux:p,uy:_,length:h}}}}function vu(e,t,i=1,n=5,r=5){return fu(e,t,i,n,r,0)}function yu(e,t,i=1,n=5,r=5){const o=e.host,s="partition"===o?.kind?t.find(e=>e.id===o.id):void 0;if(!s)return vu(e,t,i,n,r);const a=fu(e,t,i,n,r,gu(s,n,r));return"does-not-fit"===a.reason?{resolved:null,reason:"does-not-fit-jamb"}:a}function bu(e,t){return!e||(e.length!==t.length||e.host?.kind!==t.host?.kind||e.host?.id!==t.host?.id||e.host?.t!==t.host?.t)}function wu(e){const{center:t,length:i,axis:n,host:r}=e,o=i/2;return{hostId:r.id,a:[t[0]-n.ux*o,t[1]-n.uy*o],b:[t[0]+n.ux*o,t[1]+n.uy*o],depth:e.depth}}function ku(e,t=!1){const i=t?1:-1,n=e.depth/2;return{ox:-e.axis.uy*i*n,oy:e.axis.ux*i*n,cm:e.partition.cm,side:i}}function xu(e,t,i){return e.flatMap(e=>!mu(e.a)||!mu(e.b)||Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])<=1e-9?[]:[{roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`partition:${e.id}`,kind:"outer",cm:e.cm,open:!1,half:Ro(e.cm,t,i)/2,partitionHost:{kind:"partition",id:e.id}}])}function Su(e,t,i){const{center:n,length:r,axis:o}=e,s=r/2,a=t.flatMap(e=>{if(!e.kind||e.open)return[];const t=e.b[0]-e.a[0],r=e.b[1]-e.a[1],a=Math.hypot(t,r);if(!(a>i))return[];const l=t/a,c=r/a;if(Math.abs(o.ux*c-o.uy*l)>1e-6)return[];if(Math.abs((n[0]-e.a[0])*c-(n[1]-e.a[1])*l)>i)return[];const h=e=>(e[0]-n[0])*o.ux+(e[1]-n[1])*o.uy,d=h(e.a),u=h(e.b),p=Math.max(-s,Math.min(d,u)),_=Math.min(s,Math.max(d,u));return _>=p-i?[[p,_]]:[]});if(!a.length)return!1;a.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let l=-s;for(const[e,t]of a){if(e>l+i)return!1;if(l=Math.max(l,t),l>=s-i)return!0}return!1}function $u(e,t,i=1e-9){const n=e.length/(2*e.axis.length),r=e.t-n,o=e.t+n;return t.some(t=>{if(t.host.id!==e.host.id||t.opening.id===e.opening.id)return!1;const n=t.length/(2*t.axis.length);return Math.max(r,t.t-n)`}const yr={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},br=(e,t=1)=>{const i=Number(e);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):t},wr=e=>{let t=Number(e);return Number.isFinite(t)?(t=(t%360+360)%360,t>180?t-360:t):0};function kr(e,t,i){return wr(t)?[e.x,e.y]:i([e.x,e.y])}function xr(e,t,i,n){const r=Math.abs(i[0]-t[0]),o=Math.abs(i[1]-t[1]);return"line"===e?Math.hypot(r,o)>=n:r>=n&&o>=n}const Sr=(e,t,i)=>{const n=Number(e),r=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(n)&&n>0?n/r*i:0},$r=(e,t,i)=>{const n=Number(e),r=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(n)&&i>0?n/i*r:0},Mr=(e,t,i,n=yr.widthCm)=>{const r=Number(e?.width_cm);if(Number.isFinite(r)&&r>0)return r;const o=Number(e?.width);return Number.isFinite(o)&&o>0?$r(o,t,i):n};function Rr(e){const t=yr;return e.color===t.color&&e.opacity===t.opacity&&e.widthCm===t.widthCm&&e.fill===t.fill&&e.fillColor===t.fillColor&&e.fillOpacity===t.fillOpacity?null:{color:e.color,opacity:br(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),fill:!!e.fill,fill_color:e.fillColor,fill_opacity:br(e.fillOpacity,.25)}}function Cr(e,t){return{color:e.color,opacity:br(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),...t?{fill:e.fill,fill_color:e.fillColor,fill_opacity:br(e.fillOpacity,.25)}:{}}}function Tr(e){const t=e.x+e.w/2,i=e.y+e.h/2,n=wr(e.angle)*Math.PI/180,r=Math.cos(n),o=Math.sin(n),s=(e,n)=>{const s=e-t,a=n-i;return[t+s*r-a*o,i+s*o+a*r]};return[s(e.x,e.y),s(e.x+e.w,e.y),s(e.x+e.w,e.y+e.h),s(e.x,e.y+e.h)]}function Dr(e){const t=Tr(e),i=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],n=[(t[0][0]+t[2][0])/2,(t[0][1]+t[2][1])/2];return{points:[...t,i(t[0],t[1]),i(t[1],t[2]),i(t[2],t[3]),i(t[3],t[0]),n],segments:t.map((e,i)=>({a:e,b:t[(i+1)%4]}))}}function Ar(e,t,i,n,r,o,s,a){const l=wr(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),u=Math.cos(l),p=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:e.w/2,g=i>0?-e.h/2:e.h/2,f=p+m*c+g*d,v=_+m*h+g*u,y=n-f,b=r-v;let w=(y*c+b*h)*(t>0?1:-1),k=(y*d+b*u)*(i>0?1:-1),x=null;if(o){const t=w/Math.max(e.w,a),i=k/Math.max(e.h,a);x=Math.max(a/Math.max(e.w,a),a/Math.max(e.h,a),t,i),w=e.w*x,k=e.h*x}if(s>0)if(o){const t=Math.max(1,Math.round(e.w/s)),i=Math.max(1,Math.round(e.h/s));if(Math.abs(e.w-t*s)<1e-6&&Math.abs(e.h-i*s)<1e-6){const n=(e,t)=>{let i=Math.abs(e),n=Math.abs(t);for(;n;)[i,n]=[n,i%n];return Math.max(1,i)},r=1/n(t,i),o=Math.max(a/e.w,a/e.h),s=Math.max(o,Math.round((x??1)/r)*r);w=e.w*s,k=e.h*s}else{e.w>=e.h?(w=Math.round(w/s)*s,k=w*(e.h/Math.max(e.w,a))):(k=Math.round(k/s)*s,w=k*(e.w/Math.max(e.h,a)))}}else w=Math.round(w/s)*s,k=Math.round(k/s)*s;w=Math.max(a,w),k=Math.max(a,k);return{x:f+(t>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(t>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*u-k/2,w:w,h:k,angle:wr(e.angle)||void 0}}const Pr=(e,t,i)=>{const n=i[0]-t[0],r=i[1]-t[1],o=n*n+r*r;if(o<1e-12)return[...t];const s=Math.max(0,Math.min(1,((e[0]-t[0])*n+(e[1]-t[1])*r)/o));return[t[0]+n*s,t[1]+r*s]};function Fr(e,t,i,n){const r=n(e);let o=null;for(const r of t.points){const t=n(r),s=Math.hypot(t[0]-e[0],t[1]-e[1]);s<=i&&(!o||se.points),segments:e.flatMap(e=>e.segments)}}const Ir=Math.tan(.25*Math.PI/180);function Or(e,t){const i=Math.abs(Number(t[0])-Number(e[0])),n=Math.abs(Number(t[1])-Number(e[1]));if(!([i,n].every(Number.isFinite)&&i>0&&n>0))return null;const r=i>=n?"horizontal":"vertical",o=Math.max(i,n),s=Math.min(i,n);return s/o>Ir?null:{axis:r,major:o,minor:s,angleDegrees:180*Math.atan2(s,o)/Math.PI}}function Er(e,t){const i=Or(e,t);return i?"horizontal"===i.axis?[Number(t[0]),Number(e[1])]:[Number(e[0]),Number(t[1])]:[Number(t[0]),Number(t[1])]}const Nr=e=>`${e[0]},${e[1]}`,Hr=(e,t)=>e[0]===t[0]&&e[1]===t[1],Lr=(e,t)=>{const i=Nr(e),n=Nr(t);return i{let t=0;for(let i=0;i{if(e.length<3)return!1;for(let t=0;t1e-12},jr=(e,t)=>Hr(e,t.from)?[...t.to]:[...e],Wr=(e,t)=>e.map(e=>Array.isArray(e?.poly)?{...e,poly:e.poly.map(e=>jr(e,t))}:e),Ur=(e,t,i)=>{const n=e.flatMap((e,t)=>ei(e)?.some(e=>Hr(e,i.from))?[t]:[]);if(!n.length)return!1;for(const i of n){const n=ei(e[i]),r=ei(t[i]);if(!n||!r)continue;if(!qr(r))return!1;const o=Math.sign(Br(n)),s=Math.sign(Br(r));if(o&&s&&o!==s)return!1}const r=new Set;for(const e of n){const i=ei(t[e]);if(i)for(let n=0;n{let i=0;for(const n of e){const e=ei(n);if(e)for(let n=0;n{const{a:i,b:n,axis:r}=e,o="horizontal"===r?{from:n,to:[n[0],i[1]]}:{from:n,to:[i[0],n[1]]},s="horizontal"===r?{from:i,to:[i[0],n[1]]}:{from:i,to:[n[0],i[1]]};return[{move:o,preservedDegree:Vr(t,i)},{move:s,preservedDegree:Vr(t,n)}].sort((e,t)=>t.preservedDegree-e.preservedDegree||Nr(e.move.to).localeCompare(Nr(t.move.to))||Nr(e.move.from).localeCompare(Nr(t.move.from))).map(e=>e.move)};function Kr(e){const t=JSON.parse(JSON.stringify(e||{}));let i=Array.isArray(t.rooms)?t.rooms:[];const n=new Map;for(const e of i){const t=ei(e);if(t)for(let e=0;ee.key.localeCompare(t.key))){let t=null;for(const n of Gr(e,i)){const e=a.get(Nr(n.from));if(e&&e!==Nr(n.to))continue;const r=Wr(i,n);if(Ur(i,r,n)){t=n,i=r;break}}t?(a.set(Nr(t.from),Nr(t.to)),r++,s=Math.max(s,Math.hypot(t.to[0]-t.from[0],t.to[1]-t.from[1]))):o++}t.rooms=i;for(const e of t.partitions||[]){if(!Array.isArray(e?.a)||!Array.isArray(e?.b))continue;const i=Or(e.a,e.b);if(!i)continue;const n={key:String(e.id||Lr(e.a,e.b)),a:[...e.a],b:[...e.b],axis:i.axis};let a=null;for(const i of Gr(n,[{poly:[e.a,e.b]}])){const n=jr(e.a,i),r=jr(e.b,i),o=Math.hypot(r[0]-n[0],r[1]-n[1]);if(!(o>0))continue;const s=(t.openings||[]).filter(t=>"partition"===t?.host?.kind&&t.host.id===e.id).every(e=>{const t=Number(e.host.t),i=Number(e.length);return Number.isFinite(t)&&t>=0&&t<=1&&Number.isFinite(i)&&i>0&&t*o-i/2>=-1e-12&&t*o+i/2<=o+1e-12});if(s){a=i,e.a=n,e.b=r;break}}a?(r++,s=Math.max(s,Math.hypot(a.to[0]-a.from[0],a.to[1]-a.from[1]))):o++}return{space:t,report:{wallsStraightened:r,wallsStraightenSkipped:o,maxStraightenShift:s},changed:r>0}}const Yr=["rect","ellipse","furniture","image"],Xr=10**9,Zr=240,Jr=1e-4;function Qr(e){if(Array.isArray(e))return e.map(e=>Qr(e));if(null!==e&&"object"==typeof e){const t={};for(const[i,n]of Object.entries(e))t[i]=Qr(n);return t}return e}function eo(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=(e<0||Object.is(e,-0)?-1:1)*(Math.floor(Math.abs(e)*Xr+.5)/Xr);return 0===t?0:t}function to(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=e*Zr,i=Math.round(t);if(Math.abs(t-i)null!==no(e)):[]}function oo(e){return"string"==typeof e&&Yr.includes(e)}function so(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=eo(e[i]))}function ao(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=to(e[i]))}function lo(e){if(Array.isArray(e))for(let t=0;t{for(const r of n){const n=t[r];"number"==typeof n&&Number.isFinite(n)&&i(n,e)}},n=t=>{if(Array.isArray(t))for(let n=0;n{if(Array.isArray(e))for(const t of e)n(t)};for(const i of ro(e.rooms))t(i,["x","y","w","h"]),r(i.poly);for(const t of ro(e.walls))n(t.a),n(t.b);for(const t of ro(e.wall_segments))n(t.a),n(t.b);for(const i of ro(e.openings))t(i,["x","y"]);for(const i of ro(e.decor))"line"===i.kind?t(i,["x1","y1","x2","y2"]):oo(i.kind)?t(i,["x","y","w","h"]):"text"===i.kind&&t(i,["x","y"]);for(const t of ro(e.room_drafts))r(t.points);for(const t of ro(e.partitions))n(t.a),n(t.b);for(const t of ro(e.wall_columns))n(t.center);for(const t of ro(e.open_spans))n(t.a),n(t.b)}const r=no(t);if(!r)return;const o=new Map;if(n)for(const e of ro(n.spaces))null!=e.id&&o.set(String(e.id),e);for(const e of Object.values(r)){const t=no(e);if(!t)continue;const n=null!=t.s&&o.get(String(t.s))||null;for(const e of["x","y"]){const r=t[e];"number"==typeof r&&Number.isFinite(r)&&i(r,n)}}}function uo(e){const t=Number(e?.cell_cm);return t>0?t:5}function po(e,t={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},n=ro(no(e)?.spaces);let r=5;for(const e of n)r=Math.max(r,uo(e));ho(e,t,(e,t)=>{const n=e*Zr,o=Math.abs(n-Math.round(n)),s=to(e),a=o>0&&o=Jr))return;const l=a&&"number"==typeof s?Math.abs(s-e):0;if(a?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*Zr*(t?uo(t):r)),!t?.id||!a)return;const c=String(t.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(t.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*Zr*uo(t))}),i.bySpace.size&&ho(e,t,(e,t)=>{if(!t?.id)return;const n=i.bySpace.get(String(t.id));if(!n)return;const r=e*Zr;Math.abs(r-Math.round(r))>=Jr&&n.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...s}=i;return s}function _o(e){return function(e){const t=e,i=no(t);i&&ao(i,["x","y"]);return t}(Qr(e))}function mo(e){const t=e,i=no(t);if(!i)return t;for(const e of Object.values(i)){const t=no(e);t&&ao(t,["x","y"])}return t}function go(e){return fo(Qr(e))}function fo(e){const t=e,i=no(t);if(!i)return t;for(const e of ro(i.spaces)){so(e,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const t of ro(e.rooms))ao(t,["x","y","w","h"]),co(t.poly);for(const t of ro(e.walls))lo(t.a),lo(t.b);for(const t of ro(e.wall_segments))lo(t.a),lo(t.b);for(const t of ro(e.openings)){ao(t,["x","y"]),so(t,["angle","length"]);const e=no(t.host);e&&so(e,["t"])}for(const t of ro(e.decor))"line"===t.kind?ao(t,["x1","y1","x2","y2"]):oo(t.kind)?(ao(t,["x","y","w","h"]),so(t,["angle"])):"text"===t.kind&&(ao(t,["x","y"]),so(t,["scale","angle"]));for(const t of ro(e.room_drafts))co(t.points);for(const t of ro(e.partitions))lo(t.a),lo(t.b);for(const t of ro(e.wall_columns))lo(t.center),"square"===t.shape&&so(t,["angle"]);for(const t of ro(e.open_spans))lo(t.a),lo(t.b)}for(const e of ro(i.markers))so(e,["angle"]);return t}const vo=15,yo=8;function bo(e,t,i,n,r){const o=i[0]-e[0],s=i[1]-e[1],a=Math.hypot(o,s);if(!(a>0)||a<=r+1e-9)return null;const l=o/a,c=s/a,h=t=>{const n=(t[0]-e[0])*l+(t[1]-e[1])*c,o=(r-n)/(a-n);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[t[0]+(i[0]-t[0])*o,t[1]+(i[1]-t[1])*o]},d=h(t),u=h(n);return d&&u?[[e[0],e[1]],t,d,u,n]:null}const wo=Math.sin(.25*Math.PI/180);function ko(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<3}function xo(e){const t=Number(e)>0?Number(e):5;if(5===t)return 8;const i=5/t*8;return Math.min(80,Math.max(.5,i))}function So(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<2}function $o(e){return Number.isFinite(e)?Math.max(1,Math.min(100,e)):1}function Mo(e,t){return!Number.isFinite(e)||e<0?"":String(t?Math.round(e/2.54*100)/100:Math.round(100*e)/100)}function Ro(e,t,i){if(!Number.isFinite(e)||e<=0)return 0;const n=Number(t)>0?Number(t):5;return $o(e)/n*i}function Co(e,t){return t>0&&Number.isFinite(e)?Math.round(e/t)*t:e}function To(e){return Math.max(1e-6*Math.abs(e),1e-9)}function Do(e,t){if(!(t>0&&Number.isFinite(e)))return e;const i=Co(e,t);return Math.abs(i-e)<=To(t)?i:e}function Ao(e,t){let i=t[0]-e[0],n=t[1]-e[1];const r=Math.hypot(i,n);return r<1e-12?[1,0]:(i/=r,n/=r,(i<-1e-12||Math.abs(i)<=1e-12&&n<0)&&(i=-i,n=-n),[i,n])}function Po(e,t,i){const n=[Do(e[0],i),Do(e[1],i)],r=[Do(t[0],i),Do(t[1],i)],o=Co((n[0]+r[0])/2,i),s=Co((n[1]+r[1])/2,i),[a,l]=Ao(n,r);let c=Math.atan2(l,a);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${s.toFixed(d)}@${h.toFixed(4)}`}function Fo(e,t,i,n){return 1===n?Po(e,t,i):Po([e[0]/n,e[1]/n],[t[0]/n,t[1]/n],i)}function zo(e,t){if(!Array.isArray(e.a)||!Array.isArray(e.b)||e.a.length<2||e.b.length<2)return null;const i=[Number(e.a[0]),Number(e.a[1]),Number(e.b[0]),Number(e.b[1])];if(!i.every(Number.isFinite))return null;const n=t>0?t:1;return[[i[0]*n,i[1]*n],[i[2]*n,i[3]*n]]}function Io(e,t,i,n,r){const o=r>0?r:1;return{key:Fo(e,t,n,o),cm:$o(i),a:[e[0]/o,e[1]/o],b:[t[0]/o,t[1]/o]}}function Oo(e,t){const i=t>0?t:1,n=[];for(const t of e){const e=t.key.lastIndexOf("@");if(e<0)continue;const[r,o]=t.key.slice(0,e).split(",").map(Number),s=Number(t.key.slice(e+1));[r,o,s].every(Number.isFinite)&&n.push({w:t,x:r*i,y:o*i,ang:s})}return n}function Eo(e,t){const[i,n]=Ao(e,t);let r=Math.atan2(n,i);return r<0&&(r+=Math.PI),r}function No(e,t){let i=Math.abs(e-t);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Ho(e,t,i,n,r=1){if(!e?.length)return null;const o=Fo(t,i,n,r),s=e.find(e=>e.key===o);if(s)return s;const a=r>0?r:1,l=To(n)*a,c=(e,t)=>Math.abs(e[0]-t[0])<=l&&Math.abs(e[1]-t[1])<=l;for(const n of e){const e=zo(n,a);if(e&&(c(e[0],t)&&c(e[1],i)||c(e[0],i)&&c(e[1],t)))return n}const h=(t[0]+i[0])/2,d=(t[1]+i[1])/2,u=Eo(t,i),p=Math.max(.5*n,1e-9)*a;for(const t of Oo(e,a))if(No(t.ang,u)&&Math.hypot(t.x-h,t.y-d)<=p)return t.w;return null}function Lo(e,t,i,n,r=1){const o=Ho(e,t,i,n,r);if(o&&o.cm>0)return $o(o.cm);const s=function(e,t,i,n,r){if(!e?.length)return null;const o=r>0?r:1,s=Math.hypot(i[0]-t[0],i[1]-t[1]);if(s<1e-12)return null;const a=Eo(t,i),l=Math.max(.5*n,1e-9)*o;let c=null;for(const n of e){if(!(n.cm>0))continue;const e=zo(n,o);if(!e)continue;const r=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]);if(r<1e-12||!No(Eo(e[0],e[1]),a))continue;if(Ts(t[0],t[1],e[0][0],e[0][1],e[1][0],e[1][1])>l||Ts(i[0],i[1],e[0][0],e[0][1],e[1][0],e[1][1])>l)continue;if(r+l(o.has(e.key)||(e=>{const t=zo(e,n);if(!t)return!1;const[i,o]=t,a=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(a,c);if(h<=l)return!1;if(!s.some(e=>{const t=[e[0],e[1]],n=[e[2],e[3]];return No(Eo(i,o),Eo(t,n))&&Ts(i[0],i[1],t[0],t[1],n[0],n[1])<=l&&Ts(o[0],o[1],t[0],t[1],n[0],n[1])<=l}))return!1;const d=(r||[]).some(e=>{const t=[e[0],e[1]],n=[e[2],e[3]];if(!No(Eo(i,o),Eo(t,n)))return!1;const r=e=>Math.abs((e[0]-i[0])*c-(e[1]-i[1])*a)/h;if(r(t)>l||r(n)>l)return!1;const s=h*h,d=((t[0]-i[0])*a+(t[1]-i[1])*c)/s,u=((n[0]-i[0])*a+(n[1]-i[1])*c)/s;return Math.min(1,Math.max(d,u))-Math.max(0,Math.min(d,u))>l/h});return!d})(e))&&e.cm>=1&&e.cm<=100)}function qo(e,t,i,n=8){const[r,o]=Ao(e,t);let s=Math.atan2(o,r);s<0&&(s+=Math.PI);let a=i*Math.PI/180%Math.PI;a<0&&(a+=Math.PI);let l=Math.abs(s-a);return l>Math.PI/2&&(l=Math.PI-l),l<=n*Math.PI/180}function jo(e,t,i,n,r=1,o="affine",s){if(!e?.length)return[];if(t.length!==i.length)return"fixed-topology"===o&&s?.(),e.slice();const a=r>0?r:1,l=Math.max(.5*n,1e-9)*a,c=Math.max(n*a*1e-6,1e-9),h=[],d=new Map,u=new Map,p=(e,t,i)=>{const n=e.get(t)||new Set;n.add(i),e.set(t,n)};for(let e=0;e[e[0]+(t[0]-e[0])*i,e[1]+(t[1]-e[1])*i],m=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1])<=c,g=(e,t)=>{if("fixed-topology"===o){const i=t.na[0]-t.oa[0],n=t.na[1]-t.oa[1],r=t.nb[0]-t.ob[0],o=t.nb[1]-t.ob[1];return Math.hypot(i-r,n-o)<=c?[e[0]+i,e[1]+n]:m(e,t.oa)?[...t.na]:m(e,t.ob)?[...t.nb]:[...e]}const i=Math.max(0,Math.min(1,((e[0]-t.oa[0])*t.dx+(e[1]-t.oa[1])*t.dy)/t.len2));return _(t.na,t.nb,i)},f=(e,t)=>{const[i,n]=Ao(e,t);return(t[0]-e[0])*i+(t[1]-e[1])*n>=0?[[...e],[...t]]:[[...t],[...e]]},v=[],y=[],b=(e,t,i)=>{if(Math.hypot(t[0]-e[0],t[1]-e[1])<=c)return;const[r,o]=f(e,t),s=$o(i);if(y.some(e=>e.entry.cm===s&&m(e.span[0],r)&&m(e.span[1],o)))return;const l=Io(r,o,s,n,a);v.push(l),y.push({entry:l,span:[r,o]})};for(const t of e){const e=zo(t,a);if(e){const[i,n]=f(e[0],e[1]),r=n[0]-i[0],s=n[1]-i[1],a=r*r+s*s,d=Math.sqrt(a);if(d<=c){v.push({...t,cm:$o(t.cm)});continue}const u=[];for(const e of h){if(!No(Eo(i,n),Eo(e.oa,e.ob)))continue;const t=e=>Math.abs((e[0]-i[0])*s-(e[1]-i[1])*r)/d;if(t(e.oa)>l||t(e.ob)>l)continue;const o=((e.oa[0]-i[0])*r+(e.oa[1]-i[1])*s)/a,h=((e.ob[0]-i[0])*r+(e.ob[1]-i[1])*s)/a,p=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-p)*d>c&&u.push({lo:p,hi:_,move:e})}if(!u.length){"fixed-topology"===o?v.push({...t}):b(i,n,t.cm);continue}const p=[0,1,...u.flatMap(({lo:e,hi:t})=>[e,t])].sort((e,t)=>e-t).filter((e,t,i)=>0===t||Math.abs(e-i[t-1])*d>c),y=[];for(let e=0;e+1a>=e.lo-1e-12&&a<=e.hi+1e-12);if(!l.length){y.push([o,s]);continue}const h=[g(o,l[0].move),g(s,l[0].move)],f=l.slice(1).some(e=>{const t=g(o,e.move),i=g(s,e.move);return!m(h[0],t)||!m(h[1],i)});y.push(f?[o,s]:h)}const w=(e,t)=>{const i=e[1][0]-e[0][0],n=e[1][1]-e[0][1],r=t[1][0]-t[0][0],o=t[1][1]-t[0][1],s=Math.hypot(i,n);return!(s<=c||i*r+n*o<=0)&&Math.abs(i*o-n*r)/s<=c},k=[];for(const e of y){const t=k[k.length-1];t&&m(t[1],e[0])&&w(t,e)?t[1]=e[1]:k.push([[...e[0]],[...e[1]]])}if("fixed-topology"===o&&1===k.length){const[i,n]=k[0];if(m(i,e[0])&&m(n,e[1])||m(i,e[1])&&m(n,e[0])){v.push({...t});continue}}for(const[e,i]of k)b(e,i,t.cm);continue}if("fixed-topology"===o){const e=u.get(t.key);if(1===e?.size){const i=[...e][0];v.push(i===t.key?{...t}:{...t,key:i});continue}const i=[Oo([t],a)[0]];1!==a&&i.push(Oo([t],1)[0]);const n=i.filter(Boolean).some(e=>h.some(t=>{if(!No(e.ang,Eo(t.oa,t.ob)))return!1;const i=((e.x-t.oa[0])*t.dx+(e.y-t.oa[1])*t.dy)/t.len2;return i>=-1e-6&&i<=1.000001&&Ts(e.x,e.y,t.oa[0],t.oa[1],t.ob[0],t.ob[1])<=l}));((e?.size||0)>1||n)&&s?.(),v.push({...t});continue}let i="";const r=d.get(t.key);if(1===r?.size&&(i=[...r][0]),!i){const e=Oo([t],a)[0];if(e){const t=new Set;for(const i of h){if(!No(e.ang,Eo(i.oa,i.ob)))continue;const r=((e.x-i.oa[0])*i.dx+(e.y-i.oa[1])*i.dy)/i.len2;if(r<-1e-6||r>1.000001)continue;if(Ts(e.x,e.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([e.x,e.y],i),[s,c]=Ao(i.na,i.nb),h=Math.max(n*a,1e-6);t.add(Fo([o[0]-s*h,o[1]-c*h],[o[0]+s*h,o[1]+c*h],n,a))}1===t.size&&(i=[...t][0])}}v.push({...t,key:i||t.key,cm:$o(t.cm)})}return v}function Wo(e,t,i,n,r=1,o="affine"){return jo(e,t,i,n,r,o)}function Uo(e,t,i,n,r=1,o="fixed-topology"){let s=!1;const a=jo(e,t,i,n,r,o,()=>{s=!0});return{walls:s?(e||[]).map(e=>({...e})):a,rejected:s}}function Vo(e,t,i,n=1,r=[]){const o=n>0?n:1,s=Math.abs(i),a=Math.max(s*o*Jr,1e-9),l=(r||[]).flatMap(e=>{const t=zo(e,o);return t?t.map(e=>[...e]):[]}),c=e=>e.every((e,t)=>(e=>{if(!(s>0))return!0;const t=e/o/s;return Math.abs(t-Math.round(t))Math.abs(e-i[t])<=a)),h=[],d=e=>JSON.stringify([e.key,e.cm,e.a,e.b]);for(const i of e||[]){const e=zo(i,o);if(!e)continue;const[n,r]=e;if(![n[0],n[1],r[0],r[1]].every(Number.isFinite)||!c(n)||!c(r)){h.push(d(i));continue}const s=r[0]-n[0],l=r[1]-n[1],u=Math.hypot(s,l);if(u<=a){h.push(d(i));continue}const p=s/u,_=l/u,m=[];for(const e of t){const[t,i]=e;if(![t?.[0],t?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const r=e=>Math.abs((e[0]-n[0])*_-(e[1]-n[1])*p);if(r(t)>a||r(i)>a)continue;const o=(t[0]-n[0])*p+(t[1]-n[1])*_,s=(i[0]-n[0])*p+(i[1]-n[1])*_,l=Math.max(0,Math.min(o,s)),c=Math.min(u,Math.max(o,s));c-l>a&&m.push([l,c])}m.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let g=0;for(const[e,t]of m){if(e>g+a)break;if(g=Math.max(g,t),g>=u-a)break}ge.key!==s);return null==n||n<1?a:[...a,Io(t,i,n,r,o)]}function Ko(e,t,i,n,r,o=[],s=1){let a=e?e.slice():[];for(const e of function(e,t,i,n,r=1,o=[]){const s=ms(e,t,i,n,r,o);if(!s)return[];const a=[];for(let e=0;e0||(c=Go(c,t,i,n,r,s)))}return c}function Xo(e){const{a:t,b:i,halfDepth:n}=e;if(!Array.isArray(t)||!Array.isArray(i)||t.length<2||i.length<2||![t[0],t[1],i[0],i[1]].every(Number.isFinite))return null;const r=i[0]-t[0],o=i[1]-t[1],s=Math.hypot(r,o);if(!(s>1e-9&&n>0&&Number.isFinite(n)))return null;const a=-o/s*n,l=r/s*n;return[[t[0]+a,t[1]+l],[i[0]+a,i[1]+l],[i[0]-a,i[1]-l],[t[0]-a,t[1]-l]]}function Zo(e,t,i){return Math.hypot(e[0]-t[0],e[1]-t[1])<=i}function Jo(e,t,i){const n=t.b[0]-t.a[0],r=t.b[1]-t.a[1],o=n*n+r*r;if(!(o>i*i))return!1;const s=((e[0]-t.a[0])*n+(e[1]-t.a[1])*r)/o;if(!(s>0&&s<1))return!1;const a=[t.a[0]+n*s,t.a[1]+r*s];return Math.hypot(e[0]-a[0],e[1]-a[1])<=i}function Qo(e,t,i,n){const r=Math.hypot(t,i);if(!(r>1e-9&&n>0))return;const o=[t/r,i/r],s=e.find(e=>Math.abs(e.u[0]*o[1]-e.u[1]*o[0])<1e-9&&e.u[0]*o[0]+e.u[1]*o[1]>1-1e-9);s?s.halfDepth=Math.max(s.halfDepth,n):e.push({u:o,halfDepth:n})}function es(e,t){try{const i=jt(Ps(e),Ps(t));let n=null,r=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs(ss(t));t.length>=4&&i>r&&(r=i,n=t.slice(0,-1).map(e=>[e[0],e[1]]))}return n}catch{return null}}function ts(e,t=1e-6){const i=(e||[]).map((e,t)=>({segment:e,index:t})).filter(({segment:e})=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const n=Math.max(Number.isFinite(t)?t:0,1e-9),r=i.flatMap(({segment:e})=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of r)o.some(t=>Zo(t,e,n))||o.push(e);const s=[];for(const e of o){const t=[];let r=!1;for(const{segment:o,index:s}of i){const i=Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1]);Zo(e,o.a,n)?t.push({u:[(o.b[0]-o.a[0])/i,(o.b[1]-o.a[1])/i],halfDepth:o.halfDepth,length:i,index:s}):Zo(e,o.b,n)?t.push({u:[(o.a[0]-o.b[0])/i,(o.a[1]-o.b[1])/i],halfDepth:o.halfDepth,length:i,index:s}):Jo(e,o,n)&&(r=!0)}if(r||2!==t.length)continue;const[o,a]=t,l=o.u[0]*a.u[1]-o.u[1]*a.u[0];if(Math.abs(l)<1e-9)continue;const c=l<0?1:-1,h=[-o.u[1],o.u[0]],d=[-a.u[1],a.u[0]],u=[e[0]+h[0]*o.halfDepth*c,e[1]+h[1]*o.halfDepth*c],p=[e[0]-d[0]*a.halfDepth*c,e[1]-d[1]*a.halfDepth*c];if(!cs(u,o.u,p,a.u))continue;const _=[[o,a,p,[d[0]*-c,d[1]*-c]],[a,o,u,[h[0]*c,h[1]*c]]];for(const[t,,i,r]of _){const o=Math.min(2*t.halfDepth,t.length),a=[-t.u[1]*t.halfDepth,t.u[0]*t.halfDepth],l=[[e[0]+a[0],e[1]+a[1]],[e[0]+t.u[0]*o+a[0],e[1]+t.u[1]*o+a[1]],[e[0]+t.u[0]*o-a[0],e[1]+t.u[1]*o-a[1]],[e[0]-a[0],e[1]-a[1]]],c=e=>(e[0]-i[0])*r[0]+(e[1]-i[1])*r[1],h=[];for(let e=0;e=-1e-12&&h.push(t),n>1e-12&&r<-1e-12||n<-1e-12&&r>1e-12){const e=n/(n-r);h.push([t[0]+(i[0]-t[0])*e,t[1]+(i[1]-t[1])*e])}}h.length>=3&&Math.abs(ss(h))>n*n&&s.push({segmentIndex:t.index,wedge:h})}}return s}function is(e,t=1e-6){const i=(e||[]).filter(e=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const n=Math.max(Number.isFinite(t)?t:0,1e-9),r=i.flatMap(e=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of r)o.some(t=>Zo(t,e,n))||o.push(e);const s=[],a=i.map((e,t)=>({roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`join-${t}`,kind:"outer",cm:0,open:!1,half:e.halfDepth})),l=bs(a,n);for(const e of ws(l).fans)s.push(e);const c=e=>!!ks(l,e);for(const e of o){if(c(e))continue;const t=[];for(const r of i)Zo(e,r.a,n)?Qo(t,r.b[0]-r.a[0],r.b[1]-r.a[1],r.halfDepth):Zo(e,r.b,n)?Qo(t,r.a[0]-r.b[0],r.a[1]-r.b[1],r.halfDepth):Jo(e,r,n)&&(Qo(t,r.a[0]-e[0],r.a[1]-e[1],r.halfDepth),Qo(t,r.b[0]-e[0],r.b[1]-e[1],r.halfDepth));if(!(t.length<2)){t.sort((e,t)=>Math.atan2(e.u[1],e.u[0])-Math.atan2(t.u[1],t.u[0])||e.halfDepth-t.halfDepth);for(let i=0;in*n&&s.push(m)}}}return s}function ns(e,t,i,n){if(!(t>0)||!e||e.length<2)return"";if(i&&e.length>=3){let i=e;const r=e[e.length-1];if(e.length>=4&&Math.hypot(e[0][0]-r[0],e[0][1]-r[1])<1e-9&&(i=e.slice(0,-1)),i.length>=3){const e=i.map((e,i)=>n?.[i]||t),r=Js(i,e),o=us(i,e);if(r&&o)return`${ps(r)} ${ps(_s(o))}`}}const r=[];for(let i=0;i=1e-9&&a>0&&r.push({a:o,b:s,halfDepth:a})}const o=r.map(Xo);for(const{segmentIndex:e,wedge:t}of ts(r)){const i=o[e];if(!i)continue;const n=es(i,t);n&&(o[e]=n)}const s=[...o.filter(e=>!!e),...is(r)],a=function(e){let t=null;try{for(const i of e){if(i.length<3)continue;const e=Ps(i);t=t?Bt(t,e):[e]}return t}catch{return null}}(s);return a?Ws(a):s.map(e=>ps(e)).join(" ")}function rs(e,t,i,n,r=1){if(!i.length)return!1;const o=os(n,r),s=(e[0]+t[0])/2,a=(e[1]+t[1])/2,[l,c]=Ao(e,t);for(const e of i){const[t,i]=Ao([e[0],e[1]],[e[2],e[3]]);if(!(Math.abs(l*i-c*t)>.05)&&Ts(s,a,e[0],e[1],e[2],e[3])<=o)return!0}return!1}function os(e,t){return Math.max(e*(t>0?t:1)*.04,1e-9)}function ss(e){let t=0;for(let i=0;ie[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s+0)+o&&(i=!i)}return i}([c[0]+.001*a,c[1]+.001*l],e)||(a=-a,l=-l),[a,l]}function ls(e,t){const i=e[0]*t[1]-e[1]*t[0],n=e[0]*t[0]+e[1]*t[1];return Math.abs(i)<1e-9&&n>0}function cs(e,t,i,n){const r=t[0]*n[1]-t[1]*n[0];if(Math.abs(r)<1e-12)return null;const o=[i[0]-e[0],i[1]-e[1]],s=(o[0]*n[1]-o[1]*n[0])/r;return[e[0]+s*t[0],e[1]+s*t[1]]}function hs(e,t,i){const n=e?.length||0;if(n<3||!Array.isArray(i)||i.length!==n)return 0;const r=(Math.trunc(t)%n+n)%n,o=e[r],s=e[(r+1)%n],a=s[0]-o[0],l=s[1]-o[1],c=Math.hypot(a,l);if(!(c>0))return 0;const h=Math.max(0,Number(i[r])||0);if(!(h>0))return c;const d=[a/c,l/c],u=as(e,r),p=[o[0]+u[0]*h,o[1]+u[1]*h],_=t=>{const r=Math.max(0,Number(i[t])||0);if(!(r>0))return null;const s=e[t],a=e[(t+1)%n],l=a[0]-s[0],c=a[1]-s[1],h=Math.hypot(l,c);if(!(h>0))return null;const u=as(e,t),_=cs(p,d,[s[0]+u[0]*r,s[1]+u[1]*r],[l/h,c/h]);return _?(_[0]-o[0])*d[0]+(_[1]-o[1])*d[1]:null},m=_((r-1+n)%n)??0,g=(_((r+1)%n)??c)-m;return g>0?g:0}function ds(e,t,i,n,r,o,s,a=1){const l=(e||[]).find(e=>e?.id===t),c=ei(l);if(!c||c.length<3)return null;const h=Ss(e,t,i,n,r,o,s,a);if(!h)return c.map(()=>0);const d=4*os(r,a);return c.map((e,t)=>{const i=c[(t+1)%c.length],n=[(e[0]+i[0])/2,(e[1]+i[1])/2];for(let e=0;e!(e>0)))return e.map(e=>[e[0],e[1]]);const r=[];for(let o=0;o0||u>0)){r.push([e[o][0],e[o][1]]);continue}if(d>0!=u>0){const t=e[o],i=d>0?[t[0]+p*d,t[1]+_*d]:[t[0],t[1]],n=u>0?[t[0]+m*u,t[1]+g*u]:[t[0],t[1]];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}if(ls(w,k)){const t=e[o],i=[t[0]+p*d,t[1]+_*d],n=[t[0]+m*u,t[1]+g*u];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}const $=cs(x,w,S,k),M=Math.max(d,u,1e-9),R=ks(i,e[o])?.limit??4*M;if($){const i=Math.hypot($[0]-e[o][0],$[1]-e[o][1]);if(Number.isFinite(i)&&i<=R){r.push($);continue}if(Vs(e,t,o)){r.push($);continue}}d>0&&r.push([e[o][0]+p*d,e[o][1]+_*d]),u>0&&r.push([e[o][0]+m*u,e[o][1]+g*u]),d>0||u>0||r.push([e[o][0],e[o][1]])}return r.length>=3?r:null}function ps(e,t=!0){if(!e.length)return"";let i=`M ${e[0][0]} ${e[0][1]}`;for(let t=1;te?.id===t),a=ei(s);if(!a||a.length<3)return null;const l=os(n,r),c=[];for(const i of e||[]){if(!i||i.id===t)continue;const e=ei(i);if(e)for(const t of Rn(a,e,l))c.push([t[0],t[1]],[t[2],t[3]])}for(const e of i||[])c.push([e[0],e[1]],[e[2],e[3]]);for(const e of o||[]){const t=zo(e,r);t&&c.push(t[0],t[1])}const h=[],d=[];for(let e=0;el)continue;const s=((e[0]-t[0])*(i[0]-t[0])+(e[1]-t[1])*(i[1]-t[1]))/(n*n);s<=r||s>=1-r||(o.some(e=>Math.abs(e-s)*n<=2*l)||o.push(s))}o.sort((e,t)=>e-t);for(const n of o)h.push([t[0]+(i[0]-t[0])*n,t[1]+(i[1]-t[1])*n]),d.push(e)}return{poly:h,parent:d,orig:a}}function gs(e,t,i,n){const r=t.poly.length,o=new Array(r).fill(0);if(!e?.length)return o;const s=new Set,a=[];for(let l=0;l0?(o[l]=$o(c.cm),s.add(c.key)):a.push(l)}if(!a.length)return o;const l=n>0?n:1,c=Math.max(.5*i,1e-9)*l,h=Oo(e,l).filter(e=>e.w.cm>0);for(let e=a.length-1;e>=0;e--){const i=a[e],n=t.poly[i],s=t.poly[(i+1)%r],d=Eo(n,s);let u=null;for(const e of h){const t=zo(e.w,l);if(!t||!No(Eo(t[0],t[1]),d))continue;if(Ts(n[0],n[1],t[0][0],t[0][1],t[1][0],t[1][1])>c||Ts(s[0],s[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;const i=Math.hypot(s[0]-n[0],s[1]-n[1]),r=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]),o=Math.max(0,r-i);(!u||oc||Ts(r[0],r[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;i=!0,o=Math.max(0,Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1])-_)}else{if(Ts(e.x,e.y,n[0],n[1],r[0],r[1])>c)continue;o=Math.hypot(e.x-d,e.y-u)}(!p||i&&!p.exact||i===p.exact&&o0?i:1,o=(e||[]).filter(e=>e&&!e.open&&null!==e.kind&&Number.isFinite(e.half)&&e.half>0&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&[e.a[0],e.a[1],e.b[0],e.b[1]].every(Number.isFinite)&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>n).sort((e,t)=>e.key.localeCompare(t.key)||e.a[0]-t.a[0]||e.a[1]-t.a[1]||e.b[0]-t.b[0]||e.b[1]-t.b[1]||e.half-t.half),s=new Map;for(const e of o){const t=s.get(e.key);t?e.half>t.half&&s.set(e.key,{...t,half:e.half}):s.set(e.key,e)}const a=[...s.values()].flatMap(e=>[{point:[e.a[0],e.a[1]],other:e.b,halfDepth:e.half,kind:e.kind,key:e.key},{point:[e.b[0],e.b[1]],other:e.a,halfDepth:e.half,kind:e.kind,key:e.key}]).sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]||e.other[0]-t.other[0]||e.other[1]-t.other[1]||e.halfDepth-t.halfDepth),l=new Map;for(const e of a){const[t,i]=fs(e.point,n),r=vs(t,i),o=l.get(r)||[];o.push(e),l.set(r,o)}const c=[],h=new Map;for(const e of a){const t=ys(h,e.point,n).filter(t=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])<=n).sort((t,i)=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])-Math.hypot(i.point[0]-e.point[0],i.point[1]-e.point[1])||t.point[0]-i.point[0]||t.point[1]-i.point[1]);let i=t[0];if(!i){i={point:[...e.point],rays:[]},c.push(i);const[t,r]=fs(i.point,n),o=vs(t,r),s=h.get(o)||[];s.push(i),h.set(o,s)}const r=e.other[0]-e.point[0],o=e.other[1]-e.point[1],s=Math.hypot(r,o);if(!(s>n))continue;const a=[r/s,o/s];let l=Math.atan2(a[1],a[0]);l<0&&(l+=2*Math.PI),i.rays.push({u:a,halfDepth:e.halfDepth,length:s,angle:l})}const d=[],u=e=>{const t=1e-9*Math.max(1,r),i=e.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>n);return i.filter((e,n)=>!i.some((i,r)=>r!==n&&i.halfDepth>=e.halfDepth-t&&i.length>=e.length-t&&(i.halfDepth>e.halfDepth+t||i.length>e.length+t||re.length-t.length||e.halfDepth-t.halfDepth).map(e=>({...e}))};for(const e of c){const t=e.rays.sort((e,t)=>e.angle-t.angle||e.length-t.length||e.halfDepth-t.halfDepth),i=[];for(const e of t){const t=i[i.length-1];t&&Math.abs(e.angle-t.angle)<=1e-9?t.supports.push({halfDepth:e.halfDepth,length:e.length}):i.push({u:[...e.u],angle:e.angle,supports:[{halfDepth:e.halfDepth,length:e.length}]})}if(i.length>1&&2*Math.PI-i[i.length-1].angle+i[0].angle<=1e-9){const e=i.pop();i[0].supports.push(...e.supports)}if(i.length<3)continue;const r=i.map(t=>{const i=u(t.supports),r=new Set,o=[];for(const s of i){const i=[e.point[0]+t.u[0]*s.length,e.point[1]+t.u[1]*s.length];for(const t of ys(l,i,n)){if("shared"!==t.kind||Math.hypot(t.point[0]-i[0],t.point[1]-i[1])>n)continue;const s=t.other[0]-t.point[0],a=t.other[1]-t.point[1],l=Math.hypot(s,a);if(!(l>n))continue;const c=s/l,h=a/l;if(Math.hypot(t.other[0]-e.point[0],t.other[1]-e.point[1])<=n)continue;const d=`${t.key}|${t.point[0]}|${t.point[1]}|${t.other[0]}|${t.other[1]}|${t.halfDepth}`;r.has(d)||(r.add(d),o.push({start:[t.point[0],t.point[1]],u:[c,h],length:l,halfDepth:t.halfDepth}))}}return o.sort((e,t)=>e.start[0]-t.start[0]||e.start[1]-t.start[1]||e.u[0]-t.u[0]||e.u[1]-t.u[1]||e.length-t.length||e.halfDepth-t.halfDepth),{u:[...t.u],halfDepth:Math.max(...i.map(e=>e.halfDepth)),length:Math.max(...i.map(e=>e.length)),supports:i,continuations:o}}).filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>n);if(r.length<3)continue;const o=Math.max(...r.map(e=>e.halfDepth));o>0&&Number.isFinite(o)&&d.push({point:[...e.point],rays:r,halfDepth:o,limit:1.25*o})}d.sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]);const p=new Map;for(const e of d){const[t,i]=fs(e.point,n),r=vs(t,i),o=p.get(r)||[];o.push(e),p.set(r,o)}return{epsilon:n,coordinateScale:r,nodes:d,index:p}}function ws(e){const t={fans:[],supports:[]};if(!e?.nodes?.length)return t;const i=Math.max(e.epsilon,1e-9)**2;for(const n of e.nodes){const e=n.rays.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0).map(e=>({...e,thickLength:Math.max(...e.supports.filter(t=>t.halfDepth>=e.halfDepth-1e-12).map(e=>e.length),0),angle:(()=>{const t=Math.atan2(e.u[1],e.u[0]);return t<0?t+2*Math.PI:t})()})).sort((e,t)=>e.angle-t.angle);if(e.length<2)continue;const r=n.point;for(const i of e)for(const e of i.supports){if(!(e.halfDepth>0&&e.length>0))continue;const n=-i.u[1]*e.halfDepth,o=i.u[0]*e.halfDepth,s=[r[0]+i.u[0]*e.length,r[1]+i.u[1]*e.length];t.supports.push([[r[0]+n,r[1]+o],[s[0]+n,s[1]+o],[s[0]-n,s[1]-o],[r[0]-n,r[1]-o]])}for(let n=0;n{const e=s.angle-o.angle;return e>0?e:e+2*Math.PI})();if(a<1e-9)continue;const l=a>Math.PI+1e-9,c=4*Math.max(o.halfDepth,s.halfDepth),h=[r[0]-o.u[1]*o.halfDepth,r[1]+o.u[0]*o.halfDepth],d=[r[0]+s.u[1]*s.halfDepth,r[1]-s.u[0]*s.halfDepth],u=o.u[0]*s.u[1]-o.u[1]*s.u[0],p=e=>{let t=Math.atan2(e[1]-r[1],e[0]-r[0])-o.angle;for(;t<0;)t+=2*Math.PI;return t<=a+1e-9};let _=null;if(Math.abs(u)>1e-9){const e=((d[0]-h[0])*s.u[1]-(d[1]-h[1])*s.u[0])/u,t=((d[0]-h[0])*o.u[1]-(d[1]-h[1])*o.u[0])/u,i=[h[0]+o.u[0]*e,h[1]+o.u[1]*e];(l?e<=1e-9&&t<=1e-9:e>1e-9&&e<=o.thickLength&&t<=s.thickLength)&&Math.hypot(i[0]-r[0],i[1]-r[1])<=c&&p(i)&&(_=i)}const m=e=>{Math.abs(ss(e))>i&&t.fans.push(e)};if(_){const e=1.5*Math.max(o.halfDepth,s.halfDepth);m(bo([r[0],r[1]],h,_,d,e)??[[r[0],r[1]],h,_,d]);continue}if(l){m([[r[0],r[1]],h,d]);continue}const g=(e,t)=>Math.min(t,Math.sqrt(Math.max(c**2-e**2,0)),2*Math.max(o.halfDepth,s.halfDepth)),f=[h[0]+o.u[0]*g(o.halfDepth,o.thickLength),h[1]+o.u[1]*g(o.halfDepth,o.thickLength)],v=[d[0]+s.u[0]*g(s.halfDepth,s.thickLength),d[1]+s.u[1]*g(s.halfDepth,s.thickLength)];m([[r[0],r[1]],h,f,v,d])}}return t}function ks(e,t){return!e||!Array.isArray(t)||t.length<2||!t.slice(0,2).every(Number.isFinite)?null:ys(e.index,t,e.epsilon).filter(i=>Math.hypot(i.point[0]-t[0],i.point[1]-t[1])<=e.epsilon).sort((e,i)=>Math.hypot(e.point[0]-t[0],e.point[1]-t[1])-Math.hypot(i.point[0]-t[0],i.point[1]-t[1])||e.point[0]-i.point[0]||e.point[1]-i.point[1])[0]||null}function xs(e,t,i,n,r,o,s){return bs($s(e,t,i,n,r,o,s),4*os(n,s),s)}function Ss(e,t,i,n,r,o,s,a=1){const l=ms(e,t,n,r,a,i);if(!l)return null;const c=function(e,t,i){const n=(e||[]).find(e=>e?.id===t),r=ei(n);if(!r)return[];const o=[];for(const n of e||[]){if(!n||n.id===t)continue;const e=ei(n);if(e)for(const t of Rn(r,e,i))o.push(t)}return o}(e,t,os(r,a)),h=function(e,t,i,n,r){const o=os(n,r),s=[];for(let a=0;aTs(h,d,e[0],e[1],e[2],e[3])<=o);s.push(u?"shared":"outer")}return s}(l.poly,c,n,r,a),d=gs(i,l,r,a),u=d.map((e,t)=>h[t]&&e>0?Ro(e,o,s)/2:0);return{...l,kinds:h,cms:d,offsets:u}}function $s(e,t,i,n,r,o,s=1){const a=[];for(const l of e||[]){if(!l?.id)continue;const c=Ss(e,l.id,t,i,n,r,o,s);if(c)for(let e=0;e0&&(a=Go(a,e.a,e.b,e.cm,n,s));return a}function Rs(e,t,i,n,r,o,s=1){if(!t?.length)return[];const a=$s(e,t,i,n,r,o,s),l=new Map;for(const e of a){if(e.open||!e.kind||!e.roomId)continue;const t=l.get(e.key)||new Set;t.add(e.roomId),l.set(e.key,t)}const c=e=>{const t=[...l.get(e)||[]].sort();return 1!==t.length&&2!==t.length?`ambiguous:${e}`:`${1===t.length?"outer":"shared"}:${t.join("|")}`},h=[],d=new Set;for(const e of a)!e.open&&e.cm>0&&!d.has(e.key)&&(d.add(e.key),h.push({...e,ownerSignature:c(e.key)}));const u=[];for(const a of e||[]){if(!a?.id)continue;const l=Ss(e,a.id,t,i,n,r,o,s);if(l)for(let e=0;e0)||null===l.kinds[i]){e++;continue}const o=c(Fo(l.poly[i],l.poly[(i+1)%l.poly.length],n,s));let a=e;for(;a+10&&u.push({a:[d[0],d[1]],b:[p[0],p[1]],key:Fo(d,p,n,s),cm:r,len:_,ownerSignature:o}),e=a+1}}}u.sort((e,t)=>t.len-e.len||e.key.localeCompare(t.key));const p=[],_=new Set,m=new Set,g=4*os(n,s);for(const e of u){const t=h.filter(t=>!m.has(t.key)&&t.cm===e.cm&&t.ownerSignature===e.ownerSignature&&No(Eo(t.a,t.b),Eo(e.a,e.b))&&Ts(t.a[0],t.a[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g&&Ts(t.b[0],t.b[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g);if(t.length){for(const e of t)m.add(e.key);_.has(e.key)||(_.add(e.key),p.push(Io(e.a,e.b,e.cm,n,s)))}}for(const e of h)m.has(e.key)||_.has(e.key)||(_.add(e.key),p.push(Io(e.a,e.b,e.cm,n,s)));return p}function Cs(e,t,i,n,r,o,s,a=1){const l=os(r,a),c=(n[0]+n[2])/2,h=(n[1]+n[3])/2,d=Eo([n[0],n[1]],[n[2],n[3]]);let u=null;for(const n of $s(e,t,i,r,o,s,a)){if(!No(Eo(n.a,n.b),d))continue;const e=Ts(c,h,n.a[0],n.a[1],n.b[0],n.b[1]);e>4*l||(!u||e[e[0],e[1]]),o=Math.abs(ss(r));r.length>=3&&o>i&&(t=r,i=o)}return t}function As(e,t,i,n,r,o,s,a=1,l,c){const h=(e||[]).find(e=>e?.id===t),d=ei(h);if(!d||d.length<3)return null;if(!i?.length)return d.map(e=>[e[0],e[1]]);const u=Ss(e,t,i,n,r,o,s,a);if(!u||!u.offsets.some(e=>e>0))return d.map(e=>[e[0],e[1]]);const p=c||xs(e,i,n,r,o,s,a),_=us(u.poly,u.offsets,p);if(!_)return d.map(e=>[e[0],e[1]]);if(!p.nodes.length)return _;const m=void 0===l?Gs(e,i,n,[],r,o,s,a):null,g=l??("ok"===m?.status||"degraded-extra"===m?.status?m.roomGeom:void 0);if(g)try{const e=Ds(jt(Ps(u.poly),g));if(e)return e}catch{}return function(e,t){try{return Ds(qt(Ps(e),Ps(t)))}catch{return null}}(_,u.poly)||d.map(e=>[e[0],e[1]])}function Ps(e){const t=e.map(e=>[e[0],e[1]]);return t.push([e[0][0],e[0][1]]),[t]}function Fs(e){return!(!Array.isArray(e)||!e.length)&&e.every(e=>Array.isArray(e)&&e.length&&e.every(e=>Array.isArray(e)&&e.length>=4&&e.every(e=>Array.isArray(e)&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1])))&&Math.abs($i(e[0]))>1e-9)}function zs(e,t,i,n){const r=n?new Set(n):null;let o=null;for(let n=0;nt.epsilon))continue;const l=Hs([[e.point[0]+a[0]*n.halfDepth,e.point[1]+a[1]*n.halfDepth],[e.point[0]+s.u[0]*r+a[0]*n.halfDepth,e.point[1]+s.u[1]*r+a[1]*n.halfDepth],[e.point[0]+s.u[0]*r-a[0]*n.halfDepth,e.point[1]+s.u[1]*r-a[1]*n.halfDepth],[e.point[0]-a[0]*n.halfDepth,e.point[1]-a[1]*n.halfDepth]],t.coordinateScale);if(!l)continue;const c=Ps(l);o=o?Bt(o,c):c}}return o}function Is(e,t,i){let n=null;for(const r of e.rays)for(const e of r.continuations){const r=[-e.u[1],e.u[0]],o=[e.start[0]+e.u[0]*e.length,e.start[1]+e.u[1]*e.length],s=Hs([[e.start[0]+r[0]*e.halfDepth,e.start[1]+r[1]*e.halfDepth],[o[0]+r[0]*e.halfDepth,o[1]+r[1]*e.halfDepth],[o[0]-r[0]*e.halfDepth,o[1]-r[1]*e.halfDepth],[e.start[0]-r[0]*e.halfDepth,e.start[1]-r[1]*e.halfDepth]],t.coordinateScale);if(!s)continue;const a=qt(Ps(s),i);Array.isArray(a)&&0!==a.length&&(n=n?Bt(n,a):a)}return n}function Os(e,t,i=2*(4*e.halfDepth+2*t.epsilon)){const n=function(e,t=wo){const i=new Set,n=Number.isFinite(t)&&t>=0?t:wo;for(let t=0;te-t)}(e);return n.length?zs(e,t,i,n):null}function Es(e,t,i,n,r){const o=function(e){let t=null;for(const i of e){const e=Ps(i);try{t=t?Bt(t,e):e}catch{}}return t}(function(e,t,i=!1){if(!e)return[];const n=[];for(const r of e.nodes)for(let o=0;o1e-9)||h>=Math.PI-1e-9)continue;const d=[-s.u[1],s.u[0]],u=[-a.u[1],a.u[0]],p=[r.point[0]+d[0]*s.halfDepth,r.point[1]+d[1]*s.halfDepth],_=[r.point[0]-u[0]*a.halfDepth,r.point[1]-u[1]*a.halfDepth],m=cs(p,s.u,_,a.u);if(!m)continue;const g=Math.hypot(m[0]-r.point[0],m[1]-r.point[1]);if(!Number.isFinite(g)||g<=r.limit)continue;const f=t?Math.sqrt(Math.max(0,r.limit*r.limit-s.halfDepth*s.halfDepth)):0,v=t?Math.sqrt(Math.max(0,r.limit*r.limit-a.halfDepth*a.halfDepth)):0,y=Hs([[p[0]+s.u[0]*f,p[1]+s.u[1]*f],[_[0]+a.u[0]*v,_[1]+a.u[1]*v],m],e.coordinateScale);if(y&&n.push(y),i){const t=m[0]-r.point[0],i=m[1]-r.point[1],o=Math.hypot(t,i),s=g-r.limit;if(o>e.epsilon&&s>e.epsilon){const a=Math.min(Math.max(8*e.epsilon,.05*r.halfDepth),.25*s),l=t/o,c=i/o,h=-c,d=l,u=Hs([[m[0]-l*a+h*a,m[1]-c*a+d*a],[m[0]-l*a-h*a,m[1]-c*a-d*a],[m[0]+l*a,m[1]+c*a]],e.coordinateScale);u&&n.push(u)}}}return n}({...t,nodes:[e]},i,n));return o&&r?jt(o,r):o}function Ns(e,t,i,n){if(!e||!t.nodes.length)return e;let r=null;try{r=function(e){let t=null;for(const i of e.nodes){const n=Os(i,e);n&&(t=t?Bt(t,n):n)}return t}(t)}catch{return e}let o=e;for(const e of t.nodes){const s=4*e.halfDepth+2*t.epsilon,a=2*s,l=[[e.point[0]-s,e.point[1]-s],[e.point[0]+s,e.point[1]-s],[e.point[0]+s,e.point[1]+s],[e.point[0]-s,e.point[1]+s]];try{let s=o;const c=Es(e,t,!1,!0,r);c&&(s=jt(s,c));let h=zs(e,t,a);const d=Es(e,t,!0,!0,r);d&&(h=jt(h,d)),r&&(h=Bt(h,r));const u=.02*Math.min(...e.rays.map(e=>e.halfDepth));if(h=Bt(h,Ps([[e.point[0]-u,e.point[1]-u],[e.point[0]+u,e.point[1]-u],[e.point[0]+u,e.point[1]+u],[e.point[0]-u,e.point[1]+u]])),!h)continue;let p=qt(h,Ps(l));n?p=qt(p,n):i&&(p=qt(p,i));const _=Ps(l),m=jt(s,_),g=i?jt(qt(s,_),i):null,f=Is(e,t,_);o=Bt(m,...g?[g]:[],...f?[f]:[],p)}catch{}}if(r)try{let e=r;n?e=qt(e,n):i&&(e=qt(e,i)),o=Bt(o,e)}catch{}return o}function Hs(e,t=1){if(!Array.isArray(e)||e.length<3)return null;const i=Number.isFinite(t)&&t>0?t:1,n=1e-12*Math.max(1,i),r=[];for(const t of e){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),i=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(i))return null;const o=Math.round(e/n)*n,s=Math.round(i/n)*n;if(!Number.isFinite(o)||!Number.isFinite(s))return null;r.push([Object.is(o,-0)?0:o,Object.is(s,-0)?0:s])}return Math.abs(ss(r))>n*n?r:null}function Ls(e,t,i,n){if(Ts(e[0],e[1],t[0],t[1],i[0],i[1])>n)return!1;const r=i[0]-t[0],o=i[1]-t[1],s=(e[0]-t[0])*r+(e[1]-t[1])*o,a=r*r+o*o,l=n*Math.sqrt(a);return s>=-l&&s<=a+l}function Bs(e,t,i){const n=[],r=[];for(let o=0;oi*i))continue;const d=i/Math.sqrt(h),u=[0,1];for(const e of t)for(const t of[e.a,e.b]){if(!Ls(t,s,a,i))continue;const e=((t[0]-s[0])*l+(t[1]-s[1])*c)/h;e>d&&e<1-d&&u.push(e)}u.sort((e,t)=>e-t);const p=u.filter((e,t)=>0===t||Math.abs(e-u[t-1])>d);for(let e=0;e=3&&r.length===n.length?{poly:n,offsets:r}:null}function qs(e,t,i,n,r,o,s,a){const l=(e||[]).map(ei).filter(e=>!!e&&e.length>=3);if(!l.length)return null;let c=Bt(Ps(l[0]));for(let e=1;e"outer"===e.kind&&e.half>0),u=4*os(n,s),p=a||bs(h,u,s);let _=null;for(const e of function(e){const t=[];for(const i of Array.isArray(e)?e:[])if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,-1).map(e=>[e[0],e[1]]);i.length>=3&&t.push(i)}return t}(c)){const t=Bs(e,d,u);if(!t||!t.offsets.some(e=>e>0))continue;const i=Js(t.poly,t.offsets,p),n=us(t.poly,t.offsets,p);if(!i||!n)continue;const r=jt(Ps(i),Ps(n));_=_?Bt(_,r):r}return{centre:c,shell:_||[]}}function js(e,t,i,n,r,o,s=1){try{const a=qs(e,t,i,n,r,o,s,xs(e,t,i,n,r,o,s));if(!a)return[];return a.shell?.length?Bt(a.centre,a.shell):a.centre}catch{return null}}function Ws(e){if(!e)return"";let t="";for(const i of e)if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,e.length-1);i.length<3||(t+=(t?" ":"")+ps(i.map(e=>[e[0],e[1]])))}return t}const Us=15;function Vs(e,t,i){const n=e?.length||0;if(n<3||t?.length!==n)return!1;const r=e[(i-1+n)%n],o=e[i],s=e[(i+1)%n],a=[r[0]-o[0],r[1]-o[1]],l=[s[0]-o[0],s[1]-o[1]],c=Math.hypot(a[0],a[1]),h=Math.hypot(l[0],l[1]);if(!(c>1e-9&&h>1e-9))return!1;const d=Math.max(-1,Math.min(1,(a[0]*l[0]+a[1]*l[1])/(c*h))),u=Math.acos(d);if(!(u>1e-9))return!1;if(u>=Us*Math.PI/180)return!1;const p=Math.max(0,t[(i-1+n)%n]),_=Math.max(0,t[i]);if(!(p>0||_>0))return!1;const m=Math.sin(u);if(!(m>1e-12))return!1;const g=(_+p*d)/m,f=(p+_*d)/m;return Number.isFinite(g)&&Number.isFinite(f)&&g>0&&f>0&&ge>0))continue;for(const e of l.offsets)e>0&&(u=Math.max(u,2*e));const c=Js(l.poly,l.offsets,d),p=us(l.poly,l.offsets,d);c&&h.push({outset:c,inset:p})}for(const e of l){const t=e.map(e=>e[0]),i=e.map(e=>e[1]);if(t.length){const n=Math.min(Math.max(...t)-Math.min(...t),Math.max(...i)-Math.min(...i)),r=Math.min(...e.map((t,i)=>{const n=e[(i+1)%e.length];return Math.hypot(n[0]-t[0],n[1]-t[1])}));u=Math.max(u,e.length>16?n:r)}}const p=function(e,t,i,n,r,o,s,a){if(!t?.length||!i?.length)return[];const l=4*os(n,s),c=new Map;for(const a of $s(e,t,i,n,r,o,s))!a.open&&a.half>0&&!c.has(a.key)&&c.set(a.key,a);const h=[...c.values()];if(h.length<2)return[];const d=a||bs(h,l),u=[];for(const e of i)for(const t of[[e[0],e[1]],[e[2],e[3]]])u.some(e=>Math.hypot(e[0]-t[0],e[1]-t[1])<=l)||u.push(t);const p=[],_=(e,t)=>{let i=0,n=0;if(Math.hypot(e.a[0]-t[0],e.a[1]-t[1])<=l)i=e.b[0]-e.a[0],n=e.b[1]-e.a[1];else{if(!(Math.hypot(e.b[0]-t[0],e.b[1]-t[1])<=l))return null;i=e.a[0]-e.b[0],n=e.a[1]-e.b[1]}const r=Math.hypot(i,n);return r>l?[i/r,n/r]:null};for(const e of u){const t=h.map(t=>({iv:t,u:_(t,e)})).filter(e=>!!e.u);for(let i=0;i0?[e.slice(),u,m,_]:[e.slice(),_,m,u];else{if(!f)continue;{const t=[-r.u[1],r.u[0]],i=[-o.u[1],o.u[0]],n=s<0?1:-1,a=[e[0]+t[0]*r.iv.half*n,e[1]+t[1]*r.iv.half*n],l=[e[0]-i[0]*o.iv.half*n,e[1]-i[1]*o.iv.half*n];y=s>0?[e.slice(),a,l]:[e.slice(),l,a]}}Math.abs(ss(y))>l*l&&p.push(y)}}return p}(e,t,i,r,o,s,a,d),_=n.length?Qs(e,t,i,r,o,s,a):null;let m="exterior";try{const v=qs(e,t,i,r,o,s,a,d);m="paper";const y=v?v.shell?.length?Bt(v.centre,v.shell):v.centre:[],b=e=>{const t=Ps(e.outset);if(!e.inset)return t;const i=Ps(e.inset);return jt(t,i)};m="room-rings";let w=null;for(const e of h)try{const t=b(e);w=w?Bt(w,t):t}catch{}if(m="edge-bodies",v)for(const n of Xs(e,t,i,r,o,s,a))try{const e=qt(Ps(n.quad),v.centre);w=w?Bt(w,e):e}catch{}m="junctions",w=function(e,t,i=1,n=Bt){let r=e;for(const e of t||[]){const t=Hs(e,i);if(t)try{const e=Ps(t);r=r?n(r,e):e}catch{}}return r}(w,p,a),m="facade-clip",w&&v&&(w=qt(w,v.centre)),m="exterior-shell";const k=[];let x=0;if(v?.shell?.length)if(w)try{const e=Bt(w,v.shell);if(!Fs(e))throw new Error("invalid shell union");w=e}catch{if(!Fs(w)||!Fs(v.shell))throw new Error("invalid shell");k.push({id:"exterior-shell",geom:v.shell}),x++}else w=v.shell;if(m="multi-wall-trim",w&&d.nodes.length){const e=e=>e.rays.some(e=>e.supports.some(e=>e.length<2*e.halfDepth)),t=d.nodes.filter(e);if(t.length){w=Ns(w,{...d,nodes:t},v?.centre,y)}}if(m="junction-corners",d.nodes.length){const n=ws(d),l=function(e,t,i,n,r,o,s,a){try{const l=qs(e,t,i,n,r,o,s,{epsilon:a.epsilon,coordinateScale:a.coordinateScale,nodes:[],index:new Map});return l?l.shell?.length?Bt(l.centre,l.shell):l.centre:null}catch{return null}}(e,t,i,r,o,s,a,d);for(const e of n.fans)try{let t=[Ps(e)];if(l&&(t=qt(t,l)),!t?.length)continue;w=w?Bt(w,t):t}catch{}g=w,f=Math.max(d.epsilon,1e-9)**2,w=Array.isArray(g)?g.map(e=>{if(!Array.isArray(e)||!e.length)return e;const[t,...i]=e;return Math.abs(ss(t||[]))<=f?null:[t,...i.filter(e=>Math.abs(ss(e||[]))>f)]}).filter(e=>!!e):g}const S=w||[],$=[...Fs(S)?[{id:"room-primary",geom:S}]:[],...k.map((e,t)=>({id:`room-isolated-${t}`,geom:e.geom}))];m="openings";for(const e of n){if(!(e.length>0))continue;const t=ia(_,e,!0);if(!t.negative&&!t.positive)continue;const i=e.angle*Math.PI/180,n=Math.cos(i),o=Math.sin(i),s=-o,l=n,c=e.length/2,h=1.25*Math.max(u,r*a),d=[[e.x-n*c-s*h,e.y-o*c-l*h],[e.x+n*c-s*h,e.y+o*c-l*h],[e.x+n*c+s*h,e.y+o*c+l*h],[e.x-n*c+s*h,e.y-o*c+l*h]];w&&(w=jt(w,Ps(d)));for(const e of k)e.geom=jt(e.geom,Ps(d))}m="extras";const M=[];let R=0;const C=c.mergeExtra||((e,t)=>e?Bt(e,t):t);for(let e=0;ee.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]))||Math.abs($i(t))<=1e-9){R++;continue}const i=[Ps(t)];try{const t=C(w,i,e);if(!Fs(t))throw new Error("invalid extra union");w=t}catch{R++,Fs(i)&&M.push({id:`extra-${e}`,geom:i})}}M.push(...k),M.sort((e,t)=>Ws(e.geom).localeCompare(Ws(t.geom)));const T=w||[];return{status:R||x?"degraded-extra":"ok",geom:T,components:[...Fs(T)?[{id:"primary",geom:T}]:[],...M.map((e,t)=>({...e,id:`isolated-${t}`}))],roomGeom:S,roomComponents:$,paperGeom:y,depthUnits:u,openingPadUnits:1.25*Math.max(u,r*a),openingIndex:_,multiWallNodes:d,degradedExtraCount:R+x}}catch{return c.onCoreFailure?.(m),{status:"failed-core",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:u,openingIndex:null,multiWallNodes:d,degradedExtraCount:0}}var g,f}function Ks(e,t,i,n=[],r,o,s,a=1,l=[],c={}){if(!t?.length&&!l.length)return null;return Ys(Gs(e,t,i,n,r,o,s,a,l,c))}function Ys(e){if("failed-core"===e.status||"not-applicable"===e.status)return null;const t=e.components.map(e=>({id:e.id,d:Ws(e.geom),fillRule:"evenodd"})).filter(e=>!!e.d),i=t[0]?.d||"",n=Ws(e.paperGeom);if(t.length){const r={status:e.status,d:i,paths:t,components:e.components,roomGeom:e.roomGeom,multiWallNodes:e.multiWallNodes,paperD:n,depthUnits:e.depthUnits,fillRule:"evenodd"};return Object.defineProperties(r,{roomComponents:{value:e.roomComponents||[],enumerable:!1},openingIndex:{value:e.openingIndex,enumerable:!1},openingPadUnits:{value:e.openingPadUnits,enumerable:!1}}),r}return null}function Xs(e,t,i,n,r,o,s=1){if(!t?.length)return[];const a=new Set,l=[];for(const c of e||[]){if(!c?.id)continue;const h=Ss(e,c.id,t,i,n,r,o,s);if(!h)continue;const d=h.poly;for(let e=0;e0))continue;const p=Fo(t,i,n,s);if(a.has(p))continue;a.add(p);const _=Ro(u,r,o),[m,g]=as(d,e),f=-m,v=-g,y=_/2,b=[[t[0]+f*y,t[1]+v*y],[i[0]+f*y,i[1]+v*y],[i[0]+m*y,i[1]+g*y],[t[0]+m*y,t[1]+g*y]];l.push({key:p,kind:c,cm:u,quad:b,a:[t[0],t[1]],b:[i[0],i[1]],depthUnits:_})}}return l}function Zs(e,t=[]){let i=ps(e.quad);const[n,r]=Ao(e.a,e.b),o=n,s=r,a=-s,l=o;for(const n of t){if(!qo(e.a,e.b,n.angle))continue;if(Ts(n.x,n.y,e.a[0],e.a[1],e.b[0],e.b[1])>Math.max(.55*e.depthUnits,.001))continue;const t=n.length/2,r=e.depthUnits,c=n.x,h=n.y;i+=` ${ps(_s([[c-o*t-a*r,h-s*t-l*r],[c+o*t-a*r,h+s*t-l*r],[c+o*t+a*r,h+s*t+l*r],[c-o*t+a*r,h-s*t+l*r]]))}`}return i}function Js(e,t,i){const n=e?.length||0;if(n<3||t.length!==n)return null;if(t.every(e=>!(e>0)))return e.map(e=>[e[0],e[1]]);_s(e),t.slice().reverse();const r=[];for(let o=0;o0||l>0)){r.push([e[o][0],e[o][1]]);continue}if(a>0!=l>0){const t=e[o],i=a>0?[t[0]-c*a,t[1]-h*a]:[t[0],t[1]],n=l>0?[t[0]-d*l,t[1]-u*l]:[t[0],t[1]];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}if(ls(w,k)){const t=e[o],i=[t[0]-c*a,t[1]-h*a],n=[t[0]-d*l,t[1]-u*l];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}const $=cs(x,w,S,k),M=Math.max(a,l,1e-9),R=ks(i,e[o])?.limit??4*M;if($){const i=Math.hypot($[0]-e[o][0],$[1]-e[o][1]);if(Number.isFinite(i)&&i<=R){r.push($);continue}if(Vs(e,t,o)){r.push([e[o][0],e[o][1]]);continue}}a>0&&r.push([e[o][0]-c*a,e[o][1]-h*a]),l>0&&r.push([e[o][0]-d*l,e[o][1]-u*l])}return r.length>=3?r:null}function Qs(e,t,i,n,r,o,s=1){const a=[];for(const l of e||[]){if(!l?.id)continue;const c=Ss(e,l.id,t,i,n,r,o,s);if(!c)continue;const h=Math.abs($i(c.poly));for(let e=0;e[Math.max(t,e.x0),Math.min(i,e.x1)]).filter(e=>e[1]-e[0]>n).sort((e,t)=>e[0]-t[0]||e[1]-t[1]);if(!r.length)return{coverage:0,full:!1};let o=r[0][0],s=r[0][1],a=0,l=o<=t+n;for(let e=1;e=i-n,{coverage:a,full:l}}function ta(e,t){return Number(t.full)-Number(e.full)||e.faceDistance-t.faceDistance||e.area-t.area||e.roomId.localeCompare(t.roomId)}function ia(e,t,i=!1){const n=Number(t?.x),r=Number(t?.y),o=Number(t?.angle),s=Number(t?.length);if(!([n,r,o,s].every(Number.isFinite)&&s>0))return{negative:null,positive:null};const a=o*Math.PI/180,l=Math.cos(a),c=Math.sin(a),h=-c,d=l,u=s/2,p=Math.max(1e-9,e.adjacencyEps),_=new Map;let m=0;for(const t of e.edges){if(i&&!(t.half>0))continue;if(!qo(t.a,t.b,o))continue;const[e,s]=Ao(t.a,t.b);if(Math.abs((n-t.a[0])*s-(r-t.a[1])*e)>p)continue;const a=(t.a[0]-n)*l+(t.a[1]-r)*c,g=(t.b[0]-n)*l+(t.b[1]-r)*c,f=Math.max(-u,Math.min(a,g)),v=Math.min(u,Math.max(a,g));if(v-f<=p)continue;const y=t.inward[0]*h+t.inward[1]*d>=0?1:-1,b=((t.a[0]+t.b[0])/2-n)*h+((t.a[1]+t.b[1])/2-r)*d,w=Math.abs(b+y*t.half),k=`${y}|${t.roomId}`,x={x0:f,x1:v,half:t.half,cm:t.cm,key:t.key,axis:[e,s]},S=_.get(k);S?(S.pieces.push(x),S.faceDistance=Math.min(S.faceDistance,w)):_.set(k,{roomId:t.roomId,side:y,order:m++,pieces:[x],faceDistance:w,area:t.area,coverage:0,full:!1})}for(const e of _.values()){const t=ea(e.pieces,-u,u,p);e.coverage=t.coverage,e.full=t.full}const g=e=>{const t=[..._.values()].filter(t=>t.side===e&&t.coverage>p);return t.sort(ta),t[0]||null};return{negative:g(-1),positive:g(1)}}function na(e,t){const i=ia(e,t),n=[i.negative,i.positive].filter(e=>!!e);if(!n.length)return{ox:0,oy:0,cm:0,side:-1};const r=i.negative&&i.positive?-1:n[0].side,o=t.flip_v?-r:r,s=(-1===o?i.negative:i.positive)||n[0],a=[...s.pieces].sort((e,t)=>(e.x0<=0&&e.x1>=0?0:Math.min(Math.abs(e.x0),Math.abs(e.x1)))-(t.x0<=0&&t.x1>=0?0:Math.min(Math.abs(t.x0),Math.abs(t.x1)))||t.x1-t.x0-(e.x1-e.x0)||e.key.localeCompare(t.key))[0];if(!(a.half>0&&a.cm>0))return{ox:0,oy:0,cm:0,side:o};const l=t.angle*Math.PI/180,c=-Math.sin(l),h=Math.cos(l);return{ox:c*o*a.half,oy:h*o*a.half,cm:a.cm,side:o}}function ra(e,t){const i=1e-9,n=t.filter(e=>Number.isFinite(e.x0)&&Number.isFinite(e.x1)&&Number.isFinite(e.half)&&e.x1>e.x0&&e.half>0);if(!n.length)return"";const r=n.flatMap(e=>[e.x0,e.x1]).sort((e,t)=>e-t),o=[];for(const e of r){const t=o[o.length-1];(void 0===t||e>t+i)&&o.push(e)}const s=[];for(let e=0;e+1t+i))continue;const a=(t+r)/2,l=n.reduce((e,t)=>a>=t.x0-i&&a<=t.x1+i?Math.max(e,t.half):e,0);if(!(l>0))continue;const c=s[s.length-1];c&&t<=c.x1+i&&Math.abs(l-c.half)<=i?c.x1=r:s.push({x0:t,x1:r,half:l})}const a=[];for(const e of s){const t=a[a.length-1],n=t?.[t.length-1];n&&e.x0<=n.x1+i?(e.x0=n.x1,t.push(e)):a.push([e])}return a.map(t=>{const i=t[0],n=t[t.length-1],r=Math.min(.25*Math.min(...t.map(e=>e.half)),.75),o=-e*r,s=[];if(1===e){s.push(`M ${i.x0} ${o} L ${n.x1} ${o}`);for(let e=t.length-1;e>=0;e--){const i=t[e];s.push(`L ${i.x1} ${i.half} L ${i.x0} ${i.half}`)}}else{s.push(`M ${n.x1} ${o} L ${i.x0} ${o}`);for(const e of t)s.push(`L ${e.x0} ${-e.half} L ${e.x1} ${-e.half}`)}return s.push("Z"),s.join(" ")}).join(" ")}function oa(e,t,i,n){if(!n)return i;const r=e.angle*Math.PI/180,o=Math.cos(r),s=Math.sin(r),a=[],l=1e-9;for(const r of i){const[i,c]=r.axis,h=o*i+s*c;if(Math.abs(h)<=l)continue;const d=e.x*i+e.y*c,u=d+h*r.x0,p=d+h*r.x1,_=Math.min(u,p),m=Math.max(u,p),g=`${r.key}|${t}`,f=n.get(g)||[];let v=[[_,m]];for(const[e,t]of f){const i=[];for(const[n,r]of v)t<=n+l||e>=r-l?i.push([n,r]):(e>n+l&&i.push([n,Math.min(r,e)]),te[0]-t[0]||e[1]-t[1]),b=[];for(const e of y){const t=b[b.length-1];t&&e[0]<=t[1]+l?t[1]=Math.max(t[1],e[1]):b.push([e[0],e[1]])}n.set(g,b)}return a}function sa(e,t){const i=new Map;return t.map(t=>function(e,t,i){const n=ia(e,t,!0),r=n.negative,o=n.positive;if(!r&&!o)return null;let s;if(r&&o)s=[{candidate:r,side:-1},{candidate:o,side:1}];else{const e=r||o;s=[{candidate:e,side:-1},{candidate:e,side:1}]}const a=s.map(({candidate:e,side:n})=>({candidate:e,side:n,pieces:oa(t,n,e.pieces,i)})),l=a.map(({candidate:e,side:t,pieces:i})=>({side:t,roomId:e.roomId,d:ra(t,i)})),c=a.flatMap(({pieces:e})=>e);if(!c.length)return null;const h=Math.max(...c.map(e=>e.half));return{faces:l,minY:-h,maxY:h,wallKey:[...new Set(c.map(e=>e.key))].sort().join("|")}}(e,t,i))}const aa=150,la=1e-6;function ca(e){return Number.isFinite(e)?Math.max(1,Math.min(aa,e)):1}function ha(e){return((Number.isFinite(Number(e))?Number(e):0)%90+90)%90}const da=e=>{const t=e.map(e=>[e[0],e[1]]);return!t.length||t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]||t.push([...t[0]]),[t]},ua=(e,t)=>e[0]===t[0]&&e[1]===t[1];function pa(e,t=1e-6){const i=Number.isFinite(t)&&t>0?t:la,n=[];for(const t of e||[]){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),r=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(r))return null;const o=Math.round(e/i)*i,s=Math.round(r/i)*i;if(!Number.isFinite(o)||!Number.isFinite(s))return null;const a=[Object.is(o,-0)?0:o,Object.is(s,-0)?0:s];n.length&&ua(n[n.length-1],a)||n.push(a)}return n.length>1&&ua(n[0],n[n.length-1])&&n.pop(),n.length<3||new Set(n.map(e=>`${e[0]},${e[1]}`)).size<3?null:$i(n)>i*i?n:null}function _a(e){const t=[];for(const i of e||[])for(const e of i||[]){const i=(e||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||t.push(`M ${i.slice(0,-1).map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`)}return t.join(" ")}function ma(e,t,i,n,r){return Xo({a:e,b:t,halfDepth:Ro(i,n,r)/2})}function ga(e,t,i){const n=Number(t)>0?Number(t):5,r=ca(e.cm)/n*i,o=e.center[0],s=e.center[1];if("circle"===e.shape){const e=r/2;return Array.from({length:96},(t,i)=>{const n=i/96*Math.PI*2;return[o+Math.cos(n)*e,s+Math.sin(n)*e]})}const a=r/2,l=ha(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l);return[[-a,-a],[a,-a],[a,a],[-a,a]].map(([e,t])=>[o+e*c-t*h,s+e*h+t*c])}function fa(e,t){const i=Number.isFinite(t)?Math.max(0,Math.min(1,t)):0,n=(e.a[0]+e.b[0])/2,r=(e.a[1]+e.b[1])/2,o=(e.b[0]-e.a[0])*i/2,s=(e.b[1]-e.a[1])*i/2;return{...e,a:[n-o,r-s],b:[n+o,r+s]}}function va(e,t,i=1e-9){if(!t.length)return[e];let n=[da(e)];try{for(const e of t){const t=e.b[0]-e.a[0],r=e.b[1]-e.a[1],o=Math.hypot(t,r);if(!(o>i))continue;const s=t/o,a=r/o,l=-a,c=s,h=1.25*Math.max(Number(e.depth)||0,4*i),d=Math.max(2*i,1e-9*o),u=[[e.a[0]-s*d-l*h,e.a[1]-a*d-c*h],[e.b[0]+s*d-l*h,e.b[1]+a*d-c*h],[e.b[0]+s*d+l*h,e.b[1]+a*d+c*h],[e.a[0]-s*d+l*h,e.a[1]-a*d+c*h]];n=jt(n,da(u))}return Ca(n)}catch{return[e]}}function ya(e,t){try{const i=jt([[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]],[[...t.map(e=>[e[0],e[1]]),[t[0][0],t[0][1]]]]);let n=null,r=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs($i(t));t.length>=4&&i>r&&(r=i,n=t.slice(0,-1).map(e=>[e[0],e[1]]))}return n}catch{return null}}function ba(e,t,i,n=Math.max(2e-4*i,1e-9),r=[]){const o=[],s=new Map;for(const e of r){const t=s.get(e.hostId)||[];t.push(e),s.set(e.hostId,t)}const a=[],l=[],c=[];for(const n of e.partitions||[]){const e={a:n.a,b:n.b,halfDepth:Ro(n.cm,t,i)/2};if(!(e.halfDepth>0))continue;const r=Xo(e);r&&(o.push(e),a.push(r),c.push({id:n.id,body:r}))}const h=o;for(const{segmentIndex:e,wedge:t}of ts(h,n)){const i={list:a,at:e},n=ya(i.list[i.at],t);n&&(i.list[i.at]=n,c[i.at].body=n)}for(const e of c)l.push(...va(e.body,s.get(e.id)||[],n));const d=(e.wall_columns||[]).map(e=>ga(e,t,i)),u=is(o,n).flatMap(e=>va(e,r,n));return{partitions:a,columns:d,patches:u,all:[...l,...u,...d]}}function wa(e){try{const t=e.map(e=>pa(e)).filter(e=>!!e).map(e=>da(e));return t.length?Bt(t[0],...t.slice(1)):null}catch{return null}}const ka=e=>`M ${e.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`;function xa(e){const t=[];for(const i of e||[]){if(Ma([i])<=1e-6)continue;const e=[];for(const t of i||[]){const i=(t||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||e.push(ka(i.slice(0,-1)))}e.length&&t.push(e.join(" "))}return t}function Sa(e,t,i={}){const n=wa(e.filter(e=>e.length>=3)),r=t.some(e=>!pa(e))?null:wa(t);if(!n)return[];if(r)try{return xa(qt(n,r))}catch{}return function(e,t,i){let n=null;for(let r=0;r=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]));return t}function Ca(e){const t=[];for(const i of e||[]){const e=i?.[0];e?.length>=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]))}return t}function Ta(e,t){let i=!1;for(let n=0,r=t.length-1;ne[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s||1e-12)+o&&(i=!i)}return i}function Da(e,t,i){return function(e,t){for(const i of t||[]){const t=i?.[0];if(!t?.length||!Ta(e,t))continue;let n=!1;for(let t=1;tTa(e,t))}function Aa(e,t,i){if(Math.hypot(e.center[0]-t.center[0],e.center[1]-t.center[1])>i)return!1;if(Math.abs(ca(e.cm)-ca(t.cm))>1e-6)return!1;if(e.shape!==t.shape)return!0;if("circle"===e.shape||"circle"===t.shape)return!0;const n=Math.abs(ha(e.angle)-ha(t.angle));return Math.min(n,90-n)<=1e-6}const Pa=2.54;function Fa(e){const t="number"==typeof e?e:NaN;return!Number.isFinite(t)||t<=0||5===t?1:5/t}function za(e,t){return e*Fa(t)}function Ia(e){return e?Pa:1}function Oa(e,t){if(!t)return String(e);const i=e/Pa;return String(Math.round(1e6*i)/1e6)}function Ea(e,t){return t?e*Pa:e}const Na=1e3;function Ha(e,t){const i=Number(e),n=Number.isFinite(i)&&i>0?i:1,r=n>=1?t:t*n,o=n>=1?t/n:t;return{x:(t-r)/2,y:(t-o)/2,w:r,h:o}}const La=.01,Ba=100;function qa(e,t=1e3){const i=Ha(e?.plan_aspect,t),n=Number(e?.plan_scale),r=Number.isFinite(n)&&n>0?Math.min(Ba,Math.max(La,n)):1,o=Number(e?.plan_scale_x),s=Number(e?.plan_scale_y),a=Number.isFinite(o)&&o>0?Math.min(Ba,Math.max(La,o)):r,l=Number.isFinite(s)&&s>0?Math.min(Ba,Math.max(La,s)):r,c=Number(e?.plan_x),h=Number(e?.plan_y),d=wr(e?.plan_angle);return{x:i.x+(Number.isFinite(c)?Qa(c):0)*t,y:i.y+(Number.isFinite(h)?Qa(h):0)*t,w:i.w*a,h:i.h*l,...d?{angle:d}:{}}}function ja(e){if(null==e.x||null==e.y)return{x:e.x,y:e.y,w:e.w,h:e.h};const t=Number(e.w)||0,i=Number(e.h)||0;return{x:t<0?e.x+t:e.x,y:i<0?e.y+i:e.y,w:Math.abs(t),h:Math.abs(i)}}function Wa(e){return e&&Array.isArray(e.spaces)?e.spaces.map(e=>{const t=Na,i=function(e){return Array.isArray(e)&&4===e.length&&e.every(e=>Number.isFinite(e))&&e[2]>1e-6&&e[3]>1e-6?e:[0,0,1,1]}(e.view_box);return{id:e.id,title:e.title,cellCm:Number.isFinite(Number(e.cell_cm))&&Number(e.cell_cm)>0?Number(e.cell_cm):5,vb:[i[0]*Na,i[1]*t,i[2]*Na,i[3]*t],bg:e.plan_url?{href:Fn(e.plan_url),...qa(e,Na)}:null,rooms:(e.rooms||[]).map(e=>{const i={...e,...ja(e)};return{id:i.id,name:i.name,area:i.area??null,open_to:i.open_to||void 0,settings:i.settings||void 0,x:null!=i.x?i.x*Na:void 0,y:null!=i.y?i.y*t:void 0,w:null!=i.w?i.w*Na:void 0,h:null!=i.h?i.h*t:void 0,poly:i.poly?i.poly.map(e=>[e[0]*Na,e[1]*t]):void 0,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0}}),wall_segments:(e.wall_segments||[]).map(e=>({...e,id:String(e.id),a:[Number(e.a?.[0])*Na,Number(e.a?.[1])*t],b:[Number(e.b?.[0])*Na,Number(e.b?.[1])*t],cm:Number(e.cm)})),partitions:(e.partitions||[]).map(e=>({id:e.id,a:[e.a[0]*Na,e.a[1]*t],b:[e.b[0]*Na,e.b[1]*t],cm:Number(e.cm)})),wall_columns:(e.wall_columns||[]).map(e=>({id:e.id,shape:"circle"===e.shape?"circle":"square",center:[e.center[0]*Na,e.center[1]*t],cm:Number(e.cm),..."circle"===e.shape?{}:{angle:ha(e.angle)}}))}}):[]}const Ua=5e3,Va=Ua*Na,Ga=240,Ka=Na/Ga,Ya=1/Ga;function Xa(e){if(!Number.isFinite(e))return e;const t=Math.round(e*Ga/Na)*Na/Ga;return Math.abs(t-e)<=1e-9*Ka?e:t}function Za(e){return{x:Xa(e.x),y:Xa(e.y)}}function Ja(e){return Number.isFinite(e)?Math.min(Va,Math.max(-Va,e)):0}function Qa(e){return Number.isFinite(e)?Math.min(Ua,Math.max(-Ua,e)):0}const el=1/3,tl=200;function il(e){return"house"===e?"house":"content"}function nl(e){let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const o of e){const e=Number(o[0]),s=Number(o[1]);Number.isFinite(e)&&Number.isFinite(s)&&(en&&(n=e),s>r&&(r=s))}return t>n?null:{minX:t,minY:i,maxX:n,maxY:r}}function rl(e){const t=[],i=e=>{if(Array.isArray(e))if(e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1])))t.push([Number(e[0]),Number(e[1])]);else for(const t of e)i(t)};return i(e),nl(t)}function ol(e,t){const i=Number.isFinite(t)&&t>0?t:0;return{minX:e.minX-i,minY:e.minY-i,maxX:e.maxX+i,maxY:e.maxY+i}}function sl(e){return e.poly&&e.poly.length?nl(e.poly):null==e.x||null==e.y?null:nl([[e.x,e.y],[e.x+(e.w||0),e.y+(e.h||0)]])}function al(e,t=1e3,i=1e3){const n=Number(e.x)*t,r=Number(e.y)*i,o=Number(e.w)*t,s=Number(e.h)*i;return![n,r,o,s].every(Number.isFinite)||o<=0||s<=0?null:nl(Tr({x:n,y:r,w:o,h:s,angle:wr(e.angle)||void 0}))}function ll(e,t){const i=[];for(const t of e.rooms||[]){const e=sl(t);e&&i.push(e)}if(e.bg){const t=nl(Tr(e.bg));t&&i.push(t)}for(const e of t||[])if(Array.isArray(e)){const t=nl([e]);t&&i.push(t)}else i.push(e);return i}const cl=e=>{if(!e.length)return 0;const t=[...e].sort((e,t)=>e-t),i=t.length>>1;return t.length%2?t[i]:(t[i-1]+t[i])/2},hl=e=>{let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const o of e)o.minXn&&(n=o.maxX),o.maxY>r&&(r=o.maxY);return t>n||i>r?null:{x:t,y:i,w:n-t,h:r-i}};function dl(e,t){let{x:i,y:n,w:r,h:o}=e;r<30&&(i=i+r/2-100,r=tl),o<30&&(n=n+o/2-100,o=tl);const s="number"==typeof t?{top:t,right:t,bottom:t,left:t}:t,a=Math.max(r,o),l=a*s.top,c=a*s.right,h=a*s.bottom,d=a*s.left;return{x:i-d,y:n-l,w:r+d+c,h:o+l+h}}function ul(e,t={}){const i=t.pad??.05,n=t.k??10,r=t.minSpread??50,o=e.filter(e=>Number.isFinite(e.minX)&&Number.isFinite(e.minY)&&Number.isFinite(e.maxX)&&Number.isFinite(e.maxY)&&Math.abs(e.minX)<=Va&&Math.abs(e.maxX)<=Va&&Math.abs(e.minY)<=Va&&Math.abs(e.maxY)<=Va);if(!o.length)return{core:null,all:null,outliers:0};const s=hl(o);if(o.length<4){const e=dl(s,i);return{core:e,all:e,outliers:0}}const a=o.map(e=>(e.minX+e.maxX)/2),l=o.map(e=>(e.minY+e.maxY)/2),c=cl(a),h=cl(l),d=o.map((e,t)=>Math.max(Math.abs(a[t]-c),Math.abs(l[t]-h))),u=Math.max(((e,t)=>e.length?e[Math.min(e.length-1,Math.max(0,Math.round(t*(e.length-1))))]:0)([...d].sort((e,t)=>e-t),.75),r),p=d.map(e=>e>n*u),_=p.filter(Boolean).length,m=_&&_<=o.length*el?o.filter((e,t)=>!p[t]):o;return{core:dl(hl(m)||s,i),all:dl(s,i),outliers:m===o?0:_}}function pl(e){return ul(e,{pad:0}).all}function _l(e,t,i=.05){const n=ul(ll(e,t),{pad:i});if(n.core)return n.core;const r=e.vb&&4===e.vb.length&&e.vb[2]>0&&e.vb[3]>0?e.vb:[0,0,Na,Na];return{x:r[0],y:r[1],w:r[2],h:r[3]}}function ml(e){const t=_l(e);return{x:t.x+t.w/2,y:t.y+t.h/2}}function gl(e){const t=[];for(const i of e.rooms||[]){const e=sl(i);e&&t.push(e)}const i=ul(t,{pad:0}).core,n=Na*Fa(e.cellCm??5);return i?Math.max(n,Math.min(Va,Math.max(i.w,i.h))):n}function fl(e,t,i,n=1){const r=Number(i),o=Number.isFinite(n)&&n>0?n:1;return!Number.isFinite(r)||r<=0?e*o:e*gl(t)*o/r}const vl=[1,2,5,10,20,50,100,200,500,1e3];function yl(e,t,i=7){if(!(e>0&&t>0&&Number.isFinite(t)))return null;const n=vl.find(n=>e*n*t>=i);if(void 0===n)return null;const r=vl.find(e=>e>=5*n)??5*n;return{fine:n,coarse:r}}function bl(e){if(e.poly&&e.poly.length){const t=e.poly.map(e=>e[0]),i=e.poly.map(e=>e[1]),n=Math.min(...t),r=Math.min(...i);return{x:n,y:r,w:Math.max(...t)-n,h:Math.max(...i)-r}}return{x:e.x??0,y:e.y??0,w:e.w??0,h:e.h??0}}function wl(e,t,i,n,r,o=new Set){const s=t[e.id];return!o.has(e.id)&&s&&s.s===e.space?{x:s.x*Na,y:s.y*Na}:n[e.id]?n[e.id]:Za(ml(r))}function kl(e,t,i,n){const r=i["rl_"+(e.id||"")];if(r&&r.s===t)return{x:r.x*Na,y:r.y*Na};const o=function(e){if(e.poly){const t=e.poly.length;return[e.poly.reduce((e,t)=>e+t[0],0)/t,e.poly.reduce((e,t)=>e+t[1],0)/t]}return[e.x+e.w/2,e.y+.1*Math.min(e.w,e.h)]}(e);return Za({x:o[0],y:o[1]})}function xl(e,t){for(const i of e?.spaces??[])for(const e of i?.decor??[])if("furniture"===e?.kind&&"string"==typeof e.symbol&&t(e.symbol))return!0;return!1}let Sl=0;const $l=new Set;const Ml=new class{constructor(e){this.options=e,this._art=null,this._failed=!1,this._terminal=!1,this._inFlight=null,this._hosts=new Set,this._settled=[]}state(){return this._art?"ready":this._failed?"fallback":"pending"}get terminal(){return this._terminal}art(e,t){if(this._art)return this._art[e];t&&!this._failed&&this._hosts.add(t)}adopt(e,t){return!!this._art||(t!==this.options.expectedFingerprint?((this.options.warn??console.warn)("[houseplan] furniture artwork from another build ignored",{fingerprint:t}),!1):(this._install(e),!0))}ensure(){return"pending"!==this.state()?Promise.resolve():(this._inFlight||(this._inFlight=this._loadWithRetry().finally(()=>{this._inFlight=null})),this._inFlight)}onSettled(e){"pending"===this.state()?this._settled.push(e):Promise.resolve().then(e)}async _loadWithRetry(){let e=new Error("furniture artwork did not load");for(const t of[0,1])try{const i=await this.options.load(t);if(i.FURNITURE_ART_FINGERPRINT!==this.options.expectedFingerprint){this._terminal=!0,e=new Error(`furniture artwork fingerprint mismatch: expected ${this.options.expectedFingerprint}, got ${i.FURNITURE_ART_FINGERPRINT}`);break}if(this._art)return;return void this._install(i.GENERATED_FURNITURE_ART)}catch(t){e=t}this._art||(this._failed=!0,(this.options.warn??console.warn)("[houseplan] furniture artwork unavailable",e),this.options.loadFailed?.(this._terminal),this._flush())}_install(e){this._art=e,this._failed=!1,this._flush()}_flush(){const e=[...this._hosts];this._hosts.clear();for(const t of e)t.isConnected&&t.requestUpdate();const t=this._settled.splice(0);for(const e of t)e()}}({expectedFingerprint:"5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f",load:async e=>0===e?await import("./furniture-plan-art.generated-BITfBkG8.js"):await import((()=>{const e=new URL("./furniture-plan-art.generated-BITfBkG8.js",import.meta.url);return e.searchParams.set("hp_retry","art-"+ ++Sl),e.href})()),loadFailed:e=>{for(const t of $l)t(e)}}),Rl=["furniture","appliance","sanitary","other"],Cl=[{id:"sofa",group:"furniture",category:"sofa",w:220,h:90,g:[["r",0,0,1,1],["l",.09,.26,.91,.26],["l",.09,.26,.09,1],["l",.91,.26,.91,1],["l",.5,.26,.5,1]]},{id:"armchair",group:"furniture",category:"armchair",w:90,h:85,g:[["r",0,0,1,1],["l",.14,.28,.86,.28],["l",.14,.28,.14,1],["l",.86,.28,.86,1]]},{id:"coffee_table",group:"furniture",category:"coffee_table",w:110,h:60,g:[["r",0,0,1,1],["r",.08,.14,.84,.72]]},{id:"table_dining",group:"furniture",category:"dining_table",w:140,h:80,g:[["r",0,0,1,1],["r",.06,.11,.88,.78]]},{id:"table_round",group:"furniture",category:"dining_table",w:120,h:120,g:[["e",.5,.5,.5,.5],["e",.5,.5,.41,.41]]},{id:"chair",group:"furniture",category:"chair",w:45,h:45,g:[["r",0,0,1,.18],["r",.06,.18,.88,.8]]},{id:"desk",group:"furniture",category:"work_table",w:120,h:60,g:[["r",0,0,1,1],["r",.63,.07,.31,.86],["l",.63,.5,.94,.5]]},{id:"bed_double",group:"furniture",category:"bed",w:160,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.06,.1,.4,.15],["r",.54,.1,.4,.15],["l",0,.33,1,.33]]},{id:"bed_single",group:"furniture",category:"bed",w:90,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.15,.1,.7,.15],["l",0,.33,1,.33]]},{id:"nightstand",group:"furniture",category:"nightstand",w:45,h:40,g:[["r",0,0,1,1],["r",.12,.14,.76,.33],["r",.12,.53,.76,.33]]},{id:"wardrobe",group:"furniture",category:"wardrobe",w:100,h:60,g:[["r",0,0,1,1],["l",0,.72,1,.72],["l",.5,.72,.5,1]]},{id:"bookshelf",group:"furniture",category:"wardrobe",w:80,h:30,g:[["r",0,0,1,1],["l",.34,0,.34,1],["l",.67,0,.67,1]]},{id:"fridge",group:"appliance",category:"fridge",w:60,h:65,g:[["r",0,0,1,1],["l",0,.36,1,.36],["l",.83,.44,.83,.64]]},{id:"stove",group:"appliance",category:"cooktop",w:60,h:60,g:[["r",0,0,1,1],["e",.29,.31,.15,.15],["e",.71,.31,.15,.15],["e",.29,.71,.15,.15],["e",.71,.71,.15,.15]]},{id:"dishwasher",group:"appliance",category:"dishwasher",w:60,h:60,g:[["r",0,0,1,1],["r",.1,.12,.8,.76],["e",.5,.5,.27,.27],["e",.5,.5,.13,.13]]},{id:"washer",group:"appliance",category:"washer",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["e",.5,.57,.14,.14]]},{id:"dryer",group:"appliance",category:"dryer",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["p",.36,.5,.5,.64,.64,.5]]},{id:"tv",group:"appliance",category:"tv",w:120,h:30,g:[["r",0,0,1,.42],["l",.5,.42,.5,.72],["l",.3,.72,.7,.72]]},{id:"ac",group:"appliance",category:"air_conditioner",w:90,h:25,g:[["r",0,0,1,1],["l",.05,.55,.95,.55],["l",.05,.79,.95,.79]]},{id:"water_heater",group:"appliance",category:"boiler",w:45,h:45,g:[["e",.5,.5,.5,.5],["e",.5,.5,.31,.31]]},{id:"toilet",group:"sanitary",category:"toilet",w:40,h:70,g:[["r",.06,0,.88,.2],["e",.5,.58,.37,.35],["e",.5,.58,.22,.2]]},{id:"bathtub",group:"sanitary",category:"bathtub",w:170,h:75,g:[["r",0,0,1,1],["r",.05,.11,.77,.78],["e",.89,.5,.045,.1]]},{id:"shower",group:"sanitary",category:"shower",w:90,h:90,g:[["r",0,0,1,1],["l",0,0,1,1],["l",1,0,0,1],["e",.5,.5,.08,.08]]},{id:"sink",group:"sanitary",category:"sink",w:60,h:45,g:[["r",0,0,1,1],["e",.5,.6,.34,.3],["e",.5,.15,.07,.07]]},{id:"kitchen_sink",group:"sanitary",category:"kitchen_sink",w:80,h:60,g:[["r",0,0,1,1],["r",.06,.24,.44,.64],["r",.54,.24,.4,.64],["e",.5,.12,.06,.06]]},{id:"bidet",group:"sanitary",category:"bidet",w:40,h:55,g:[["e",.5,.5,.44,.5],["e",.5,.5,.26,.3]]},{id:"stairs",group:"other",category:"stairs",w:100,h:280,g:[["r",0,0,1,1],["l",0,.111,1,.111],["l",0,.222,1,.222],["l",0,.333,1,.333],["l",0,.444,1,.444],["l",0,.556,1,.556],["l",0,.667,1,.667],["l",0,.778,1,.778],["l",0,.889,1,.889],["l",.5,.93,.5,.06],["p",.38,.16,.5,.06,.62,.16]]},{id:"fireplace",group:"other",category:"fireplace",w:120,h:40,g:[["r",0,0,1,1],["p",.22,1,.22,.42,.78,.42,.78,1]]},{id:"plant",group:"other",category:"plant",w:40,h:40,g:[["e",.5,.5,.22,.22],["l",.5,.28,.5,.02],["l",.5,.72,.5,.98],["l",.28,.5,.02,.5],["l",.72,.5,.98,.5],["l",.34,.34,.13,.13],["l",.66,.66,.87,.87],["l",.66,.34,.87,.13],["l",.34,.66,.13,.87]]},{id:"rug",group:"other",category:"rug",w:200,h:140,g:[["r",0,0,1,1],["r",.06,.09,.88,.82]]}],Tl=new Set(["fridge","dishwasher","washer","dryer","ac","water_heater","shower","sink","stairs","fireplace","plant","rug"]),Dl=[...[{id:"coffee_table",group:"furniture",category:"coffee_table",w:120,h:60},{id:"coffee_table_round",group:"furniture",category:"coffee_table",w:80,h:80},{id:"coffee_table_oval",group:"furniture",category:"coffee_table",w:120,h:60},{id:"coffee_table_rounded",group:"furniture",category:"coffee_table",w:120,h:60},{id:"table_dining",group:"furniture",category:"dining_table",w:160,h:90},{id:"table_round",group:"furniture",category:"dining_table",w:110,h:110},{id:"table_dining_oval",group:"furniture",category:"dining_table",w:180,h:100},{id:"table_dining_rounded",group:"furniture",category:"dining_table",w:160,h:90},{id:"desk",group:"furniture",category:"work_table",w:140,h:70},{id:"desk_corner",group:"furniture",category:"work_table",w:160,h:160},{id:"chair",group:"furniture",category:"chair",w:50,h:50},{id:"chair_bar",group:"furniture",category:"chair",w:45,h:48},{id:"armchair",group:"furniture",category:"armchair",w:90,h:90},{id:"armchair_office",group:"furniture",category:"armchair",w:65,h:65},{id:"sofa",group:"furniture",category:"sofa",w:180,h:90},{id:"sofa_three_seat",group:"furniture",category:"sofa",w:240,h:90},{id:"sofa_corner_right",group:"furniture",category:"sofa",w:260,h:170},{id:"bed_single",group:"furniture",category:"bed",w:90,h:200},{id:"bed_double",group:"furniture",category:"bed",w:160,h:200},{id:"nightstand",group:"furniture",category:"nightstand",w:50,h:40},{id:"cabinet_tv",group:"furniture",category:"nightstand",w:140,h:45},{id:"cabinet_shoe",group:"furniture",category:"nightstand",w:80,h:35},{id:"cabinet_sink",group:"furniture",category:"nightstand",w:80,h:50},{id:"bookshelf",group:"furniture",category:"wardrobe",w:100,h:35},{id:"wall_unit",group:"furniture",category:"wardrobe",w:240,h:45},{id:"wardrobe",group:"furniture",category:"wardrobe",w:180,h:60},{id:"kitchen_floor",group:"furniture",category:"kitchen_cabinet",w:60,h:60},{id:"kitchen_floor_corner",group:"furniture",category:"kitchen_cabinet",w:90,h:90},{id:"kitchen_wall",group:"furniture",category:"kitchen_cabinet",w:60,h:35},{id:"kitchen_wall_corner",group:"furniture",category:"kitchen_cabinet",w:60,h:60},{id:"shelf_floor",group:"furniture",category:"shelving",w:100,h:35},{id:"shelf_wall",group:"furniture",category:"shelving",w:100,h:25},{id:"cooktop_two",group:"appliance",category:"cooktop",w:30,h:50},{id:"stove",group:"appliance",category:"cooktop",w:60,h:60},{id:"tv",group:"appliance",category:"tv",w:120,h:28},{id:"tv_wall",group:"appliance",category:"tv",w:120,h:15},{id:"toilet",group:"sanitary",category:"toilet",w:40,h:70},{id:"toilet_built_in",group:"sanitary",category:"toilet",w:40,h:55},{id:"bathtub",group:"sanitary",category:"bathtub",w:170,h:75},{id:"bathtub_corner",group:"sanitary",category:"bathtub",w:140,h:140},{id:"bidet",group:"sanitary",category:"bidet",w:40,h:60},{id:"bidet_built_in",group:"sanitary",category:"bidet",w:40,h:50},{id:"kitchen_sink",group:"sanitary",category:"kitchen_sink",w:60,h:50},{id:"kitchen_sink_double",group:"sanitary",category:"kitchen_sink",w:90,h:50}].map(e=>({id:e.id,group:e.group,category:e.category,w:e.w,h:e.h,designer:!0})),...Cl.filter(e=>Tl.has(e.id))],Al=new Map(Dl.map(e=>[e.id,e]));function Pl(e){return e&&Al.get(e)||null}function Fl(e){return!0===Al.get(e)?.designer}function zl(e){return Dl.filter(t=>t.group===e)}function Il(e){const t=Pl(e);return t?{w:t.w,h:t.h}:{w:60,h:60}}function Ol(e,t,i=Ka,n=1e3){const r=Number(t)>0?Number(t):5;return(Number(e)||0)/r*i/n}const El=5e-4,Nl=Ua;function Hl(e){return Number.isFinite(e)?Math.max(El,Math.min(Nl,e)):El}function Ll(e){return Number.isFinite(e)?Math.max(1,Math.min(1e4,e)):1}const Bl=e=>{const t=Math.round(1e3*e)/1e3;return Object.is(t,-0)?"0":String(t)};function ql(e,t){const i=Pl(e);if(!i)return null;if(i.designer)return Ml.art(e,t)??null;const n=function(e,t,i){if(!e.g)return"";const n=e=>Bl(e*t),r=e=>Bl(e*i),o=[];for(const s of e.g)if("r"===s[0]){const[,e,t,i,a]=s;o.push(`M${n(e)} ${r(t)}H${n(e+i)}V${r(t+a)}H${n(e)}Z`)}else if("l"===s[0]){const[,e,t,i,a]=s;o.push(`M${n(e)} ${r(t)}L${n(i)} ${r(a)}`)}else if("e"===s[0]){const[,e,a,l,c]=s;o.push(`M${n(e-l)} ${r(a)}A${Bl(l*t)} ${Bl(c*i)} 0 0 1 ${n(e+l)} ${r(a)}A${Bl(l*t)} ${Bl(c*i)} 0 0 1 ${n(e-l)} ${r(a)}Z`)}else{const e=s.slice(1);if(e.length<4)continue;let t=`M${n(e[0])} ${r(e[1])}`;for(let i=2;i+10?n:Number.isFinite(r)&&r>0?r:1,s=Number(t),a=o*(Number.isFinite(s)&&s>0?s:1);return Number.isFinite(a)&&a>0?a:o}function Wl(e,t,i,n,r){const o=e+i/2,s=t+n/2,a=(Number(r)||0)*Math.PI/180,l=Math.cos(a),c=Math.sin(a),h=(e,t)=>{const i=e-o,n=t-s;return[o+i*l-n*c,s+i*c+n*l]};return[h(e,t),h(e+i,t),h(e+i,t+n),h(e,t+n)]}function Ul(e,t,i,n,r,o,s){const a=Number.isFinite(s)&&s>0?s:1e-6,l=(Number(e.angle)||0)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),u=Math.cos(l),p=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:t<0?e.w/2:0,g=i>0?-e.h/2:i<0?e.h/2:0,f=p+m*c+g*d,v=_+m*h+g*u,y=n-f,b=r-v,w=t?(y*c+b*h)*(t>0?1:-1):e.w,k=i?(y*d+b*u)*(i>0?1:-1):e.h;let x=t?Math.abs(w):e.w,S=i?Math.abs(k):e.h;if(o&&t&&i){const t=x/Math.max(e.w,a),i=S/Math.max(e.h,a),n=Math.abs(t-1)>=Math.abs(i-1)?t:i,r=Math.max(a/e.w,a/e.h),o=Math.max(r,Number.isFinite(n)?n:r);x=e.w*o,S=e.h*o}x=Math.max(a,Number.isFinite(x)?x:a),S=Math.max(a,Number.isFinite(S)?S:a);const $=!!t&&w<0,M=!!i&&k<0,R=t?(t>0?1:-1)*($?-1:1):0,C=i?(i>0?1:-1)*(M?-1:1):0,T=f+R*(x/2)*c+C*(S/2)*d,D=v+R*(x/2)*h+C*(S/2)*u,A=!!e.flip_h!==$,P=!!e.flip_v!==M;return{x:T-x/2,y:D-S/2,w:x,h:S,...Number(e.angle)?{angle:Number(e.angle)}:{},...A?{flip_h:!0}:{},...P?{flip_v:!0}:{}}}function Vl(e,t,i,n){let r=Number(e)+(Number(i)-Number(t));if([r,t,i].every(Number.isFinite)||(r=0),n){const e=r/45;r=45*(e<0?-Math.round(Math.abs(e)):Math.round(e))}return r=(r%360+360)%360,r>180?r-360:r}function Gl(e,t,i,n,r){const o=e.x*t,s=e.y*i,a=e.w*t,l=e.h*i,c=o+a/2,h=s+l/2,d=o+(e.flip_h?a:0),u=s+(e.flip_v?l:0),p=(e.flip_h?-1:1)*a/n,_=(e.flip_v?-1:1)*l/r,m=Number(e.angle)||0;return(m?`rotate(${m} ${c} ${h}) `:"")+`translate(${d} ${u}) scale(${p} ${_})`}function Kl(e,t,i,n=.1){if("string"==typeof e&&!e.trim())return null;const r=Number(e);if(!Number.isFinite(r)||0===r)return null;const o=r*(t?30.48:100),s=Math.abs(o);return si?null:o}function Yl(e,t,i){const n=Math.abs(Number(e))/(i?30.48:100),r=Number(n.toFixed(6));return String(t?-r:r)}const Xl=15e3,Zl=2e3,Jl=new WeakMap;function Ql(e,t){let i=Jl.get(e);if(!i){const t=new Set;i={hiddenAt:"hidden"===e.visibilityState?Date.now():0,token:0,subscribers:t,onVisibility:()=>{const t=Jl.get(e);if(!t)return;const i=Date.now();if("hidden"===e.visibilityState){t.hiddenAt||(t.hiddenAt=i);const e={kind:"hidden",token:t.token,at:i,hiddenFor:0,long:!1};for(const i of[...t.subscribers])i(e);return}const n=t.hiddenAt?Math.max(0,i-t.hiddenAt):0;t.hiddenAt=0,t.token++;const r={kind:"visible",token:t.token,at:i,hiddenFor:n,long:n>=Xl};for(const e of[...t.subscribers])e(r)},onPageShow:t=>{const i=Jl.get(e);if(!i)return;const n=Date.now();i.token++;const r={kind:"pageshow",token:i.token,at:n,hiddenFor:0,long:!!t.persisted,persisted:!!t.persisted};for(const e of[...i.subscribers])e(r)}},Jl.set(e,i),e.addEventListener("visibilitychange",i.onVisibility),e.defaultView?.addEventListener("pageshow",i.onPageShow)}return i.subscribers.add(t),()=>{const i=Jl.get(e);i&&(i.subscribers.delete(t),i.subscribers.size||(e.removeEventListener("visibilitychange",i.onVisibility),e.defaultView?.removeEventListener("pageshow",i.onPageShow),Jl.delete(e)))}}const ec={now:()=>Date.now(),setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>window.clearTimeout(e),requestAnimationFrame:e=>window.requestAnimationFrame(e),cancelAnimationFrame:e=>window.cancelAnimationFrame(e)};class tc{constructor(e,t=ec){this.onChange=e,this.clock=t,this._state="steady",this._token=0,this._frameFingerprint="",this._hasCompleteFrame=!1,this._overlayPhase="none",this._recoveryReason=null,this._overlayTimer=0,this._overlayRaf=0,this._overlayOpaqueAt=0,this._barrierRafs=new Set,this._trace=[],this._disposed=!1}get state(){return this._state}get token(){return this._token}get frameFingerprint(){return this._frameFingerprint}get hasCompleteFrame(){return this._hasCompleteFrame}get overlayPhase(){return this._overlayPhase}get overlayVisible(){return"none"!==this._overlayPhase}get overlayBlocksInteraction(){return this.overlayVisible}get recoveryReason(){return this._recoveryReason}get trace(){return this._trace.map(e=>({...e,...e.stage?{stage:[...e.stage]}:{}}))}note(e,t={}){this.record(e,void 0,t)}record(e,t,i={}){this._trace.push({at:this.clock.now(),token:this._token,event:e,state:this._state,...t?{reason:t}:{},...i}),this._trace.length>80&&this._trace.splice(0,this._trace.length-80)}changed(){this._disposed||this.onChange()}adoptCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-adopted"),this.changed())}markCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-complete"),this.changed())}refreshCompleteFrame(e){!this._disposed&&this._hasCompleteFrame&&"steady"===this._state&&e&&e!==this._frameFingerprint&&(this._frameFingerprint=e,this.record("frame-refreshed"))}visibility(e){return"hidden"===e.kind?(this.record("visibility-hidden"),this._token):e.long||"visible"!==e.kind&&"pageshow"!==e.kind?this.beginCandidate("pageshow"===e.kind?"pageshow":"long-resume"):(this.record("pageshow"===e.kind?"pageshow-noop":"visibility-visible-quick"),this._token)}beginCandidate(e,t="plan"){return this._token++,this._recoveryReason=t,this._hasCompleteFrame?(this._state="connection"===t?"offline-stale":"holding",this.clearOverlay()):this.overlayVisible?this._state="overlay-visible":(this._state="overlay-pending",this.scheduleOverlay(t)),this.record("candidate-start",e),this.changed(),this._token}connectionLost(){return this.beginCandidate("connection-lost","connection")}candidateReady(e){return!this._disposed&&e===this._token&&(this._state="candidate-ready",this.record("candidate-ready"),this.changed(),!0)}async commitAfterPaint(e,t){if(this._disposed||e!==this._token)return!1;let i=!0;const n=(async()=>{for(await t.updateComplete();i&&!this._disposed&&e===this._token;)if(t.stageValid()&&t.assetsReady()){if(await this.nextFrame(),e!==this._token||!t.stageValid()||!t.assetsReady())continue;if(await this.nextFrame(),e===this._token&&t.stageValid()&&t.assetsReady())return!0}else await this.nextFrame();return!1})();let r=0;const o=new Promise(e=>{r=this.clock.setTimeout(()=>e({ready:!1,timedOut:!0}),Zl)}),s=await Promise.race([n.then(e=>({ready:e,timedOut:!1})),o]);return i=!1,this.clock.clearTimeout(r),!this._disposed&&e===this._token&&(!(!s.ready&&!s.timedOut)&&(s.ready?(this._hasCompleteFrame=!0,this._frameFingerprint=t.frameFingerprint(),this.record("paint-barrier"),this.finishOverlayAfterCommit(),!0):(this.record("paint-barrier-timeout"),this._hasCompleteFrame?(this._state="connection"===this._recoveryReason?"offline-stale":"steady",this.clearOverlay()):(this._state="recovery-error","opaque"!==this._overlayPhase&&this.showOverlayNow()),this.changed(),!1)))}retry(e=this._recoveryReason||"plan"){return this.beginCandidate("retry",e)}nextFrame(){return new Promise(e=>{const t=this.clock.requestAnimationFrame(()=>{this._barrierRafs.delete(t),e()});this._barrierRafs.add(t)})}scheduleOverlay(e){this.clearOverlayTimer(),this._recoveryReason=e,this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._hasCompleteFrame||"overlay-pending"!==this._state&&"candidate-ready"!==this._state||(this._state="overlay-visible",this._overlayPhase="entering",this.record("overlay-enter"),this.changed(),this._overlayRaf=this.clock.requestAnimationFrame(()=>{this._overlayRaf=0,"entering"===this._overlayPhase&&(this._overlayPhase="fading-in",this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,"fading-in"===this._overlayPhase&&(this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-opaque"),this.changed())},150))}))},150)}showOverlayNow(){this.clearOverlayTimer(),this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-error")}finishOverlayAfterCommit(){if(this.clearOverlayTimer(),"none"===this._overlayPhase||"entering"===this._overlayPhase||"fading-in"===this._overlayPhase)return this.clearOverlay(),this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),void this.changed();const e=Math.max(0,this._overlayOpaqueAt+250-this.clock.now());this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="leaving",this.record("overlay-leave"),this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="none",this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),this.changed()},180)},e)}clearOverlayTimer(){this._overlayTimer&&this.clock.clearTimeout(this._overlayTimer),this._overlayTimer=0}clearOverlay(){this.clearOverlayTimer(),this._overlayRaf&&this.clock.cancelAnimationFrame(this._overlayRaf),this._overlayRaf=0,this._overlayPhase="none",this._overlayOpaqueAt=0}dispose(){this._disposed=!0,this._token++,this.clearOverlay();for(const e of this._barrierRafs)this.clock.cancelAnimationFrame(e);this._barrierRafs.clear()}}function ic(e){let t=2166136261,i=2654435769;const n=new WeakSet,r=e=>{for(let n=0;n>>0)+(i>>>2)}},o=e=>{if(null===e)return void r("n");const t=typeof e;if("string"===t)return void r(`s${e.length}:${e}`);if("number"===t)return void r(`d${Number.isNaN(e)?"NaN":String(e)}`);if("boolean"===t)return void r(e?"t":"f");if("undefined"===t)return void r("u");if("object"!==t)return void r(`${t}:${String(e)}`);const i=e;if(n.has(i))r("[cycle]");else{if(n.add(i),Array.isArray(e)){r("[");for(const t of e)o(t);return r("]"),void n.delete(i)}r("{");for(const t of Object.keys(e).sort())r(t),o(e[t]);r("}"),n.delete(i)}};return o(e),`${(t>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function nc(e){return ic(e)}const rc=new WeakMap;class oc{constructor(e,t=()=>Date.now()){this.onUpdate=e,this.now=t,this.fallbackAuthority={},this.referenceOwner={},this.referenced=new Set,this.queued=new Set,this.disposed=!1,this.sharedUpdate=()=>{this.disposed||this.onUpdate()}}bind(e){const t=((e,t)=>{const i=e?.connection||e?.callWS||t;return!i||"object"!=typeof i&&"function"!=typeof i?t:i})(e,this.fallbackAuthority);return this.shared&&this.authority===t||(this.shared&&(this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner)),this.authority=t,this.shared=(e=>{let t=rc.get(e);return t||(t={signed:{},queued:new Set,inFlight:new Map,retry:new Map,listeners:new Set,settlers:new Set,references:new Map},rc.set(e,t)),t})(t),this.disposed||(this.shared.listeners.add(this.sharedUpdate),this.shared.references.set(this.referenceOwner,new Set(this.referenced)))),this.shared}start(e,t){this.disposed=!1,this.referenced=new Set(t());const i=this.bind(e());i.listeners.add(this.sharedUpdate),i.references.set(this.referenceOwner,new Set(this.referenced)),this.stopTimer(),this.resignTimer=setInterval(()=>this.resign(e(),t()),288e5)}dispose(){if(this.disposed=!0,this.stopTimer(),clearTimeout(this.batchTimer),this.shared){this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner);for(const e of this.queued)this.shared.queued.delete(e)}this.queued.clear()}invalidate(e){const t=this.bind(e);clearTimeout(this.batchTimer),this.queued.clear(),t.queued.clear(),t.inFlight.clear(),t.retry.clear(),t.signed={}}stopTimer(){void 0!==this.resignTimer&&clearInterval(this.resignTimer),this.resignTimer=void 0}display(e,t){const i=Fn(t);if(!i.startsWith("/api/houseplan/content/"))return i;const n=this.bind(e);this.referenced.add(i),n.references.set(this.referenceOwner,new Set(this.referenced));const r=n.signed[i],o=r?this.now()-r.at:1/0;return o{const t=[...this.queued];this.queued.clear();for(const e of t)i.queued.delete(e);this.sign(e,t)},30))}sign(e,t){if(!t.length||!e?.callWS)return;const i=this.bind(e);for(const n of function(e,t){const i=Math.max(1,Math.floor(t)),n=[];for(let t=0;t{const n=i.inFlight.get(e);return!(void 0!==n&&t-n<15e3)&&(i.inFlight.set(e,t),!0)});r.length&&e.callWS({type:"houseplan/content/sign",paths:r}).then(e=>{const t=this.now();let n=0,o=!1;for(const s of r){const r=e?.urls?.[s];if("string"==typeof r&&r){const e=i.signed[s];e?.loaded&&e.url!==r?(e.pending={url:r,at:t},this.preloadReplacement(i,s,r,t)):(i.signed[s]={url:r,at:t,loaded:e?.url===r&&!!e.loaded},o=!0),i.retry.delete(s),n++}else this.backOff(i,s)}if(n&&(this.trimShared(i),o))for(const e of[...i.listeners])e()}).catch(()=>{for(const e of r)this.backOff(i,e)}).finally(()=>{for(const e of r)i.inFlight.get(e)===t&&i.inFlight.delete(e);for(const e of[...i.settlers])e()})}}preloadReplacement(e,t,i,n){const r=()=>{const r=e.signed[t];if(r?.pending?.url===i){e.signed[t]={url:i,at:n,loaded:!0},e.retry.delete(t),this.trimShared(e);for(const t of[...e.listeners])t()}},o=()=>{const n=e.signed[t];n?.pending?.url===i&&(delete n.pending,this.backOff(e,t))};if("undefined"==typeof Image)return void r();const s=new Image;s.onload=()=>{("function"==typeof s.decode?s.decode():Promise.resolve()).then(r).catch(o)},s.onerror=o,s.src=i}preloadCurrentImage(e,t,i){if(i.loaded)return Promise.resolve(!0);if(i.preload)return i.preload;if("undefined"==typeof Image)return i.loaded=!0,Promise.resolve(!0);const n=i.url;return i.preload=new Promise(r=>{const o=new Image;let s=!1;const a=o=>{if(s)return;s=!0,clearTimeout(l);const a=e.signed[t];if(a===i&&delete a.preload,o&&a===i&&a.url===n){a.loaded=!0;for(const t of[...e.listeners])t();r(!0)}else o||a!==i||this.backOff(e,t),r(!1)};o.onload=()=>{("function"==typeof o.decode?o.decode():Promise.resolve()).then(()=>a(!0)).catch(()=>a(!1))},o.onerror=()=>a(!1);const l=setTimeout(()=>a(!1),Zl);o.src=n}),i.preload}prepareImage(e,t){const i=Fn(t);if(!i.startsWith("/api/houseplan/content/"))return Promise.resolve(!0);const n=this.bind(e),r=()=>{const t=n.signed[i];if(t&&this.now()-t.atthis.now()&&!n.inFlight.has(i)&&!n.queued.has(i)?Promise.resolve(!1):null},o=r();return o?(s=o,new Promise(e=>{let t=!1;const i=i=>{t||(t=!0,clearTimeout(n),e(i))},n=setTimeout(()=>i(!1),Zl);s.then(i).catch(()=>i(!1))})):new Promise(e=>{let t=!1,i=null;const o=i=>{t||(t=!0,clearTimeout(a),n.settlers.delete(s),e(i))},s=()=>{t||i||(i=r(),i&&i.then(o).catch(()=>o(!1)))},a=setTimeout(()=>o(!1),Zl);n.settlers.add(s),s()});var s}backOff(e,t){const i=e.retry.get(t)?.delay||0,n=Math.min(6e4,i?2*i:2e3);e.retry.set(t,{notBefore:this.now()+n,delay:n})}trimShared(e){const t=Object.entries(e.signed);if(t.length<=512)return;const i=new Set(e.inFlight.keys());for(const t of e.references.values())for(const e of t)i.add(e);for(const[e,n]of t)(n.pending||n.preload)&&i.add(e);t.sort((e,t)=>t[1].at-e[1].at);const n=t.filter(([e])=>i.has(e));for(const e of t){if(n.length>=512)break;i.has(e[0])||n.push(e)}e.signed=Object.fromEntries(n)}resign(e,t){const i=this.bind(e);this.referenced=new Set(t),i.references.set(this.referenceOwner,new Set(this.referenced));const n=this.now(),r=new Set;for(const e of i.references.values())for(const t of e)r.add(t);const o={};for(const[e,t]of Object.entries(i.signed))r.has(e)&&n-t.at!!o[e]&&!o[e].pending))}markLoaded(e,t,i){const n=Fn(t);if(!n.startsWith("/api/houseplan/content/"))return;const r=this.bind(e).signed[n];if(r&&(!i||r.url===i)&&!r.loaded){r.loaded=!0;for(const t of[...this.bind(e).listeners])t()}}isReady(e,t){const i=Fn(t);if(!i.startsWith("/api/houseplan/content/"))return!0;const n=this.bind(e).signed[i];return!!n&&this.now()-n.ate.id===t)}var ac="M11,18H13V16H11V18M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,6A4,4 0 0,0 8,10H10A2,2 0 0,1 12,8A2,2 0 0,1 14,10C14,12 11,11.75 11,15H13C13,12.75 16,12.5 16,10A4,4 0 0,0 12,6Z";function lc(e,t,i){return[e[0]*t+e[1]*i+e[2],e[3]*t+e[4]*i+e[5]]}function cc(e,t){let i=0;for(const[n,r]of t){const t=lc(e,n[0],n[1]);i=Math.max(i,Math.hypot(t[0]-r[0],t[1]-r[1]))}return i}const hc=e=>{if(null==e||""===e)return null;const t=Number(e);return Number.isFinite(t)?t:null},dc=e=>{const t=e,i=hc(Array.isArray(t)?t[0]:t?.x),n=hc(Array.isArray(t)?t[1]:t?.y);return null==i||null==n?null:[i,n]};function uc(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=dc(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}if(t.length<3)return null;let i=0,n=0,r=0;for(let e=0;ee+t[0],0)/t.length,t.reduce((e,t)=>e+t[1],0)/t.length]:[n/(3*i),r/(3*i)]}function pc(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=dc(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}const i=uc(t);if(!i)return null;const n=t.map(e=>e[0]),r=t.map(e=>e[1]);return{centroid:i,bbox:[Math.min(...n),Math.min(...r),Math.max(...n),Math.max(...r)]}}function _c(e){let t=e;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;t=e.path??e.points??t}if(!Array.isArray(t)||!t.length)return[];let i=(t.some(e=>(e=>Array.isArray(e)?e.length>=2&&!Array.isArray(e[0])&&("object"!=typeof e[0]||null==e[0]):!!e&&"object"==typeof e&&("x"in e||"y"in e))(e))?[t]:t.filter(Array.isArray)).map(e=>e.map(dc).filter(e=>null!=e)).filter(e=>e.length>=2);i.length>64&&(i=i.slice(-64));const n=i.reduce((e,t)=>e+t.length,0);if(n<=4e3)return i.map(e=>e.slice());const r=4e3-2*i.length,o=i.map(e=>e.length-2),s=o.reduce((e,t)=>e+t,0),a=o.map(e=>r*e/s),l=a.map(Math.floor);let c=r-l.reduce((e,t)=>e+t,0);const h=a.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction||e.index-t.index);for(let e=0;efunction(e,t){if(t>=e.length)return e.slice();if(t<=2)return[e[0],e[e.length-1]];const i=[];for(let n=0;ne.slice()),i=t[t.length-1];return i?(i.length>2?i.pop():t.pop(),t):[]}const fc=e=>Number.isFinite(e[0])&&Number.isFinite(e[1]),vc=(e,t)=>e[0]===t[0]&&e[1]===t[1];function yc(e){if(!e)return null;const t=e.vacuum_position||e.robot_position||null,i=t&&null!=hc(t.x)&&null!=hc(t.y)?{x:hc(t.x),y:hc(t.y),a:hc(t.a??t.angle??t.theta)}:null,n=_c(e.path?.path??e.path?.points??e.path),r=[],o=e.rooms,s=Array.isArray(o)?o.map((e,t)=>[String(e?.id??t),e]):o&&"object"==typeof o?Object.entries(o):[];for(const[e,t]of s){if(!t||"object"!=typeof t)continue;const i=String(t.name??t.label??"").trim(),n=[[hc(t.cx),hc(t.cy)],[hc(t.center?.x),hc(t.center?.y)],[hc(t.x),hc(t.y)]].find(([e,t])=>null!=e&&null!=t);let o=n?.[0]??null,s=n?.[1]??null;const a=pc(t.outline),l=hc(t.x0),c=hc(t.y0),h=hc(t.x1),d=hc(t.y1),u=(null!=l&&null!=c&&null!=h&&null!=d?[Math.min(l,h),Math.min(c,d),Math.max(l,h),Math.max(c,d)]:null)||a?.bbox||null;if(null!=o&&null!=s||!a||([o,s]=a.centroid),null!=o&&null!=s||!u||(o=(u[0]+u[2])/2,s=(u[1]+u[3])/2),i&&null!=o&&null!=s){const t={id:e,name:i,cx:o,cy:s};u&&([t.x0,t.y0,t.x1,t.y1]=u),r.push(t)}}const a=function(e){return String(e.map_name??e.current_map??e.map_index??e.selected_map??"default")}(e);return i||r.length||n.length?{pos:i,path:n,rooms:r,mapId:a}:null}function bc(e,t,i){return![e,t,i].every(Number.isFinite)||e<0||t<=0||i<=0?Number.POSITIVE_INFINITY:e/t*i}const wc=40;function kc(e,t,i){if(!e||!t)return null;const n=t.attributes||{},r=e.split(".")[0]||"",o=null!=i?.platform?String(i.platform):null,s=!!dc(n.vacuum_position??n.robot_position),a=!(!n.rooms||"object"!=typeof n.rooms),l=_c(n.path?.path??n.path?.points??n.path).length>0,c=[n.map_name,n.current_map,n.map_index,n.selected_map].some(e=>null!=e),h="xiaomi_cloud_map_extractor"===o,d=a||l||c;let u=null;if(s?u="compatible":h?u="known_xcme_incomplete":d?u="partial":"camera"===r&&(u="camera"),!u)return null;const p=s?"camera"===r?300:200:h?100:d?50:0;return{entityId:e,name:String(n.friendly_name||e),platform:o,category:u,hasPosition:s,hasRooms:a,hasPath:l,hasMapId:c,score:p}}const xc=e=>e.toLowerCase().replace(/[\s_\-.,]+/g,"");function Sc(e,t){const i=new Set(t.map(xc).filter(Boolean)),n=new Set;for(const t of e){const e=xc(t.name||"");e&&i.has(e)&&n.add(e)}return n.size}function $c(e,t){const i=new Map(t.map(e=>[xc(e.name),e])),n=[],r=[];for(const t of e){const e=i.get(xc(t.name));e&&(n.push([[t.cx,t.cy],[e.cx,e.cy]]),r.push(t.name))}if(n.length<3)return null;const o=function(e){if(e.length<3)return null;let t=0,i=0,n=0,r=0,o=0,s=0,a=0,l=0,c=0,h=0,d=0,u=0;for(const[[p,_],[m,g]]of e){if(![p,_,m,g].every(Number.isFinite))return null;t+=p*p,i+=p*_,n+=p,r+=_*_,o+=_,s+=1,a+=p*m,l+=_*m,c+=m,h+=p*g,d+=_*g,u+=g}const p=[t,i,n,i,r,o,n,o,s],_=e=>{const[t,i,n,r,o,s,a,l,c]=p,h=t*(o*c-s*l)-i*(r*c-s*a)+n*(r*l-o*a);if(!Number.isFinite(h)||Math.abs(h)<1e-9)return null;const d=[(o*c-s*l)/h,(n*l-i*c)/h,(i*s-n*o)/h,(s*a-r*c)/h,(t*c-n*a)/h,(n*r-t*s)/h,(r*l-o*a)/h,(i*a-t*l)/h,(t*o-i*r)/h];return[d[0]*e[0]+d[1]*e[1]+d[2]*e[2],d[3]*e[0]+d[4]*e[1]+d[5]*e[2],d[6]*e[0]+d[7]*e[1]+d[8]*e[2]]},m=_([a,l,c]),g=_([h,d,u]);if(!m||!g)return null;const f=[m[0],m[1],m[2],g[0],g[1],g[2]];return f.every(Number.isFinite)?f:null}(n);return o?{matrix:o,matched:r,residual:cc(o,n)}:null}function Mc(e,t,i){const n=e[e.length-1];if(n&&n[0]===t[0]&&n[1]===t[1])return e;if(e.push(t),e.length<=600)return e;let r=function(e,t){if(e.length<3)return e.slice();const i=new Uint8Array(e.length);i[0]=i[e.length-1]=1;const n=[[0,e.length-1]];for(;n.length;){const[r,o]=n.pop(),[s,a]=e[r],[l,c]=e[o],h=l-s,d=c-a,u=Math.hypot(h,d)||1e-9;let p=0,_=-1;for(let t=r+1;tp&&(p=i,_=t)}_>0&&p>t&&(i[_]=1,n.push([r,_],[_,o]))}const r=[];for(let t=0;t600&&(r=r.filter((e,t)=>t%2==0||t===r.length-1)),r}function Rc(e){return"cleaning"===e||"returning"===e||"on"===e}const Cc={0:[1,0],90:[0,1],180:[-1,0],270:[0,-1]};function Tc(e){const[t,i]=Cc[e.rot]||[1,0],n=e.mir?-1:1;return[e.s*t*n,-e.s*i,e.ox,e.s*i*n,e.s*t,e.oy]}function Dc(e){const t=e[0]*e[4]-e[1]*e[3];if(!Number.isFinite(t)||Math.abs(t)<1e-12)return null;const i=t<0,n=Math.sqrt(Math.abs(t));let r=180*Math.atan2(-e[1],e[4])/Math.PI;return r=(90*Math.round(r/90)%360+360)%360,{ox:e[2],oy:e[5],s:n,rot:r,mir:i}}function Ac(e,t){const i=[],n=[];for(const t of e)null!=t.x0?(i.push(t.x0,t.x1),n.push(t.y0,t.y1)):(i.push(t.cx),n.push(t.cy));if(!i.length)return{ox:t[0]+t[2]/2,oy:t[1]+t[3]/2,s:t[2]/1e4,rot:0,mir:!0};const r=Math.min(...i),o=Math.max(...i),s=Math.min(...n),a=Math.max(...n),l=Math.max(o-r,a-s)||1,c={ox:0,oy:0,s:.6*Math.min(t[2],t[3])/l,rot:0,mir:!0},h=Tc(c),[d,u]=lc(h,(r+o)/2,(s+a)/2);return c.ox=t[0]+t[2]/2-d,c.oy=t[1]+t[3]/2-u,c}function Pc(e,t,i,n){const[r,o]=lc(Tc(t),i,n),s=Tc({...e,ox:0,oy:0}),[a,l]=lc(s,i,n);return{...e,ox:r-a,oy:o-l}}function Fc(e){const t=e?.trail_mode;return"never"===t||"cleaning"===t||"always"===t?t:!1===e?.trail?"never":"cleaning"}const zc=e=>"number"==typeof e&&Number.isFinite(e);function Ic(e){return Array.isArray(e)&&6===e.length&&e.every(zc)?[e[0],e[1],e[2],e[3],e[4],e[5]]:null}function Oc(e,t,i){return"legacy:"+e+" "+t+" "+i}function Ec(e,t,i,n){const r=t?.map_routes;if(Array.isArray(r))return r.filter(e=>e&&"string"==typeof e.id&&e.id).map(e=>({id:e.id,source:String(e.source??""),map_id:String(e.map_id??""),space:String(e.space??""),calibration:Ic(e.calibration)}));const o="string"==typeof t?.source&&t.source?t.source:n||"";if(!o)return[];const s=t?.calibration;if(!s||"object"!=typeof s)return[];const a=[];for(const t of Object.keys(s)){const n=Ic(s[t]);n&&a.push({id:Oc(e,o,t),source:o,map_id:t,space:i,calibration:n})}return a}const Nc=(e,t)=>e instanceof Map?e.get(t):e?.[t];function Hc(e){const t=[];let i=!1,n="",r="";for(const o of e.routes){const s=Nc(e.observed,o.source);void 0!==s&&(i=!0,n||(n=o.source,r=s),s===o.map_id&&t.push(o))}if(t.length>1)return{kind:"ambiguous",routeIds:t.map(e=>e.id).sort()};if(1===t.length){const i=t[0];if(e.spaceIds&&!e.spaceIds.has(i.space))return{kind:"missing_space",route:i};const n=Ic(i.calibration);return n?{kind:"ready",route:{...i,calibration:n}}:{kind:"needs_calibration",route:i}}if(i)return{kind:"unmapped",source:n,mapId:r};const o=e.observed instanceof Map?[...e.observed.entries()]:Object.entries(e.observed||{});if(o.length){const e=o.slice().sort((e,t)=>e[0].localeCompare(t[0]))[0];return{kind:"unmapped",source:e[0],mapId:e[1]}}return{kind:"none"}}function Lc(e,t,i){const n=new Set;for(const t of e)t.source&&n.add(t.source);for(const e of t)e&&n.add(e);const r={};for(const e of[...n].sort()){const t=i(e);void 0!==t&&(r[e]=t)}return r}function Bc(e,t,i){if(!e)return null;const n="string"==typeof e.route_id?e.route_id:"";if(n)return t.find(e=>e.id===n)||null;const r=function(e,t,i){if(!e||"string"!=typeof e.map_id)return{kind:"orphan_run"};const n=e.map_id,r="string"==typeof i?i:"";let o=t.filter(e=>e.map_id===n);return r&&(o=o.filter(e=>e.source===r)),1===o.length?{kind:"adopted",route:o[0]}:0===o.length?{kind:"orphan_run"}:{kind:"ambiguous_run",routeIds:o.map(e=>e.id).sort()}}(e,t,i);return"adopted"===r.kind?r.route:null}function qc(e){const t="ready"===e.resolution.kind?e.resolution.route:null,i=t&&t.space===e.renderSpace?Ic(t.calibration):null,n=Bc(e.serverCurrent,e.routes,e.rootSource),r=!!t&&!!n&&n.id===t.id,o=Bc(e.serverPrevious,e.routes,e.rootSource);return{live:i,currentRunMatches:r,previous:!!o&&o.space===e.renderSpace&&(e.explicitRoutes||!!t&&o.id===t.id)?Ic(o.calibration):null}}const jc={availability:"available",status:"alarm",activity:"none"},Wc=new Set(["motion","vibration","sound"]),Uc=new Set(["occupancy","presence"]),Vc=new Set(["door","window","garage_door","opening"]),Gc=new Set(["running","power"]),Kc=new Set(["smoke","gas","carbon_monoxide","moisture","safety","tamper","problem"]);const Yc=new Set(["running","working","washing","rinsing","spinning","drying","heating","cooling","cleaning","cooking","playing","recording","pumping","irrigating","humidifying","dehumidifying","fan","preheating","defrosting"]),Xc=new Set([...Yc,"start","started","run","active","in_progress","wash","rinse","spin","dry"]),Zc=new Set(["off","idle","paused","standby","docked","finished","complete","completed","stopped","ready","sleeping","stop","end","done","inactive"]),Jc=new Set(["heat","cool","heat_cool","auto","dry","fan_only"]),Qc=e=>""===e||"unknown"===e||"unavailable"===e||"__missing__"===e,eh=e=>String(e??"").trim().toLowerCase(),th=e=>eh(e).replace(/[\s-]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),ih=new Map([["run_state",0],["job_state",0],["operation_state",0],["activity_state",0],["machine_state",1],["running_state",1],["status",2],["device_status",2],["machine_status",2]]),nh=new Set(["wifi","connection","signal","battery"]);function rh(e,t){const i=e?.entities?.[t]||{};if("config"===i.entity_category)return null;const n=String(t||"").split(".").slice(1).join("."),r=[i.translation_key,i.original_name,i.name],o=[...r,n];r.some(e=>eh(e))||o.push(e?.states?.[t]?.attributes?.friendly_name);const s=o.map(th).filter(Boolean);if(s.some(e=>e.split("_").some(e=>nh.has(e))))return null;let a=null;for(const e of s)for(const[t,i]of ih)(e===t||e.endsWith(`_${t}`))&&(a=null==a?i:Math.min(a,i));return a}const oh=(e,t)=>null!=rh(e,t);function sh(e,t){if(!t.startsWith("switch."))return!1;const i=e?.entities?.[t]||{},n=e?.states?.[t],r=t.slice(7).toLowerCase();if(/(?:^|_)(?:main_)?power$/.test(r))return!0;if([i.translation_key,i.original_name,i.name].map(eh).some(e=>["power","main power","power switch","питание"].includes(e)))return!0;const o=eh(n?.attributes?.friendly_name);return/(?:^|[\s._-])(?:main[\s._-]+)?power$/.test(o)||/(?:^|[\s._-])питание$/.test(o)}function ah(e){for(const t of["hvac_action","action","current_operation","run_state","job_state","operation","activity"]){const i=eh(e?.[t]);if(Yc.has(i)||Zc.has(i))return i}return""}function lh(e,t){const i=e?.states?.[t],n=i?eh(i.state):"__missing__",r=String(t||"").split(".")[0],o=eh(i?.attributes?.device_class),s={eid:t,state:n,availability:Qc(n)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===s.availability)return s;if(function(e,t,i){return"alarm_control_panel"===e?"triggered"===i:"on"===i&&jn(e,t)}(r,o,n))return{...s,status:"alarm"};if("binary_sensor"===r)return Wc.has(o)?{...s,edge:"rising"}:Uc.has(o)?{...s,activity:"on"===n?"presence":"none"}:Vc.has(o)?{...s,status:"on"===n?"open":"neutral",edge:"rising"}:"moving"===o?{...s,activity:"on"===n?"transition":"none"}:Gc.has(o)&&"on"===n?{...s,status:"working",activity:"running"}:s;if("cover"===r)return{...s,activity:"opening"===n||"closing"===n?"transition":"none",edge:"terminal_transition"};if("lock"===r)return{...s,status:"unlocked"===n||"open"===n?"open":"neutral",activity:"locking"===n||"unlocking"===n?"transition":"none",edge:"terminal_transition"};if("valve"===r)return{...s,status:["open","opening","closing"].includes(n)?"open":"neutral",activity:"opening"===n||"closing"===n?"transition":"none",edge:"terminal_transition"};if("climate"===r){const e=ah(i.attributes),t=Array.isArray(i.attributes?.hvac_modes)?i.attributes.hvac_modes.map(eh):[],r=!Zc.has(n)&&(Jc.has(n)||Yc.has(n)||t.includes(n));return(e?Yc.has(e):r)?{...s,status:"working",activity:"running"}:s}if(["light","switch","fan","humidifier"].includes(r))return"on"===n?{...s,status:"working",activity:"running"}:s;if("media_player"===r)return"off"===n?{...s,availability:"unavailable"}:s;if("vacuum"===r)return"cleaning"===n?{...s,status:"working",activity:"running"}:"returning"===n?{...s,status:"working",activity:"transition"}:s;if("script"===r)return"on"===n?{...s,status:"working",activity:"running"}:s;if("automation"===r)return s;if("button"===r||"event"===r)return{...s,edge:"change"};const a=ah(i.attributes);return Yc.has(a)||Yc.has(n)&&!Zc.has(n)?{...s,status:"working",activity:"running"}:s}function ch(e,t,i){const n=i.filter(t=>t.startsWith("switch.")&&!e?.entities?.[t]?.entity_category),r=t.find(t=>sh(e,t));if(!(n.length>1&&!!r))return t.map(t=>lh(e,t));const o=t.find(t=>t!==r&&oh(e,t)),s=lh(e,r);return"unavailable"===s.availability||"off"===s.state?t.map(t=>({eid:t,state:e?.states?.[t]?eh(e.states[t].state):"__missing__",availability:"unavailable",status:"neutral",activity:"none",edge:"none"})):t.map(t=>{if(t===o)return function(e,t){const i=e?.states?.[t],n=i?eh(i.state):"__missing__",r={eid:t,state:n,availability:Qc(n)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===r.availability)return r;const o=ah(i?.attributes);return Yc.has(o)||Xc.has(n)&&!Zc.has(n)?{...r,status:"working",activity:"running"}:r}(e,t);return{...t===r?s:lh(e,t),status:"neutral",activity:"none",edge:"none"}})}function hh(e){if(!e.length)return{availability:"available",status:"neutral",activity:"none"};const t=e.filter(e=>"available"===e.availability);if(!t.length)return{availability:"unavailable",status:"neutral",activity:"none"};if(t.some(e=>"alarm"===e.status))return jc;const i=t.some(e=>"working"===e.status)?"working":t.some(e=>"open"===e.status)?"open":"neutral",n=t.some(e=>"transition"===e.activity)?"transition":t.some(e=>"presence"===e.activity)?"presence":t.some(e=>"running"===e.activity)?"running":"none";return{availability:"available",status:i,activity:n}}function dh(e,t){if(!(e=>!!e&&!Qc(e))(e)||"unavailable"===t.availability||e===t.state)return null;if("rising"===t.edge)return"off"===e&&"on"===t.state?"event":null;if("change"===t.edge)return"event";if("terminal_transition"===t.edge){const i=new Set([e,t.state]);if(i.has("closed")&&i.has("open")||i.has("locked")&&i.has("unlocked"))return"transition"}return null}const uh=(e,t=0)=>{const i=Number(e);return Number.isInteger(i)&&i>=0?i:t},ph=(e,t)=>{const i={rev:0,configRev:uh(t),off:new Set};if(null==e)return{snapshot:i,valid:!1};const n=e.off;return!Number.isInteger(e.rev)||Number(e.rev)<0||!Number.isInteger(e.config_rev)||Number(e.config_rev)<0||!Array.isArray(n)||n.some(e=>"string"!=typeof e||!e)?{snapshot:i,valid:!1}:{snapshot:{rev:Number(e.rev),configRev:Number(e.config_rev),off:new Set(n)},valid:!0}};function _h(e,t=0){return ph(e,t).snapshot}function mh(e,t,i,n){const r=ph(t,i);return n&&r.valid&&r.snapshot.configRev===i?e.configRev===i&&r.snapshot.rev{try{const[i,n]=await Promise.all([e.callWS({type:"config/device_registry/list"}),e.callWS({type:"config/entity_registry/list"})]),r=Rh(i,"id"),o=Rh(n,"entity_id");if(!r||!o)throw new Error("invalid_registry_response");t.devices=r,t.entities=o,t.authoritative=!0,t.access="full",t.lastSuccess=Date.now(),t.error=void 0}catch(e){t.authoritative=!1,t.access="limited",t.error=function(e){if(e&&"object"==typeof e){const t=e;return String(t.message||t.code||t.error||"registry_unavailable")}return String(e||"registry_unavailable")}(e)}finally{t.revision++,t.loading=void 0,function(e){for(const t of[...e.listeners])try{t()}catch{}}(t)}})()),t.loading}function Th(e,t){void 0===t.reloadTimer&&(t.reloadTimer=globalThis.setTimeout(()=>{t.reloadTimer=void 0,Ch(e,t)},80))}async function Dh(e,t){if(t.subscribing||t.unsubDevice&&t.unsubEntity)return t.subscribing;const i=e?.connection?.subscribeEvents;return"function"==typeof i?(t.subscribing=(async()=>{try{t.unsubDevice||(t.unsubDevice=await i.call(e.connection,()=>Th(e,t),"device_registry_updated")),t.unsubEntity||(t.unsubEntity=await i.call(e.connection,()=>Th(e,t),"entity_registry_updated"))}catch{}finally{0===t.refs&&(t.unsubDevice?.(),t.unsubEntity?.(),t.unsubDevice=void 0,t.unsubEntity=void 0),t.subscribing=void 0}})(),t.subscribing):void 0}function Ah(e,t){const i=Mh(e);if(!i)return()=>{};const n=0===i.refs;i.refs++,i.listeners.add(t),("pending"===i.access||n)&&Ch(e,i),Dh(e,i);let r=!1;return()=>{r||(r=!0,i.listeners.delete(t),i.refs=Math.max(0,i.refs-1),i.refs>0||(i.unsubDevice?.(),i.unsubEntity?.(),i.unsubDevice=void 0,i.unsubEntity=void 0,void 0!==i.reloadTimer&&globalThis.clearTimeout(i.reloadTimer),i.reloadTimer=void 0))}}function Ph(e){const t=Mh(e);t&&(Th(e,t),Dh(e,t))}function Fh(e){const t=Mh(e);if(!t)return{revision:0,authoritative:!1,access:"limited",devices:e?.devices||{},entities:e?.entities||{},lastSuccess:0,error:"registry_unavailable"};let i=e?.devices||{},n=e?.entities||{};if(t.authoritative){const r=t.liveDevices!==i||t.liveEntities!==n,o=void 0!==t.liveDevices||void 0!==t.liveEntities;if(r&&(t.liveDevices=i,t.liveEntities=n,t.projectedRevision=void 0,o&&Th(e,t)),t.projectedRevision!==t.revision||!t.projectedDevices||!t.projectedEntities){const e={...t.devices},r={...t.entities};for(const[t,n]of Object.entries(i))Object.prototype.hasOwnProperty.call(e,t)||(e[t]=n);for(const[e,t]of Object.entries(n))Object.prototype.hasOwnProperty.call(r,e)||(r[e]=t);t.projectedDevices=e,t.projectedEntities=r,t.projectedRevision=t.revision}i=t.projectedDevices,n=t.projectedEntities}return{revision:t.revision,authoritative:t.authoritative,access:t.access,devices:i,entities:n,lastSuccess:t.lastSuccess,error:t.error}}function zh(e){if(!e||"object"!=typeof e&&"function"!=typeof e)return 0;let t=kh.get(e);return t||(t=xh++,kh.set(e,t)),t}function Ih(e,t=Fh(e)){return[t.revision,t.access,zh(t.devices),zh(t.entities)].join(":")}function Oh(e){return!!e&&null==e.disabled_by}function Eh(e,t=Fh(e)){const i={},n={},r={};for(const[e,n]of Object.entries(t.devices||{}))Oh(n)&&(i[e]=n);for(const[e,i]of Object.entries(t.entities||{})){if(!Oh(i))continue;const r=i.device_id?t.devices?.[i.device_id]:null;t.authoritative&&i.device_id&&!r||(r&&!Oh(r)||(n[e]=i))}for(const[i,n]of Object.entries(e?.states||{})){const e=t.entities?.[i];if(e&&!Oh(e))continue;const o=e?.device_id?t.devices?.[e.device_id]:null;t.authoritative&&e?.device_id&&!o||(o&&!Oh(o)||(r[i]=n))}return{...e,devices:i,entities:n,states:r}}function Nh(e,t=Fh(e)){return{...e,devices:t.devices||{},entities:t.entities||{}}}function Hh(e,t){const i=[];for(const[n,r]of Object.entries(e||{}))r?.device_id===t&&i.push(n);return i}function Lh(){if($h)return $h;if("undefined"==typeof localStorage)return{};try{const e=JSON.parse(localStorage.getItem(Sh)||"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=Date.now(),i={};for(const[n,r]of Object.entries(e))!r||"active"!==r.kind&&"ha_disabled"!==r.kind||!Number.isFinite(r.ts)||t-r.ts>7776e6||(i[n]=r);return $h=i,$h}catch{return{}}}function Bh(e,t,i=Fh(e)){if(!t||"virtual"===t)return{kind:"active",enabledEntityIds:[],allEntityIds:[]};const n=t.indexOf(":");if(n<1)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const r=t.slice(0,n),o=t.slice(n+1);if("device"!==r&&"entity"!==r||!o)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const s=i.devices||{},a=i.entities||{};if(i.authoritative){if("device"===r){const e=s[o];if(!e)return{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[]};const t=Hh(a,o);if(!Oh(e))return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:t};const i=t.filter(e=>Oh(a[e]));return t.length&&!i.length?{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:t}:{kind:"active",enabledEntityIds:i,allEntityIds:t}}const t=a[o];return t&&!Oh(t)?{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!s[t.device_id]?{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!Oh(s[t.device_id])?{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]}:t||e?.states?.[o]?{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}:{kind:"orphaned",reason:"entity_missing",enabledEntityIds:[],allEntityIds:[]}}const l=function(e){return Lh()[e]||null}(t);if("device"===r){const t=s[o],i=Hh(a,o);if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:i};const n=i.filter(e=>{const t=a[e];return null==t?.disabled_by&&(!t.device_id||null==s[t.device_id]?.disabled_by)});if(i.length&&!n.length&&i.every(e=>null!=a[e]?.disabled_by))return{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:i};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"device",enabledEntityIds:[],allEntityIds:i};if(t||n.some(t=>!!e?.states?.[t]))return{kind:"active",enabledEntityIds:n,allEntityIds:i}}else{const t=a[o];if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]};if(t?.device_id&&null!=s[t.device_id]?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"entity",enabledEntityIds:[],allEntityIds:[o]};if(t||e?.states?.[o])return{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}}return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]}}function qh(e){const t=Fh(e);return{access:t.access,authoritative:t.authoritative,revision:t.revision,lastSuccess:t.lastSuccess,error:t.error}}function jh(e){const t={};for(const[i,n]of Object.entries(e.entities)){if(!n?.device_id||!Oh(n))continue;const r=e.devices?.[n.device_id];r&&!Oh(r)||(t[n.device_id]=t[n.device_id]||[]).push(i)}return t}function Wh(e,t){const i=new Map;for(const n of e){if(!0===n?.removed)continue;const e=n?.binding||"";if(!e.startsWith("entity:"))continue;const r=e.slice(7);if(!r)continue;const o=t?.entities?.[r]?.device_id;if(!o)continue;const s=i.get(o)||new Set;s.add(r),i.set(o,s)}return{byDevice:i}}function Uh(e,t,i,n){const r=n.byDevice.get(t);return r?.size?{partial:!0,entityIds:i.filter(t=>!r.has(t)&&!e?.entities?.[t]?.hidden)}:{partial:!1,entityIds:[...i]}}function Vh(e,t,i){if(t.identifiers?.[0]?.[0])return t.identifiers[0][0];for(const t of i){const i=e.entities[t]?.platform;if(i)return i}return""}function Gh(e,t){if(/_device_temperature$/.test(t))return!1;if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_temperature$/.test(t);const n=i.attributes||{};return"temperature"===n.device_class||/°C|°F/.test(n.unit_of_measurement||"")||/_temperature$/.test(t)}const Kh=["vacuum","lawn_mower","climate","media_player","light","cover","lock","valve","alarm_control_panel","water_heater","fan","humidifier","siren","camera","remote"],Yh=e=>[...e.filter(e=>!e.reg?.hidden),...e.filter(e=>!!e.reg?.hidden)];function Xh(e,t){const i=t.map(t=>({eid:t,reg:e?.entities?.[t]})).filter(e=>!!e.reg);if(!i.length)return[];const n=i.filter(e=>!e.reg.entity_category),r=n.length?n:i;for(const e of Kh){const t=r.filter(t=>t.eid.startsWith(e+"."));if(t.length)return Yh(t).map(e=>e.eid)}const o=r.filter(t=>function(e,t){if(!t.startsWith("binary_sensor."))return!1;const i=eh(e?.states?.[t]?.attributes?.device_class||e?.entities?.[t]?.device_class||e?.entities?.[t]?.original_device_class);return Wc.has(i)||Uc.has(i)||Vc.has(i)||Gc.has(i)||"moving"===i||Kc.has(i)}(e,t.eid));if(o.length)return Yh(o).map(e=>e.eid);const s=r.filter(e=>e.eid.startsWith("switch."));if(s.length){const t=Yh(s),n=t.find(t=>sh(e,t.eid));if(s.length>1&&n){const t=i.filter(t=>t.eid!==n.eid&&"config"!==t.reg?.entity_category&&null!=rh(e,t.eid)),r=t.filter(e=>!e.reg?.entity_category),o=r.length?r:t;for(const t of[0,1,2]){const i=Yh(o.filter(i=>rh(e,i.eid)===t));if(i.length)return[i[0].eid,n.eid]}}return[(n||t[0]).eid]}const a=[];for(const e of Le)a.push(...Yh(r.filter(t=>t.eid.startsWith(e+"."))));return a.push(...Yh(r.filter(e=>!Le.includes(e.eid.split(".")[0])))),a.map(e=>e.eid)}function Zh(e,t,i){const n=t.map(t=>({eid:t,reg:e.entities[t],st:e.states[t]})).filter(e=>e.reg),r=[n.filter(e=>!e.reg.hidden&&!e.reg.entity_category),n.filter(e=>!e.reg.entity_category),n.filter(e=>!e.reg.hidden),n];if("mdi:thermometer"===i||"mdi:air-filter"===i)for(const t of r){const i=t.find(t=>Gh(e,t.eid));if(i)return i.eid}const o=Xh(e,t);return o.find(Mn)||o[0]}function Jh(e,t,i=[]){return[...new Set(Qh(e,t,i))].filter(e=>Mn(e))}function Qh(e,t,i=[]){const n=e?.startsWith("entity:")?new Set([e.slice(7)]):new Set(i);return(t||[]).filter(e=>"string"==typeof e&&!n.has(e))}function ed(e,t){if("string"==typeof t)return e.area===t;const i=e.marker?.room_id;return i?!!t.id&&i===t.id:!!t.area&&e.area===t.area}function td(e){const t=e.marker?.binding?.startsWith("entity:")?e.marker.binding.slice(7):null,i=e.entities.filter(Mn),n=e.primary&&Mn(e.primary)?e.primary:null;return[...new Set([t,n,...i].filter(e=>!!e&&Mn(e)))]}function id(e){const t=td(e),i=e.marker?.light_entity;return i&&t.includes(i)?i:t[0]||null}function nd(e,t){if(!1===t.marker?.is_light)return[];if(!0===t.marker?.is_light){return[{eid:id(t),via:"forced"}]}const i=t.primary||Xh(e,t.entities)[0];return i&&!i.startsWith("light.")?[]:t.entities.filter(t=>t.startsWith("light.")&&!!e.states?.[t]).map(e=>({eid:e,via:"light"}))}const rd=new WeakMap,od=new WeakMap;function sd(e){return e.map(e=>[e.id||"",!0===e.hidden?1:0,e.primary||"",[...e.entities].join(","),void 0===e.controls?"":[...e.controls].join(","),e.marker?.id||"",e.marker?.binding||"",e.marker?.is_light,e.marker?.tap_action||"",!0===e.marker?.removed?1:0,e.marker?.light_entity||"",null==e.marker?.controls?"":[...e.marker.controls].join(",")].join("")).join("")}function ad(e){const t=sd(e),i=rd.get(e);if(i?.fingerprint===t)return i;const n=e.filter(e=>!e.hidden),r=new Map,o=new Map;for(const t of e){o.set(t,Qh(t.marker?.binding,t.marker?.controls??t.controls,t.entities));const e=t.hidden||!0!==t.marker?.is_light?null:t.marker?.id||t.id;e&&r.set(String(e),t)}const s=new Map;for(const t of e){const e=o.get(t)||[],i=new Set(void 0===t.controls?e.filter(Mn):t.controls.filter(Mn)),n=id(t),a=i.size?[...i]:n?[n]:[];for(const i of e){if(!i.startsWith("marker:"))continue;const e=i.slice(7);if(!e||e===String(t.marker?.id||t.id||""))continue;if(!r.has(e))continue;const n=s.get(e)||{markerId:e,controllers:[],driverEids:[]};n.controllers.push({device:t,driverEids:[...a]}),n.driverEids=[...new Set([...n.driverEids,...a])],s.set(e,n)}}const a={fingerprint:t,visible:n,markerById:r,persistedByDevice:o,incomingByMarker:s};return rd.set(e,a),a}function ld(e){return ad(e).incomingByMarker}function cd(e,t){const i=Jh(t.marker?.binding,t.controls??t.marker?.controls,t.entities),n=Qh(t.marker?.binding,t.marker?.controls??t.controls,t.entities);return(null!=t.marker?.is_light||!i.length&&!n.some(e=>e.startsWith("marker:")))&&nd(e,t).length>0}function hd(e,t){return nd(e,t).some(e=>!!e.eid)}function dd(e,t,i,n){const r="always"===e||"auto"===e&&t,o=r&&!i;return{sourceExists:r,fromSourceEnabled:r&&i,manualEnabled:r,radiusEnabled:r,passive:o,effectiveMode:o&&"auto"===n?"fixed":n}}function ud(e,t){const i=Jh(t.marker?.binding,t.controls??t.marker?.controls,t.entities).map(e=>({eid:e,via:"controls"})),n=cd(e,t)?nd(e,t):[];for(const e of n)e.eid&&i.some(t=>t.eid===e.eid)||i.push(e);return i}function pd(e,t,i,n){if(null!=i)return pd(e,t,null,n).filter(e=>ed(e.device,i));const r=sd(t),o=function(e,t){const i=new Set;for(const e of t){for(const t of e.entities)i.add(t);for(const t of e.controls||e.marker?.controls||[])"string"!=typeof t||t.startsWith("marker:")||i.add(t)}return[...i].sort().map(t=>`${t}:${e?.states?.[t]?.state??""}`).join("|")}(e,t),s=fh(n),a=od.get(t);if(a?.graphFingerprint===r&&a.stateFingerprint===o&&a.virtualLightFingerprint===s&&a.registry===e?.entities)return a.sources;const{visible:l,markerById:c,persistedByDevice:h,incomingByMarker:d}=ad(t),u=null==i?l:l.filter(e=>ed(e,i)),p=new Map,_=new Map;for(const t of u){const i=ud(e,t).filter(e=>"controls"!==e.via);for(const n of i){const i=!0===t.marker?.is_light?String(t.marker?.id||t.id||""):"",r=i?`marker:${i}`:`entity:${n.eid}`,o=n.eid?[n.eid]:[],s={key:r,eid:n.eid||"",stateEids:o,serviceEids:o,device:t,via:n.via,castsGlow:!0,passive:!n.eid,on:!n.eid||"on"===e.states?.[n.eid]?.state};p.set(t,[...p.get(t)||[],s]),n.eid&&_.set(n.eid,s)}}const m=new Map;for(const e of t){const t=h.get(e)||[],i=new Set(void 0===e.controls?t.filter(Mn):e.controls);m.set(e,i)}for(const t of p.values())for(const i of t){if(!i.passive)continue;const t=i.key.slice(7),r=d.get(t);i.on=!r||r.driverEids.some(t=>"on"===e.states?.[t]?.state),!r&&vh(i.device.marker)&&(i.on=yh(i.device.marker,n))}const g=new Map,f=e=>{const t=g.get(e.key);(!t||e.castsGlow&&!t.castsGlow)&&g.set(e.key,e)};for(const t of l){const n=h.get(t)||[],r=null==i||ed(t,i);for(const i of n){if(i.startsWith("marker:")){const e=c.get(i.slice(7)),t=e?p.get(e):null;if(t)for(const e of t)f(e);continue}if(!Mn(i)||!m.get(t)?.has(i))continue;const n=_.get(i);n?f(n):r&&f({key:`entity:${i}`,eid:i,stateEids:[i],serviceEids:[i],device:t,via:"controls",castsGlow:!1,passive:!1,on:"on"===e.states?.[i]?.state})}for(const e of p.get(t)||[])f(e)}const v=[...g.values()];return od.set(t,{graphFingerprint:r,stateFingerprint:o,virtualLightFingerprint:s,registry:e?.entities,sources:v}),v}function _d(e){const t=e.filter(e=>e.castsGlow);return t.find(e=>e.on)||t[0]||null}function md(e){return e.length?e.some(e=>e.on)?"on":"off":"none"}function gd(e,t){const i=[];for(const n of t){const t=e.states[n];if(!t)continue;const r=(t.attributes?.unit_of_measurement||"").toLowerCase();if(/_(linkquality|lqi)$/.test(n)||"lqi"===r){const e=parseFloat(t.state);isNaN(e)||i.push(e);continue}const o=t.attributes?.linkquality??t.attributes?.lqi;if(null!=o){const e=parseFloat(o);isNaN(e)||i.push(e)}}return Pi(i)}function fd(e,t){for(const i of t){if(!Gh(e,i))continue;const t=e.states[i];if(!t)continue;const n=parseFloat(t.state);if(!isNaN(n))return Math.round(10*n)/10}return null}function vd(e,t){for(const i of t){if(!i.startsWith("climate."))continue;const t=e.states[i];if(!t||"unavailable"===t.state||"unknown"===t.state)continue;const n=parseFloat(t.attributes?.current_temperature);if(Number.isFinite(n))return Math.round(10*n)/10}return null}function yd(e,t){if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_humidity$/.test(t);const n=i.attributes||{};return"humidity"===n.device_class||"%"===n.unit_of_measurement&&/_humidity$/.test(t)||/_humidity$/.test(t)}function bd(e,t){for(const i of t){if(!yd(e,i))continue;const t=e.states[i];if(!t)continue;const n=parseFloat(t.state);if(!isNaN(n))return Math.round(n)}return null}function wd(e,t){if(!t)return[];const i=[];for(const[t,n]of Object.entries(e.entities)){if(!t.startsWith("light.")||n.hidden||!Oh(n))continue;let r=null;if("group"===n.platform)r=n.area_id||null;else{if(!n.device_id)continue;{const t=e.devices[n.device_id];if(!Oh(t))continue;if("Group"!==t?.model)continue;r=t.area_id||n.area_id||null}}if(!r)continue;const o=e.states[t];i.push({eid:t,name:n.name||o?.attributes?.friendly_name||t,area:r})}return i}function kd(e,t,i,n,r){const o=He(t,i,r);if(o!==Ne)return o;const s=[];for(const t of n){const i=e.states[t]?.attributes?.device_class;i&&s.push(i)}return function(e){for(const t of e){const e=Ee[t];if(e)return e}return null}(s)??Ne}function xd(e,t){return e.map(e=>{if(!Array.isArray(e.controls))return e;const i=e.controls.filter(e=>!("string"==typeof e&&e.startsWith("marker:")&&t.has(e.slice(7))));return i.length===e.controls.length?e:{...e,controls:i.length?i:null}})}function Sd(e,t,i){if(!t||!i||t===i)return[...e];const n=`marker:${t}`,r=`marker:${i}`;return e.map(e=>{const t=Array.isArray(e.controls)?e.controls.map(e=>e===n?r:e):e.controls,i="derived_marker_state"===e.value_badge?.source?.kind&&e.value_badge.source.ref===n?{...e.value_badge,source:{...e.value_badge.source,ref:r}}:e.value_badge,o="derived_marker_state"===e.value_source?.kind&&e.value_source.ref===n?{...e.value_source,ref:r}:e.value_source;return t===e.controls&&i===e.value_badge&&o===e.value_source?e:{...e,controls:t,...void 0!==i?{value_badge:i}:{},...void 0!==o?{value_source:o}:{}}})}function $d(e,t,i){if(!t||t===i)return!0;const n=new Map;for(const t of e)n.set(t.id,(t.controls||[]).filter(e=>"string"==typeof e&&e.startsWith("marker:")).map(e=>e.slice(7)));const r=new Set,o=[i];for(;o.length;){const e=o.pop();if(e===t)return!0;r.has(e)||(r.add(e),o.push(...n.get(e)||[]))}return!1}function Md(e,t,i,n){const r=new Set([t]),o=e.filter(e=>{const o=e.id===t||!n&&e.binding===i;return o&&r.add(e.id),!o});return{markers:n?o:[...o,{id:t,binding:i,removed:!0,hidden:!0}],cleanupIds:r}}function Rd(e){const t=new Set,i=new Set,n=new Set;for(const r of e||[]){const e=String(r.binding||"").indexOf(":");if(e<1)continue;const o=r.binding.slice(0,e),s=r.binding.slice(e+1);s&&(!0===r?.removed?"device"===o?t.add(s):"entity"===o&&i.add(s):"entity"===o&&n.add(s))}return{devices:t,entities:i,liveEntities:n}}function Cd(e,t,i){if(i.liveEntities.has(t))return!1;if(i.entities.has(t))return!0;const n=e?.entities?.[t]?.device_id;return!!n&&i.devices.has(n)}function Td(e,t,i,n,r){const o=Jh(t.binding,t.controls,e.entities).filter(e=>!Cd(i,e,n)).filter(e=>"active"===Bh(i,"entity:"+e,r).kind);e.marker=t,e.controls=o,e.userHidden=!0===t.hidden,e.hidden=e.userHidden||"ha_disabled"===e.bindingStatus?.kind,t.name&&(e.name=t.name),t.icon&&(e.icon=t.icon),null!=t.model&&(e.model=t.model),e.link=t.link??null,e.description=t.description??null,e.pdfs=t.pdfs||[],e.tapAction=t.tap_action??null}function Dd(e){const t=e.hass,i=e.registry||Fh(t),n=Eh(t,i),r=Nh(t,i),{areaToSpace:o,markers:s,settings:a,excluded:l,iconRules:c}=e,h=!1!==a.group_lights,d=Rd(s),u=wd(n,h).filter(e=>!Cd(n,e.eid,d)),p=new Set(u.map(e=>e.area)),_=jh(n),m=Wh(s,r),g=new Set(s.map(e=>e.binding)),f=[];for(const e of Object.values(n.devices)){const r=e.area_id;if(!r||!o[r])continue;if("service"===e.entry_type)continue;if(g.has("device:"+e.id))continue;if("active"!==Bh(t,"device:"+e.id,i).kind)continue;const s=Uh(n,e.id,_[e.id]||[],m);if(s.partial&&!s.entityIds.length)continue;const a=s.entityIds,d=Vh(n,e,a);let u=l.has(d)||"Group"===e.model||/scene/i.test(e.model||"")||/bridge/i.test((e.model||"")+(e.name||""))||"myheat"===d&&!!e.via_device_id;if(!u&&h&&p.has(r)){const t=(e.name_by_user||e.name||"").trim();"mdi:lightbulb"===kd(n,t,e.model,a,c)&&(u=!0)}u&&f.push("device:"+e.id)}return f}function Ad(e,t,i,n){if("string"==typeof e.room_id&&e.room_id.length>0&&null===e.area)return{area:"",space:e.space||n};const r=e.area||t||"";return{area:r,space:r&&i[r]||e.space||n}}function Pd(e){const t=e.hass,i=e.registry||Fh(t),n=Eh(t,i),r=Nh(t,i),{areaToSpace:o,markers:s,settings:a,excluded:l,showAll:c,firstSpaceId:h,loc:d,iconRules:u}=e,p=!1!==a.group_lights,_=Rd(s),m=wd(n,p).filter(e=>!Cd(n,e.eid,_)),g=new Set(m.map(e=>e.area)),f=jh(n),v=function(e){const t={};for(const[i,n]of Object.entries(e.entities||{}))n?.device_id&&(t[n.device_id]=t[n.device_id]||[]).push(i);return t}(r),y=Wh(s,r),b=new Set;for(const e of s){const[t,i]=e.binding.split(":");"device"!==t&&"entity"!==t||!i||b.add(e.binding)}const w=(e,t)=>s.find(i=>i.binding===e+":"+t),k={},x=[];for(const e of Object.values(n.devices)){const r=e.area_id;if(!r||!o[r])continue;if("service"===e.entry_type)continue;if(b.has("device:"+e.id))continue;const s=Bh(t,"device:"+e.id,i);if("active"!==s.kind)continue;const h=w("device",e.id);if(h&&h.hidden&&!a.filter_seeded)continue;const _=Uh(n,e.id,f[e.id]||[],y);if(_.partial&&!_.entityIds.length)continue;const m=_.entityIds,v=_.partial?{kind:"active",enabledEntityIds:m,allEntityIds:m}:s,S=Vh(n,e,m),$=!a.filter_seeded;if($&&!c){if(l.has(S))continue;if("Group"===e.model)continue;if(/scene/i.test(e.model||""))continue;if(/bridge/i.test((e.model||"")+(e.name||"")))continue;if("myheat"===S&&e.via_device_id)continue}const M=(e.name_by_user||e.name||d("device.unnamed")).trim(),R=M+"|"+r;let C=kd(n,M,e.model,m,u);if(m.some(e=>e.startsWith("lock."))&&(C="mdi:lock"),$&&!c&&p&&"mdi:lightbulb"===C&&g.has(r))continue;k[R]=(k[R]||0)+1;const T=k[R]>1?M+" "+k[R]:M,D={id:e.id,name:T,model:e.model||"",area:r,space:o[r],icon:C,entities:m,allEntities:v.allEntityIds,bindingStatus:v,bindingKind:"device",bindingRef:e.id,pdfs:[]};D.primary=Zh(n,m,C),"mdi:thermometer"!==C&&"mdi:air-filter"!==C||(D.temp=fd(n,m)),D.primary&&yd(n,D.primary)&&(D.hum=bd(n,m)),x.push(D)}for(const e of m)o[e.area]&&(b.has("entity:"+e.eid)||x.push({id:"lg_"+e.eid,name:e.name,model:d("device.light_group"),area:e.area,space:o[e.area],icon:"mdi:lightbulb-group",entities:[e.eid],allEntities:[e.eid],bindingStatus:{kind:"active",enabledEntityIds:[e.eid],allEntityIds:[e.eid]},primary:e.eid,bindingKind:"entity",bindingRef:e.eid,pdfs:[]}));for(const e of s){if(e.removed)continue;const[s,l]=e.binding.split(":"),c="device"===s||"entity"===s?Bh(t,e.binding,i):null;if(!e.hidden||a.filter_seeded||"ha_disabled"===c?.kind)if("device"===s){const t=c;if("unverified"===t.kind)continue;const s=r.devices[l],{area:a,space:p}=Ad(e,s?.area_id,o,h),m="active"===t.kind?t.enabledEntityIds:[];let g=s?kd(n,s.name_by_user||s.name||"",s.model,m,u):"mdi:help-circle";m.some(e=>e.startsWith("lock."))&&(g="mdi:lock");const f={id:e.id,name:s?.name_by_user||s?.name||d("device.fallback"),model:s?.model||"",area:a,space:p,icon:g,entities:m,allEntities:t.allEntityIds.length?t.allEntityIds:s&&v[s.id]||[],bindingStatus:t,bindingKind:"device",bindingRef:l};f.primary=Zh(n,m,g),"mdi:thermometer"!==g&&"mdi:air-filter"!==g||(f.temp=fd(n,m)),f.primary&&yd(n,f.primary)&&(f.hum=bd(n,m)),Td(f,e,r,_,i),x.push(f)}else if("entity"===s){if(Cd(r,l,_))continue;const t=c;if("unverified"===t.kind)continue;const s=r.entities[l],a=s?.area_id||s?.device_id&&r.devices[s.device_id]?.area_id||"",{area:d,space:p}=Ad(e,a,o,h),m=n.states[l],g=s?.name||m?.attributes?.friendly_name||l;let f=kd(n,g,"",[l],u);l.startsWith("lock.")&&(f="mdi:lock");const v={id:e.id,name:g,model:"",area:d,space:p,icon:f,entities:"active"===t.kind?[l]:[],allEntities:[l],bindingStatus:t,primary:"active"===t.kind?l:void 0,bindingKind:"entity",bindingRef:l};"mdi:thermometer"!==f&&"mdi:air-filter"!==f||!v.entities.length||(v.temp=fd(n,v.entities)),v.entities.length&&yd(n,l)&&(v.hum=bd(n,v.entities)),Td(v,e,r,_,i),x.push(v)}else{const t=e.area||"",n=e.space||t&&o[t]||h,s={id:e.id,name:e.name||d("device.virtual"),model:e.model||"",area:t,space:n,icon:e.icon||"mdi:map-marker",entities:[],allEntities:[],bindingStatus:{kind:"active",enabledEntityIds:[],allEntityIds:[]},bindingKind:"virtual",virtual:!0};Td(s,e,r,_,i),x.push(s)}}return x}function Fd(e){const{marker:t,siblingMarkers:i=[],...n}=e;return Pd({...n,markers:[...i.filter(e=>e.id!==t.id),t]}).find(e=>e.id===t.id)||null}function zd(e,t,i,n){if(!t)return null;if(function(e,t,i){if(!t)return!1;const n=t.indexOf(":");if(n<1)return!1;const r=t.slice(0,n),o=t.slice(n+1),s=Rd(i);return"device"===r?s.devices.has(o):"entity"===r&&Cd(e,o,s)}(e,t,n))return null;const r=t.indexOf(":");if(r<0)return null;const o=t.slice(0,r),s=t.slice(r+1);if(!s)return null;if("entity"===o){const t=parseFloat(e.states[s]?.state);return Number.isFinite(t)?"temp"===i?Math.round(10*t)/10:Math.round(t):null}if("device"===o){const t=Object.entries(e.entities).filter(([,e])=>e.device_id===s).map(([e])=>e);return"temp"===i?fd(e,t):bd(e,t)}return null}const Id=new RegExp(["water","voda","coolant","flow_?temp","return_?temp","target","setpoint","chip","cpu","processor","board","core_temp","device_temp","batter","akkum","freezer","fridge","oven","kettle","boiler"].join("|"),"i");function Od(e,t){return t.area?t.area:e&&t.id?`@room/${encodeURIComponent(e)}/${encodeURIComponent(t.id)}`:null}function Ed(e){return null==e.area&&e.space&&e.room_id?Od(e.space,{id:e.room_id,area:null}):e.area||null}function Nd(e){const t=e?.exclude_integrations;return t?new Set(t):Pe}function Hd(e,t,i,n=Pe){const r=new Map;if(!e?.entities)return r;const o=Rd(i),s=new Set,a=new Map,l=new Map;for(const e of i||[]){if(e?.removed)continue;const t=(e.binding||"").indexOf(":");if(t<=0)continue;const i=e.binding.slice(0,t),n=e.binding.slice(t+1);if(!n)continue;!0===e.use_climate_temp&&s.add(n);const r=Ed(e);r&&("entity"!==i||a.has(n)?"device"!==i||l.has(n)||l.set(n,r):a.set(n,r))}const c=new Map;for(const[t,i]of Object.entries(e.entities)){if(i.device_id&&o.devices.has(i.device_id)&&!o.liveEntities.has(t)||!i.device_id&&o.entities.has(t)&&!o.liveEntities.has(t))continue;const r=i.device_id?e.devices?.[i.device_id]:null;if(!Oh(i)||r&&!Oh(r))continue;const h=a.get(t)||(i.device_id?l.get(i.device_id):null)||i.area_id||r?.area_id||null;if(!h)continue;if(i.entity_category)continue;if(!(s.size>0&&t.startsWith("climate.")&&(s.has(t)||i.device_id&&s.has(i.device_id)))){if(n.has(i.platform))continue;if(Id.test(t))continue}let d=c.get(h);d||(d=new Map,c.set(h,d));const u=i.device_id||t;let p=d.get(u);if(!p){const n=e.states?.[t];p={name:(r?r.name_by_user||r.name:i.name||n?.attributes?.friendly_name||t)||t,model:r?.model,ents:[]},d.set(u,p)}p.ents.push(t)}for(const[i,n]of c){const o=[],a=[];for(const[i,r]of n){const n=kd(e,r.name,r.model,r.ents,t),l="mdi:thermometer"===n||"mdi:air-filter"===n;if(l){const t=fd(e,r.ents);null!=t&&o.push(t)}if(s.size>0&&(s.has(i)||r.ents.some(e=>s.has(e)))){const t=vd(e,r.ents);null!=t&&o.push(t)}if(l||"mdi:water-percent"===n){const t=bd(e,r.ents);null!=t&&a.push(t)}}(o.length||a.length)&&r.set(i,{temp:o.length?Math.round(o.reduce((e,t)=>e+t,0)/o.length*10)/10:null,hum:a.length?Math.round(a.reduce((e,t)=>e+t,0)/a.length):null})}return r}function Ld(e,t,i){const n=[];for(const r of t){if(r.area!==i||r.virtual)continue;const t=gd(e,r.entities);null!=t&&n.push(t)}return Pi(n)}const Bd={offStates:["off"],unknownUsesToggle:!0},qd={light:Bd,switch:Bd,fan:Bd,humidifier:Bd,input_boolean:Bd,automation:Bd,remote:Bd,group:Bd,climate:{...Bd,featureMasks:{turn_on:256,turn_off:128,toggle:384}},media_player:{...Bd,featureMasks:{turn_on:128,turn_off:256,toggle:384}},siren:{...Bd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},vacuum:{...Bd,featureMasks:{turn_on:1,turn_off:2,toggle:3}},water_heater:{...Bd,featureMasks:{turn_on:8,turn_off:8,toggle:8}},camera:{...Bd,featureMasks:{turn_on:1,turn_off:1,toggle:1}}};function jd(e){return e.slice(0,e.indexOf("."))}function Wd(e,t,i){if(!e?.services||"object"!=typeof e.services)return!1;const n=e.services?.[t];return!!n&&Object.prototype.hasOwnProperty.call(n,i)}function Ud(e,t,i){return Wd(e,t,i)?{domain:t,service:i}:Wd(e,"homeassistant",i)?{domain:"homeassistant",service:i}:null}function Vd(e,t){return e?.entities?.[t]||null}function Gd(e,t,i){const n=e?.states?.[i],r=Vd(t,i);return n?.attributes?.friendly_name||r?.name||r?.original_name||i}function Kd(e,t){const i=Vd(e,t);if(null!=i?.disabled_by)return!0;const n=i?.device_id?e?.devices?.[i.device_id]:null;return null!=n?.disabled_by}function Yd(e,t){const i=e?.attributes?.supported_features;if(null==i||""===i)return!1;const n=Number(i);return Number.isFinite(n)&&(n&t)===t}function Xd(e,t,i){const n=jd(i);if("lock"===n||"alarm_control_panel"===n)return!0;if("cover"!==n)return!1;const r=e?.states?.[i],o=Vd(t,i),s=String(r?.attributes?.device_class||o?.device_class||o?.original_device_class||"");return Bi.has(s)}function Zd(e,t,i,n,r){return{ref:i,entityId:n,name:n?Gd(e,t,n):null,reason:r}}function Jd(e,t,i,n,r,o=null){return{target:null,skipped:Zd(e,t,i,n,r),semantics:o,nextEffect:null,command:null}}function Qd(e,t,i,n,r=i){const o=jd(i);if("cover"!==o&&"valve"!==o)return function(e,t,i,n,r=i){const o=jd(i),s=e?.states?.[i];if(Kd(t,i))return Jd(e,t,r,i,"ha-disabled","power");if(Xd(e,t,i))return Jd(e,t,r,i,"secure");if(!s)return Jd(e,t,r,i,"missing","power");if("unavailable"===s.state)return Jd(e,t,r,i,"unavailable","power");const a=qd[o];if(!a)return Jd(e,t,r,i,"unsupported");let l,c;if("unknown"===s.state||""===s.state){if(!a.unknownUsesToggle)return Jd(e,t,r,i,"unsupported","power");l="toggle",c="toggle"}else a.offStates.includes(String(s.state))?(l="turn-on",c="turn_on"):(l="turn-off",c="turn_off");const h=a.featureMasks?.[c];if(h&&!Yd(s,h))return Jd(e,t,r,i,"unsupported","power");const d=Ud(e,o,c);return d?{target:{entityId:i,name:Gd(e,t,i),state:String(s.state||""),via:n},skipped:null,semantics:"power",nextEffect:l,command:{...d,data:{entity_id:i}}}:Jd(e,t,r,i,"unsupported","power")}(e,t,i,n,r);if(Kd(t,i))return Jd(e,t,r,i,"ha-disabled",o);if(Xd(e,t,i))return Jd(e,t,r,i,"secure",o);const s=e?.states?.[i];if(!s)return Jd(e,t,r,i,"missing",o);if("unavailable"===s.state)return Jd(e,t,r,i,"unavailable",o);const a=function(e,t,i){const n=String(i?.state||""),r="closed"===n?{service:`open_${t}`,effect:"open",feature:1}:"open"===n?{service:`close_${t}`,effect:"close",feature:2}:"opening"===n||"closing"===n?{service:`stop_${t}`,effect:"stop",feature:8}:null;return r&&Yd(i,r.feature)&&Wd(e,t,r.service)?r:Yd(i,3)&&Wd(e,t,"toggle")?{service:"toggle",effect:"toggle"}:null}(e,o,s);if(!a)return Jd(e,t,r,i,"unsupported",o);return{target:{entityId:i,name:Gd(e,t,i),state:String(s.state||""),via:n},skipped:null,semantics:o,nextEffect:a.effect,command:{domain:o,service:a.service,data:{entity_id:i}}}}function eu(e){return"entity"===e.bindingKind?e.bindingRef&&Mn(e.bindingRef)?[e.bindingRef]:[]:"virtual"===e.bindingKind?[]:td(e)}function tu(e){const t=e.marker?.toggle_entity;return t&&eu(e).includes(t)?t:null}function iu(e,t,i){const n=function(e,t){if("entity"===e.bindingKind&&e.bindingRef){const t=e.marker?.light_entity?id(e):null;return[...new Set([t,e.bindingRef].filter(e=>!!e))]}const i=e.entities.length?e.entities:e.allEntities||[],n=e.marker?.light_entity||e.primary&&Mn(e.primary)?id(e):null;return[...new Set([n,...Xh(t,i)].filter(e=>!!e))]}(i,t);if(!n.length)return null;const r="entity"===i.bindingKind?"binding":"device-role";if("binding"===r)return Qd(e,t,n[0],r);let o=null,s=null;for(const i of n){const n=Qd(e,t,i,r);if(n.command)return n;const a=n.skipped?.reason;if("missing"===a||"unavailable"===a||"secure"===a)return n;"ha-disabled"!==a?o||=n:s||=n}return o||s}function nu(e){const t=e.skipped?.reason;return"missing"===t?"unavailable":t||"unsupported"}function ru(e,t){return{origin:e,kind:"none",semantics:null,targets:[],skippedTargets:[],noneReason:t,nextEffect:null,command:null}}function ou(e,t){return"cover"===e||"toggle"===e?"toggle":"more-info"===e||"run"===e||"info"===e||"none"===e?e:(null==e||""===e)&&"light"===t?"toggle":"info"}function su(e,t){return{origin:e,kind:"single",semantics:t.semantics,targets:t.target?[t.target]:[],skippedTargets:t.skipped?[t.skipped]:[],noneReason:t.command?null:nu(t),nextEffect:t.nextEffect,command:t.command}}function au(e,t,i,n=[]){const r=new Map,o=[],s=new Set,a=e=>{const t=`${e.ref}\n${e.entityId||""}\n${e.reason}`;s.has(t)||(s.add(t),o.push(e))};for(const e of n)a(e);for(const n of i){const i=Qd(e,t,n.entityId,n.via,n.ref);i.target?r.set(n.entityId,r.get(n.entityId)||i.target):i.skipped&&a(i.skipped)}const l=[...r.values()];if(!l.length)return{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:o.length&&o.every(e=>"secure"===e.reason)?"secure":"configured-targets-missing",nextEffect:null,command:null};const c=l.some(e=>"on"===e.state)?"turn_off":"turn_on",h=Ud(e,"homeassistant",c);return h?{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:null,nextEffect:"turn_on"===c?"turn-on":"turn-off",command:{...h,data:{entity_id:l.map(e=>e.entityId)}}}:{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:[],skippedTargets:[...o,...l.map(i=>Zd(e,t,i.entityId,i.entityId,"unsupported"))],noneReason:"unsupported",nextEffect:null,command:null}}function lu(e){return String(e.marker?.id||e.id||"")}function cu(e){const{hass:t,device:i}=e,n=e.registryHass||t,r=function(e){return"toggle"===e.tapAction?"explicit-toggle":"cover"===e.tapAction?"legacy-cover":!e.tapAction&&e.primary?.startsWith("light.")?"default-light":null}(i);if(!r)return null;const o=i.marker;if("explicit-toggle"===r&&vh(o)){const t=String(o?.id||i.id||""),n=ld(e.devices).get(t);if(n)return function(e,t){const i=e.registryHass||e.hass;return au(e.hass,i,t.driverEids.map(e=>({entityId:e,via:"control-marker-driver",ref:`marker:${t.markerId}`})))}(e,n);const s=yh(o,e.virtualLights);return{origin:r,kind:"single",semantics:"power",targets:[{entityId:"",name:i.name,state:s?"on":"off",via:"virtual-light"}],skippedTargets:[],noneReason:null,nextEffect:s?"turn-off":"turn-on",command:null,operation:{kind:"virtual-light",markerId:o.id}}}if("explicit-toggle"===r){if(Qh(i.marker?.binding,i.marker?.controls??i.controls,i.entities).length)return function(e,t=null){const{hass:i,device:n,devices:r}=e,o=e.registryHass||i,s=Qh(n.marker?.binding,n.marker?.controls??n.controls,n.entities),a=e.lightSources||pd(i,r,null,e.virtualLights),l=new Map;for(const e of a){if(!e.key.startsWith("marker:"))continue;const t=l.get(e.key)||[];t.push(e),l.set(e.key,t)}const c=ld(r),h=new Map;for(const e of r){const t=String(e.marker?.id||e.id||"");t&&h.set(t,e)}const d=[],u=[];t&&d.push({entityId:t,via:"entity"===n.bindingKind?"binding":"device-role",ref:t});for(const e of s){if(!e.startsWith("marker:")){Mn(e)?d.push({entityId:e,via:"control-entity",ref:e}):u.push(Zd(i,o,e,e.includes(".")?e:null,"unsupported"));continue}const t=l.get(e)||[];if(!t.length){const t=h.get(e.slice(7));if("ha_disabled"===t?.bindingStatus?.kind){const n=t.bindingStatus.allEntityIds[0]||null;u.push({ref:e,entityId:n,name:t.name||(n?Gd(i,o,n):null),reason:"ha-disabled"})}else u.push(Zd(i,o,e,null,"missing"));continue}const r=[...new Set(t.flatMap(e=>e.serviceEids))];if(r.length){for(const t of r)d.push({entityId:t,via:"control-entity",ref:e});continue}const s=t.some(e=>e.passive),a=e.slice(7),p=lu(n),_=c.get(a)?.controllers.find(e=>lu(e.device)===p);if(s&&_?.driverEids.length)for(const t of _.driverEids)d.push({entityId:t,via:"control-marker-driver",ref:e});else u.push(Zd(i,o,e,null,s?"missing":"unsupported"))}return au(i,o,d,u)}(e,tu(i))}if("legacy-cover"===r){const e=i.entities.find(e=>e.startsWith("cover."))||i.allEntities?.find(e=>e.startsWith("cover."));return e?su(r,Qd(t,n,e,"device-role")):ru(r,"no-actionable-entity")}const s=tu(i),a=s?Qd(t,n,s,"entity"===i.bindingKind?"binding":"device-role"):iu(t,n,i);return a?su(r,a):ru(r,i.virtual||"virtual"===i.bindingKind?"no-actionable-entity":"no-binding")}function hu(e){if(!e)return[];const t=Array.isArray(e.data.entity_id)?e.data.entity_id:[e.data.entity_id];return[...new Set(t)].sort()}function du(e){return e?e.operation?e.operation:e.command?{kind:"ha-service",command:e.command}:null:null}const uu=new Set(["missing","ha-disabled","unavailable"]);function pu(e,t){const i=du(e),n=du(t);return!(!i||!n||i.kind!==n.kind)&&("virtual-light"===i.kind&&"virtual-light"===n.kind?i.markerId===n.markerId:"ha-service"===i.kind&&"ha-service"===n.kind&&function(e,t){const i=hu(e),n=hu(t);return i.length===n.length&&i.every((e,t)=>e===n[t])}(i.command,n.command))}function _u(e,t){const i=e.targets[0]||e.skippedTargets[0],n=[];return"group"===e.kind?e.targets.length&&n.push(t.group(e.targets)):i&&n.push(t.single(i)),e.nextEffect&&e.targets.length&&n.push("group"===e.kind?t.groupCurrentNext(e.targets,e.nextEffect):t.currentNext(e.targets[0],e.nextEffect)),e.skippedTargets.length&&n.push(t.skipped(e.skippedTargets)),!e.command&&e.noneReason&&n.push(t.none(e.noneReason)),n}const mu=e=>!!e&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function gu(e,t=5,i=5){return Ro(e.cm,t,i)/2}function fu(e,t,i=1,n=5,r=5,o=0){const s=e.host;if(!s||"partition"!==s.kind||"string"!=typeof s.id||!s.id)return{resolved:null,reason:"invalid-host"};const a=t.find(e=>e.id===s.id);if(!a)return{resolved:null,reason:"missing-partition"};if(!mu(a.a)||!mu(a.b)||!Number.isFinite(s.t)||s.t<0||s.t>1)return{resolved:null,reason:"invalid-position"};const l=a.b[0]-a.a[0],c=a.b[1]-a.a[1],h=Math.hypot(l,c),d=Number(e.length)*i;if(!(h>1e-9&&d>0&&Number.isFinite(d)))return{resolved:null,reason:"invalid-length"};const u=s.t*h;if(u-d/2h-o+1e-9)return{resolved:null,reason:"does-not-fit"};const p=l/h,_=c/h;let m=180*Math.atan2(c,l)/Math.PI;return m>=90?m-=180:m<-90&&(m+=180),{reason:null,resolved:{opening:e,host:s,partition:a,center:[a.a[0]+l*s.t,a.a[1]+c*s.t],angle:m,length:d,depth:Ro(a.cm,n,r),t:s.t,axis:{a:[a.a[0],a.a[1]],b:[a.b[0],a.b[1]],ux:p,uy:_,length:h}}}}function vu(e,t,i=1,n=5,r=5){return fu(e,t,i,n,r,0)}function yu(e,t,i=1,n=5,r=5){const o=e.host,s="partition"===o?.kind?t.find(e=>e.id===o.id):void 0;if(!s)return vu(e,t,i,n,r);const a=fu(e,t,i,n,r,gu(s,n,r));return"does-not-fit"===a.reason?{resolved:null,reason:"does-not-fit-jamb"}:a}function bu(e,t){return!e||(e.length!==t.length||e.host?.kind!==t.host?.kind||e.host?.id!==t.host?.id||e.host?.t!==t.host?.t)}function wu(e){const{center:t,length:i,axis:n,host:r}=e,o=i/2;return{hostId:r.id,a:[t[0]-n.ux*o,t[1]-n.uy*o],b:[t[0]+n.ux*o,t[1]+n.uy*o],depth:e.depth}}function ku(e,t=!1){const i=t?1:-1,n=e.depth/2;return{ox:-e.axis.uy*i*n,oy:e.axis.ux*i*n,cm:e.partition.cm,side:i}}function xu(e,t,i){return e.flatMap(e=>!mu(e.a)||!mu(e.b)||Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])<=1e-9?[]:[{roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`partition:${e.id}`,kind:"outer",cm:e.cm,open:!1,half:Ro(e.cm,t,i)/2,partitionHost:{kind:"partition",id:e.id}}])}function Su(e,t,i){const{center:n,length:r,axis:o}=e,s=r/2,a=t.flatMap(e=>{if(!e.kind||e.open)return[];const t=e.b[0]-e.a[0],r=e.b[1]-e.a[1],a=Math.hypot(t,r);if(!(a>i))return[];const l=t/a,c=r/a;if(Math.abs(o.ux*c-o.uy*l)>1e-6)return[];if(Math.abs((n[0]-e.a[0])*c-(n[1]-e.a[1])*l)>i)return[];const h=e=>(e[0]-n[0])*o.ux+(e[1]-n[1])*o.uy,d=h(e.a),u=h(e.b),p=Math.max(-s,Math.min(d,u)),_=Math.min(s,Math.max(d,u));return _>=p-i?[[p,_]]:[]});if(!a.length)return!1;a.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let l=-s;for(const[e,t]of a){if(e>l+i)return!1;if(l=Math.max(l,t),l>=s-i)return!0}return!1}function $u(e,t,i=1e-9){const n=e.length/(2*e.axis.length),r=e.t-n,o=e.t+n;return t.some(t=>{if(t.host.id!==e.host.id||t.opening.id===e.opening.id)return!1;const n=t.length/(2*t.axis.length);return Math.max(r,t.t-n){e.isConnected&&e.requestUpdate()}),Tu.has(e)?"warm":"cold"):(Du.delete(e)&&(e.inert=!1,e.removeAttribute("aria-busy")),i&&(e.setAttribute("lang","fallback"===n?"en":i),Tu.add(e)),"ready")}function Pu(){return j``}const Fu=[{code:"en",nativeLabel:"English",dictionary:Cu},{code:"ru",nativeLabel:"Русский",dictionary:{"editor.context_actions":"Действия: {object}","editor.tool_options":"Параметры инструмента: {tool}","editor.palette":"Палитра: {tool}","editor.open_group":"Группа инструментов: {group}","editor.group_active":"{group} — активно: {item}","editor.disabled_action":"{action} недоступно: {reason}","editor.loading":"Загружаем редактор…","editor.loading_aria":"Редактор плана загружается","editor.load_failed":"Не удалось загрузить редактор.","editor.refresh_advice":"Обновите страницу и повторите попытку.","editor.retry_advice":"Проверьте сеть и нажмите ещё раз.","version_mismatch.title":"Версии House Plan не совпадают","version_mismatch.body":"Если Home Assistant ещё перезапускается, дождитесь завершения, затем перезагрузите эту страницу.","version_mismatch.frontend":"Карточка","version_mismatch.backend":"Интеграция","version_mismatch.reload":"Перезагрузить страницу","color_picker.title":"Выбор цвета","color_picker.hue":"Оттенок","color_picker.saturation":"Насыщенность","color_picker.value":"Яркость","color_picker.hex":"Цвет HEX","color_picker.invalid_hex":"Введите цвет HEX из 3 или 6 цифр","color_picker.confirm":"ОК","btn.properties":"Свойства","btn.keep_as_walls":"Оставить стенами","btn.delete_room_keep_walls":"Удалить комнату, оставить стены","btn.delete_room_with_walls":"Удалить комнату и стены","title.markup_select":"Выбор и редактирование стен и колонн","title.markup_column":"Колонна: кликните точку сетки для квадратной колонны","markup.partition":"Перегородка","markup.column":"Колонна","markup.hint_column":"кликните точку сетки, чтобы поставить квадратную колонну","history.wall_segment":"Добавление отрезка стены","history.column_add":"Добавление колонны","history.physical_edit":"Изменение физического объекта","history.physical_delete":"Удаление физического объекта","history.physical_move":"Перемещение физического объекта","history.wall_face_batch":"Создание комнат из стен","toast.column_duplicate":"Колонна с тем же центром и внешним размером уже существует","physical.partition_properties":"Свойства перегородки","physical.column_properties":"Свойства колонны","physical.shape":"Форма","physical.square":"Квадрат","physical.circle":"Круг","physical.diameter":"Диаметр","physical.side":"Сторона","physical.rotation":"Угол поворота","physical.length":"Длина","physical.allowed_range":"Допустимо: {min}–{max} {unit}","physical.column_size_title":"Внешняя сторона квадратной колонны, создаваемой кликом (1–150 см).","card.title":"План дома","count.devices":"{n} устр.","empty.no_spaces":"Пространств пока нет.","empty.add_first":"Добавьте первое пространство и загрузите план этажа.","empty.install":"Установите интеграцию House Plan и добавьте запись в «Устройства и службы».","btn.add_space":"Добавить пространство","btn.cancel":"Отмена","btn.save":"Сохранить","btn.close":"Закрыть","btn.delete":"Удалить","btn.copy":"Копировать","btn.edit":"Редактировать","btn.open_in_ha":"Открыть в HA","btn.reset":"Сброс","btn.attach":"Прикрепить…","btn.upload":"Загрузить…","btn.replace":"Заменить…","title.zoom_in":"Приблизить","title.zoom_out":"Отдалить","title.zoom_fit":"Вписать всё","title.configure_space":"Настроить пространство","title.add_space":"Добавить пространство","title.markup_add":"Стены: рисуйте непрерывную цепочку; каждый принятый отрезок сохраняется отдельно. Shift фиксирует 45°","title.markup_merge":"Объединить: клик по одной комнате, затем по соседней с общей стеной","title.markup_split":"Разделить комнату: клик по комнате, затем две точки на её стенах","title.markup_delroom":"Удалить комнату: кликните внутри комнаты и подтвердите удаление","title.need_plan":"Загрузите подложку (план этажа)","markup.add":"Стены","markup.merge":"Объединить","markup.split":"Разделить","markup.resize":"Размер","title.markup_resize":"Изменение размера комнат: тяните доступную ручку горизонтальной или вертикальной стены","markup.hint_resize":"тяните доступную ручку стены · стена упирается в первую небезопасную позицию · Esc — отмена · Ctrl+Z — отмена шага","resize.disabled.diagonal":"Стена расположена под углом: Resize поддерживает только горизонтальные и вертикальные стены","resize.disabled.side-angle":"Примыкающая стена расположена под углом: для Resize обе примыкающие стены должны образовывать прямой угол","resize.disabled.duplicate-physical-wall":"Стену перекрывает отдельная перегородка или колонна; удалите или переместите её перед изменением размера","resize.disabled.partial-shared":"Соседняя комната использует только часть этой стены, поэтому её нельзя безопасно двигать как одну общую стену","resize.disabled.unequal-shared":"У соседней комнаты другие конечные точки или длина стены, поэтому стены нельзя безопасно двигать вместе","resize.disabled.multiple-rooms":"Перемещение затронуло бы больше двух комнат","resize.disabled.thickness-conflict":"Толщину стены нельзя безопасно сохранить","resize.disabled.opening-conflict":"Проём на этой стене нельзя безопасно переместить","resize.disabled.invalid-geometry":"Эту стену нельзя переместить без изменения структуры плана","resize.limit_stopped":"Стена остановлена: дальше нарушается ограничение стыков","resize.commit_failed":"Изменение размера отменено: итоговый план не прошёл проверку геометрии","resize.preview_failed":"Стена остановлена в последней безопасной позиции: геометрию плана нельзя сохранить без потерь","markup.opening":"Проём","markup.delete_room":"Удалить комнату","history.undo":"Отменить","history.redo":"Повторить","history.undo_named":"Отменить: {name} (Ctrl+Z)","history.redo_named":"Повторить: {name} (Ctrl+Shift+Z / Ctrl+Y)","history.undo_empty":"Нет операций для отмены","history.redo_empty":"Нет операций для повтора","history.undone":"Отменено: {name}","history.redone":"Повторено: {name}","history.add_room":"Создание комнаты","history.split_room":"Разделение комнаты","history.merge_rooms":"Объединение комнат","history.resize_room":"Изменение размера комнаты","history.wall_thickness":"Изменение толщины стены","history.add_opening":"Добавление дверного или оконного проёма","history.edit_opening":"Изменение проёма","history.move_opening":"Перемещение проёма","history.delete_opening":"Удаление проёма","history.delete_room_keep_walls":"Удаление комнаты с сохранением стен","history.delete_room_with_walls":"Удаление комнаты и её стен","history.decor_add":"Добавление объекта декора","history.decor_edit":"Изменение объекта декора","history.decor_move":"Перемещение объекта декора","history.decor_transform":"Трансформация объекта декора","history.decor_delete":"Удаление объекта декора","history.backdrop_transform":"Трансформация подложки плана","history.device_move":"Перемещение: {name}","history.device_stale":"История позиций больше неприменима и была очищена","opening.new":"Новый проём","opening.edit":"Проём","opening.door":"Дверь","opening.window":"Окно","opening.gate":"Ворота","opening.passage":"Открытый проём","opening.passage_binding_warning":"При сохранении датчик открытия и замок будут удалены.","opening.invalid_passage_fields":"У открытого проёма на плане «{room}» есть недопустимые параметры: {fields}.","opening.type_label":"Тип","opening.length_label":"Длина, см","opening.contact_label":"Датчик открытия","opening.lock_label":"Замок","opening.none":"— нет —","opening.search_ph":"Поиск: имя или entity_id…","opening.invert":"Инвертировать открыто/закрыто","opening.flip_h":"Петли с другой стороны","opening.flip_v":"Открывается в другую сторону","opening.open":"Открыто","opening.closed":"Закрыто","opening.locked":"Заперто","opening.unlocked":"Не заперто","opening.state_unknown":"недоступно","opening.no_entities":"Датчики не привязаны — статичный символ на плане.","toast.opening_no_wall":"Кликните рядом со стеной комнаты или независимой стеной","opening.host_partition":"Независимая стена","opening.partition_orphan":"Независимая стена этого проёма больше не существует","opening.partition_jamb_margin":"Оставьте от края проёма до торца стены минимум {distance}","opening.rebind_partition":"Привязать к другой независимой стене","confirm.delete_partition_openings_title":"Удалить стену и проёмы?","confirm.delete_partition_openings_body":"В стене есть проёмы: {count}. Они будут удалены вместе со стеной.","confirm.delete_partition_openings_item":"• {type}, {length}","markup.hint_points":"точек: {n} · Shift — шаг 45° · Esc — завершить цепочку · Ctrl+Z — убрать точку · при замыкании будет предложена комната","markup.hint_start":"кликните точку сетки, чтобы начать цепочку стен","tip.lqi":"средний сигнал zigbee:","tip.area":"площадь: {value}","info.device_header":"Устройство на плане","info.model":"Модель","info.state":"Состояние","info.link":"Ссылка","info.manuals":"Инструкции","info.none":"Нет дополнительной информации","marker.new_device":"Новое устройство","marker.name_label":"Имя (отображается на плане)","marker.name_ph":"Название","marker.binding_label":"Привязка к устройству HA","marker.binding_disabled":"деактивировано в Home Assistant","marker.virtual_option":"Виртуальное устройство (без привязки)","marker.search_ph":"Поиск устройства / группы…","marker.nothing_found":"ничего не найдено","marker.room_label":"Комната","marker.room_override":" (переопределить размещение)","marker.room_choose":"— выберите комнату —","marker.room_auto":"— по зоне устройства (авто) —","marker.icon_label":"Иконка","marker.icon_ph":"mdi:… (пусто = авто)","marker.display_label":"Отображение","display.badge":"Значок + состояние","display.icon_ripple":"Значок + состояние и активность","display.static_icon":"Всегда статичный значок","marker.display_hint_badge":"Значок и динамическая подложка показывают состояние устройства без обычной пульсации активности. Красная тревога сохраняется.","marker.display_hint_icon_ripple":"Значок, динамическая подложка и пульсация: короткая — для событий, постоянная — для работы, движения или присутствия. Красная тревога имеет отдельный приоритет.","marker.display_hint_value":"Значок заменяется выбранным или автоматически найденным значением Home Assistant; подложка продолжает показывать состояние. Красная тревога сохраняется.","marker.display_hint_static_icon":"Подложка в цветах темы и значок всегда остаются одинаковыми. Состояния, активность, недоступность и тревоги не меняют отображение.","marker.static_alarm_warning":"Это устройство может сообщать о тревогах. Статичный режим скрывает визуальную тревогу маркера.","marker.preview.title":"Предпросмотр отображения","marker.preview.actual":"Сейчас","marker.preview.example":"Пример","marker.preview.integration":"Интеграция","marker.preview.source":"Источник отображения","marker.preview.current_state":"Текущее состояние","marker.preview.result":"На плане","marker.preview.details":"Подробнее об источниках","marker.preview.select_source":"Выберите устройство или сущность Home Assistant, чтобы увидеть фактическое отображение.","marker.preview.unknown_provider":"Интеграция неизвестна","marker.preview.virtual_provider":"House Plan · виртуальное устройство","marker.preview.no_source":"Нет активного источника","marker.preview.no_state":"Нет текущего состояния","marker.preview.mixed_states":"Несколько разных состояний","marker.preview.multiple_sources":"Источников: {n}","marker.preview.more_sources":"ещё {n}","marker.preview.scaled":"Предпросмотр уменьшен до {n}%, чтобы поместиться. Сохранённый размер не изменится.","marker.preview.demo_short":"Показать краткую активность","marker.preview.demo_continuous":"Показать постоянную активность","marker.preview.stop_continuous":"Остановить постоянную активность","marker.preview.demo_short_notice":"Пример краткой активности; фактическое состояние устройства не меняется.","marker.preview.demo_continuous_notice":"Пример постоянной активности; фактическое состояние устройства не меняется.","marker.preview.demo_already_visible":"Текущее состояние уже показывает реальную активность или тревогу.","marker.preview.reduced_motion":"В системе включено уменьшение движения, поэтому обычная активность показана точкой.","marker.preview.reason.neutral":"Нейтральная тёмная подложка","marker.preview.reason.working":"Жёлтая подложка: устройство сейчас работает","marker.preview.reason.working_activity":"Жёлтая подложка и эффект активности: устройство сейчас работает","marker.preview.reason.open":"Оранжевая подложка: физически открыто или разблокировано","marker.preview.reason.cover_icon_state":"Нейтральная подложка; состояние и значок определяет сущность шторы или заслонки","marker.preview.reason.presence":"Эффект активности, пока обнаружено присутствие","marker.preview.reason.event":"Короткий эффект активности после события","marker.preview.reason.transition":"Эффект активности во время движения или смены состояния","marker.preview.reason.media_neutral":"Медиаустройство остаётся на нейтральной тёмной подложке, пока доступно","marker.preview.reason.unavailable":"Приглушённая нейтральная подложка: отключено или недоступно","marker.preview.reason.alarm":"Красная тревожная подложка; тревога отображается всегда","marker.preview.reason.live_states_disabled":"Оформление по живым состояниям отключено в настройках карточки","marker.preview.reason.value_no_state":"Нет подходящего значения состояния — вместо него показан значок","marker.preview.reason.value_ambiguous_sources":"Подходит несколько источников значения — вместо него показан значок","marker.preview.reason.value_non_scalar":"Источник вернул не простое значение — вместо него показан значок","marker.preview.reason.value_virtual":"У виртуального устройства нет значения HA — вместо него показан значок","marker.preview.reason.vacuum_live_plan_only":"Живая позиция и след пылесоса доступны только на полном плане","marker.preview.reason.hidden_design_preview":"Устройство скрыто на плане, но его оформление видно в предпросмотре","marker.preview.reason.composite_power_source":"Состояние берётся из сущности питания устройства; вспомогательные переключатели не учитываются","marker.preview.reason.activity_display_disabled":"Выбранный режим отображения не показывает обычные эффекты активности","marker.preview.reason.ha_disabled":"Привязка отключена в Home Assistant, поэтому устройство будет скрыто на плане","marker.preview.reason.orphaned":"Сохранённая привязка Home Assistant больше не найдена","marker.preview.reason.static_icon":"Статичный режим: состояние устройства не меняет значок","marker.activity_color":"Цвет пульсации активности","marker.ripple_size":"Размер пульсации активности","marker.activity_alarm_note":"Цвет и размер относятся только к обычной активности и не влияют на красную тревогу.","marker.pulse_a11y_alarm":"Тревога","marker.pulse_a11y_event":"Недавнее событие","marker.pulse_a11y_presence":"Обнаружено присутствие","marker.pulse_a11y_transition":"Изменение состояния","marker.pulse_a11y_running":"Работает","marker.state_a11y_neutral":"Обычное состояние","marker.state_a11y_working":"Работает","marker.state_a11y_open":"Открыто","marker.state_a11y_locked":"Заблокировано","marker.state_a11y_unlocked":"Разблокировано","marker.state_a11y_alarm":"Тревога","marker.state_a11y_unavailable":"Недоступно","marker.lqi_a11y_low":"LQI {value}, слабый сигнал","marker.lqi_a11y_mid":"LQI {value}, средний сигнал","marker.lqi_a11y_high":"LQI {value}, сильный сигнал","marker.size_label":"Размер / поворот значка","marker.angle_label":"Поворот","marker.model_label":"Модель","marker.model_ph":"напр. Aqara T&H","marker.link_label":"Ссылка","marker.desc_label":"Описание","marker.desc_ph":"Заметки, характеристики…","marker.manuals_label":"Инструкции (PDF и т.п.)","marker.sub_device":"устройство","marker.sub_z2m_group":" · Z2M-группа","marker.sub_group":"группа","marker.sub_helper":"хелпер","space.new":"Новое пространство","space.copy_title":"Копирование пространства","space.copy_name":"Название нового пространства","space.copy_fallback":"Пространство","space.copy_create":"Создать копию","space.copy_optimize_title":"Оптимизировать перед копированием?","space.copy_optimize_body":"Перед созданием «{name}» House Plan должен оптимизировать весь план, включая другие пространства. Продолжить?","space.copy_optimize_confirm":"Оптимизировать и скопировать","space.copy_error_changed":"План изменился, пока было открыто подтверждение. Проверьте его и повторите попытку.","space.copy_error_source_missing":"Исходного пространства больше нет. Снова откройте его настройки и повторите попытку.","space.copy_error_source_invalid":"House Plan не смог проверить все стены этого пространства. Исправьте исходное пространство и повторите попытку.","space.copy_error_spaces_limit":"В House Plan уже создано максимальное число пространств.","space.copy_error_partitions_limit":"В этом пространстве слишком много стен для копирования.","space.copy_error_openings_limit":"В этом пространстве слишком много проёмов для копирования.","space.copy_error_decor_limit":"В этом пространстве слишком много элементов подложки для копирования.","space.copy_error_columns_limit":"В этом пространстве слишком много колонн для копирования.","space.copy_error_opening_host":"Один из проёмов больше не привязан к стене. Исправьте или удалите его перед копированием.","space.copy_error_geometry":"Копия создаст небезопасную геометрию стен. Исправьте исходное пространство и повторите попытку.","space.copy_error_optimize_geometry":"Копирование остановлено: оптимизация всего плана небезопасна для одного из пространств.","space.header":"Пространство","space.title_label":"Название","space.title_ph":"Например: Гараж","space.plan_label":"Подложка (план)","space.no_plan":"нет подложки","space.plan_alt":"план","room.new":"Новая комната","room.name_label":"Отображаемое имя","room.name_ph":"Например: Терраса","room.area_label":"Зона Home Assistant (свободные)","room.no_area_option":"— без зоны —","room.default_name":"Комната","device.unnamed":"без имени","device.light_group":"группа света","device.fallback":"устройство","device.virtual":"виртуальное устройство","confirm.delete_room_title":"Удалить комнату «{name}»?","confirm.delete_room_body":"Выберите, нужно ли оставить физические стены, принадлежащие только этой комнате. Общие с другой комнатой стены сохраняются всегда.","confirm.remove_marker_title":"Удалить устройство с плана?","confirm.remove_marker_body":"Устройство исчезнет полностью и перестанет участвовать в данных плана. Позже его можно будет добавить заново.","confirm.erase_decor":"Стереть объект «{kind}»? Действие можно отменить из истории редактора.","confirm.delete_space_title":"Удалить пространство?","confirm.delete_space_body":"Пространство, все его комнаты и вся разметка плана будут удалены.","confirm.delete_space_vac_routes":"Также будет снято сопоставление карт роботов: {count}.","space.delete_blocked":"Это пространство всё ещё используется устройствами: {n}. Сначала перенесите их в другое пространство или удалите.","toast.pos_save_failed":"Не удалось сохранить позицию: {err}","toast.no_entity":"У устройства нет подходящей сущности","toast.ha_disabled_action":"Деактивированный объект Home Assistant нельзя использовать на плане.","toast.ha_disabled_show_device":"Деактивированное в Home Assistant устройство нельзя показать на плане. Сначала активируйте его в Home Assistant.","toast.ha_disabled_show_entity":"Деактивированную в Home Assistant сущность нельзя показать на плане. Сначала активируйте её в Home Assistant.","toast.ha_disabled_add":"Деактивированный объект Home Assistant нельзя добавить на план. Сначала активируйте его в Home Assistant.","toast.ha_binding_unverified":"Статус объекта не удалось подтвердить по реестру Home Assistant. Отображение и действия временно недоступны.","toast.markup_needs_server":"Разметка доступна после переноса конфига на сервер","toast.space_order_changed":"Порядок изменён. Если где-то этаж карточки задан номером, проверьте такие панели.","toast.conflict":"Конфиг изменён в другом окне — данные обновлены, повторите последнее действие","toast.cfg_save_failed":"Не удалось сохранить конфиг: {err}","toast.room_overlap":"Контур накладывается на комнату «{name}» — комнаты не должны накладываться","toast.contour_cannot_close":"Контур нельзя замкнуть: он вырожден или пересекает сам себя","toast.merge_not_adjacent":"Объединять можно только комнаты с общей стеной","toast.rooms_merged":"Комнаты объединены в «{name}»","toast.split_pick_wall":"Начните разрез на стене комнаты","toast.split_bad_cut":"Разрез — от стены до стены внутри комнаты, без пересечения стен и самого себя","merge.header":"Объединение комнат","merge.hint":"У объединённой комнаты одно имя и одна зона. Вторая зона освобождается — её устройства уйдут с плана, пока их не заберёт другая комната.","merge.keep":"Оставить","merge.no_area":"без зоны","toast.room_saved":"Комната сохранена ({n}). Устройств добавлено: {added}. Обведите следующую или выйдите из разметки.","toast.room_saved_no_area":"Комната сохранена ({n}, без зоны). Обведите следующую или выйдите из разметки.","toast.marker_needs_server":"Редактирование устройств доступно после переноса конфига на сервер","toast.virtual_name_required":"Укажите имя виртуального устройства","toast.marker_saved":"Устройство сохранено","toast.marker_removed":"Устройство удалено с плана","toast.integration_missing":"Интеграция House Plan не установлена — управление недоступно","toast.plan_formats":"Поддерживаются SVG, PNG, JPG, WebP","toast.plan_required":"Загрузите подложку — план этажа обязателен","toast.space_added_onboard":"Пространство добавлено. Обведите комнаты: кликайте по точкам сетки и замкните контур.","toast.space_added":"Пространство добавлено","toast.space_copied":"Пространство «{name}» создано","toast.space_saved":"Пространство сохранено","toast.space_deleted":"Пространство удалено","toast.delete_failed":"Ошибка удаления: {err}","toast.error":"Ошибка: {err}","toast.toggle_target_unavailable":"Цель «{name}» недоступна — действие не выполнено","toast.toggle_targets_unavailable":"Цели недоступны: {names}. Действие не выполнено","toast.file_failed":"Файл «{name}» не загружен: {err}","toast.files_attached":"Прикреплено файлов: {n}","err.unknown":"неизвестная ошибка","err.code":"код {code}","err.too_large":"файл больше {mb} МБ","err.bad_ext":"недопустимый тип (нужен PDF/изображение)","err.unauthorized":"нужны права администратора","editor.title":"Заголовок","editor.default_floor":"Стартовое пространство","editor.default_floor_missing":"Стартовое пространство «{id}» больше не существует. Выберите другое.","editor.floor":"Закреплённое пространство","editor.floor_none":"— не закреплять —","editor.floor_index":"YAML-индекс {index} (сохранён)","fixed_floor.loading":"Загружаем закреплённое пространство…","fixed_floor.invalid_title":"Закреплённое пространство недоступно","fixed_floor.invalid_body":"Проверьте floor в конфигурации карточки. Настроенное значение: {value}","editor.icon_size":"Размер иконок, % ширины плана","editor.show_temperature":"Показывать температуру","editor.live_states":"Живые состояния (вкл/выкл, открыто…)","editor.light_pools":"Световые пулы и тени от стен","editor.show_signal":"Показывать сигнал zigbee (LQI)","editor.language":"Язык интерфейса","editor.lang_auto":"Авто (профиль HA)","title.icon_rules":"Правила иконок: какая MDI-иконка достаётся устройству по имени","rules.title":"Правила иконок","rules.hint":"Правила проверяются сверху вниз по строке «имя устройства + модель» (regex без учёта регистра); срабатывает первое совпадение. Если ничего не подошло — решает device class сущности, затем — иконка-заглушка.","rules.pattern_ph":"regex, напр. розетк|plug","rules.icon_ph":"mdi:power-socket-de","rules.add":"Добавить правило","rules.reset":"Сбросить к умолчаниям","rules.test_ph":"Проверьте имя устройства…","rules.invalid":"некорректный regex","rules.saved":"Правила иконок сохранены","btn.up":"Вверх","btn.down":"Вниз","tap.info":"Карточка устройства","tap.more_info":"Диалог HA (more-info)","tap.toggle":"Переключить состояние","marker.tap_label":"Действие по нажатию для этого устройства","tap.toggle_note":"Под селектором показано, какое состояние изменится. Защищённые устройства не переключаются с плана.","import.title":"Создать пространства из этажей HA","import.hint":"Home Assistant уже знает эти этажи. Отметьте, какие превратить в пространства плана — далее для каждого попросим картинку плана. Комнаты затем обводятся вручную по плану.","import.start":"Создать: {n}","import.manual":"Начать с нуля","import.progress":"Этаж {i} из {n}","import.done":"Пространства созданы. Обведите комнаты: кликайте по точкам сетки и замкните контур.","btn.skip":"Пропустить","space.scale_label":"Масштаб (размер клетки сетки)","space.cell_cm.help":"Связывает сетку с реальными размерами: от значения зависят длины и площади, толщина стен, размеры проёмов и радиус свечения. Изменение после разметки меняет расчётные размеры всего пространства, но не двигает его точки на плане.","space.cell_cm.help.aria":"Подсказка: масштаб пространства","space.scale_unit":"см на клетку","space.scale_unit_imperial":"дюйм на клетку","space.display_section":"Отображение","space.show_borders":"Всегда отображать границы комнат","space.zero_wall_style":"Стены нулевой толщины","space.zero_wall_style.help":"Пунктирные стены нулевой толщины пропускают Glow и солнечные лучи, сплошные блокируют их как барьер нулевой площади. Выбор меняет все такие стены пространства, даже когда их линии скрыты в просмотре.","space.zero_wall_style.help.aria":"Подсказка: вид стен нулевой толщины","space.zero_wall_dashed":"Пунктирные","space.zero_wall_solid":"Сплошные","space.show_names":"Отображать названия комнат (перетаскиваются)","space.room_color":"Цвет границ и названий","space.opacity":"Прозрачность","space.fill_label":"Заливка комнат","space.fill_mode.help":"«Свой цвет» задаёт оформление, а «Свет», «Температура» и «LQI» используют текущие данные Home Assistant; Glow включается отдельно.","space.fill_mode.help.aria":"Подсказка: режим заливки комнат","fill.none":"Нет","fill.lqi":"По силе зигби-сигнала","fill.light":"По освещению","fill.custom":"Свой цвет","space.custom_fill":"Цвет заливки","space.source_file":"У меня есть картинка плана","space.source_draw":"Нет подложки — нарисую комнаты вручную","fill.temp":"По температуре","tip.temp_avg":"средняя температура:","tip.hum_avg":"средняя влажность:","space_card.button":"Перейти к пространству","space_card.not_found":"Пространство «{id}» не найдено","space_card.loading":"Загрузка…","continuity.restore_plan":"Восстанавливаем план…","continuity.restore_connection":"Восстанавливаем подключение к устройствам…","continuity.retry":"Повторить","editor.space":"Пространство","editor.framing":"Кадрирование","editor.fit_content":"Всё видимое содержимое","editor.fit_house":"Плотно по геометрии дома","editor.show_button":"Показывать кнопку","editor.button_label":"Текст кнопки","editor.button_target":"Путь дашборда (куда вести)","marker.sub_entity":"сущность","title.general_settings":"Общие настройки","gs.title":"Общие настройки","gs.light_group":"Заливка: освещение","gs.light_on":"Свет включён","gs.light_off":"Весь свет выключен","gs.temp_group":"Заливка: температура","gs.temp_cold":"Холодно","gs.temp_ok":"Комфорт","gs.temp_hot":"Жарко","gs.lqi_group":"Заливка: зигби-сигнал","gs.lqi_low":"Слабый сигнал","gs.lqi_high":"Сильный сигнал","gs.reset":"Сбросить к умолчаниям","gs.saved":"Общие настройки сохранены","space.show_lqi":"Показывать зигби-сигнал (LQI) у устройств","space.hide_decor":"Скрыть декоративный слой","space.hide_decor_tip":"Линии, фигуры, надписи и мебель остаются на месте — их видно в редакторе подложки, но не на плане.","space.hide_openings":"Скрыть проёмы","space.hide_openings_tip":"Двери, окна и ворота не рисуются, но продолжают работать: свет проходит, солнце светит в окна, датчики открытия срабатывают. В редакторе плана проёмы видно всегда.","gs.light_none":"Нет источников света","mode.plan":"Редактор плана","mode.devices":"Редактор устройств","display.value":"Значение + состояние","marker.subarea":"без зоны, вручную","device.new":"Новое устройство — откройте его редактор, чтобы снять отметку","opening.unlock_action":"Открыть замок","opening.lock_action":"Закрыть замок","opening.lock_pending":"Выполняется…","title.close_editor":"Закрыть редактор (вернуться к просмотру)","title.add_device":"Добавить устройство на план","devbar.add":"Добавить","devbar.rules":"Правила иконок","device_inbox.button":"Устройства","device_inbox.title":"Устройства на плане","device_inbox.search":"Поиск по устройствам, сущностям и интеграциям…","device_inbox.add_virtual":"Добавить виртуальное устройство","device_inbox.tab_on_plan":"На плане","device_inbox.tab_available":"Доступны","device_inbox.tab_hidden":"Скрытые","device_inbox.tab_readd":"Доступны снова","device_inbox.only_new":"Только новые","device_inbox.show_entities":"Показывать сущности","device_inbox.show_hidden":"Показывать скрытые на плане","device_inbox.show_hidden.help":"Временно показывает на плане скрытые и деактивированные маркеры служебными призраками только в редакторе устройств. Сохранённая видимость устройств не меняется.","device_inbox.show_hidden.help.aria":"Подсказка: показывать скрытые устройства на плане","device_inbox.new":"Новое","device_inbox.find":"Найти на плане","device_inbox.edit":"Настроить","device_inbox.hide":"Скрыть","device_inbox.show":"Показать","device_inbox.add":"Добавить","device_inbox.readd":"Добавить заново","device_inbox.hide_available":"Скрыть из списка","device_inbox.show_more":"Показать ещё","device_inbox.more_actions":"Другие действия","device_inbox.find_hidden_hint":"Сначала включите «Показывать скрытые на плане»","device_inbox.show_disabled":"Перед показом активируйте эту привязку в Home Assistant","device_inbox.empty_on_plan":"На плане пока нет подходящих устройств.","device_inbox.empty_available":"Нет доступных устройств для добавления.","device_inbox.empty_hidden":"Скрытых устройств нет.","device_inbox.empty_readd":"Нет удалённых устройств, доступных для повторного добавления.","device_inbox.reason_visible_auto":"Найдено автоматически","device_inbox.reason_visible_explicit":"Добавлено явно","device_inbox.reason_manual_hidden":"Скрыто пользователем","device_inbox.reason_automatic_hidden":"Скрыто автоматически","device_inbox.reason_service_entry":"Служебная запись реестра","device_inbox.reason_excluded_integration":"Исключена интеграция «{integration}»","device_inbox.reason_excluded_domain":"Непространственный тип сущности","device_inbox.reason_grouped_light":"Представлено группой света комнаты","device_inbox.reason_represented_by_parent":"Представлено родительским устройством","device_inbox.reason_removed":"Ранее удалено с плана","device_inbox.reason_available":"Можно добавить на план","device_inbox.reason_no_bound_room":"Зона HA не связана с комнатой плана","device_inbox.status_ha_disabled":"Отключено в Home Assistant","device_inbox.status_orphaned":"Привязка больше не найдена в Home Assistant","device_inbox.status_unverified":"Реестр Home Assistant временно недоступен","device_inbox.saved":"Список устройств обновлён","device_inbox.filters_excluded":"Исключённые интеграции","device_inbox.filters_group_lights":"Объединять светильники комнаты в один маркер","device_inbox.filters_preview_appear":"появится: {count}","device_inbox.filters_preview_hide":"скроется: {count}","device_inbox.filters_preview_lights":"затронет светильников: {count}","device_inbox.filters_reset":"Вернуть рекомендуемые","device_inbox.filters_save":"Сохранить фильтры","device_inbox.filters_search_ph":"Добавить интеграцию…","device_inbox.filters_title":"Фильтры обнаружения","space.roomcard_section":"В карточке комнаты:","space.label_temp":"Температура","space.label_hum":"Влажность","space.label_lqi":"Средний Zigbee-сигнал","space.label_light":"Свет вкл/выкл","roomcard.light_on":"Вкл","roomcard.light_off":"Выкл","roomcard.light_partial":"{on} из {total}","toast.split_pick_inside":"Промежуточные точки разреза — внутри комнаты","mode.decor":"Редактор подложки","decor.select":"Выбрать","decor.line":"Линия","decor.rect":"Прямоугольник","decor.ellipse":"Овал","decor.text":"Надпись","decor.erase":"Стереть","decor.erase_confirm_title":"Стереть объект?","decor.color":"Цвет","decor.width":"Толщина линии","decor.line_style":"Стиль линии","decor.line_style_solid":"Сплошная","decor.line_style_dashed":"Пунктирная","decor.fill":"Заливка","decor.fill_color":"Цвет заливки","decor.length":"Длина","decor.size":"Размер","decor.flip_h":"Отзеркалить по горизонтали","decor.flip_v":"Отзеркалить по вертикали","decor.angle":"Угол поворота, °","decor.text_size":"Размер текста","decor.backdrop_properties":"Свойства картинки-подложки","decor.text_title":"Надпись","decor.object_title":"Редактирование: {kind}","decor.text_label":"Текст","decor.live_group":"Вставить переменную HA","decor.live_entity":"Сущность","decor.live_entity_ph":"выберите сущность","decor.live_attr":"Значение","decor.live_attr_ph":"выберите состояние или атрибут","decor.live_state":"Состояние","decor.backdrop":"Картинка-подложка","decor.backdrop_hint":"Тяните картинку — перемещение; угол — размер; верхнюю ручку — поворот. Shift меняет пропорции или снимает шаг угла.","decor.backdrop_reset":"Вернуть картинку","decor.backdrop_reset_done":"Картинка вернулась на своё место и в свой размер","marker.icon_auto":"Авто: {icon} (по правилам иконок; выберите свою, чтобы заменить)","marker.icon_pin_auto":"Закрепить","mode.plan_tip":"Редактор плана — геометрия дома: рисование и объединение/разделение комнат, привязка к зонам HA, двери, окна и ворота, карточки комнат, масштаб","mode.devices_tip":"Редактор устройств — всё про значки: перетаскивание, клик — настройка привязки/иконки/отображения, виртуальные устройства, правила иконок","mode.decor_tip":"Редактор подложки — чисто визуальный декор под планом: линии, прямоугольники, овалы и надписи, не реагирующие на клики","space.glow_enabled":"Свечение источников света","gs.glow_group":"Свечение источников света","gs.glow_base":"Темнота дома","gs.glow_light":"Цвет света по умолчанию / интенсивность","gs.wall_group":"Стены","gs.wall_fill":"Цвет заливки стен","gs.glow_radius":"Радиус свечения","gs.glow_radius.help":"Задаёт общий радиус светового пятна в метрах или футах; персональный радиус устройства заменяет это значение.","gs.glow_radius.help.aria":"Подсказка: общий радиус свечения","gs.unit_m":"м","gs.unit_ft":"фут","marker.controls_label":"Управляет другими источниками света","marker.controls.help":"При действии «Переключить состояние» перечисленные источники переключаются вместе с этим маркером. Их световые пятна остаются у собственных маркеров, а эта связь сама по себе не делает управляющий маркер источником света.","marker.controls.help.aria":"Подсказка: управление другими источниками света","marker.controls_filter":"Поиск ламп и выключателей…","info.controls":"Управляет","marker.glow_radius_label":"Радиус свечения","marker.glow_radius.help":"Задаёт радиус свечения в метрах или футах; пустое значение использует радиус из общих настроек.","marker.glow_radius.help.aria":"Подсказка: радиус свечения","markup.wallthick":"Толщина","markup.select":"Выбрать","title.markup_wallthick":"Толщина — клик по стене задаёт толщину от 0 до 100 см.","markup.hint_wallthick":"клик по стене · Esc закрывает без применения","wallthick.field":"Толщина","wallthick.unit_cm":"см","wallthick.unit_in":"дюйм","wallthick.apply_room":"Применить ко всем стенам комнаты","markup.draw_wall_title":"Толщина каждого нового сегмента стены (0–100 см). Общие стены сохраняют существующее значение.","room.queue_progress":"Комната {current} из {total}","toast.wall_rooms_saved":"Создано комнат: {n}","toast.wall_chain_saved":"Цепочка стен сохранена","toast.wallthick_pick":"Кликните по стене","toast.wallthick_set":"Толщина стены задана","toast.wallthick_cleared":"Толщина стены убрана","toast.physical_range":"Введите значение от {min} до {max} {unit}","toast.zero_wall_opening_conflict":"Сначала удалите проём на этом участке стены.","toast.zero_wall_ambiguous":"Не удалось однозначно выбрать участок стены. Уточните геометрию узла.","toast.zero_wall_migration_blocked":"Пространство не преобразовано: {reason}. Данные не изменены.","toast.physical_angle":"Введите угол поворота от 0° до 90°, не включая 90°","toast.physical_limit":"В пространстве достигнут лимит объектов этого типа","toast.geometry_unsafe":"Изменение отменено: геометрию стен нельзя безопасно построить.","junction.limit_angle":"Слишком острый угол между стенами: {actual}°, минимум {limit}°.","junction.limit_valence":"Слишком много стен в одном узле: {actual}, максимум {limit}.","junction.limit_length":"Слишком короткий участок стены: {actual} см, минимум {limit} см.","junction.limit_distance":"Стены и узлы слишком близко: {actual} см, минимум {limit} см.","junction.limit_clearance":"Внутри комнаты не остаётся места: {actual} см², минимум {limit} см².","junction.limit_check_failed":"Проверку стыков выполнить не удалось — изменение не сохранено","toast.wall_model_migration_blocked":"Не удалось обновить модель стен: {reason}. План не изменён. Запустите «Оптимизировать планы»; если ошибка повторится, исправьте конфликтующую геометрию стен.","toast.wall_model_client_outdated":"Обновите карточку и перезагрузите страницу перед редактированием плана.","wall_model.reason.invalid-room":"некорректный контур комнаты","wall_model.reason.zero-length":"отрезок стены нулевой длины","wall_model.reason.third-owner":"стена принадлежит более чем двум комнатам","wall_model.reason.duplicate-id":"конфликт идентификаторов стен","wall_model.reason.thickness-conflict":"конфликт значений толщины стены","wall_model.reason.opening-host":"проём нельзя однозначно привязать к стене","toast.delete_room_pick":"Кликните внутри комнаты, которую нужно удалить","toast.plan_snap_ambiguous":"Увеличьте масштаб, чтобы выбрать узел стены","toast.wall_repair_ambiguous":"У контура несколько возможных соединений. Увеличьте масштаб и соедините стены явно.","toast.wall_repair_too_large":"Разрыв больше 2 см. Соедините стены перед созданием комнаты.","toast.wall_repair_changed":"Геометрия стен изменилась. Попробуйте создать комнату ещё раз.","toast.opening_on_zero_wall":"Проёмы на стене нулевой толщины запрещены","marker.from_ha_option":"Выбрать из списка HA","marker.show_entities":"Показывать сущности","marker.show_entities_tip":"Добавляет в список не только устройства, но и все их сущности","marker.pick_ph":"Выберите устройство…","room.open_area":"Открыть зону в HA","room.fit_action":"Вписать комнату {name}","view.volumetric":"Объёмный вид","view.flat":"Плоский вид","kiosk.title":"Размеры на этом экране","kiosk.hint":"Хранится только на этом устройстве — у каждого настенного планшета или ТВ свои удобные размеры.","kiosk.icon_scale":"Размер значков устройств","kiosk.font_scale":"Размер текста карточек комнат","editor.kiosk":"Режим настенного устройства (киоск)","editor.cycle":"Автосмена пространств каждые N секунд (киоск, 0 = выкл)","room.settings_title":"Настройки комнаты","room.settings_section":"Настройки комнаты (переопределяют пространство)","room.fill_label":"Заливка в ЭТОЙ комнате","fill.inherit":"Как у пространства","room.custom_fill_space":"Цвет пространства","room.custom_fill_own":"Цвет комнаты","room.temp_src_label":"Источник температуры","room.hum_src_label":"Источник влажности","room.src_average":"Средняя по датчикам комнаты (по умолчанию)","room.src_pick":"Конкретное устройство или сущность HA","room.src_ph":"Выберите источник…","toast.room_updated":"Комната обновлена","space.card_font":"Размер шрифта карточек комнат (всё пространство)","room.sizes_section":"Размеры шрифтов","room.name_scale":"Размер названия","room.label_scale":"Размер подписей","preview.room_name":"Гостиная","toast.cfg_reload_failed":"Не удалось перечитать план с сервера: {err}","toast.locale_load_failed":"Не удалось загрузить языковой пакет. До перезагрузки страницы используется английский.","toast.furniture_art_load_failed":"Не удалось загрузить изображения мебели. Обновите страницу, чтобы их показать.","room.settings_short":"Настройки комнаты","room.unnamed":"Комната без имени","marker.use_climate_temp":"Учитывать температуру устройства в комнате","marker.use_climate_temp_tip":"Добавляет current_temperature кондиционера или термостата в среднюю температуру комнаты. Внешний бейдж со значением настраивается отдельно ниже.","marker.value_badge_title":"Бейдж со значением","marker.value_badge.help":"Показывает одно выбранное значение рядом со значком. Не влияет на комнатные показатели, свет, Glow и действие по нажатию.","marker.value_badge.help.aria":"Подсказка: бейдж со значением устройства","marker.value_badge_enabled":"Отображать бейдж со значением","marker.value_badge_source":"Значение","marker.value_badge_source.help":"Выберите конкретное состояние, поддерживаемый атрибут или производное значение этого устройства.","marker.value_badge_source.help.aria":"Подсказка: источник значения бейджа","marker.value_badge_position":"Расположение","marker.value_badge_position.help":"Выбранная сторона сохраняется постоянно и не переворачивается автоматически у края плана.","marker.value_badge_position.help.aria":"Подсказка: расположение бейджа","marker.value_badge_right":"Справа","marker.value_badge_bottom":"Снизу","marker.value_badge_left":"Слева","marker.value_badge_top":"Сверху","marker.value_badge_empty":"У этого устройства нет доступных значений","marker.value_badge_static":"Статичный значок не показывает живые значения. Настройка сохранится.","marker.value_badge_missing":"Источник недоступен","marker.value_badge_missing_hint":"Сохранённый источник сейчас недоступен. Можно сохранить его, отключить бейдж или выбрать другой.","marker.value_badge_duplicate":"То же значение уже показано внутри значка.","marker.value_badge_state":"Состояние · {name}","marker.value_badge_marker_state":"Состояние источника света · {name}","marker.value_badge_lqi":"Качество Zigbee-сигнала (среднее)","marker.value_badge_attr_current_temperature":"Текущая температура · {name}","marker.value_badge_attr_temperature":"Целевая температура · {name}","marker.value_badge_attr_current_humidity":"Текущая влажность · {name}","marker.value_badge_attr_humidity":"Влажность · {name}","marker.value_badge_attr_current_position":"Положение · {name}","marker.value_badge_attr_percentage":"Скорость · {name}","marker.value_badge_attr_brightness":"Яркость · {name}","marker.value_badge_attr_volume_level":"Громкость · {name}","marker.value_badge_attr_battery_level":"Заряд батареи · {name}","marker.value_badge_attr_fan_speed":"Скорость вентилятора · {name}","marker.value_source":"Источник значения","marker.value_source.help":"Выберите, что заменит значок. Действие по нажатию не изменится.","marker.value_source.help.aria":"Подсказка: источник значения внутри значка","marker.value_source_auto":"Автоматически (как раньше)","marker.value_source_missing_hint":"Сохранённый источник сейчас недоступен. До его восстановления или выбора другого значения внутри будет показано —.","marker.light_role_label":"Является источником света","marker.light_role.help":"«Авто» использует фактическую роль привязанного устройства, «Всегда» принудительно создаёт собственный источник, а «Никогда» исключает его; связанные лампы выше остаются независимыми.","marker.light_role.help.aria":"Подсказка: является ли устройство источником света","marker.light_role_auto_yes":"Автоматически (источник света)","marker.light_role_auto_no":"Автоматически (не источник света)","marker.light_role_always":"Всегда источник света","marker.light_role_never":"Никогда не источник света","marker.light_entity_label":"Ведущая сущность света","marker.light_entity.help":"Для составного устройства выберите сущность, состояние, цвет и яркость которой представляют этот источник на плане. Автоматический вариант сохраняет совместимость со старыми планами.","marker.light_entity.help.aria":"Подсказка: ведущая сущность света","marker.light_entity_auto":"Автоматически ({entity})","marker.light_entity_none":"нет управляемой сущности","marker.light_entity_missing":"Сохранённая сущность {entity} недоступна. Временно используется {fallback}; выбор восстановится, если сущность вернётся.","marker.toggle_entity_label":"Переключаемая сущность","marker.toggle_entity.help":"Для составного устройства выберите собственную лампу или переключатель, которой управляет нажатие. Автоматический вариант сохраняет прежние правила цели и не зависит от ведущей сущности света.","marker.toggle_entity.help.aria":"Подсказка: переключаемая сущность","marker.toggle_entity_auto":"Автоматически ({entity})","marker.toggle_entity_none":"нет собственной управляемой сущности","marker.toggle_entity_missing":"Сохранённой сущности {entity} больше нет среди выбираемых каналов этого маркера. Временно используется {fallback}; выбор восстановится, если сущность вернётся.","marker.glow_color_label":"Цвет и яркость свечения","marker.glow_mode.help":"Используйте данные источника, задайте только цвет или зафиксируйте цвет и яркость. Минимум — 1%; чтобы отключить источник, выберите «Никогда».","marker.glow_mode.help.aria":"Подсказка: цвет и яркость свечения","marker.glow_mode_auto":"Из источника","marker.glow_mode_color":"Задать цвет","marker.glow_mode_fixed":"Задать цвет и яркость","marker.glow_color":"Цвет свечения","marker.glow_brightness":"Яркость","marker.glow_disabled_never":"Настройки свечения недоступны: маркер явно исключён из источников света.","marker.glow_disabled_auto":"В автоматическом режиме у этого маркера не найден пространственный источник света.","marker.glow_disabled_no_entity":"Для пространственного источника нет активной управляемой сущности Home Assistant.","marker.glow_passive_hint":"У источника нет собственных данных Home Assistant. Задайте цвет и яркость вручную; радиус остаётся доступным.","marker.control_broken":"Сохранённый источник отсутствует или больше не отмечен как источник света","marker.control_missing_label":"Отсутствующий источник на плане","marker.control_passive":"пассивный источник","toast.marker_control_cycle":"Такая связь создаст циклическую цепочку управления светом.","toast.marker_binding_required":"Сначала выберите устройство Home Assistant, затем добавьте управляемый источник света.","confirm.unlock_title":"Открыть замок?","confirm.unlock_body":"House Plan отправит этому замку команду открытия.","toast.files_migrate_failed":"Не удалось перенести вложения к новой привязке, ссылки остались на старые файлы: {err}","space.pick_saved":"Уже загруженные","space.pick_saved_hint":"Планы, сохранённые на сервере, включая отцеплённые ранее","space.no_saved":"На сервере пока нет сохранённых планов.","space.loading":"Загрузка…","space.used_by":"используется: {list}","space.in_use":"План используется пространством — сначала отцепите его","btn.use":"Выбрать","confirm.delete_plan_title":"Удалить файл плана?","confirm.delete_plan_body":"Файл будет удалён с сервера. Это действие нельзя отменить.","toast.plans_list_failed":"Не удалось получить список планов: {err}","toast.plan_delete_failed":"Не удалось удалить план: {err}","marker.hide":"Скрыть","marker.hide_tip":"Устройство исчезнет с плана после сохранения, но продолжит участвовать в расчёте сигнала комнаты. Вернуть его можно через каталог «Устройства» в редакторе устройств.","marker.show":"Показать","marker.show_tip":"Устройство снова появится на плане после сохранения.","marker.hidden_ghost":"Устройство скрыто пользователем","marker.ha_disabled_device":"Устройство деактивировано в Home Assistant и скрыто с плана.","marker.ha_disabled_entity":"Сущность деактивирована в Home Assistant и скрыта с плана.","marker.ha_disabled_all_entities":"У устройства нет активных сущностей Home Assistant, поэтому оно скрыто с плана.","marker.ha_registry_limited":"Полный реестр Home Assistant недоступен этому пользователю. Неподтверждённый объект временно нельзя показывать или использовать.","marker.delete_tip":"Полностью удалить устройство с плана и из всех расчётов. Позже его можно добавить заново.","tap.run":"Запустить автоматизацию/скрипт/сцену","tap.none":"Ничего не делать","marker.run_target_label":"Что запускать","marker.run_search_ph":"Поиск: автоматизация, скрипт или сцена…","marker.run_target_gone":"Цель {id} не найдена — выберите заново","marker.tap_confirm":"Спрашивать подтверждение","marker.tap_confirm_tip":"Перед выполнением показать диалог подтверждения — защита от случайных нажатий.","marker.toggle_hint_single":"Цель: {name} ({id}).","marker.virtual_light_target":"Виртуальный свет: {name}.","marker.virtual_light_current":"Ручное состояние: {state} → {effect}.","marker.virtual_light_state_on":"включён","marker.virtual_light_state_off":"выключен","marker.toggle_hint_group":"Переключатся источники ({count}): {names}.","marker.toggle_hint_current":"Сейчас: {state} → {effect}.","marker.toggle_hint_group_current":"Сейчас включено {on} из {count} → {effect}.","marker.toggle_hint_skipped":"Не будут затронуты ({count}): {targets}.","marker.toggle_effect_turn_on":"включится","marker.toggle_effect_turn_off":"выключится","marker.toggle_effect_open":"откроется","marker.toggle_effect_close":"закроется","marker.toggle_effect_stop":"остановится","marker.toggle_effect_toggle":"состояние переключится","marker.toggle_skip_missing":"не найдено","marker.toggle_skip_ha_disabled":"деактивировано в HA","marker.toggle_skip_unavailable":"недоступно","marker.toggle_skip_unsupported":"переключение не поддерживается","marker.toggle_skip_secure":"заблокировано из соображений безопасности","marker.toggle_none_no_binding":"У устройства нет привязки, состояние переключать нечем. По нажатию ничего не произойдёт.","marker.toggle_none_no_actionable_entity":"У устройства нет состояния, которое можно переключить. По нажатию ничего не произойдёт.","marker.toggle_none_configured_targets_missing":"Настроенные цели сейчас недоступны. Собственная сущность устройства не будет подставлена вместо них.","marker.toggle_none_ha_disabled":"Цель деактивирована в Home Assistant и не может использоваться на плане.","marker.toggle_none_unavailable":"Цель сейчас недоступна. По нажатию ничего не произойдёт.","marker.toggle_none_unsupported":"Для этой сущности Home Assistant не предоставляет безопасного переключения. По нажатию ничего не произойдёт.","marker.toggle_none_secure":"Переключение замков, сигнализации и защитных ворот с плана заблокировано из соображений безопасности.","run.automation":"автоматизация","run.script":"скрипт","run.scene":"сцена","confirm.tap_run":"Запустить «{name}»?","confirm.tap_toggle":"Переключить «{name}»?","confirm.current_state":"Текущее состояние: {state}","confirm.expected_state":"После переключения: {state}","confirm.group_current":"включено {on} из {total}","confirm.group_all_on":"все включены","confirm.group_all_off":"все выключены","confirm.unavailable_targets":"Недоступно: {count}","confirm.expected_by_ha":"Состояние определит Home Assistant","confirm.state_on":"Включено","confirm.state_off":"Выключено","confirm.state_open":"Открыто","confirm.state_closed":"Закрыто","confirm.state_opening":"Открывается","confirm.state_closing":"Закрывается","confirm.state_stopped":"Остановлено","confirm.state_unknown":"Неизвестно","toast.run_started":"Запущено: {name}","toast.run_target_missing":"Цель запуска не найдена — проверьте настройки устройства","toast.run_target_required":"Выберите автоматизацию, скрипт или сцену","toast.tap_target_changed":"Цель действия изменилась. Повторите попытку.","toast.virtual_light_toggle_failed":"Не удалось переключить виртуальный свет: {err}","toast.value_badge_source_required":"Выберите значение для бейджа","btn.run":"Выполнить","vac.section":"Робот-пылесос: живая позиция","vac.autocal":"Настроить автоматически","vac.live":"Живая позиция на плане","vac.trail":"Показывать путь робота","vac.autocal_no_rooms":"Интеграция не отдаёт список комнат — откройте «Подогнать вручную»","vac.route_warn_unmapped":"Робот убирает на карте, которая не сопоставлена ни одному этажу","vac.route_warn_needs_calibration":"Карта сопоставлена этажу, но не откалибрована","vac.route_warn_ambiguous":"Две карты неразличимы — этаж не выбран","vac.route_warn_missing_space":"Пространство этой карты удалено","vac.autocal_no_match":"Не совпали имена комнат (нужно ≥3 общих) — откройте «Подогнать вручную»","vac.autocal_done":"Готово: привязка по {rooms} комнатам. Запустите уборку и проверьте","vac.cal_need_pos":"Робот сейчас не отдаёт координаты — запустите уборку и поставьте на паузу","vac.cal_done":"Калибровка сохранена. Запустите уборку и проверьте","vac.cal_cancelled":"Калибровка отменена","vac.fit":"Подогнать вручную","vac.fit_hint":"Перетащите карту робота на место, растяните за уголки","vac.fit_rotate":"Повернуть 90°","vac.fit_mirror":"Отразить","vac.trail_never":"Не показывать никогда","vac.trail_cleaning":"Во время уборки","vac.trail_always":"Показывать всегда","gs.bg_group":"Фон сцены","gs.bg_color":"Цвет фона вокруг плана","gs.bg_default":"Как в теме","gs.bg_theme":"по умолчанию — из темы","gs.bg_mode":"Фон плана","gs.bg_mode.help":"«Следует за Солнцем» использует sun.sun, а при недоступности — локальные часы браузера; статичный режим всегда показывает выбранный цвет.","gs.bg_mode.help.aria":"Подсказка: общий фон плана","gs.bg_static":"Статичный цвет","gs.bg_daynight":"Следует за Солнцем","gs.sun_group":"Солнце","gs.sun_missing":"Сущность sun.sun не найдена — фон следует локальным часам, а оконные лучи недоступны.","gs.north":"Север на плане","gs.north.help":"Угол отсчитывается по часовой стрелке от верхней вертикали плана; север нужен для оконных лучей, а не для фона «Следует за Солнцем».","gs.north.help.aria":"Подсказка: общее направление севера","gs.north_ph":"не задан","gs.north_clear":"Сбросить","gs.north_letter":"С","gs.sun_rays":"Солнце в окнах","gs.about_version":"Houseplan Card v{v}","gs.about_github":"GitHub · документация и issues","gs.about_telegram":"Чат в Telegram","support.title":"Помощь и обратная связь","space.bg_color":"Цвет фона вокруг плана","space.bg_inherit":"Наследовать общий","space.bg_inherited":"наследуется из общих настроек","space.bg_mode":"Фон плана","space.bg_mode.help":"Выберите наследование общего фона либо переопределите это пространство статичным цветом или режимом «Следует за Солнцем».","space.bg_mode.help.aria":"Подсказка: фон пространства","space.north":"Север на плане (переопределение)","space.north.help":"Переопределяет общий север для этого пространства; угол отсчитывается по часовой стрелке от верхней вертикали плана и используется оконными лучами.","space.north.help.aria":"Подсказка: север для пространства","space.north_inherited":"наследуется: {v}","space.sun_rays":"Солнце в окнах","space.sun_inherit":"Наследовать общий","space.sun_on":"Вкл","space.sun_off":"Выкл","canvas.far_objects":"Объектов далеко от плана: {n}","canvas.show_far":"Показать","canvas.home_tip":"План там — нажмите, чтобы вписать","gs.grid_group":"Обслуживание планов","gs.grid_hint":"Обновляет модели данных, выравнивает элементы по сетке и объединяет лишние фрагменты стен. Перед записью будет показан точный отчёт.","gs.align_all":"Оптимизировать планы","gs.align_title":"Оптимизировать планы","gs.align_none":"Все планы уже используют актуальную и оптимальную модель данных.","gs.optimize_no_automatic_changes":"Автоматических изменений нет. Проверьте пункты ниже.","gs.align_count":"Сдвинется элементов: {n} из {total}, максимум на {cm} см.","gs.align_where":"Наибольший сдвиг — в пространстве «{s}».","gs.align_turned":"Проёмов с исправлением угла: {n}.","gs.align_preflight_failed":"Не удалось безопасно проверить геометрию следующих пространств: {spaces}{more}.","gs.align_preflight_hint":"Планы не изменены. Скопируйте диагностику кнопкой ниже и приложите её к отчёту об ошибке вместе с экспортом пространства.","gs.preflight_reason_prepare-exception":"Не удалось подготовить геометрию пространства (исключение при сборке модели)","gs.preflight_reason_wall-null":"Тело стен не построилось (объединение вернуло пустоту)","gs.preflight_reason_wall-degraded-extra":"Тело стен деградировало с лишней геометрией","gs.preflight_reason_wall-failed-core":"Ядро тела стен не собралось","gs.preflight_reason_wall-exception":"Построение стен упало с исключением","gs.preflight_reason_floor-null":"Контур пола не построился","gs.preflight_reason_floor-exception":"Построение пола упало с исключением","gs.preflight_copy":"Скопировать диагностику","gs.preflight_copied":"Диагностика скопирована","gs.preflight_update_hint":"Версии карточки и интеграции различаются — обновите House Plan и повторите.","gs.align_preflight_space":"Пространство {n}","gs.align_preflight_more":" и ещё {n}","gs.optimize_changes":"Миграций модели: {m}; обновлено пространств: {c}; устранён шум координат: {p}; объединено отрезков реальных стен: {w}; объединено отрезков стен нулевой толщины: {s}; независимых: {i}.","gs.zero_walls_migrated":"Преобразовано виртуальных участков: {n}.","gs.wall_segments_migrated":"Стабилизировано сегментов стен: {n}.","gs.room_drafts_migrated":"Незавершённые контуры преобразованы в обычные стены: {drafts}; отрезков: {segments}.","gs.optimize_lattice_summary":"Канонизировано шумовых значений координат: {n}; максимальный сдвиг: {cm} см.","gs.optimize_lattice_space":"{space}: канонизировано значений координат: {n}; оставлено значений вне сетки: {far}.","gs.optimize_coincident_partitions":"Скрытые участки независимых стен поглощены стенами комнат: {n}.","gs.optimize_openings_rehosted":"Проёмы перепривязаны к стенам комнат: {n}.","gs.optimize_walls_straightened":"Выпрямлено стен: {n}; максимальное перемещение: {cm} см.","gs.optimize_walls_straightened_where":"Максимальная правка стены: {s}.","gs.optimize_walls_straighten_skipped":"Оставлено почти осевых стен, которые нельзя безопасно выпрямить: {n}.","gs.optimize_glow_migration":"Старый Glow: пространств — {spaces} → без заливки данных + независимый Glow; комнат — {rooms} → наследуемая заливка + независимый Glow.","gs.optimize_references":"Исправлено ссылок: пространства — {spaces}; комнаты — {rooms}; позиции — {positions}; устройств отвязано от отсутствующих пространств — {detached}.","gs.optimize_reference_more":", и ещё {n}","gs.optimize_orphans_removed":"Убрано забытых записей: {total} — подписи комнат: {rooms}; устройства: {devices}; групповые метки: {groups}. Все они принадлежали пространствам, удалённым ранее.","gs.optimize_live_positions":"Старые позиции в удалённых пространствах принадлежат существующим объектам: {n}{names}. Они будут сохранены.","gs.optimize_live_positions_remove":"Старые позиции в удалённых пространствах принадлежат существующим объектам: {n}{names}. Они выбраны для удаления.","gs.optimize_live_names":": {names}{more}","gs.optimize_live_remove":"Убрать старые позиции","gs.optimize_live_keep":"Сохранить старые позиции","gs.optimize_live_selected":"Старые позиции будут убраны после применения оптимизации.","gs.optimize_unverified":"Не удалось безопасно проверить позиций: {n}. Они оставлены без изменений.","gs.optimize_registry_limited":"Для безопасной проверки нужен полный доступ администратора к реестрам Home Assistant.","gs.optimize_vacuum_warning":"Сопоставления комнат пылесоса требуют проверки: {n}.","gs.optimize_details":"Подробности","gs.optimize_details_more":"И ещё записей: {n}.","gs.optimize_detail_removed":"будет удалено","gs.optimize_detail_live":"будет сохранено","gs.optimize_detail_unverified":"не проверено","gs.optimize_detail_room_label":"подпись комнаты","gs.optimize_detail_device":"устройство","gs.optimize_detail_group":"групповая метка","gs.optimize_detail_unknown":"неизвестный владелец","gs.optimize_detail_item":"{status}: {kind} {id}; прежнее пространство {space}","gs.align_warn":"Элементы, намеренно поставленные между узлами, будут сдвинуты. После операции доступна одна отмена — только до следующего изменения плана.","gs.align_run":"Оптимизировать","gs.align_done":"Планы оптимизированы: сдвинуто элементов — {n}, обслужено записей — {m}, исправлено ссылок — {r}","gs.optimize_undo":"Отменить последнюю оптимизацию","gs.optimize_undone":"Последняя оптимизация отменена","decor.furniture":"Мебель","decor.image":"Изображение","decor.image_title":"Свои изображения","decor.image_upload":"Загрузить изображение","decor.image_replace":"Заменить изображение","decor.image_uploading":"Загрузка…","decor.image_asset":"Файл изображения","decor.image_pick_hint":"Загрузите изображение или выберите уже используемое в House Plan.","decor.image_place_hint":"Кликните по плану, чтобы разместить изображение.","decor.image_none":"Загруженных изображений пока нет.","decor.image_unavailable":"Изображение недоступно","decor.image_used":"Используется в объектах: {n}","decor.image_upload_failed":"Не удалось загрузить изображение: {err}","decor.image_error_capacity":"Хранилище пользовательских изображений заполнено.","decor.image_in_use":"Перед удалением файла удалите все размещённые копии.","decor.image_delete_title":"Удалить файл изображения?","decor.image_delete_message":"Удалить «{name}» из House Plan? Это действие нельзя отменить.","furn.title":"Библиотека мебели","furn.symbol":"Символ","furn.group_furniture":"Мебель","furn.group_appliance":"Техника","furn.group_sanitary":"Сантехника","furn.group_other":"Прочее","furn.width":"Ширина","furn.depth":"Глубина","furn.back_to_categories":"Все категории","furn.pick_hint":"Выберите категорию, затем символ.","furn.place_hint":"Кликните по плану — предмет встанет к ближайшей стене. Shift — свободно.","furn.cat_air_conditioner":"Кондиционеры","furn.cat_armchair":"Кресла","furn.cat_bathtub":"Ванны","furn.cat_bed":"Кровати","furn.cat_bidet":"Биде","furn.cat_boiler":"Бойлеры","furn.cat_chair":"Стулья","furn.cat_coffee_table":"Журнальные столы","furn.cat_cooktop":"Варочные панели","furn.cat_dining_table":"Обеденные столы","furn.cat_dishwasher":"Посудомоечные машины","furn.cat_dryer":"Сушильные машины","furn.cat_fireplace":"Камины","furn.cat_fridge":"Холодильники","furn.cat_kitchen_cabinet":"Кухонные шкафы","furn.cat_kitchen_sink":"Кухонные мойки","furn.cat_nightstand":"Тумбы","furn.cat_plant":"Растения","furn.cat_rug":"Ковры","furn.cat_shelving":"Стеллажи","furn.cat_shower":"Душевые","furn.cat_sink":"Раковины","furn.cat_sofa":"Диваны","furn.cat_stairs":"Лестницы","furn.cat_toilet":"Унитазы","furn.cat_tv":"Телевизоры","furn.cat_wardrobe":"Шкафы","furn.cat_washer":"Стиральные машины","furn.cat_work_table":"Рабочие столы","furn.sym_sofa":"Диван двухместный","furn.sym_sofa_three_seat":"Диван трёхместный","furn.sym_sofa_corner_right":"Угловой диван, правый","furn.sym_armchair":"Кресло мягкое","furn.sym_armchair_office":"Кресло офисное","furn.sym_coffee_table":"Журнальный стол, прямоугольный","furn.sym_coffee_table_round":"Журнальный стол, круглый","furn.sym_coffee_table_oval":"Журнальный стол, овальный","furn.sym_coffee_table_rounded":"Журнальный стол, скруглённый","furn.sym_table_dining":"Обеденный стол, прямоугольный","furn.sym_table_round":"Круглый стол","furn.sym_table_dining_oval":"Обеденный стол, овальный","furn.sym_table_dining_rounded":"Обеденный стол, скруглённый","furn.sym_chair":"Стул","furn.sym_chair_bar":"Барный стул","furn.sym_desk":"Рабочий стол, прямоугольный","furn.sym_desk_corner":"Рабочий стол, угловой","furn.sym_bed_double":"Двуспальная кровать","furn.sym_bed_single":"Односпальная кровать","furn.sym_nightstand":"Тумба прикроватная","furn.sym_cabinet_tv":"Тумба под телевизор","furn.sym_cabinet_shoe":"Тумба для обуви","furn.sym_cabinet_sink":"Тумба под раковину","furn.sym_wardrobe":"Шкаф гардеробный","furn.sym_bookshelf":"Шкаф книжный","furn.sym_wall_unit":"Шкаф-стенка","furn.sym_kitchen_floor":"Кухонный напольный модуль","furn.sym_kitchen_floor_corner":"Кухонный напольный угловой модуль","furn.sym_kitchen_wall":"Кухонный навесной модуль","furn.sym_kitchen_wall_corner":"Кухонный навесной угловой модуль","furn.sym_shelf_floor":"Стеллаж напольный","furn.sym_shelf_wall":"Полка настенная","furn.sym_fridge":"Холодильник","furn.sym_stove":"Варочная панель, 4 конфорки","furn.sym_cooktop_two":"Варочная панель, 2 конфорки","furn.sym_dishwasher":"Посудомоечная машина","furn.sym_washer":"Стиральная машина","furn.sym_dryer":"Сушильная машина","furn.sym_tv":"Телевизор на подставке","furn.sym_tv_wall":"Телевизор на кронштейне","furn.sym_ac":"Кондиционер","furn.sym_water_heater":"Бойлер","furn.sym_toilet":"Унитаз напольный","furn.sym_toilet_built_in":"Унитаз встроенный","furn.sym_bathtub":"Ванна прямоугольная","furn.sym_bathtub_corner":"Ванна угловая","furn.sym_shower":"Душ","furn.sym_sink":"Раковина","furn.sym_kitchen_sink":"Кухонная мойка одинарная","furn.sym_kitchen_sink_double":"Кухонная мойка двойная","furn.sym_bidet":"Биде напольное","furn.sym_bidet_built_in":"Биде встроенное","furn.sym_stairs":"Лестница","furn.sym_fireplace":"Камин","furn.sym_plant":"Растение","furn.sym_rug":"Ковёр","common.yes":"Да","common.no":"Нет","vac.diag_source":"Источник","vac.diag_platform":"Интеграция","vac.diag_status":"Статус","vac.diag_position":"Позиция","vac.diag_rooms":"Комнаты","vac.diag_rooms_value":"{total} · совпало имён: {matched} · {readiness}","vac.autocal_ready":"автокалибровка доступна","vac.autocal_not_ready":"нужно 3 совпавших имени","vac.diag_path":"Путь интеграции","vac.diag_map":"ID карты","vac.source_none":"не выбран","vac.source_status_ok":"Готов","vac.source_status_missing":"Не найден","vac.source_status_disabled":"Деактивирован в Home Assistant","vac.source_status_unavailable":"Недоступен","vac.source_status_unverified":"Нельзя проверить с текущими правами","vac.source_status_unsupported":"Нет данных позиции","vac.source_status_none":"Нет источника","vac.source_banner_missing":"Сохранённый источник больше не существует. Он не заменён автоматически: выберите другой или восстановите его в Home Assistant.","vac.source_banner_disabled":"Сохранённый источник деактивирован в Home Assistant. Активируйте его там или выберите другой.","vac.source_banner_unverified":"Текущих прав Home Assistant недостаточно для проверки источника. Привязка сохранена и не будет заменена автоматически.","vac.choose_source":"Выбрать источник","vac.source_auto":"Автоматически","vac.source_auto_hint":"Использовать совместимую сущность этого устройства","vac.all_cameras":"Все камеры","vac.all_cameras_warn":"Камера может не отдавать данные робота. Выбирайте её только если это карта вашего пылесоса.","vac.all_cameras_empty":"Других сущностей камеры не найдено.","vac.platform_unknown":"интеграция неизвестна","vac.cap_position":"позиция","vac.cap_rooms_short":"комнаты","vac.cap_path":"путь","vac.cap_map":"ID карты","vac.cap_none":"данные робота не обнаружены","vac.xcme_hint":"Включите атрибуты Xiaomi Cloud Map Extractor:","vac.documentation":"Документация","vac.residual_title":"Проверьте автокалибровку","vac.residual_message":"Совпавшие комнаты расходятся максимум на {error}. Примените приблизительную калибровку, подгоните её вручную либо отмените без изменения сохранённых настроек.","vac.apply_proposal":"Применить","gs.backup_group":"Резервная копия и перенос","gs.backup_hint":"Скачайте переносимую JSON-копию или проверьте и импортируйте копию, созданную House Plan.","backup.export_open":"Экспорт","backup.import_open":"Импорт","backup.export_title":"Экспорт House Plan","backup.import_title":"Импорт House Plan","backup.export_hint":"Выберите, должна ли копия содержать всю конфигурацию House Plan или только текущее пространство.","backup.full":"Полная копия","backup.current_space":"Текущее пространство","backup.current_space_title":"Текущее пространство: {title}","backup.no_current_space":"Нет текущего пространства","backup.plan_only":"Только планировка","backup.plan_only_hint":"Сохранить комнаты, стены, проёмы, декор и позиции подписей комнат без устройств и привязок Home Assistant.","backup.plan_only_preview":"Файл содержит только планировку","backup.privacy_warning":"Архив сохраняет названия, идентификаторы Home Assistant и точные координаты. Внутренние планы и вложения указываются ссылками, но не вкладываются; текущие состояния и маршруты пылесосов не включаются.","backup.download":"Скачать JSON","backup.export_done":"Резервная копия скачана","backup.reading":"Проверяем резервную копию…","backup.revalidated":"После предпросмотра план изменился. Сводка обновлена — проверьте её и подтвердите ещё раз.","backup.error.support_invalid_message":"Проверьте сообщение для поддержки и повторите попытку.","backup.error.support_package_too_large":"Обезличенный пакет для поддержки превышает лимит 8 МиБ.","backup.error.support_preview_expired":"Предпросмотр вложения для поддержки истёк или больше недоступен.","backup.error.support_rate_limited":"Запрошено слишком много репортов или предпросмотров. Повторите позже.","backup.error.support_rejected":"Репорт не прошёл проверку службы поддержки.","backup.error.support_unavailable":"Закрытая служба поддержки временно недоступна.","backup.error.unauthorized":"У вас нет прав на экспорт или импорт этого плана.","backup.error.not_ready":"House Plan ещё не готов. Повторите попытку через несколько секунд.","backup.error.too_large":"Размер резервной копии превышает 8 МиБ.","backup.error.invalid_json":"Выбранный файл не является корректным JSON.","backup.error.invalid_format":"Выбранный файл не является резервной копией House Plan.","backup.error.invalid_image":"Изображение повреждено или не соответствует своему формату.","backup.error.unsupported_export_version":"Эта версия формата резервной копии не поддерживается установленной версией.","backup.error.unsupported_image":"Используйте поддерживаемое изображение PNG, JPEG, WebP или SVG.","backup.error.future_model":"Резервная копия создана в более новой версии модели данных House Plan.","backup.error.invalid_config":"Резервная копия содержит некорректную конфигурацию House Plan.","backup.error.wall_model_migration_blocked":"Не удалось безопасно обновить модель стен из резервной копии. Сначала оптимизируйте исходный план и повторите экспорт.","backup.error.invalid_layout":"Резервная копия содержит некорректные позиции объектов.","backup.error.invalid_content":"Резервная копия содержит некорректные или несогласованные ссылки на файлы.","backup.error.space_not_found":"Выбранное пространство больше не существует.","backup.error.capacity_exceeded":"Добавление этой копии превысит ограничения размера плана.","backup.error.preview_expired":"Время предпросмотра истекло. Выберите файл резервной копии заново.","backup.error.preview_owner_mismatch":"Этот предпросмотр принадлежит другому пользователю Home Assistant.","backup.error.conflict":"После предпросмотра план изменился. Проверьте обновлённую сводку.","backup.error.content_confirmation_required":"Подтвердите отсоединение недоступных локальных файлов.","backup.error.commit_failed":"Не удалось безопасно применить копию. Предыдущий план восстановлен или ожидает восстановления.","backup.error.missing_plan":"После предпросмотра исчез связанный файл плана. Проверьте копию ещё раз.","backup.error.missing_content":"После предпросмотра исчез связанный локальный файл. Проверьте копию ещё раз.","backup.error.marker_control_missing":"В резервной копии отсутствует связанный источник света на плане.","backup.error.marker_control_not_light":"Связанная цель больше не отмечена как источник света.","backup.error.marker_control_self":"Источник света не может управлять самим собой.","backup.error.marker_control_cycle":"Резервная копия содержит циклическую цепочку управления светом.","backup.error.duplicate_marker_control":"Резервная копия содержит повторяющуюся связь с источником света.","backup.error.no_backup":"Нет снимка импорта или оптимизации, который можно восстановить.","backup.error.in_use":"Элемент ещё используется","backup.error.invalid_data":"Запрос содержит некорректные данные","backup.error.invalid_light_entity":"Ведущий свет должен быть сущностью light.* или switch.*","backup.error.invalid_marker_control":"Некорректная ссылка управления маркером","backup.error.invalid_name":"Некорректное имя","backup.error.invalid_partition_opening_host":"Проём должен сохранить свою перегородку-носитель","backup.error.invalid_partition_opening_jamb_margin":"Проём не оставляет физического простенка у края стены","backup.error.invalid_passage_fields":"Открытый проход не может нести настройки двери","backup.error.invalid_space_id":"Неизвестное пространство","backup.error.invalid_toggle_entity":"Сущность переключения должна быть light.* или switch.*","backup.error.invalid_value_badge":"Некорректные настройки бейджа значения","backup.error.invalid_value_badge_attribute":"Некорректный атрибут бейджа значения","backup.error.invalid_value_badge_position":"Некорректная позиция бейджа значения","backup.error.invalid_value_badge_source":"Некорректный источник бейджа значения","backup.error.invalid_vacuum_map_route":"Проверьте сопоставление карт робота пространствам.","backup.error.invalid_value_source":"Некорректный источник значения","backup.error.invalid_value_source_attribute":"Некорректный атрибут источника значения","backup.error.io_error":"Файловая операция на сервере не удалась","backup.error.not_toggleable":"Это устройство нельзя переключить","backup.error.nothing_to_repair":"Нечего чинить","backup.error.space_in_use":"На пространство ещё есть ссылки","backup.error.value_badge_source_required":"Бейджу значения нужен источник","backup.error.wall_model_client_outdated":"План обновлён в другом месте — перезагрузите страницу","backup.same_source":"Создано на этом экземпляре Home Assistant","backup.foreign_source":"Создано на другом экземпляре Home Assistant","backup.created":"Создано: {value}","backup.versions":"Карточка {card}; интеграция {integration}; модель данных {model}","backup.count_spaces":"Пространств: {n}","backup.count_rooms":"Комнат: {n}","backup.count_walls":"Стен: {n}","backup.count_openings":"Проёмов: {n}","backup.count_decor":"Объектов декора: {n}","backup.count_markers":"Устройств: {n}","backup.count_layout":"Позиций: {n}","backup.bindings":"Привязки — устройства: {device}, сущности: {entity}, виртуальные: {virtual}; позиций без пространства: {legacy}","backup.binding_status":"Статус на целевом экземпляре — активных: {active}, деактивированных: {disabled}, отсутствующих: {missing}","backup.missing_areas":"На целевом экземпляре отсутствуют зоны: {areas}","backup.dropped_marker_links":"Связи с источниками света вне переносимого пространства пропущены: {n}.","backup.room_drafts_migrated":"Старые незавершённые контуры преобразованы в обычные стены: {drafts}; отрезков: {segments}.","backup.repaired_target_refs":"Существующих ссылок восстановлено этим импортом: {n}.","backup.preserved_unresolved_refs":"Неоднозначные ссылки сохранены без изменений: {n}.","backup.preserved_unresolved_hint":"House Plan ничего не угадывал и не удалял. После импорта запустите «Оптимизировать планы», чтобы проверить оставшиеся ссылки.","backup.import_details":"Подробности восстановления ссылок","backup.import_detail.incoming_remapped":"Ссылок обновлено внутри импортируемой копии: {n}","backup.import_detail.target_repaired":"Существующих ссылок восстановлено: {n}","backup.import_detail.preserved_unresolved":"Неразрешимых ссылок сохранено: {n}","backup.import_detail.collisions":"Конфликтов назначения безопасно сохранено: {n}","backup.import_detail.dropped_links":"Входящих связей пропущено по правилам переноса: {n}","backup.import_detail.bounded_lineages":"Чрезмерно вложенных идентификаторов ограничено: {n}","backup.replace_warning":"Текущая конфигурация и расположение будут заменены. Загруженные файлы не удаляются. Одну отмену можно выполнить до следующего изменения плана.","backup.foreign_bookkeeping":"Служебные списки известных и новых устройств другого экземпляра импортированы не будут.","backup.final_name":"Название нового пространства","backup.target_settings":"Глобальные настройки целевого экземпляра не изменятся.","backup.duplicates":"Уже существующих привязок: {n}","backup.skip":"Пропустить повторяющиеся устройства","backup.virtual_copy":"Добавить безопасные статичные виртуальные копии","backup.content":"Связанное содержимое","backup.decor_images_summary":"Свои изображения: объектов — {objects}, файлов — {assets}; отсутствует файлов — {missing}.","backup.content_available":"доступно локально","backup.content_external":"внешняя ссылка","backup.content_detach_required":"будет отвязано","backup.confirm_detach":"Я понимаю, что недоступные внутренние планы и вложения будут отвязаны от импортируемой конфигурации.","backup.confirm_missing_images":"Я понимаю, что отсутствующие свои изображения останутся восстанавливаемыми заглушками, а остальные недоступные локальные файлы будут отвязаны.","backup.replace":"Заменить","backup.add":"Добавить пространство","backup.space_done":"Пространство импортировано: комнат — {rooms}, устройств — {markers}, существующих ссылок восстановлено — {refs}","backup.full_done":"Копия восстановлена: пространств — {spaces}, комнат — {rooms}, устройств — {markers}","backup.undo_import":"Отменить последний полный импорт","backup.import_undone":"Полный импорт отменён","backdrop.large_title":"Большое изображение","backdrop.large_body":"Изображение {w}×{h} ({fileMb} МБ), для показа потребуется около {decodedMb} МБ памяти. На планшетах это может привести к падению страницы.","backdrop.unknown_body":"Не удалось прочитать размеры изображения — файл может быть повреждён. Продолжение может привести к падению страницы на планшете.","backdrop.reduced_dimensions":"Уменьшенная копия: {w}×{h} px.","backdrop.use_downscaled":"Загрузить уменьшенную копию","backdrop.reducing":"Уменьшаем…","backdrop.keep_original":"Оставить оригинал","backdrop.too_large_title":"Изображение слишком большое","backdrop.too_large_body":"Изображение превышает возможности браузера ({w}×{h}, предел {limit} px по стороне). Уменьшите его в редакторе на компьютере и загрузите снова.","backdrop.downscale_failed":"Не удалось создать уменьшенную копию. Текущий план не изменён."}},{code:"de",nativeLabel:"Deutsch",loadDictionary:async function(e){const t=0===e?await import("./de-BolUcHuX.js"):await import(new URL("./de-BolUcHuX.js?retry",import.meta.url).href);return{dictionary:t.dictionary,fingerprint:t.fingerprint}}},{code:"fr",nativeLabel:"Français",loadDictionary:async function(e){const t=0===e?await import("./fr-CyV9xY4W.js"):await import(new URL("./fr-CyV9xY4W.js?retry",import.meta.url).href);return{dictionary:t.dictionary,fingerprint:t.fingerprint}}}],zu=Cu,Iu=new Set;const Ou=new class{constructor(e,t,i=console.warn,n){this.entries=e,this.expectedFingerprint=t,this.warn=i,this.loadFailed=n,this.dictionaries=new Map,this.pending=new Map,this.failed=new Set;for(const t of e)t.dictionary&&this.dictionaries.set(t.code,t.dictionary)}state(e){return this.dictionaries.has(e)?"ready":this.failed.has(e)?"fallback":"pending"}dictionary(e){return this.dictionaries.get(e)}ensure(e){if("pending"!==this.state(e))return Promise.resolve();const t=this.pending.get(e);if(t)return t;const i=this.entries.find(t=>t.code===e),n=this.load(i).finally(()=>this.pending.delete(e));return this.pending.set(e,n),n}async load(e){if(!e?.loadDictionary)return void(e&&this.failed.add(e.code));let t;for(const i of[0,1])try{const t=await e.loadDictionary(i);if(t.fingerprint!==this.expectedFingerprint)throw new Error(`locale fingerprint mismatch for ${e.code}`);return this.dictionaries.set(e.code,t.dictionary),void this.failed.delete(e.code)}catch(e){t=e}this.failed.add(e.code),this.warn(`[houseplan] unable to load ${e.code} locale; using English`,t),this.loadFailed?.(e.code)}}(Fu,"646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00",console.warn,function(e){for(const t of Iu)t(e)});function Eu(e){const t=Lu(e)?.code??"en";return Ou.dictionary(t)??zu}function Nu(e){return"string"==typeof e?e.trim().replaceAll("_","-").toLowerCase():""}const Hu=new Map(Fu.map(e=>[Nu(e.code),e]));function Lu(e){return Hu.get(Nu(e))}function Bu(e,t){const i=[{value:"",label:e},...Fu.map(({code:e,nativeLabel:t})=>({value:e,label:t}))],n="string"==typeof t?t:"";return n&&!i.some(e=>e.value===n)&&i.push({value:n,label:Lu(n)?.nativeLabel??n}),i}function qu(e,t){return function(e,t,i,n){const r=new Map(i.map(e=>[Nu(e),e])),o=r.get(Nu(e));if(o)return o;const s=Nu(t),a=r.get(s);return a||(r.get(s.split("-")[0]||"")??n)}(t,e?.locale?.language||e?.language,Fu.map(({code:e})=>e),"en")}function ju(e,t,i){return Qi(Eu(e)[t]??zu[t]??t,i)}function Wu(e,t){const i=Eu(e)[t]??zu[t];return"string"==typeof i&&i.trim().length>0}function Uu(e,t,i,n){return{ox:0,oy:0}}function Vu(e,t){const i=(e.angle+90)*Math.PI/180,n=za(16,t),r=e.gateFace?-n*e.gateFace.side:n*(e.flipV?-1:1);return[[e.x+Math.cos(i)*r,e.y+Math.sin(i)*r],r<0]}function Gu(e){const t=e.length/2,i=e.face.cm>0?e.face.cm/e.cellCm*e.gridPitch/2:za(4,e.cellCm),n="gate"===e.type?Math.sin(10*Math.PI/180)*t:0;return{half:t,jambHalf:i,gateDepth:n,outlineHalf:Math.max(za(16,e.cellCm),i+za(8,e.cellCm),n+za(8,e.cellCm)),hitHalf:Math.max(za(20,e.cellCm),i+za(10,e.cellCm),n+za(12,e.cellCm))}}function Ku(e,t,i){e.minX=Math.min(e.minX,t),e.minY=Math.min(e.minY,i),e.maxX=Math.max(e.maxX,t),e.maxY=Math.max(e.maxY,i)}function Yu(e,t,i,n,r,o,s,a){const l=Math.min(s,a)*Math.PI/180,c=Math.max(s,a)*Math.PI/180,h=(e,t)=>{const i=Math.atan2(t,e),n=[l,c];for(let e=-3;e<=3;e++){const t=e*Math.PI-i,r=Math.PI/2+e*Math.PI-i;t>l&&tl&&r0&&[e.length,e.angle,t[0],t[1]].every(Number.isFinite)))return null;const{half:i,jambHalf:n}=Gu(e),r=Fa(e.cellCm),o=1.75*r,s=1.25*r,a=.75*r,l={minX:-i-s,minY:-n-s,maxX:i+s,maxY:n+s},c={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("window"===e.type)Yu(c,-i,0,i,-o,o,-90,0),Yu(c,i,-i,0,-o,o,0,90),Ku(c,-i-a,-i-a),Ku(c,i+a,a);else if("gate"===e.type){const t=10*e.face.side;Yu(c,-i,0,i,-o,o,0,t),Yu(c,i,-i,0,-o,o,-t,0)}else Yu(c,-i,0,e.length,-o,o,-90,0),Ku(c,-i-a,-e.length-a),Ku(c,i+a,a);const[h,d]=Xu(e),u={...l};Ku(u,c.minX+h,c.minY+d),Ku(u,c.maxX+h,c.maxY+d);const p=e.flipH?-1:1,_="gate"===e.type?1:e.flipV?-1:1,m=e.angle*Math.PI/180,g=Math.cos(m),f=Math.sin(m),v={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};for(const e of[u.minX,u.maxX])for(const i of[u.minY,u.maxY]){const n=e*p,r=i*_;Ku(v,t[0]+n*g-r*f,t[1]+n*f+r*g)}return v}function Ju(e){if("passage"===e.type)return W``;const t=Math.max(0,Math.min(1,e.amount)),{half:i,jambHalf:n}=Gu(e),r=Fa(e.cellCm),o=1.75*r,s=e.flipH?-1:1,a=e.flipV?-1:1,l="gate"===e.type?1:a,[c,h]=Xu(e);let d;if("window"===e.type){const o=Math.PI/2*i,s=e.face.cm>0?W`{e.isConnected&&e.requestUpdate()}),Tu.has(e)?"warm":"cold"):(Du.delete(e)&&(e.inert=!1,e.removeAttribute("aria-busy")),i&&(e.setAttribute("lang","fallback"===n?"en":i),Tu.add(e)),"ready")}function Pu(){return j``}const Fu=[{code:"en",nativeLabel:"English",dictionary:Cu},{code:"ru",nativeLabel:"Русский",dictionary:{"editor.context_actions":"Действия: {object}","editor.tool_options":"Параметры инструмента: {tool}","editor.palette":"Палитра: {tool}","editor.open_group":"Группа инструментов: {group}","editor.group_active":"{group} — активно: {item}","editor.disabled_action":"{action} недоступно: {reason}","editor.loading":"Загружаем редактор…","editor.loading_aria":"Редактор плана загружается","editor.load_failed":"Не удалось загрузить редактор.","editor.refresh_advice":"Обновите страницу и повторите попытку.","editor.retry_advice":"Проверьте сеть и нажмите ещё раз.","version_mismatch.title":"Версии House Plan не совпадают","version_mismatch.body":"Если Home Assistant ещё перезапускается, дождитесь завершения, затем перезагрузите эту страницу.","version_mismatch.frontend":"Карточка","version_mismatch.backend":"Интеграция","version_mismatch.reload":"Перезагрузить страницу","color_picker.title":"Выбор цвета","color_picker.hue":"Оттенок","color_picker.saturation":"Насыщенность","color_picker.value":"Яркость","color_picker.hex":"Цвет HEX","color_picker.invalid_hex":"Введите цвет HEX из 3 или 6 цифр","color_picker.confirm":"ОК","btn.properties":"Свойства","btn.keep_as_walls":"Оставить стенами","btn.delete_room_keep_walls":"Удалить комнату, оставить стены","btn.delete_room_with_walls":"Удалить комнату и стены","title.markup_select":"Выбор и редактирование стен и колонн","title.markup_column":"Колонна: кликните точку сетки для квадратной колонны","markup.partition":"Перегородка","markup.column":"Колонна","markup.hint_column":"кликните точку сетки, чтобы поставить квадратную колонну","history.wall_segment":"Добавление отрезка стены","history.column_add":"Добавление колонны","history.physical_edit":"Изменение физического объекта","history.physical_delete":"Удаление физического объекта","history.physical_move":"Перемещение физического объекта","history.wall_face_batch":"Создание комнат из стен","toast.column_duplicate":"Колонна с тем же центром и внешним размером уже существует","physical.partition_properties":"Свойства перегородки","physical.column_properties":"Свойства колонны","physical.shape":"Форма","physical.square":"Квадрат","physical.circle":"Круг","physical.diameter":"Диаметр","physical.side":"Сторона","physical.rotation":"Угол поворота","physical.length":"Длина","physical.allowed_range":"Допустимо: {min}–{max} {unit}","physical.column_size_title":"Внешняя сторона квадратной колонны, создаваемой кликом (1–150 см).","card.title":"План дома","count.devices":"{n} устр.","empty.no_spaces":"Пространств пока нет.","empty.add_first":"Добавьте первое пространство и загрузите план этажа.","empty.install":"Установите интеграцию House Plan и добавьте запись в «Устройства и службы».","btn.add_space":"Добавить пространство","btn.cancel":"Отмена","btn.save":"Сохранить","btn.close":"Закрыть","btn.delete":"Удалить","btn.copy":"Копировать","btn.edit":"Редактировать","btn.open_in_ha":"Открыть в HA","btn.reset":"Сброс","btn.attach":"Прикрепить…","btn.upload":"Загрузить…","btn.replace":"Заменить…","title.zoom_in":"Приблизить","title.zoom_out":"Отдалить","title.zoom_fit":"Вписать всё","title.configure_space":"Настроить пространство","title.add_space":"Добавить пространство","title.markup_add":"Стены: рисуйте непрерывную цепочку; каждый принятый отрезок сохраняется отдельно. Shift фиксирует 45°","title.markup_merge":"Объединить: клик по одной комнате, затем по соседней с общей стеной","title.markup_split":"Разделить комнату: клик по комнате, затем две точки на её стенах","title.markup_delroom":"Удалить комнату: кликните внутри комнаты и подтвердите удаление","title.need_plan":"Загрузите подложку (план этажа)","markup.add":"Стены","markup.merge":"Объединить","markup.split":"Разделить","markup.resize":"Размер","title.markup_resize":"Изменение размера комнат: тяните доступную ручку горизонтальной или вертикальной стены","markup.hint_resize":"тяните доступную ручку стены · стена упирается в первую небезопасную позицию · Esc — отмена · Ctrl+Z — отмена шага","resize.disabled.diagonal":"Стена расположена под углом: Resize поддерживает только горизонтальные и вертикальные стены","resize.disabled.side-angle":"Примыкающая стена расположена под углом: для Resize обе примыкающие стены должны образовывать прямой угол","resize.disabled.duplicate-physical-wall":"Стену перекрывает отдельная перегородка или колонна; удалите или переместите её перед изменением размера","resize.disabled.partial-shared":"Соседняя комната использует только часть этой стены, поэтому её нельзя безопасно двигать как одну общую стену","resize.disabled.unequal-shared":"У соседней комнаты другие конечные точки или длина стены, поэтому стены нельзя безопасно двигать вместе","resize.disabled.multiple-rooms":"Перемещение затронуло бы больше двух комнат","resize.disabled.thickness-conflict":"Толщину стены нельзя безопасно сохранить","resize.disabled.opening-conflict":"Проём на этой стене нельзя безопасно переместить","resize.disabled.invalid-geometry":"Эту стену нельзя переместить без изменения структуры плана","resize.limit_stopped":"Стена остановлена: дальше нарушается ограничение стыков","resize.commit_failed":"Изменение размера отменено: итоговый план не прошёл проверку геометрии","resize.preview_failed":"Стена остановлена в последней безопасной позиции: геометрию плана нельзя сохранить без потерь","markup.opening":"Проём","markup.delete_room":"Удалить комнату","history.undo":"Отменить","history.redo":"Повторить","history.undo_named":"Отменить: {name} (Ctrl+Z)","history.redo_named":"Повторить: {name} (Ctrl+Shift+Z / Ctrl+Y)","history.undo_empty":"Нет операций для отмены","history.redo_empty":"Нет операций для повтора","history.undone":"Отменено: {name}","history.redone":"Повторено: {name}","history.add_room":"Создание комнаты","history.split_room":"Разделение комнаты","history.merge_rooms":"Объединение комнат","history.resize_room":"Изменение размера комнаты","history.wall_thickness":"Изменение толщины стены","history.add_opening":"Добавление дверного или оконного проёма","history.edit_opening":"Изменение проёма","history.move_opening":"Перемещение проёма","history.delete_opening":"Удаление проёма","history.delete_room_keep_walls":"Удаление комнаты с сохранением стен","history.delete_room_with_walls":"Удаление комнаты и её стен","history.decor_add":"Добавление объекта декора","history.decor_edit":"Изменение объекта декора","history.decor_move":"Перемещение объекта декора","history.decor_transform":"Трансформация объекта декора","history.decor_delete":"Удаление объекта декора","history.backdrop_transform":"Трансформация подложки плана","history.device_move":"Перемещение: {name}","history.device_stale":"История позиций больше неприменима и была очищена","opening.new":"Новый проём","opening.edit":"Проём","opening.door":"Дверь","opening.window":"Окно","opening.gate":"Ворота","opening.passage":"Открытый проём","opening.passage_binding_warning":"При сохранении датчик открытия и замок будут удалены.","opening.invalid_passage_fields":"У открытого проёма на плане «{room}» есть недопустимые параметры: {fields}.","opening.type_label":"Тип","opening.length_label":"Длина, см","opening.contact_label":"Датчик открытия","opening.lock_label":"Замок","opening.none":"— нет —","opening.search_ph":"Поиск: имя или entity_id…","opening.invert":"Инвертировать открыто/закрыто","opening.flip_h":"Петли с другой стороны","opening.flip_v":"Открывается в другую сторону","opening.open":"Открыто","opening.closed":"Закрыто","opening.locked":"Заперто","opening.unlocked":"Не заперто","opening.state_unknown":"недоступно","opening.no_entities":"Датчики не привязаны — статичный символ на плане.","toast.opening_no_wall":"Кликните рядом со стеной комнаты или независимой стеной","opening.host_partition":"Независимая стена","opening.partition_orphan":"Независимая стена этого проёма больше не существует","opening.partition_jamb_margin":"Оставьте от края проёма до торца стены минимум {distance}","opening.rebind_partition":"Привязать к другой независимой стене","confirm.delete_partition_openings_title":"Удалить стену и проёмы?","confirm.delete_partition_openings_body":"В стене есть проёмы: {count}. Они будут удалены вместе со стеной.","confirm.delete_partition_openings_item":"• {type}, {length}","markup.hint_points":"точек: {n} · Shift — шаг 45° · Esc — завершить цепочку · Ctrl+Z — убрать точку · при замыкании будет предложена комната","markup.hint_start":"кликните точку сетки, чтобы начать цепочку стен","tip.lqi":"средний сигнал zigbee:","tip.area":"площадь: {value}","info.device_header":"Устройство на плане","info.model":"Модель","info.state":"Состояние","info.link":"Ссылка","info.manuals":"Инструкции","info.none":"Нет дополнительной информации","marker.new_device":"Новое устройство","marker.name_label":"Имя (отображается на плане)","marker.name_ph":"Название","marker.binding_label":"Привязка к устройству HA","marker.binding_disabled":"деактивировано в Home Assistant","marker.virtual_option":"Виртуальное устройство (без привязки)","marker.search_ph":"Поиск устройства / группы…","marker.nothing_found":"ничего не найдено","marker.room_label":"Комната","marker.room_override":" (переопределить размещение)","marker.room_choose":"— выберите комнату —","marker.room_auto":"— по зоне устройства (авто) —","marker.icon_label":"Иконка","marker.icon_ph":"mdi:… (пусто = авто)","marker.display_label":"Отображение","display.badge":"Значок + состояние","display.icon_ripple":"Значок + состояние и активность","display.static_icon":"Всегда статичный значок","marker.display_hint_badge":"Значок и динамическая подложка показывают состояние устройства без обычной пульсации активности. Красная тревога сохраняется.","marker.display_hint_icon_ripple":"Значок, динамическая подложка и пульсация: короткая — для событий, постоянная — для работы, движения или присутствия. Красная тревога имеет отдельный приоритет.","marker.display_hint_value":"Значок заменяется выбранным или автоматически найденным значением Home Assistant; подложка продолжает показывать состояние. Красная тревога сохраняется.","marker.display_hint_static_icon":"Подложка в цветах темы и значок всегда остаются одинаковыми. Состояния, активность, недоступность и тревоги не меняют отображение.","marker.static_alarm_warning":"Это устройство может сообщать о тревогах. Статичный режим скрывает визуальную тревогу маркера.","marker.preview.title":"Предпросмотр отображения","marker.preview.actual":"Сейчас","marker.preview.example":"Пример","marker.preview.integration":"Интеграция","marker.preview.source":"Источник отображения","marker.preview.current_state":"Текущее состояние","marker.preview.result":"На плане","marker.preview.details":"Подробнее об источниках","marker.preview.select_source":"Выберите устройство или сущность Home Assistant, чтобы увидеть фактическое отображение.","marker.preview.unknown_provider":"Интеграция неизвестна","marker.preview.virtual_provider":"House Plan · виртуальное устройство","marker.preview.no_source":"Нет активного источника","marker.preview.no_state":"Нет текущего состояния","marker.preview.mixed_states":"Несколько разных состояний","marker.preview.multiple_sources":"Источников: {n}","marker.preview.more_sources":"ещё {n}","marker.preview.scaled":"Предпросмотр уменьшен до {n}%, чтобы поместиться. Сохранённый размер не изменится.","marker.preview.demo_short":"Показать краткую активность","marker.preview.demo_continuous":"Показать постоянную активность","marker.preview.stop_continuous":"Остановить постоянную активность","marker.preview.demo_short_notice":"Пример краткой активности; фактическое состояние устройства не меняется.","marker.preview.demo_continuous_notice":"Пример постоянной активности; фактическое состояние устройства не меняется.","marker.preview.demo_already_visible":"Текущее состояние уже показывает реальную активность или тревогу.","marker.preview.reduced_motion":"В системе включено уменьшение движения, поэтому обычная активность показана точкой.","marker.preview.reason.neutral":"Нейтральная тёмная подложка","marker.preview.reason.working":"Жёлтая подложка: устройство сейчас работает","marker.preview.reason.working_activity":"Жёлтая подложка и эффект активности: устройство сейчас работает","marker.preview.reason.open":"Оранжевая подложка: физически открыто или разблокировано","marker.preview.reason.cover_icon_state":"Нейтральная подложка; состояние и значок определяет сущность шторы или заслонки","marker.preview.reason.presence":"Эффект активности, пока обнаружено присутствие","marker.preview.reason.event":"Короткий эффект активности после события","marker.preview.reason.transition":"Эффект активности во время движения или смены состояния","marker.preview.reason.media_neutral":"Медиаустройство остаётся на нейтральной тёмной подложке, пока доступно","marker.preview.reason.unavailable":"Приглушённая нейтральная подложка: отключено или недоступно","marker.preview.reason.alarm":"Красная тревожная подложка; тревога отображается всегда","marker.preview.reason.live_states_disabled":"Оформление по живым состояниям отключено в настройках карточки","marker.preview.reason.value_no_state":"Нет подходящего значения состояния — вместо него показан значок","marker.preview.reason.value_ambiguous_sources":"Подходит несколько источников значения — вместо него показан значок","marker.preview.reason.value_non_scalar":"Источник вернул не простое значение — вместо него показан значок","marker.preview.reason.value_virtual":"У виртуального устройства нет значения HA — вместо него показан значок","marker.preview.reason.vacuum_live_plan_only":"Живая позиция и след пылесоса доступны только на полном плане","marker.preview.reason.hidden_design_preview":"Устройство скрыто на плане, но его оформление видно в предпросмотре","marker.preview.reason.composite_power_source":"Состояние берётся из сущности питания устройства; вспомогательные переключатели не учитываются","marker.preview.reason.activity_display_disabled":"Выбранный режим отображения не показывает обычные эффекты активности","marker.preview.reason.ha_disabled":"Привязка отключена в Home Assistant, поэтому устройство будет скрыто на плане","marker.preview.reason.orphaned":"Сохранённая привязка Home Assistant больше не найдена","marker.preview.reason.static_icon":"Статичный режим: состояние устройства не меняет значок","marker.activity_color":"Цвет пульсации активности","marker.ripple_size":"Размер пульсации активности","marker.activity_alarm_note":"Цвет и размер относятся только к обычной активности и не влияют на красную тревогу.","marker.pulse_a11y_alarm":"Тревога","marker.pulse_a11y_event":"Недавнее событие","marker.pulse_a11y_presence":"Обнаружено присутствие","marker.pulse_a11y_transition":"Изменение состояния","marker.pulse_a11y_running":"Работает","marker.state_a11y_neutral":"Обычное состояние","marker.state_a11y_working":"Работает","marker.state_a11y_open":"Открыто","marker.state_a11y_locked":"Заблокировано","marker.state_a11y_unlocked":"Разблокировано","marker.state_a11y_alarm":"Тревога","marker.state_a11y_unavailable":"Недоступно","marker.lqi_a11y_low":"LQI {value}, слабый сигнал","marker.lqi_a11y_mid":"LQI {value}, средний сигнал","marker.lqi_a11y_high":"LQI {value}, сильный сигнал","marker.size_label":"Размер / поворот значка","marker.angle_label":"Поворот","marker.model_label":"Модель","marker.model_ph":"напр. Aqara T&H","marker.link_label":"Ссылка","marker.desc_label":"Описание","marker.desc_ph":"Заметки, характеристики…","marker.manuals_label":"Инструкции (PDF и т.п.)","marker.sub_device":"устройство","marker.sub_z2m_group":" · Z2M-группа","marker.sub_group":"группа","marker.sub_helper":"хелпер","space.new":"Новое пространство","space.copy_title":"Копирование пространства","space.copy_name":"Название нового пространства","space.copy_fallback":"Пространство","space.copy_create":"Создать копию","space.copy_optimize_title":"Оптимизировать перед копированием?","space.copy_optimize_body":"Перед созданием «{name}» House Plan должен оптимизировать весь план, включая другие пространства. Продолжить?","space.copy_optimize_confirm":"Оптимизировать и скопировать","space.copy_error_changed":"План изменился, пока было открыто подтверждение. Проверьте его и повторите попытку.","space.copy_error_source_missing":"Исходного пространства больше нет. Снова откройте его настройки и повторите попытку.","space.copy_error_source_invalid":"House Plan не смог проверить все стены этого пространства. Исправьте исходное пространство и повторите попытку.","space.copy_error_spaces_limit":"В House Plan уже создано максимальное число пространств.","space.copy_error_partitions_limit":"В этом пространстве слишком много стен для копирования.","space.copy_error_openings_limit":"В этом пространстве слишком много проёмов для копирования.","space.copy_error_decor_limit":"В этом пространстве слишком много элементов подложки для копирования.","space.copy_error_columns_limit":"В этом пространстве слишком много колонн для копирования.","space.copy_error_opening_host":"Один из проёмов больше не привязан к стене. Исправьте или удалите его перед копированием.","space.copy_error_geometry":"Копия создаст небезопасную геометрию стен. Исправьте исходное пространство и повторите попытку.","space.copy_error_optimize_geometry":"Копирование остановлено: оптимизация всего плана небезопасна для одного из пространств.","space.header":"Пространство","space.title_label":"Название","space.title_ph":"Например: Гараж","space.plan_label":"Подложка (план)","space.no_plan":"нет подложки","space.plan_alt":"план","room.new":"Новая комната","room.name_label":"Отображаемое имя","room.name_ph":"Например: Терраса","room.area_label":"Зона Home Assistant (свободные)","room.no_area_option":"— без зоны —","room.default_name":"Комната","device.unnamed":"без имени","device.light_group":"группа света","device.fallback":"устройство","device.virtual":"виртуальное устройство","confirm.delete_room_title":"Удалить комнату «{name}»?","confirm.delete_room_body":"Выберите, нужно ли оставить физические стены, принадлежащие только этой комнате. Общие с другой комнатой стены сохраняются всегда.","confirm.remove_marker_title":"Удалить устройство с плана?","confirm.remove_marker_body":"Устройство исчезнет полностью и перестанет участвовать в данных плана. Позже его можно будет добавить заново.","confirm.erase_decor":"Стереть объект «{kind}»? Действие можно отменить из истории редактора.","confirm.delete_space_title":"Удалить пространство?","confirm.delete_space_body":"Пространство, все его комнаты и вся разметка плана будут удалены.","confirm.delete_space_vac_routes":"Также будет снято сопоставление карт роботов: {count}.","space.delete_blocked":"Это пространство всё ещё используется устройствами: {n}. Сначала перенесите их в другое пространство или удалите.","toast.pos_save_failed":"Не удалось сохранить позицию: {err}","toast.no_entity":"У устройства нет подходящей сущности","toast.ha_disabled_action":"Деактивированный объект Home Assistant нельзя использовать на плане.","toast.ha_disabled_show_device":"Деактивированное в Home Assistant устройство нельзя показать на плане. Сначала активируйте его в Home Assistant.","toast.ha_disabled_show_entity":"Деактивированную в Home Assistant сущность нельзя показать на плане. Сначала активируйте её в Home Assistant.","toast.ha_disabled_add":"Деактивированный объект Home Assistant нельзя добавить на план. Сначала активируйте его в Home Assistant.","toast.ha_binding_unverified":"Статус объекта не удалось подтвердить по реестру Home Assistant. Отображение и действия временно недоступны.","toast.markup_needs_server":"Разметка доступна после переноса конфига на сервер","toast.space_order_changed":"Порядок изменён. Если где-то этаж карточки задан номером, проверьте такие панели.","toast.conflict":"Конфиг изменён в другом окне — данные обновлены, повторите последнее действие","toast.cfg_save_failed":"Не удалось сохранить конфиг: {err}","toast.room_overlap":"Контур накладывается на комнату «{name}» — комнаты не должны накладываться","toast.contour_cannot_close":"Контур нельзя замкнуть: он вырожден или пересекает сам себя","toast.merge_not_adjacent":"Объединять можно только комнаты с общей стеной","toast.rooms_merged":"Комнаты объединены в «{name}»","toast.split_pick_wall":"Начните разрез на стене комнаты","toast.split_bad_cut":"Разрез — от стены до стены внутри комнаты, без пересечения стен и самого себя","merge.header":"Объединение комнат","merge.hint":"У объединённой комнаты одно имя и одна зона. Вторая зона освобождается — её устройства уйдут с плана, пока их не заберёт другая комната.","merge.keep":"Оставить","merge.no_area":"без зоны","toast.room_saved":"Комната сохранена ({n}). Устройств добавлено: {added}. Обведите следующую или выйдите из разметки.","toast.room_saved_no_area":"Комната сохранена ({n}, без зоны). Обведите следующую или выйдите из разметки.","toast.marker_needs_server":"Редактирование устройств доступно после переноса конфига на сервер","toast.virtual_name_required":"Укажите имя виртуального устройства","toast.marker_saved":"Устройство сохранено","toast.marker_removed":"Устройство удалено с плана","toast.integration_missing":"Интеграция House Plan не установлена — управление недоступно","toast.plan_formats":"Поддерживаются SVG, PNG, JPG, WebP","toast.plan_required":"Загрузите подложку — план этажа обязателен","toast.space_added_onboard":"Пространство добавлено. Обведите комнаты: кликайте по точкам сетки и замкните контур.","toast.space_added":"Пространство добавлено","toast.space_copied":"Пространство «{name}» создано","toast.space_saved":"Пространство сохранено","toast.space_deleted":"Пространство удалено","toast.delete_failed":"Ошибка удаления: {err}","toast.error":"Ошибка: {err}","toast.toggle_target_unavailable":"Цель «{name}» недоступна — действие не выполнено","toast.toggle_targets_unavailable":"Цели недоступны: {names}. Действие не выполнено","toast.file_failed":"Файл «{name}» не загружен: {err}","toast.files_attached":"Прикреплено файлов: {n}","err.unknown":"неизвестная ошибка","err.code":"код {code}","err.too_large":"файл больше {mb} МБ","err.bad_ext":"недопустимый тип (нужен PDF/изображение)","err.unauthorized":"нужны права администратора","editor.title":"Заголовок","editor.default_floor":"Стартовое пространство","editor.default_floor_missing":"Стартовое пространство «{id}» больше не существует. Выберите другое.","editor.floor":"Закреплённое пространство","editor.floor_none":"— не закреплять —","editor.floor_index":"YAML-индекс {index} (сохранён)","fixed_floor.loading":"Загружаем закреплённое пространство…","fixed_floor.invalid_title":"Закреплённое пространство недоступно","fixed_floor.invalid_body":"Проверьте floor в конфигурации карточки. Настроенное значение: {value}","editor.icon_size":"Размер иконок, % ширины плана","editor.show_temperature":"Показывать температуру","editor.live_states":"Живые состояния (вкл/выкл, открыто…)","editor.light_pools":"Световые пулы и тени от стен","editor.show_signal":"Показывать сигнал zigbee (LQI)","editor.language":"Язык интерфейса","editor.lang_auto":"Авто (профиль HA)","title.icon_rules":"Правила иконок: какая MDI-иконка достаётся устройству по имени","rules.title":"Правила иконок","rules.hint":"Правила проверяются сверху вниз по строке «имя устройства + модель» (regex без учёта регистра); срабатывает первое совпадение. Если ничего не подошло — решает device class сущности, затем — иконка-заглушка.","rules.pattern_ph":"regex, напр. розетк|plug","rules.icon_ph":"mdi:power-socket-de","rules.add":"Добавить правило","rules.reset":"Сбросить к умолчаниям","rules.test_ph":"Проверьте имя устройства…","rules.invalid":"некорректный regex","rules.saved":"Правила иконок сохранены","btn.up":"Вверх","btn.down":"Вниз","tap.info":"Карточка устройства","tap.more_info":"Диалог HA (more-info)","tap.toggle":"Переключить состояние","marker.tap_label":"Действие по нажатию для этого устройства","tap.toggle_note":"Под селектором показано, какое состояние изменится. Защищённые устройства не переключаются с плана.","import.title":"Создать пространства из этажей HA","import.hint":"Home Assistant уже знает эти этажи. Отметьте, какие превратить в пространства плана — далее для каждого попросим картинку плана. Комнаты затем обводятся вручную по плану.","import.start":"Создать: {n}","import.manual":"Начать с нуля","import.progress":"Этаж {i} из {n}","import.done":"Пространства созданы. Обведите комнаты: кликайте по точкам сетки и замкните контур.","btn.skip":"Пропустить","space.scale_label":"Масштаб (размер клетки сетки)","space.cell_cm.help":"Связывает сетку с реальными размерами: от значения зависят длины и площади, толщина стен, размеры проёмов и радиус свечения. Изменение после разметки меняет расчётные размеры всего пространства, но не двигает его точки на плане.","space.cell_cm.help.aria":"Подсказка: масштаб пространства","space.scale_unit":"см на клетку","space.scale_unit_imperial":"дюйм на клетку","space.display_section":"Отображение","space.show_borders":"Всегда отображать границы комнат","space.zero_wall_style":"Стены нулевой толщины","space.zero_wall_style.help":"Пунктирные стены нулевой толщины пропускают Glow и солнечные лучи, сплошные блокируют их как барьер нулевой площади. Выбор меняет все такие стены пространства, даже когда их линии скрыты в просмотре.","space.zero_wall_style.help.aria":"Подсказка: вид стен нулевой толщины","space.zero_wall_dashed":"Пунктирные","space.zero_wall_solid":"Сплошные","space.show_names":"Отображать названия комнат (перетаскиваются)","space.room_color":"Цвет границ и названий","space.opacity":"Прозрачность","space.fill_label":"Заливка комнат","space.fill_mode.help":"«Свой цвет» задаёт оформление, а «Свет», «Температура» и «LQI» используют текущие данные Home Assistant; Glow включается отдельно.","space.fill_mode.help.aria":"Подсказка: режим заливки комнат","fill.none":"Нет","fill.lqi":"По силе зигби-сигнала","fill.light":"По освещению","fill.custom":"Свой цвет","space.custom_fill":"Цвет заливки","space.source_file":"У меня есть картинка плана","space.source_draw":"Нет подложки — нарисую комнаты вручную","fill.temp":"По температуре","tip.temp_avg":"средняя температура:","tip.hum_avg":"средняя влажность:","space_card.button":"Перейти к пространству","space_card.not_found":"Пространство «{id}» не найдено","space_card.loading":"Загрузка…","continuity.restore_plan":"Восстанавливаем план…","continuity.restore_connection":"Восстанавливаем подключение к устройствам…","continuity.retry":"Повторить","editor.space":"Пространство","editor.framing":"Кадрирование","editor.fit_content":"Всё видимое содержимое","editor.fit_house":"Плотно по геометрии дома","editor.show_button":"Показывать кнопку","editor.button_label":"Текст кнопки","editor.button_target":"Путь дашборда (куда вести)","marker.sub_entity":"сущность","title.general_settings":"Общие настройки","gs.title":"Общие настройки","gs.light_group":"Заливка: освещение","gs.light_on":"Свет включён","gs.light_off":"Весь свет выключен","gs.temp_group":"Заливка: температура","gs.temp_cold":"Холодно","gs.temp_ok":"Комфорт","gs.temp_hot":"Жарко","gs.lqi_group":"Заливка: зигби-сигнал","gs.lqi_low":"Слабый сигнал","gs.lqi_high":"Сильный сигнал","gs.reset":"Сбросить к умолчаниям","gs.saved":"Общие настройки сохранены","space.show_lqi":"Показывать зигби-сигнал (LQI) у устройств","space.hide_decor":"Скрыть декоративный слой","space.hide_decor_tip":"Линии, фигуры, надписи и мебель остаются на месте — их видно в редакторе подложки, но не на плане.","space.hide_openings":"Скрыть проёмы","space.hide_openings_tip":"Двери, окна и ворота не рисуются, но продолжают работать: свет проходит, солнце светит в окна, датчики открытия срабатывают. В редакторе плана проёмы видно всегда.","gs.light_none":"Нет источников света","mode.plan":"Редактор плана","mode.devices":"Редактор устройств","display.value":"Значение + состояние","marker.subarea":"без зоны, вручную","device.new":"Новое устройство — откройте его редактор, чтобы снять отметку","opening.unlock_action":"Открыть замок","opening.lock_action":"Закрыть замок","opening.lock_pending":"Выполняется…","title.close_editor":"Закрыть редактор (вернуться к просмотру)","title.add_device":"Добавить устройство на план","devbar.add":"Добавить","devbar.rules":"Правила иконок","device_inbox.button":"Устройства","device_inbox.title":"Устройства на плане","device_inbox.search":"Поиск по устройствам, сущностям и интеграциям…","device_inbox.add_virtual":"Добавить виртуальное устройство","device_inbox.tab_on_plan":"На плане","device_inbox.tab_available":"Доступны","device_inbox.tab_hidden":"Скрытые","device_inbox.tab_readd":"Доступны снова","device_inbox.only_new":"Только новые","device_inbox.show_entities":"Показывать сущности","device_inbox.show_hidden":"Показывать скрытые на плане","device_inbox.show_hidden.help":"Временно показывает на плане скрытые и деактивированные маркеры служебными призраками только в редакторе устройств. Сохранённая видимость устройств не меняется.","device_inbox.show_hidden.help.aria":"Подсказка: показывать скрытые устройства на плане","device_inbox.new":"Новое","device_inbox.find":"Найти на плане","device_inbox.edit":"Настроить","device_inbox.hide":"Скрыть","device_inbox.show":"Показать","device_inbox.add":"Добавить","device_inbox.readd":"Добавить заново","device_inbox.hide_available":"Скрыть из списка","device_inbox.show_more":"Показать ещё","device_inbox.more_actions":"Другие действия","device_inbox.find_hidden_hint":"Сначала включите «Показывать скрытые на плане»","device_inbox.show_disabled":"Перед показом активируйте эту привязку в Home Assistant","device_inbox.empty_on_plan":"На плане пока нет подходящих устройств.","device_inbox.empty_available":"Нет доступных устройств для добавления.","device_inbox.empty_hidden":"Скрытых устройств нет.","device_inbox.empty_readd":"Нет удалённых устройств, доступных для повторного добавления.","device_inbox.reason_visible_auto":"Найдено автоматически","device_inbox.reason_visible_explicit":"Добавлено явно","device_inbox.reason_manual_hidden":"Скрыто пользователем","device_inbox.reason_automatic_hidden":"Скрыто автоматически","device_inbox.reason_service_entry":"Служебная запись реестра","device_inbox.reason_excluded_integration":"Исключена интеграция «{integration}»","device_inbox.reason_excluded_domain":"Непространственный тип сущности","device_inbox.reason_grouped_light":"Представлено группой света комнаты","device_inbox.reason_represented_by_parent":"Представлено родительским устройством","device_inbox.reason_removed":"Ранее удалено с плана","device_inbox.reason_available":"Можно добавить на план","device_inbox.reason_no_bound_room":"Зона HA не связана с комнатой плана","device_inbox.status_ha_disabled":"Отключено в Home Assistant","device_inbox.status_orphaned":"Привязка больше не найдена в Home Assistant","device_inbox.status_unverified":"Реестр Home Assistant временно недоступен","device_inbox.saved":"Список устройств обновлён","device_inbox.filters_excluded":"Исключённые интеграции","device_inbox.filters_group_lights":"Объединять светильники комнаты в один маркер","device_inbox.filters_preview_appear":"появится: {count}","device_inbox.filters_preview_hide":"скроется: {count}","device_inbox.filters_preview_lights":"затронет светильников: {count}","device_inbox.filters_reset":"Вернуть рекомендуемые","device_inbox.filters_save":"Сохранить фильтры","device_inbox.filters_search_ph":"Добавить интеграцию…","device_inbox.filters_title":"Фильтры обнаружения","space.roomcard_section":"В карточке комнаты:","space.label_temp":"Температура","space.label_hum":"Влажность","space.label_lqi":"Средний Zigbee-сигнал","space.label_light":"Свет вкл/выкл","roomcard.light_on":"Вкл","roomcard.light_off":"Выкл","roomcard.light_partial":"{on} из {total}","toast.split_pick_inside":"Промежуточные точки разреза — внутри комнаты","mode.decor":"Редактор подложки","decor.select":"Выбрать","decor.line":"Линия","decor.rect":"Прямоугольник","decor.ellipse":"Овал","decor.text":"Надпись","decor.erase":"Стереть","decor.erase_confirm_title":"Стереть объект?","decor.color":"Цвет","decor.width":"Толщина линии","decor.line_style":"Стиль линии","decor.line_style_solid":"Сплошная","decor.line_style_dashed":"Пунктирная","decor.fill":"Заливка","decor.fill_color":"Цвет заливки","decor.length":"Длина","decor.size":"Размер","decor.flip_h":"Отзеркалить по горизонтали","decor.flip_v":"Отзеркалить по вертикали","decor.angle":"Угол поворота, °","decor.text_size":"Размер текста","decor.backdrop_properties":"Свойства картинки-подложки","decor.text_title":"Надпись","decor.object_title":"Редактирование: {kind}","decor.text_label":"Текст","decor.live_group":"Вставить переменную HA","decor.live_entity":"Сущность","decor.live_entity_ph":"выберите сущность","decor.live_attr":"Значение","decor.live_attr_ph":"выберите состояние или атрибут","decor.live_state":"Состояние","decor.backdrop":"Картинка-подложка","decor.backdrop_hint":"Тяните картинку — перемещение; угол — размер; верхнюю ручку — поворот. Shift меняет пропорции или снимает шаг угла.","decor.backdrop_reset":"Вернуть картинку","decor.backdrop_reset_done":"Картинка вернулась на своё место и в свой размер","marker.icon_auto":"Авто: {icon} (по правилам иконок; выберите свою, чтобы заменить)","marker.icon_pin_auto":"Закрепить","mode.plan_tip":"Редактор плана — геометрия дома: рисование и объединение/разделение комнат, привязка к зонам HA, двери, окна и ворота, карточки комнат, масштаб","mode.devices_tip":"Редактор устройств — всё про значки: перетаскивание, клик — настройка привязки/иконки/отображения, виртуальные устройства, правила иконок","mode.decor_tip":"Редактор подложки — чисто визуальный декор под планом: линии, прямоугольники, овалы и надписи, не реагирующие на клики","space.glow_enabled":"Свечение источников света","gs.glow_group":"Свечение источников света","gs.glow_base":"Темнота дома","gs.glow_light":"Цвет света по умолчанию / интенсивность","gs.wall_group":"Стены","gs.wall_fill":"Цвет заливки стен","gs.glow_radius":"Радиус свечения","gs.glow_radius.help":"Задаёт общий радиус светового пятна в метрах или футах; персональный радиус устройства заменяет это значение.","gs.glow_radius.help.aria":"Подсказка: общий радиус свечения","gs.unit_m":"м","gs.unit_ft":"фут","marker.controls_label":"Управляет другими источниками света","marker.controls.help":"При действии «Переключить состояние» перечисленные источники переключаются вместе с этим маркером. Их световые пятна остаются у собственных маркеров, а эта связь сама по себе не делает управляющий маркер источником света.","marker.controls.help.aria":"Подсказка: управление другими источниками света","marker.controls_filter":"Поиск ламп и выключателей…","info.controls":"Управляет","marker.glow_radius_label":"Радиус свечения","marker.glow_radius.help":"Задаёт радиус свечения в метрах или футах; пустое значение использует радиус из общих настроек.","marker.glow_radius.help.aria":"Подсказка: радиус свечения","markup.wallthick":"Толщина","markup.select":"Выбрать","title.markup_wallthick":"Толщина — клик по стене задаёт толщину от 0 до 100 см.","markup.hint_wallthick":"клик по стене · Esc закрывает без применения","wallthick.field":"Толщина","wallthick.unit_cm":"см","wallthick.unit_in":"дюйм","wallthick.apply_room":"Применить ко всем стенам комнаты","markup.draw_wall_title":"Толщина каждого нового сегмента стены (0–100 см). Общие стены сохраняют существующее значение.","room.queue_progress":"Комната {current} из {total}","toast.wall_rooms_saved":"Создано комнат: {n}","toast.wall_chain_saved":"Цепочка стен сохранена","toast.wallthick_pick":"Кликните по стене","toast.wallthick_set":"Толщина стены задана","toast.wallthick_cleared":"Толщина стены убрана","toast.physical_range":"Введите значение от {min} до {max} {unit}","toast.zero_wall_opening_conflict":"Сначала удалите проём на этом участке стены.","toast.zero_wall_ambiguous":"Не удалось однозначно выбрать участок стены. Уточните геометрию узла.","toast.zero_wall_migration_blocked":"Пространство не преобразовано: {reason}. Данные не изменены.","toast.physical_angle":"Введите угол поворота от 0° до 90°, не включая 90°","toast.physical_limit":"В пространстве достигнут лимит объектов этого типа","toast.geometry_unsafe":"Изменение отменено: геометрию стен нельзя безопасно построить.","junction.limit_angle":"Слишком острый угол между стенами: {actual}°, минимум {limit}°.","junction.limit_valence":"Слишком много стен в одном узле: {actual}, максимум {limit}.","junction.limit_length":"Слишком короткий участок стены: {actual} см, минимум {limit} см.","junction.limit_distance":"Стены и узлы слишком близко: {actual} см, минимум {limit} см.","junction.limit_clearance":"Внутри комнаты не остаётся места: {actual} см², минимум {limit} см².","junction.limit_check_failed":"Проверку стыков выполнить не удалось — изменение не сохранено","toast.wall_model_migration_blocked":"Не удалось обновить модель стен: {reason}. План не изменён. Запустите «Оптимизировать планы»; если ошибка повторится, исправьте конфликтующую геометрию стен.","toast.wall_model_client_outdated":"Обновите карточку и перезагрузите страницу перед редактированием плана.","wall_model.reason.invalid-room":"некорректный контур комнаты","wall_model.reason.zero-length":"отрезок стены нулевой длины","wall_model.reason.third-owner":"стена принадлежит более чем двум комнатам","wall_model.reason.duplicate-id":"конфликт идентификаторов стен","wall_model.reason.thickness-conflict":"конфликт значений толщины стены","wall_model.reason.opening-host":"проём нельзя однозначно привязать к стене","toast.delete_room_pick":"Кликните внутри комнаты, которую нужно удалить","toast.plan_snap_ambiguous":"Увеличьте масштаб, чтобы выбрать узел стены","toast.wall_repair_ambiguous":"У контура несколько возможных соединений. Увеличьте масштаб и соедините стены явно.","toast.wall_repair_too_large":"Разрыв больше 2 см. Соедините стены перед созданием комнаты.","toast.wall_repair_changed":"Геометрия стен изменилась. Попробуйте создать комнату ещё раз.","toast.opening_on_zero_wall":"Проёмы на стене нулевой толщины запрещены","marker.from_ha_option":"Выбрать из списка HA","marker.show_entities":"Показывать сущности","marker.show_entities_tip":"Добавляет в список не только устройства, но и все их сущности","marker.pick_ph":"Выберите устройство…","room.open_area":"Открыть зону в HA","room.fit_action":"Вписать комнату {name}","view.volumetric":"Объёмный вид","view.flat":"Плоский вид","kiosk.title":"Размеры на этом экране","kiosk.hint":"Хранится только на этом устройстве — у каждого настенного планшета или ТВ свои удобные размеры.","kiosk.icon_scale":"Размер значков устройств","kiosk.font_scale":"Размер текста карточек комнат","editor.kiosk":"Режим настенного устройства (киоск)","editor.cycle":"Автосмена пространств каждые N секунд (киоск, 0 = выкл)","room.settings_title":"Настройки комнаты","room.settings_section":"Настройки комнаты (переопределяют пространство)","room.fill_label":"Заливка в ЭТОЙ комнате","fill.inherit":"Как у пространства","room.custom_fill_space":"Цвет пространства","room.custom_fill_own":"Цвет комнаты","room.temp_src_label":"Источник температуры","room.hum_src_label":"Источник влажности","room.src_average":"Средняя по датчикам комнаты (по умолчанию)","room.src_pick":"Конкретное устройство или сущность HA","room.src_ph":"Выберите источник…","toast.room_updated":"Комната обновлена","space.card_font":"Размер шрифта карточек комнат (всё пространство)","room.sizes_section":"Размеры шрифтов","room.name_scale":"Размер названия","room.label_scale":"Размер подписей","preview.room_name":"Гостиная","toast.cfg_reload_failed":"Не удалось перечитать план с сервера: {err}","toast.locale_load_failed":"Не удалось загрузить языковой пакет. До перезагрузки страницы используется английский.","toast.furniture_art_load_failed":"Не удалось загрузить изображения мебели. Обновите страницу, чтобы их показать.","room.settings_short":"Настройки комнаты","room.unnamed":"Комната без имени","marker.use_climate_temp":"Учитывать температуру устройства в комнате","marker.use_climate_temp_tip":"Добавляет current_temperature кондиционера или термостата в среднюю температуру комнаты. Внешний бейдж со значением настраивается отдельно ниже.","marker.value_badge_title":"Бейдж со значением","marker.value_badge.help":"Показывает одно выбранное значение рядом со значком. Не влияет на комнатные показатели, свет, Glow и действие по нажатию.","marker.value_badge.help.aria":"Подсказка: бейдж со значением устройства","marker.value_badge_enabled":"Отображать бейдж со значением","marker.value_badge_source":"Значение","marker.value_badge_source.help":"Выберите конкретное состояние, поддерживаемый атрибут или производное значение этого устройства.","marker.value_badge_source.help.aria":"Подсказка: источник значения бейджа","marker.value_badge_position":"Расположение","marker.value_badge_position.help":"Выбранная сторона сохраняется постоянно и не переворачивается автоматически у края плана.","marker.value_badge_position.help.aria":"Подсказка: расположение бейджа","marker.value_badge_right":"Справа","marker.value_badge_bottom":"Снизу","marker.value_badge_left":"Слева","marker.value_badge_top":"Сверху","marker.value_badge_empty":"У этого устройства нет доступных значений","marker.value_badge_static":"Статичный значок не показывает живые значения. Настройка сохранится.","marker.value_badge_missing":"Источник недоступен","marker.value_badge_missing_hint":"Сохранённый источник сейчас недоступен. Можно сохранить его, отключить бейдж или выбрать другой.","marker.value_badge_duplicate":"То же значение уже показано внутри значка.","marker.value_badge_state":"Состояние · {name}","marker.value_badge_marker_state":"Состояние источника света · {name}","marker.value_badge_lqi":"Качество Zigbee-сигнала (среднее)","marker.value_badge_attr_current_temperature":"Текущая температура · {name}","marker.value_badge_attr_temperature":"Целевая температура · {name}","marker.value_badge_attr_current_humidity":"Текущая влажность · {name}","marker.value_badge_attr_humidity":"Влажность · {name}","marker.value_badge_attr_current_position":"Положение · {name}","marker.value_badge_attr_percentage":"Скорость · {name}","marker.value_badge_attr_brightness":"Яркость · {name}","marker.value_badge_attr_volume_level":"Громкость · {name}","marker.value_badge_attr_battery_level":"Заряд батареи · {name}","marker.value_badge_attr_fan_speed":"Скорость вентилятора · {name}","marker.value_source":"Источник значения","marker.value_source.help":"Выберите, что заменит значок. Действие по нажатию не изменится.","marker.value_source.help.aria":"Подсказка: источник значения внутри значка","marker.value_source_auto":"Автоматически (как раньше)","marker.value_source_missing_hint":"Сохранённый источник сейчас недоступен. До его восстановления или выбора другого значения внутри будет показано —.","marker.light_role_label":"Является источником света","marker.light_role.help":"«Авто» использует фактическую роль привязанного устройства, «Всегда» принудительно создаёт собственный источник, а «Никогда» исключает его; связанные лампы выше остаются независимыми.","marker.light_role.help.aria":"Подсказка: является ли устройство источником света","marker.light_role_auto_yes":"Автоматически (источник света)","marker.light_role_auto_no":"Автоматически (не источник света)","marker.light_role_always":"Всегда источник света","marker.light_role_never":"Никогда не источник света","marker.light_entity_label":"Ведущая сущность света","marker.light_entity.help":"Для составного устройства выберите сущность, состояние, цвет и яркость которой представляют этот источник на плане. Автоматический вариант сохраняет совместимость со старыми планами.","marker.light_entity.help.aria":"Подсказка: ведущая сущность света","marker.light_entity_auto":"Автоматически ({entity})","marker.light_entity_none":"нет управляемой сущности","marker.light_entity_missing":"Сохранённая сущность {entity} недоступна. Временно используется {fallback}; выбор восстановится, если сущность вернётся.","marker.toggle_entity_label":"Переключаемая сущность","marker.toggle_entity.help":"Для составного устройства выберите собственную лампу или переключатель, которой управляет нажатие. Автоматический вариант сохраняет прежние правила цели и не зависит от ведущей сущности света.","marker.toggle_entity.help.aria":"Подсказка: переключаемая сущность","marker.toggle_entity_auto":"Автоматически ({entity})","marker.toggle_entity_none":"нет собственной управляемой сущности","marker.toggle_entity_missing":"Сохранённой сущности {entity} больше нет среди выбираемых каналов этого маркера. Временно используется {fallback}; выбор восстановится, если сущность вернётся.","marker.glow_color_label":"Цвет и яркость свечения","marker.glow_mode.help":"Используйте данные источника, задайте только цвет или зафиксируйте цвет и яркость. Минимум — 1%; чтобы отключить источник, выберите «Никогда».","marker.glow_mode.help.aria":"Подсказка: цвет и яркость свечения","marker.glow_mode_auto":"Из источника","marker.glow_mode_color":"Задать цвет","marker.glow_mode_fixed":"Задать цвет и яркость","marker.glow_color":"Цвет свечения","marker.glow_brightness":"Яркость","marker.glow_disabled_never":"Настройки свечения недоступны: маркер явно исключён из источников света.","marker.glow_disabled_auto":"В автоматическом режиме у этого маркера не найден пространственный источник света.","marker.glow_disabled_no_entity":"Для пространственного источника нет активной управляемой сущности Home Assistant.","marker.glow_passive_hint":"У источника нет собственных данных Home Assistant. Задайте цвет и яркость вручную; радиус остаётся доступным.","marker.control_broken":"Сохранённый источник отсутствует или больше не отмечен как источник света","marker.control_missing_label":"Отсутствующий источник на плане","marker.control_passive":"пассивный источник","toast.marker_control_cycle":"Такая связь создаст циклическую цепочку управления светом.","toast.marker_binding_required":"Сначала выберите устройство Home Assistant, затем добавьте управляемый источник света.","confirm.unlock_title":"Открыть замок?","confirm.unlock_body":"House Plan отправит этому замку команду открытия.","toast.files_migrate_failed":"Не удалось перенести вложения к новой привязке, ссылки остались на старые файлы: {err}","space.pick_saved":"Уже загруженные","space.pick_saved_hint":"Планы, сохранённые на сервере, включая отцеплённые ранее","space.no_saved":"На сервере пока нет сохранённых планов.","space.loading":"Загрузка…","space.used_by":"используется: {list}","space.in_use":"План используется пространством — сначала отцепите его","btn.use":"Выбрать","confirm.delete_plan_title":"Удалить файл плана?","confirm.delete_plan_body":"Файл будет удалён с сервера. Это действие нельзя отменить.","toast.plans_list_failed":"Не удалось получить список планов: {err}","toast.plan_delete_failed":"Не удалось удалить план: {err}","marker.hide":"Скрыть","marker.hide_tip":"Устройство исчезнет с плана после сохранения, но продолжит участвовать в расчёте сигнала комнаты. Вернуть его можно через каталог «Устройства» в редакторе устройств.","marker.show":"Показать","marker.show_tip":"Устройство снова появится на плане после сохранения.","marker.hidden_ghost":"Устройство скрыто пользователем","marker.ha_disabled_device":"Устройство деактивировано в Home Assistant и скрыто с плана.","marker.ha_disabled_entity":"Сущность деактивирована в Home Assistant и скрыта с плана.","marker.ha_disabled_all_entities":"У устройства нет активных сущностей Home Assistant, поэтому оно скрыто с плана.","marker.ha_registry_limited":"Полный реестр Home Assistant недоступен этому пользователю. Неподтверждённый объект временно нельзя показывать или использовать.","marker.delete_tip":"Полностью удалить устройство с плана и из всех расчётов. Позже его можно добавить заново.","tap.run":"Запустить автоматизацию/скрипт/сцену","tap.none":"Ничего не делать","marker.run_target_label":"Что запускать","marker.run_search_ph":"Поиск: автоматизация, скрипт или сцена…","marker.run_target_gone":"Цель {id} не найдена — выберите заново","marker.tap_confirm":"Спрашивать подтверждение","marker.tap_confirm_tip":"Перед выполнением показать диалог подтверждения — защита от случайных нажатий.","marker.toggle_hint_single":"Цель: {name} ({id}).","marker.virtual_light_target":"Виртуальный свет: {name}.","marker.virtual_light_current":"Ручное состояние: {state} → {effect}.","marker.virtual_light_state_on":"включён","marker.virtual_light_state_off":"выключен","marker.toggle_hint_group":"Переключатся источники ({count}): {names}.","marker.toggle_hint_current":"Сейчас: {state} → {effect}.","marker.toggle_hint_group_current":"Сейчас включено {on} из {count} → {effect}.","marker.toggle_hint_skipped":"Не будут затронуты ({count}): {targets}.","marker.toggle_effect_turn_on":"включится","marker.toggle_effect_turn_off":"выключится","marker.toggle_effect_open":"откроется","marker.toggle_effect_close":"закроется","marker.toggle_effect_stop":"остановится","marker.toggle_effect_toggle":"состояние переключится","marker.toggle_skip_missing":"не найдено","marker.toggle_skip_ha_disabled":"деактивировано в HA","marker.toggle_skip_unavailable":"недоступно","marker.toggle_skip_unsupported":"переключение не поддерживается","marker.toggle_skip_secure":"заблокировано из соображений безопасности","marker.toggle_none_no_binding":"У устройства нет привязки, состояние переключать нечем. По нажатию ничего не произойдёт.","marker.toggle_none_no_actionable_entity":"У устройства нет состояния, которое можно переключить. По нажатию ничего не произойдёт.","marker.toggle_none_configured_targets_missing":"Настроенные цели сейчас недоступны. Собственная сущность устройства не будет подставлена вместо них.","marker.toggle_none_ha_disabled":"Цель деактивирована в Home Assistant и не может использоваться на плане.","marker.toggle_none_unavailable":"Цель сейчас недоступна. По нажатию ничего не произойдёт.","marker.toggle_none_unsupported":"Для этой сущности Home Assistant не предоставляет безопасного переключения. По нажатию ничего не произойдёт.","marker.toggle_none_secure":"Переключение замков, сигнализации и защитных ворот с плана заблокировано из соображений безопасности.","run.automation":"автоматизация","run.script":"скрипт","run.scene":"сцена","confirm.tap_run":"Запустить «{name}»?","confirm.tap_toggle":"Переключить «{name}»?","confirm.current_state":"Текущее состояние: {state}","confirm.expected_state":"После переключения: {state}","confirm.group_current":"включено {on} из {total}","confirm.group_all_on":"все включены","confirm.group_all_off":"все выключены","confirm.unavailable_targets":"Недоступно: {count}","confirm.expected_by_ha":"Состояние определит Home Assistant","confirm.state_on":"Включено","confirm.state_off":"Выключено","confirm.state_open":"Открыто","confirm.state_closed":"Закрыто","confirm.state_opening":"Открывается","confirm.state_closing":"Закрывается","confirm.state_stopped":"Остановлено","confirm.state_unknown":"Неизвестно","toast.run_started":"Запущено: {name}","toast.run_target_missing":"Цель запуска не найдена — проверьте настройки устройства","toast.run_target_required":"Выберите автоматизацию, скрипт или сцену","toast.tap_target_changed":"Цель действия изменилась. Повторите попытку.","toast.virtual_light_toggle_failed":"Не удалось переключить виртуальный свет: {err}","toast.value_badge_source_required":"Выберите значение для бейджа","btn.run":"Выполнить","vac.section":"Робот-пылесос: живая позиция","vac.autocal":"Настроить автоматически","vac.live":"Живая позиция на плане","vac.trail":"Показывать путь робота","vac.autocal_no_rooms":"Интеграция не отдаёт список комнат — откройте «Подогнать вручную»","vac.route_warn_unmapped":"Робот убирает на карте, которая не сопоставлена ни одному этажу","vac.route_warn_needs_calibration":"Карта сопоставлена этажу, но не откалибрована","vac.route_warn_ambiguous":"Две карты неразличимы — этаж не выбран","vac.route_warn_missing_space":"Пространство этой карты удалено","vac.autocal_no_match":"Не совпали имена комнат (нужно ≥3 общих) — откройте «Подогнать вручную»","vac.autocal_done":"Готово: привязка по {rooms} комнатам. Запустите уборку и проверьте","vac.cal_need_pos":"Робот сейчас не отдаёт координаты — запустите уборку и поставьте на паузу","vac.cal_done":"Калибровка сохранена. Запустите уборку и проверьте","vac.cal_cancelled":"Калибровка отменена","vac.fit":"Подогнать вручную","vac.fit_hint":"Перетащите карту робота на место, растяните за уголки","vac.fit_rotate":"Повернуть 90°","vac.fit_mirror":"Отразить","vac.trail_never":"Не показывать никогда","vac.trail_cleaning":"Во время уборки","vac.trail_always":"Показывать всегда","gs.bg_group":"Фон сцены","gs.bg_color":"Цвет фона вокруг плана","gs.bg_default":"Как в теме","gs.bg_theme":"по умолчанию — из темы","gs.bg_mode":"Фон плана","gs.bg_mode.help":"«Следует за Солнцем» использует sun.sun, а при недоступности — локальные часы браузера; статичный режим всегда показывает выбранный цвет.","gs.bg_mode.help.aria":"Подсказка: общий фон плана","gs.bg_static":"Статичный цвет","gs.bg_daynight":"Следует за Солнцем","gs.sun_group":"Солнце","gs.sun_missing":"Сущность sun.sun не найдена — фон следует локальным часам, а оконные лучи недоступны.","gs.north":"Север на плане","gs.north.help":"Угол отсчитывается по часовой стрелке от верхней вертикали плана; север нужен для оконных лучей, а не для фона «Следует за Солнцем».","gs.north.help.aria":"Подсказка: общее направление севера","gs.north_ph":"не задан","gs.north_clear":"Сбросить","gs.north_letter":"С","gs.sun_rays":"Солнце в окнах","gs.about_version":"Houseplan Card v{v}","gs.about_github":"GitHub · документация и issues","gs.about_telegram":"Чат в Telegram","support.title":"Помощь и обратная связь","space.bg_color":"Цвет фона вокруг плана","space.bg_inherit":"Наследовать общий","space.bg_inherited":"наследуется из общих настроек","space.bg_mode":"Фон плана","space.bg_mode.help":"Выберите наследование общего фона либо переопределите это пространство статичным цветом или режимом «Следует за Солнцем».","space.bg_mode.help.aria":"Подсказка: фон пространства","space.north":"Север на плане (переопределение)","space.north.help":"Переопределяет общий север для этого пространства; угол отсчитывается по часовой стрелке от верхней вертикали плана и используется оконными лучами.","space.north.help.aria":"Подсказка: север для пространства","space.north_inherited":"наследуется: {v}","space.sun_rays":"Солнце в окнах","space.sun_inherit":"Наследовать общий","space.sun_on":"Вкл","space.sun_off":"Выкл","canvas.far_objects":"Объектов далеко от плана: {n}","canvas.show_far":"Показать","canvas.home_tip":"План там — нажмите, чтобы вписать","gs.grid_group":"Обслуживание планов","gs.grid_hint":"Обновляет модели данных, выравнивает элементы по сетке и объединяет лишние фрагменты стен. Перед записью будет показан точный отчёт.","gs.align_all":"Оптимизировать планы","gs.align_title":"Оптимизировать планы","gs.align_none":"Все планы уже используют актуальную и оптимальную модель данных.","gs.optimize_no_automatic_changes":"Автоматических изменений нет. Проверьте пункты ниже.","gs.align_count":"Сдвинется элементов: {n} из {total}, максимум на {cm} см.","gs.align_where":"Наибольший сдвиг — в пространстве «{s}».","gs.align_turned":"Проёмов с исправлением угла: {n}.","gs.align_preflight_failed":"Не удалось безопасно проверить геометрию следующих пространств: {spaces}{more}.","gs.align_preflight_hint":"Планы не изменены. Скопируйте диагностику кнопкой ниже и приложите её к отчёту об ошибке вместе с экспортом пространства.","gs.preflight_reason_prepare-exception":"Не удалось подготовить геометрию пространства (исключение при сборке модели)","gs.preflight_reason_wall-null":"Тело стен не построилось (объединение вернуло пустоту)","gs.preflight_reason_wall-degraded-extra":"Тело стен деградировало с лишней геометрией","gs.preflight_reason_wall-failed-core":"Ядро тела стен не собралось","gs.preflight_reason_wall-exception":"Построение стен упало с исключением","gs.preflight_reason_floor-null":"Контур пола не построился","gs.preflight_reason_floor-exception":"Построение пола упало с исключением","gs.preflight_copy":"Скопировать диагностику","gs.preflight_copied":"Диагностика скопирована","gs.preflight_update_hint":"Версии карточки и интеграции различаются — обновите House Plan и повторите.","gs.align_preflight_space":"Пространство {n}","gs.align_preflight_more":" и ещё {n}","gs.optimize_changes":"Миграций модели: {m}; обновлено пространств: {c}; устранён шум координат: {p}; объединено отрезков реальных стен: {w}; объединено отрезков стен нулевой толщины: {s}; независимых: {i}.","gs.zero_walls_migrated":"Преобразовано виртуальных участков: {n}.","gs.wall_segments_migrated":"Стабилизировано сегментов стен: {n}.","gs.room_drafts_migrated":"Незавершённые контуры преобразованы в обычные стены: {drafts}; отрезков: {segments}.","gs.optimize_lattice_summary":"Канонизировано шумовых значений координат: {n}; максимальный сдвиг: {cm} см.","gs.optimize_lattice_space":"{space}: канонизировано значений координат: {n}; оставлено значений вне сетки: {far}.","gs.optimize_coincident_partitions":"Скрытые участки независимых стен поглощены стенами комнат: {n}.","gs.optimize_openings_rehosted":"Проёмы перепривязаны к стенам комнат: {n}.","gs.optimize_walls_straightened":"Выпрямлено стен: {n}; максимальное перемещение: {cm} см.","gs.optimize_walls_straightened_where":"Максимальная правка стены: {s}.","gs.optimize_walls_straighten_skipped":"Оставлено почти осевых стен, которые нельзя безопасно выпрямить: {n}.","gs.optimize_glow_migration":"Старый Glow: пространств — {spaces} → без заливки данных + независимый Glow; комнат — {rooms} → наследуемая заливка + независимый Glow.","gs.optimize_references":"Исправлено ссылок: пространства — {spaces}; комнаты — {rooms}; позиции — {positions}; устройств отвязано от отсутствующих пространств — {detached}.","gs.optimize_reference_more":", и ещё {n}","gs.optimize_orphans_removed":"Убрано забытых записей: {total} — подписи комнат: {rooms}; устройства: {devices}; групповые метки: {groups}. Все они принадлежали пространствам, удалённым ранее.","gs.optimize_live_positions":"Старые позиции в удалённых пространствах принадлежат существующим объектам: {n}{names}. Они будут сохранены.","gs.optimize_live_positions_remove":"Старые позиции в удалённых пространствах принадлежат существующим объектам: {n}{names}. Они выбраны для удаления.","gs.optimize_live_names":": {names}{more}","gs.optimize_live_remove":"Убрать старые позиции","gs.optimize_live_keep":"Сохранить старые позиции","gs.optimize_live_selected":"Старые позиции будут убраны после применения оптимизации.","gs.optimize_unverified":"Не удалось безопасно проверить позиций: {n}. Они оставлены без изменений.","gs.optimize_registry_limited":"Для безопасной проверки нужен полный доступ администратора к реестрам Home Assistant.","gs.optimize_vacuum_warning":"Сопоставления комнат пылесоса требуют проверки: {n}.","gs.optimize_details":"Подробности","gs.optimize_details_more":"И ещё записей: {n}.","gs.optimize_detail_removed":"будет удалено","gs.optimize_detail_live":"будет сохранено","gs.optimize_detail_unverified":"не проверено","gs.optimize_detail_room_label":"подпись комнаты","gs.optimize_detail_device":"устройство","gs.optimize_detail_group":"групповая метка","gs.optimize_detail_unknown":"неизвестный владелец","gs.optimize_detail_item":"{status}: {kind} {id}; прежнее пространство {space}","gs.align_warn":"Элементы, намеренно поставленные между узлами, будут сдвинуты. После операции доступна одна отмена — только до следующего изменения плана.","gs.align_run":"Оптимизировать","gs.align_done":"Планы оптимизированы: сдвинуто элементов — {n}, обслужено записей — {m}, исправлено ссылок — {r}","gs.optimize_undo":"Отменить последнюю оптимизацию","gs.optimize_undone":"Последняя оптимизация отменена","decor.furniture":"Мебель","decor.image":"Изображение","decor.image_title":"Свои изображения","decor.image_upload":"Загрузить изображение","decor.image_replace":"Заменить изображение","decor.image_uploading":"Загрузка…","decor.image_asset":"Файл изображения","decor.image_pick_hint":"Загрузите изображение или выберите уже используемое в House Plan.","decor.image_place_hint":"Кликните по плану, чтобы разместить изображение.","decor.image_none":"Загруженных изображений пока нет.","decor.image_unavailable":"Изображение недоступно","decor.image_used":"Используется в объектах: {n}","decor.image_upload_failed":"Не удалось загрузить изображение: {err}","decor.image_error_capacity":"Хранилище пользовательских изображений заполнено.","decor.image_in_use":"Перед удалением файла удалите все размещённые копии.","decor.image_delete_title":"Удалить файл изображения?","decor.image_delete_message":"Удалить «{name}» из House Plan? Это действие нельзя отменить.","furn.title":"Библиотека мебели","furn.symbol":"Символ","furn.group_furniture":"Мебель","furn.group_appliance":"Техника","furn.group_sanitary":"Сантехника","furn.group_other":"Прочее","furn.width":"Ширина","furn.depth":"Глубина","furn.back_to_categories":"Все категории","furn.pick_hint":"Выберите категорию, затем символ.","furn.place_hint":"Кликните по плану — предмет встанет к ближайшей стене. Shift — свободно.","furn.cat_air_conditioner":"Кондиционеры","furn.cat_armchair":"Кресла","furn.cat_bathtub":"Ванны","furn.cat_bed":"Кровати","furn.cat_bidet":"Биде","furn.cat_boiler":"Бойлеры","furn.cat_chair":"Стулья","furn.cat_coffee_table":"Журнальные столы","furn.cat_cooktop":"Варочные панели","furn.cat_dining_table":"Обеденные столы","furn.cat_dishwasher":"Посудомоечные машины","furn.cat_dryer":"Сушильные машины","furn.cat_fireplace":"Камины","furn.cat_fridge":"Холодильники","furn.cat_kitchen_cabinet":"Кухонные шкафы","furn.cat_kitchen_sink":"Кухонные мойки","furn.cat_nightstand":"Тумбы","furn.cat_plant":"Растения","furn.cat_rug":"Ковры","furn.cat_shelving":"Стеллажи","furn.cat_shower":"Душевые","furn.cat_sink":"Раковины","furn.cat_sofa":"Диваны","furn.cat_stairs":"Лестницы","furn.cat_toilet":"Унитазы","furn.cat_tv":"Телевизоры","furn.cat_wardrobe":"Шкафы","furn.cat_washer":"Стиральные машины","furn.cat_work_table":"Рабочие столы","furn.sym_sofa":"Диван двухместный","furn.sym_sofa_three_seat":"Диван трёхместный","furn.sym_sofa_corner_right":"Угловой диван, правый","furn.sym_armchair":"Кресло мягкое","furn.sym_armchair_office":"Кресло офисное","furn.sym_coffee_table":"Журнальный стол, прямоугольный","furn.sym_coffee_table_round":"Журнальный стол, круглый","furn.sym_coffee_table_oval":"Журнальный стол, овальный","furn.sym_coffee_table_rounded":"Журнальный стол, скруглённый","furn.sym_table_dining":"Обеденный стол, прямоугольный","furn.sym_table_round":"Круглый стол","furn.sym_table_dining_oval":"Обеденный стол, овальный","furn.sym_table_dining_rounded":"Обеденный стол, скруглённый","furn.sym_chair":"Стул","furn.sym_chair_bar":"Барный стул","furn.sym_desk":"Рабочий стол, прямоугольный","furn.sym_desk_corner":"Рабочий стол, угловой","furn.sym_bed_double":"Двуспальная кровать","furn.sym_bed_single":"Односпальная кровать","furn.sym_nightstand":"Тумба прикроватная","furn.sym_cabinet_tv":"Тумба под телевизор","furn.sym_cabinet_shoe":"Тумба для обуви","furn.sym_cabinet_sink":"Тумба под раковину","furn.sym_wardrobe":"Шкаф гардеробный","furn.sym_bookshelf":"Шкаф книжный","furn.sym_wall_unit":"Шкаф-стенка","furn.sym_kitchen_floor":"Кухонный напольный модуль","furn.sym_kitchen_floor_corner":"Кухонный напольный угловой модуль","furn.sym_kitchen_wall":"Кухонный навесной модуль","furn.sym_kitchen_wall_corner":"Кухонный навесной угловой модуль","furn.sym_shelf_floor":"Стеллаж напольный","furn.sym_shelf_wall":"Полка настенная","furn.sym_fridge":"Холодильник","furn.sym_stove":"Варочная панель, 4 конфорки","furn.sym_cooktop_two":"Варочная панель, 2 конфорки","furn.sym_dishwasher":"Посудомоечная машина","furn.sym_washer":"Стиральная машина","furn.sym_dryer":"Сушильная машина","furn.sym_tv":"Телевизор на подставке","furn.sym_tv_wall":"Телевизор на кронштейне","furn.sym_ac":"Кондиционер","furn.sym_water_heater":"Бойлер","furn.sym_toilet":"Унитаз напольный","furn.sym_toilet_built_in":"Унитаз встроенный","furn.sym_bathtub":"Ванна прямоугольная","furn.sym_bathtub_corner":"Ванна угловая","furn.sym_shower":"Душ","furn.sym_sink":"Раковина","furn.sym_kitchen_sink":"Кухонная мойка одинарная","furn.sym_kitchen_sink_double":"Кухонная мойка двойная","furn.sym_bidet":"Биде напольное","furn.sym_bidet_built_in":"Биде встроенное","furn.sym_stairs":"Лестница","furn.sym_fireplace":"Камин","furn.sym_plant":"Растение","furn.sym_rug":"Ковёр","common.yes":"Да","common.no":"Нет","vac.diag_source":"Источник","vac.diag_platform":"Интеграция","vac.diag_status":"Статус","vac.diag_position":"Позиция","vac.diag_rooms":"Комнаты","vac.diag_rooms_value":"{total} · совпало имён: {matched} · {readiness}","vac.autocal_ready":"автокалибровка доступна","vac.autocal_not_ready":"нужно 3 совпавших имени","vac.diag_path":"Путь интеграции","vac.diag_map":"ID карты","vac.source_none":"не выбран","vac.source_status_ok":"Готов","vac.source_status_missing":"Не найден","vac.source_status_disabled":"Деактивирован в Home Assistant","vac.source_status_unavailable":"Недоступен","vac.source_status_unverified":"Нельзя проверить с текущими правами","vac.source_status_unsupported":"Нет данных позиции","vac.source_status_none":"Нет источника","vac.source_banner_missing":"Сохранённый источник больше не существует. Он не заменён автоматически: выберите другой или восстановите его в Home Assistant.","vac.source_banner_disabled":"Сохранённый источник деактивирован в Home Assistant. Активируйте его там или выберите другой.","vac.source_banner_unverified":"Текущих прав Home Assistant недостаточно для проверки источника. Привязка сохранена и не будет заменена автоматически.","vac.choose_source":"Выбрать источник","vac.source_auto":"Автоматически","vac.source_auto_hint":"Использовать совместимую сущность этого устройства","vac.all_cameras":"Все камеры","vac.all_cameras_warn":"Камера может не отдавать данные робота. Выбирайте её только если это карта вашего пылесоса.","vac.all_cameras_empty":"Других сущностей камеры не найдено.","vac.platform_unknown":"интеграция неизвестна","vac.cap_position":"позиция","vac.cap_rooms_short":"комнаты","vac.cap_path":"путь","vac.cap_map":"ID карты","vac.cap_none":"данные робота не обнаружены","vac.xcme_hint":"Включите атрибуты Xiaomi Cloud Map Extractor:","vac.documentation":"Документация","vac.residual_title":"Проверьте автокалибровку","vac.residual_message":"Совпавшие комнаты расходятся максимум на {error}. Примените приблизительную калибровку, подгоните её вручную либо отмените без изменения сохранённых настроек.","vac.apply_proposal":"Применить","gs.backup_group":"Резервная копия и перенос","gs.backup_hint":"Скачайте переносимую JSON-копию или проверьте и импортируйте копию, созданную House Plan.","backup.export_open":"Экспорт","backup.import_open":"Импорт","backup.export_title":"Экспорт House Plan","backup.import_title":"Импорт House Plan","backup.export_hint":"Выберите, должна ли копия содержать всю конфигурацию House Plan или только текущее пространство.","backup.full":"Полная копия","backup.current_space":"Текущее пространство","backup.current_space_title":"Текущее пространство: {title}","backup.no_current_space":"Нет текущего пространства","backup.plan_only":"Только планировка","backup.plan_only_hint":"Сохранить комнаты, стены, проёмы, декор и позиции подписей комнат без устройств и привязок Home Assistant.","backup.plan_only_preview":"Файл содержит только планировку","backup.privacy_warning":"Архив сохраняет названия, идентификаторы Home Assistant и точные координаты. Внутренние планы и вложения указываются ссылками, но не вкладываются; текущие состояния и маршруты пылесосов не включаются.","backup.download":"Скачать JSON","backup.export_done":"Резервная копия скачана","backup.reading":"Проверяем резервную копию…","backup.revalidated":"После предпросмотра план изменился. Сводка обновлена — проверьте её и подтвердите ещё раз.","backup.error.support_invalid_message":"Проверьте сообщение для поддержки и повторите попытку.","backup.error.support_package_too_large":"Обезличенный пакет для поддержки превышает лимит 8 МиБ.","backup.error.support_preview_expired":"Предпросмотр вложения для поддержки истёк или больше недоступен.","backup.error.support_rate_limited":"Запрошено слишком много репортов или предпросмотров. Повторите позже.","backup.error.support_rejected":"Репорт не прошёл проверку службы поддержки.","backup.error.support_unavailable":"Закрытая служба поддержки временно недоступна.","backup.error.unauthorized":"У вас нет прав на экспорт или импорт этого плана.","backup.error.not_ready":"House Plan ещё не готов. Повторите попытку через несколько секунд.","backup.error.too_large":"Размер резервной копии превышает 8 МиБ.","backup.error.invalid_json":"Выбранный файл не является корректным JSON.","backup.error.invalid_format":"Выбранный файл не является резервной копией House Plan.","backup.error.invalid_image":"Изображение повреждено или не соответствует своему формату.","backup.error.unsupported_export_version":"Эта версия формата резервной копии не поддерживается установленной версией.","backup.error.unsupported_image":"Используйте поддерживаемое изображение PNG, JPEG, WebP или SVG.","backup.error.future_model":"Резервная копия создана в более новой версии модели данных House Plan.","backup.error.invalid_config":"Резервная копия содержит некорректную конфигурацию House Plan.","backup.error.wall_model_migration_blocked":"Не удалось безопасно обновить модель стен из резервной копии. Сначала оптимизируйте исходный план и повторите экспорт.","backup.error.invalid_layout":"Резервная копия содержит некорректные позиции объектов.","backup.error.invalid_content":"Резервная копия содержит некорректные или несогласованные ссылки на файлы.","backup.error.space_not_found":"Выбранное пространство больше не существует.","backup.error.capacity_exceeded":"Добавление этой копии превысит ограничения размера плана.","backup.error.preview_expired":"Время предпросмотра истекло. Выберите файл резервной копии заново.","backup.error.preview_owner_mismatch":"Этот предпросмотр принадлежит другому пользователю Home Assistant.","backup.error.conflict":"После предпросмотра план изменился. Проверьте обновлённую сводку.","backup.error.content_confirmation_required":"Подтвердите отсоединение недоступных локальных файлов.","backup.error.commit_failed":"Не удалось безопасно применить копию. Предыдущий план восстановлен или ожидает восстановления.","backup.error.missing_plan":"После предпросмотра исчез связанный файл плана. Проверьте копию ещё раз.","backup.error.missing_content":"После предпросмотра исчез связанный локальный файл. Проверьте копию ещё раз.","backup.error.marker_control_missing":"В резервной копии отсутствует связанный источник света на плане.","backup.error.marker_control_not_light":"Связанная цель больше не отмечена как источник света.","backup.error.marker_control_self":"Источник света не может управлять самим собой.","backup.error.marker_control_cycle":"Резервная копия содержит циклическую цепочку управления светом.","backup.error.duplicate_marker_control":"Резервная копия содержит повторяющуюся связь с источником света.","backup.error.no_backup":"Нет снимка импорта или оптимизации, который можно восстановить.","backup.error.in_use":"Элемент ещё используется","backup.error.invalid_data":"Запрос содержит некорректные данные","backup.error.invalid_light_entity":"Ведущий свет должен быть сущностью light.* или switch.*","backup.error.invalid_marker_control":"Некорректная ссылка управления маркером","backup.error.invalid_name":"Некорректное имя","backup.error.invalid_partition_opening_host":"Проём должен сохранить свою перегородку-носитель","backup.error.invalid_partition_opening_jamb_margin":"Проём не оставляет физического простенка у края стены","backup.error.invalid_passage_fields":"Открытый проход не может нести настройки двери","backup.error.invalid_space_id":"Неизвестное пространство","backup.error.invalid_toggle_entity":"Сущность переключения должна быть light.* или switch.*","backup.error.invalid_value_badge":"Некорректные настройки бейджа значения","backup.error.invalid_value_badge_attribute":"Некорректный атрибут бейджа значения","backup.error.invalid_value_badge_position":"Некорректная позиция бейджа значения","backup.error.invalid_value_badge_source":"Некорректный источник бейджа значения","backup.error.invalid_vacuum_map_route":"Проверьте сопоставление карт робота пространствам.","backup.error.invalid_value_source":"Некорректный источник значения","backup.error.invalid_value_source_attribute":"Некорректный атрибут источника значения","backup.error.io_error":"Файловая операция на сервере не удалась","backup.error.not_toggleable":"Это устройство нельзя переключить","backup.error.nothing_to_repair":"Нечего чинить","backup.error.space_in_use":"На пространство ещё есть ссылки","backup.error.value_badge_source_required":"Бейджу значения нужен источник","backup.error.wall_model_client_outdated":"План обновлён в другом месте — перезагрузите страницу","backup.same_source":"Создано на этом экземпляре Home Assistant","backup.foreign_source":"Создано на другом экземпляре Home Assistant","backup.created":"Создано: {value}","backup.versions":"Карточка {card}; интеграция {integration}; модель данных {model}","backup.count_spaces":"Пространств: {n}","backup.count_rooms":"Комнат: {n}","backup.count_walls":"Стен: {n}","backup.count_openings":"Проёмов: {n}","backup.count_decor":"Объектов декора: {n}","backup.count_markers":"Устройств: {n}","backup.count_layout":"Позиций: {n}","backup.bindings":"Привязки — устройства: {device}, сущности: {entity}, виртуальные: {virtual}; позиций без пространства: {legacy}","backup.binding_status":"Статус на целевом экземпляре — активных: {active}, деактивированных: {disabled}, отсутствующих: {missing}","backup.missing_areas":"На целевом экземпляре отсутствуют зоны: {areas}","backup.dropped_marker_links":"Связи с источниками света вне переносимого пространства пропущены: {n}.","backup.room_drafts_migrated":"Старые незавершённые контуры преобразованы в обычные стены: {drafts}; отрезков: {segments}.","backup.repaired_target_refs":"Существующих ссылок восстановлено этим импортом: {n}.","backup.preserved_unresolved_refs":"Неоднозначные ссылки сохранены без изменений: {n}.","backup.preserved_unresolved_hint":"House Plan ничего не угадывал и не удалял. После импорта запустите «Оптимизировать планы», чтобы проверить оставшиеся ссылки.","backup.import_details":"Подробности восстановления ссылок","backup.import_detail.incoming_remapped":"Ссылок обновлено внутри импортируемой копии: {n}","backup.import_detail.target_repaired":"Существующих ссылок восстановлено: {n}","backup.import_detail.preserved_unresolved":"Неразрешимых ссылок сохранено: {n}","backup.import_detail.collisions":"Конфликтов назначения безопасно сохранено: {n}","backup.import_detail.dropped_links":"Входящих связей пропущено по правилам переноса: {n}","backup.import_detail.bounded_lineages":"Чрезмерно вложенных идентификаторов ограничено: {n}","backup.replace_warning":"Текущая конфигурация и расположение будут заменены. Загруженные файлы не удаляются. Одну отмену можно выполнить до следующего изменения плана.","backup.foreign_bookkeeping":"Служебные списки известных и новых устройств другого экземпляра импортированы не будут.","backup.final_name":"Название нового пространства","backup.target_settings":"Глобальные настройки целевого экземпляра не изменятся.","backup.duplicates":"Уже существующих привязок: {n}","backup.skip":"Пропустить повторяющиеся устройства","backup.virtual_copy":"Добавить безопасные статичные виртуальные копии","backup.content":"Связанное содержимое","backup.decor_images_summary":"Свои изображения: объектов — {objects}, файлов — {assets}; отсутствует файлов — {missing}.","backup.content_available":"доступно локально","backup.content_external":"внешняя ссылка","backup.content_detach_required":"будет отвязано","backup.confirm_detach":"Я понимаю, что недоступные внутренние планы и вложения будут отвязаны от импортируемой конфигурации.","backup.confirm_missing_images":"Я понимаю, что отсутствующие свои изображения останутся восстанавливаемыми заглушками, а остальные недоступные локальные файлы будут отвязаны.","backup.replace":"Заменить","backup.add":"Добавить пространство","backup.space_done":"Пространство импортировано: комнат — {rooms}, устройств — {markers}, существующих ссылок восстановлено — {refs}","backup.full_done":"Копия восстановлена: пространств — {spaces}, комнат — {rooms}, устройств — {markers}","backup.undo_import":"Отменить последний полный импорт","backup.import_undone":"Полный импорт отменён","backdrop.large_title":"Большое изображение","backdrop.large_body":"Изображение {w}×{h} ({fileMb} МБ), для показа потребуется около {decodedMb} МБ памяти. На планшетах это может привести к падению страницы.","backdrop.unknown_body":"Не удалось прочитать размеры изображения — файл может быть повреждён. Продолжение может привести к падению страницы на планшете.","backdrop.reduced_dimensions":"Уменьшенная копия: {w}×{h} px.","backdrop.use_downscaled":"Загрузить уменьшенную копию","backdrop.reducing":"Уменьшаем…","backdrop.keep_original":"Оставить оригинал","backdrop.too_large_title":"Изображение слишком большое","backdrop.too_large_body":"Изображение превышает возможности браузера ({w}×{h}, предел {limit} px по стороне). Уменьшите его в редакторе на компьютере и загрузите снова.","backdrop.downscale_failed":"Не удалось создать уменьшенную копию. Текущий план не изменён."}},{code:"de",nativeLabel:"Deutsch",loadDictionary:async function(e){const t=0===e?await import("./de-CK49IrCl.js"):await import(new URL("./de-CK49IrCl.js?retry",import.meta.url).href);return{dictionary:t.dictionary,fingerprint:t.fingerprint}}},{code:"fr",nativeLabel:"Français",loadDictionary:async function(e){const t=0===e?await import("./fr-HLiHJMys.js"):await import(new URL("./fr-HLiHJMys.js?retry",import.meta.url).href);return{dictionary:t.dictionary,fingerprint:t.fingerprint}}}],zu=Cu,Iu=new Set;const Ou=new class{constructor(e,t,i=console.warn,n){this.entries=e,this.expectedFingerprint=t,this.warn=i,this.loadFailed=n,this.dictionaries=new Map,this.pending=new Map,this.failed=new Set;for(const t of e)t.dictionary&&this.dictionaries.set(t.code,t.dictionary)}state(e){return this.dictionaries.has(e)?"ready":this.failed.has(e)?"fallback":"pending"}dictionary(e){return this.dictionaries.get(e)}ensure(e){if("pending"!==this.state(e))return Promise.resolve();const t=this.pending.get(e);if(t)return t;const i=this.entries.find(t=>t.code===e),n=this.load(i).finally(()=>this.pending.delete(e));return this.pending.set(e,n),n}async load(e){if(!e?.loadDictionary)return void(e&&this.failed.add(e.code));let t;for(const i of[0,1])try{const t=await e.loadDictionary(i);if(t.fingerprint!==this.expectedFingerprint)throw new Error(`locale fingerprint mismatch for ${e.code}`);return this.dictionaries.set(e.code,t.dictionary),void this.failed.delete(e.code)}catch(e){t=e}this.failed.add(e.code),this.warn(`[houseplan] unable to load ${e.code} locale; using English`,t),this.loadFailed?.(e.code)}}(Fu,"5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f",console.warn,function(e){for(const t of Iu)t(e)});function Eu(e){const t=Lu(e)?.code??"en";return Ou.dictionary(t)??zu}function Nu(e){return"string"==typeof e?e.trim().replaceAll("_","-").toLowerCase():""}const Hu=new Map(Fu.map(e=>[Nu(e.code),e]));function Lu(e){return Hu.get(Nu(e))}function Bu(e,t){const i=[{value:"",label:e},...Fu.map(({code:e,nativeLabel:t})=>({value:e,label:t}))],n="string"==typeof t?t:"";return n&&!i.some(e=>e.value===n)&&i.push({value:n,label:Lu(n)?.nativeLabel??n}),i}function qu(e,t){return function(e,t,i,n){const r=new Map(i.map(e=>[Nu(e),e])),o=r.get(Nu(e));if(o)return o;const s=Nu(t),a=r.get(s);return a||(r.get(s.split("-")[0]||"")??n)}(t,e?.locale?.language||e?.language,Fu.map(({code:e})=>e),"en")}function ju(e,t,i){return Qi(Eu(e)[t]??zu[t]??t,i)}function Wu(e,t){const i=Eu(e)[t]??zu[t];return"string"==typeof i&&i.trim().length>0}function Uu(e,t,i,n){return{ox:0,oy:0}}function Vu(e,t){const i=(e.angle+90)*Math.PI/180,n=za(16,t),r=e.gateFace?-n*e.gateFace.side:n*(e.flipV?-1:1);return[[e.x+Math.cos(i)*r,e.y+Math.sin(i)*r],r<0]}function Gu(e){const t=e.length/2,i=e.face.cm>0?e.face.cm/e.cellCm*e.gridPitch/2:za(4,e.cellCm),n="gate"===e.type?Math.sin(10*Math.PI/180)*t:0;return{half:t,jambHalf:i,gateDepth:n,outlineHalf:Math.max(za(16,e.cellCm),i+za(8,e.cellCm),n+za(8,e.cellCm)),hitHalf:Math.max(za(20,e.cellCm),i+za(10,e.cellCm),n+za(12,e.cellCm))}}function Ku(e,t,i){e.minX=Math.min(e.minX,t),e.minY=Math.min(e.minY,i),e.maxX=Math.max(e.maxX,t),e.maxY=Math.max(e.maxY,i)}function Yu(e,t,i,n,r,o,s,a){const l=Math.min(s,a)*Math.PI/180,c=Math.max(s,a)*Math.PI/180,h=(e,t)=>{const i=Math.atan2(t,e),n=[l,c];for(let e=-3;e<=3;e++){const t=e*Math.PI-i,r=Math.PI/2+e*Math.PI-i;t>l&&tl&&r0&&[e.length,e.angle,t[0],t[1]].every(Number.isFinite)))return null;const{half:i,jambHalf:n}=Gu(e),r=Fa(e.cellCm),o=1.75*r,s=1.25*r,a=.75*r,l={minX:-i-s,minY:-n-s,maxX:i+s,maxY:n+s},c={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("window"===e.type)Yu(c,-i,0,i,-o,o,-90,0),Yu(c,i,-i,0,-o,o,0,90),Ku(c,-i-a,-i-a),Ku(c,i+a,a);else if("gate"===e.type){const t=10*e.face.side;Yu(c,-i,0,i,-o,o,0,t),Yu(c,i,-i,0,-o,o,-t,0)}else Yu(c,-i,0,e.length,-o,o,-90,0),Ku(c,-i-a,-e.length-a),Ku(c,i+a,a);const[h,d]=Xu(e),u={...l};Ku(u,c.minX+h,c.minY+d),Ku(u,c.maxX+h,c.maxY+d);const p=e.flipH?-1:1,_="gate"===e.type?1:e.flipV?-1:1,m=e.angle*Math.PI/180,g=Math.cos(m),f=Math.sin(m),v={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};for(const e of[u.minX,u.maxX])for(const i of[u.minY,u.maxY]){const n=e*p,r=i*_;Ku(v,t[0]+n*g-r*f,t[1]+n*f+r*g)}return v}function Ju(e){if("passage"===e.type)return W``;const t=Math.max(0,Math.min(1,e.amount)),{half:i,jambHalf:n}=Gu(e),r=Fa(e.cellCm),o=1.75*r,s=e.flipH?-1:1,a=e.flipV?-1:1,l="gate"===e.type?1:a,[c,h]=Xu(e);let d;if("window"===e.type){const o=Math.PI/2*i,s=e.face.cm>0?W``:W``;d=W`
- `});return W`${s}`}function Wp(e,t,i){const n=i>0?i:1;return{a:[e[0]/n,e[1]/n],b:[t[0]/n,t[1]/n]}}function Up(e,t){const i=t>0?t:1;return[e.a[0]*i,e.a[1]*i,e.b[0]*i,e.b[1]*i]}function Vp(e){return Array.isArray(e)&&e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))}function Gp(e){if(!Array.isArray(e))return[];const t=[];for(const i of e){if(!i||"object"!=typeof i)continue;const e=i;if(!Vp(e.a)||!Vp(e.b))continue;const n=[Number(e.a[0]),Number(e.a[1])],r=[Number(e.b[0]),Number(e.b[1])];Math.hypot(r[0]-n[0],r[1]-n[1])<.001||t.push({a:n,b:r})}return t}function Kp(e,t,i,n,r=!0){const o=(e||[]).filter(e=>e?.id),s=Gp(t);if(s.length)return function(e,t,i,n){const r=Gp(e);if(!r.length)return[];const o=function(e,t){const i=[],n=(e||[]).filter(e=>e?.id);for(let e=0;e4*n||o>4*n)continue;const s=(e[0]-r)*u+(e[1]-l)*p,c=(e[2]-r)*u+(e[3]-l)*p,h=Math.max(0,Math.min(s,c)),m=Math.min(d,Math.max(s,c));if(m-he.lo-t.lo||e.hi-t.hi);const i=[];for(const e of t){const t=i[i.length-1];t&&e.lo<=t.hi+a?t.hi=Math.max(t.hi,e.hi):i.push({...e})}for(const t of i){const i=[r+u*t.lo,l+p*t.lo],n=[r+u*t.hi,l+p*t.hi];Math.hypot(n[0]-i[0],n[1]-i[1])i.pair===e&&Math.abs(i.ux*s-i.uy*o)<=1e-6&&Math.abs((t[0]-i.origin[0])*i.uy-(t[1]-i.origin[1])*i.ux)<=c&&Math.abs((t[2]-i.origin[0])*i.uy-(t[3]-i.origin[1])*i.ux)<=c);h||(h={pair:e,origin:[t[0],t[1]],ux:o,uy:s,ranges:[]},l.push(h));const d=(t[0]-h.origin[0])*h.ux+(t[1]-h.origin[1])*h.uy,u=(t[2]-h.origin[0])*h.ux+(t[3]-h.origin[1])*h.uy;h.ranges.push({lo:Math.min(d,u),hi:Math.max(d,u)})}const h=[];for(const e of l){e.ranges.sort((e,t)=>e.lo-t.lo||e.hi-t.hi);const t=[];for(const i of e.ranges){const e=t[t.length-1];e&&i.lo<=e.hi+a?e.hi=Math.max(e.hi,i.hi):t.push({...i})}for(const n of t){const t=[e.origin[0]+e.ux*n.lo,e.origin[1]+e.uy*n.lo],r=[e.origin[0]+e.ux*n.hi,e.origin[1]+e.uy*n.hi];Math.hypot(r[0]-t[0],r[1]-t[1])>=a&&h.push(Wp(t,r,i))}}return h}(s,e,i,n).map(e=>Up(e,i));if(!r)return[];const a=[],l=(e,t)=>(e.open_to||[]).includes(t.id)||(t.open_to||[]).includes(e.id);for(let e=0;er)&&qo([o[0],o[1]],[o[2],o[3]],i))return!0;return!1}const Xp=e=>Array.isArray(e)&&e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1])),Zp=(e,t,i)=>[Number(e[0])*i,Number(e[1])*i,Number(t[0])*i,Number(t[1])*i],Jp=e=>{const t=`${Number(e[0]).toFixed(9)},${Number(e[1]).toFixed(9)}`,i=`${Number(e[2]).toFixed(9)},${Number(e[3]).toFixed(9)}`;return t<=i?`${t}|${i}`:`${i}|${t}`},Qp=e=>{const t=new Map;for(const i of e.flat())!Array.isArray(i)||i.length<4||!i.every(Number.isFinite)||Math.hypot(i[2]-i[0],i[3]-i[1])<=1e-9||t.set(Jp(i),[...i]);return[...t.values()]};function e_(e){return"solid"===e?.zero_wall_style?"solid":"dashed"}function t_(e,t=1,i){const n=[];for(const r of Array.isArray(e?.wall_segments)?e.wall_segments:[])0===Number(r?.cm)&&Xp(r?.a)&&Xp(r?.b)&&(i&&!i.has(String(r.id||""))||n.push(Zp(r.a,r.b,t)));return Qp([n])}function i_(e,t=1){const i=[];for(const n of Array.isArray(e?.partitions)?e.partitions:[])0===Number(n?.cm)&&Xp(n?.a)&&Xp(n?.b)&&i.push(Zp(n.a,n.b,t));return Qp([i])}function n_(e,t,i,n){if(!e)return[];const r=Gp(e.open_spans);return Kp(t,r.length?r:null,i,n,!0)}function r_(e,t,i,n){const r=e_(e),o=new Set;for(const e of t.rooms||[])for(const t of Array.isArray(e.wall_ids)?e.wall_ids:[])"string"==typeof t&&t&&o.add(t);const s=Qp([t_(t,1,o.size?o:void 0),n_(e,t.rooms,i,n)]),a=Qp([s,i_(t,1)]);return{style:r,lines:a,contour:s,barriers:"solid"===r?a:[],transmissive:"dashed"===r?s:[]}}function o_(e,t){return(e||[]).some(e=>e?.host?.kind===t.kind&&e.host.id===t.id)}function s_(e){return e instanceof Error?e.name||"Error":typeof e}function a_(e){return ic({id:e?.id??"",cell_cm:e?.cell_cm,rooms:e?.rooms||[],walls:e?.walls||[],wall_segments:e?.wall_segments||[],open_spans:e?.open_spans||[],openings:e?.openings||[],partitions:e?.partitions||[],wall_columns:e?.wall_columns||[]})}function l_(e,t,i={}){const n=(Array.isArray(e?.spaces)?e.spaces:[]).find(e=>String(e?.id||"")===String(t||"")),r=a_(n);if(!n)return{spaceId:String(t||""),displayName:"",status:"failed",reason:"prepare-exception",fingerprint:r,ok:!1};const o=__({...e,spaces:[n]},{...i,fingerprint:()=>r}).spaces[0]||{spaceId:String(t||""),displayName:"",status:"failed",reason:"prepare-exception"};return{...o,fingerprint:r,ok:"failed"!==o.status}}function c_(e,t,i,n=Ka,r=1e3){return(Array.isArray(e?.openings)?e.openings:[]).flatMap(e=>{const o={...e,rx:Number(e.x)*r,ry:Number(e.y)*r,rlen:Number(e.length)*r};if(!e.host||"wall"===e.host.kind)return[o];const s=vu(e,t.partitions,r,i,n);return s.resolved?[{...e,rx:s.resolved.center[0],ry:s.resolved.center[1],rlen:s.resolved.length,angle:s.resolved.angle,partitionHost:s.resolved}]:[]})}function h_(e,t=()=>!0){return e.flatMap(e=>e.host&&e.partitionHost&&t(e)?[wu(e.partitionHost)]:[])}function d_(e,t,i,n,r,o,s=Ka,a=1e3){const l=$s(t.rooms,[...i],n,r,o,s,a);return e.flatMap(e=>{const t={x:e.rx,y:e.ry,angle:Number(e.angle)||0,length:e.rlen};return e.host&&"wall"!==e.host.kind?e.partitionHost&&Su(e.partitionHost,l,2e-4*s)?[t]:[]:[t]})}function u_(e,t){const i=Ya,n=Ka,r=Na,o=Number.isFinite(Number(t.cellCm))&&Number(t.cellCm)>0?Number(t.cellCm):5,s=Array.isArray(e?.walls)?e.walls:[],a=function(e,t,i=Ka,n=1e3){return Kp(t.rooms,e?.open_spans,n,.02*i)}(e,t,n,r),l=function(e,t,i=Ka){if(!t.length)return[];const n=e.filter(e=>e?.id),r=.02*i,o=[];for(let e=0;e{const t=[(e[0]+e[2])/2,(e[1]+e[3])/2];return h.some(e=>Bn(t,e)<4*r)}).map(e=>[...e]);d.length&&o.push({a:s,b:a,segs:d})}return o}(t.rooms,a,n).flatMap(e=>e.segs),c=c_(e,t,o,n,r),h=h_(c),d=ba(t,o,n,2e-4*n,h).all;return{space:t,walls:s,openCuts:l,openings:c,roomOpenings:d_(c,t,s,l,i,o,n,r),partitionCuts:h,physicalBodies:d,wallKeyPitch:i,cellCm:o,gridPitch:n,coordScale:r}}function p_(e,t,i){const n="string"==typeof e?.title?e.title.trim():"",r=null==e?.id?"":String(e.id).trim();return{spaceId:r,displayName:n||r||i(t+1)}}function __(e,t={}){const i=(t.fingerprint||ic)(e),n=Array.isArray(e?.spaces)?e.spaces:[],r=t.fallbackSpaceName||(e=>`Space ${e}`),o=t.prepareSpace||u_,s=t.wallPass||Gs,a=t.floorPass||js,l=[];for(let i=0;i0||d.physicalBodies.length>0;if(!d.space.rooms.length&&!u){l.push({...h,status:"not-applicable"});continue}let p=null;if(u){try{p=s(d.space.rooms,d.walls,d.openCuts,d.roomOpenings,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale,d.physicalBodies)}catch(e){l.push({...h,status:"failed",reason:"wall-exception",detail:s_(e)});continue}if(null==p){l.push({...h,status:"failed",reason:"wall-null"});continue}if("degraded-extra"===p.status){l.push({...h,status:"failed",reason:"wall-degraded-extra"});continue}if("failed-core"===p.status){l.push({...h,status:"failed",reason:"wall-failed-core"});continue}t.captureWallGeometry?.(d,p)}if(d.space.rooms.length&&null==p?.paperGeom){let e;try{e=a(d.space.rooms,d.walls,d.openCuts,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale)}catch(e){l.push({...h,status:"failed",reason:"floor-exception",detail:s_(e)});continue}if(null==e){l.push({...h,status:"failed",reason:"floor-null"});continue}}l.push({...h,status:"ok"})}const c=l.filter(e=>"failed"===e.status);return{fingerprint:i,spaces:l,failures:c,ok:0===c.length}}const m_=e=>"string"==typeof e&&e.length>0&&e.length<=500;function g_(e){return m_(e)&&(e.startsWith("device:")||e.startsWith("entity:"))&&e.indexOf(":")0||null===e.area&&"string"==typeof e.space&&e.space.length>0&&"string"==typeof e.room_id&&e.room_id.length>0)}(i)||i&&i.binding!==t?null:"entity"!==e.bindingKind||i?t:null}function b_(e,t){return e.rooms.filter(e=>{const i=function(e){if(Array.isArray(e.poly)&&e.poly.length>=3)return e.poly;const{x:t,y:i,w:n,h:r}=e;return![t,i,n,r].every(Number.isFinite)||Number(n)<=0||Number(r)<=0?null:[[t,i],[t+n,i],[t+n,i+r],[t,i+r]]}(e);return!!i&&gi(t,i)})}function w_(e,t){return{id:e,binding:null,area:null,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:t}}function k_(e){const t=e.indexOf(":");return[e.slice(0,t),e.slice(t+1)]}function x_(e){const t=[],i=new Set;if(!e.authoritative)return{decisions:t,relocateIds:i};const n=f_(e.snapshot);for(const i of e.cleanupSnapshotIds||[])n[i]&&t.push({...w_(i,"registry-unverified"),removeSnapshot:!0});const r=Number.isFinite(e.coordinateScale)&&Number(e.coordinateScale)>0?Number(e.coordinateScale):1e3,o=new Map;for(const t of e.model)for(const e of t.rooms){if(!e.area)continue;const i=o.get(e.area)||[];i.push({space:t,room:e}),o.set(e.area,i)}for(const s of e.devices){const a=n[s.id],l=y_(s);if(!l){a&&t.push({...w_(s.id,"registry-unverified"),removeSnapshot:!0});continue}const c=m_(s.area)?s.area:null;if(!c){t.push({id:s.id,binding:l,area:null,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:"registry-unverified"});continue}const h=o.get(c);if(!h||1!==h.length){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:"target-unresolved"});continue}if(a?.binding===l){const e=a.area!==c;e&&i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:e,updateSnapshot:e,removeSnapshot:!1,reason:e?"area-changed":"unchanged"});continue}const d=e.layout[s.id];if(!d){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!0,removeSnapshot:!1,reason:"new-without-layout"});continue}const[{space:u,room:p}]=h;if(d.s&&d.s!==u.id){i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:!0,updateSnapshot:!0,removeSnapshot:!1,reason:"backfill-cross-space"});continue}if(d.s!==u.id||!Number.isFinite(d.x)||!Number.isFinite(d.y)){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!0,removeSnapshot:!1,reason:"backfill-ambiguous"});continue}const _=b_(u,[d.x*r,d.y*r]),m=1===_.length?_[0]:null,g=m===p||!!m?.id&&!!p.id&&m.id===p.id,f=!!m?.area&&m.area!==c,v=!g&&f;v&&i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:v,updateSnapshot:!0,removeSnapshot:!1,reason:v?"backfill-stale-room":g?"backfill-same-room":"backfill-ambiguous"})}return{decisions:t,relocateIds:i}}const S_=1,$_=/^[0-9a-f]{64}$/,M_=new WeakMap;function R_(e){const t=new Set;for(const i of e?.spaces||[])for(const e of i?.decor||[])"image"===e?.kind&&$_.test(e.asset_id)&&t.add(e.asset_id);return[...t]}function C_(e,t,i){const n=Number(e.x)*t,r=Number(e.y)*i,o=Number(e.w)*t,s=Number(e.h)*i;if(![n,r,o,s].every(Number.isFinite)||o<=0||s<=0)return null;const a=n+o/2,l=r+s/2,c=wr(e.angle);return[n,r,o,s,br(e.opacity,1),`translate(${a} ${l}) rotate(${c}) scale(${e.flip_h?-1:1} ${e.flip_v?-1:1}) translate(${-a} ${-l})`]}function T_(e){const t=new Map,i=e?.assets;if(!Array.isArray(i))return t;for(const e of i){const i=e,n="image/png"===i.mime?"png":"image/jpeg"===i.mime?"jpg":"image/webp"===i.mime?"webp":"image/svg+xml"===i.mime?"svg":"",r=`/api/houseplan/content/assets/_/${i.asset_id}.${n}`;!$_.test(String(i.asset_id||""))||i.url!==r||"string"!=typeof i.name||!Number.isFinite(i.bytes)||Number(i.bytes)<1||!Number.isFinite(i.width)||!Number.isFinite(i.height)||Number(i.width)<=0||Number(i.height)<=0||t.set(i.asset_id,i)}return t}async function D_(e,t,i){const n=[...new Set(t.filter(e=>$_.test(e)))].sort(),r=e.connection||e,o=JSON.stringify([i,n]),s=M_.get(r);if(s?.[0]===o)return s[1];const a=new Map;for(let t=0;t0&&t>0?e/t:1;let n=100,r=n/i;return r>200&&(r=200,n=r*i),{w:n,h:r}}const P_=(e,t,i)=>{const n=new Map;for(let r=t;r<=i;r++)n.set(e[r],r);return n},F_=pe(class extends _e{constructor(e){if(super(e),e.type!==ue)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let n;void 0===i?i=t:void 0!==t&&(n=t);const r=[],o=[];let s=0;for(const t of e)r[s]=n?n(t,s):s,o[s]=i(t,s),s++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,n]){const r=xe(e),{values:o,keys:s}=this.dt(t,i,n);if(!Array.isArray(r))return this.ut=s,o;const a=this.ut??=[],l=[];let c,h,d=0,u=r.length-1,p=0,_=o.length-1;for(;d<=u&&p<=_;)if(null===r[d])d++;else if(null===r[u])u--;else if(a[d]===s[p])l[p]=be(r[d],o[p]),d++,p++;else if(a[u]===s[_])l[_]=be(r[u],o[_]),u--,_--;else if(a[d]===s[_])l[_]=be(r[d],o[_]),ye(e,l[_+1],r[d]),d++,_--;else if(a[u]===s[p])l[p]=be(r[u],o[p]),ye(e,r[d],r[u]),u--,p++;else if(void 0===c&&(c=P_(s,p,_),h=P_(a,d,u)),c.has(a[d]))if(c.has(a[u])){const t=h.get(s[p]),i=void 0!==t?r[t]:null;if(null===i){const t=ye(e,r[d]);be(t,o[p]),l[p]=t}else l[p]=be(i,o[p]),ye(e,r[d],i),r[t]=null;p++}else Se(r[u]),u--;else Se(r[d]),d++;for(;p<=_;){const t=ye(e,l[_+1]);be(t,o[p]),l[p++]=t}for(;d<=u;){const e=r[d++];null!==e&&Se(e)}return this.ut=s,ke(e,l),U}}),z_=1e-5;function I_(e){const t=e.map(()=>[]);for(let i=0;i=1-1e-9||u<=1e-9||u>=1-1e-9||(t[i].push(d),t[s].push(u))}}const i=[];for(let n=0;ne-t),1];for(let e=1;e{const i=t[2]-t[0],n=t[3]-t[1],r=i*i+n*n;if(!(r>0))return Math.hypot(e[0]-t[0],e[1]-t[1]);const o=Math.max(0,Math.min(1,((e[0]-t[0])*i+(e[1]-t[1])*n)/r));return Math.hypot(e[0]-(t[0]+o*i),e[1]-(t[1]+o*n))},N_=(e,t,i,n)=>{const r=n[2]-n[0],o=n[3]-n[1],s=t*o-i*r;if(Math.abs(s)<1e-12)return 1/0;const a=n[0]-e[0],l=n[1]-e[1],c=(a*o-l*r)/s;if(!(c>1e-9))return 1/0;const h=(a*i-l*t)/s;return h<-1e-9||h>1+1e-9?1/0:c};const H_=[[0,1],[45,.88],[70,.62],[86,.32],[100,0]];function L_(){return{clipCache:new Map,geometryWarnings:new Set,featherUnits:null,renderedSources:new Map,lastAppearance:new Map,enteringSources:new Set,enterRafs:new Map,fadeTimers:new Map,featherSuspendUntil:0,featherResumeTimer:0,sourceSeq:0}}function B_(e,t){if(!e.clipCache.has(t))return{hit:!1,value:null};const i=e.clipCache.get(t)??null;return e.clipCache.delete(t),e.clipCache.set(t,i),{hit:!0,value:i}}function q_(e,t,i,n=256){for(e.clipCache.delete(t),e.clipCache.set(t,i);e.clipCache.size>n;){const t=e.clipCache.keys().next().value;if(void 0===t)break;e.clipCache.delete(t)}}function j_(e){const t=pd(e.hass,e.devices,null,e.virtualLights).filter(t=>t.device.space===e.spaceId),i=new Map;for(const e of t){if(!e.device.id)continue;const t=i.get(e.device.id)||[];t.push(e),i.set(e.device.id,t)}const n=[];for(const t of e.devices){if(!t.id||t.space!==e.spaceId)continue;const r=_d(i.get(t.id)||[]);if(!r)continue;const o=Sn(r.passive?{state:r.on?"on":"off",attributes:{}}:e.hass.states[r.eid],t.marker?.glow_color,e.defaultColor),s=Number(t.marker?.glow_radius_cm),a=Number.isFinite(s)&&s>0?s/e.cellCm*e.gridPitch:e.defaultRadiusUnits;n.push({key:`${e.spaceId}|${t.id}`,sourceEid:r.eid,pos:e.position(t),radius:a,appearance:o?{c:o.c,alpha:$n(o.bri,e.paletteAlpha)}:null})}return n}function W_(e){const t=ic([e.rawSpaceConfig,e.cellCm,e.gridPitch]),i=e.space.rooms.flatMap(e=>{const t=ei(e);return t?[{room:e,poly:t}]:[]}),n=Math.max(10/e.cellCm*e.gridPitch,.5*e.gridPitch),r=e=>i.some(({poly:t})=>ui(e,t)),o=e.openings.flatMap(t=>{if("door"!==(i=String(t.type))&&"gate"!==i&&"passage"!==i)return[];var i;const o=t.angle*Math.PI/180,s=-Math.sin(o),a=Math.cos(o);return r([t.rx+s*n,t.ry+a*n])&&r([t.rx-s*n,t.ry-a*n])?[{opening:t,amount:ai(e.openingAmount(t))}]:[]});return{geometryFingerprint:t,fingerprint:ic([t,o.map(({opening:e,amount:t})=>({id:e.id,type:e.type,contact:e.contact,amount:t})).filter(e=>!!e.contact&&("door"===e.type||"gate"===e.type)).map(e=>{const t=Math.max(0,Math.min(1,Number(e.amount)||0));return`${e.id}:${t.toFixed(3)}`}).sort().join("|")]),polygons:i,passageStates:o}}function U_(e){const{revision:t}=e,i=`${e.space.id}|${t.fingerprint}`,n=[...e.zeroWalls.transmissive],r=d_(t.passageStates.filter(({amount:e})=>e>0).map(({opening:e,amount:t})=>({...e,rlen:li(e.rlen,t)})),e.space,[...e.walls],e.zeroWalls.contour,e.wallKeyPitch,e.cellCm,e.gridPitch,e.coordScale);for(const e of r){const t=e.angle*Math.PI/180,i=Math.cos(t)*e.length/2,r=Math.sin(t)*e.length/2;n.push([e.x-i,e.y-r,e.x+i,e.y+r])}const o=t.passageStates.flatMap(({opening:e,amount:t})=>t>0&&e.partitionHost?[fa(wu(e.partitionHost),t)]:[]),s=e.physicalBodies(o,i),a=[],l=e.sharedWallGeometry?.sourceFingerprint,c=(e.sharedWallGeometry&&l===t.geometryFingerprint?function(e,t=[],i=[],n={}){if("failed-core"===e.status||"not-applicable"===e.status)return null;const r=e.roomComponents?.length?e.roomComponents:Fs(e.roomGeom)?[{id:"room-primary",geom:e.roomGeom}]:[];let o=r[0]?.geom||null;const s=r.slice(1).map(e=>({...e}));try{for(const i of t){if(!(i.length>0&&e.openingIndex))continue;const t=ia(e.openingIndex,i,!0);if(!t.negative&&!t.positive)continue;const n=i.angle*Math.PI/180,r=Math.cos(n),a=Math.sin(n),l=-a,c=r,h=i.length/2,d=e.openingPadUnits??1.25*Math.max(e.depthUnits,1),u=Ps([[i.x-r*h-l*d,i.y-a*h-c*d],[i.x+r*h-l*d,i.y+a*h-c*d],[i.x+r*h+l*d,i.y+a*h+c*d],[i.x-r*h+l*d,i.y-a*h+c*d]]);o&&(o=jt(o,u));for(const e of s)e.geom=jt(e.geom,u)}const r=[...s];let a=s.length;const l=n.mergeExtra||((e,t)=>e?Bt(e,t):t);for(let e=0;ee.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]))||Math.abs($i(t))<=1e-9){a++;continue}const n=[Ps(t)];try{const t=l(o,n,e);if(!Fs(t))throw new Error("invalid extra union");o=t}catch{a++,Fs(n)&&r.push({id:`policy-extra-${e}`,geom:n})}}r.sort((e,t)=>Ws(e.geom).localeCompare(Ws(t.geom)));const c=o||[];return{status:a?"degraded-extra":"ok",geom:c,components:[...Fs(c)?[{id:"primary",geom:c}]:[],...r.map((e,t)=>({...e,id:`isolated-${t}`}))]}}catch{return null}}(e.sharedWallGeometry,r,s):null)||(e.walls.length||s.length?Gs(e.space.rooms,[...e.walls],e.zeroWalls.contour,r,e.wallKeyPitch,e.cellCm,e.gridPitch,e.coordScale,s):null);if(!c||"ok"!==c.status&&"degraded-extra"!==c.status)for(const e of s)a.push(...O_(e));else for(const e of c.components)for(const t of Ra(e.geom))a.push(...O_(t));const h=.02*e.gridPitch;for(const{poly:e}of t.polygons){const t=n.length?Tn(e,n,h):O_(e);for(const e of t)a.push(e)}for(const t of e.zeroWalls.barriers)a.push(t);return{occluders:I_(a),floor:t.polygons.map(({poly:e})=>e),fingerprint:t.fingerprint,masonryGeometry:!c||"ok"!==c.status&&"degraded-extra"!==c.status?[]:c.components.flatMap(e=>e.geom),opaqueBodies:s}}function V_(e){const t=function(e,t,i,n=96){if(!(t>0&&Number.isFinite(e[0])&&Number.isFinite(e[1])))return[];const r=[];for(const n of i){if(!n||n.length<4)continue;if(![n[0],n[1],n[2],n[3]].every(Number.isFinite))continue;const i=E_(e,n);if(i<1e-7)return[];i>t||r.push(n)}const o=[],s=Math.max(12,Math.round(n));for(let e=0;ee-t);const l=[];let c=Number.NEGATIVE_INFINITY;for(const i of o){if(i-c<1e-9)continue;c=i;const n=Math.cos(i),o=Math.sin(i);let s=t;for(const t of r){const i=N_(e,n,o,t);i=3?l:[]}([e.source.x,e.source.y],e.radius,e.scene.occluders,96);return{lit:t.length>=3?Sa([t],e.scene.floor,{onBoundsFailure:({boundIndex:t,phase:i})=>{const n=e.polygons[t]?.room;e.onBoundsFailure?.(n?.id||`#${t}`,i)}}):[]}}function G_(e,t){return Da([e.x,e.y],t.masonryGeometry,t.opaqueBodies)}function K_(e,t){if(t.reducedMotion())return;const i=t.window();e.featherSuspendUntil=Math.max(e.featherSuspendUntil,Date.now()+500),i.clearTimeout(e.featherResumeTimer);const n=()=>{e.featherResumeTimer=0,Date.now(){e.enterRafs.get(i)===n&&(e.enterRafs.delete(i),e.enteringSources.delete(i),t.isConnected()&&t.requestUpdate())});e.enterRafs.set(i,n)}return{domId:o,entering:e.enteringSources.has(i),leaving:!1}}if(null==o)return null;const s=e.enterRafs.get(i);if(null!=s&&r.cancelAnimationFrame(s),e.enterRafs.delete(i),e.enteringSources.delete(i),!e.fadeTimers.has(i)){K_(e,t);const n=r.setTimeout(()=>{e.fadeTimers.get(i)===n&&(e.fadeTimers.delete(i),e.renderedSources.delete(i),e.lastAppearance.delete(i),t.isConnected()&&t.requestUpdate())},534);e.fadeTimers.set(i,n)}return{domId:o,entering:!1,leaving:!0}}function X_(e,t,i){const n=t.window(),r=e.fadeTimers.get(i),o=e.enterRafs.get(i);null!=r&&n.clearTimeout(r),null!=o&&n.cancelAnimationFrame(o),e.fadeTimers.delete(i),e.enterRafs.delete(i),e.enteringSources.delete(i),e.renderedSources.delete(i),e.lastAppearance.delete(i)}function Z_(e,t,i){const n=`${i}|`;for(const i of[...e.renderedSources.keys()])i.startsWith(n)&&X_(e,t,i)}function J_(e,t,i,n){const r=`${i}|`;for(const i of[...e.renderedSources.keys()])i.startsWith(r)&&!n.has(i)&&X_(e,t,i)}function Q_(e,t){const i=t.window();for(const t of e.fadeTimers.values())i.clearTimeout(t);for(const t of e.enterRafs.values())i.cancelAnimationFrame(t);i.clearTimeout(e.featherResumeTimer),e.clipCache.clear(),e.geometryWarnings.clear(),e.fadeTimers.clear(),e.enterRafs.clear(),e.enteringSources.clear(),e.renderedSources.clear(),e.lastAppearance.clear(),e.featherUnits=null,e.featherSuspendUntil=0,e.featherResumeTimer=0,e.sourceSeq=0}function em(e,t,i,n,r){const o=`${t}|${i}|${n}`;if(!e.geometryWarnings.has(o)){if(e.geometryWarnings.size>=128){const t=e.geometryWarnings.values().next().value;t&&e.geometryWarnings.delete(t)}e.geometryWarnings.add(o),console.warn(`HOUSEPLAN GLOW GEOMETRY FALLBACK: #218, space ${t}, room ${n}, phase ${r}`)}}function tm(e,t,i){const n=1/(t>0?t:1),r=i&&Date.now()>=e.featherSuspendUntil;return(null==e.featherUnits||r)&&(e.featherUnits=n),{feather:e.featherUnits??n,enabled:r}}function im(e){if(!e.spots.length)return W``;const t=4*e.feather,i=e.spots.reduce((e,i)=>({x:Math.min(e.x,i.pos.x-i.r-t),y:Math.min(e.y,i.pos.y-i.r-t),maxX:Math.max(e.maxX,i.pos.x+i.r+t),maxY:Math.max(e.maxY,i.pos.y+i.r+t),w:0,h:0}),{x:1/0,y:1/0,maxX:-1/0,maxY:-1/0,w:0,h:0});i.w=i.maxX-i.x,i.h=i.maxY-i.y;const n=e.enabledClip?.length?e.enabledClip:null;return W`
- ${F_(e.spots,e=>e.key,e=>{const t=e.domId;return W`
+ `});return W`${s}`}function Wp(e,t,i){const n=i>0?i:1;return{a:[e[0]/n,e[1]/n],b:[t[0]/n,t[1]/n]}}function Up(e,t){const i=t>0?t:1;return[e.a[0]*i,e.a[1]*i,e.b[0]*i,e.b[1]*i]}function Vp(e){return Array.isArray(e)&&e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))}function Gp(e){if(!Array.isArray(e))return[];const t=[];for(const i of e){if(!i||"object"!=typeof i)continue;const e=i;if(!Vp(e.a)||!Vp(e.b))continue;const n=[Number(e.a[0]),Number(e.a[1])],r=[Number(e.b[0]),Number(e.b[1])];Math.hypot(r[0]-n[0],r[1]-n[1])<.001||t.push({a:n,b:r})}return t}function Kp(e,t,i,n,r=!0){const o=(e||[]).filter(e=>e?.id),s=Gp(t);if(s.length)return function(e,t,i,n){const r=Gp(e);if(!r.length)return[];const o=function(e,t){const i=[],n=(e||[]).filter(e=>e?.id);for(let e=0;e4*n||o>4*n)continue;const s=(e[0]-r)*u+(e[1]-l)*p,c=(e[2]-r)*u+(e[3]-l)*p,h=Math.max(0,Math.min(s,c)),m=Math.min(d,Math.max(s,c));if(m-he.lo-t.lo||e.hi-t.hi);const i=[];for(const e of t){const t=i[i.length-1];t&&e.lo<=t.hi+a?t.hi=Math.max(t.hi,e.hi):i.push({...e})}for(const t of i){const i=[r+u*t.lo,l+p*t.lo],n=[r+u*t.hi,l+p*t.hi];Math.hypot(n[0]-i[0],n[1]-i[1])i.pair===e&&Math.abs(i.ux*s-i.uy*o)<=1e-6&&Math.abs((t[0]-i.origin[0])*i.uy-(t[1]-i.origin[1])*i.ux)<=c&&Math.abs((t[2]-i.origin[0])*i.uy-(t[3]-i.origin[1])*i.ux)<=c);h||(h={pair:e,origin:[t[0],t[1]],ux:o,uy:s,ranges:[]},l.push(h));const d=(t[0]-h.origin[0])*h.ux+(t[1]-h.origin[1])*h.uy,u=(t[2]-h.origin[0])*h.ux+(t[3]-h.origin[1])*h.uy;h.ranges.push({lo:Math.min(d,u),hi:Math.max(d,u)})}const h=[];for(const e of l){e.ranges.sort((e,t)=>e.lo-t.lo||e.hi-t.hi);const t=[];for(const i of e.ranges){const e=t[t.length-1];e&&i.lo<=e.hi+a?e.hi=Math.max(e.hi,i.hi):t.push({...i})}for(const n of t){const t=[e.origin[0]+e.ux*n.lo,e.origin[1]+e.uy*n.lo],r=[e.origin[0]+e.ux*n.hi,e.origin[1]+e.uy*n.hi];Math.hypot(r[0]-t[0],r[1]-t[1])>=a&&h.push(Wp(t,r,i))}}return h}(s,e,i,n).map(e=>Up(e,i));if(!r)return[];const a=[],l=(e,t)=>(e.open_to||[]).includes(t.id)||(t.open_to||[]).includes(e.id);for(let e=0;er)&&qo([o[0],o[1]],[o[2],o[3]],i))return!0;return!1}const Xp=e=>Array.isArray(e)&&e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1])),Zp=(e,t,i)=>[Number(e[0])*i,Number(e[1])*i,Number(t[0])*i,Number(t[1])*i],Jp=e=>{const t=`${Number(e[0]).toFixed(9)},${Number(e[1]).toFixed(9)}`,i=`${Number(e[2]).toFixed(9)},${Number(e[3]).toFixed(9)}`;return t<=i?`${t}|${i}`:`${i}|${t}`},Qp=e=>{const t=new Map;for(const i of e.flat())!Array.isArray(i)||i.length<4||!i.every(Number.isFinite)||Math.hypot(i[2]-i[0],i[3]-i[1])<=1e-9||t.set(Jp(i),[...i]);return[...t.values()]};function e_(e){return"solid"===e?.zero_wall_style?"solid":"dashed"}function t_(e,t=1,i){const n=[];for(const r of Array.isArray(e?.wall_segments)?e.wall_segments:[])0===Number(r?.cm)&&Xp(r?.a)&&Xp(r?.b)&&(i&&!i.has(String(r.id||""))||n.push(Zp(r.a,r.b,t)));return Qp([n])}function i_(e,t=1){const i=[];for(const n of Array.isArray(e?.partitions)?e.partitions:[])0===Number(n?.cm)&&Xp(n?.a)&&Xp(n?.b)&&i.push(Zp(n.a,n.b,t));return Qp([i])}function n_(e,t,i,n){if(!e)return[];const r=Gp(e.open_spans);return Kp(t,r.length?r:null,i,n,!0)}function r_(e,t,i,n){const r=e_(e),o=new Set;for(const e of t.rooms||[])for(const t of Array.isArray(e.wall_ids)?e.wall_ids:[])"string"==typeof t&&t&&o.add(t);const s=Qp([t_(t,1,o.size?o:void 0),n_(e,t.rooms,i,n)]),a=Qp([s,i_(t,1)]);return{style:r,lines:a,contour:s,barriers:"solid"===r?a:[],transmissive:"dashed"===r?s:[]}}function o_(e,t){return(e||[]).some(e=>e?.host?.kind===t.kind&&e.host.id===t.id)}function s_(e){return e instanceof Error?e.name||"Error":typeof e}function a_(e){return ic({id:e?.id??"",cell_cm:e?.cell_cm,rooms:e?.rooms||[],walls:e?.walls||[],wall_segments:e?.wall_segments||[],open_spans:e?.open_spans||[],openings:e?.openings||[],partitions:e?.partitions||[],wall_columns:e?.wall_columns||[]})}function l_(e,t,i={}){const n=(Array.isArray(e?.spaces)?e.spaces:[]).find(e=>String(e?.id||"")===String(t||"")),r=a_(n);if(!n)return{spaceId:String(t||""),displayName:"",status:"failed",reason:"prepare-exception",fingerprint:r,ok:!1};const o=m_({...e,spaces:[n]},{...i,fingerprint:()=>r}).spaces[0]||{spaceId:String(t||""),displayName:"",status:"failed",reason:"prepare-exception"};return{...o,fingerprint:r,ok:"failed"!==o.status}}function c_(e,t,i=Ka,n=1e3){return Kp(t.rooms,e?.open_spans,n,.02*i)}function h_(e,t,i,n=Ka,r=1e3){return(Array.isArray(e?.openings)?e.openings:[]).flatMap(e=>{const o={...e,rx:Number(e.x)*r,ry:Number(e.y)*r,rlen:Number(e.length)*r};if(!e.host||"wall"===e.host.kind)return[o];const s=vu(e,t.partitions,r,i,n);return s.resolved?[{...e,rx:s.resolved.center[0],ry:s.resolved.center[1],rlen:s.resolved.length,angle:s.resolved.angle,partitionHost:s.resolved}]:[]})}function d_(e,t=()=>!0){return e.flatMap(e=>e.host&&e.partitionHost&&t(e)?[wu(e.partitionHost)]:[])}function u_(e,t,i,n,r,o,s=Ka,a=1e3){const l=$s(t.rooms,[...i],n,r,o,s,a);return e.flatMap(e=>{const t={x:e.rx,y:e.ry,angle:Number(e.angle)||0,length:e.rlen};return e.host&&"wall"!==e.host.kind?e.partitionHost&&Su(e.partitionHost,l,2e-4*s)?[t]:[]:[t]})}function p_(e,t){const i=Ya,n=Ka,r=Na,o=Number.isFinite(Number(t.cellCm))&&Number(t.cellCm)>0?Number(t.cellCm):5,s=Array.isArray(e?.walls)?e.walls:[],a=c_(e,t,n,r),l=function(e,t,i=Ka){if(!t.length)return[];const n=e.filter(e=>e?.id),r=.02*i,o=[];for(let e=0;e{const t=[(e[0]+e[2])/2,(e[1]+e[3])/2];return h.some(e=>Bn(t,e)<4*r)}).map(e=>[...e]);d.length&&o.push({a:s,b:a,segs:d})}return o}(t.rooms,a,n).flatMap(e=>e.segs),c=h_(e,t,o,n,r),h=d_(c),d=ba(t,o,n,2e-4*n,h).all;return{space:t,walls:s,openCuts:l,openings:c,roomOpenings:u_(c,t,s,l,i,o,n,r),partitionCuts:h,physicalBodies:d,wallKeyPitch:i,cellCm:o,gridPitch:n,coordScale:r}}function __(e,t,i){const n="string"==typeof e?.title?e.title.trim():"",r=null==e?.id?"":String(e.id).trim();return{spaceId:r,displayName:n||r||i(t+1)}}function m_(e,t={}){const i=(t.fingerprint||ic)(e),n=Array.isArray(e?.spaces)?e.spaces:[],r=t.fallbackSpaceName||(e=>`Space ${e}`),o=t.prepareSpace||p_,s=t.wallPass||Gs,a=t.floorPass||js,l=[];for(let i=0;i0||d.physicalBodies.length>0;if(!d.space.rooms.length&&!u){l.push({...h,status:"not-applicable"});continue}let p=null;if(u){try{p=s(d.space.rooms,d.walls,d.openCuts,d.roomOpenings,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale,d.physicalBodies)}catch(e){l.push({...h,status:"failed",reason:"wall-exception",detail:s_(e)});continue}if(null==p){l.push({...h,status:"failed",reason:"wall-null"});continue}if("degraded-extra"===p.status){l.push({...h,status:"failed",reason:"wall-degraded-extra"});continue}if("failed-core"===p.status){l.push({...h,status:"failed",reason:"wall-failed-core"});continue}t.captureWallGeometry?.(d,p)}if(d.space.rooms.length&&null==p?.paperGeom){let e;try{e=a(d.space.rooms,d.walls,d.openCuts,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale)}catch(e){l.push({...h,status:"failed",reason:"floor-exception",detail:s_(e)});continue}if(null==e){l.push({...h,status:"failed",reason:"floor-null"});continue}}l.push({...h,status:"ok"})}const c=l.filter(e=>"failed"===e.status);return{fingerprint:i,spaces:l,failures:c,ok:0===c.length}}const g_=e=>"string"==typeof e&&e.length>0&&e.length<=500;function f_(e){return g_(e)&&(e.startsWith("device:")||e.startsWith("entity:"))&&e.indexOf(":")0||null===e.area&&"string"==typeof e.space&&e.space.length>0&&"string"==typeof e.room_id&&e.room_id.length>0)}(i)||i&&i.binding!==t?null:"entity"!==e.bindingKind||i?t:null}function w_(e,t){return e.rooms.filter(e=>{const i=function(e){if(Array.isArray(e.poly)&&e.poly.length>=3)return e.poly;const{x:t,y:i,w:n,h:r}=e;return![t,i,n,r].every(Number.isFinite)||Number(n)<=0||Number(r)<=0?null:[[t,i],[t+n,i],[t+n,i+r],[t,i+r]]}(e);return!!i&&gi(t,i)})}function k_(e,t){return{id:e,binding:null,area:null,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:t}}function x_(e){const t=e.indexOf(":");return[e.slice(0,t),e.slice(t+1)]}function S_(e){const t=[],i=new Set;if(!e.authoritative)return{decisions:t,relocateIds:i};const n=v_(e.snapshot);for(const i of e.cleanupSnapshotIds||[])n[i]&&t.push({...k_(i,"registry-unverified"),removeSnapshot:!0});const r=Number.isFinite(e.coordinateScale)&&Number(e.coordinateScale)>0?Number(e.coordinateScale):1e3,o=new Map;for(const t of e.model)for(const e of t.rooms){if(!e.area)continue;const i=o.get(e.area)||[];i.push({space:t,room:e}),o.set(e.area,i)}for(const s of e.devices){const a=n[s.id],l=b_(s);if(!l){a&&t.push({...k_(s.id,"registry-unverified"),removeSnapshot:!0});continue}const c=g_(s.area)?s.area:null;if(!c){t.push({id:s.id,binding:l,area:null,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:"registry-unverified"});continue}const h=o.get(c);if(!h||1!==h.length){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:"target-unresolved"});continue}if(a?.binding===l){const e=a.area!==c;e&&i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:e,updateSnapshot:e,removeSnapshot:!1,reason:e?"area-changed":"unchanged"});continue}const d=e.layout[s.id];if(!d){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!0,removeSnapshot:!1,reason:"new-without-layout"});continue}const[{space:u,room:p}]=h;if(d.s&&d.s!==u.id){i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:!0,updateSnapshot:!0,removeSnapshot:!1,reason:"backfill-cross-space"});continue}if(d.s!==u.id||!Number.isFinite(d.x)||!Number.isFinite(d.y)){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!0,removeSnapshot:!1,reason:"backfill-ambiguous"});continue}const _=w_(u,[d.x*r,d.y*r]),m=1===_.length?_[0]:null,g=m===p||!!m?.id&&!!p.id&&m.id===p.id,f=!!m?.area&&m.area!==c,v=!g&&f;v&&i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:v,updateSnapshot:!0,removeSnapshot:!1,reason:v?"backfill-stale-room":g?"backfill-same-room":"backfill-ambiguous"})}return{decisions:t,relocateIds:i}}const $_=1,M_=/^[0-9a-f]{64}$/,R_=new WeakMap;function C_(e){const t=new Set;for(const i of e?.spaces||[])for(const e of i?.decor||[])"image"===e?.kind&&M_.test(e.asset_id)&&t.add(e.asset_id);return[...t]}function T_(e,t,i){const n=Number(e.x)*t,r=Number(e.y)*i,o=Number(e.w)*t,s=Number(e.h)*i;if(![n,r,o,s].every(Number.isFinite)||o<=0||s<=0)return null;const a=n+o/2,l=r+s/2,c=wr(e.angle);return[n,r,o,s,br(e.opacity,1),`translate(${a} ${l}) rotate(${c}) scale(${e.flip_h?-1:1} ${e.flip_v?-1:1}) translate(${-a} ${-l})`]}function D_(e){const t=new Map,i=e?.assets;if(!Array.isArray(i))return t;for(const e of i){const i=e,n="image/png"===i.mime?"png":"image/jpeg"===i.mime?"jpg":"image/webp"===i.mime?"webp":"image/svg+xml"===i.mime?"svg":"",r=`/api/houseplan/content/assets/_/${i.asset_id}.${n}`;!M_.test(String(i.asset_id||""))||i.url!==r||"string"!=typeof i.name||!Number.isFinite(i.bytes)||Number(i.bytes)<1||!Number.isFinite(i.width)||!Number.isFinite(i.height)||Number(i.width)<=0||Number(i.height)<=0||t.set(i.asset_id,i)}return t}async function A_(e,t,i){const n=[...new Set(t.filter(e=>M_.test(e)))].sort(),r=e.connection||e,o=JSON.stringify([i,n]),s=R_.get(r);if(s?.[0]===o)return s[1];const a=new Map;for(let t=0;t0&&t>0?e/t:1;let n=100,r=n/i;return r>200&&(r=200,n=r*i),{w:n,h:r}}const F_=(e,t,i)=>{const n=new Map;for(let r=t;r<=i;r++)n.set(e[r],r);return n},z_=pe(class extends _e{constructor(e){if(super(e),e.type!==ue)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let n;void 0===i?i=t:void 0!==t&&(n=t);const r=[],o=[];let s=0;for(const t of e)r[s]=n?n(t,s):s,o[s]=i(t,s),s++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,n]){const r=xe(e),{values:o,keys:s}=this.dt(t,i,n);if(!Array.isArray(r))return this.ut=s,o;const a=this.ut??=[],l=[];let c,h,d=0,u=r.length-1,p=0,_=o.length-1;for(;d<=u&&p<=_;)if(null===r[d])d++;else if(null===r[u])u--;else if(a[d]===s[p])l[p]=be(r[d],o[p]),d++,p++;else if(a[u]===s[_])l[_]=be(r[u],o[_]),u--,_--;else if(a[d]===s[_])l[_]=be(r[d],o[_]),ye(e,l[_+1],r[d]),d++,_--;else if(a[u]===s[p])l[p]=be(r[u],o[p]),ye(e,r[d],r[u]),u--,p++;else if(void 0===c&&(c=F_(s,p,_),h=F_(a,d,u)),c.has(a[d]))if(c.has(a[u])){const t=h.get(s[p]),i=void 0!==t?r[t]:null;if(null===i){const t=ye(e,r[d]);be(t,o[p]),l[p]=t}else l[p]=be(i,o[p]),ye(e,r[d],i),r[t]=null;p++}else Se(r[u]),u--;else Se(r[d]),d++;for(;p<=_;){const t=ye(e,l[_+1]);be(t,o[p]),l[p++]=t}for(;d<=u;){const e=r[d++];null!==e&&Se(e)}return this.ut=s,ke(e,l),U}}),I_=1e-5;function O_(e){const t=e.map(()=>[]);for(let i=0;i=1-1e-9||u<=1e-9||u>=1-1e-9||(t[i].push(d),t[s].push(u))}}const i=[];for(let n=0;ne-t),1];for(let e=1;e{const i=t[2]-t[0],n=t[3]-t[1],r=i*i+n*n;if(!(r>0))return Math.hypot(e[0]-t[0],e[1]-t[1]);const o=Math.max(0,Math.min(1,((e[0]-t[0])*i+(e[1]-t[1])*n)/r));return Math.hypot(e[0]-(t[0]+o*i),e[1]-(t[1]+o*n))},H_=(e,t,i,n)=>{const r=n[2]-n[0],o=n[3]-n[1],s=t*o-i*r;if(Math.abs(s)<1e-12)return 1/0;const a=n[0]-e[0],l=n[1]-e[1],c=(a*o-l*r)/s;if(!(c>1e-9))return 1/0;const h=(a*i-l*t)/s;return h<-1e-9||h>1+1e-9?1/0:c};const L_=[[0,1],[45,.88],[70,.62],[86,.32],[100,0]];function B_(){return{clipCache:new Map,geometryWarnings:new Set,featherUnits:null,renderedSources:new Map,lastAppearance:new Map,enteringSources:new Set,enterRafs:new Map,fadeTimers:new Map,featherSuspendUntil:0,featherResumeTimer:0,sourceSeq:0}}function q_(e,t){if(!e.clipCache.has(t))return{hit:!1,value:null};const i=e.clipCache.get(t)??null;return e.clipCache.delete(t),e.clipCache.set(t,i),{hit:!0,value:i}}function j_(e,t,i,n=256){for(e.clipCache.delete(t),e.clipCache.set(t,i);e.clipCache.size>n;){const t=e.clipCache.keys().next().value;if(void 0===t)break;e.clipCache.delete(t)}}function W_(e){const t=pd(e.hass,e.devices,null,e.virtualLights).filter(t=>t.device.space===e.spaceId),i=new Map;for(const e of t){if(!e.device.id)continue;const t=i.get(e.device.id)||[];t.push(e),i.set(e.device.id,t)}const n=[];for(const t of e.devices){if(!t.id||t.space!==e.spaceId)continue;const r=_d(i.get(t.id)||[]);if(!r)continue;const o=Sn(r.passive?{state:r.on?"on":"off",attributes:{}}:e.hass.states[r.eid],t.marker?.glow_color,e.defaultColor),s=Number(t.marker?.glow_radius_cm),a=Number.isFinite(s)&&s>0?s/e.cellCm*e.gridPitch:e.defaultRadiusUnits;n.push({key:`${e.spaceId}|${t.id}`,sourceEid:r.eid,pos:e.position(t),radius:a,appearance:o?{c:o.c,alpha:$n(o.bri,e.paletteAlpha)}:null})}return n}function U_(e){const t=ic([e.rawSpaceConfig,e.cellCm,e.gridPitch]),i=e.space.rooms.flatMap(e=>{const t=ei(e);return t?[{room:e,poly:t}]:[]}),n=Math.max(10/e.cellCm*e.gridPitch,.5*e.gridPitch),r=e=>i.some(({poly:t})=>ui(e,t)),o=e.openings.flatMap(t=>{if("door"!==(i=String(t.type))&&"gate"!==i&&"passage"!==i)return[];var i;const o=t.angle*Math.PI/180,s=-Math.sin(o),a=Math.cos(o);return r([t.rx+s*n,t.ry+a*n])&&r([t.rx-s*n,t.ry-a*n])?[{opening:t,amount:ai(e.openingAmount(t))}]:[]});return{geometryFingerprint:t,fingerprint:ic([t,o.map(({opening:e,amount:t})=>({id:e.id,type:e.type,contact:e.contact,amount:t})).filter(e=>!!e.contact&&("door"===e.type||"gate"===e.type)).map(e=>{const t=Math.max(0,Math.min(1,Number(e.amount)||0));return`${e.id}:${t.toFixed(3)}`}).sort().join("|")]),polygons:i,passageStates:o}}function V_(e){const{revision:t}=e,i=`${e.space.id}|${t.fingerprint}`,n=[...e.zeroWalls.transmissive],r=u_(t.passageStates.filter(({amount:e})=>e>0).map(({opening:e,amount:t})=>({...e,rlen:li(e.rlen,t)})),e.space,[...e.walls],e.zeroWalls.contour,e.wallKeyPitch,e.cellCm,e.gridPitch,e.coordScale);for(const e of r){const t=e.angle*Math.PI/180,i=Math.cos(t)*e.length/2,r=Math.sin(t)*e.length/2;n.push([e.x-i,e.y-r,e.x+i,e.y+r])}const o=t.passageStates.flatMap(({opening:e,amount:t})=>t>0&&e.partitionHost?[fa(wu(e.partitionHost),t)]:[]),s=e.physicalBodies(o,i),a=[],l=e.sharedWallGeometry?.sourceFingerprint,c=(e.sharedWallGeometry&&l===t.geometryFingerprint?function(e,t=[],i=[],n={}){if("failed-core"===e.status||"not-applicable"===e.status)return null;const r=e.roomComponents?.length?e.roomComponents:Fs(e.roomGeom)?[{id:"room-primary",geom:e.roomGeom}]:[];let o=r[0]?.geom||null;const s=r.slice(1).map(e=>({...e}));try{for(const i of t){if(!(i.length>0&&e.openingIndex))continue;const t=ia(e.openingIndex,i,!0);if(!t.negative&&!t.positive)continue;const n=i.angle*Math.PI/180,r=Math.cos(n),a=Math.sin(n),l=-a,c=r,h=i.length/2,d=e.openingPadUnits??1.25*Math.max(e.depthUnits,1),u=Ps([[i.x-r*h-l*d,i.y-a*h-c*d],[i.x+r*h-l*d,i.y+a*h-c*d],[i.x+r*h+l*d,i.y+a*h+c*d],[i.x-r*h+l*d,i.y-a*h+c*d]]);o&&(o=jt(o,u));for(const e of s)e.geom=jt(e.geom,u)}const r=[...s];let a=s.length;const l=n.mergeExtra||((e,t)=>e?Bt(e,t):t);for(let e=0;ee.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]))||Math.abs($i(t))<=1e-9){a++;continue}const n=[Ps(t)];try{const t=l(o,n,e);if(!Fs(t))throw new Error("invalid extra union");o=t}catch{a++,Fs(n)&&r.push({id:`policy-extra-${e}`,geom:n})}}r.sort((e,t)=>Ws(e.geom).localeCompare(Ws(t.geom)));const c=o||[];return{status:a?"degraded-extra":"ok",geom:c,components:[...Fs(c)?[{id:"primary",geom:c}]:[],...r.map((e,t)=>({...e,id:`isolated-${t}`}))]}}catch{return null}}(e.sharedWallGeometry,r,s):null)||(e.walls.length||s.length?Gs(e.space.rooms,[...e.walls],e.zeroWalls.contour,r,e.wallKeyPitch,e.cellCm,e.gridPitch,e.coordScale,s):null);if(!c||"ok"!==c.status&&"degraded-extra"!==c.status)for(const e of s)a.push(...E_(e));else for(const e of c.components)for(const t of Ra(e.geom))a.push(...E_(t));const h=.02*e.gridPitch;for(const{poly:e}of t.polygons){const t=n.length?Tn(e,n,h):E_(e);for(const e of t)a.push(e)}for(const t of e.zeroWalls.barriers)a.push(t);return{occluders:O_(a),floor:t.polygons.map(({poly:e})=>e),fingerprint:t.fingerprint,masonryGeometry:!c||"ok"!==c.status&&"degraded-extra"!==c.status?[]:c.components.flatMap(e=>e.geom),opaqueBodies:s}}function G_(e){const t=function(e,t,i,n=96){if(!(t>0&&Number.isFinite(e[0])&&Number.isFinite(e[1])))return[];const r=[];for(const n of i){if(!n||n.length<4)continue;if(![n[0],n[1],n[2],n[3]].every(Number.isFinite))continue;const i=N_(e,n);if(i<1e-7)return[];i>t||r.push(n)}const o=[],s=Math.max(12,Math.round(n));for(let e=0;ee-t);const l=[];let c=Number.NEGATIVE_INFINITY;for(const i of o){if(i-c<1e-9)continue;c=i;const n=Math.cos(i),o=Math.sin(i);let s=t;for(const t of r){const i=H_(e,n,o,t);i=3?l:[]}([e.source.x,e.source.y],e.radius,e.scene.occluders,96);return{lit:t.length>=3?Sa([t],e.scene.floor,{onBoundsFailure:({boundIndex:t,phase:i})=>{const n=e.polygons[t]?.room;e.onBoundsFailure?.(n?.id||`#${t}`,i)}}):[]}}function K_(e,t){return Da([e.x,e.y],t.masonryGeometry,t.opaqueBodies)}function Y_(e,t){if(t.reducedMotion())return;const i=t.window();e.featherSuspendUntil=Math.max(e.featherSuspendUntil,Date.now()+500),i.clearTimeout(e.featherResumeTimer);const n=()=>{e.featherResumeTimer=0,Date.now(){e.enterRafs.get(i)===n&&(e.enterRafs.delete(i),e.enteringSources.delete(i),t.isConnected()&&t.requestUpdate())});e.enterRafs.set(i,n)}return{domId:o,entering:e.enteringSources.has(i),leaving:!1}}if(null==o)return null;const s=e.enterRafs.get(i);if(null!=s&&r.cancelAnimationFrame(s),e.enterRafs.delete(i),e.enteringSources.delete(i),!e.fadeTimers.has(i)){Y_(e,t);const n=r.setTimeout(()=>{e.fadeTimers.get(i)===n&&(e.fadeTimers.delete(i),e.renderedSources.delete(i),e.lastAppearance.delete(i),t.isConnected()&&t.requestUpdate())},534);e.fadeTimers.set(i,n)}return{domId:o,entering:!1,leaving:!0}}function Z_(e,t,i){const n=t.window(),r=e.fadeTimers.get(i),o=e.enterRafs.get(i);null!=r&&n.clearTimeout(r),null!=o&&n.cancelAnimationFrame(o),e.fadeTimers.delete(i),e.enterRafs.delete(i),e.enteringSources.delete(i),e.renderedSources.delete(i),e.lastAppearance.delete(i)}function J_(e,t,i){const n=`${i}|`;for(const i of[...e.renderedSources.keys()])i.startsWith(n)&&Z_(e,t,i)}function Q_(e,t,i,n){const r=`${i}|`;for(const i of[...e.renderedSources.keys()])i.startsWith(r)&&!n.has(i)&&Z_(e,t,i)}function em(e,t){const i=t.window();for(const t of e.fadeTimers.values())i.clearTimeout(t);for(const t of e.enterRafs.values())i.cancelAnimationFrame(t);i.clearTimeout(e.featherResumeTimer),e.clipCache.clear(),e.geometryWarnings.clear(),e.fadeTimers.clear(),e.enterRafs.clear(),e.enteringSources.clear(),e.renderedSources.clear(),e.lastAppearance.clear(),e.featherUnits=null,e.featherSuspendUntil=0,e.featherResumeTimer=0,e.sourceSeq=0}function tm(e,t,i,n,r){const o=`${t}|${i}|${n}`;if(!e.geometryWarnings.has(o)){if(e.geometryWarnings.size>=128){const t=e.geometryWarnings.values().next().value;t&&e.geometryWarnings.delete(t)}e.geometryWarnings.add(o),console.warn(`HOUSEPLAN GLOW GEOMETRY FALLBACK: #218, space ${t}, room ${n}, phase ${r}`)}}function im(e,t,i){const n=1/(t>0?t:1),r=i&&Date.now()>=e.featherSuspendUntil;return(null==e.featherUnits||r)&&(e.featherUnits=n),{feather:e.featherUnits??n,enabled:r}}function nm(e){if(!e.spots.length)return W``;const t=4*e.feather,i=e.spots.reduce((e,i)=>({x:Math.min(e.x,i.pos.x-i.r-t),y:Math.min(e.y,i.pos.y-i.r-t),maxX:Math.max(e.maxX,i.pos.x+i.r+t),maxY:Math.max(e.maxY,i.pos.y+i.r+t),w:0,h:0}),{x:1/0,y:1/0,maxX:-1/0,maxY:-1/0,w:0,h:0});i.w=i.maxX-i.x,i.h=i.maxY-i.y;const n=e.enabledClip?.length?e.enabledClip:null;return W`
+ ${z_(e.spots,e=>e.key,e=>{const t=e.domId;return W`
- ${H_.map(([t,i])=>W`
+ ${L_.map(([t,i])=>W`
`)}
@@ -4757,7 +4757,7 @@ globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae6
data-blend=${e.screenBlend?"screen":"normal"}
data-feather-px="${2}"
clip-path=${n?"url(#hp-glow-enabled)":V}>
- ${F_(e.spots,e=>e.key,e=>W`
+ ${z_(e.spots,e=>e.key,e=>W`
ju(e.lang,t),iconRules:r})}function hm(e){const t=Wa(e.cfg),i=t.find(t=>t.id===e.spaceId);if(!i)return null;const n=ln(e.cfg.spaces.find(t=>t.id===e.spaceId)),r=un(e.cfg.settings),o=e.iconSize??2.5,s=o>8?2.5:o,a=qp(s),l=e.registry?Eh(e.hass,e.registry):e.hass,c=e.registry?Nh(e.hass,e.registry):e.hass,h=e.devices||cm(e),d=e.areaRelocationIds||x_({devices:h,model:t,layout:e.layout,snapshot:e.cfg.settings?.marker_area_snapshot,authoritative:!0===e.registry?.authoritative,coordinateScale:Na}).relocateIds,u=h.filter(t=>t.space===e.spaceId),p=u.filter(e=>!e.hidden),_=function(e,t,i){const n={},r=i/100*gl(t)*1.3;for(const i of t.rooms){if(!i.area)continue;const t=e.filter(e=>e.area===i.area);if(!t.length)continue;const o=bl(i),s=.1*Math.min(o.w,o.h),a=o.w-2*s,l=o.h-2*s,c=Math.max(1,Math.round(Math.sqrt(t.length*a/Math.max(l,1)))),h=a/c,d=l/Math.max(Math.ceil(t.length/c),1),u=t.map((e,t)=>({x:o.x+s+h*(t%c+.5),y:o.y+s+d*(Math.floor(t/c)+.5)}));zi(u,o,r,.5*s),t.forEach((e,t)=>n[e.id]=Za(u[t]))}return n}(u,i,s),m=ze(e.cfg.settings?.icon_rules?.length?e.cfg.settings.icon_rules:Fe),g=Hd(l,m,e.cfg.markers||[],Nd(e.cfg.settings)),f=t=>{const n=t.settings?.temp_source;if(n)return zd(l,n,"temp",e.cfg.markers||[]);const r=Od(i.id,t);return r?g.get(r)?.temp??null:null},v=[];for(const t of p){const i=e.layout[t.id];if(i&&i.s===e.spaceId){const e=i.x*Na,t=i.y*Na;v.push({minX:e,minY:t,maxX:e,maxY:t})}}const y=e.cfg.spaces.find(t=>t.id===e.spaceId)||{};if(!n.hideDecor)for(const t of y.decor||[]){if("image"!==t?.kind||!e.decorAssetUrl?.(String(t.asset_id||"")))continue;const i=al(t);i&&v.push(i)}const b=Array.isArray(y.walls)?y.walls:[],w=Number(y.cell_cm)>0?Number(y.cell_cm):5,k=r_(y,i,Na,.02*Ka),x=(y.openings||[]).flatMap(e=>{if("partition"!==e.host?.kind)return[];const t=vu(e,i.partitions,Na,w,Ka).resolved;return t?[t]:[]}),S=ic({partitions:i.partitions,columns:i.wall_columns,cellCm:w,hostedOpenings:x.map(e=>({id:e.opening.id,host:e.host,length:e.length,type:e.opening.type}))}),$=function(e,t,i,n){let r=rm.get(e);r||(r=new Map,rm.set(e,r));const o=r.get(t);if(o?.fingerprint===i)return o.value;const s=n();return r.set(t,{fingerprint:i,value:s}),s}(e.cfg,i.id,S,()=>ba(i,w,Ka,2e-4*Ka,x.map(wu)).all);for(const e of $){const t=e.map(e=>e[0]),i=e.map(e=>e[1]);t.length&&v.push({minX:Math.min(...t),minY:Math.min(...i),maxX:Math.max(...t),maxY:Math.max(...i)})}for(const e of k.lines)v.push({minX:Math.min(e[0],e[2]),minY:Math.min(e[1],e[3]),maxX:Math.max(e[0],e[2]),maxY:Math.max(e[1],e[3])});const M=function(e,t=1e3){const i=[];for(const[n,r]of(e||[]).entries()){if("passage"!==r?.type)continue;const e={...r,id:String(r.id||`passage-${n}`),type:"passage",rx:Number(r.x)*t,ry:Number(r.y)*t,rlen:Number(r.length)*t};[e.rx,e.ry,e.rlen,e.angle].every(Number.isFinite)&&e.rlen>0&&i.push(e)}return i}((y.openings||[]).flatMap(e=>{if(!e.host||"wall"===e.host.kind)return[e];const t=x.find(t=>t.opening.id===e.id);return t?[Mu(e,t,Na)]:[]}),Na),R=$s(i.rooms,b,k.contour,Ya,w,Ka,Na),C=x.filter(e=>Su(e,R,2e-4*Ka)).map(e=>({x:e.center[0],y:e.center[1],angle:e.angle,length:e.length})),T=il(e.fit),D=!!(b.length||$.length&&n.showBorders),A=D?ic(M.length?{rooms:i.rooms,walls:b,extras:$,cellCm:w,zero:k.contour,passages:M.map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),hostedCompositeOpenings:C}:{rooms:i.rooms,walls:b,extras:$,cellCm:w,zero:k.contour}):"",P=D?function(e,t,i,n){let r=nm.get(e);r||(r=new Map,nm.set(e,r));const o=r.get(t);if(o?.fingerprint===i)return o.value;const s=n();return r.set(t,{fingerprint:i,value:s}),s}(e.cfg,i.id,A,()=>{const e=Ks(i.rooms,b,k.contour,[...M.filter(e=>"partition"!==e.host?.kind).map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),...C],Ya,w,Ka,Na,$);return e&&Object.defineProperty(e,"sourceFingerprint",{value:ic([y,w,Ka]),enumerable:!1}),e}):null;let F=_l(i,v,e.compactTopFrame?{top:0,right:.05,bottom:.05,left:.05}:.05);if("house"===T){const e=[],t=za(2.5,w)/2,r=za(.6,w)/2;for(const n of i.rooms){const i=sl(n);i&&e.push(ol(i,t))}if(n.showBorders)for(const t of P?.components||[]){const i=rl(t.geom);i&&e.push(ol(i,r))}if(n.showBorders)for(const t of $){const i=rl(t);i&&e.push(ol(i,r))}if(n.showBorders)for(const i of k.lines){const n={minX:Math.min(i[0],i[2]),minY:Math.min(i[1],i[3]),maxX:Math.max(i[0],i[2]),maxY:Math.max(i[1],i[3])};e.push(ol(n,t))}if(!n.hideOpenings)for(const t of x){const i=t.opening,n="gate"===i.type?!i.flip_v:!!i.flip_v,r=Zu({type:i.type,length:t.length,angle:t.angle,flipH:!!i.flip_h,flipV:!!i.flip_v,cellCm:w,gridPitch:Ka,face:ku(t,n)},t.center);r&&e.push(r)}F=pl(e)||F}const z=[F.x,F.y,F.w,F.h],I=new Map(i.rooms.map(t=>{const i=zn(n.fill,t);return[t,_n(i,"lqi"===i&&t.area?Ld(l,u,t.area):null,"light"===i?md(pd(l,u,t,e.virtualLights)):"none","temp"===i?f(t):null,n.tempMin,n.tempMax,r,an(n.customFill,t))]})),O=new Map;for(const e of i.rooms)e.id&&O.set(e.id,I.get(e)||null);const E=i.rooms.filter(e=>e.area||n.showBorders||"none"!==zn(n.fill,e)).map(e=>{let t="room "+(i.bg?"overlay":"yard"),r="";const o=zn(n.fill,e);if(n.showBorders||"none"!==o){t+=" styled";const i=[`--room-stroke:${n.color}`,`--room-stroke-op:${n.showBorders&&!k.contour.length?n.opacity:0}`],o=I.get(e)||null;o?(t+=" filled",i.push(`--room-fill:${o.color}`,`--room-fill-op:${o.opacity.toFixed(3)}`)):i.push("--room-fill:transparent","--room-fill-op:0"),r=i.join(";")}const s=e.id||V,a=e.area||V,l=e.poly?W``}const rm=new WeakMap,om=new WeakMap,sm=new WeakMap,am=new WeakMap;function lm(e,t){const i=e.get(t);return void 0!==i&&(e.delete(t),e.set(t,i)),i}function cm(e,t,i,n){for(e.delete(t),e.set(t,i);e.size>n;)e.delete(e.keys().next().value)}function hm(e){const t=Wa(e.cfg),i={};for(const t of e.cfg.spaces||[])for(const e of t.rooms||[])e.area&&(i[e.area]=t.id);const n=Nd(e.cfg.settings),r=ze(e.cfg.settings?.icon_rules?.length?e.cfg.settings.icon_rules:Fe);return Pd({hass:e.hass,registry:e.registry,areaToSpace:i,markers:e.cfg.markers||[],settings:e.cfg.settings||{},excluded:n,showAll:!!e.cfg.settings?.show_all,firstSpaceId:t[0]?.id||"",loc:t=>ju(e.lang,t),iconRules:r})}function dm(e){const t=Wa(e.cfg),i=t.find(t=>t.id===e.spaceId);if(!i)return null;const n=ln(e.cfg.spaces.find(t=>t.id===e.spaceId)),r=un(e.cfg.settings),o=e.iconSize??2.5,s=o>8?2.5:o,a=qp(s),l=e.registry?Eh(e.hass,e.registry):e.hass,c=e.registry?Nh(e.hass,e.registry):e.hass,h=e.devices||hm(e),d=e.areaRelocationIds||S_({devices:h,model:t,layout:e.layout,snapshot:e.cfg.settings?.marker_area_snapshot,authoritative:!0===e.registry?.authoritative,coordinateScale:Na}).relocateIds,u=h.filter(t=>t.space===e.spaceId),p=u.filter(e=>!e.hidden),_=function(e,t,i){const n={},r=i/100*gl(t)*1.3;for(const i of t.rooms){if(!i.area)continue;const t=e.filter(e=>e.area===i.area);if(!t.length)continue;const o=bl(i),s=.1*Math.min(o.w,o.h),a=o.w-2*s,l=o.h-2*s,c=Math.max(1,Math.round(Math.sqrt(t.length*a/Math.max(l,1)))),h=a/c,d=l/Math.max(Math.ceil(t.length/c),1),u=t.map((e,t)=>({x:o.x+s+h*(t%c+.5),y:o.y+s+d*(Math.floor(t/c)+.5)}));zi(u,o,r,.5*s),t.forEach((e,t)=>n[e.id]=Za(u[t]))}return n}(u,i,s),m=ze(e.cfg.settings?.icon_rules?.length?e.cfg.settings.icon_rules:Fe),g=Hd(l,m,e.cfg.markers||[],Nd(e.cfg.settings)),f=t=>{const n=t.settings?.temp_source;if(n)return zd(l,n,"temp",e.cfg.markers||[]);const r=Od(i.id,t);return r?g.get(r)?.temp??null:null},v=[];for(const t of p){const i=e.layout[t.id];if(i&&i.s===e.spaceId){const e=i.x*Na,t=i.y*Na;v.push({minX:e,minY:t,maxX:e,maxY:t})}}const y=e.cfg.spaces.find(t=>t.id===e.spaceId)||{};if(!n.hideDecor)for(const t of y.decor||[]){if("image"!==t?.kind||!e.decorAssetUrl?.(String(t.asset_id||"")))continue;const i=al(t);i&&v.push(i)}const b=Array.isArray(y.walls)?y.walls:[],w=Number(y.cell_cm)>0?Number(y.cell_cm):5,k=r_(y,i,Na,.02*Ka),x=(y.openings||[]).flatMap(e=>{if("partition"!==e.host?.kind)return[];const t=vu(e,i.partitions,Na,w,Ka).resolved;return t?[t]:[]}),S=ic({partitions:i.partitions,columns:i.wall_columns,cellCm:w,hostedOpenings:x.map(e=>({id:e.opening.id,host:e.host,length:e.length,type:e.opening.type}))}),$=function(e,t,i,n){let r=om.get(e);r||(r=new Map,om.set(e,r));const o=r.get(t);if(o?.fingerprint===i)return o.value;const s=n();return r.set(t,{fingerprint:i,value:s}),s}(e.cfg,i.id,S,()=>ba(i,w,Ka,2e-4*Ka,x.map(wu)).all);for(const e of $){const t=e.map(e=>e[0]),i=e.map(e=>e[1]);t.length&&v.push({minX:Math.min(...t),minY:Math.min(...i),maxX:Math.max(...t),maxY:Math.max(...i)})}for(const e of k.lines)v.push({minX:Math.min(e[0],e[2]),minY:Math.min(e[1],e[3]),maxX:Math.max(e[0],e[2]),maxY:Math.max(e[1],e[3])});const M=function(e,t=1e3){const i=[];for(const[n,r]of(e||[]).entries()){if("passage"!==r?.type)continue;const e={...r,id:String(r.id||`passage-${n}`),type:"passage",rx:Number(r.x)*t,ry:Number(r.y)*t,rlen:Number(r.length)*t};[e.rx,e.ry,e.rlen,e.angle].every(Number.isFinite)&&e.rlen>0&&i.push(e)}return i}((y.openings||[]).flatMap(e=>{if(!e.host||"wall"===e.host.kind)return[e];const t=x.find(t=>t.opening.id===e.id);return t?[Mu(e,t,Na)]:[]}),Na),R=$s(i.rooms,b,k.contour,Ya,w,Ka,Na),C=x.filter(e=>Su(e,R,2e-4*Ka)).map(e=>({x:e.center[0],y:e.center[1],angle:e.angle,length:e.length})),T=il(e.fit),D=!!(b.length||$.length&&n.showBorders),A=D?ic(M.length?{rooms:i.rooms,walls:b,extras:$,cellCm:w,zero:k.contour,passages:M.map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),hostedCompositeOpenings:C}:{rooms:i.rooms,walls:b,extras:$,cellCm:w,zero:k.contour}):"",P=D?function(e,t,i,n){let r=rm.get(e);r||(r=new Map,rm.set(e,r));const o=r.get(t);if(o?.fingerprint===i)return o.value;const s=n();return r.set(t,{fingerprint:i,value:s}),s}(e.cfg,i.id,A,()=>{const e=Ks(i.rooms,b,k.contour,[...M.filter(e=>"partition"!==e.host?.kind).map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),...C],Ya,w,Ka,Na,$);return e&&Object.defineProperty(e,"sourceFingerprint",{value:ic([y,w,Ka]),enumerable:!1}),e}):null;let F=_l(i,v,e.compactTopFrame?{top:0,right:.05,bottom:.05,left:.05}:.05);if("house"===T){const e=[],t=za(2.5,w)/2,r=za(.6,w)/2;for(const n of i.rooms){const i=sl(n);i&&e.push(ol(i,t))}if(n.showBorders)for(const t of P?.components||[]){const i=rl(t.geom);i&&e.push(ol(i,r))}if(n.showBorders)for(const t of $){const i=rl(t);i&&e.push(ol(i,r))}if(n.showBorders)for(const i of k.lines){const n={minX:Math.min(i[0],i[2]),minY:Math.min(i[1],i[3]),maxX:Math.max(i[0],i[2]),maxY:Math.max(i[1],i[3])};e.push(ol(n,t))}if(!n.hideOpenings)for(const t of x){const i=t.opening,n="gate"===i.type?!i.flip_v:!!i.flip_v,r=Zu({type:i.type,length:t.length,angle:t.angle,flipH:!!i.flip_h,flipV:!!i.flip_v,cellCm:w,gridPitch:Ka,face:ku(t,n)},t.center);r&&e.push(r)}F=pl(e)||F}const z=[F.x,F.y,F.w,F.h],I=new Map(i.rooms.map(t=>{const i=zn(n.fill,t);return[t,_n(i,"lqi"===i&&t.area?Ld(l,u,t.area):null,"light"===i?md(pd(l,u,t,e.virtualLights)):"none","temp"===i?f(t):null,n.tempMin,n.tempMax,r,an(n.customFill,t))]})),O=new Map;for(const e of i.rooms)e.id&&O.set(e.id,I.get(e)||null);const E=i.rooms.filter(e=>e.area||n.showBorders||"none"!==zn(n.fill,e)).map(e=>{let t="room "+(i.bg?"overlay":"yard"),r="";const o=zn(n.fill,e);if(n.showBorders||"none"!==o){t+=" styled";const i=[`--room-stroke:${n.color}`,`--room-stroke-op:${n.showBorders&&!k.contour.length?n.opacity:0}`],o=I.get(e)||null;o?(t+=" filled",i.push(`--room-fill:${o.color}`,`--room-fill-op:${o.opacity.toFixed(3)}`)):i.push("--room-fill:transparent","--room-fill-op:0"),r=i.join(";")}const s=e.id||V,a=e.area||V,l=e.poly?W``:W``;return l}),N=i.rooms.filter(e=>In(n.glow,e)),H=N.filter(e=>{const t=I.get(e);return!t||t.opacity<=0}).map(e=>e.poly?W``}),U=n.showNames?i.rooms.filter(e=>e.name).map(t=>{const r=kl(t,i.id,e.layout,e.cfg),o=(r.x-z[0])/z[2]*100,s=(r.y-z[1])/z[3]*100,a=Math.min(1,n.opacity+.25);return j`
`}_discoveryFilterState(t){const e=this.host._settings,s=void 0!==t.draftGroupLights?t.draftGroupLights:!1!==e.group_lights,i=e.exclude_integrations,o=void 0!==t.draftExcluded?null===t.draftExcluded?[...ki]:t.draftExcluded:i?[...i]:[...ki],a=void 0!==t.draftExcluded?null===t.draftExcluded:!i,n=void 0!==t.draftGroupLights||void 0!==t.draftExcluded;return{groupLights:s,excluded:o.sort(),usesProductList:a,dirty:n}}_registryIntegrations(){const t=new Set,e=this.host._fullRegistryHass;for(const s of Object.values(e?.entities||{}))s?.platform&&t.add(String(s.platform));for(const s of Object.values(e?.devices||{})){const e=s?.identifiers?.[0],i=Array.isArray(e)?e[0]:null;i&&t.add(String(i))}return[...t].sort()}_discoveryFilterPreview(t){const e=this._discoveryFilterState(t),s=[e.groupLights?1:0,e.usesProductList?"p":e.excluded.join(","),this.host._cfgEpoch,this.host._regSignature].join("|");if(this._discoveryPreviewMemo?.key===s)return this._discoveryPreviewMemo.value;const i={hass:this.host.hass,registry:this.host._haRegistry,areaToSpace:Object.fromEntries(Object.entries(this.host._areaToSpace).map(([t,e])=>[t,e.space])),markers:this.host._markers,showAll:this.host._showAll,firstSpaceId:this.host._model[0]?.id||"",loc:t=>this.host._t(t),iconRules:this.host._iconRules},o=(t,e)=>new Set(Zi({...i,settings:t,excluded:e})),a=(t,e)=>new Set(Qi({...i,settings:t,excluded:e}).map(t=>t.bindingRef||t.id)),n=xi(this.host._settings),r={...this.host._settings,group_lights:e.groupLights},l=new Set(e.excluded),h=o(this.host._settings,n),c=o(r,l),d=a(this.host._settings,n),p=a(r,l);let u=0,_=0,m=0;const g=t=>t.includes("light.");for(const t of h)c.has(t)||(u++,g(t)&&m++);for(const t of c)h.has(t)||(_++,g(t)&&m++);for(const t of p)d.has(t)||(u++,g(t)&&m++);for(const t of d)p.has(t)||(_++,g(t)&&m++);const f={appear:u,hide:_,lights:m};return this._discoveryPreviewMemo={key:s,value:f},f}async _saveDiscoveryFilters(t){const e=this.host._serverCfg;if(!e)return;const s=this._discoveryFilterState(t),i={...e.settings};s.groupLights?delete i.group_lights:i.group_lights=!1,s.usesProductList?delete i.exclude_integrations:i.exclude_integrations=s.excluded,this.host._serverCfg={...e,settings:i},this.host._deviceInboxMemo=null,this._discoveryPreviewMemo=null,this.host._regSignature="",this.host._deviceInbox&&(this.host._deviceInbox={...t,draftGroupLights:void 0,draftExcluded:void 0}),this._saveConfig(),this.host._maybeRebuildDevices(),this.host.requestUpdate()}_renderDiscoveryFilters(t){const e=this._discoveryFilterState(t),s=e=>this.host._deviceInbox={...t,...e},i=t.filtersOpen&&e.dirty?this._discoveryFilterPreview(t):null,o=this._registryIntegrations().filter(t=>!e.excluded.includes(t));return h``}_discoveryFilterState(t){const e=this.host._settings,s=void 0!==t.draftGroupLights?t.draftGroupLights:!1!==e.group_lights,i=e.exclude_integrations,o=void 0!==t.draftExcluded?null===t.draftExcluded?[...xi]:t.draftExcluded:i?[...i]:[...xi],a=void 0!==t.draftExcluded?null===t.draftExcluded:!i,n=void 0!==t.draftGroupLights||void 0!==t.draftExcluded;return{groupLights:s,excluded:o.sort(),usesProductList:a,dirty:n}}_registryIntegrations(){const t=new Set,e=this.host._fullRegistryHass;for(const s of Object.values(e?.entities||{}))s?.platform&&t.add(String(s.platform));for(const s of Object.values(e?.devices||{})){const e=s?.identifiers?.[0],i=Array.isArray(e)?e[0]:null;i&&t.add(String(i))}return[...t].sort()}_discoveryFilterPreview(t){const e=this._discoveryFilterState(t),s=[e.groupLights?1:0,e.usesProductList?"p":e.excluded.join(","),this.host._cfgEpoch,this.host._regSignature].join("|");if(this._discoveryPreviewMemo?.key===s)return this._discoveryPreviewMemo.value;const i={hass:this.host.hass,registry:this.host._haRegistry,areaToSpace:Object.fromEntries(Object.entries(this.host._areaToSpace).map(([t,e])=>[t,e.space])),markers:this.host._markers,showAll:this.host._showAll,firstSpaceId:this.host._model[0]?.id||"",loc:t=>this.host._t(t),iconRules:this.host._iconRules},o=(t,e)=>new Set(Qi({...i,settings:t,excluded:e})),a=(t,e)=>new Set(to({...i,settings:t,excluded:e}).map(t=>t.bindingRef||t.id)),n=Si(this.host._settings),r={...this.host._settings,group_lights:e.groupLights},l=new Set(e.excluded),h=o(this.host._settings,n),c=o(r,l),d=a(this.host._settings,n),p=a(r,l);let u=0,_=0,m=0;const g=t=>t.includes("light.");for(const t of h)c.has(t)||(u++,g(t)&&m++);for(const t of c)h.has(t)||(_++,g(t)&&m++);for(const t of p)d.has(t)||(u++,g(t)&&m++);for(const t of d)p.has(t)||(_++,g(t)&&m++);const f={appear:u,hide:_,lights:m};return this._discoveryPreviewMemo={key:s,value:f},f}async _saveDiscoveryFilters(t){const e=this.host._serverCfg;if(!e)return;const s=this._discoveryFilterState(t),i={...e.settings};s.groupLights?delete i.group_lights:i.group_lights=!1,s.usesProductList?delete i.exclude_integrations:i.exclude_integrations=s.excluded,this.host._serverCfg={...e,settings:i},this.host._deviceInboxMemo=null,this._discoveryPreviewMemo=null,this.host._regSignature="",this.host._deviceInbox&&(this.host._deviceInbox={...t,draftGroupLights:void 0,draftExcluded:void 0}),this._saveConfig(),this.host._maybeRebuildDevices(),this.host.requestUpdate()}_renderDiscoveryFilters(t){const e=this._discoveryFilterState(t),s=e=>this.host._deviceInbox={...t,...e},i=t.filtersOpen&&e.dirty?this._discoveryFilterPreview(t):null,o=this._registryIntegrations().filter(t=>!e.excluded.includes(t));return h`s({filtersOpen:t.target.open})}>
${this.host._t("device_inbox.filters_title")}
@@ -2236,7 +2236,7 @@ globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae6
this.host._deviceInbox=null}>
${this.host._t("btn.close")}
- `}}export{Ic as EDITOR_RUNTIME_FINGERPRINT,Tc as HouseplanEditorRuntime};
+ `}}export{Lc as EDITOR_RUNTIME_FINGERPRINT,Oc as HouseplanEditorRuntime};
diff --git a/dist/houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js b/dist/houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js
similarity index 97%
rename from dist/houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js
rename to dist/houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js
index 777087cb..9df90a24 100644
--- a/dist/houseplan-assets/houseplan-onboarding-runtime-DvtWmEpp.js
+++ b/dist/houseplan-assets/houseplan-onboarding-runtime-DaYRnSkx.js
@@ -1,5 +1,5 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{l as t,a_ as s,A as e,x as o,b as a,ch as l,ci as i,cj as h,ck as c,aX as n,cl as r,cq as p,cm as _,cn as d,co as u,cp as g,dh as m,aW as b,aY as $,di as v}from"./houseplan-card-B_QYG0Py.js";import{i as f,c as y,e as w,r as D,a as k,b as S,g as C,t as M}from"./backdrop-pick-D6LhKf2N.js";const F=1e3,x=t=>{if(!t.trim())return null;const s=Number(t.replace(",","."));return Number.isFinite(s)?s:null},T="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";class L{constructor(t){this.host=t,this._toggleServerPlans=async()=>{const t=this.host._spaceDialog;if(t)if(t.pickSaved)this.host._spaceDialog={...t,pickSaved:!1};else{this.host._spaceDialog={...t,pickSaved:!0,savedBusy:!0};try{const t=await this.host.hass.callWS({type:"houseplan/plans/list"}),s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,saved:t?.plans||[],savedBusy:!1})}catch(t){const s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,saved:[],savedBusy:!1}),this.host._showToast(this.host._t("toast.plans_list_failed",{err:this.host._errText(t)}))}}}}_help(l){const i=`${l}.aria`,h=t(this.host.hass,this.host._config?.language);return s(h,l)&&s(h,i)?a``:e}_openSpaceDialog(t,s){if(!this.host._serverStorage||!this.host._serverCfg)return void this.host._showToast(this.host._t("toast.integration_missing"));if("edit"===t){const e=this.host._serverCfg.spaces.find(t=>t.id===s);if(!e)return;const o=l(e),a=e.settings?.custom_fill&&"object"==typeof e.settings.custom_fill?i(e.settings.custom_fill):null,p="none"===o.fill?{...a||h,a:0}:a;return void(this.host._spaceDialog={mode:t,spaceId:s,title:e.title,planUrl:e.plan_url||null,planFile:null,source:e.plan_url?"file":"draw",showBorders:o.showBorders,showNames:o.showNames,zeroWallStyle:r(e),displayTouched:!0,hideDecor:o.hideDecor,hideOpenings:o.hideOpenings,roomColor:o.color,roomOpacity:o.opacity,fillMode:"none"===o.fill?"custom":o.fill,customFill:p,glowEnabled:o.glow,bgColor:o.bgColor,bgMode:"static"===e.settings?.bg_mode||"daynight"===e.settings?.bg_mode?e.settings.bg_mode:null,northDeg:n({},e.settings),sunRays:"boolean"==typeof e.settings?.sun_rays?e.settings.sun_rays:null,tempMin:o.tempMin,tempMax:o.tempMax,showLqi:o.showLqi??this.host._config?.show_signal??!0,cardFontScale:o.cardFontScale,labelTemp:o.labelTemp,labelHum:o.labelHum,labelLqi:o.labelLqi,labelLight:o.labelLight,cellCm:Number(e.cell_cm)>0?Number(e.cell_cm):5,cellCmInput:c(Number(e.cell_cm)>0?Number(e.cell_cm):5,this.host._imperial),cellCmTouched:!1,busy:!1})}const e=p(this.host._imperial);this.host._spaceDialog={mode:t,title:"",planUrl:null,planFile:null,...f(),hideDecor:!1,hideOpenings:!1,zeroWallStyle:"dashed",roomColor:g,roomOpacity:u,fillMode:"custom",customFill:{...h,a:0},glowEnabled:!0,bgColor:null,bgMode:"daynight",northDeg:null,sunRays:null,tempMin:d,tempMax:_,showLqi:this.host._config?.show_signal??!0,cardFontScale:1,labelTemp:!1,labelHum:!1,labelLqi:!1,labelLight:!1,cellCm:e,cellCmInput:c(e,this.host._imperial),cellCmTouched:!1,busy:!1}}async _pickPlanFile(t){const s=t.target,e=s.files?.[0];if(!e||!this.host._spaceDialog)return;s.value="";const o=await y(e);if("reject"===o.kind)return void this.host._showToast(this.host._t("toast.plan_formats"));if("guard"===o.kind)return void(this.host._backdropGuard=o.state);const a=await w(e,o.ext,e.name);this.host._spaceDialog&&(this.host._spaceDialog={...this.host._spaceDialog,planFile:a})}_renderBackdropGuard(){return D(this.host,t=>{this.host._spaceDialog&&(this.host._spaceDialog={...this.host._spaceDialog,planFile:t})},()=>{this.host._backdropGuard=null},this.host.hass)??e}_useServerPlan(t){const s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,planUrl:t,planFile:null,pickSaved:!1,savedAspect:void 0},this.host._aspectJob=this._readPlanAspect(t))}async _readPlanAspect(t){for(let s=0;s<40;s++){const s=this.host._display(t);if(s){const e=await new Promise(t=>{const e=new Image;e.onload=()=>t(e.naturalWidth&&e.naturalHeight?e.naturalWidth/e.naturalHeight:0),e.onerror=()=>t(0),e.src=s}),o=this.host._spaceDialog;return o&&o.planUrl===t&&Number.isFinite(e)&&e>0?(this.host._spaceDialog={...o,savedAspect:e},e):0}if(await new Promise(t=>setTimeout(t,150)),this.host._spaceDialog?.planUrl!==t)return 0}return 0}async _deleteServerPlan(t){const s=this.host._spaceDialog,e=s?.saved?.find(s=>s.name===t);if(!s||!e||e.used_by.length||e.url===s.planUrl)return;const o=await this.host._confirmDanger({key:"delete-plan",kind:"destructive",title:this.host._t("confirm.delete_plan_title"),message:this.host._t("confirm.delete_plan_body"),objectName:t,confirmLabel:this.host._t("btn.delete"),cancelLabel:this.host._t("btn.cancel")}),a=this.host._spaceDialog,l=a?.saved?.find(s=>s.name===t);if(o&&a&&l&&l.url===e.url&&l.modified===e.modified&&!l.used_by.length&&l.url!==a.planUrl)try{await this.host.hass.callWS({type:"houseplan/plans/delete",name:t});const s=this.host._spaceDialog;s?.saved&&(this.host._spaceDialog={...s,saved:s.saved.filter(s=>s.name!==t)})}catch(t){this.host._showToast(this.host._t("toast.plan_delete_failed",{err:this.host._errText(t)}))}}_renderServerPlans(t){if(t.savedBusy)return a`
${this.host._t("space.loading")}
`;const s=t.saved||[];if(!s.length)return a`
${this.host._t("space.no_saved")}
`;return a`
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{l as t,a_ as s,A as e,x as o,b as a,ci as l,cj as i,ck as h,cl as c,aX as n,cm as r,cr as p,cn as d,co as _,cp as u,cq as g,di as m,aW as b,aY as $,dj as v}from"./houseplan-card-6Hf8VPda.js";import{i as f,c as y,e as w,r as D,a as k,b as S,g as C,t as M}from"./backdrop-pick-BsRoeWMx.js";const F=1e3,x=t=>{if(!t.trim())return null;const s=Number(t.replace(",","."));return Number.isFinite(s)?s:null},T="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";class L{constructor(t){this.host=t,this._toggleServerPlans=async()=>{const t=this.host._spaceDialog;if(t)if(t.pickSaved)this.host._spaceDialog={...t,pickSaved:!1};else{this.host._spaceDialog={...t,pickSaved:!0,savedBusy:!0};try{const t=await this.host.hass.callWS({type:"houseplan/plans/list"}),s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,saved:t?.plans||[],savedBusy:!1})}catch(t){const s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,saved:[],savedBusy:!1}),this.host._showToast(this.host._t("toast.plans_list_failed",{err:this.host._errText(t)}))}}}}_help(l){const i=`${l}.aria`,h=t(this.host.hass,this.host._config?.language);return s(h,l)&&s(h,i)?a``:e}_openSpaceDialog(t,s){if(!this.host._serverStorage||!this.host._serverCfg)return void this.host._showToast(this.host._t("toast.integration_missing"));if("edit"===t){const e=this.host._serverCfg.spaces.find(t=>t.id===s);if(!e)return;const o=l(e),a=e.settings?.custom_fill&&"object"==typeof e.settings.custom_fill?i(e.settings.custom_fill):null,p="none"===o.fill?{...a||h,a:0}:a;return void(this.host._spaceDialog={mode:t,spaceId:s,title:e.title,planUrl:e.plan_url||null,planFile:null,source:e.plan_url?"file":"draw",showBorders:o.showBorders,showNames:o.showNames,zeroWallStyle:r(e),displayTouched:!0,hideDecor:o.hideDecor,hideOpenings:o.hideOpenings,roomColor:o.color,roomOpacity:o.opacity,fillMode:"none"===o.fill?"custom":o.fill,customFill:p,glowEnabled:o.glow,bgColor:o.bgColor,bgMode:"static"===e.settings?.bg_mode||"daynight"===e.settings?.bg_mode?e.settings.bg_mode:null,northDeg:n({},e.settings),sunRays:"boolean"==typeof e.settings?.sun_rays?e.settings.sun_rays:null,tempMin:o.tempMin,tempMax:o.tempMax,showLqi:o.showLqi??this.host._config?.show_signal??!0,cardFontScale:o.cardFontScale,labelTemp:o.labelTemp,labelHum:o.labelHum,labelLqi:o.labelLqi,labelLight:o.labelLight,cellCm:Number(e.cell_cm)>0?Number(e.cell_cm):5,cellCmInput:c(Number(e.cell_cm)>0?Number(e.cell_cm):5,this.host._imperial),cellCmTouched:!1,busy:!1})}const e=p(this.host._imperial);this.host._spaceDialog={mode:t,title:"",planUrl:null,planFile:null,...f(),hideDecor:!1,hideOpenings:!1,zeroWallStyle:"dashed",roomColor:g,roomOpacity:u,fillMode:"custom",customFill:{...h,a:0},glowEnabled:!0,bgColor:null,bgMode:"daynight",northDeg:null,sunRays:null,tempMin:_,tempMax:d,showLqi:this.host._config?.show_signal??!0,cardFontScale:1,labelTemp:!1,labelHum:!1,labelLqi:!1,labelLight:!1,cellCm:e,cellCmInput:c(e,this.host._imperial),cellCmTouched:!1,busy:!1}}async _pickPlanFile(t){const s=t.target,e=s.files?.[0];if(!e||!this.host._spaceDialog)return;s.value="";const o=await y(e);if("reject"===o.kind)return void this.host._showToast(this.host._t("toast.plan_formats"));if("guard"===o.kind)return void(this.host._backdropGuard=o.state);const a=await w(e,o.ext,e.name);this.host._spaceDialog&&(this.host._spaceDialog={...this.host._spaceDialog,planFile:a})}_renderBackdropGuard(){return D(this.host,t=>{this.host._spaceDialog&&(this.host._spaceDialog={...this.host._spaceDialog,planFile:t})},()=>{this.host._backdropGuard=null},this.host.hass)??e}_useServerPlan(t){const s=this.host._spaceDialog;s&&(this.host._spaceDialog={...s,planUrl:t,planFile:null,pickSaved:!1,savedAspect:void 0},this.host._aspectJob=this._readPlanAspect(t))}async _readPlanAspect(t){for(let s=0;s<40;s++){const s=this.host._display(t);if(s){const e=await new Promise(t=>{const e=new Image;e.onload=()=>t(e.naturalWidth&&e.naturalHeight?e.naturalWidth/e.naturalHeight:0),e.onerror=()=>t(0),e.src=s}),o=this.host._spaceDialog;return o&&o.planUrl===t&&Number.isFinite(e)&&e>0?(this.host._spaceDialog={...o,savedAspect:e},e):0}if(await new Promise(t=>setTimeout(t,150)),this.host._spaceDialog?.planUrl!==t)return 0}return 0}async _deleteServerPlan(t){const s=this.host._spaceDialog,e=s?.saved?.find(s=>s.name===t);if(!s||!e||e.used_by.length||e.url===s.planUrl)return;const o=await this.host._confirmDanger({key:"delete-plan",kind:"destructive",title:this.host._t("confirm.delete_plan_title"),message:this.host._t("confirm.delete_plan_body"),objectName:t,confirmLabel:this.host._t("btn.delete"),cancelLabel:this.host._t("btn.cancel")}),a=this.host._spaceDialog,l=a?.saved?.find(s=>s.name===t);if(o&&a&&l&&l.url===e.url&&l.modified===e.modified&&!l.used_by.length&&l.url!==a.planUrl)try{await this.host.hass.callWS({type:"houseplan/plans/delete",name:t});const s=this.host._spaceDialog;s?.saved&&(this.host._spaceDialog={...s,saved:s.saved.filter(s=>s.name!==t)})}catch(t){this.host._showToast(this.host._t("toast.plan_delete_failed",{err:this.host._errText(t)}))}}_renderServerPlans(t){if(t.savedBusy)return a`
diff --git a/dist/houseplan-assets/hp-zigbee-topology-overlay-DVdGoL1j.js b/dist/houseplan-assets/hp-zigbee-topology-overlay-B947ne3H.js
similarity index 93%
rename from dist/houseplan-assets/hp-zigbee-topology-overlay-DVdGoL1j.js
rename to dist/houseplan-assets/hp-zigbee-topology-overlay-B947ne3H.js
index 457a69d4..e0bca90e 100644
--- a/dist/houseplan-assets/hp-zigbee-topology-overlay-DVdGoL1j.js
+++ b/dist/houseplan-assets/hp-zigbee-topology-overlay-B947ne3H.js
@@ -1,4 +1,4 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{t as e,l as t,A as i,dQ as r,w as o,b as s,q as n}from"./houseplan-card-B_QYG0Py.js";import{t as a,a as h,r as d}from"./zigbee-topology-BnpLzLg7.js";import{zigbeeTopologyRuntimeSnapshot as p,subscribeZigbeeTopology as l}from"./zigbee-topology-runtime-JzXR8tg6.js";function c(e,t,i,r,o,s=9,n=4.5){const a=t.x-e.x,h=t.y-e.y,d=Math.hypot(a,h),p=d-Math.max(0,i)-Math.max(0,r);if(!Number.isFinite(d)||d<=0||p<4)return null;const l=a/d,c=h/d,_="toward-neighbor"===o,u=_?{x:t.x-l*Math.max(0,r),y:t.y-c*Math.max(0,r)}:{x:e.x+l*Math.max(0,i),y:e.y+c*Math.max(0,i)},m=Math.min(s,Math.max(4,.45*p)),v=Math.min(n,.5*m),b=_?-1:1,g=u.x+l*m*b,y=u.y+c*m*b,x=-c;return{tip:u,points:[u,{x:g+x*v,y:y+l*v},{x:g-x*v,y:y-l*v}]}}const _={revision:0,topologies:[],states:{}},u="data-hp-zigbee-topology-endpoint";class m extends e{constructor(){super(...arguments),this.devices=[],this.currentSpace="",this._runtime=_,this._hovered="",this._desiredEndpointIds=new Set,this._endpointSetDirty=!1,this._endpointElements=new Set,this._pointerOver=e=>{if(!this._mouseAllowed(e))return void this._clear();const t=this._deviceFromEvent(e),i=t?.dataset.id||"";i&&i!==this._hovered&&(this._hovered=i,this.requestUpdate())},this._pointerOut=e=>{const t=this._deviceFromEvent(e);if(!t||t.dataset.id!==this._hovered)return;const i=e.relatedTarget instanceof Element?e.relatedTarget.closest('[data-hp="device"]'):null;i?.dataset.id!==this._hovered&&this._clear()},this._pointerDown=e=>{"mouse"!==e.pointerType&&this._clear()}}connectedCallback(){super.connectedCallback();const e=this.getRootNode();e.host&&"undefined"!=typeof MutationObserver&&(this._hoverGateObserver=new MutationObserver(()=>{e.host.hasAttribute("data-pointer-hover")||this._clear()}),this._hoverGateObserver.observe(e.host,{attributes:!0,attributeFilter:["data-pointer-hover"]})),queueMicrotask(()=>this._connectParent())}disconnectedCallback(){this._release?.(),this._release=void 0,this._disconnectParent(),this._hoverGateObserver?.disconnect(),this._hoverGateObserver=void 0,this._hovered="",this._desiredEndpointIds.clear(),super.disconnectedCallback()}updated(e){e.has("hass")&&(this._release?.(),this._acceptRuntime(p(this.hass)),this._release=l(this.hass,()=>{this._acceptRuntime(p(this.hass))}));const t=e.has("currentSpace")||e.has("devices")||e.has("registry");t&&(this._mappedMemo=void 0,this.devices.some(e=>e.id===this._hovered&&e.space===this.currentSpace)||this._clear()),this._connectParent(),(this._endpointSetDirty||t)&&this._syncEndpointOwnership()}_acceptRuntime(e){e.revision===this._runtime.revision&&e.topologies===this._runtime.topologies&&e.states===this._runtime.states||(this._setDesiredEndpointIds([]),this._clearEndpointOwnership(),this._endpointSetDirty=!1,this._runtime=e,this._mappedMemo=void 0,this.requestUpdate())}_connectParent(){const e=this.parentElement;e&&e!==this._parent&&(this._disconnectParent(),this._parent=e,e.addEventListener("pointerover",this._pointerOver),e.addEventListener("pointerout",this._pointerOut),e.addEventListener("pointerdown",this._pointerDown,!0),"undefined"!=typeof MutationObserver&&(this._markerObserver=new MutationObserver(()=>this._syncEndpointOwnership()),this._markerObserver.observe(e,{childList:!0})),this._syncEndpointOwnership())}_disconnectParent(){this._parent?.removeEventListener("pointerover",this._pointerOver),this._parent?.removeEventListener("pointerout",this._pointerOut),this._parent?.removeEventListener("pointerdown",this._pointerDown,!0),this._markerObserver?.disconnect(),this._markerObserver=void 0,this._clearEndpointOwnership(),this._parent=void 0}_deviceFromEvent(e){for(const t of e.composedPath())if(t instanceof HTMLElement&&"device"===t.dataset.hp)return t;return null}_mouseAllowed(e){const t=this.getRootNode();return"mouse"===e.pointerType&&t.host?.hasAttribute?.("data-pointer-hover")}_clear(){this._setDesiredEndpointIds([]),this._clearEndpointOwnership(),this._endpointSetDirty=!1,this._hovered&&(this._hovered="",this.requestUpdate())}_setDesiredEndpointIds(e){const t=new Set(e);t.size===this._desiredEndpointIds.size&&[...t].every(e=>this._desiredEndpointIds.has(e))||(this._desiredEndpointIds=t,this._endpointSetDirty=!0)}_marker(e){return[...this._parent?.querySelectorAll('.dev[data-hp="device"][data-id]')||[]].find(t=>t.dataset.id===e)||null}_clearEndpointOwnership(){for(const e of this._endpointElements)e.removeAttribute(u);for(const e of this._parent?.querySelectorAll(`[${u}]`)||[])e.removeAttribute(u);this._endpointElements.clear()}_syncEndpointOwnership(){const e=new Set;for(const t of this._desiredEndpointIds){const i=this._marker(t);i&&e.add(i)}for(const t of this._endpointElements)e.has(t)||t.removeAttribute(u);for(const t of this._parent?.querySelectorAll(`[${u}]`)||[])e.has(t)||t.removeAttribute(u);for(const t of e)this._endpointElements.has(t)&&t.hasAttribute(u)||t.setAttribute(u,"");this._endpointElements=e,this._endpointSetDirty=!1}_position(e,t,i){const r=this._marker(e);if(!r)return null;const o=Number.parseFloat(r.style.left),s=Number.parseFloat(r.style.top),n=r.getBoundingClientRect();return Number.isFinite(o)&&Number.isFinite(s)?{x:o*t/100,y:s*i/100,width:n.width,height:n.height}:null}_targetText(e){if("remote-space"===e.kind){const i=this.spaces?.find(t=>t.id===e.spaceId)?.title;return"string"==typeof i&&i.trim()||a(t(this.hass),"route_other_space")}return a(t(this.hass),"unplaced-coordinator"===e.kind?"route_coordinator_not_on_plan":"route_device_not_on_plan")}_markerClearance(e){return.61*Math.max(e.width,e.height)+3}_points(e){return e.map(e=>`${e.x.toFixed(2)},${e.y.toFixed(2)}`).join(" ")}render(){if(!this._hovered||!this.registry||!this._runtime.topologies.length)return this._setDesiredEndpointIds([]),i;const e=this._mappedMemo,n=e&&e.runtime===this._runtime&&e.devices===this.devices&&e.registry===this.registry?e.mapped:h(this._runtime.topologies,this.devices,this.registry);e&&n===e.mapped||(this._mappedMemo={runtime:this._runtime,devices:this.devices,registry:this.registry,mapped:n});const p=d(n,this.currentSpace,this._hovered),l=this.clientWidth||this._parent?.clientWidth||1,_=this.clientHeight||this._parent?.clientHeight||1,u=this._position(this._hovered,l,_);if(!u)return this._setDesiredEndpointIds([]),i;const m=p.lines.map(e=>({...e,point:this._position(e.neighborMarkerId,l,_)})).filter(e=>!!e.point).map(e=>{const t=void 0===e.lqi?"rgba(145,155,165,.85)":r(e.lqi),i=e.routeDirection?c(u,e.point,this._markerClearance(u),this._markerClearance(e.point),e.routeDirection):null;return{...e,color:t,arrow:i}}),v=u.x>l/2,b=this._markerClearance(u)+18,g=p.parentTargets.map((e,t)=>{const i=30*(t-(p.parentTargets.length-1)/2),r={x:u.x+(v?-b:b),y:Math.max(14,Math.min(_-14,u.y+i))};return{target:e,point:r,arrow:c(u,r,this._markerClearance(u),0,"toward-neighbor")}});return this._setDesiredEndpointIds(m.length||g.length||p.remoteCount?[this._hovered,...m.map(e=>e.neighborMarkerId)]:[]),s`
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{t as e,l as t,A as i,dR as r,w as o,b as s,q as n}from"./houseplan-card-6Hf8VPda.js";import{t as a,a as h,r as d}from"./zigbee-topology-C3YPlOFO.js";import{zigbeeTopologyRuntimeSnapshot as p,subscribeZigbeeTopology as l}from"./zigbee-topology-runtime-Cjiy8VeA.js";function c(e,t,i,r,o,s=9,n=4.5){const a=t.x-e.x,h=t.y-e.y,d=Math.hypot(a,h),p=d-Math.max(0,i)-Math.max(0,r);if(!Number.isFinite(d)||d<=0||p<4)return null;const l=a/d,c=h/d,_="toward-neighbor"===o,u=_?{x:t.x-l*Math.max(0,r),y:t.y-c*Math.max(0,r)}:{x:e.x+l*Math.max(0,i),y:e.y+c*Math.max(0,i)},m=Math.min(s,Math.max(4,.45*p)),b=Math.min(n,.5*m),v=_?-1:1,g=u.x+l*m*v,y=u.y+c*m*v,x=-c;return{tip:u,points:[u,{x:g+x*b,y:y+l*b},{x:g-x*b,y:y-l*b}]}}const _={revision:0,topologies:[],states:{}},u="data-hp-zigbee-topology-endpoint";class m extends e{constructor(){super(...arguments),this.devices=[],this.currentSpace="",this._runtime=_,this._hovered="",this._desiredEndpointIds=new Set,this._endpointSetDirty=!1,this._endpointElements=new Set,this._pointerOver=e=>{if(!this._mouseAllowed(e))return void this._clear();const t=this._deviceFromEvent(e),i=t?.dataset.id||"";i&&i!==this._hovered&&(this._hovered=i,this.requestUpdate())},this._pointerOut=e=>{const t=this._deviceFromEvent(e);if(!t||t.dataset.id!==this._hovered)return;const i=e.relatedTarget instanceof Element?e.relatedTarget.closest('[data-hp="device"]'):null;i?.dataset.id!==this._hovered&&this._clear()},this._pointerDown=e=>{"mouse"!==e.pointerType&&this._clear()}}connectedCallback(){super.connectedCallback();const e=this.getRootNode();e.host&&"undefined"!=typeof MutationObserver&&(this._hoverGateObserver=new MutationObserver(()=>{e.host.hasAttribute("data-pointer-hover")||this._clear()}),this._hoverGateObserver.observe(e.host,{attributes:!0,attributeFilter:["data-pointer-hover"]})),queueMicrotask(()=>this._connectParent())}disconnectedCallback(){this._release?.(),this._release=void 0,this._disconnectParent(),this._hoverGateObserver?.disconnect(),this._hoverGateObserver=void 0,this._hovered="",this._desiredEndpointIds.clear(),super.disconnectedCallback()}updated(e){e.has("hass")&&(this._release?.(),this._acceptRuntime(p(this.hass)),this._release=l(this.hass,()=>{this._acceptRuntime(p(this.hass))}));const t=e.has("currentSpace")||e.has("devices")||e.has("registry");t&&(this._mappedMemo=void 0,this.devices.some(e=>e.id===this._hovered&&e.space===this.currentSpace)||this._clear()),this._connectParent(),(this._endpointSetDirty||t)&&this._syncEndpointOwnership()}_acceptRuntime(e){e.revision===this._runtime.revision&&e.topologies===this._runtime.topologies&&e.states===this._runtime.states||(this._setDesiredEndpointIds([]),this._clearEndpointOwnership(),this._endpointSetDirty=!1,this._runtime=e,this._mappedMemo=void 0,this.requestUpdate())}_connectParent(){const e=this.parentElement;e&&e!==this._parent&&(this._disconnectParent(),this._parent=e,e.addEventListener("pointerover",this._pointerOver),e.addEventListener("pointerout",this._pointerOut),e.addEventListener("pointerdown",this._pointerDown,!0),"undefined"!=typeof MutationObserver&&(this._markerObserver=new MutationObserver(()=>this._syncEndpointOwnership()),this._markerObserver.observe(e,{childList:!0})),this._syncEndpointOwnership())}_disconnectParent(){this._parent?.removeEventListener("pointerover",this._pointerOver),this._parent?.removeEventListener("pointerout",this._pointerOut),this._parent?.removeEventListener("pointerdown",this._pointerDown,!0),this._markerObserver?.disconnect(),this._markerObserver=void 0,this._clearEndpointOwnership(),this._parent=void 0}_deviceFromEvent(e){for(const t of e.composedPath())if(t instanceof HTMLElement&&"device"===t.dataset.hp)return t;return null}_mouseAllowed(e){const t=this.getRootNode();return"mouse"===e.pointerType&&t.host?.hasAttribute?.("data-pointer-hover")}_clear(){this._setDesiredEndpointIds([]),this._clearEndpointOwnership(),this._endpointSetDirty=!1,this._hovered&&(this._hovered="",this.requestUpdate())}_setDesiredEndpointIds(e){const t=new Set(e);t.size===this._desiredEndpointIds.size&&[...t].every(e=>this._desiredEndpointIds.has(e))||(this._desiredEndpointIds=t,this._endpointSetDirty=!0)}_marker(e){return[...this._parent?.querySelectorAll('.dev[data-hp="device"][data-id]')||[]].find(t=>t.dataset.id===e)||null}_clearEndpointOwnership(){for(const e of this._endpointElements)e.removeAttribute(u);for(const e of this._parent?.querySelectorAll(`[${u}]`)||[])e.removeAttribute(u);this._endpointElements.clear()}_syncEndpointOwnership(){const e=new Set;for(const t of this._desiredEndpointIds){const i=this._marker(t);i&&e.add(i)}for(const t of this._endpointElements)e.has(t)||t.removeAttribute(u);for(const t of this._parent?.querySelectorAll(`[${u}]`)||[])e.has(t)||t.removeAttribute(u);for(const t of e)this._endpointElements.has(t)&&t.hasAttribute(u)||t.setAttribute(u,"");this._endpointElements=e,this._endpointSetDirty=!1}_position(e,t,i){const r=this._marker(e);if(!r)return null;const o=Number.parseFloat(r.style.left),s=Number.parseFloat(r.style.top),n=r.getBoundingClientRect();return Number.isFinite(o)&&Number.isFinite(s)?{x:o*t/100,y:s*i/100,width:n.width,height:n.height}:null}_targetText(e){if("remote-space"===e.kind){const i=this.spaces?.find(t=>t.id===e.spaceId)?.title;return"string"==typeof i&&i.trim()||a(t(this.hass),"route_other_space")}return a(t(this.hass),"unplaced-coordinator"===e.kind?"route_coordinator_not_on_plan":"route_device_not_on_plan")}_markerClearance(e){return.61*Math.max(e.width,e.height)+3}_points(e){return e.map(e=>`${e.x.toFixed(2)},${e.y.toFixed(2)}`).join(" ")}render(){if(!this._hovered||!this.registry||!this._runtime.topologies.length)return this._setDesiredEndpointIds([]),i;const e=this._mappedMemo,n=e&&e.runtime===this._runtime&&e.devices===this.devices&&e.registry===this.registry?e.mapped:h(this._runtime.topologies,this.devices,this.registry);e&&n===e.mapped||(this._mappedMemo={runtime:this._runtime,devices:this.devices,registry:this.registry,mapped:n});const p=d(n,this.currentSpace,this._hovered),l=this.clientWidth||this._parent?.clientWidth||1,_=this.clientHeight||this._parent?.clientHeight||1,u=this._position(this._hovered,l,_);if(!u)return this._setDesiredEndpointIds([]),i;const m=p.lines.map(e=>({...e,point:this._position(e.neighborMarkerId,l,_)})).filter(e=>!!e.point).map(e=>{const t=void 0===e.lqi?"rgba(145,155,165,.85)":r(e.lqi),i=e.routeDirection?c(u,e.point,this._markerClearance(u),this._markerClearance(e.point),e.routeDirection):null;return{...e,color:t,arrow:i}}),b=u.x>l/2,v=this._markerClearance(u)+18,g=p.parentTargets.map((e,t)=>{const i=30*(t-(p.parentTargets.length-1)/2),r={x:u.x+(b?-v:v),y:Math.max(14,Math.min(_-14,u.y+i))};return{target:e,point:r,arrow:c(u,r,this._markerClearance(u),0,"toward-neighbor")}});return this._setDesiredEndpointIds(m.length||g.length||p.remoteCount?[this._hovered,...m.map(e=>e.neighborMarkerId)]:[]),s`
${m.length||g.length?o`
`)}
- ${g.map(e=>s`
s`
${this._targetText(e.target)}
`)}
${p.remoteCount?s`
`${Number(e[0].toFixed(4))} ${Number(e[1].toFixed(4))}`;function j(e){let t=0;for(let n=0;nArray.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1])).map(e=>[Number(e[0]),Number(e[1])]),n=t[t.length-1];return t.length>1&&t[0][0]===n[0]&&t[0][1]===n[1]&&t.pop(),t}(e);if(n.length<3)return[];const o=!t;return j(n)>0===o?n:[...n].reverse()}function O(e,t,o){return e.length?`M ${e.map(e=>C(n(e,o,t))).join(" L ")} Z`:""}function A(e,t,n){const o=t[1]-e[1],i=-(t[0]-e[0]),a=n.rotDeg*Math.PI/180;return o*Math.sin(a)+i*Math.cos(a)}function B(t,o,i=e){if(!Number.isFinite(o)||o<0)throw new Error("invalid floor edge height");const a=(t||[]).map(e=>(e||[]).map((e,t)=>function(e,t){const n=N(e,t);if(!n.length)return n;let o=0;for(let e=1;e0)).filter(e=>e.length>=3&&Math.abs(j(e))>=1e-9)).filter(e=>e.length&&j(e[0])>0);a.sort((e,t)=>{const n=e[0][0],o=t[0][0];return n[0]-o[0]||n[1]-o[1]||Math.abs(j(t[0]))-Math.abs(j(e[0]))});const r=[],s=[];let l=0;for(let e=0;ee.depth-t.depth||e.component-t.component||e.edge-t.edge),{footprintPath:r.join(" "),sides:s,componentCount:a.length,edgeCount:l}}function R(e,t){return e^=Math.round(64*(Number.isFinite(t)?t:0)),Math.imul(e,16777619)>>>0}const H=Object.freeze({revision:1,leafThicknessRatio:.04,frameThicknessRatio:.055,gateTurnDeg:10,gateTopRatio:.88,windowBottomRatio:.27,windowTopRatio:.78,doorTopRatio:.92});H.leafThicknessRatio,H.frameThicknessRatio;const F=e=>e.every(Number.isFinite);function T(e,t){return Object.freeze([Object.is(e,-0)?0:e,Object.is(t,-0)?0:t])}function L(e,t){return[e[0]+t[0],e[1]+t[1]]}function V(e,t){return[e[0]-t[0],e[1]-t[1]]}function G(e,t){return[e[0]*t,e[1]*t]}function W(e,t,n,o){const i=e[0]*n,a=e[1]*o,r=t*Math.PI/180;return[i*Math.cos(r)-a*Math.sin(r),i*Math.sin(r)+a*Math.cos(r)]}function E(e,t,n,i,a,r,s){const l=e.flipH?-1:1,c="gate"===e.type?1:e.flipV?-1:1,d=o(e.type,e.flipV,e.angle,e.face);return{leaf:t,hinge:L([e.x+d.ox,e.y+d.oy],W(n,e.angle,l,c)),closedVector:W(i,e.angle,l,c),quarterVector:W([-i[1],i[0]],e.angle,l,c),turnDeg:a,bottom:r,top:s}}const q=e=>`${Number(e[0].toFixed(4))} ${Number(e[1].toFixed(4))}`;function D(e,t,o,i,a={}){const r=o.map(e=>n(e.point,e.z,i));return Object.freeze({kind:e,material:t,d:`M ${r.map(q).join(" L ")} Z`,depth:Math.max(...r.map(e=>e[1])),...a})}function _(e,t,n,o,i,a,r,s={}){return D(e,t,[{point:n,z:i},{point:o,z:i},{point:o,z:a},{point:n,z:a}],r,s)}function U(t,o,i=e){const a=Math.max(0,Math.min(1,Number.isFinite(o)?o:0));return t.leaves.map(e=>{const o=function(e,t){const n=e.turnDeg*t*Math.PI/180;return[e.hinge[0]+e.closedVector[0]*Math.cos(n)+e.quarterVector[0]*Math.sin(n),e.hinge[1]+e.closedVector[1]*Math.cos(n)+e.quarterVector[1]*Math.sin(n)]}(e,a),r=n(e.hinge,e.bottom,i),s=n(o,e.bottom,i),l=n(o,e.top,i),c=n(e.hinge,e.top,i),d="window"===t.type?"light-window":"matte-leaf",f="window"===t.type?Object.freeze([_("window-insert","light-window",e.hinge,o,e.bottom,e.top,i)]):function(e,t,n,o){const i=V(t,e.hinge),a=Math.hypot(i[0],i[1]);if(!(a>1e-9&&n>0))return Object.freeze([]);const r=T(-i[1]*n/(2*a),i[0]*n/(2*a)),s=L(e.hinge,r),l=L(t,r),c=V(e.hinge,r),d=V(t,r),f=[_("leaf-back","matte-leaf",d,c,e.bottom,e.top,o),_("leaf-front","matte-leaf",s,l,e.bottom,e.top,o),_("leaf-edge","matte-leaf",c,s,e.bottom,e.top,o,{edge:"hinge"}),_("leaf-edge","matte-leaf",l,d,e.bottom,e.top,o,{edge:"tip"}),D("leaf-top","matte-leaf",[{point:s,z:e.top},{point:c,z:e.top},{point:d,z:e.top},{point:l,z:e.top}],o)];return Object.freeze(f.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||String(e.edge||"").localeCompare(String(t.edge||""))))}(e,o,t.leafThickness,i);return Object.freeze({id:t.id,sourceIndex:t.sourceIndex,type:t.type,leaf:e.leaf,d:`M ${q(r)} L ${q(s)} L ${q(l)} L ${q(c)} Z`,shadowD:`M ${q(n(e.hinge,0,i))} L ${q(n(o,0,i))}`,depth:Math.max(r[1],s[1]),material:d,thickness:"window"===t.type?0:t.leafThickness,surfaces:f})})}const K=1e-9,Z=e=>e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function J(e){let t=0;for(let n=0;n=3&&e.every(Z)&&Math.abs(J(e))>K}function X(e,t,n){const o=n[0]-t[0],i=n[1]-t[1],a=o*o+i*i,r=a?Math.max(0,Math.min(1,((e[0]-t[0])*o+(e[1]-t[1])*i)/a)):0;return Math.hypot(e[0]-t[0]-r*o,e[1]-t[1]-r*i)}function Y(e,t,n=1e-7){for(let o=0;oe[1]!=r[1]>e[1]&&e[0]<(r[0]-a[0])*(e[1]-a[1])/(r[1]-a[1])+a[0]&&(n=!n)}return n}function te(e){return Math.max(0,Math.abs(J(e.outer))-(e.holes||[]).reduce((e,t)=>e+Math.abs(J(t)),0))}function ne(e){return!!e.id&&Q(e.outer)&&(e.holes||[]).every(Q)&&te(e)>K}function oe(e,t){if(!ne(t)||Y(e,t.outer)||!ee(e,t.outer))return!1;for(const n of t.holes||[])if(Y(e,n)||ee(e,n))return!1;return!0}function ie(e){if(!ne(e))return null;if(e.safePoint&&oe(e.safePoint,e))return[e.safePoint[0],e.safePoint[1]];const t=e.outer.map(e=>e[0]),n=e.outer.map(e=>e[1]),o=Math.min(...t),i=Math.max(...t),a=Math.min(...n),r=Math.max(...n),s=[[(o+i)/2,(a+r)/2],[t.reduce((e,t)=>e+t,0)/t.length,n.reduce((e,t)=>e+t,0)/n.length]];for(let t=0;t{if(!oe(t,e))return;const n=function(e,t){let n=1/0;for(const o of[t.outer,...t.holes||[]])for(let t=0;tc+K&&(l=t,c=n)};s.forEach(d);for(let e=1;e<16;e++)for(let t=1;t<16;t++)d([o+(i-o)*e/16,a+(r-a)*t/16]);return l}function ae(e){if(!Z(e.floorAnchor))return null;const t=e.roomsValidated?e.rooms:e.rooms.filter(ne),n=e.preferredRoomId&&t.find(t=>t.id===e.preferredRoomId)||null;let o=null;return"device"===e.kind?(n&&oe(e.floorAnchor,n)&&(o=n),o||(o=t.filter(t=>oe(e.floorAnchor,t)).sort((e,t)=>te(e)-te(t)||((e,t)=>et?1:0)(e.id,t.id))[0]||null)):o=n,o?{id:o.id,area:te(o),safePoint:e.roomsValidated&&o.safePoint?[o.safePoint[0],o.safePoint[1]]:ie(o)}:null}function re(t,o,i,a=e,r=[0,0]){if(!Z(t)||!Z(o)||o[0]<0||o[1]<0||!Number.isFinite(i)||!Z(r))throw new Error("invalid isometric overlay footprint");return[[t[0]-o[0],t[1]-o[1]],[t[0]+o[0],t[1]-o[1]],[t[0]+o[0],t[1]+o[1]],[t[0]-o[0],t[1]+o[1]]].map(e=>{const t=n(e,i,a);return[t[0]+r[0],t[1]+r[1]]})}function se(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function le(e,t,n,o){const i=se(e,t,n),a=se(e,t,o),r=se(n,o,e),s=se(n,o,t);return(i>K&&a<-K||i<-K&&a>K)&&(r>K&&s<-K||r<-K&&s>K)||(Math.abs(i)<=K&&X(n,e,t)<=K||Math.abs(a)<=K&&X(o,e,t)<=K||Math.abs(r)<=K&&X(e,n,o)<=K||Math.abs(s)<=K&&X(t,n,o)<=K)}function ce(e,t,n,o){return le(e,t,n,o)?0:Math.min(X(e,n,o),X(t,n,o),X(n,e,t),X(o,e,t))}const de=new WeakMap;function fe(e){if(!e.length)return null;let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const a of e){if(!Z(a))return null;t=Math.min(t,a[0]),n=Math.min(n,a[1]),o=Math.max(o,a[0]),i=Math.max(i,a[1])}return[t,n,o,i]}function ue(e,t){if(!t)return fe(e.outer);if(de.has(e))return de.get(e)??null;const n=fe(e.outer);return de.set(e,n),n}function he(e,t,n){return e[0]<=t[2]+n&&e[2]>=t[0]-n&&e[1]<=t[3]+n&&e[3]>=t[1]-n}function pe(e,t,n,o){return Math.min(t[0],n[0])<=e[2]+o&&Math.max(t[0],n[0])>=e[0]-o&&Math.min(t[1],n[1])<=e[3]+o&&Math.max(t[1],n[1])>=e[1]-o}function me(e,t,n,o,i){const a=ue(n,i);if(!a||!he(t,a,o))return!1;if(e.some(e=>function(e,t){return!!ee(e,t.outer)&&!(t.holes||[]).some(t=>ee(e,t))}(e,n)))return!0;if(n.outer.some(n=>n[0]>=t[0]&&n[0]<=t[2]&&n[1]>=t[1]&&n[1]<=t[3]&&ee(n,e)))return!0;for(const i of[n.outer,...n.holes||[]])for(let n=0;n"wall-side"===e.layer?0:"wall-top"===e.layer?1:2,Me=e=>{if("wall-side"===e.layer)return`${e.face.polygon}:${e.face.ring}:${e.face.edge}`;if("wall-top"===e.layer)return String(e.face.component);const t=e.surface;return`${t.sourceIndex}:${t.leaf??-1}:${t.kind}:${t.jamb??-1}:${t.edge??""}:${t.id}:${t.material}`};function be(e,t){const n=[...e.sides.map(e=>({layer:"wall-side",depth:e.depth,face:e})),...e.topFaces.map(e=>({layer:"wall-top",depth:e.depth,face:e})),...t.map(e=>({layer:"opening",depth:e.depth,surface:e}))];return n.sort((e,t)=>e.depth-t.depth||xe(e)-xe(t)||Me(e).localeCompare(Me(t))),Object.freeze(n)}const Se=Object.freeze({textLatinAdvance:.72,textWideAsciiAdvance:1,textWideAdvance:1.1,textSpaceAdvance:.4,textWidthSafety:1.08,deviceShellInset:.134375,deviceShellGap:.1,deviceSectionGap:.08,deviceBadgeMinWidth:.7875,deviceBadgeHeight:.7875,deviceBadgeInlinePadding:.28,deviceValueInlinePadding:.32,deviceAuxiliaryExtent:.7,deviceLqiFontSize:.38,deviceLqiTop:.734375,deviceLqiBelowBottomBadgeTop:1.571875,devicePadding:.08,roomNameLineHeight:1.25,roomAreaLinkWidth:1.1,roomMetricsTopGap:.15,roomMetricFontSize:.75,roomMetricLineHeight:1.25,roomMetricIconWidth:1.05,roomMetricInnerGap:.12,roomMetricRowGap:.55,roomMetricMinWidth:11,roomPadding:.4,openingLockHalfSize:.62,roomMetricTextCharacters:Object.freeze({temperature:10,humidity:8,lqi:6,light:24})});function $e(e){return[...String(e)].reduce((e,t)=>/\s/.test(t)?e+Se.textSpaceAdvance:/[MW@#%&]/.test(t)?e+Se.textWideAsciiAdvance:e+(t.codePointAt(0)>255?Se.textWideAdvance:Se.textLatinAdvance),0)*Se.textWidthSafety}function ke(e,t){return $e(e)*z(t||e)}function ze(e,t){return[Math.max(Math.abs(e.left),Math.abs(e.right))+t,Math.max(Math.abs(e.top),Math.abs(e.bottom))+t]}function Ie(e){if("opening-lock"===e.kind){const t=(Number.isFinite(e.size)&&e.size>0?e.size:0)*Se.openingLockHalfSize;return[t,t]}if("room-label"===e.kind){const t=Number.isFinite(e.font)&&e.font>0?e.font:0,n=v(e.room.settings?.name_scale),o=v(e.room.settings?.label_scale),i=($e(e.room.name||"")+(e.room.area?Se.roomAreaLinkWidth:0))*n,a=Se.roomNameLineHeight*n,r=[e.display.labelTemp?Se.roomMetricTextCharacters.temperature:0,e.display.labelHum?Se.roomMetricTextCharacters.humidity:0,e.display.labelLqi&&e.room.area?Se.roomMetricTextCharacters.lqi:0,e.display.labelLight?Se.roomMetricTextCharacters.light:0].filter(e=>e>0),s=Se.roomMetricFontSize*o,l=r.length?Math.max(Se.roomMetricMinWidth,r.reduce((e,t)=>e+Se.roomMetricIconWidth+Se.roomMetricInnerGap+t*Se.textLatinAdvance*Se.textWidthSafety,0)+(r.length-1)*Se.roomMetricRowGap)*s:0,c=r.length?s*Se.roomMetricLineHeight:0,d=ze({left:-Math.max(i,l)/2,right:Math.max(i,l)/2,top:-a/2,bottom:r.length?a/2+Se.roomMetricsTopGap+c:a/2},Se.roomPadding);return[d[0]*t,d[1]*t]}const t=Number.isFinite(e.core)&&e.core>0?e.core:0,n=e.presentation,o=null==n.valueText?1:Math.max(1,ke(n.valueText,n.valueFullText||n.valueText)+Se.deviceValueInlinePadding),i=[];n.valueBadge&&i.push(Math.max(Se.deviceBadgeMinWidth,ke(n.valueBadge.text,n.valueBadge.fullText||n.valueBadge.text)+Se.deviceBadgeInlinePadding));for(const e of x(n)){const t=e.text+e.suffix;i.push(Math.max(Se.deviceBadgeMinWidth,ke(t,t)+Se.deviceBadgeInlinePadding))}const a=n.valueBadge?.position||"right";let r;if(!i.length||"left"!==a&&"right"!==a)if(i.length){const e=i.reduce((e,t)=>e+t,0)+(i.length-1)*Se.deviceSectionGap,t=Math.max(o,e),n=1+Se.deviceShellGap+Se.deviceBadgeHeight;r="bottom"===a?{left:-t/2-Se.deviceShellInset,right:t/2+Se.deviceShellInset,top:-.5-Se.deviceShellInset,bottom:-.5+n+Se.deviceShellInset}:{left:-t/2-Se.deviceShellInset,right:t/2+Se.deviceShellInset,top:.5-n-Se.deviceShellInset,bottom:.5+Se.deviceShellInset}}else r={left:-.5-Se.deviceShellInset,right:-.5+o+Se.deviceShellInset,top:-.5-Se.deviceShellInset,bottom:.5+Se.deviceShellInset};else{const e=Math.max(...i),t=i.length*Se.deviceBadgeHeight+(i.length-1)*Se.deviceSectionGap,n=o+Se.deviceShellGap+e,s=Math.max(1,t);r="right"===a?{left:-.5-Se.deviceShellInset,right:-.5+n+Se.deviceShellInset,top:-s/2-Se.deviceShellInset,bottom:s/2+Se.deviceShellInset}:{left:.5-n-Se.deviceShellInset,right:.5+Se.deviceShellInset,top:-s/2-Se.deviceShellInset,bottom:s/2+Se.deviceShellInset}}const s=Se.deviceAuxiliaryExtent;if(r.left=Math.min(r.left,-s),r.right=Math.max(r.right,s),r.top=Math.min(r.top,-s),r.bottom=Math.max(r.bottom,s),n.pulse.animated){const e=Math.max(1,n.pulse.diameterScale)/2;r.left=Math.min(r.left,-e),r.right=Math.max(r.right,e),r.top=Math.min(r.top,-e),r.bottom=Math.max(r.bottom,e)}if(null!=n.lqiText){const e="bottom"===n.valueBadge?.position?Se.deviceLqiBelowBottomBadgeTop:Se.deviceLqiTop,t=$e(n.lqiText)*Se.deviceLqiFontSize/2;r.left=Math.min(r.left,-t),r.right=Math.max(r.right,t),r.bottom=Math.max(r.bottom,e+Se.deviceLqiFontSize)}const l=ze(r,Se.devicePadding);return[l[0]*t,l[1]*t]}function Pe(e,t){return e.flatMap((e,n)=>e.orphanReason?[]:[{id:String(e.id||n),sourceIndex:n,type:e.type,x:e.rx,y:e.ry,angle:Number(e.angle)||0,length:e.rlen>0?e.rlen:.9*t,flipH:!!e.flip_h,flipV:!!e.flip_v}])}function Ce(e){return{id:e.id,x:e.x,y:e.y,w:e.w,h:e.h,poly:e.poly,wall_ids:e.wall_ids}}function je(e,t){const n=e?.partitionHost;if(!n)return null;const o="gate"===t.type?!t.flipV:t.flipV;return{sourceIndex:t.sourceIndex,hostId:n.host.id,t:n.t,depth:n.depth,face:p(n,o)}}function Ne(n,o=H){const i=Pe(n.openings,n.coordinateScale),r=i.map(e=>je(n.openings[e.sourceIndex],e)),p=a(t,n.cellCm),m=a(s,n.cellCm),g=a(l,n.cellCm);return{key:`${n.space.id}|${function(e){let t=2166136261;const n=e=>{if("number"!=typeof e)if("string"!=typeof e)if("boolean"!=typeof e)if(Array.isArray(e)){t=R(t,e.length);for(const t of e)n(t)}else{if(e&&"object"==typeof e){const t=e;for(const e of Object.keys(t).sort())n(e),n(t[e]);return}t=R(t,-1)}else t=R(t,e?1:0);else for(const n of e)t=R(t,n.codePointAt(0)||0);else t=R(t,e)};return n(e),t.toString(36)}({rooms:n.space.rooms.map(Ce),walls:n.walls,openCuts:n.openCuts,openings:i,openingHosts:r,openingGeometryPolicy:o,partitions:n.space.partitions,columns:n.space.wall_columns,cellCm:n.cellCm,gridPitch:n.gridPitch,wallKeyPitch:n.wallKeyPitch,camera:e,wallHeight:p,raisedHeight:g,floorEdgeHeight:m,algorithm:4})}`,build:()=>{n.onBuild();const a=c(n.space,n.cellCm,n.gridPitch,2e-4*n.gridPitch,n.partitionCuts()).all,s=n.roomOpenings(),l=n.walls.length||a.length?d(n.space.rooms,n.walls,n.openCuts,s,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale,a):null;if(l&&("failed-core"===l.status||"not-applicable"===l.status))throw new Error("wall boolean geometry failed");const m=l?.paperGeom??f(n.space.rooms,n.walls,n.openCuts,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale);if(!m)throw new Error("floor boolean geometry failed");const g=l?.openingIndex||u(n.space.rooms,n.walls,n.openCuts,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale),w=i.map((e,i)=>{const a=r[i],s="gate"===e.type?!e.flipV:e.flipV,l=a?a.face:n.walls.length||"gate"===e.type?h(g,{x:e.x,y:e.y,angle:e.angle,length:e.length,flip_v:s}):{ox:0,oy:0,cm:0,side:-1};return function(e,n=t,o=H){const i=e.face.cm??0;if(!F([e.x,e.y,e.angle,e.length,e.face.ox,e.face.oy,i,n])||!(e.length>0)||!(n>0)||-1!==e.face.side&&1!==e.face.side||i<0)throw new Error("invalid isometric opening input");const a=e.length/2,r=e.angle*Math.PI/180,s=T(Math.cos(r),Math.sin(r)),l=T(-Math.sin(r),Math.cos(r)),c=T(e.x,e.y),d=T(e.x-s[0]*a,e.y-s[1]*a),f=T(e.x+s[0]*a,e.y+s[1]*a),u=T(e.face.ox,e.face.oy),h=T(d[0]+u[0],d[1]+u[1]),p=T(f[0]+u[0],f[1]+u[1]),m=T(d[0]-u[0],d[1]-u[1]),g=T(f[0]-u[0],f[1]-u[1]),w=Object.freeze({center:c,tangent:s,normal:l,start:d,end:f}),y=Object.freeze({side:e.face.side,cm:i,depth:2*Math.hypot(e.face.ox,e.face.oy),offset:u,selectedStart:h,selectedEnd:p,oppositeStart:m,oppositeEnd:g}),v="passage"===e.type?[]:[Object.freeze({jamb:0,center:d,selected:h,opposite:m}),Object.freeze({jamb:1,center:f,selected:p,opposite:g})];let x;if("passage"===e.type)x=[];else if("gate"===e.type){const t=e.face.side*o.gateTurnDeg;x=[E(e,0,[-a,0],[a,0],t,0,n*o.gateTopRatio),E(e,1,[a,0],[-a,0],-t,0,n*o.gateTopRatio)]}else x="window"===e.type?[E(e,0,[-a,0],[a,0],-90,n*o.windowBottomRatio,n*o.windowTopRatio),E(e,1,[a,0],[-a,0],90,n*o.windowBottomRatio,n*o.windowTopRatio)]:[E(e,0,[-a,0],[e.length,0],-90,0,n*o.doorTopRatio)];return Object.freeze({id:e.id,sourceIndex:e.sourceIndex,type:e.type,wallHeight:n,leafThickness:n*o.leafThicknessRatio,frameThickness:n*o.frameThicknessRatio,axis:w,face:y,reveals:Object.freeze(v),leaves:Object.freeze(x.map(e=>Object.freeze({...e,hinge:T(e.hinge[0],e.hinge[1]),closedVector:T(e.closedVector[0],e.closedVector[1]),quarterVector:T(e.quarterVector[0],e.quarterVector[1])})))})}({...e,face:l},p,o)}),y=Object.freeze(w);return{walls:l?.components.flatMap(e=>e.geom)||[],floor:m,openings:y,openingSurfaces:Object.freeze(y.flatMap(t=>function(t,n=e){if("passage"===t.type)return Object.freeze([]);const o=[];if(t.face.depth>1e-9)for(const e of t.reveals)o.push(_("jamb-reveal","reveal",e.selected,e.opposite,0,t.wallHeight,n,{jamb:e.jamb}));if("window"!==t.type||!t.leaves.length)return Object.freeze(o.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||(e.jamb??0)-(t.jamb??0)));const i=Math.min(...t.leaves.map(e=>e.bottom)),a=Math.max(...t.leaves.map(e=>e.top)),r=Math.min(t.frameThickness,Math.hypot(t.axis.end[0]-t.axis.start[0],t.axis.end[1]-t.axis.start[1])/4,(a-i)/4),s=L(t.axis.start,G(t.axis.tangent,r)),l=V(t.axis.end,G(t.axis.tangent,r)),c=t.face.depth>1e-9?[t.face.offset,T(-t.face.offset[0],-t.face.offset[1])]:[t.face.offset];for(const e of c){const c=L(t.axis.start,e),d=L(t.axis.end,e),f=L(s,e),u=L(l,e);o.push(_("window-frame-side","light-frame",c,f,i,a,n,{jamb:0}),_("window-frame-side","light-frame",u,d,i,a,n,{jamb:1}),_("window-frame-top","light-frame",f,u,Math.max(i,a-r),a,n))}return t.face.depth>1e-9&&o.push(D("window-sill","light-sill",[{point:t.face.selectedStart,z:i},{point:t.face.selectedEnd,z:i},{point:t.face.oppositeEnd,z:i},{point:t.face.oppositeStart,z:i}],n)),Object.freeze(o.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||(e.jamb??0)-(t.jamb??0)))}(t).map(e=>Object.freeze({...e,id:t.id,sourceIndex:t.sourceIndex,type:t.type}))))}}}}const Oe=e=>Array.isArray(e)?e:[];function Ae(e,t){const o=e=>Oe(e).flatMap(e=>Array.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1])?[n([Number(e[0]),Number(e[1])],t)]:[]);return Oe(e).flatMap(e=>{const t=Oe(e);if(!t.length)return[];const n=o(t[0]);if(n.length<3)return[];return[{outer:n,holes:t.slice(1).map(o).filter(e=>e.length>=3)}]})}function Be(o){const i=a(t,o.cellCm),r=a(s,o.cellCm),c=a(l,o.cellCm),d=S(o.cache,o.source.key);let f=d.hit?d.value:void 0;if(!f){const a=o.source.build(),s=function(o,i=e,a=t){if(!Number.isFinite(a)||a<0)throw new Error("invalid wall height");const r=[],s=[],l=[],c=[];let d=0;for(let e=0;e<(o||[]).length;e++){const t=o[e],f=[];let u=-1/0;for(let o=0;o<(t||[]).length;o++){const s=N(t[o],o>0);if(s.length<3||Math.abs(j(s))<1e-9)continue;const h=O(s,i,a);r.push(h),f.push(h),u=Math.max(u,...s.map(e=>n(e,a,i)[1])),d+=s.length;for(let t=0;te.depth-t.depth||e.polygon-t.polygon||e.ring-t.ring||e.edge-t.edge),s.sort((e,t)=>e.depth-t.depth||e.component-t.component),{topPath:r.join(" "),topFaces:s,sides:l,contactPath:c.join(" "),edgeCount:d}}(a.walls,e,i),l=Ae(a.walls,i);f={geometry:s,floor:B(a.floor,r),wallSilhouettes:Object.freeze([...l,...s.sides.map(e=>({outer:e.points}))]),openings:a.openings,openingSurfaces:a.openingSurfaces},$(o.cache,o.source.key,f,8)}const u=function(e){let t=1/0,n=1/0,o=-1/0,i=-1/0;const a=(e,a=0)=>{t=Math.min(t,e[0]-a),n=Math.min(n,e[1]-a),o=Math.max(o,e[0]+a),i=Math.max(i,e[1]+a)};for(const t of e)if("passage"!==t.type){a(t.axis.start),a(t.axis.end),a(t.face.selectedStart),a(t.face.selectedEnd),a(t.face.oppositeStart),a(t.face.oppositeEnd);for(const e of t.leaves){const n=Math.hypot(e.closedVector[0],e.closedVector[1])+t.leafThickness/2;a(e.hinge,n)}}return F([t,n,o,i])?{x:t,y:n,w:o-t,h:i-n}:null}(f.openings),h=u?Re(o.liveFrame,u):o.liveFrame,p=k({rect:h,wallHeight:i,openingHeight:i,floorDepth:r,raisedHeight:c});return{key:o.source.key,...f,frame:p}}const Re=(e,t)=>{const n=Math.min(e.x,t.x),o=Math.min(e.y,t.y);return{x:n,y:o,w:Math.max(e.x+e.w,t.x+t.w)-n,h:Math.max(e.y+e.h,t.y+t.h)-o}},He=e=>{if(!e.length||!e.every(e=>Number.isFinite(e[0])&&Number.isFinite(e[1])))return null;const t=e.map(e=>e[0]),n=e.map(e=>e[1]),o=Math.min(...t),i=Math.min(...n);return{x:o,y:i,w:Math.max(...t)-o,h:Math.max(...n)-i}},Fe=(e,t)=>{const n=e.placement,o=t?n.visualScene:n.raisedScene,[i,a]=e.screenHalfSize,r=t?n.footprint:n.footprint.map(e=>[e[0]-n.nudgeScene[0],e[1]-n.nudgeScene[1]]);return[n.floorScene,...r,[o[0]-i,o[1]-a],[o[0]+i,o[1]-a],[o[0]+i,o[1]+a],[o[0]-i,o[1]+a]]},Te=(e,t)=>void 0===t?e:e.filter(e=>e.placement.owner?.id===t);function Le(e,t){return e?He(Te(e.entries,t).flatMap(e=>Fe(e,!0))):null}function Ve(e){const t=Te(e.entries,e.ownerId),n=He(t.flatMap(e=>Fe(e,!1))),o=n?Re(e.baseBounds,n):e.baseBounds,i=e.targetView(o);if(!(i&&i.w>0&&i.h>0&&[i.x,i.y,i.w,i.h].every(Number.isFinite)))return null;const a=e.stageSize;if(!(n&&a&&a.width>0&&a.height>0))return{bounds:o,view:i};const r=e=>Math.max(e.w/a.width,e.h/a.height),s=t=>{const o=48*t,i={x:n.x-o,y:n.y-o,w:n.w+2*o,h:n.h+2*o},a=Re(e.baseBounds,i),r=e.targetView(a);return r&&[r.x,r.y,r.w,r.h].every(Number.isFinite)&&r.w>0&&r.h>0?{bounds:a,view:r}:null};let l=0,c=Math.max(r(i),Number.EPSILON),d=s(c);for(let e=0;d&&r(d.view)>c*(1+1e-10)&&e<24;e++)l=c,c*=2,d=s(c);if(!d)return null;for(let e=0;e<40;e++){const e=(l+c)/2,t=s(e);if(!t)return null;r(t.view)<=e?(c=e,d=t):l=e}return d}const Ge=new WeakMap,We=2048,Ee=new WeakMap,qe=new WeakMap,De=new WeakMap;function _e(e,t){if(e.size!==t.size)return!1;for(const[n,o]of t)if(e.get(n)!==o)return!1;return!0}function Ue(e){const t=Ge.get(e.rooms);if(t)return t;const n=e.rooms.flatMap((e,t)=>{const n=w(e);return n&&n.length>=3?[{room:e,index:t,poly:n}]:[]}),o=Object.freeze(n.map(({room:e,index:t,poly:o})=>{const i=y(o,n.filter(e=>e.index!==t).map(e=>e.poly)),a={id:e.id||`room-index-${t}`,outer:o.map(e=>[e[0],e[1]]),holes:i.map(e=>e.map(e=>[e[0],e[1]]))};return{room:e,overlayRoom:{...a,safePoint:ie(a)||void 0}}}));return Ge.set(e.rooms,o),o}function Ke(o){const s=o.stageSize&&o.stageSize.width>0&&o.stageSize.height>0?Math.max(o.view.w/o.stageSize.width,o.view.h/o.stageSize.height):Math.max(o.view.w,o.view.h)/1e3,l=Ue(o.space),c=l.map(e=>e.overlayRoom),d=a(t,o.cellCm),f=a(i,o.cellCm),u=new Map,h=new Map,p=new Map,m=[];let g=Ee.get(o.wallSilhouettes);g||(g=new Map,Ee.set(o.wallSilhouettes,g));let w=qe.get(l);w||(w=new Map,qe.set(l,w));const y=o.iconPct*r(o.space)*o.kioskIconScale/100,v=o.deviceBasePct*r(o.space)*o.kioskIconScale/100,x=(a,r,l,u,h,p=!1)=>{const m=`${!1===o.resolveCollisions?"fit":"live"}\0${a}\0${r}`,y=[l[0],l[1],u[0],u[1],h||"",d,f,o.layers.shadows?1:0,p?1:0].join("|"),v=`${y}|${s}`,x=S(g,m);if(x.hit&&x.value.signature===v)return x.value.placement;if(x.hit&&x.value.shapeSignature===y&&s<=x.value.unitsPerPixel){const e=x.value.placement,t=e.nudgeDistanceCss*x.value.unitsPerPixel/s;if(!e.nearWallBefore||e.cleared&&t<=48)return e}const M=`${a}\0${r}`,b=[l[0],l[1],h||""].join("|"),k=S(w,M),z=k.hit&&k.value.signature===b?k.value.owner:ae({kind:a,floorAnchor:l,rooms:c,roomsValidated:!0,preferredRoomId:h});k.hit&&k.value.signature===b||$(w,M,{signature:b,owner:z},We);const I=function(o){const a=o.camera||e,r=o.wallHeight??t,s=o.visualOffset??i,l=o.sceneUnitsPerCssPixel??1,c=o.safetyGapCssPx??4,d=o.maxNudgeCssPx??48;if(!Z(o.floorAnchor)||!Z(o.footprintHalfSize)||o.footprintHalfSize[0]<0||o.footprintHalfSize[1]<0||!Number.isFinite(r)||r<0||!Number.isFinite(s)||s<0||!Number.isFinite(l)||l<=0||!Number.isFinite(c)||c<0||!Number.isFinite(d)||d<0)throw new Error("invalid isometric overlay input");const f=[o.floorAnchor[0],o.floorAnchor[1]],u=n(f,0,a),h=(p=o.kind,!o.showBorders||"device"!==p&&"room-label"!==p&&"opening-lock"!==p?"floor":"raised");var p;if("floor"===h)return{plane:h,owner:null,floorAnchor:f,floorScene:u,raisedScene:u,visualScene:u,footprint:[],nudgeScene:[0,0],nudgeCss:[0,0],nudgeDistanceCss:0,nudged:!1,nearWallBefore:!1,nearWallAfter:!1,cleared:!0,capped:!1,grounding:{center:u,visible:!1},tether:ye(u,u,!1),status:"ok",reason:null};const m=r+s,g=n(f,m,a),w=o.ownerAlreadyResolved?o.resolvedOwner??null:ae(o),y=o.wallGeometryValidated??o.wallSilhouettes.every(ge),v=c*l,x=re(f,o.footprintHalfSize,m,a),M=e=>{const t=fe(e);return!!t&&o.wallSilhouettes.some(n=>me(e,t,n,v,!0===o.wallGeometryValidated))},b=!y||M(x);let S=0,$=[0,0],k=null,z=!1,I=y?"ok":"degraded",P=y?null:"invalid-wall-geometry";if(y&&b)if(w)if(w.safePoint){const e=o.rooms.find(e=>e.id===w.id)||null,t=n(w.safePoint,m,a),i=t[0]-g[0],r=t[1]-g[1],s=Math.hypot(i,r);if(s<=K)I="degraded",P="invalid-safe-point";else{const t=i/s,n=r/s,a=Math.min(d,s/l),c=a*l/s,u=[f[0]+(w.safePoint[0]-f[0])*c,f[1]+(w.safePoint[1]-f[1])*c],h=[t*a*l,n*a*l],p=fe([...x,...x.map(e=>[e[0]+h[0],e[1]+h[1]])]),m=p?o.wallSilhouettes.filter(e=>{const t=ue(e,!0===o.wallGeometryValidated);return!!t&&he(p,t,v)}):o.wallSilhouettes,g=!!e&&we(f,u,e),y=e=>{const i=[t*e*l,n*e*l],a=x.map(e=>[e[0]+i[0],e[1]+i[1]]),r=fe(a);return!!r&&m.some(e=>me(a,r,e,v,!0===o.wallGeometryValidated))},M=o.nudgeHintCss;if(Number.isFinite(M)&&M>=0&&M<=a){const t=M*l/s,n=[f[0]+(w.safePoint[0]-f[0])*t,f[1]+(w.safePoint[1]-f[1])*t];(g||e&&we(f,n,e))&&!y(M)&&(S=M,k=!1)}if(null===k){let t=null,n=0,o=!1;const i=Math.ceil(a);for(let r=1;r<=i;r++){const i=Math.min(a,r),c=i*l/s,d=[f[0]+(w.safePoint[0]-f[0])*c,f[1]+(w.safePoint[1]-f[1])*c];if(!(g||e&&we(f,d,e))){o=!0;break}if(!y(i)){t=i;break}n=i}if(null!==t){let e=n,o=t;for(let t=0;t<14;t++){const t=(e+o)/2;y(t)?e=t:o=t}S=o}else S=n,z=!0,I="degraded",P=o?"owner-boundary":"nudge-cap"}$=[t*S*l,n*S*l]}}else I="degraded",P="invalid-safe-point";else I="degraded",P="missing-owner";const C=[g[0]+$[0],g[1]+$[1]],j=re(f,o.footprintHalfSize,m,a,$),N=!y||(k??M(j)),O=S>K,A=O||b||N||!!o.hovered||!!o.focused||!!o.selected;return{plane:h,owner:w,floorAnchor:f,floorScene:u,raisedScene:g,visualScene:C,footprint:j,nudgeScene:$,nudgeCss:[$[0]/l,$[1]/l],nudgeDistanceCss:S,nudged:O,nearWallBefore:b,nearWallAfter:N,cleared:!N,capped:z,grounding:{center:u,visible:!1!==o.filtersSupported},tether:ye(u,C,A),status:I,reason:P}}({kind:a,floorAnchor:l,rooms:c,roomsValidated:!0,preferredRoomId:h,ownerAlreadyResolved:!0,resolvedOwner:z,nudgeHintCss:x.hit&&x.value.shapeSignature===y?x.value.placement.nudgeDistanceCss*x.value.unitsPerPixel/s:void 0,showBorders:!0,wallSilhouettes:!1===o.resolveCollisions?[]:o.wallSilhouettes,wallGeometryValidated:!0,footprintHalfSize:u,wallHeight:d,visualOffset:f,sceneUnitsPerCssPixel:s,filtersSupported:o.layers.shadows,hovered:!0,selected:p});return $(g,m,{signature:v,shapeSignature:y,unitsPerPixel:s,placement:I},We),I};for(const e of o.devices){const t=o.positionOf(e),n=o.presentationOf(e,o.showLqi),i=v*n.scale,a=Ie({kind:"device",core:i,presentation:n}),r=e.marker?.room_id||l.find(t=>!!e.area&&t.room.area===e.area)?.overlayRoom.id||null,s=x("device",e.id,[t.x,t.y],a,r,o.selectedDeviceId===e.id);u.set(e.id,s),m.push({id:e.id,kind:"device",placement:s,groundRadius:Math.max(.32*i,2),screenHalfSize:a})}for(const{room:e,overlayRoom:t}of l){if(!o.display.showNames||!e.name)continue;const n=o.labelPositionOf(e,o.space.id),i=.5*y*(o.labelScaleOf(e)*o.kioskFontScale*o.display.cardFontScale),a=Ie({kind:"room-label",font:i,room:e,display:o.display}),r=x("room-label",t.id,[n.x,n.y],a,t.id,o.focusedRoomId===e.id);h.set(e,r),m.push({id:t.id,kind:"room-label",placement:r,groundRadius:Math.max(.75*i,2),screenHalfSize:a})}const M=o.openings.filter(e=>!e.orphanReason&&("door"===e.type||"gate"===e.type)&&"string"==typeof e.lock&&!!e.lock&&o.openingEntityAvailable(e.lock));if(M.length){const e=o.openingWallIndex();for(const t of M){const n=Je(t,e,o.cellCm),i=n.floorAnchor,a=.62*y,r=Ie({kind:"opening-lock",size:a}),s=x("opening-lock",String(t.id),i,r,n.preferredRoomId,o.selectedOpeningId===t.id);p.set(String(t.id),s),m.push({id:String(t.id),kind:"opening-lock",placement:s,groundRadius:Math.max(.28*a,2),screenHalfSize:r})}}const b={devices:u,rooms:h,locks:p,entries:Object.freeze(m)},k=!1===o.resolveCollisions?"fit":"live";let z=De.get(o.wallSilhouettes);z||(z=new Map,De.set(o.wallSilhouettes,z));const I=z.get(k);return I&&function(e,t){return e.length===t.length&&t.every((t,n)=>{const o=e[n];return o.id===t.id&&o.kind===t.kind&&o.placement===t.placement&&o.groundRadius===t.groundRadius&&o.screenHalfSize[0]===t.screenHalfSize[0]&&o.screenHalfSize[1]===t.screenHalfSize[1]})}(I.entries,b.entries)&&_e(I.devices,b.devices)&&_e(I.rooms,b.rooms)&&_e(I.locks,b.locks)?I:(z.set(k,b),b)}function Ze(e,t,n){return Je(e,t,n).floorAnchor}function Je(e,t,n){const o=!e.flip_v,i="gate"===e.type?e.partitionHost?p(e.partitionHost,o):h(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen,flip_v:o}):null,[a,r]=m({x:e.rx,y:e.ry,angle:e.angle,flipV:!!e.flip_v,gateFace:i},n);if(e.partitionHost)return{floorAnchor:a,preferredRoomId:null};const s=g(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen},!0),l=r?"negative":"positive";return{floorAnchor:a,preferredRoomId:s[l]?.roomId||null}}function Qe(e){let t=!1;try{t="undefined"!=typeof CSS&&"function"==typeof CSS.supports&&CSS.supports("filter","blur(1px)")}catch{t=!1}let n=!1;try{n="function"==typeof matchMedia&&matchMedia("(forced-colors: active)").matches}catch{n=!0}return function(e){const t=!!e.showBorders;return{structural:t,panels:t&&!e.hideOpenings,shadows:t&&e.filtersSupported&&!e.forcedColors,materialNuance:t&&e.filtersSupported&&!e.forcedColors,floorSymbols:!e.hideOpenings&&!t}}({showBorders:e.showBorders,hideOpenings:e.hideOpenings,filtersSupported:t,forcedColors:n})}function Xe(e,t,n,o){if(!e.panels||!t)return[];return t.openings.flatMap(e=>{const t=n[e.sourceIndex];return t?U(e,o(t)):[]}).sort((e,t)=>e.depth-t.depth||e.sourceIndex-t.sourceIndex||e.leaf-t.leaf)}function Ye(e){const t=Qe(e.display),n=t.panels?Xe(t,e.scene,e.openings,e.amountOf):[],o=e.overlays(t),i=t=>({layers:t,panels:n,overlays:o,underlay:at(t,e.scene?.floor,e.cellCm),shadows:rt(t,n,e.scene?.geometry,e.cellCm),walls:st(e.projection,t,e.scene,n,e.cellCm),grounds:ot(o,t,e.cellCm),raised:it(o)});try{return i(t)}catch(e){if(!t.shadows&&!t.materialNuance)throw e;return i({...t,shadows:!1,materialNuance:!1})}}const et=()=>b``;function tt(e){return`translate(${a(4,e)} ${a(8,e)})`}function nt(e,t,n){const o=I(n);return b`
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{dt as e,du as t,a$ as n,dv as o,dw as i,m as a,dx as r,dy as s,dz as l,dA as c,a4 as d,dB as f,ah as u,bT as h,bS as p,dC as m,ai as g,P as w,dD as y,cM as v,dE as x,A as M,w as b,dF as S,dG as $,dH as k,dI as z,dJ as I}from"./houseplan-card-6Hf8VPda.js";import{i as P}from"./guard-loEtwhSf.js";const C=e=>`${Number(e[0].toFixed(4))} ${Number(e[1].toFixed(4))}`;function j(e){let t=0;for(let n=0;nArray.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1])).map(e=>[Number(e[0]),Number(e[1])]),n=t[t.length-1];return t.length>1&&t[0][0]===n[0]&&t[0][1]===n[1]&&t.pop(),t}(e);if(n.length<3)return[];const o=!t;return j(n)>0===o?n:[...n].reverse()}function O(e,t,o){return e.length?`M ${e.map(e=>C(n(e,o,t))).join(" L ")} Z`:""}function A(e,t,n){const o=t[1]-e[1],i=-(t[0]-e[0]),a=n.rotDeg*Math.PI/180;return o*Math.sin(a)+i*Math.cos(a)}function B(t,o,i=e){if(!Number.isFinite(o)||o<0)throw new Error("invalid floor edge height");const a=(t||[]).map(e=>(e||[]).map((e,t)=>function(e,t){const n=N(e,t);if(!n.length)return n;let o=0;for(let e=1;e0)).filter(e=>e.length>=3&&Math.abs(j(e))>=1e-9)).filter(e=>e.length&&j(e[0])>0);a.sort((e,t)=>{const n=e[0][0],o=t[0][0];return n[0]-o[0]||n[1]-o[1]||Math.abs(j(t[0]))-Math.abs(j(e[0]))});const r=[],s=[];let l=0;for(let e=0;ee.depth-t.depth||e.component-t.component||e.edge-t.edge),{footprintPath:r.join(" "),sides:s,componentCount:a.length,edgeCount:l}}function H(e,t){return e^=Math.round(64*(Number.isFinite(t)?t:0)),Math.imul(e,16777619)>>>0}const R=Object.freeze({revision:1,leafThicknessRatio:.04,frameThicknessRatio:.055,gateTurnDeg:10,gateTopRatio:.88,windowBottomRatio:.27,windowTopRatio:.78,doorTopRatio:.92});R.leafThicknessRatio,R.frameThicknessRatio;const F=e=>e.every(Number.isFinite);function T(e,t){return Object.freeze([Object.is(e,-0)?0:e,Object.is(t,-0)?0:t])}function L(e,t){return[e[0]+t[0],e[1]+t[1]]}function V(e,t){return[e[0]-t[0],e[1]-t[1]]}function G(e,t){return[e[0]*t,e[1]*t]}function W(e,t,n,o){const i=e[0]*n,a=e[1]*o,r=t*Math.PI/180;return[i*Math.cos(r)-a*Math.sin(r),i*Math.sin(r)+a*Math.cos(r)]}function E(e,t,n,i,a,r,s){const l=e.flipH?-1:1,c="gate"===e.type?1:e.flipV?-1:1,d=o(e.type,e.flipV,e.angle,e.face);return{leaf:t,hinge:L([e.x+d.ox,e.y+d.oy],W(n,e.angle,l,c)),closedVector:W(i,e.angle,l,c),quarterVector:W([-i[1],i[0]],e.angle,l,c),turnDeg:a,bottom:r,top:s}}const q=e=>`${Number(e[0].toFixed(4))} ${Number(e[1].toFixed(4))}`;function D(e,t,o,i,a={}){const r=o.map(e=>n(e.point,e.z,i));return Object.freeze({kind:e,material:t,d:`M ${r.map(q).join(" L ")} Z`,depth:Math.max(...r.map(e=>e[1])),...a})}function _(e,t,n,o,i,a,r,s={}){return D(e,t,[{point:n,z:i},{point:o,z:i},{point:o,z:a},{point:n,z:a}],r,s)}function U(t,o,i=e){const a=Math.max(0,Math.min(1,Number.isFinite(o)?o:0));return t.leaves.map(e=>{const o=function(e,t){const n=e.turnDeg*t*Math.PI/180;return[e.hinge[0]+e.closedVector[0]*Math.cos(n)+e.quarterVector[0]*Math.sin(n),e.hinge[1]+e.closedVector[1]*Math.cos(n)+e.quarterVector[1]*Math.sin(n)]}(e,a),r=n(e.hinge,e.bottom,i),s=n(o,e.bottom,i),l=n(o,e.top,i),c=n(e.hinge,e.top,i),d="window"===t.type?"light-window":"matte-leaf",f="window"===t.type?Object.freeze([_("window-insert","light-window",e.hinge,o,e.bottom,e.top,i)]):function(e,t,n,o){const i=V(t,e.hinge),a=Math.hypot(i[0],i[1]);if(!(a>1e-9&&n>0))return Object.freeze([]);const r=T(-i[1]*n/(2*a),i[0]*n/(2*a)),s=L(e.hinge,r),l=L(t,r),c=V(e.hinge,r),d=V(t,r),f=[_("leaf-back","matte-leaf",d,c,e.bottom,e.top,o),_("leaf-front","matte-leaf",s,l,e.bottom,e.top,o),_("leaf-edge","matte-leaf",c,s,e.bottom,e.top,o,{edge:"hinge"}),_("leaf-edge","matte-leaf",l,d,e.bottom,e.top,o,{edge:"tip"}),D("leaf-top","matte-leaf",[{point:s,z:e.top},{point:c,z:e.top},{point:d,z:e.top},{point:l,z:e.top}],o)];return Object.freeze(f.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||String(e.edge||"").localeCompare(String(t.edge||""))))}(e,o,t.leafThickness,i);return Object.freeze({id:t.id,sourceIndex:t.sourceIndex,type:t.type,leaf:e.leaf,d:`M ${q(r)} L ${q(s)} L ${q(l)} L ${q(c)} Z`,shadowD:`M ${q(n(e.hinge,0,i))} L ${q(n(o,0,i))}`,depth:Math.max(r[1],s[1]),material:d,thickness:"window"===t.type?0:t.leafThickness,surfaces:f})})}const K=1e-9,Z=e=>e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function J(e){let t=0;for(let n=0;n=3&&e.every(Z)&&Math.abs(J(e))>K}function X(e,t,n){const o=n[0]-t[0],i=n[1]-t[1],a=o*o+i*i,r=a?Math.max(0,Math.min(1,((e[0]-t[0])*o+(e[1]-t[1])*i)/a)):0;return Math.hypot(e[0]-t[0]-r*o,e[1]-t[1]-r*i)}function Y(e,t,n=1e-7){for(let o=0;oe[1]!=r[1]>e[1]&&e[0]<(r[0]-a[0])*(e[1]-a[1])/(r[1]-a[1])+a[0]&&(n=!n)}return n}function te(e){return Math.max(0,Math.abs(J(e.outer))-(e.holes||[]).reduce((e,t)=>e+Math.abs(J(t)),0))}function ne(e){return!!e.id&&Q(e.outer)&&(e.holes||[]).every(Q)&&te(e)>K}function oe(e,t){if(!ne(t)||Y(e,t.outer)||!ee(e,t.outer))return!1;for(const n of t.holes||[])if(Y(e,n)||ee(e,n))return!1;return!0}function ie(e){if(!ne(e))return null;if(e.safePoint&&oe(e.safePoint,e))return[e.safePoint[0],e.safePoint[1]];const t=e.outer.map(e=>e[0]),n=e.outer.map(e=>e[1]),o=Math.min(...t),i=Math.max(...t),a=Math.min(...n),r=Math.max(...n),s=[[(o+i)/2,(a+r)/2],[t.reduce((e,t)=>e+t,0)/t.length,n.reduce((e,t)=>e+t,0)/n.length]];for(let t=0;t{if(!oe(t,e))return;const n=function(e,t){let n=1/0;for(const o of[t.outer,...t.holes||[]])for(let t=0;tc+K&&(l=t,c=n)};s.forEach(d);for(let e=1;e<16;e++)for(let t=1;t<16;t++)d([o+(i-o)*e/16,a+(r-a)*t/16]);return l}function ae(e){if(!Z(e.floorAnchor))return null;const t=e.roomsValidated?e.rooms:e.rooms.filter(ne),n=e.preferredRoomId&&t.find(t=>t.id===e.preferredRoomId)||null;let o=null;return"device"===e.kind?(n&&oe(e.floorAnchor,n)&&(o=n),o||(o=t.filter(t=>oe(e.floorAnchor,t)).sort((e,t)=>te(e)-te(t)||((e,t)=>et?1:0)(e.id,t.id))[0]||null)):o=n,o?{id:o.id,area:te(o),safePoint:e.roomsValidated&&o.safePoint?[o.safePoint[0],o.safePoint[1]]:ie(o)}:null}function re(t,o,i,a=e,r=[0,0]){if(!Z(t)||!Z(o)||o[0]<0||o[1]<0||!Number.isFinite(i)||!Z(r))throw new Error("invalid isometric overlay footprint");return[[t[0]-o[0],t[1]-o[1]],[t[0]+o[0],t[1]-o[1]],[t[0]+o[0],t[1]+o[1]],[t[0]-o[0],t[1]+o[1]]].map(e=>{const t=n(e,i,a);return[t[0]+r[0],t[1]+r[1]]})}function se(e,t,n){return(t[0]-e[0])*(n[1]-e[1])-(t[1]-e[1])*(n[0]-e[0])}function le(e,t,n,o){const i=se(e,t,n),a=se(e,t,o),r=se(n,o,e),s=se(n,o,t);return(i>K&&a<-K||i<-K&&a>K)&&(r>K&&s<-K||r<-K&&s>K)||(Math.abs(i)<=K&&X(n,e,t)<=K||Math.abs(a)<=K&&X(o,e,t)<=K||Math.abs(r)<=K&&X(e,n,o)<=K||Math.abs(s)<=K&&X(t,n,o)<=K)}function ce(e,t,n,o){return le(e,t,n,o)?0:Math.min(X(e,n,o),X(t,n,o),X(n,e,t),X(o,e,t))}const de=new WeakMap;function fe(e){if(!e.length)return null;let t=1/0,n=1/0,o=-1/0,i=-1/0;for(const a of e){if(!Z(a))return null;t=Math.min(t,a[0]),n=Math.min(n,a[1]),o=Math.max(o,a[0]),i=Math.max(i,a[1])}return[t,n,o,i]}function ue(e,t){if(!t)return fe(e.outer);if(de.has(e))return de.get(e)??null;const n=fe(e.outer);return de.set(e,n),n}function he(e,t,n){return e[0]<=t[2]+n&&e[2]>=t[0]-n&&e[1]<=t[3]+n&&e[3]>=t[1]-n}function pe(e,t,n,o){return Math.min(t[0],n[0])<=e[2]+o&&Math.max(t[0],n[0])>=e[0]-o&&Math.min(t[1],n[1])<=e[3]+o&&Math.max(t[1],n[1])>=e[1]-o}function me(e,t,n,o,i){const a=ue(n,i);if(!a||!he(t,a,o))return!1;if(e.some(e=>function(e,t){return!!ee(e,t.outer)&&!(t.holes||[]).some(t=>ee(e,t))}(e,n)))return!0;if(n.outer.some(n=>n[0]>=t[0]&&n[0]<=t[2]&&n[1]>=t[1]&&n[1]<=t[3]&&ee(n,e)))return!0;for(const i of[n.outer,...n.holes||[]])for(let n=0;n"wall-side"===e.layer?0:"wall-top"===e.layer?1:2,Me=e=>{if("wall-side"===e.layer)return`${e.face.polygon}:${e.face.ring}:${e.face.edge}`;if("wall-top"===e.layer)return String(e.face.component);const t=e.surface;return`${t.sourceIndex}:${t.leaf??-1}:${t.kind}:${t.jamb??-1}:${t.edge??""}:${t.id}:${t.material}`};function be(e,t){const n=[...e.sides.map(e=>({layer:"wall-side",depth:e.depth,face:e})),...e.topFaces.map(e=>({layer:"wall-top",depth:e.depth,face:e})),...t.map(e=>({layer:"opening",depth:e.depth,surface:e}))];return n.sort((e,t)=>e.depth-t.depth||xe(e)-xe(t)||Me(e).localeCompare(Me(t))),Object.freeze(n)}const Se=Object.freeze({textLatinAdvance:.72,textWideAsciiAdvance:1,textWideAdvance:1.1,textSpaceAdvance:.4,textWidthSafety:1.08,deviceShellInset:.134375,deviceShellGap:.1,deviceSectionGap:.08,deviceBadgeMinWidth:.7875,deviceBadgeHeight:.7875,deviceBadgeInlinePadding:.28,deviceValueInlinePadding:.32,deviceAuxiliaryExtent:.7,deviceLqiFontSize:.38,deviceLqiTop:.734375,deviceLqiBelowBottomBadgeTop:1.571875,devicePadding:.08,roomNameLineHeight:1.25,roomAreaLinkWidth:1.1,roomMetricsTopGap:.15,roomMetricFontSize:.75,roomMetricLineHeight:1.25,roomMetricIconWidth:1.05,roomMetricInnerGap:.12,roomMetricRowGap:.55,roomMetricMinWidth:11,roomPadding:.4,openingLockHalfSize:.62,roomMetricTextCharacters:Object.freeze({temperature:10,humidity:8,lqi:6,light:24})});function $e(e){return[...String(e)].reduce((e,t)=>/\s/.test(t)?e+Se.textSpaceAdvance:/[MW@#%&]/.test(t)?e+Se.textWideAsciiAdvance:e+(t.codePointAt(0)>255?Se.textWideAdvance:Se.textLatinAdvance),0)*Se.textWidthSafety}function ke(e,t){return $e(e)*z(t||e)}function ze(e,t){return[Math.max(Math.abs(e.left),Math.abs(e.right))+t,Math.max(Math.abs(e.top),Math.abs(e.bottom))+t]}function Ie(e){if("opening-lock"===e.kind){const t=(Number.isFinite(e.size)&&e.size>0?e.size:0)*Se.openingLockHalfSize;return[t,t]}if("room-label"===e.kind){const t=Number.isFinite(e.font)&&e.font>0?e.font:0,n=v(e.room.settings?.name_scale),o=v(e.room.settings?.label_scale),i=($e(e.room.name||"")+(e.room.area?Se.roomAreaLinkWidth:0))*n,a=Se.roomNameLineHeight*n,r=[e.display.labelTemp?Se.roomMetricTextCharacters.temperature:0,e.display.labelHum?Se.roomMetricTextCharacters.humidity:0,e.display.labelLqi&&e.room.area?Se.roomMetricTextCharacters.lqi:0,e.display.labelLight?Se.roomMetricTextCharacters.light:0].filter(e=>e>0),s=Se.roomMetricFontSize*o,l=r.length?Math.max(Se.roomMetricMinWidth,r.reduce((e,t)=>e+Se.roomMetricIconWidth+Se.roomMetricInnerGap+t*Se.textLatinAdvance*Se.textWidthSafety,0)+(r.length-1)*Se.roomMetricRowGap)*s:0,c=r.length?s*Se.roomMetricLineHeight:0,d=ze({left:-Math.max(i,l)/2,right:Math.max(i,l)/2,top:-a/2,bottom:r.length?a/2+Se.roomMetricsTopGap+c:a/2},Se.roomPadding);return[d[0]*t,d[1]*t]}const t=Number.isFinite(e.core)&&e.core>0?e.core:0,n=e.presentation,o=null==n.valueText?1:Math.max(1,ke(n.valueText,n.valueFullText||n.valueText)+Se.deviceValueInlinePadding),i=[];n.valueBadge&&i.push(Math.max(Se.deviceBadgeMinWidth,ke(n.valueBadge.text,n.valueBadge.fullText||n.valueBadge.text)+Se.deviceBadgeInlinePadding));for(const e of x(n)){const t=e.text+e.suffix;i.push(Math.max(Se.deviceBadgeMinWidth,ke(t,t)+Se.deviceBadgeInlinePadding))}const a=n.valueBadge?.position||"right";let r;if(!i.length||"left"!==a&&"right"!==a)if(i.length){const e=i.reduce((e,t)=>e+t,0)+(i.length-1)*Se.deviceSectionGap,t=Math.max(o,e),n=1+Se.deviceShellGap+Se.deviceBadgeHeight;r="bottom"===a?{left:-t/2-Se.deviceShellInset,right:t/2+Se.deviceShellInset,top:-.5-Se.deviceShellInset,bottom:-.5+n+Se.deviceShellInset}:{left:-t/2-Se.deviceShellInset,right:t/2+Se.deviceShellInset,top:.5-n-Se.deviceShellInset,bottom:.5+Se.deviceShellInset}}else r={left:-.5-Se.deviceShellInset,right:-.5+o+Se.deviceShellInset,top:-.5-Se.deviceShellInset,bottom:.5+Se.deviceShellInset};else{const e=Math.max(...i),t=i.length*Se.deviceBadgeHeight+(i.length-1)*Se.deviceSectionGap,n=o+Se.deviceShellGap+e,s=Math.max(1,t);r="right"===a?{left:-.5-Se.deviceShellInset,right:-.5+n+Se.deviceShellInset,top:-s/2-Se.deviceShellInset,bottom:s/2+Se.deviceShellInset}:{left:.5-n-Se.deviceShellInset,right:.5+Se.deviceShellInset,top:-s/2-Se.deviceShellInset,bottom:s/2+Se.deviceShellInset}}const s=Se.deviceAuxiliaryExtent;if(r.left=Math.min(r.left,-s),r.right=Math.max(r.right,s),r.top=Math.min(r.top,-s),r.bottom=Math.max(r.bottom,s),n.pulse.animated){const e=Math.max(1,n.pulse.diameterScale)/2;r.left=Math.min(r.left,-e),r.right=Math.max(r.right,e),r.top=Math.min(r.top,-e),r.bottom=Math.max(r.bottom,e)}if(null!=n.lqiText){const e="bottom"===n.valueBadge?.position?Se.deviceLqiBelowBottomBadgeTop:Se.deviceLqiTop,t=$e(n.lqiText)*Se.deviceLqiFontSize/2;r.left=Math.min(r.left,-t),r.right=Math.max(r.right,t),r.bottom=Math.max(r.bottom,e+Se.deviceLqiFontSize)}const l=ze(r,Se.devicePadding);return[l[0]*t,l[1]*t]}function Pe(e,t){return e.flatMap((e,n)=>e.orphanReason?[]:[{id:String(e.id||n),sourceIndex:n,type:e.type,x:e.rx,y:e.ry,angle:Number(e.angle)||0,length:e.rlen>0?e.rlen:.9*t,flipH:!!e.flip_h,flipV:!!e.flip_v}])}function Ce(e){return{id:e.id,x:e.x,y:e.y,w:e.w,h:e.h,poly:e.poly,wall_ids:e.wall_ids}}function je(e,t){const n=e?.partitionHost;if(!n)return null;const o="gate"===t.type?!t.flipV:t.flipV;return{sourceIndex:t.sourceIndex,hostId:n.host.id,t:n.t,depth:n.depth,face:p(n,o)}}function Ne(n,o=R){const i=Pe(n.openings,n.coordinateScale),r=i.map(e=>je(n.openings[e.sourceIndex],e)),p=a(t,n.cellCm),m=a(s,n.cellCm),g=a(l,n.cellCm);return{key:`${n.space.id}|${function(e){let t=2166136261;const n=e=>{if("number"!=typeof e)if("string"!=typeof e)if("boolean"!=typeof e)if(Array.isArray(e)){t=H(t,e.length);for(const t of e)n(t)}else{if(e&&"object"==typeof e){const t=e;for(const e of Object.keys(t).sort())n(e),n(t[e]);return}t=H(t,-1)}else t=H(t,e?1:0);else for(const n of e)t=H(t,n.codePointAt(0)||0);else t=H(t,e)};return n(e),t.toString(36)}({rooms:n.space.rooms.map(Ce),walls:n.walls,openCuts:n.openCuts,openings:i,openingHosts:r,openingGeometryPolicy:o,partitions:n.space.partitions,columns:n.space.wall_columns,cellCm:n.cellCm,gridPitch:n.gridPitch,wallKeyPitch:n.wallKeyPitch,camera:e,wallHeight:p,raisedHeight:g,floorEdgeHeight:m,algorithm:4})}`,build:()=>{n.onBuild();const a=c(n.space,n.cellCm,n.gridPitch,2e-4*n.gridPitch,n.partitionCuts()).all,s=n.roomOpenings(),l=n.walls.length||a.length?d(n.space.rooms,n.walls,n.openCuts,s,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale,a):null;if(l&&("failed-core"===l.status||"not-applicable"===l.status))throw new Error("wall boolean geometry failed");const m=l?.paperGeom??f(n.space.rooms,n.walls,n.openCuts,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale);if(!m)throw new Error("floor boolean geometry failed");const g=l?.openingIndex||u(n.space.rooms,n.walls,n.openCuts,n.wallKeyPitch,n.cellCm,n.gridPitch,n.coordinateScale),w=i.map((e,i)=>{const a=r[i],s="gate"===e.type?!e.flipV:e.flipV,l=a?a.face:n.walls.length||"gate"===e.type?h(g,{x:e.x,y:e.y,angle:e.angle,length:e.length,flip_v:s}):{ox:0,oy:0,cm:0,side:-1};return function(e,n=t,o=R){const i=e.face.cm??0;if(!F([e.x,e.y,e.angle,e.length,e.face.ox,e.face.oy,i,n])||!(e.length>0)||!(n>0)||-1!==e.face.side&&1!==e.face.side||i<0)throw new Error("invalid isometric opening input");const a=e.length/2,r=e.angle*Math.PI/180,s=T(Math.cos(r),Math.sin(r)),l=T(-Math.sin(r),Math.cos(r)),c=T(e.x,e.y),d=T(e.x-s[0]*a,e.y-s[1]*a),f=T(e.x+s[0]*a,e.y+s[1]*a),u=T(e.face.ox,e.face.oy),h=T(d[0]+u[0],d[1]+u[1]),p=T(f[0]+u[0],f[1]+u[1]),m=T(d[0]-u[0],d[1]-u[1]),g=T(f[0]-u[0],f[1]-u[1]),w=Object.freeze({center:c,tangent:s,normal:l,start:d,end:f}),y=Object.freeze({side:e.face.side,cm:i,depth:2*Math.hypot(e.face.ox,e.face.oy),offset:u,selectedStart:h,selectedEnd:p,oppositeStart:m,oppositeEnd:g}),v="passage"===e.type?[]:[Object.freeze({jamb:0,center:d,selected:h,opposite:m}),Object.freeze({jamb:1,center:f,selected:p,opposite:g})];let x;if("passage"===e.type)x=[];else if("gate"===e.type){const t=e.face.side*o.gateTurnDeg;x=[E(e,0,[-a,0],[a,0],t,0,n*o.gateTopRatio),E(e,1,[a,0],[-a,0],-t,0,n*o.gateTopRatio)]}else x="window"===e.type?[E(e,0,[-a,0],[a,0],-90,n*o.windowBottomRatio,n*o.windowTopRatio),E(e,1,[a,0],[-a,0],90,n*o.windowBottomRatio,n*o.windowTopRatio)]:[E(e,0,[-a,0],[e.length,0],-90,0,n*o.doorTopRatio)];return Object.freeze({id:e.id,sourceIndex:e.sourceIndex,type:e.type,wallHeight:n,leafThickness:n*o.leafThicknessRatio,frameThickness:n*o.frameThicknessRatio,axis:w,face:y,reveals:Object.freeze(v),leaves:Object.freeze(x.map(e=>Object.freeze({...e,hinge:T(e.hinge[0],e.hinge[1]),closedVector:T(e.closedVector[0],e.closedVector[1]),quarterVector:T(e.quarterVector[0],e.quarterVector[1])})))})}({...e,face:l},p,o)}),y=Object.freeze(w);return{walls:l?.components.flatMap(e=>e.geom)||[],floor:m,openings:y,openingSurfaces:Object.freeze(y.flatMap(t=>function(t,n=e){if("passage"===t.type)return Object.freeze([]);const o=[];if(t.face.depth>1e-9)for(const e of t.reveals)o.push(_("jamb-reveal","reveal",e.selected,e.opposite,0,t.wallHeight,n,{jamb:e.jamb}));if("window"!==t.type||!t.leaves.length)return Object.freeze(o.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||(e.jamb??0)-(t.jamb??0)));const i=Math.min(...t.leaves.map(e=>e.bottom)),a=Math.max(...t.leaves.map(e=>e.top)),r=Math.min(t.frameThickness,Math.hypot(t.axis.end[0]-t.axis.start[0],t.axis.end[1]-t.axis.start[1])/4,(a-i)/4),s=L(t.axis.start,G(t.axis.tangent,r)),l=V(t.axis.end,G(t.axis.tangent,r)),c=t.face.depth>1e-9?[t.face.offset,T(-t.face.offset[0],-t.face.offset[1])]:[t.face.offset];for(const e of c){const c=L(t.axis.start,e),d=L(t.axis.end,e),f=L(s,e),u=L(l,e);o.push(_("window-frame-side","light-frame",c,f,i,a,n,{jamb:0}),_("window-frame-side","light-frame",u,d,i,a,n,{jamb:1}),_("window-frame-top","light-frame",f,u,Math.max(i,a-r),a,n))}return t.face.depth>1e-9&&o.push(D("window-sill","light-sill",[{point:t.face.selectedStart,z:i},{point:t.face.selectedEnd,z:i},{point:t.face.oppositeEnd,z:i},{point:t.face.oppositeStart,z:i}],n)),Object.freeze(o.sort((e,t)=>e.depth-t.depth||e.kind.localeCompare(t.kind)||(e.jamb??0)-(t.jamb??0)))}(t).map(e=>Object.freeze({...e,id:t.id,sourceIndex:t.sourceIndex,type:t.type}))))}}}}const Oe=e=>Array.isArray(e)?e:[];function Ae(e,t){const o=e=>Oe(e).flatMap(e=>Array.isArray(e)&&Number.isFinite(e[0])&&Number.isFinite(e[1])?[n([Number(e[0]),Number(e[1])],t)]:[]);return Oe(e).flatMap(e=>{const t=Oe(e);if(!t.length)return[];const n=o(t[0]);if(n.length<3)return[];return[{outer:n,holes:t.slice(1).map(o).filter(e=>e.length>=3)}]})}function Be(o){const i=a(t,o.cellCm),r=a(s,o.cellCm),c=a(l,o.cellCm),d=S(o.cache,o.source.key);let f=d.hit?d.value:void 0;if(!f){const a=o.source.build(),s=function(o,i=e,a=t){if(!Number.isFinite(a)||a<0)throw new Error("invalid wall height");const r=[],s=[],l=[],c=[];let d=0;for(let e=0;e<(o||[]).length;e++){const t=o[e],f=[];let u=-1/0;for(let o=0;o<(t||[]).length;o++){const s=N(t[o],o>0);if(s.length<3||Math.abs(j(s))<1e-9)continue;const h=O(s,i,a);r.push(h),f.push(h),u=Math.max(u,...s.map(e=>n(e,a,i)[1])),d+=s.length;for(let t=0;te.depth-t.depth||e.polygon-t.polygon||e.ring-t.ring||e.edge-t.edge),s.sort((e,t)=>e.depth-t.depth||e.component-t.component),{topPath:r.join(" "),topFaces:s,sides:l,contactPath:c.join(" "),edgeCount:d}}(a.walls,e,i),l=Ae(a.walls,i);f={geometry:s,floor:B(a.floor,r),wallSilhouettes:Object.freeze([...l,...s.sides.map(e=>({outer:e.points}))]),openings:a.openings,openingSurfaces:a.openingSurfaces},$(o.cache,o.source.key,f,8)}const u=function(e){let t=1/0,n=1/0,o=-1/0,i=-1/0;const a=(e,a=0)=>{t=Math.min(t,e[0]-a),n=Math.min(n,e[1]-a),o=Math.max(o,e[0]+a),i=Math.max(i,e[1]+a)};for(const t of e)if("passage"!==t.type){a(t.axis.start),a(t.axis.end),a(t.face.selectedStart),a(t.face.selectedEnd),a(t.face.oppositeStart),a(t.face.oppositeEnd);for(const e of t.leaves){const n=Math.hypot(e.closedVector[0],e.closedVector[1])+t.leafThickness/2;a(e.hinge,n)}}return F([t,n,o,i])?{x:t,y:n,w:o-t,h:i-n}:null}(f.openings),h=u?He(o.liveFrame,u):o.liveFrame,p=k({rect:h,wallHeight:i,openingHeight:i,floorDepth:r,raisedHeight:c});return{key:o.source.key,...f,frame:p}}const He=(e,t)=>{const n=Math.min(e.x,t.x),o=Math.min(e.y,t.y);return{x:n,y:o,w:Math.max(e.x+e.w,t.x+t.w)-n,h:Math.max(e.y+e.h,t.y+t.h)-o}},Re=e=>{if(!e.length||!e.every(e=>Number.isFinite(e[0])&&Number.isFinite(e[1])))return null;const t=e.map(e=>e[0]),n=e.map(e=>e[1]),o=Math.min(...t),i=Math.min(...n);return{x:o,y:i,w:Math.max(...t)-o,h:Math.max(...n)-i}},Fe=(e,t)=>{const n=e.placement,o=t?n.visualScene:n.raisedScene,[i,a]=e.screenHalfSize,r=t?n.footprint:n.footprint.map(e=>[e[0]-n.nudgeScene[0],e[1]-n.nudgeScene[1]]);return[n.floorScene,...r,[o[0]-i,o[1]-a],[o[0]+i,o[1]-a],[o[0]+i,o[1]+a],[o[0]-i,o[1]+a]]},Te=(e,t)=>void 0===t?e:e.filter(e=>e.placement.owner?.id===t);function Le(e,t){return e?Re(Te(e.entries,t).flatMap(e=>Fe(e,!0))):null}function Ve(e){const t=Te(e.entries,e.ownerId),n=Re(t.flatMap(e=>Fe(e,!1))),o=n?He(e.baseBounds,n):e.baseBounds,i=e.targetView(o);if(!(i&&i.w>0&&i.h>0&&[i.x,i.y,i.w,i.h].every(Number.isFinite)))return null;const a=e.stageSize;if(!(n&&a&&a.width>0&&a.height>0))return{bounds:o,view:i};const r=e=>Math.max(e.w/a.width,e.h/a.height),s=t=>{const o=48*t,i={x:n.x-o,y:n.y-o,w:n.w+2*o,h:n.h+2*o},a=He(e.baseBounds,i),r=e.targetView(a);return r&&[r.x,r.y,r.w,r.h].every(Number.isFinite)&&r.w>0&&r.h>0?{bounds:a,view:r}:null};let l=0,c=Math.max(r(i),Number.EPSILON),d=s(c);for(let e=0;d&&r(d.view)>c*(1+1e-10)&&e<24;e++)l=c,c*=2,d=s(c);if(!d)return null;for(let e=0;e<40;e++){const e=(l+c)/2,t=s(e);if(!t)return null;r(t.view)<=e?(c=e,d=t):l=e}return d}const Ge=new WeakMap,We=2048,Ee=new WeakMap,qe=new WeakMap,De=new WeakMap;function _e(e,t){if(e.size!==t.size)return!1;for(const[n,o]of t)if(e.get(n)!==o)return!1;return!0}function Ue(e){const t=Ge.get(e.rooms);if(t)return t;const n=e.rooms.flatMap((e,t)=>{const n=w(e);return n&&n.length>=3?[{room:e,index:t,poly:n}]:[]}),o=Object.freeze(n.map(({room:e,index:t,poly:o})=>{const i=y(o,n.filter(e=>e.index!==t).map(e=>e.poly)),a={id:e.id||`room-index-${t}`,outer:o.map(e=>[e[0],e[1]]),holes:i.map(e=>e.map(e=>[e[0],e[1]]))};return{room:e,overlayRoom:{...a,safePoint:ie(a)||void 0}}}));return Ge.set(e.rooms,o),o}function Ke(o){const s=o.stageSize&&o.stageSize.width>0&&o.stageSize.height>0?Math.max(o.view.w/o.stageSize.width,o.view.h/o.stageSize.height):Math.max(o.view.w,o.view.h)/1e3,l=Ue(o.space),c=l.map(e=>e.overlayRoom),d=a(t,o.cellCm),f=a(i,o.cellCm),u=new Map,h=new Map,p=new Map,m=[];let g=Ee.get(o.wallSilhouettes);g||(g=new Map,Ee.set(o.wallSilhouettes,g));let w=qe.get(l);w||(w=new Map,qe.set(l,w));const y=o.iconPct*r(o.space)*o.kioskIconScale/100,v=o.deviceBasePct*r(o.space)*o.kioskIconScale/100,x=(a,r,l,u,h,p=!1)=>{const m=`${!1===o.resolveCollisions?"fit":"live"}\0${a}\0${r}`,y=[l[0],l[1],u[0],u[1],h||"",d,f,o.layers.shadows?1:0,p?1:0].join("|"),v=`${y}|${s}`,x=S(g,m);if(x.hit&&x.value.signature===v)return x.value.placement;if(x.hit&&x.value.shapeSignature===y&&s<=x.value.unitsPerPixel){const e=x.value.placement,t=e.nudgeDistanceCss*x.value.unitsPerPixel/s;if(!e.nearWallBefore||e.cleared&&t<=48)return e}const M=`${a}\0${r}`,b=[l[0],l[1],h||""].join("|"),k=S(w,M),z=k.hit&&k.value.signature===b?k.value.owner:ae({kind:a,floorAnchor:l,rooms:c,roomsValidated:!0,preferredRoomId:h});k.hit&&k.value.signature===b||$(w,M,{signature:b,owner:z},We);const I=function(o){const a=o.camera||e,r=o.wallHeight??t,s=o.visualOffset??i,l=o.sceneUnitsPerCssPixel??1,c=o.safetyGapCssPx??4,d=o.maxNudgeCssPx??48;if(!Z(o.floorAnchor)||!Z(o.footprintHalfSize)||o.footprintHalfSize[0]<0||o.footprintHalfSize[1]<0||!Number.isFinite(r)||r<0||!Number.isFinite(s)||s<0||!Number.isFinite(l)||l<=0||!Number.isFinite(c)||c<0||!Number.isFinite(d)||d<0)throw new Error("invalid isometric overlay input");const f=[o.floorAnchor[0],o.floorAnchor[1]],u=n(f,0,a),h=(p=o.kind,!o.showBorders||"device"!==p&&"room-label"!==p&&"opening-lock"!==p?"floor":"raised");var p;if("floor"===h)return{plane:h,owner:null,floorAnchor:f,floorScene:u,raisedScene:u,visualScene:u,footprint:[],nudgeScene:[0,0],nudgeCss:[0,0],nudgeDistanceCss:0,nudged:!1,nearWallBefore:!1,nearWallAfter:!1,cleared:!0,capped:!1,grounding:{center:u,visible:!1},tether:ye(u,u,!1),status:"ok",reason:null};const m=r+s,g=n(f,m,a),w=o.ownerAlreadyResolved?o.resolvedOwner??null:ae(o),y=o.wallGeometryValidated??o.wallSilhouettes.every(ge),v=c*l,x=re(f,o.footprintHalfSize,m,a),M=e=>{const t=fe(e);return!!t&&o.wallSilhouettes.some(n=>me(e,t,n,v,!0===o.wallGeometryValidated))},b=!y||M(x);let S=0,$=[0,0],k=null,z=!1,I=y?"ok":"degraded",P=y?null:"invalid-wall-geometry";if(y&&b)if(w)if(w.safePoint){const e=o.rooms.find(e=>e.id===w.id)||null,t=n(w.safePoint,m,a),i=t[0]-g[0],r=t[1]-g[1],s=Math.hypot(i,r);if(s<=K)I="degraded",P="invalid-safe-point";else{const t=i/s,n=r/s,a=Math.min(d,s/l),c=a*l/s,u=[f[0]+(w.safePoint[0]-f[0])*c,f[1]+(w.safePoint[1]-f[1])*c],h=[t*a*l,n*a*l],p=fe([...x,...x.map(e=>[e[0]+h[0],e[1]+h[1]])]),m=p?o.wallSilhouettes.filter(e=>{const t=ue(e,!0===o.wallGeometryValidated);return!!t&&he(p,t,v)}):o.wallSilhouettes,g=!!e&&we(f,u,e),y=e=>{const i=[t*e*l,n*e*l],a=x.map(e=>[e[0]+i[0],e[1]+i[1]]),r=fe(a);return!!r&&m.some(e=>me(a,r,e,v,!0===o.wallGeometryValidated))},M=o.nudgeHintCss;if(Number.isFinite(M)&&M>=0&&M<=a){const t=M*l/s,n=[f[0]+(w.safePoint[0]-f[0])*t,f[1]+(w.safePoint[1]-f[1])*t];(g||e&&we(f,n,e))&&!y(M)&&(S=M,k=!1)}if(null===k){let t=null,n=0,o=!1;const i=Math.ceil(a);for(let r=1;r<=i;r++){const i=Math.min(a,r),c=i*l/s,d=[f[0]+(w.safePoint[0]-f[0])*c,f[1]+(w.safePoint[1]-f[1])*c];if(!(g||e&&we(f,d,e))){o=!0;break}if(!y(i)){t=i;break}n=i}if(null!==t){let e=n,o=t;for(let t=0;t<14;t++){const t=(e+o)/2;y(t)?e=t:o=t}S=o}else S=n,z=!0,I="degraded",P=o?"owner-boundary":"nudge-cap"}$=[t*S*l,n*S*l]}}else I="degraded",P="invalid-safe-point";else I="degraded",P="missing-owner";const C=[g[0]+$[0],g[1]+$[1]],j=re(f,o.footprintHalfSize,m,a,$),N=!y||(k??M(j)),O=S>K,A=O||b||N||!!o.hovered||!!o.focused||!!o.selected;return{plane:h,owner:w,floorAnchor:f,floorScene:u,raisedScene:g,visualScene:C,footprint:j,nudgeScene:$,nudgeCss:[$[0]/l,$[1]/l],nudgeDistanceCss:S,nudged:O,nearWallBefore:b,nearWallAfter:N,cleared:!N,capped:z,grounding:{center:u,visible:!1!==o.filtersSupported},tether:ye(u,C,A),status:I,reason:P}}({kind:a,floorAnchor:l,rooms:c,roomsValidated:!0,preferredRoomId:h,ownerAlreadyResolved:!0,resolvedOwner:z,nudgeHintCss:x.hit&&x.value.shapeSignature===y?x.value.placement.nudgeDistanceCss*x.value.unitsPerPixel/s:void 0,showBorders:!0,wallSilhouettes:!1===o.resolveCollisions?[]:o.wallSilhouettes,wallGeometryValidated:!0,footprintHalfSize:u,wallHeight:d,visualOffset:f,sceneUnitsPerCssPixel:s,filtersSupported:o.layers.shadows,hovered:!0,selected:p});return $(g,m,{signature:v,shapeSignature:y,unitsPerPixel:s,placement:I},We),I};for(const e of o.devices){const t=o.positionOf(e),n=o.presentationOf(e,o.showLqi),i=v*n.scale,a=Ie({kind:"device",core:i,presentation:n}),r=e.marker?.room_id||l.find(t=>!!e.area&&t.room.area===e.area)?.overlayRoom.id||null,s=x("device",e.id,[t.x,t.y],a,r,o.selectedDeviceId===e.id);u.set(e.id,s),m.push({id:e.id,kind:"device",placement:s,groundRadius:Math.max(.32*i,2),screenHalfSize:a})}for(const{room:e,overlayRoom:t}of l){if(!o.display.showNames||!e.name)continue;const n=o.labelPositionOf(e,o.space.id),i=.5*y*(o.labelScaleOf(e)*o.kioskFontScale*o.display.cardFontScale),a=Ie({kind:"room-label",font:i,room:e,display:o.display}),r=x("room-label",t.id,[n.x,n.y],a,t.id,o.focusedRoomId===e.id);h.set(e,r),m.push({id:t.id,kind:"room-label",placement:r,groundRadius:Math.max(.75*i,2),screenHalfSize:a})}const M=o.openings.filter(e=>!e.orphanReason&&("door"===e.type||"gate"===e.type)&&"string"==typeof e.lock&&!!e.lock&&o.openingEntityAvailable(e.lock));if(M.length){const e=o.openingWallIndex();for(const t of M){const n=Je(t,e,o.cellCm),i=n.floorAnchor,a=.62*y,r=Ie({kind:"opening-lock",size:a}),s=x("opening-lock",String(t.id),i,r,n.preferredRoomId,o.selectedOpeningId===t.id);p.set(String(t.id),s),m.push({id:String(t.id),kind:"opening-lock",placement:s,groundRadius:Math.max(.28*a,2),screenHalfSize:r})}}const b={devices:u,rooms:h,locks:p,entries:Object.freeze(m)},k=!1===o.resolveCollisions?"fit":"live";let z=De.get(o.wallSilhouettes);z||(z=new Map,De.set(o.wallSilhouettes,z));const I=z.get(k);return I&&function(e,t){return e.length===t.length&&t.every((t,n)=>{const o=e[n];return o.id===t.id&&o.kind===t.kind&&o.placement===t.placement&&o.groundRadius===t.groundRadius&&o.screenHalfSize[0]===t.screenHalfSize[0]&&o.screenHalfSize[1]===t.screenHalfSize[1]})}(I.entries,b.entries)&&_e(I.devices,b.devices)&&_e(I.rooms,b.rooms)&&_e(I.locks,b.locks)?I:(z.set(k,b),b)}function Ze(e,t,n){return Je(e,t,n).floorAnchor}function Je(e,t,n){const o=!e.flip_v,i="gate"===e.type?e.partitionHost?p(e.partitionHost,o):h(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen,flip_v:o}):null,[a,r]=m({x:e.rx,y:e.ry,angle:e.angle,flipV:!!e.flip_v,gateFace:i},n);if(e.partitionHost)return{floorAnchor:a,preferredRoomId:null};const s=g(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen},!0),l=r?"negative":"positive";return{floorAnchor:a,preferredRoomId:s[l]?.roomId||null}}function Qe(e){let t=!1;try{t="undefined"!=typeof CSS&&"function"==typeof CSS.supports&&CSS.supports("filter","blur(1px)")}catch{t=!1}let n=!1;try{n="function"==typeof matchMedia&&matchMedia("(forced-colors: active)").matches}catch{n=!0}return function(e){const t=!!e.showBorders;return{structural:t,panels:t&&!e.hideOpenings,shadows:t&&e.filtersSupported&&!e.forcedColors,materialNuance:t&&e.filtersSupported&&!e.forcedColors,floorSymbols:!e.hideOpenings&&!t}}({showBorders:e.showBorders,hideOpenings:e.hideOpenings,filtersSupported:t,forcedColors:n})}function Xe(e,t,n,o){if(!e.panels||!t)return[];return t.openings.flatMap(e=>{const t=n[e.sourceIndex];return t?U(e,o(t)):[]}).sort((e,t)=>e.depth-t.depth||e.sourceIndex-t.sourceIndex||e.leaf-t.leaf)}function Ye(e){const t=Qe(e.display),n=t.panels?Xe(t,e.scene,e.openings,e.amountOf):[],o=e.overlays(t),i=t=>({layers:t,panels:n,overlays:o,underlay:at(t,e.scene?.floor,e.cellCm),shadows:rt(t,n,e.scene?.geometry,e.cellCm),walls:st(e.projection,t,e.scene,n,e.cellCm),grounds:ot(o,t,e.cellCm),raised:it(o)});try{return i(t)}catch(e){if(!t.shadows&&!t.materialNuance)throw e;return i({...t,shadows:!1,materialNuance:!1})}}const et=()=>b``;function tt(e){return`translate(${a(4,e)} ${a(8,e)})`}function nt(e,t,n){const o=I(n);return b`
${"walls"===t&&e.materialNuance?b`
diff --git a/dist/houseplan-assets/live-interaction-runtime-Bn789cLD.js b/dist/houseplan-assets/live-interaction-runtime-B4GlJv_x.js
similarity index 96%
rename from dist/houseplan-assets/live-interaction-runtime-Bn789cLD.js
rename to dist/houseplan-assets/live-interaction-runtime-B4GlJv_x.js
index e1ec7ebb..949e30c9 100644
--- a/dist/houseplan-assets/live-interaction-runtime-Bn789cLD.js
+++ b/dist/houseplan-assets/live-interaction-runtime-B4GlJv_x.js
@@ -1 +1 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{dQ as e}from"./houseplan-card-B_QYG0Py.js";const t=new WeakMap,n=e=>{let n=t.get(e);return n||(n={painted:null,pending:null,raf:0},t.set(e,n)),n},o=e=>`${e.x} ${e.y} ${e.w} ${e.h}`;const r=e=>0===e.translateXPercent&&0===e.translateYPercent&&1===e.scaleX&&1===e.scaleY,a=e=>[e.x,e.y,e.w,e.h].every(Number.isFinite)&&e.w>0&&e.h>0,s=(e,t)=>{if(!t)return e.style.removeProperty("transform"),e.style.removeProperty("transform-origin"),void e.style.removeProperty("will-change");e.style.transformOrigin="0 0",e.style.willChange="transform",e.style.transform=`translate(${t.translateXPercent}%,${t.translateYPercent}%) scale(${t.scaleX},${t.scaleY})`};function i(e,t,n){if(!a(t.view)||!a(n.view)||!a(n.floor))return;const i=o(n.view),l=o(n.floor);for(const t of e.querySelectorAll('[data-hp-live-viewbox="camera"]'))t.setAttribute("viewBox",i);for(const t of e.querySelectorAll('[data-hp-live-viewbox="floor"]'))t.setAttribute("viewBox",l);const c=(f=t.view,u=n.view,{translateXPercent:(f.x-u.x)/u.w*100,translateYPercent:(f.y-u.y)/u.h*100,scaleX:f.w/u.w,scaleY:f.h/u.h});var f,u;for(const t of e.querySelectorAll('[data-hp-live-layer="camera"]'))s(t,r(c)?null:c);const d=e.querySelector("[data-hp-live-zoom]");if(d){d.hidden=n.zoom<=1;const e=d.querySelector("[data-hp-live-zoom-value]");e&&(e.textContent=`${Math.round(100*n.zoom)}%`)}}const l=e=>{const t=e._viewOr(e._baseVb());return{view:{...t},floor:{...e._floorView(t)},zoom:e._zoom}};const c=new WeakMap,f=(e,t,n,o)=>{if(!n)return;const r=document.createElement("span");if(r.className="m",t){r.append(`${t} `);const e=document.createElement("b");e.textContent=n,o&&(e.style.color=o),r.append(e)}else r.textContent=n;e.append(r)},u=(e,t,n)=>{const o=e.querySelector(t);o&&(o.setAttribute("d",n),o.toggleAttribute("hidden",!n))};function d(t){const n=t,o=n.renderRoot;if(!o)return;((t,n)=>{const o=n.querySelector("[data-hp-live-tip]");if(!o)return;const r=t._tip;if(!r)return o.hidden=!0,void o.replaceChildren();o.style.left=`${r.x+12}px`,o.style.top=`${r.y+12}px`,o.replaceChildren();const a=document.createElement("b");a.textContent=r.title,o.append(a),f(o,"",r.meta),f(o,t._t("tip.temp_avg"),null==r.temp?"":`${r.temp}°`),f(o,t._t("tip.hum_avg"),null==r.hum?"":`${r.hum}%`),f(o,t._t("tip.lqi"),null==r.lqi?"":String(r.lqi),null==r.lqi?void 0:e(r.lqi)),o.hidden=!1})(n,o);const r=n._hoverRoom,a=c.get(t),s=r?.space||"",i=r?.room||null;if(a?.room===i&&a?.space===s)return;c.set(t,{room:i,space:s});const l=r&&n._spaceModel(),d=l?n._roomHoverPaths(l):null;u(o,'[data-hp-live-room-hover="fill"]',d?.fillD||""),u(o,'[data-hp-live-room-hover="halo"]',d?.outlineD||""),u(o,'[data-hp-live-room-hover="outline"]',d?.outlineD||"")}function m(e){c.delete(e)}class p{constructor(e){this.host=e,this.deferredHass=!1}hass(e,t,n,o){const r=function(e,t,n){if(e===t)return"none";if(!e||!t||!n)return"structural";if(e.connection!==t.connection||e.entities!==t.entities||e.devices!==t.devices||e.areas!==t.areas||e.themes!==t.themes||e.user!==t.user||e.config!==t.config||e.floors!==t.floors||e.services!==t.services||e.panels!==t.panels||e.language!==t.language||e.locale?.language!==t.locale?.language||e.locale?.number_format!==t.locale?.number_format||e.locale?.time_format!==t.locale?.time_format||e.locale?.date_format!==t.locale?.date_format)return"structural";const o=new Set(["states","connection","entities","devices","areas","themes","user","config","floors","services","panels","language","locale"]);for(const n of new Set([...Object.keys(e),...Object.keys(t)]))if(!o.has(n)&&e[n]!==t[n])return"structural";for(const o of n.entityIds)if(e.states?.[o]!==t.states?.[o])return"state";return"none"}(e,t,n),a="state"===r&&this.active();a&&(this.deferredHass=!0);const s="none"!==r&&!a;return s||this.host._renderLife.observe(e,t,n,o),s}clear(){this.deferredHass=!1}take(){const e=this.deferredHass;return this.deferredHass=!1,e}viewport(e=!1){!function(e,t=!1){const o=e,r=n(e),a=l(o);if(t)return r.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(r.raf),r.raf=0,r.pending=null,r.painted||(r.painted=a),void i(o.renderRoot,r.painted,a);r.pending=a,r.raf||"function"!=typeof requestAnimationFrame||(r.raf=requestAnimationFrame(()=>{r.raf=0;const e=r.pending;r.pending=null;const t=o.renderRoot;e&&t&&(r.painted||(r.painted=e),i(t,r.painted,e))}))}(this.host,e)}hover(){d(this.host)}active(){const e=this.host;return e._pointers.size>0||e._cameraTransition.active||!!e._deviceDrag||!!e._physicalDrag||!!e._physicalRotate||!!e._decorMove||!!e._decorDraft||!!e._dtDrag||!!e._bdDrag||!!e._opDrag||!!e._resize?.dragging}commit(){!function(e){const t=e,o=n(e);o.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o.raf),o.raf=0,o.pending=null,o.painted=l(t);const r=t.renderRoot;if(r){for(const e of r.querySelectorAll('[data-hp-live-layer="camera"]'))s(e,null);i(r,o.painted,o.painted)}}(this.host),m(this.host),d(this.host)}dispose(){!function(e){const n=t.get(e);n?.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(n.raf),t.delete(e)}(this.host),m(this.host)}}export{p as LiveRuntime};
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{dR as e}from"./houseplan-card-6Hf8VPda.js";const t=new WeakMap,n=e=>{let n=t.get(e);return n||(n={painted:null,pending:null,raf:0},t.set(e,n)),n},o=e=>`${e.x} ${e.y} ${e.w} ${e.h}`;const r=e=>0===e.translateXPercent&&0===e.translateYPercent&&1===e.scaleX&&1===e.scaleY,a=e=>[e.x,e.y,e.w,e.h].every(Number.isFinite)&&e.w>0&&e.h>0,s=(e,t)=>{if(!t)return e.style.removeProperty("transform"),e.style.removeProperty("transform-origin"),void e.style.removeProperty("will-change");e.style.transformOrigin="0 0",e.style.willChange="transform",e.style.transform=`translate(${t.translateXPercent}%,${t.translateYPercent}%) scale(${t.scaleX},${t.scaleY})`};function i(e,t,n){if(!a(t.view)||!a(n.view)||!a(n.floor))return;const i=o(n.view),l=o(n.floor);for(const t of e.querySelectorAll('[data-hp-live-viewbox="camera"]'))t.setAttribute("viewBox",i);for(const t of e.querySelectorAll('[data-hp-live-viewbox="floor"]'))t.setAttribute("viewBox",l);const c=(f=t.view,u=n.view,{translateXPercent:(f.x-u.x)/u.w*100,translateYPercent:(f.y-u.y)/u.h*100,scaleX:f.w/u.w,scaleY:f.h/u.h});var f,u;for(const t of e.querySelectorAll('[data-hp-live-layer="camera"]'))s(t,r(c)?null:c);const d=e.querySelector("[data-hp-live-zoom]");if(d){d.hidden=n.zoom<=1;const e=d.querySelector("[data-hp-live-zoom-value]");e&&(e.textContent=`${Math.round(100*n.zoom)}%`)}}const l=e=>{const t=e._viewOr(e._baseVb());return{view:{...t},floor:{...e._floorView(t)},zoom:e._zoom}};const c=new WeakMap,f=(e,t,n,o)=>{if(!n)return;const r=document.createElement("span");if(r.className="m",t){r.append(`${t} `);const e=document.createElement("b");e.textContent=n,o&&(e.style.color=o),r.append(e)}else r.textContent=n;e.append(r)},u=(e,t,n)=>{const o=e.querySelector(t);o&&(o.setAttribute("d",n),o.toggleAttribute("hidden",!n))};function d(t){const n=t,o=n.renderRoot;if(!o)return;((t,n)=>{const o=n.querySelector("[data-hp-live-tip]");if(!o)return;const r=t._tip;if(!r)return o.hidden=!0,void o.replaceChildren();o.style.left=`${r.x+12}px`,o.style.top=`${r.y+12}px`,o.replaceChildren();const a=document.createElement("b");a.textContent=r.title,o.append(a),f(o,"",r.meta),f(o,t._t("tip.temp_avg"),null==r.temp?"":`${r.temp}°`),f(o,t._t("tip.hum_avg"),null==r.hum?"":`${r.hum}%`),f(o,t._t("tip.lqi"),null==r.lqi?"":String(r.lqi),null==r.lqi?void 0:e(r.lqi)),o.hidden=!1})(n,o);const r=n._hoverRoom,a=c.get(t),s=r?.space||"",i=r?.room||null;if(a?.room===i&&a?.space===s)return;c.set(t,{room:i,space:s});const l=r&&n._spaceModel(),d=l?n._roomHoverPaths(l):null;u(o,'[data-hp-live-room-hover="fill"]',d?.fillD||""),u(o,'[data-hp-live-room-hover="halo"]',d?.outlineD||""),u(o,'[data-hp-live-room-hover="outline"]',d?.outlineD||"")}function m(e){c.delete(e)}class p{constructor(e){this.host=e,this.deferredHass=!1}hass(e,t,n,o){const r=function(e,t,n){if(e===t)return"none";if(!e||!t||!n)return"structural";if(e.connection!==t.connection||e.entities!==t.entities||e.devices!==t.devices||e.areas!==t.areas||e.themes!==t.themes||e.user!==t.user||e.config!==t.config||e.floors!==t.floors||e.services!==t.services||e.panels!==t.panels||e.language!==t.language||e.locale?.language!==t.locale?.language||e.locale?.number_format!==t.locale?.number_format||e.locale?.time_format!==t.locale?.time_format||e.locale?.date_format!==t.locale?.date_format)return"structural";const o=new Set(["states","connection","entities","devices","areas","themes","user","config","floors","services","panels","language","locale"]);for(const n of new Set([...Object.keys(e),...Object.keys(t)]))if(!o.has(n)&&e[n]!==t[n])return"structural";for(const o of n.entityIds)if(e.states?.[o]!==t.states?.[o])return"state";return"none"}(e,t,n),a="state"===r&&this.active();a&&(this.deferredHass=!0);const s="none"!==r&&!a;return s||this.host._renderLife.observe(e,t,n,o),s}clear(){this.deferredHass=!1}take(){const e=this.deferredHass;return this.deferredHass=!1,e}viewport(e=!1){!function(e,t=!1){const o=e,r=n(e),a=l(o);if(t)return r.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(r.raf),r.raf=0,r.pending=null,r.painted||(r.painted=a),void i(o.renderRoot,r.painted,a);r.pending=a,r.raf||"function"!=typeof requestAnimationFrame||(r.raf=requestAnimationFrame(()=>{r.raf=0;const e=r.pending;r.pending=null;const t=o.renderRoot;e&&t&&(r.painted||(r.painted=e),i(t,r.painted,e))}))}(this.host,e)}hover(){d(this.host)}active(){const e=this.host;return e._pointers.size>0||e._cameraTransition.active||!!e._deviceDrag||!!e._physicalDrag||!!e._physicalRotate||!!e._decorMove||!!e._decorDraft||!!e._dtDrag||!!e._bdDrag||!!e._opDrag||!!e._resize?.dragging}commit(){!function(e){const t=e,o=n(e);o.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(o.raf),o.raf=0,o.pending=null,o.painted=l(t);const r=t.renderRoot;if(r){for(const e of r.querySelectorAll('[data-hp-live-layer="camera"]'))s(e,null);i(r,o.painted,o.painted)}}(this.host),m(this.host),d(this.host)}dispose(){!function(e){const n=t.get(e);n?.raf&&"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(n.raf),t.delete(e)}(this.host),m(this.host)}}export{p as LiveRuntime};
diff --git a/custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-BnpLzLg7.js b/dist/houseplan-assets/zigbee-topology-C3YPlOFO.js
similarity index 98%
rename from custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-BnpLzLg7.js
rename to dist/houseplan-assets/zigbee-topology-C3YPlOFO.js
index c437e46b..e18783bd 100644
--- a/custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-BnpLzLg7.js
+++ b/dist/houseplan-assets/zigbee-topology-C3YPlOFO.js
@@ -1 +1 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{s as e,F as n}from"./houseplan-card-B_QYG0Py.js";var t={title:"Zigbee links",toggle:"Show Zigbee links when hovering over a device",hint:"Shows observed direct neighbours only. Nothing is fetched while you hover.",help:"Shows which Zigbee devices each device talks to directly. Line colour is link quality (LQI) on the same scale as the device's LQI reading: red at 40 and below, green at 180 and above. A dashed line means quality was not reported. An arrow points to the next device on the way to the coordinator: one arrow leads out, incoming arrows are the devices that route through this one. A line without an arrow is a spare neighbour. This is the route tree House Plan builds, not the path a packet takes right now: a label at the end of an arrow means its target is not on this plan, and no arrow at all means the route is unknown. Data comes from the last load and goes stale; links are shown with a mouse only.",help_aria:"Help: Zigbee links",admin_only:"Topology data is available to Home Assistant administrators only.",save_first:"Save this setting before loading topology data.",zha:"ZHA",zha_read:"Read ZHA data",zha_hint:"Reads ZHA's cached topology; it does not start a radio scan.",z2m:"Zigbee2MQTT",z2m_topics:"Base topics (one per line)",z2m_update:"Update map",z2m_warning:"A network-map scan can take 10 seconds to 2 minutes and may temporarily reduce Zigbee responsiveness.",status_idle:"Data not loaded",status_loading:"Loading…",status_ready:"Received {time}",status_stale:"Received {time} · stale",status_partial:"Received {time} · some nodes were omitted",status_no_links:"Received {time} · no observed links found",error_permission:"Administrator permission is required.",error_unsupported:"This provider or Home Assistant API is unavailable.",error_timeout:"The provider did not respond in time.",error_invalid_topic:"Check the Zigbee2MQTT base topic.",error_invalid_payload:"The provider returned unsupported topology data.",error_provider:"Topology data could not be loaded.",remote_count:"+{n} in other spaces",route_device_not_on_plan:"device is not on the plan",route_coordinator_not_on_plan:"coordinator is not on the plan",route_other_space:"another space"};const i={en:t,ru:{title:"Связи Zigbee",toggle:"Показывать связи Zigbee при наведении на устройство",hint:"Показываются только наблюдаемые прямые соседи. Наведение ничего не запрашивает.",help:"Показывает, с какими устройствами Zigbee каждое связано напрямую. Цвет линии — качество связи (LQI) по той же шкале, что у показателя LQI устройства: красный при 40 и ниже, зелёный при 180 и выше. Пунктир — качество не сообщено. Стрелка ведёт к следующему устройству по пути к координатору: исходящая одна, входящие — те, кто ходит через это устройство. Линия без стрелки — запасной сосед. Это дерево маршрутов, которое строит House Plan, а не путь пакета в эту секунду: подпись на конце стрелки значит, что цель не на этом плане, а отсутствие стрелки — что путь неизвестен. Данные из последней загрузки и устаревают, связи видны только при работе мышью.",help_aria:"Справка: связи Zigbee",admin_only:"Данные топологии доступны только администраторам Home Assistant.",save_first:"Сохраните настройку перед загрузкой данных топологии.",zha:"ZHA",zha_read:"Прочитать данные ZHA",zha_hint:"Читает сохранённую топологию ZHA и не запускает радио-сканирование.",z2m:"Zigbee2MQTT",z2m_topics:"Базовые топики (по одному в строке)",z2m_update:"Обновить карту",z2m_warning:"Сканирование карты сети занимает от 10 секунд до 2 минут и временно может снизить отзывчивость Zigbee.",status_idle:"Данные не загружены",status_loading:"Загрузка…",status_ready:"Получено: {time}",status_stale:"Получено: {time} · данные устарели",status_partial:"Получено: {time} · часть узлов не показана",status_no_links:"Получено: {time} · наблюдаемые связи не найдены",error_permission:"Нужны права администратора.",error_unsupported:"Провайдер или API Home Assistant недоступен.",error_timeout:"Провайдер не ответил вовремя.",error_invalid_topic:"Проверьте базовый топик Zigbee2MQTT.",error_invalid_payload:"Провайдер вернул неподдерживаемые данные топологии.",error_provider:"Не удалось загрузить данные топологии.",remote_count:"+{n} в других пространствах",route_device_not_on_plan:"устройства нет на плане",route_coordinator_not_on_plan:"координатора нет на плане",route_other_space:"другое пространство"},de:{title:"Zigbee-Verbindungen",toggle:"Zigbee-Verbindungen beim Darüberfahren über ein Gerät anzeigen",hint:"Es werden nur beobachtete direkte Nachbarn angezeigt. Beim Darüberfahren werden keine Daten abgerufen.",help:"Zeigt, mit welchen Zigbee-Geräten jedes Gerät direkt verbunden ist. Die Linienfarbe ist die Verbindungsqualität (LQI) auf derselben Skala wie der LQI-Wert des Geräts: rot bei 40 und darunter, grün bei 180 und darüber. Eine gestrichelte Linie bedeutet, dass die Qualität nicht gemeldet wurde. Ein Pfeil zeigt auf das nächste Gerät auf dem Weg zum Koordinator: ein Pfeil führt hinaus, eingehende Pfeile sind die Geräte, die über dieses Gerät routen. Eine Linie ohne Pfeil ist ein Ersatznachbar. Das ist der Routenbaum, den House Plan bildet, nicht der Weg eines Pakets in diesem Moment: eine Beschriftung am Pfeilende bedeutet, dass das Ziel nicht auf diesem Plan liegt, und ein fehlender Pfeil, dass die Route unbekannt ist. Die Daten stammen aus dem letzten Laden und veralten; Verbindungen sind nur mit der Maus sichtbar.",help_aria:"Hilfe: Zigbee-Verbindungen",admin_only:"Topologiedaten sind nur für Home-Assistant-Administratoren verfügbar.",save_first:"Speichere diese Einstellung, bevor Topologiedaten geladen werden.",zha:"ZHA",zha_read:"ZHA-Daten lesen",zha_hint:"Liest den ZHA-Topologiecache; es wird kein Funkscan gestartet.",z2m:"Zigbee2MQTT",z2m_topics:"Basistopics (eines pro Zeile)",z2m_update:"Karte aktualisieren",z2m_warning:"Ein Netzwerkscan kann 10 Sekunden bis 2 Minuten dauern und Zigbee vorübergehend verlangsamen.",status_idle:"Daten nicht geladen",status_loading:"Wird geladen…",status_ready:"Empfangen: {time}",status_stale:"Empfangen: {time} · veraltet",status_partial:"Empfangen: {time} · einige Knoten fehlen",status_no_links:"Empfangen: {time} · keine beobachteten Verbindungen gefunden",error_permission:"Administratorrechte sind erforderlich.",error_unsupported:"Dieser Anbieter oder die Home-Assistant-API ist nicht verfügbar.",error_timeout:"Der Anbieter hat nicht rechtzeitig geantwortet.",error_invalid_topic:"Prüfe das Zigbee2MQTT-Basistopic.",error_invalid_payload:"Der Anbieter hat nicht unterstützte Topologiedaten geliefert.",error_provider:"Topologiedaten konnten nicht geladen werden.",remote_count:"+{n} in anderen Bereichen",route_device_not_on_plan:"Gerät ist nicht im Plan",route_coordinator_not_on_plan:"Koordinator ist nicht im Plan",route_other_space:"anderer Bereich"},fr:{title:"Liens Zigbee",toggle:"Afficher les liens Zigbee au survol d’un appareil",hint:"Seuls les voisins directs observés sont affichés. Le survol ne lance aucune requête.",help:"Montre avec quels appareils Zigbee chaque appareil communique directement. La couleur de la ligne est la qualité du lien (LQI) sur la même échelle que l'indicateur LQI de l'appareil : rouge à 40 et en dessous, vert à 180 et au-dessus. Une ligne pointillée signifie que la qualité n'a pas été communiquée. Une flèche pointe vers l'appareil suivant sur le chemin du coordinateur : une flèche part, les flèches entrantes sont les appareils qui passent par celui-ci. Une ligne sans flèche est un voisin de secours. C'est l'arbre de routes que construit House Plan, pas le trajet d'un paquet à cet instant : une étiquette au bout d'une flèche signifie que sa cible n'est pas sur ce plan, et l'absence de flèche que la route est inconnue. Les données proviennent du dernier chargement et vieillissent ; les liens ne sont visibles qu'à la souris.",help_aria:"Aide : liens Zigbee",admin_only:"Les données de topologie sont réservées aux administrateurs Home Assistant.",save_first:"Enregistrez ce réglage avant de charger les données de topologie.",zha:"ZHA",zha_read:"Lire les données ZHA",zha_hint:"Lit la topologie en cache de ZHA sans lancer d’analyse radio.",z2m:"Zigbee2MQTT",z2m_topics:"Topics de base (un par ligne)",z2m_update:"Actualiser la carte",z2m_warning:"L’analyse de la carte réseau peut durer de 10 secondes à 2 minutes et réduire temporairement la réactivité de Zigbee.",status_idle:"Données non chargées",status_loading:"Chargement…",status_ready:"Reçu : {time}",status_stale:"Reçu : {time} · obsolète",status_partial:"Reçu : {time} · certains nœuds sont omis",status_no_links:"Reçu : {time} · aucun lien observé trouvé",error_permission:"Les droits administrateur sont requis.",error_unsupported:"Ce fournisseur ou l’API Home Assistant n’est pas disponible.",error_timeout:"Le fournisseur n’a pas répondu à temps.",error_invalid_topic:"Vérifiez le topic de base Zigbee2MQTT.",error_invalid_payload:"Le fournisseur a renvoyé des données de topologie non prises en charge.",error_provider:"Impossible de charger les données de topologie.",remote_count:"+{n} dans d’autres espaces",route_device_not_on_plan:"appareil absent du plan",route_coordinator_not_on_plan:"coordinateur absent du plan",route_other_space:"autre espace"}};function r(e,n){const r=i[e]?.[n]??t[n];return"string"==typeof r&&r.trim().length>0}function o(n,r,o){return e(i[n]?.[r]??t[r]??r,o)}const s=3e5,a=2097152,d=6e3;function l(e){return null!==e&&"object"==typeof e?e:null}function u(e){if("string"!=typeof e&&"number"!=typeof e)return null;let n=String(e).trim().toLowerCase();return n=/^0x[0-9a-f]{16}$/.test(n)?n.slice(2):n.replace(/[:-]/g,""),/^[0-9a-f]{16}$/.test(n)?n:null}function c(e,n,t){return`${e}:${n}:${t}`}function p(e){const n=String(e||"").toLowerCase().replace(/[ _-]/g,"");return n.includes("coordinator")?"coordinator":n.includes("router")?"router":n.includes("enddevice")||"end"===n?"end":"unknown"}const h=["parent","child","sibling","none","previous_child"];function g(e){const n=l(e),t=function(e){const n=Number(e);return Number.isFinite(n)&&n>=0&&n<=255?Math.round(n):void 0}(n?.lqi??n?.linkquality??n?.link_quality),i=function(e){if("number"==typeof e)return h[e];if("string"!=typeof e)return;const n=e.trim().toLowerCase().replace(/[\s_-]+/g,"");return"previouschild"===n?"previous_child":n.slice(0,40)||void 0}(n?.relationship);return{...void 0===t?{}:{lqi:t},...i?{relationship:i}:{}}}function f(e,n){return Array.isArray(e)&&e.length<=n?e:null}function _(e){if("string"==typeof e)return e.length<=a;try{return JSON.stringify(e).length<=a}catch{return!1}}function b(e,n,t,i,r){if(t===i)return void n.push({code:"self_link",nodeKey:t});const o=t=d){t.push({code:"invalid_payload"});break}const n=l(e),i=u(n?.ieee??n?.ieee_address);if(!i){t.push({code:"invalid_payload",nodeKey:s});continue}const a=c("zha","zha",i);r.has(a)||r.set(a,{key:a,ieee:i,role:p(n?.device_type)}),b(o,t,s,a,e)}else null!=n?.neighbors&&t.push({code:"invalid_payload",nodeKey:s})}return{provider:"zha",instanceId:"zha",obtainedAt:n,freshness:"provider-cache",nodes:[...r.values()],links:[...o.values()],warnings:t}}function v(e,n){const t=l(e),i=u(t?.ieeeAddr??t?.ieee_address??t?.ieee??e);if(i)return i;for(const i of[t?.id,t?.networkAddress,t?.network_address,e])if(null!=i){const e=n.get(String(i));if(e)return e}return null}function y(e,t,i=Date.now()){const r=[],o=n(t)||"invalid",s=_(e)?function(e){let n=e;if("string"==typeof n){if(n.length>a)return null;try{n=JSON.parse(n)}catch{return null}}const t=l(n),i=l(t?.data);if(n=i?.value??t?.value??t?.data??n,"string"==typeof n){if(n.length>a)return null;try{n=JSON.parse(n)}catch{return null}}return n}(e):null,h=l(s),g=f(h?.nodes,1e3),m=f(h?.links,d);if(!g||!m)return{provider:"z2m",instanceId:o,obtainedAt:i,freshness:"fresh-scan",nodes:[],links:[],warnings:[{code:"invalid_payload"}]};const y=new Map,k=new Map;for(const e of g){const n=l(e),t=u(n?.ieeeAddr??n?.ieee_address??n?.ieee);if(!t){r.push({code:"invalid_payload"});continue}const i=c("z2m",o,t);y.set(i,{key:i,ieee:t,role:p(n?.type??n?.device_type),..."boolean"==typeof n?.failed?{available:!n.failed}:{}});for(const e of[n?.id,n?.networkAddress,n?.network_address])null!=e&&k.set(String(e),t)}const w=new Map;for(const e of m){const n=l(e),t=u(n?.sourceIeeeAddr)??v(n?.source,k),i=u(n?.targetIeeeAddr)??v(n?.target,k);if(!t||!i){r.push({code:"invalid_payload"});continue}const s=c("z2m",o,t),a=c("z2m",o,i);y.has(s)||y.set(s,{key:s,ieee:t,role:"unknown"}),y.has(a)||y.set(a,{key:a,ieee:i,role:"unknown"}),b(w,r,s,a,e)}return{provider:"z2m",instanceId:o,obtainedAt:i,freshness:"fresh-scan",nodes:[...y.values()],links:[...w.values()],warnings:r}}function k(e){if("string"!=typeof e)return null;const n=u(e);if(n)return n;const t=e.toLowerCase().match(/^zigbee2mqtt(?:_bridge)?_(.+)$/);return t?u(t[1]):null}function w(e,n){if(e.deviceId&&n.devices[e.deviceId])return[e.deviceId];const t=new Set;for(const[i,r]of Object.entries(n.devices)){const n=l(r);(Array.isArray(n?.identifiers)?n.identifiers:[]).some(n=>Array.isArray(n)&&k(n[1])===e.ieee)&&t.add(i)}if(t.size)return[...t];for(const i of Object.values(n.entities)){const n=l(i);"string"==typeof n?.device_id&&"string"==typeof n.unique_id&&(k(n.unique_id)===e.ieee&&t.add(n.device_id))}return[...t]}function z(e){return!e.hidden&&!e.virtual&&"ha_disabled"!==e.bindingStatus?.kind&&"orphaned"!==e.bindingStatus?.kind&&"unverified"!==e.bindingStatus?.kind}function A(e){const n=new Map,t=new Map,i=e.nodes.filter(e=>"coordinator"===e.role).map(e=>e.key).sort();if(1!==i.length)return{distances:n,parents:t};const r=i[0],o=function(e){const n=new Set(e.nodes.map(e=>e.key)),t=new Map;for(const e of[...n].sort())t.set(e,[]);for(const i of[...e.links].sort((e,n)=>`${e.a}\0${e.b}`.localeCompare(`${n.a}\0${n.b}`)))n.has(i.a)&&n.has(i.b)&&(t.get(i.a).push({neighborKey:i.b,observation:i.aToB}),t.get(i.b).push({neighborKey:i.a,observation:i.bToA}));for(const e of t.values())e.sort((e,n)=>e.neighborKey.localeCompare(n.neighborKey));return t}(e);if(!o.has(r))return{distances:n,parents:t};n.set(r,0);const s=[r];for(let e=0;en.get(e)===i-1).sort((e,n)=>{const t="parent"===e.observation?.relationship?1:0,i="parent"===n.observation?.relationship?1:0;if(t!==i)return i-t;const r=e.observation?.lqi??-1;return(n.observation?.lqi??-1)-r||e.neighborKey.localeCompare(n.neighborKey)});r[0]&&t.set(e,r[0].neighborKey)}return{coordinatorKey:r,distances:n,parents:t}}function Z(e,n,t){const i=new Map,r=[];for(const o of e.nodes){if(!1===o.available){r.push({code:"provider_scan_failure",nodeKey:o.key});continue}const e=w(o,t);if(1!==e.length){r.push({code:"unmatched_device",nodeKey:o.key});continue}const s=e[0];let a=n.filter(e=>z(e)&&"device"===e.bindingKind&&e.bindingRef===s);a.length||(a=n.filter(e=>z(e)&&"entity"===e.bindingKind&&!!e.bindingRef&&t.entities[e.bindingRef]?.device_id===s)),1===a.length?i.set(o.key,{markerId:a[0].id,space:a[0].space}):r.push({code:a.length>1?"ambiguous_placement":"unmatched_device",nodeKey:o.key})}return{placements:i,warnings:r}}function T(e,n,t){return e.map(e=>({topology:e,placements:Z(e,n,t).placements,routes:A(e)}))}function q(e,n,t){const i=new Map,r=new Set,o=new Map;let s=0;for(const{topology:a,placements:d,routes:l}of e){const e=new Set([...d].filter(([,e])=>e.markerId===t&&e.space===n).map(([e])=>e));if(e.size){for(const t of e){const e=l.parents.get(t);if(!e)continue;const i=d.get(e);if(i?.space===n)continue;let r;r=i?{kind:"remote-space",spaceId:i.space}:"coordinator"===a.nodes.find(n=>n.key===e)?.role?{kind:"unplaced-coordinator"}:{kind:"unplaced-device"};const s="remote-space"===r.kind?`${r.kind}:${r.spaceId}`:r.kind;o.set(s,r)}for(const o of a.links){const a=e.has(o.a),u=e.has(o.b);if(!a&&!u)continue;const c=a?o.a:o.b,p=a?o.b:o.a,h=d.get(p);if(!h||h.markerId===t){s++;continue}const g=l.parents.get(c)===p;if(h.space!==n){g||r.add(h.markerId);continue}const f=a?o.aToB:o.bToA,_=g?"toward-neighbor":l.parents.get(p)===c?"toward-origin":void 0,b=i.get(h.markerId);b?(void 0===b.line.lqi&&void 0!==f?.lqi&&(b.line.lqi=f.lqi),_&&b.directions.add(_)):i.set(h.markerId,{line:{neighborMarkerId:h.markerId,lqi:f?.lqi},directions:new Set(_?[_]:[])})}}}return{lines:[...i.values()].map(({line:e,directions:n})=>1===n.size?{...e,routeDirection:[...n][0]}:e),remoteCount:r.size,omittedCount:s,parentTargets:[...o.values()]}}export{s as T,T as a,y as b,r as h,Z as m,m as n,q as r,o as t};
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{s as e,F as n}from"./houseplan-card-6Hf8VPda.js";var t={title:"Zigbee links",toggle:"Show Zigbee links when hovering over a device",hint:"Shows observed direct neighbours only. Nothing is fetched while you hover.",help:"Shows which Zigbee devices each device talks to directly. Line colour is link quality (LQI) on the same scale as the device's LQI reading: red at 40 and below, green at 180 and above. A dashed line means quality was not reported. An arrow points to the next device on the way to the coordinator: one arrow leads out, incoming arrows are the devices that route through this one. A line without an arrow is a spare neighbour. This is the route tree House Plan builds, not the path a packet takes right now: a label at the end of an arrow means its target is not on this plan, and no arrow at all means the route is unknown. Data comes from the last load and goes stale; links are shown with a mouse only.",help_aria:"Help: Zigbee links",admin_only:"Topology data is available to Home Assistant administrators only.",save_first:"Save this setting before loading topology data.",zha:"ZHA",zha_read:"Read ZHA data",zha_hint:"Reads ZHA's cached topology; it does not start a radio scan.",z2m:"Zigbee2MQTT",z2m_topics:"Base topics (one per line)",z2m_update:"Update map",z2m_warning:"A network-map scan can take 10 seconds to 2 minutes and may temporarily reduce Zigbee responsiveness.",status_idle:"Data not loaded",status_loading:"Loading…",status_ready:"Received {time}",status_stale:"Received {time} · stale",status_partial:"Received {time} · some nodes were omitted",status_no_links:"Received {time} · no observed links found",error_permission:"Administrator permission is required.",error_unsupported:"This provider or Home Assistant API is unavailable.",error_timeout:"The provider did not respond in time.",error_invalid_topic:"Check the Zigbee2MQTT base topic.",error_invalid_payload:"The provider returned unsupported topology data.",error_provider:"Topology data could not be loaded.",remote_count:"+{n} in other spaces",route_device_not_on_plan:"device is not on the plan",route_coordinator_not_on_plan:"coordinator is not on the plan",route_other_space:"another space"};const i={en:t,ru:{title:"Связи Zigbee",toggle:"Показывать связи Zigbee при наведении на устройство",hint:"Показываются только наблюдаемые прямые соседи. Наведение ничего не запрашивает.",help:"Показывает, с какими устройствами Zigbee каждое связано напрямую. Цвет линии — качество связи (LQI) по той же шкале, что у показателя LQI устройства: красный при 40 и ниже, зелёный при 180 и выше. Пунктир — качество не сообщено. Стрелка ведёт к следующему устройству по пути к координатору: исходящая одна, входящие — те, кто ходит через это устройство. Линия без стрелки — запасной сосед. Это дерево маршрутов, которое строит House Plan, а не путь пакета в эту секунду: подпись на конце стрелки значит, что цель не на этом плане, а отсутствие стрелки — что путь неизвестен. Данные из последней загрузки и устаревают, связи видны только при работе мышью.",help_aria:"Справка: связи Zigbee",admin_only:"Данные топологии доступны только администраторам Home Assistant.",save_first:"Сохраните настройку перед загрузкой данных топологии.",zha:"ZHA",zha_read:"Прочитать данные ZHA",zha_hint:"Читает сохранённую топологию ZHA и не запускает радио-сканирование.",z2m:"Zigbee2MQTT",z2m_topics:"Базовые топики (по одному в строке)",z2m_update:"Обновить карту",z2m_warning:"Сканирование карты сети занимает от 10 секунд до 2 минут и временно может снизить отзывчивость Zigbee.",status_idle:"Данные не загружены",status_loading:"Загрузка…",status_ready:"Получено: {time}",status_stale:"Получено: {time} · данные устарели",status_partial:"Получено: {time} · часть узлов не показана",status_no_links:"Получено: {time} · наблюдаемые связи не найдены",error_permission:"Нужны права администратора.",error_unsupported:"Провайдер или API Home Assistant недоступен.",error_timeout:"Провайдер не ответил вовремя.",error_invalid_topic:"Проверьте базовый топик Zigbee2MQTT.",error_invalid_payload:"Провайдер вернул неподдерживаемые данные топологии.",error_provider:"Не удалось загрузить данные топологии.",remote_count:"+{n} в других пространствах",route_device_not_on_plan:"устройства нет на плане",route_coordinator_not_on_plan:"координатора нет на плане",route_other_space:"другое пространство"},de:{title:"Zigbee-Verbindungen",toggle:"Zigbee-Verbindungen beim Darüberfahren über ein Gerät anzeigen",hint:"Es werden nur beobachtete direkte Nachbarn angezeigt. Beim Darüberfahren werden keine Daten abgerufen.",help:"Zeigt, mit welchen Zigbee-Geräten jedes Gerät direkt verbunden ist. Die Linienfarbe ist die Verbindungsqualität (LQI) auf derselben Skala wie der LQI-Wert des Geräts: rot bei 40 und darunter, grün bei 180 und darüber. Eine gestrichelte Linie bedeutet, dass die Qualität nicht gemeldet wurde. Ein Pfeil zeigt auf das nächste Gerät auf dem Weg zum Koordinator: ein Pfeil führt hinaus, eingehende Pfeile sind die Geräte, die über dieses Gerät routen. Eine Linie ohne Pfeil ist ein Ersatznachbar. Das ist der Routenbaum, den House Plan bildet, nicht der Weg eines Pakets in diesem Moment: eine Beschriftung am Pfeilende bedeutet, dass das Ziel nicht auf diesem Plan liegt, und ein fehlender Pfeil, dass die Route unbekannt ist. Die Daten stammen aus dem letzten Laden und veralten; Verbindungen sind nur mit der Maus sichtbar.",help_aria:"Hilfe: Zigbee-Verbindungen",admin_only:"Topologiedaten sind nur für Home-Assistant-Administratoren verfügbar.",save_first:"Speichere diese Einstellung, bevor Topologiedaten geladen werden.",zha:"ZHA",zha_read:"ZHA-Daten lesen",zha_hint:"Liest den ZHA-Topologiecache; es wird kein Funkscan gestartet.",z2m:"Zigbee2MQTT",z2m_topics:"Basistopics (eines pro Zeile)",z2m_update:"Karte aktualisieren",z2m_warning:"Ein Netzwerkscan kann 10 Sekunden bis 2 Minuten dauern und Zigbee vorübergehend verlangsamen.",status_idle:"Daten nicht geladen",status_loading:"Wird geladen…",status_ready:"Empfangen: {time}",status_stale:"Empfangen: {time} · veraltet",status_partial:"Empfangen: {time} · einige Knoten fehlen",status_no_links:"Empfangen: {time} · keine beobachteten Verbindungen gefunden",error_permission:"Administratorrechte sind erforderlich.",error_unsupported:"Dieser Anbieter oder die Home-Assistant-API ist nicht verfügbar.",error_timeout:"Der Anbieter hat nicht rechtzeitig geantwortet.",error_invalid_topic:"Prüfe das Zigbee2MQTT-Basistopic.",error_invalid_payload:"Der Anbieter hat nicht unterstützte Topologiedaten geliefert.",error_provider:"Topologiedaten konnten nicht geladen werden.",remote_count:"+{n} in anderen Bereichen",route_device_not_on_plan:"Gerät ist nicht im Plan",route_coordinator_not_on_plan:"Koordinator ist nicht im Plan",route_other_space:"anderer Bereich"},fr:{title:"Liens Zigbee",toggle:"Afficher les liens Zigbee au survol d’un appareil",hint:"Seuls les voisins directs observés sont affichés. Le survol ne lance aucune requête.",help:"Montre avec quels appareils Zigbee chaque appareil communique directement. La couleur de la ligne est la qualité du lien (LQI) sur la même échelle que l'indicateur LQI de l'appareil : rouge à 40 et en dessous, vert à 180 et au-dessus. Une ligne pointillée signifie que la qualité n'a pas été communiquée. Une flèche pointe vers l'appareil suivant sur le chemin du coordinateur : une flèche part, les flèches entrantes sont les appareils qui passent par celui-ci. Une ligne sans flèche est un voisin de secours. C'est l'arbre de routes que construit House Plan, pas le trajet d'un paquet à cet instant : une étiquette au bout d'une flèche signifie que sa cible n'est pas sur ce plan, et l'absence de flèche que la route est inconnue. Les données proviennent du dernier chargement et vieillissent ; les liens ne sont visibles qu'à la souris.",help_aria:"Aide : liens Zigbee",admin_only:"Les données de topologie sont réservées aux administrateurs Home Assistant.",save_first:"Enregistrez ce réglage avant de charger les données de topologie.",zha:"ZHA",zha_read:"Lire les données ZHA",zha_hint:"Lit la topologie en cache de ZHA sans lancer d’analyse radio.",z2m:"Zigbee2MQTT",z2m_topics:"Topics de base (un par ligne)",z2m_update:"Actualiser la carte",z2m_warning:"L’analyse de la carte réseau peut durer de 10 secondes à 2 minutes et réduire temporairement la réactivité de Zigbee.",status_idle:"Données non chargées",status_loading:"Chargement…",status_ready:"Reçu : {time}",status_stale:"Reçu : {time} · obsolète",status_partial:"Reçu : {time} · certains nœuds sont omis",status_no_links:"Reçu : {time} · aucun lien observé trouvé",error_permission:"Les droits administrateur sont requis.",error_unsupported:"Ce fournisseur ou l’API Home Assistant n’est pas disponible.",error_timeout:"Le fournisseur n’a pas répondu à temps.",error_invalid_topic:"Vérifiez le topic de base Zigbee2MQTT.",error_invalid_payload:"Le fournisseur a renvoyé des données de topologie non prises en charge.",error_provider:"Impossible de charger les données de topologie.",remote_count:"+{n} dans d’autres espaces",route_device_not_on_plan:"appareil absent du plan",route_coordinator_not_on_plan:"coordinateur absent du plan",route_other_space:"autre espace"}};function r(e,n){const r=i[e]?.[n]??t[n];return"string"==typeof r&&r.trim().length>0}function o(n,r,o){return e(i[n]?.[r]??t[r]??r,o)}const s=3e5,a=2097152,d=6e3;function l(e){return null!==e&&"object"==typeof e?e:null}function u(e){if("string"!=typeof e&&"number"!=typeof e)return null;let n=String(e).trim().toLowerCase();return n=/^0x[0-9a-f]{16}$/.test(n)?n.slice(2):n.replace(/[:-]/g,""),/^[0-9a-f]{16}$/.test(n)?n:null}function c(e,n,t){return`${e}:${n}:${t}`}function p(e){const n=String(e||"").toLowerCase().replace(/[ _-]/g,"");return n.includes("coordinator")?"coordinator":n.includes("router")?"router":n.includes("enddevice")||"end"===n?"end":"unknown"}const h=["parent","child","sibling","none","previous_child"];function g(e){const n=l(e),t=function(e){const n=Number(e);return Number.isFinite(n)&&n>=0&&n<=255?Math.round(n):void 0}(n?.lqi??n?.linkquality??n?.link_quality),i=function(e){if("number"==typeof e)return h[e];if("string"!=typeof e)return;const n=e.trim().toLowerCase().replace(/[\s_-]+/g,"");return"previouschild"===n?"previous_child":n.slice(0,40)||void 0}(n?.relationship);return{...void 0===t?{}:{lqi:t},...i?{relationship:i}:{}}}function f(e,n){return Array.isArray(e)&&e.length<=n?e:null}function _(e){if("string"==typeof e)return e.length<=a;try{return JSON.stringify(e).length<=a}catch{return!1}}function b(e,n,t,i,r){if(t===i)return void n.push({code:"self_link",nodeKey:t});const o=t=d){t.push({code:"invalid_payload"});break}const n=l(e),i=u(n?.ieee??n?.ieee_address);if(!i){t.push({code:"invalid_payload",nodeKey:s});continue}const a=c("zha","zha",i);r.has(a)||r.set(a,{key:a,ieee:i,role:p(n?.device_type)}),b(o,t,s,a,e)}else null!=n?.neighbors&&t.push({code:"invalid_payload",nodeKey:s})}return{provider:"zha",instanceId:"zha",obtainedAt:n,freshness:"provider-cache",nodes:[...r.values()],links:[...o.values()],warnings:t}}function v(e,n){const t=l(e),i=u(t?.ieeeAddr??t?.ieee_address??t?.ieee??e);if(i)return i;for(const i of[t?.id,t?.networkAddress,t?.network_address,e])if(null!=i){const e=n.get(String(i));if(e)return e}return null}function y(e,t,i=Date.now()){const r=[],o=n(t)||"invalid",s=_(e)?function(e){let n=e;if("string"==typeof n){if(n.length>a)return null;try{n=JSON.parse(n)}catch{return null}}const t=l(n),i=l(t?.data);if(n=i?.value??t?.value??t?.data??n,"string"==typeof n){if(n.length>a)return null;try{n=JSON.parse(n)}catch{return null}}return n}(e):null,h=l(s),g=f(h?.nodes,1e3),m=f(h?.links,d);if(!g||!m)return{provider:"z2m",instanceId:o,obtainedAt:i,freshness:"fresh-scan",nodes:[],links:[],warnings:[{code:"invalid_payload"}]};const y=new Map,k=new Map;for(const e of g){const n=l(e),t=u(n?.ieeeAddr??n?.ieee_address??n?.ieee);if(!t){r.push({code:"invalid_payload"});continue}const i=c("z2m",o,t);y.set(i,{key:i,ieee:t,role:p(n?.type??n?.device_type),..."boolean"==typeof n?.failed?{available:!n.failed}:{}});for(const e of[n?.id,n?.networkAddress,n?.network_address])null!=e&&k.set(String(e),t)}const w=new Map;for(const e of m){const n=l(e),t=u(n?.sourceIeeeAddr)??v(n?.source,k),i=u(n?.targetIeeeAddr)??v(n?.target,k);if(!t||!i){r.push({code:"invalid_payload"});continue}const s=c("z2m",o,t),a=c("z2m",o,i);y.has(s)||y.set(s,{key:s,ieee:t,role:"unknown"}),y.has(a)||y.set(a,{key:a,ieee:i,role:"unknown"}),b(w,r,s,a,e)}return{provider:"z2m",instanceId:o,obtainedAt:i,freshness:"fresh-scan",nodes:[...y.values()],links:[...w.values()],warnings:r}}function k(e){if("string"!=typeof e)return null;const n=u(e);if(n)return n;const t=e.toLowerCase().match(/^zigbee2mqtt(?:_bridge)?_(.+)$/);return t?u(t[1]):null}function w(e,n){if(e.deviceId&&n.devices[e.deviceId])return[e.deviceId];const t=new Set;for(const[i,r]of Object.entries(n.devices)){const n=l(r);(Array.isArray(n?.identifiers)?n.identifiers:[]).some(n=>Array.isArray(n)&&k(n[1])===e.ieee)&&t.add(i)}if(t.size)return[...t];for(const i of Object.values(n.entities)){const n=l(i);"string"==typeof n?.device_id&&"string"==typeof n.unique_id&&(k(n.unique_id)===e.ieee&&t.add(n.device_id))}return[...t]}function z(e){return!e.hidden&&!e.virtual&&"ha_disabled"!==e.bindingStatus?.kind&&"orphaned"!==e.bindingStatus?.kind&&"unverified"!==e.bindingStatus?.kind}function A(e){const n=new Map,t=new Map,i=e.nodes.filter(e=>"coordinator"===e.role).map(e=>e.key).sort();if(1!==i.length)return{distances:n,parents:t};const r=i[0],o=function(e){const n=new Set(e.nodes.map(e=>e.key)),t=new Map;for(const e of[...n].sort())t.set(e,[]);for(const i of[...e.links].sort((e,n)=>`${e.a}\0${e.b}`.localeCompare(`${n.a}\0${n.b}`)))n.has(i.a)&&n.has(i.b)&&(t.get(i.a).push({neighborKey:i.b,observation:i.aToB}),t.get(i.b).push({neighborKey:i.a,observation:i.bToA}));for(const e of t.values())e.sort((e,n)=>e.neighborKey.localeCompare(n.neighborKey));return t}(e);if(!o.has(r))return{distances:n,parents:t};n.set(r,0);const s=[r];for(let e=0;en.get(e)===i-1).sort((e,n)=>{const t="parent"===e.observation?.relationship?1:0,i="parent"===n.observation?.relationship?1:0;if(t!==i)return i-t;const r=e.observation?.lqi??-1;return(n.observation?.lqi??-1)-r||e.neighborKey.localeCompare(n.neighborKey)});r[0]&&t.set(e,r[0].neighborKey)}return{coordinatorKey:r,distances:n,parents:t}}function Z(e,n,t){const i=new Map,r=[];for(const o of e.nodes){if(!1===o.available){r.push({code:"provider_scan_failure",nodeKey:o.key});continue}const e=w(o,t);if(1!==e.length){r.push({code:"unmatched_device",nodeKey:o.key});continue}const s=e[0];let a=n.filter(e=>z(e)&&"device"===e.bindingKind&&e.bindingRef===s);a.length||(a=n.filter(e=>z(e)&&"entity"===e.bindingKind&&!!e.bindingRef&&t.entities[e.bindingRef]?.device_id===s)),1===a.length?i.set(o.key,{markerId:a[0].id,space:a[0].space}):r.push({code:a.length>1?"ambiguous_placement":"unmatched_device",nodeKey:o.key})}return{placements:i,warnings:r}}function T(e,n,t){return e.map(e=>({topology:e,placements:Z(e,n,t).placements,routes:A(e)}))}function q(e,n,t){const i=new Map,r=new Set,o=new Map;let s=0;for(const{topology:a,placements:d,routes:l}of e){const e=new Set([...d].filter(([,e])=>e.markerId===t&&e.space===n).map(([e])=>e));if(e.size){for(const t of e){const e=l.parents.get(t);if(!e)continue;const i=d.get(e);if(i?.space===n)continue;let r;r=i?{kind:"remote-space",spaceId:i.space}:"coordinator"===a.nodes.find(n=>n.key===e)?.role?{kind:"unplaced-coordinator"}:{kind:"unplaced-device"};const s="remote-space"===r.kind?`${r.kind}:${r.spaceId}`:r.kind;o.set(s,r)}for(const o of a.links){const a=e.has(o.a),u=e.has(o.b);if(!a&&!u)continue;const c=a?o.a:o.b,p=a?o.b:o.a,h=d.get(p);if(!h||h.markerId===t){s++;continue}const g=l.parents.get(c)===p;if(h.space!==n){g||r.add(h.markerId);continue}const f=a?o.aToB:o.bToA,_=g?"toward-neighbor":l.parents.get(p)===c?"toward-origin":void 0,b=i.get(h.markerId);b?(void 0===b.line.lqi&&void 0!==f?.lqi&&(b.line.lqi=f.lqi),_&&b.directions.add(_)):i.set(h.markerId,{line:{neighborMarkerId:h.markerId,lqi:f?.lqi},directions:new Set(_?[_]:[])})}}}return{lines:[...i.values()].map(({line:e,directions:n})=>1===n.size?{...e,routeDirection:[...n][0]}:e),remoteCount:r.size,omittedCount:s,parentTargets:[...o.values()]}}export{s as T,T as a,y as b,r as h,Z as m,m as n,q as r,o as t};
diff --git a/dist/houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js b/dist/houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js
similarity index 93%
rename from dist/houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js
rename to dist/houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js
index f9b59aba..b0cb0a1f 100644
--- a/dist/houseplan-assets/zigbee-topology-runtime-JzXR8tg6.js
+++ b/dist/houseplan-assets/zigbee-topology-runtime-Cjiy8VeA.js
@@ -1 +1 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";import{n as t,b as n}from"./zigbee-topology-BnpLzLg7.js";import{F as e}from"./houseplan-card-B_QYG0Py.js";const o=new WeakMap;function i(t){const n=function(t){const n=t?.connection||t;return!n||"object"!=typeof n&&"function"!=typeof n?null:n}(t);if(!n)return null;let e=o.get(n);return e||(e={revision:0,topologies:[],states:{},listeners:new Set,inflight:new Map},o.set(n,e)),e}function r(t,n,e){t.states={...t.states,[n]:e},function(t){t.revision++;for(const n of t.listeners)n()}(t)}function s(t){const n=t?.code;if("permission"===n||"unsupported"===n||"timeout"===n||"invalid_topic"===n||"invalid_payload"===n)return n;const e=String(t?.message||"").toLowerCase();return e.includes("unauthor")||e.includes("permission")?"permission":e.includes("unknown_command")||e.includes("not found")?"unsupported":"provider"}function a(t){return Object.assign(new Error(t),{code:t})}function c(t,n,e){const o=t.inflight.get(n);if(o)return o;r(t,n,{phase:"loading"});const i=e().then(n=>{if(!n.nodes.length&&n.warnings.some(t=>"invalid_payload"===t.code))throw a("invalid_payload");!function(t,n){t.topologies=[...t.topologies.filter(t=>!(t.provider===n.provider&&t.instanceId===n.instanceId)),n],r(t,"zha"===n.provider?"zha":`z2m:${n.instanceId}`,{phase:"ready",obtainedAt:n.obtainedAt,partial:n.warnings.length>0})}(t,n)}).catch(e=>{r(t,n,{phase:"error",error:s(e)})}).finally(()=>t.inflight.delete(n));return t.inflight.set(n,i),i}function l(t){const n=i(t);return n?{revision:n.revision,topologies:n.topologies,states:n.states}:{revision:0,topologies:[],states:{}}}function u(t,n){const e=i(t);return e?(e.listeners.add(n),()=>e.listeners.delete(n)):()=>{}}function f(t){if(!0!==t?.user?.is_admin)throw a("permission")}function p(n){const e=i(n);return e?c(e,"zha",async()=>{if(f(n),"function"!=typeof n?.callWS)throw a("unsupported");return t(await n.callWS({type:"zha/devices"}))}):Promise.resolve()}function d(t){return null!==t&&"object"==typeof t?t:null}function h(t){const n=d(t),e=n?.payload??t;if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return null}}async function m(t,n){let e;try{return await Promise.race([t,new Promise((t,o)=>{e=globalThis.setTimeout(()=>o(a("timeout")),Math.max(1,n))})])}finally{void 0!==e&&globalThis.clearTimeout(e)}}function g(t,o,r=15e4){const s=i(t);if(!s)return Promise.resolve();const l=e(o);return c(s,`z2m:${l||String(o)}`,async()=>{if(f(t),!l)throw a("invalid_topic");const e=t.connection,o=e?.subscribeMessage;if("function"!=typeof o||"function"!=typeof t?.callService)throw a("unsupported");const i=function(){const t=globalThis.crypto;return"function"==typeof t?.randomUUID?`houseplan-${t.randomUUID()}`:`houseplan-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),s=Date.now()+Math.max(1,r);let c=!1,u=null,p=null,g=null;const y=new Promise(t=>{u=t}),w=new Promise((t,n)=>{p=t,g=n}),b=[];try{const r=await o.call(e,t=>{!0===d(t)?.retain&&h(t)&&u?.()},{type:"mqtt/subscribe",topic:`${l}/bridge/info`});"function"==typeof r&&b.push(r);const f=await o.call(e,t=>{if(!0===d(t)?.retain)return;const n=h(t);null!==n?n&&function(t){const n=d(t),e=n?.transaction??d(n?.data)?.transaction;return"string"==typeof e||"number"==typeof e?String(e):null}(n)===i&&p?.(n):c&&g?.(a("invalid_payload"))},{type:"mqtt/subscribe",topic:`${l}/bridge/response/networkmap`});"function"==typeof f&&b.push(f),await m(y,Math.min(4e3,Math.max(1,s-Date.now()))),c=!0,await t.callService("mqtt","publish",{topic:`${l}/bridge/request/networkmap`,payload:JSON.stringify({type:"raw",routes:!1,transaction:i}),qos:0,retain:!1});const v=await m(w,s-Date.now()),_=d(v)?.status;if(_&&"ok"!==_)throw a("provider");return n(v,l)}finally{for(const t of b)try{t()}catch{}}})}export{p as readZhaTopology,g as refreshZ2mTopology,u as subscribeZigbeeTopology,l as zigbeeTopologyRuntimeSnapshot};
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";import{n as t,b as n}from"./zigbee-topology-C3YPlOFO.js";import{F as e}from"./houseplan-card-6Hf8VPda.js";const o=new WeakMap;function i(t){const n=function(t){const n=t?.connection||t;return!n||"object"!=typeof n&&"function"!=typeof n?null:n}(t);if(!n)return null;let e=o.get(n);return e||(e={revision:0,topologies:[],states:{},listeners:new Set,inflight:new Map},o.set(n,e)),e}function r(t,n,e){t.states={...t.states,[n]:e},function(t){t.revision++;for(const n of t.listeners)n()}(t)}function s(t){const n=t?.code;if("permission"===n||"unsupported"===n||"timeout"===n||"invalid_topic"===n||"invalid_payload"===n)return n;const e=String(t?.message||"").toLowerCase();return e.includes("unauthor")||e.includes("permission")?"permission":e.includes("unknown_command")||e.includes("not found")?"unsupported":"provider"}function a(t){return Object.assign(new Error(t),{code:t})}function c(t,n,e){const o=t.inflight.get(n);if(o)return o;r(t,n,{phase:"loading"});const i=e().then(n=>{if(!n.nodes.length&&n.warnings.some(t=>"invalid_payload"===t.code))throw a("invalid_payload");!function(t,n){t.topologies=[...t.topologies.filter(t=>!(t.provider===n.provider&&t.instanceId===n.instanceId)),n],r(t,"zha"===n.provider?"zha":`z2m:${n.instanceId}`,{phase:"ready",obtainedAt:n.obtainedAt,partial:n.warnings.length>0})}(t,n)}).catch(e=>{r(t,n,{phase:"error",error:s(e)})}).finally(()=>t.inflight.delete(n));return t.inflight.set(n,i),i}function l(t){const n=i(t);return n?{revision:n.revision,topologies:n.topologies,states:n.states}:{revision:0,topologies:[],states:{}}}function u(t,n){const e=i(t);return e?(e.listeners.add(n),()=>e.listeners.delete(n)):()=>{}}function f(t){if(!0!==t?.user?.is_admin)throw a("permission")}function p(n){const e=i(n);return e?c(e,"zha",async()=>{if(f(n),"function"!=typeof n?.callWS)throw a("unsupported");return t(await n.callWS({type:"zha/devices"}))}):Promise.resolve()}function d(t){return null!==t&&"object"==typeof t?t:null}function h(t){const n=d(t),e=n?.payload??t;if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return null}}async function m(t,n){let e;try{return await Promise.race([t,new Promise((t,o)=>{e=globalThis.setTimeout(()=>o(a("timeout")),Math.max(1,n))})])}finally{void 0!==e&&globalThis.clearTimeout(e)}}function g(t,o,r=15e4){const s=i(t);if(!s)return Promise.resolve();const l=e(o);return c(s,`z2m:${l||String(o)}`,async()=>{if(f(t),!l)throw a("invalid_topic");const e=t.connection,o=e?.subscribeMessage;if("function"!=typeof o||"function"!=typeof t?.callService)throw a("unsupported");const i=function(){const t=globalThis.crypto;return"function"==typeof t?.randomUUID?`houseplan-${t.randomUUID()}`:`houseplan-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}(),s=Date.now()+Math.max(1,r);let c=!1,u=null,p=null,g=null;const y=new Promise(t=>{u=t}),w=new Promise((t,n)=>{p=t,g=n}),b=[];try{const r=await o.call(e,t=>{!0===d(t)?.retain&&h(t)&&u?.()},{type:"mqtt/subscribe",topic:`${l}/bridge/info`});"function"==typeof r&&b.push(r);const f=await o.call(e,t=>{if(!0===d(t)?.retain)return;const n=h(t);null!==n?n&&function(t){const n=d(t),e=n?.transaction??d(n?.data)?.transaction;return"string"==typeof e||"number"==typeof e?String(e):null}(n)===i&&p?.(n):c&&g?.(a("invalid_payload"))},{type:"mqtt/subscribe",topic:`${l}/bridge/response/networkmap`});"function"==typeof f&&b.push(f),await m(y,Math.min(4e3,Math.max(1,s-Date.now()))),c=!0,await t.callService("mqtt","publish",{topic:`${l}/bridge/request/networkmap`,payload:JSON.stringify({type:"raw",routes:!1,transaction:i}),qos:0,retain:!1});const v=await m(w,s-Date.now()),_=d(v)?.status;if(_&&"ok"!==_)throw a("provider");return n(v,l)}finally{for(const t of b)try{t()}catch{}}})}export{p as readZhaTopology,g as refreshZ2mTopology,u as subscribeZigbeeTopology,l as zigbeeTopologyRuntimeSnapshot};
diff --git a/dist/houseplan-card.js b/dist/houseplan-card.js
index c167f81e..6a070b8c 100644
--- a/dist/houseplan-card.js
+++ b/dist/houseplan-card.js
@@ -1 +1 @@
-globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="646efb7cbcc3983509681c3430fa42513ae62445f7606ebb8de7f3967afe4f00";try{await import("./houseplan-assets/houseplan-card-B_QYG0Py.js")}catch(e){if(!customElements.get("houseplan-card")){const l=String(navigator.language||"en").toLowerCase();const m=l.startsWith("ru")?"House Plan обновился — перезагрузите страницу (Ctrl+F5).":l.startsWith("de")?"House Plan wurde aktualisiert — bitte laden Sie die Seite neu (Strg+F5).":l.startsWith("fr")?"House Plan a été mis à jour — veuillez recharger la page (Ctrl+F5).":"House Plan was updated — please reload the page (Ctrl+F5).";customElements.define("houseplan-card",class extends HTMLElement{setConfig(){}getCardSize(){return 1}connectedCallback(){this.style.cssText="display:block;box-sizing:border-box;padding:16px;border:1px solid var(--divider-color,#e0e0e0);border-radius:var(--ha-card-border-radius,12px);background:var(--card-background-color,#fff);color:var(--primary-text-color,#212121);font:14px/1.4 var(--paper-font-body1_-_font-family,sans-serif)";this.textContent=m}})}console.error("[houseplan] stale entry: the main chunk is unavailable",e)}
+globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="5079760604161d9cbfaf7a5bd435ebd0962fb66b7ec87f09c61d43ef34a98c7f";try{await import("./houseplan-assets/houseplan-card-6Hf8VPda.js")}catch(e){if(!customElements.get("houseplan-card")){const l=String(navigator.language||"en").toLowerCase();const m=l.startsWith("ru")?"House Plan обновился — перезагрузите страницу (Ctrl+F5).":l.startsWith("de")?"House Plan wurde aktualisiert — bitte laden Sie die Seite neu (Strg+F5).":l.startsWith("fr")?"House Plan a été mis à jour — veuillez recharger la page (Ctrl+F5).":"House Plan was updated — please reload the page (Ctrl+F5).";customElements.define("houseplan-card",class extends HTMLElement{setConfig(){}getCardSize(){return 1}connectedCallback(){this.style.cssText="display:block;box-sizing:border-box;padding:16px;border:1px solid var(--divider-color,#e0e0e0);border-radius:var(--ha-card-border-radius,12px);background:var(--card-background-color,#fff);color:var(--primary-text-color,#212121);font:14px/1.4 var(--paper-font-body1_-_font-family,sans-serif)";this.textContent=m}})}console.error("[houseplan] stale entry: the main chunk is unavailable",e)}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 713ebacc..0720a016 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -568,6 +568,10 @@ writer entrance.
Active-chain Undo preserves the complete record of every surviving partition,
including its stable ID; only a genuinely new edge receives a new identity.
+Each segment history snapshot carries session-only chain seed IDs. While the
+chain is active the snapshot is literal and Undo removes one point; after
+finish, Undo/Redo passes that seed scope through the same lossless finalizer so
+hidden collinear seams cannot return as durable Optimize debt (#477).
The backend stale-client guard compares only room/compatibility contour geometry
with `wall_segments[]`. Partitions, columns and
explicitly hosted openings own their identity and may be written without a
@@ -850,8 +854,10 @@ boundary so a stale success cannot approve a newer candidate. Marker, title,
colour and other presentation edits bypass this structural check, allowing an
old degraded plan to be exported or corrected without a background migration.
-`reconcileCoincidentPartitions()` is an explicit-Optimize-only structural
-canonicalizer (#276/#296). It consumes canonical room-wall intervals and the
+`reconcileCoincidentPartitions()` is the shared structural canonicalizer
+(#276/#296/#477). Full-space use remains an explicit Optimize operation; the
+current wall-chain writer invokes it only at finish and only for the surviving
+seed component it just authored. It consumes canonical room-wall intervals and the
partition-opening compatibility resolver; it does not implement a second
nearest-wall model. A source axis is atomized at solid interval and opening
boundaries. Exact one-owner outer or two-owner shared spans may be absorbed;
@@ -860,8 +866,9 @@ their hosted openings. Converted openings are materialised onto ordinary room
walls, and `max(roomCm, partitionCm)` keeps the original centred physical union
envelope. Unknown partition semantics, gaps, overlapping openings and adjacent
independent bodies fail closed. The candidate then crosses the existing whole-plan
-geometry preflight and one atomic Optimize write/Undo boundary. No render or
-ordinary save path invokes this pass, so `PLAN_MODEL_VERSION` remains unchanged.
+geometry preflight and one atomic Optimize write/Undo boundary. Render and
+unrelated ordinary save paths never invoke this pass, so `PLAN_MODEL_VERSION`
+remains unchanged.
`OptimizeDependencies` is a narrow test/benchmark seam: production uses the
real helper, while the committed large-house benchmark substitutes a no-op to
measure only this pass and the unit contract instruments its exact per-space
@@ -878,9 +885,15 @@ viewBox, so the editable target does not collapse to the visual one-pixel line.
Every completed Walls segment is persisted immediately as an ordinary
`partition`, including the thickness selected when that segment was placed.
The ordered path, chain id and participating partition ids are session-only.
-Changing Plan tool, editor or floor finishes an open chain by clearing that
-session state; the already accepted walls stay unchanged and re-selecting Walls
-is a no-op.
+Changing Plan tool, editor or floor finishes an open chain through one bounded
+lossless finalizer before clearing that session state. The finalizer repeatedly
+merges only the seed-connected compatible collinear run, rehosts its openings,
+and reconciles only surviving positive seed partitions proven coincident with
+room masonry. Its cloned candidate crosses the current-model identity barrier,
+one local physical/junction proof and storage canonicalization before atomic
+adoption; rejection keeps the visible chain and original config. It adds no
+history command and never sweeps unrelated legacy debt. Esc, Reset, route/hash
+departure and a rejected-all room-face batch share this owner (#477).
Pan, pinch, pointer cancellation and suppressed clicks never finish a chain or
append a segment. A finished open chain is ordinary masonry and is not resumed
after reload or remount.
@@ -935,6 +948,11 @@ openings. Delete-walls cascades only those exclusive openings. Shared walls,
explicit partitions and partition-hosted openings survive. The selected room,
wall profile/open spans, partitions and openings commit in one named geometry
transaction through an accessible `hp-dialog`, never native `confirm()`.
+The same command rewrites room references in every marker: direct `room_id` is
+deleted (or remapped to the survivor for Merge), and exact values in cross-space
+`vacuum.segment_map` are deleted/remapped. History snapshots only these room
+fields, so Undo/Redo and write rollback are atomic with geometry while unrelated
+marker and vacuum fields remain live (#477).
While drawing, the length of the current segment follows the cursor (`_fmtLen` → `segmentCm`/
`formatLength`): metres, or feet+inches when `hass.config.unit_system` is imperial. The scale is
diff --git a/docs/CANVAS.md b/docs/CANVAS.md
index 74c91b43..97e3fdc5 100644
--- a/docs/CANVAS.md
+++ b/docs/CANVAS.md
@@ -585,6 +585,13 @@ either store changes, commits both revisions, and retains one snapshot.
has changed since the optimization. A crash between store writes is
completed from the intent on the next integration setup.
+The grid pass deliberately excludes the complete transform of `furniture` and
+uploaded `image` decor. Their position, size and rotation are continuously
+authored values (#383), so changing even one of those fields would make
+Optimize create debt from a normal editor operation. Other decor kinds and
+storage-level numeric canonicalization keep their existing grid contract
+(#477).
+
The pair returned by `optimizePlans` passes the same lattice-aware boundary as
the storage writers **before** visible Align and before `changed` is computed.
This boundary is required because the normalized grid step `1 / 240` has no
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 7c1dfcf1..b79d08c8 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -11,6 +11,11 @@
specially resumed after a reload; legacy saved outlines migrate safely to
the new model, and walls consumed by a newly created room no longer remain as
duplicate masonry ([#478](https://github.com/Matysh/houseplan-card/issues/478)).
+- Finished wall chains now merge their own compatible straight sections and
+ reconcile proven duplicate masonry immediately. Room Delete/Merge keeps
+ device and cross-floor vacuum room references consistent through Undo/Redo,
+ while Optimize preserves smooth furniture and image transforms
+ ([#477](https://github.com/Matysh/houseplan-card/issues/477)).
## v1.73.0-beta.1 — 2026-09-06
diff --git a/docs/CHANGELOG.ru.md b/docs/CHANGELOG.ru.md
index 82ef60a2..74ad1d1e 100755
--- a/docs/CHANGELOG.ru.md
+++ b/docs/CHANGELOG.ru.md
@@ -18,6 +18,11 @@
безопасно мигрируют в новую модель, а поглощённые созданной комнатой стены не
остаются дубликатами кладки
([#478](https://github.com/Matysh/houseplan-card/issues/478)).
+- Завершённая цепочка стен теперь сразу объединяет собственные совместимые
+ прямые участки и устраняет доказанно дублирующую кладку. Удаление и объединение
+ комнат согласованно обновляет привязки устройств и межэтажные карты пылесоса
+ через Undo/Redo, а оптимизация сохраняет плавные трансформации мебели и
+ изображений ([#477](https://github.com/Matysh/houseplan-card/issues/477)).
## v1.73.0-beta.1 — 2026-09-06
diff --git a/docs/STATUS.md b/docs/STATUS.md
index cd852d54..e2ece5f3 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -22,7 +22,7 @@ metadata). Only an explicit owner-approved emergency hotfix may skip this gate.
| Item | State |
|---|---|
| Version | **v1.73.0-beta.1** everywhere (manifest, const.py, package.json, CARD_VERSION) |
-| Current local cycle | v1.73.0-beta.1 keeps active Zigbee topology readable above room names and unrelated markers while preserving linked-device markers on top (#464). The following hidden-alpha correction removes painted rectangular plates around raised device, room and lock overlays while retaining their invisible collision/fit footprint (#471). Publish from `dev` only after exact-SHA Validate is green; `main` remains at v1.72.0. |
+| Current local cycle | v1.73.0-beta.1 keeps active Zigbee topology readable above room names and unrelated markers while preserving linked-device markers on top (#464). Unreleased work removes painted rectangular plates around raised device, room and lock overlays while retaining their invisible collision/fit footprint (#471), and makes completed editor writers converge with Optimize: bounded wall-chain finish, room-reference transactions and continuous furniture/image transforms (#477, building on #478). Publish from `dev` only after exact-SHA Validate is green; `main` remains at v1.72.0. |
| Hidden Alpha Stage | #89 Stage 1 ships in v1.63.0-beta.1, #122 Stage 2 in v1.64.0 and #160 Stage 3 in v1.73.0-beta.1. The same hidden `iso` view uses the fixed 4° camera, raised/tethered device-room-lock overlays, deeper openings and bounded theme materials; #471 removes the overlay plates from paint while retaining their safety geometry. Since #448 the experiment is enabled only through the single indefinite browser-local `hp_alpha` gate; it is not expiring and has no per-stage key. Flat remains default; editors, `houseplan-space-card`, floor effects, stored coordinates and HA actions remain unchanged. Stage 3 stays internal and is absent from public changelog/user documentation. |
| Workflow | Superseded 2026-08-12: the pre-1.62 rule of "local edits without tests or commits" is **dead** — since release 1.62 every product change follows `PROCESS.md` (issue in `S5-ready`+, branch `issue/-slug`, trailers on every commit, review pipeline; `AGENTS.md` is the summary). Release mechanics below remain current. A requested pre-release gets a production build plus the smallest targeted unit/smoke set covering the changed surfaces, one tested `dev` commit/tag and a GitHub Release with `prerelease=true`; `main` stays untouched. The complete local frontend/backend/smoke gate runs only before a stable release, after which `main` is fast-forwarded to the exact tested `dev` SHA and the GitHub Release uses `prerelease=false`. Release bodies are short and bilingual (Russian first); every bullet links its GitHub issue (#NN) so the #328 rules stay machine-checkable. A STABLE body aggregates the changelog since the PREVIOUS STABLE release (never since the last beta): features/fixes described across the line's beta changelogs must appear, while bugs that were introduced and fixed strictly inside the beta line (never shipped in any stable) are excluded — draft with `npm run release:notes -- `, curate by hand, then `npm run release:notes -- --verify` must pass. `Мелкие исправления и улучшения` / `Small fixes and improvements` is allowed only when the range really contains user-visible work not itemised in the body; a single-issue hotfix ships without it (the verifier enforces this). Every body ends with separate links to the Russian and English changelogs. Open or partially delivered issues are never presented as shipped. Telegram announcements are sent only for stable releases; beta and RC publication is silent. `docs/RELEASE-NOTES.md` is the current canonical body instance; `npm run release:prerelease -- --issues=… --yes` is the primary local publication path and the manual `Publish prerelease` workflow is its GitHub-only equivalent once present on `main`. Nothing is copied to the home instance by hand |
| GitHub | https://github.com/Matysh/houseplan-card — [Issues](https://github.com/Matysh/houseplan-card/issues) are the canonical task records; their labels carry priority and workflow status (`PROCESS.md` §9). GitHub Projects is no longer used. `main` carries stable releases; pre-release tags may point directly at `dev`. Work lands on `dev` and is merged into `main` for a stable release, so `dev` is normally equal to or ahead of `main`, never behind. Push via SSH key `ha_jb` (remote git@github.com:…); API releases via the fine-grained PAT in `~/.git-credentials` (Contents R/W, issued 2026-07-23) |
@@ -91,7 +91,10 @@ metadata). Only an explicit owner-approved emergency hotfix may skip this gate.
dashed/solid selector controls both line style and Glow/sun transmission.
It also converts persisted unfinished contours to ordinary partitions; new
wall-chain segments are partitions from the first accepted click and chain
- state is session-only. Zero walls have no body, area or opening host, and
+ state is session-only. A finished chain losslessly merges/reconciles its own
+ seed component and finished-chain Undo/Redo restores the same fixed point;
+ room Delete/Merge owns direct and vacuum room-reference cleanup (#477).
+ Zero walls have no body, area or opening host, and
there is no Boundary tool.
- **Rooms**: room cards with metrics (temp/hum/lqi/light "1 of 3") and
proportional resize (v1.31); link icon to the HA area (v1.40.1, room taps
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 33f1da3f..13b85901 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -176,6 +176,29 @@
- [ ] Mutation `room-accept-leaves-coincident-partitions` proves the real editor
smoke fails if accepted room carriers stop being consumed atomically.
+## Current-writer fixed point (#477)
+
+- [ ] `test/writer-fixed-point.test.mjs` proves seed-bounded repeated collinear
+ merge, safe positive coincident reconciliation/opening rehost, identical
+ fail-closed cases, exact room-reference rewrite/restore and the executable
+ writer-owner manifest.
+- [ ] `demo/smoke_writer_fixed_point.mjs` finishes a real straight Walls chain
+ through the production bundle, then proves the immediate, post-Undo and
+ post-Redo Optimize previews are no-ops. The same smoke deletes a room and
+ restores/reapplies direct and cross-space vacuum references without
+ overwriting unrelated marker fields.
+- [ ] `demo/benchmark_wall_draw_click.mjs` keeps the #461 terminal-click budgets
+ and structural counters, then separately proves finish uses one bounded
+ physical/junction transaction, one write, no extra history and sublinear
+ scaling when unrelated rooms are added.
+- [ ] `test/align-grid.test.mjs` proves Optimize leaves complete furniture/image
+ transforms byte-equivalent while an ordinary decor rectangle remains
+ grid-bound.
+- [ ] The `writer-*` mutations in `scripts/mutation-gate.mjs` remove one finish
+ owner, pre-adoption safety, history normalization, direct/vacuum reference
+ rewrite, free-transform exclusion, terminal-click separation, seed merge
+ and seed reconciliation; each named witness must turn red.
+
## Resize: реальный pointer pipeline (#293)
- [ ] `demo/smoke_resize_pointer_real_plan.mjs` загружает tracked fixture
diff --git a/docs/USER-GUIDE.md b/docs/USER-GUIDE.md
index ac2f60f7..7a013f38 100644
--- a/docs/USER-GUIDE.md
+++ b/docs/USER-GUIDE.md
@@ -408,7 +408,12 @@ but become unplaced. Plan images and attachments are not deleted automatically.
Select **Walls** and draw one continuous chain. Every completed segment is
saved immediately as an ordinary independent wall. Changing tool, editor,
-floor, leaving the card or reloading only ends the session-local chain. When the
+floor or leaving the card finishes the session-local chain: compatible straight
+sections become one wall and a proven duplicate over room masonry is absorbed
+immediately. Undo/Redo remains segment-by-segment but restores a canonical
+result, so a normal current-version chain leaves no work for **Optimize plans**.
+Reloading preserves the accepted walls but cannot finish the interrupted
+session. When the
latest segment creates bounded endpoint/T/X faces, House Plan offers them from
smallest to largest. Save creates that room and consumes exactly coincident
chain walls, Keep as walls rejects only that candidate, and Cancel leaves all
@@ -449,6 +454,12 @@ Other operations edit existing geometry:

+Deleting a room also clears that exact room from direct device assignments and
+vacuum segment maps, including maps owned by a vacuum on another floor.
+Merging rooms redirects the same references to the surviving room. The change
+is part of the room command: Undo and Redo restore or reapply geometry and
+references together without changing unrelated marker settings.
+
Wall thickness is stored in real units. A room may have different thicknesses
on different spans. Open wall branches and T-junctions are allowed; shared
geometry remains joined without painted end caps. At a saved T-junction both
@@ -834,6 +845,8 @@ item. Rotation is smooth and `Shift` snaps it to 45°; signed size fields and
the two mirror checkboxes provide the same result numerically. Furniture is
selected within 10 physical centimetres of its drawn strokes, not throughout
its empty bounding box.
+**Optimize plans** preserves the complete smooth position, size and rotation of
+furniture and uploaded images; these authored transforms are not grid debt.
The plan image is interactive only with Backdrop selected. Undo/Redo shares the
50-command editor history.
diff --git a/docs/USER-GUIDE.ru.md b/docs/USER-GUIDE.ru.md
index a2bd0c4a..8a231320 100644
--- a/docs/USER-GUIDE.ru.md
+++ b/docs/USER-GUIDE.ru.md
@@ -550,10 +550,15 @@ Undo оптимизации.
Каждый законченный отрезок цепочки сохраняется сразу. `Esc` завершает принятые
отрезки как независимые стены, оставляет инструмент **Стены** активным и
-отцепляется от последней точки; следующий клик начинает новую цепочку.
+отцепляется от последней точки; совместимые прямые участки становятся одной
+стеной, а доказанный дубликат поверх кладки комнаты сразу поглощается. Следующий
+клик начинает новую цепочку.
`Ctrl/Cmd+Z` вместо этого удаляет последнюю точку и отрезок. Pan, pinch и
`pointercancel` ничего не завершают и не добавляют. После перезагрузки стены
-остаются на плане, но цепочка не возобновляется автоматически.
+остаются на плане, но цепочка не возобновляется автоматически. После обычного
+завершения Undo/Redo по-прежнему работает по отрезкам, однако восстанавливает
+канонический результат: цепочка текущей версии не оставляет работу для команды
+**«Оптимизировать планы»**.
### Ограничения стыков стен
@@ -618,6 +623,10 @@ Undo оптимизации.
явная совпадающая перегородка и их проёмы сохраняются. Оставшиеся записи
толщины нормализуются уже по новому составу комнат: одинаковая толщина не
склеивается через переход «общая ↔ наружная» или между разными парами комнат.
+Удаление также убирает именно эту комнату из прямых привязок устройств и карт
+сегментов пылесоса, даже если пылесос находится на другом этаже. Объединение
+переводит те же ссылки на оставшуюся комнату. Undo/Redo восстанавливает или
+повторяет геометрию и ссылки вместе, не затрагивая прочие настройки маркеров.

@@ -1389,7 +1398,7 @@ Power=`off`/`unavailable` подавляет даже устаревший ак
| Изображение | Загрузка PNG/JPEG/WebP/SVG или выбор ранее загруженного файла, затем клик | Плавный размер, отражение по горизонтали/вертикали, прозрачность, угол и замена файла; без магнита к стене |
| Стереть | Клик по объекту | После подтверждения удаляет объект; действие можно отменить через Undo |
-Новые фигуры создаются не меньше половины клетки. После создания объект остаётся выбранным. Создание, движение и изменение размера обычного декора квантуются по сетке. Resize мебели — исключение: углы двигаются плавно и по умолчанию сохраняют пропорции (`Shift` разрешает разные оси), а четыре средние ручки меняют только одну ось. Переход через противоположную грань зеркалит предмет. Поворот плавный, с `Shift` привязывается к 45°. Знаковые размеры и две галочки отражения в свойствах дают тот же результат численно. Выбрать мебель можно в пределах физических 10 см от её нарисованных линий, но не по всей пустой рамке. При рисовании и перемещении действует лёгкий магнит к углам, серединам, центрам и рёбрам других объектов декора и комнат; устройства, проёмы и картинка-подложка не являются целями магнита.
+Новые фигуры создаются не меньше половины клетки. После создания объект остаётся выбранным. Создание, движение и изменение размера обычного декора квантуются по сетке. Resize мебели — исключение: углы двигаются плавно и по умолчанию сохраняют пропорции (`Shift` разрешает разные оси), а четыре средние ручки меняют только одну ось. Переход через противоположную грань зеркалит предмет. Поворот плавный, с `Shift` привязывается к 45°. Знаковые размеры и две галочки отражения в свойствах дают тот же результат численно. Выбрать мебель можно в пределах физических 10 см от её нарисованных линий, но не по всей пустой рамке. Команда **«Оптимизировать планы»** сохраняет целиком плавные координаты, размер и поворот мебели и загруженных изображений: такие авторские трансформации не считаются отклонением от сетки. При рисовании и перемещении действует лёгкий магнит к углам, серединам, центрам и рёбрам других объектов декора и комнат; устройства, проёмы и картинка-подложка не являются целями магнита.
В инструменте **«Выбрать»** клавиши-стрелки сдвигают выбранную линию, фигуру,
надпись, мебель или пользовательское изображение ровно на одну текущую клетку
diff --git a/scripts/mutation-gate.mjs b/scripts/mutation-gate.mjs
index 4e50092c..68182714 100644
--- a/scripts/mutation-gate.mjs
+++ b/scripts/mutation-gate.mjs
@@ -1281,12 +1281,14 @@ const MUTANT_DEFINITIONS = [
find: ' try { valid = input.validatePreview(accepted.preview); } catch { valid = false; }',
replace: ' try { valid = true; } catch { valid = false; }',
}, {
- file: 'src/houseplan-card.ts',
+ file: 'src/houseplan-editor-runtime.ts',
find: ' if (!legacySafe) {',
replace: ' if (false && !legacySafe) {',
}, {
- file: 'src/houseplan-card.ts',
- find: ' && this._checkSpacePhysicalGeometry(committedCandidate, before.spaceId).ok;',
+ file: 'src/houseplan-editor-runtime.ts',
+ find: ' && this.host._checkSpacePhysicalGeometry(\n'
+ + ' physicalCandidateFor(committedCandidate), before.spaceId,\n'
+ + ' ).ok;',
replace: ' && true;',
}],
},
@@ -1296,32 +1298,7 @@ const MUTANT_DEFINITIONS = [
because: 'write-time wall degradation must not erase the one Resize Undo command; '
+ 'the strict outbound barrier remains authoritative after the local restore (#293)',
patches: [{
- file: 'src/houseplan-card.ts',
- find: ' const physicalChanged = spacePhysicalGeometryFingerprint(before)\n'
- + ' !== spacePhysicalGeometryFingerprint(state);\n'
- + ' if (physicalChanged) {\n'
- + ' let safe = false;\n'
- + ' try {\n'
- + ' const check = restoredCandidate\n'
- + ' ? this._checkSpacePhysicalGeometry(restoredCandidate, state.spaceId)\n'
- + ' : null;\n'
- + " safe = !!check?.ok || !!(allowHistoryBoundaryRepair\n"
- + " && check?.reason === 'wall-degraded-extra');\n"
- + ' } catch { safe = false; }\n'
- + ' if (!safe) {',
- replace: ' const physicalChanged = spacePhysicalGeometryFingerprint(before)\n'
- + ' !== spacePhysicalGeometryFingerprint(state);\n'
- + ' if (physicalChanged) {\n'
- + ' let safe = false;\n'
- + ' try {\n'
- + ' const check = restoredCandidate\n'
- + ' ? this._checkSpacePhysicalGeometry(restoredCandidate, state.spaceId)\n'
- + ' : null;\n'
- + ' safe = !!check?.ok;\n'
- + ' } catch { safe = false; }\n'
- + ' if (!safe) {',
- }, {
- file: 'src/houseplan-card.ts',
+ file: 'src/houseplan-editor-runtime.ts',
find: " // A history snapshot can predate the write-time wall degradation that\n"
+ " // canonicalized its command. Restore that one repairable baseline so\n"
+ " // Undo remains byte-exact immediately; _writeConfig still degrades and\n"
@@ -2550,9 +2527,23 @@ const MUTANT_DEFINITIONS = [
+ 'gesture is cleared, otherwise the invalid point survives without history or a write (#461 AC6)',
patches: [{
file: 'src/draft-live-commit.ts',
- find: ' if (introduced.length) {\n runtime._clearGeometryGesture();\n'
- + ' runtime._restoreGeometryStateLocal(before);',
- replace: ' if (introduced.length) {\n runtime._clearGeometryGesture();',
+ find: ' if (introduced.length) {\n'
+ + ' runtime._clearGeometryGesture();\n'
+ + ' runtime._restoreGeometryStateLocal(before);\n'
+ + ' host._showToast(runtime._junctionLimitLabel(introduced[0]));\n'
+ + ' return false;\n'
+ + ' }\n\n'
+ + ' adoptWallSegmentModelCandidateInPlace(liveCandidate, committedCandidate);\n'
+ + ' const acceptedSpace = liveCandidate.spaces.find((space) => space.id === before.spaceId);\n'
+ + ' const accepted = acceptedSpace?.partitions?.find((partition) => partition.id === partitionId);',
+ replace: ' if (introduced.length) {\n'
+ + ' runtime._clearGeometryGesture();\n'
+ + ' host._showToast(runtime._junctionLimitLabel(introduced[0]));\n'
+ + ' return false; // mutant: rejected segment survives\n'
+ + ' }\n\n'
+ + ' adoptWallSegmentModelCandidateInPlace(liveCandidate, committedCandidate);\n'
+ + ' const acceptedSpace = liveCandidate.spaces.find((space) => space.id === before.spaceId);\n'
+ + ' const accepted = acceptedSpace?.partitions?.find((partition) => partition.id === partitionId);',
}],
},
{
@@ -2562,8 +2553,28 @@ const MUTANT_DEFINITIONS = [
+ 'the junction pass; discarding it repays the expensive union on every click (#461 AC5)',
patches: [{
file: 'src/draft-live-commit.ts',
- find: ' localCandidate, localPrevious, before.spaceId, geometry, candidateProjection.roomIds,',
- replace: ' localCandidate, localPrevious, before.spaceId, null, candidateProjection.roomIds,',
+ find: ' localCandidate, localPrevious, before.spaceId, geometry, candidateProjection.roomIds,\n'
+ + ' );\n'
+ + ' if (introduced.length) {\n'
+ + ' runtime._clearGeometryGesture();\n'
+ + ' runtime._restoreGeometryStateLocal(before);\n'
+ + ' host._showToast(runtime._junctionLimitLabel(introduced[0]));\n'
+ + ' return false;\n'
+ + ' }\n\n'
+ + ' adoptWallSegmentModelCandidateInPlace(liveCandidate, committedCandidate);\n'
+ + ' const acceptedSpace = liveCandidate.spaces.find((space) => space.id === before.spaceId);\n'
+ + ' const accepted = acceptedSpace?.partitions?.find((partition) => partition.id === partitionId);',
+ replace: ' localCandidate, localPrevious, before.spaceId, null, candidateProjection.roomIds,\n'
+ + ' );\n'
+ + ' if (introduced.length) {\n'
+ + ' runtime._clearGeometryGesture();\n'
+ + ' runtime._restoreGeometryStateLocal(before);\n'
+ + ' host._showToast(runtime._junctionLimitLabel(introduced[0]));\n'
+ + ' return false;\n'
+ + ' }\n\n'
+ + ' adoptWallSegmentModelCandidateInPlace(liveCandidate, committedCandidate);\n'
+ + ' const acceptedSpace = liveCandidate.spaces.find((space) => space.id === before.spaceId);\n'
+ + ' const accepted = acceptedSpace?.partitions?.find((partition) => partition.id === partitionId);',
}],
},
{
@@ -6822,6 +6833,144 @@ const MUTANT_DEFINITIONS = [
+ ' event.preventDefault();',
}],
},
+ // #477: current writers must leave Optimize at a fixed point. These
+ // mutants cover every newly owned boundary rather than merely exercising
+ // the happy-path pure helper.
+ {
+ id: 'writer-finish-reset-bypasses-finalizer',
+ guard: 'node --test --test-name-pattern="source contract routes" test/writer-fixed-point.test.mjs',
+ because: 'Reset is a real wall-chain finish owner; clearing its session directly would leave '
+ + 'the just-authored collinear seams for Optimize to find (#477)',
+ patches: [{
+ file: 'src/houseplan-editor-runtime.ts',
+ find: 'if (this._finishWallChain()) this.host.requestUpdate();',
+ replace: 'this._cancelPath(); this.host.requestUpdate(); // mutant: Reset skips finish',
+ }],
+ },
+ {
+ id: 'writer-finish-adopts-unsafe-candidate',
+ guard: 'node --test --test-name-pattern="source contract routes" test/writer-fixed-point.test.mjs',
+ because: 'the completed-chain candidate must pass the bounded physical proof before it can '
+ + 'replace live config; moving adoption across that boundary defeats atomic fail-closed save (#477)',
+ patches: [{
+ file: 'src/draft-live-commit.ts',
+ find: ' const localPrevious = {\n'
+ + ' ...previousConfig, spaces: [previousProjection.space],\n'
+ + ' } as unknown as ServerConfig;\n\n'
+ + ' let geometry: Geometry | null = null;\n'
+ + ' let safe = false;\n'
+ + ' try {\n'
+ + ' const authoredPoints = host._path.length >= 2\n'
+ + ' ? host._path.map((point) => [point[0] / NORM_W, point[1] / NORM_W]) : [];\n'
+ + ' safe = wallModelOffGridValueCount(committedSpace)\n'
+ + ' <= wallModelOffGridValueCount(before, authoredPoints)\n'
+ + ' && host._checkSpacePhysicalGeometry(\n'
+ + ' localCandidate, before.spaceId, (value) => { geometry = value; },\n'
+ + ' ).ok;\n'
+ + ' } catch {\n'
+ + ' safe = false;\n'
+ + ' }\n'
+ + ' if (!safe) return rejectUnsafe(runtime, before);',
+ replace: ' const localPrevious = {\n'
+ + ' ...previousConfig, spaces: [previousProjection.space],\n'
+ + ' } as unknown as ServerConfig;\n\n'
+ + ' let geometry: Geometry | null = null;\n'
+ + ' let safe = true; // mutant: physical proof bypassed\n'
+ + ' if (!safe) return rejectUnsafe(runtime, before);',
+ }],
+ },
+ {
+ id: 'writer-history-skips-finished-chain-normalization',
+ guard: 'npm run bundle:sync && node demo/smoke_writer_fixed_point.mjs',
+ because: 'Undo/Redo after a chain has finished must restore canonical snapshots rather than '
+ + 'bringing the hidden collinear seams back into durable config (#477)',
+ patches: [{
+ file: 'src/houseplan-editor-runtime.ts',
+ find: ' const target = this._canonicalWallChainHistoryState(state);',
+ replace: ' const target = state; // mutant: finished-chain history is restored literally',
+ }],
+ },
+ {
+ id: 'writer-room-delete-keeps-direct-reference',
+ guard: 'npx tsc -p tsconfig.test.json && node scripts/fix-test-build.mjs '
+ + '&& node --test --test-name-pattern="room reference transaction" test/writer-fixed-point.test.mjs',
+ because: 'Delete room owns exact direct marker.room_id cleanup in the same undoable transaction (#477)',
+ patches: [{
+ file: 'src/room-reference-transaction.ts',
+ find: ' if (marker.room_id === operation.roomId) {\n'
+ + ' delete marker.room_id;\n'
+ + ' changed = true;\n'
+ + ' }',
+ replace: ' if (marker.room_id === operation.roomId) {\n'
+ + ' changed = true; // mutant: stale direct room reference retained\n'
+ + ' }',
+ }],
+ },
+ {
+ id: 'writer-room-delete-keeps-vacuum-reference',
+ guard: 'npx tsc -p tsconfig.test.json && node scripts/fix-test-build.mjs '
+ + '&& node --test --test-name-pattern="room reference transaction" test/writer-fixed-point.test.mjs',
+ because: 'vacuum segment maps may point across spaces and must lose exactly the deleted room '
+ + 'entry while retaining every unrelated map and wrapper field (#477)',
+ patches: [{
+ file: 'src/room-reference-transaction.ts',
+ find: ' if (operation.kind === \'delete\' && segmentMap[key] === operation.roomId) {\n'
+ + ' delete segmentMap[key];\n'
+ + ' changed = true;\n'
+ + ' }',
+ replace: ' if (operation.kind === \'delete\' && segmentMap[key] === operation.roomId) {\n'
+ + ' changed = true; // mutant: stale vacuum room reference retained\n'
+ + ' }',
+ }],
+ },
+ {
+ id: 'writer-align-snaps-free-decor-transform',
+ guard: 'npx tsc -p tsconfig.test.json && node scripts/fix-test-build.mjs '
+ + '&& node --test --test-name-pattern="continuous furniture/image transforms" test/align-grid.test.mjs',
+ because: 'furniture and image transforms are intentionally continuous; counting them as '
+ + 'legacy grid debt makes Optimize alter a normal resize or rotation (#383/#477)',
+ patches: [{
+ file: 'src/align-grid.ts',
+ find: " if (sh.kind === 'furniture' || sh.kind === 'image') continue;",
+ replace: " if (false && (sh.kind === 'furniture' || sh.kind === 'image')) continue;",
+ }],
+ },
+ {
+ id: 'writer-terminal-click-runs-finish-reconciliation',
+ guard: 'node --test --test-name-pattern="source contract routes" test/writer-fixed-point.test.mjs',
+ because: 'the latency-critical terminal click persists one crash-safe segment only; global '
+ + 'merge/reconciliation belongs to explicit chain finish and must not return to every click (#461/#477)',
+ patches: [{
+ file: 'src/houseplan-editor-runtime.ts',
+ find: 'public _markupClick(ev: MouseEvent): void {',
+ replace: 'public _markupClick(ev: MouseEvent): void {\n'
+ + ' void this._finalizeWallChainPartitions(this.host._activeWallChainPartitionIds); // mutant',
+ }],
+ },
+ {
+ id: 'writer-finish-skips-seed-merge',
+ guard: 'npx tsc -p tsconfig.test.json && node scripts/fix-test-build.mjs '
+ + '&& node --test --test-name-pattern="collinear chain" test/writer-fixed-point.test.mjs',
+ because: 'a finished current-writer chain must collapse its own compatible collinear seams '
+ + 'to fixed point without touching unrelated partitions (#477)',
+ patches: [{
+ file: 'src/writer-fixed-point.ts',
+ find: ' seedIds: seeds,',
+ replace: ' seedIds: [], // mutant: finished chain never enters merge scope',
+ }],
+ },
+ {
+ id: 'writer-finish-skips-coincident-reconciliation',
+ guard: 'npx tsc -p tsconfig.test.json && node scripts/fix-test-build.mjs '
+ + '&& node --test --test-name-pattern="coincident" test/writer-fixed-point.test.mjs',
+ because: 'a positive wall authored over room masonry must be reconciled by its finish owner, '
+ + 'including deterministic opening rehost, rather than left for Optimize (#477)',
+ patches: [{
+ file: 'src/writer-fixed-point.ts',
+ find: ' partitionIds: surviving,',
+ replace: ' partitionIds: [], // mutant: finish skips coincident seed scope',
+ }],
+ },
];
const mutationCardSource = readFileSync(join(repoRoot, 'src/houseplan-card.ts'), 'utf8');
diff --git a/scripts/smoke-links.mjs b/scripts/smoke-links.mjs
index 57e0b67e..344191b6 100644
--- a/scripts/smoke-links.mjs
+++ b/scripts/smoke-links.mjs
@@ -57,6 +57,17 @@ export const SMOKE_LINKS = [
+ 'Undo/Redo identity through the real Walls click handler; those browser effects are '
+ 'outside the pure projector and transaction source contracts',
},
+ {
+ symbols: [
+ 'commitWallChainFinishGeometry', 'finalizeWallChainSpace',
+ '_finalizeWallChainPartitions', '_canonicalWallChainHistoryState',
+ 'rewriteMarkerRoomReferences', 'restoreMarkerRoomReferences',
+ ],
+ smokes: ['smoke_writer_fixed_point.mjs'],
+ because: 'the #477 production-bundle scenario proves that a finished chain and its later '
+ + 'Undo/Redo states remain Optimize no-ops, and that Delete room updates and restores '
+ + 'direct and cross-space vacuum references through the real editor history transaction',
+ },
{
symbols: [
'VersionRecoveryController', 'VersionReloadSafetySnapshot',
diff --git a/src/align-grid.ts b/src/align-grid.ts
index 4ca792ca..2ae0c3c6 100644
--- a/src/align-grid.ts
+++ b/src/align-grid.ts
@@ -256,6 +256,11 @@ export function alignAllToGrid(
// ---- decor ---------------------------------------------------------
for (const sh of sp.decor || []) {
+ // #383 deliberately made these transforms continuous. Their saved
+ // provenance no longer tells placement from resize, so Optimize must
+ // preserve the whole authored transform instead of moving a corner or
+ // changing the size behind the user's back (#477).
+ if (sh.kind === 'furniture' || sh.kind === 'image') continue;
total++;
let d = 0;
if (sh.kind === 'line') {
diff --git a/src/coincident-partitions.ts b/src/coincident-partitions.ts
index 78793b9b..14242bfc 100644
--- a/src/coincident-partitions.ts
+++ b/src/coincident-partitions.ts
@@ -39,6 +39,13 @@ export interface CoincidentPartitionOptions {
coordScale: number;
/** Room creation consumes every coincident carrier, including duplicates. */
allowCoincidentPartitions?: boolean;
+ /**
+ * Optional writer-owned scope. Optimize and room acceptance omit it and
+ * retain their full-space behaviour; a completed wall chain supplies the
+ * surviving ids which came from that chain so unrelated partitions are not
+ * rewritten as a side effect of finishing the gesture (#477).
+ */
+ partitionIds?: readonly string[];
}
interface AxisRange { lo: number; hi: number }
@@ -222,9 +229,16 @@ export function reconcileCoincidentPartitions(
let openings = openings0;
let partitionsReconciled = 0;
let openingsRehosted = 0;
+ // `undefined` means the full-space Optimize/room-acceptance sweep. An
+ // explicitly supplied empty list is still a bounded writer scope: none of
+ // its seeds survived, so it must not adopt unrelated historical debt.
+ const partitionIds = options.partitionIds
+ ? new Set(options.partitionIds)
+ : null;
const modelById = new Map(model.partitions.map((partition) => [partition.id, partition]));
for (const rawPartition of [...partitions0].sort((a, b) => a.id.localeCompare(b.id))) {
+ if (partitionIds && !partitionIds.has(rawPartition.id)) continue;
if (!partitions.some((item) => item.id === rawPartition.id)) continue;
if (!rawPartitionKnown(rawPartition)) continue;
const source = modelById.get(rawPartition.id);
diff --git a/src/draft-live-commit.ts b/src/draft-live-commit.ts
index 42b3f2da..1be6be52 100644
--- a/src/draft-live-commit.ts
+++ b/src/draft-live-commit.ts
@@ -10,6 +10,7 @@ import {
import { spacePhysicalGeometryFingerprint } from './plan-geometry-preflight';
import {
isSinglePartitionAppend, wallChainLiveCandidateSpace, wallChainLiveSeed,
+ type WallChainLiveSeed,
} from './draft-live-preflight';
const NORM_W = 1000;
@@ -34,7 +35,10 @@ export interface WallChainLiveCommitRuntime<
Violation,
> {
host: WallChainLiveHost;
- _commitPhysicalGeometry: (name: string, before: State | null) => boolean;
+ _commitPhysicalGeometry: (
+ name: string, before: State | null,
+ additionalAuthoredPoints?: readonly (readonly number[])[], recordHistory?: boolean,
+ ) => boolean;
_clearGeometryGesture: () => void;
_restoreGeometryStateInConfig: (config: ServerConfig, state: State) => boolean;
_restoreGeometryStateLocal: (state: State) => boolean;
@@ -48,6 +52,88 @@ export interface WallChainLiveCommitRuntime<
_saveConfig: () => void;
}
+/**
+ * #477 finish transaction for a chain which has already been normalised on a
+ * clone. It uses the same production physical/junction proof as a terminal
+ * click, centred on the pre-normalisation seed. Unlike a click it records no
+ * extra history command: all segment commands already exist.
+ */
+export function commitWallChainFinishGeometry<
+ State extends { spaceId: string },
+ Geometry extends JunctionSharedGeometry,
+ Violation,
+>(
+ runtime: WallChainLiveCommitRuntime,
+ name: string,
+ before: State | null,
+ seed: WallChainLiveSeed | null,
+): boolean {
+ const { host } = runtime;
+ const liveCandidate = host._serverCfg;
+ const fallback = () => runtime._commitPhysicalGeometry(name, before, [], false);
+ if (!before || !liveCandidate || !seed
+ || Number(liveCandidate.model_version || 0) !== WALL_SEGMENT_MODEL_VERSION) return fallback();
+
+ let committedCandidate: ServerConfig;
+ try {
+ committedCandidate = commitWallSegmentModel(liveCandidate).config;
+ } catch (error) {
+ runtime._clearGeometryGesture();
+ runtime._restoreGeometryStateLocal(before);
+ runtime._showWallModelMigrationBlocked(error);
+ return false;
+ }
+ const committedSpace = committedCandidate.spaces.find((space) => space.id === before.spaceId);
+ const previousConfig = JSON.parse(JSON.stringify(liveCandidate)) as ServerConfig;
+ if (!committedSpace || !runtime._restoreGeometryStateInConfig(previousConfig, before)) {
+ return fallback();
+ }
+ const previousSpace = previousConfig.spaces.find((space) => space.id === before.spaceId);
+ const candidateProjection = wallChainLiveCandidateSpace(committedSpace, seed);
+ const previousProjection = wallChainLiveCandidateSpace(previousSpace, seed);
+ if (!candidateProjection || !previousProjection) return fallback();
+ const localCandidate = {
+ ...committedCandidate, spaces: [candidateProjection.space],
+ } as unknown as ServerConfig;
+ const localPrevious = {
+ ...previousConfig, spaces: [previousProjection.space],
+ } as unknown as ServerConfig;
+
+ let geometry: Geometry | null = null;
+ let safe = false;
+ try {
+ const authoredPoints = host._path.length >= 2
+ ? host._path.map((point) => [point[0] / NORM_W, point[1] / NORM_W]) : [];
+ safe = wallModelOffGridValueCount(committedSpace)
+ <= wallModelOffGridValueCount(before, authoredPoints)
+ && host._checkSpacePhysicalGeometry(
+ localCandidate, before.spaceId, (value) => { geometry = value; },
+ ).ok;
+ } catch {
+ safe = false;
+ }
+ if (!safe) return rejectUnsafe(runtime, before);
+ const introduced = runtime._junctionLimitsIntroduced(
+ localCandidate, localPrevious, before.spaceId, geometry, candidateProjection.roomIds,
+ );
+ if (introduced.length) {
+ runtime._clearGeometryGesture();
+ runtime._restoreGeometryStateLocal(before);
+ host._showToast(runtime._junctionLimitLabel(introduced[0]));
+ return false;
+ }
+
+ adoptWallSegmentModelCandidateInPlace(liveCandidate, committedCandidate);
+ const acceptedSpace = liveCandidate.spaces.find((space) => space.id === before.spaceId);
+ const pending = host._pendingPhysicalWrites.get(before.spaceId);
+ host._pendingPhysicalWrites.set(before.spaceId, {
+ before: pending?.before || before,
+ fingerprint: spacePhysicalGeometryFingerprint(acceptedSpace),
+ });
+ runtime._saveConfig();
+ return true;
+}
+
const rejectUnsafe = (runtime: WallChainLiveCommitRuntime, before: State): false => {
runtime._clearGeometryGesture();
diff --git a/src/houseplan-card.ts b/src/houseplan-card.ts
index 97a74966..49b90c06 100755
--- a/src/houseplan-card.ts
+++ b/src/houseplan-card.ts
@@ -403,6 +403,7 @@ import {
reorderSpaceIds,
} from './space-order';
import { applyOpeningMoves, mergeCollinearPartitions, spaceMergeGeometry } from './wall-merge';
+import type { MarkerRoomReferenceSnapshot } from './room-reference-transaction';
const CARD_VERSION = '1.73.0-beta.1';
const ENTRY_BUILD_FINGERPRINT = '__HOUSEPLAN_SOURCE_FINGERPRINT__';
@@ -562,6 +563,10 @@ interface SpaceGeometryState {
plan_x?: number; plan_y?: number; plan_scale?: number;
plan_scale_x?: number; plan_scale_y?: number; plan_angle?: number;
};
+ /** Session-only: current-writer normalisation scope for wall-chain history. */
+ wallChainSeedIds?: string[];
+ /** Session-only: exact room fields touched by Delete/Merge room. */
+ roomReferences?: MarkerRoomReferenceSnapshot[];
}
const fireEvent = (node: EventTarget, type: string, detail?: unknown) => {
const ev = new Event(type, { bubbles: true, composed: true }) as any;
diff --git a/src/houseplan-editor-runtime.ts b/src/houseplan-editor-runtime.ts
index 2f6f49aa..462d1331 100644
--- a/src/houseplan-editor-runtime.ts
+++ b/src/houseplan-editor-runtime.ts
@@ -63,7 +63,10 @@ import {
type ResizeProjectionResult,
} from './resize-controller';
import { resizeLiveCandidateSpace, resizeLiveJunctionRoomIds } from './resize-live-preflight';
-import { commitWallChainSegmentGeometry } from './draft-live-commit';
+import {
+ commitWallChainFinishGeometry, commitWallChainSegmentGeometry,
+} from './draft-live-commit';
+import { wallChainLiveSeed } from './draft-live-preflight';
import {
placeResizeAreaLabel, resizeMeasuredEdges,
type ResizeAreaPlacement,
@@ -368,6 +371,11 @@ import {
} from './space-order';
import { applyOpeningMoves, mergeCollinearPartitions, spaceMergeGeometry } from './wall-merge';
import { reconcileCoincidentPartitions } from './coincident-partitions';
+import { finalizeWallChainSpace } from './writer-fixed-point';
+import {
+ captureMarkerRoomReferences, restoreMarkerRoomReferences,
+ rewriteMarkerRoomReferences, type MarkerRoomReferenceSnapshot,
+} from './room-reference-transaction';
const CARD_VERSION = '1.73.0-beta.1';
@@ -717,6 +725,10 @@ interface SpaceGeometryState {
plan_x?: number; plan_y?: number; plan_scale?: number;
plan_scale_x?: number; plan_scale_y?: number; plan_angle?: number;
};
+ /** Session-only: current-writer normalisation scope for wall-chain history. */
+ wallChainSeedIds?: string[];
+ /** Session-only: exact room fields touched by Delete/Merge room. */
+ roomReferences?: MarkerRoomReferenceSnapshot[];
}
/** Tools of the decor (background) editor. `furniture` is the library
* (docs/FURNITURE.md): it opens a palette and places a symbol at real size. */
@@ -1469,10 +1481,64 @@ public _mergeSpacePartitions(sp: any, seedIds?: string[]): number {
coordScale: NORM_W, cellCm: this.host._cellCm, gridPitch: this.host._gridPitch,
});
return result.merged;
+}
+
+public _finalizeWallChainPartitions(seedIds: readonly string[]): boolean {
+ if (!seedIds.length) return true;
+ const sp = this.host._curSpaceCfg;
+ const model = this.host._spaceModel();
+ const before = this._geometrySnapshot();
+ if (!sp || !model || !before) return false;
+ const seed = seedIds.map((id) => wallChainLiveSeed(sp, id)).find(Boolean) || null;
+ const session = {
+ path: this.host._path.map((point) => [...point]),
+ chainId: this.host._activeWallChainId,
+ ids: [...this.host._activeWallChainPartitionIds],
+ cms: [...this.host._wallChainSegmentCms],
+ redo: this.host._wallChainRedo.map((item) => ({
+ ...item, point: [...item.point],
+ })),
+ closingCm: this.host._closingWallCm,
+ };
+ let result;
+ try {
+ result = finalizeWallChainSpace(
+ sp, model, this.host._openCuts(), seedIds,
+ {
+ pitch: this.host._wallKeyPitch,
+ cellCm: this.host._cellCm,
+ gridPitch: this.host._gridPitch,
+ coordScale: NORM_W,
+ },
+ );
+ } catch {
+ this.host._showToast(this.host._t('toast.geometry_unsafe'));
+ return false;
+ }
+ if (!result.report.changed) return true;
+ const config = this.host._serverCfg;
+ const index = config?.spaces?.findIndex((space) => space.id === before.spaceId) ?? -1;
+ if (index < 0) return false;
+ config!.spaces[index] = result.space;
+ const committed = commitWallChainFinishGeometry(
+ this, this.host._t('history.wall_segment'), before, seed,
+ );
+ if (committed) return true;
+ // The common transaction clears gestures on refusal. A finish failure is
+ // fail-closed: keep the visible chain so the requested navigation can be
+ // retried after the underlying geometry is fixed.
+ this.host._path = session.path;
+ this.host._activeWallChainId = session.chainId;
+ this.host._activeWallChainPartitionIds = session.ids;
+ this.host._wallChainSegmentCms = session.cms;
+ this.host._wallChainRedo = session.redo;
+ this.host._closingWallCm = session.closingCm;
+ return false;
}
public _finishWallChain(): boolean {
if (this.host._tool !== 'draw' || this.host._wallFaceBatch || this.host._roomDialog) return true;
+ if (!this._finalizeWallChainPartitions(this.host._activeWallChainPartitionIds)) return false;
this.host._path = [];
this.host._activeWallChainId = null;
this.host._activeWallChainPartitionIds = [];
@@ -1852,6 +1918,15 @@ public _recordGeometry(name: string, before: SpaceGeometryState | null): void {
if (!before) return;
const after = this._geometrySnapshot(before.spaceId);
if (!after || JSON.stringify(before) === JSON.stringify(after)) return;
+ if (before.wallChainSeedIds) {
+ after.wallChainSeedIds = [...this.host._activeWallChainPartitionIds];
+ }
+ if (before.roomReferences) {
+ after.roomReferences = captureMarkerRoomReferences(
+ this.host._serverCfg?.markers || [],
+ before.roomReferences.map((reference) => reference.markerId),
+ );
+ }
this.host._geometryHistory.push({ name, before, after });
this.host.requestUpdate();
}
@@ -1893,9 +1968,53 @@ public _restoreGeometryStateInConfig(
for (const key of ['plan_x', 'plan_y', 'plan_scale', 'plan_scale_x', 'plan_scale_y', 'plan_angle'] as const)
delete (sp as any)[key];
Object.assign(sp, copy(state.plan_transform || {}));
+ if (state.roomReferences) {
+ config.markers ||= [];
+ restoreMarkerRoomReferences(config.markers, state.roomReferences);
+ }
return true;
}
+public _canonicalWallChainHistoryState(state: SpaceGeometryState): SpaceGeometryState | null {
+ if (this.host._activeWallChainId || !state.wallChainSeedIds?.length) return state;
+ if (!this.host._serverCfg) return null;
+ const candidate = JSON.parse(JSON.stringify(this.host._serverCfg));
+ if (!this._restoreGeometryStateInConfig(candidate, state)) return null;
+ let committed: ServerConfig;
+ try { committed = commitWallSegmentModel(candidate).config; }
+ catch { return null; }
+ const raw = committed.spaces?.find((space) => space.id === state.spaceId);
+ const model = selectSpaceModelById(spaceModels(committed), state.spaceId);
+ if (!raw || !model) return null;
+ const result = finalizeWallChainSpace(
+ raw,
+ model,
+ geometryOpenCuts(raw, model, GRID_PITCH, NORM_W),
+ state.wallChainSeedIds,
+ {
+ pitch: GRID_STEP_N,
+ cellCm: Number(raw.cell_cm) > 0 ? Number(raw.cell_cm) : 5,
+ gridPitch: GRID_PITCH,
+ coordScale: NORM_W,
+ },
+ );
+ const index = committed.spaces.findIndex((space) => space.id === state.spaceId);
+ committed.spaces[index] = result.space;
+ // The finalizer can replace partitions with authoritative wall segments.
+ // Cross that model boundary once more before recording the history state,
+ // exactly as the production finish transaction does. Otherwise a Redo
+ // could restore the pre-commit carrier representation and Optimize would
+ // find work immediately afterwards.
+ let finalized: ServerConfig;
+ try { finalized = commitWallSegmentModel(committed).config; }
+ catch { return null; }
+ const normalized = this._geometrySnapshotFromConfig(finalized, state.spaceId);
+ if (!normalized) return null;
+ normalized.wallChainSeedIds = [...state.wallChainSeedIds];
+ if (state.roomReferences) normalized.roomReferences = JSON.parse(JSON.stringify(state.roomReferences));
+ return normalized;
+ }
+
public _restoreGeometryStateLocal(state: SpaceGeometryState): boolean {
if (!this._restoreGeometryStateInConfig(this.host._serverCfg, state)) return false;
this.host._cfgEpoch++;
@@ -2031,9 +2150,17 @@ public _commitPhysicalGeometry(
name: string,
before: SpaceGeometryState | null,
additionalAuthoredPoints: readonly (readonly number[])[] = [],
+ recordHistory = true,
): boolean {
if (!before || !this.host._serverCfg) return false;
const liveCandidate = this.host._serverCfg;
+ // The public guard already selects one space internally. Give it the
+ // bounded carrier as well so a writer finish cannot accidentally make a
+ // future preflight implementation inspect unrelated floors (#477/#461).
+ const physicalCandidateFor = (config: ServerConfig): ServerConfig => {
+ const space = config?.spaces?.find((item) => item.id === before.spaceId);
+ return space ? { ...config, spaces: [space] } : config;
+ };
const editedState = this._geometrySnapshotFromConfig(liveCandidate, before.spaceId);
const liveSpace = liveCandidate.spaces.find((space) => space.id === before.spaceId);
if (!liveSpace || spacePhysicalGeometryFingerprint(before)
@@ -2042,7 +2169,11 @@ public _commitPhysicalGeometry(
// repair/atomise a degraded legacy projection, but it must never be used to
// make an otherwise rejected user edit look safe.
let legacySafe = false;
- try { legacySafe = this.host._checkSpacePhysicalGeometry(liveCandidate, before.spaceId).ok; }
+ try {
+ legacySafe = this.host._checkSpacePhysicalGeometry(
+ physicalCandidateFor(liveCandidate), before.spaceId,
+ ).ok;
+ }
catch { legacySafe = false; }
if (!legacySafe) {
this._clearGeometryGesture();
@@ -2068,6 +2199,8 @@ public _commitPhysicalGeometry(
throw new WallSegmentModelError('invalid-room', before.spaceId);
const baseline = commitWallSegmentModel(baselineSource).config;
historyBefore = this._geometrySnapshotFromConfig(baseline, before.spaceId) || before;
+ historyBefore.wallChainSeedIds = before.wallChainSeedIds;
+ historyBefore.roomReferences = before.roomReferences;
const editedWithIdentity = JSON.parse(JSON.stringify(baseline));
if (!editedState || !this._restoreGeometryStateInConfig(
editedWithIdentity, editedState, true,
@@ -2112,7 +2245,9 @@ public _commitPhysicalGeometry(
authoredPoints.push(...additionalAuthoredPoints.map((point) => [point[0], point[1]]));
safe = wallModelOffGridValueCount(afterSpace)
<= wallModelOffGridValueCount(historyBefore, authoredPoints)
- && this.host._checkSpacePhysicalGeometry(committedCandidate, before.spaceId).ok;
+ && this.host._checkSpacePhysicalGeometry(
+ physicalCandidateFor(committedCandidate), before.spaceId,
+ ).ok;
} catch {
safe = false;
}
@@ -2137,7 +2272,7 @@ public _commitPhysicalGeometry(
return false;
}
adoptWallSegmentModelCandidateInPlace(liveCandidate, committedCandidate);
- this._recordGeometry(name, historyBefore);
+ if (recordHistory) this._recordGeometry(name, historyBefore);
const afterSpace = liveCandidate.spaces.find((space) => space.id === before.spaceId);
const pending = this.host._pendingPhysicalWrites.get(before.spaceId);
this.host._pendingPhysicalWrites.set(before.spaceId, {
@@ -2222,17 +2357,18 @@ public _stagePointerCancel(ev: PointerEvent): void {
public _applyGeometryState(
state: SpaceGeometryState, allowHistoryBoundaryRepair = false,
): boolean {
- if (!this.host._canCommitSpace(state.spaceId)) return false;
- const before = this._geometrySnapshot(state.spaceId);
- if (!before || !this._restoreGeometryStateLocal(state)) return false;
+ const target = this._canonicalWallChainHistoryState(state);
+ if (!target || !this.host._canCommitSpace(target.spaceId)) return false;
+ const before = this._geometrySnapshot(target.spaceId);
+ if (!before || !this._restoreGeometryStateLocal(target)) return false;
const restoredCandidate = this.host._serverCfg;
const physicalChanged = spacePhysicalGeometryFingerprint(before)
- !== spacePhysicalGeometryFingerprint(state);
+ !== spacePhysicalGeometryFingerprint(target);
if (physicalChanged) {
let safe = false;
try {
const check = restoredCandidate
- ? this.host._checkSpacePhysicalGeometry(restoredCandidate, state.spaceId)
+ ? this.host._checkSpacePhysicalGeometry(restoredCandidate, target.spaceId)
: null;
safe = !!check?.ok || !!(allowHistoryBoundaryRepair
&& check?.reason === 'wall-degraded-extra');
@@ -2255,7 +2391,7 @@ public _applyGeometryState(
let safe = false;
try {
const check = committedCandidate
- ? this.host._checkSpacePhysicalGeometry(committedCandidate, state.spaceId)
+ ? this.host._checkSpacePhysicalGeometry(committedCandidate, target.spaceId)
: null;
// A history snapshot can predate the write-time wall degradation that
// canonicalized its command. Restore that one repairable baseline so
@@ -2271,16 +2407,16 @@ public _applyGeometryState(
return false;
}
adoptWallSegmentModelCandidateInPlace(restoredCandidate, committedCandidate);
- const afterSpace = restoredCandidate?.spaces.find((space) => space.id === state.spaceId);
- const pending = this.host._pendingPhysicalWrites.get(state.spaceId);
- this.host._pendingPhysicalWrites.set(state.spaceId, {
+ const afterSpace = restoredCandidate?.spaces.find((space) => space.id === target.spaceId);
+ const pending = this.host._pendingPhysicalWrites.get(target.spaceId);
+ this.host._pendingPhysicalWrites.set(target.spaceId, {
before: pending?.before || before,
fingerprint: spacePhysicalGeometryFingerprint(afterSpace),
});
} else adoptWallSegmentModelCandidateInPlace(restoredCandidate, committedCandidate);
this._clearGeometryGesture();
- if (this.host._space !== state.spaceId) {
- this.host._commitSpace(state.spaceId);
+ if (this.host._space !== target.spaceId) {
+ this.host._commitSpace(target.spaceId);
this.host._saveNav();
this.host._restoreZoom();
}
@@ -2522,6 +2658,7 @@ public _markupClick(ev: MouseEvent): void {
const beforeCms = [...this.host._wallChainSegmentCms];
const beforeGraphSources = this._wallGraphSources([]);
const before = this._geometrySnapshot();
+ if (before) before.wallChainSeedIds = [...beforeIds];
const id = `partition-${crypto.randomUUID?.() || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}`;
sp.partitions ||= [];
sp.partitions.push({
@@ -5122,7 +5259,9 @@ public _renderPlanSecondary(): EditorSecondaryModel | null {
${drawHint ? html`${drawHint}` : nothing}
${hintKey ? html`${this.host._t(hintKey as any)}` : nothing}
${this.host._tool === 'draw' && this.host._path.length
- ? html` this._runEditorContext(contextId, () => this._cancelPath())}>
+ ? html` this._runEditorContext(contextId, () => {
+ if (this._finishWallChain()) this.host.requestUpdate();
+ })}>
${this.host._t('btn.reset')}
` : nothing}`,
};
@@ -5511,6 +5650,10 @@ public _confirmRoomDelete = (keepWalls: boolean): void => {
return;
}
const before = this._geometrySnapshot();
+ const referenceRewrite = rewriteMarkerRoomReferences(
+ this.host._serverCfg?.markers || [], { kind: 'delete', roomId: dialog.roomId },
+ );
+ if (before && referenceRewrite.changed) before.roomReferences = referenceRewrite.before;
const materializedWalls = materializeWallIntervals(
space.rooms, this.host._spaceWalls, openCuts,
this.host._wallKeyPitch, this.host._cellCm, this.host._gridPitch, NORM_W,
@@ -5565,6 +5708,9 @@ public _confirmRoomDelete = (keepWalls: boolean): void => {
if (!sp.openings.length) delete sp.openings;
}
sp.rooms = sp.rooms.filter((r: any) => r.id !== room.id);
+ if (referenceRewrite.changed && this.host._serverCfg) {
+ this.host._serverCfg.markers = referenceRewrite.markers;
+ }
this.host._cfgEpoch++;
const normalized = this.host._normalizeWalls(materializedWalls, this.host._openCuts());
if (normalized.length) sp.walls = normalized;
@@ -6413,6 +6559,10 @@ public _commitMerge(): void {
const H = this.host._spaceH;
const keepId = d.pick === 'a' ? d.aId : d.bId;
const dropId = d.pick === 'a' ? d.bId : d.aId;
+ const referenceRewrite = rewriteMarkerRoomReferences(
+ this.host._serverCfg?.markers || [], { kind: 'merge', dropId, keepId },
+ );
+ if (before && referenceRewrite.changed) before.roomReferences = referenceRewrite.before;
const keep = sp.rooms.find((r: any) => r.id === keepId);
if (!keep) {
this.host._mergeDialog = null;
@@ -6422,6 +6572,9 @@ public _commitMerge(): void {
keep.poly = d.poly.map((p) => [p[0] / NORM_W, p[1] / H]);
delete keep.x; delete keep.y; delete keep.w; delete keep.h; // a merged room is never a rect
sp.rooms = sp.rooms.filter((r: any) => r.id !== dropId);
+ if (referenceRewrite.changed && this.host._serverCfg) {
+ this.host._serverCfg.markers = referenceRewrite.markers;
+ }
const committed = this._commitPhysicalGeometry(this.host._t('history.merge_rooms'), before);
this.host._mergeDialog = null;
this.host._regSignature = '';
@@ -6725,6 +6878,7 @@ public _applyWallFaceBatch(): void {
const effectiveActivePath = this._activePathWithRepair(batch.activePath, repairs[0]);
if (!accepted.length) {
+ if (!this._finalizeWallChainPartitions(batch.activePartitionIds)) return;
this.host._path = [];
this.host._activeWallChainId = null;
this.host._activeWallChainPartitionIds = [];
@@ -7562,6 +7716,7 @@ public _keepClosedAsPartitions = (): void => {
if (!this.host._contourClosed || this.host._pendingSplit || !this.host._curSpaceCfg) return;
// Every accepted edge is already an ordinary partition. Rejecting all
// detected faces only ends the session; it must not duplicate the chain.
+ if (!this._finalizeWallChainPartitions(this.host._activeWallChainPartitionIds)) return;
this.host._roomDialog = false;
this.host._path = [];
this.host._activeWallChainId = null;
diff --git a/src/room-reference-transaction.ts b/src/room-reference-transaction.ts
new file mode 100644
index 00000000..b6ffc0d5
--- /dev/null
+++ b/src/room-reference-transaction.ts
@@ -0,0 +1,119 @@
+/** Room-reference part of Delete/Merge room transactions (#477). */
+
+import type { Marker } from './types';
+
+export interface MarkerRoomReferenceSnapshot {
+ markerId: string;
+ roomIdPresent: boolean;
+ roomId?: Marker['room_id'];
+ vacuumPresent: boolean;
+ segmentMapPresent: boolean;
+ segmentMap?: Record;
+}
+
+export interface RoomReferenceRewriteResult {
+ markers: Marker[];
+ before: MarkerRoomReferenceSnapshot[];
+ after: MarkerRoomReferenceSnapshot[];
+ changed: number;
+}
+
+const clone = (value: T): T => (
+ value === undefined ? value : JSON.parse(JSON.stringify(value))
+);
+const own = (value: unknown, key: string): boolean => (
+ !!value && typeof value === 'object' && Object.prototype.hasOwnProperty.call(value, key)
+);
+
+export function captureMarkerRoomReferences(
+ markers: readonly Marker[], markerIds?: readonly string[],
+): MarkerRoomReferenceSnapshot[] {
+ const wanted = markerIds ? new Set(markerIds) : null;
+ return (markers || [])
+ .filter((marker) => typeof marker?.id === 'string' && (!wanted || wanted.has(marker.id)))
+ .map((marker) => {
+ const vacuum = marker.vacuum;
+ return {
+ markerId: marker.id,
+ roomIdPresent: own(marker, 'room_id'),
+ ...(own(marker, 'room_id') ? { roomId: clone(marker.room_id) } : {}),
+ vacuumPresent: own(marker, 'vacuum'),
+ segmentMapPresent: own(vacuum, 'segment_map'),
+ ...(own(vacuum, 'segment_map')
+ ? { segmentMap: clone(vacuum?.segment_map) }
+ : {}),
+ };
+ })
+ .sort((left, right) => left.markerId.localeCompare(right.markerId));
+}
+
+/** Restore only room-related fields; unrelated marker/vacuum edits survive. */
+export function restoreMarkerRoomReferences(
+ markers: Marker[], snapshots: readonly MarkerRoomReferenceSnapshot[],
+): void {
+ const byId = new Map((markers || []).map((marker) => [marker?.id, marker]));
+ for (const snapshot of snapshots) {
+ const marker = byId.get(snapshot.markerId);
+ if (!marker) continue;
+ if (snapshot.roomIdPresent) marker.room_id = clone(snapshot.roomId);
+ else delete marker.room_id;
+
+ if (snapshot.segmentMapPresent) {
+ if (!marker.vacuum || typeof marker.vacuum !== 'object' || Array.isArray(marker.vacuum)) {
+ marker.vacuum = {};
+ }
+ marker.vacuum.segment_map = clone(snapshot.segmentMap) || {};
+ continue;
+ }
+ if (marker.vacuum && typeof marker.vacuum === 'object' && !Array.isArray(marker.vacuum)) {
+ delete marker.vacuum.segment_map;
+ if (!snapshot.vacuumPresent && Object.keys(marker.vacuum).length === 0) delete marker.vacuum;
+ }
+ }
+}
+
+export function rewriteMarkerRoomReferences(
+ markersIn: readonly Marker[],
+ operation: { kind: 'delete'; roomId: string } | { kind: 'merge'; dropId: string; keepId: string },
+): RoomReferenceRewriteResult {
+ const markers: Marker[] = clone([...(markersIn || [])]);
+ const touched = new Set();
+ for (const marker of markers) {
+ if (typeof marker?.id !== 'string') continue;
+ let changed = false;
+ if (operation.kind === 'delete') {
+ if (marker.room_id === operation.roomId) {
+ delete marker.room_id;
+ changed = true;
+ }
+ } else if (marker.room_id === operation.dropId) {
+ marker.room_id = operation.keepId;
+ changed = true;
+ }
+
+ const segmentMap = marker.vacuum?.segment_map;
+ if (segmentMap && typeof segmentMap === 'object' && !Array.isArray(segmentMap)) {
+ for (const key of Object.keys(segmentMap)) {
+ if (operation.kind === 'delete' && segmentMap[key] === operation.roomId) {
+ delete segmentMap[key];
+ changed = true;
+ } else if (operation.kind === 'merge' && segmentMap[key] === operation.dropId) {
+ segmentMap[key] = operation.keepId;
+ changed = true;
+ }
+ }
+ if (operation.kind === 'delete' && Object.keys(segmentMap).length === 0) {
+ if (marker.vacuum) delete marker.vacuum.segment_map;
+ if (marker.vacuum && Object.keys(marker.vacuum).length === 0) delete marker.vacuum;
+ }
+ }
+ if (changed) touched.add(marker.id);
+ }
+ const ids = [...touched].sort((left, right) => left.localeCompare(right));
+ return {
+ markers,
+ before: captureMarkerRoomReferences(markersIn, ids),
+ after: captureMarkerRoomReferences(markers, ids),
+ changed: ids.length,
+ };
+}
diff --git a/src/writer-fixed-point.ts b/src/writer-fixed-point.ts
new file mode 100644
index 00000000..e4ff17b8
--- /dev/null
+++ b/src/writer-fixed-point.ts
@@ -0,0 +1,141 @@
+/**
+ * Lossless current-writer normalisation (#477).
+ *
+ * This module owns no UI and never mutates its inputs. A wall-chain finish
+ * can therefore build and validate the complete candidate before the live
+ * config, history or pending-write fingerprint sees any of it.
+ */
+import { reconcileCoincidentPartitions } from './coincident-partitions';
+import type {
+ OpeningCfg, PartitionCfg, RoomCfg, SpaceModel, WallColumnCfg,
+} from './types';
+import type { WallEntry } from './wall-thickness';
+import {
+ applyOpeningMoves, mergeCollinearPartitions, spaceMergeGeometry,
+} from './wall-merge';
+
+export interface WallChainFinalizerOptions {
+ pitch: number;
+ cellCm: number;
+ gridPitch: number;
+ coordScale: number;
+}
+
+export interface WallChainFinalizerReport {
+ partitionsMerged: number;
+ partitionsReconciled: number;
+ openingsRehosted: number;
+ changed: boolean;
+}
+
+export interface WriterFixedPointSpace extends Record {
+ rooms?: RoomCfg[];
+ partitions?: PartitionCfg[];
+ openings?: OpeningCfg[];
+ walls?: WallEntry[];
+ wall_columns?: WallColumnCfg[];
+}
+
+export interface WallChainFinalizerResult {
+ space: WriterFixedPointSpace;
+ report: WallChainFinalizerReport;
+}
+
+const clone = (value: T): T => JSON.parse(JSON.stringify(value));
+
+/** Ids from the active chain after all deterministic merge remaps. */
+function survivingSeedIds(
+ partitions: readonly PartitionCfg[],
+ seedIds: readonly string[],
+ moves: readonly { fromId: string; toId: string }[],
+): string[] {
+ const present = new Set(partitions.map((partition) => partition.id));
+ const mapped = new Map(moves.map((move) => [move.fromId, move.toId]));
+ return [...new Set(seedIds
+ .map((id) => mapped.get(id) || id)
+ .filter((id) => present.has(id)))]
+ .sort((left, right) => left.localeCompare(right));
+}
+
+/**
+ * Canonicalise only the connected partition component touched by one finished
+ * wall chain. Full-space maintenance remains the responsibility of Optimize.
+ */
+export function finalizeWallChainSpace(
+ rawSpace: WriterFixedPointSpace,
+ model: Pick,
+ openCuts: number[][],
+ seedIds: readonly string[],
+ options: WallChainFinalizerOptions,
+): WallChainFinalizerResult {
+ const space = clone(rawSpace);
+ const seeds = [...new Set(seedIds.filter((id) => typeof id === 'string' && id))];
+ const emptyReport: WallChainFinalizerReport = {
+ partitionsMerged: 0,
+ partitionsReconciled: 0,
+ openingsRehosted: 0,
+ changed: false,
+ };
+ if (!seeds.length || !Array.isArray(space?.partitions)) {
+ return { space, report: emptyReport };
+ }
+
+ const before = JSON.stringify(space);
+ const merged = mergeCollinearPartitions(space.partitions as PartitionCfg[], {
+ pitch: options.pitch,
+ seedIds: seeds,
+ geometry: spaceMergeGeometry(space),
+ });
+ if (merged.merged) space.partitions = merged.partitions;
+ const mergedOpenings = (Array.isArray(space.openings) ? space.openings : []) as OpeningCfg[];
+ if (merged.merged) {
+ applyOpeningMoves(mergedOpenings, merged.partitions, merged.openingMoves, {
+ coordScale: options.coordScale,
+ cellCm: options.cellCm,
+ gridPitch: options.gridPitch,
+ });
+ }
+
+ const surviving = survivingSeedIds(merged.partitions, seeds, merged.openingMoves);
+ const mergedModel = {
+ rooms: model.rooms,
+ wall_columns: model.wall_columns,
+ partitions: merged.partitions.map((partition) => ({
+ ...partition,
+ a: [partition.a[0] * options.coordScale, partition.a[1] * options.coordScale],
+ b: [partition.b[0] * options.coordScale, partition.b[1] * options.coordScale],
+ })),
+ };
+ const reconciled = reconcileCoincidentPartitions(
+ space,
+ mergedModel,
+ space.walls as WallEntry[] | undefined,
+ openCuts,
+ {
+ ...options,
+ partitionIds: surviving,
+ },
+ );
+ // A no-op finish must be byte-equivalent: in particular it must not turn an
+ // authored empty array into an absent field merely because the shared
+ // reconciliation helper returns canonical empty collections. Adopt those
+ // collections only when the proof actually consumed a partition.
+ if (reconciled.partitionsReconciled) {
+ if (reconciled.walls.length) space.walls = reconciled.walls;
+ else delete space.walls;
+ if (reconciled.partitions.length) space.partitions = reconciled.partitions;
+ else delete space.partitions;
+ if (reconciled.openings.length) space.openings = reconciled.openings;
+ else delete space.openings;
+ }
+
+ return {
+ space,
+ report: {
+ partitionsMerged: merged.merged,
+ partitionsReconciled: reconciled.partitionsReconciled,
+ openingsRehosted: reconciled.openingsRehosted,
+ changed: JSON.stringify(space) !== before,
+ },
+ };
+}
diff --git a/test/align-grid.test.mjs b/test/align-grid.test.mjs
index 72ef7c4c..93e5d3cd 100644
--- a/test/align-grid.test.mjs
+++ b/test/align-grid.test.mjs
@@ -93,6 +93,34 @@ test('ordinary off-grid movement is not duplicated in the near-node counter', ()
assert.equal(result.report.coordsCanonicalized, 0);
});
+test('#477 Optimize preserves complete furniture/image transforms and excludes them from its report', () => {
+ const furniture = {
+ id: 'furniture', kind: 'furniture', asset: 'sofa',
+ x: 0.10123456789, y: 0.20345678901, w: 0.3123456789, h: 0.08765432109,
+ angle: 17.123456789, flip_h: true, future_field: { keep: true },
+ };
+ const image = {
+ id: 'image', kind: 'image', href: '/local/custom.png',
+ x: 0.40123456789, y: 0.50345678901, w: 0.1123456789, h: 0.18765432109,
+ angle: -12.987654321, flip_v: true, future_field: ['keep'],
+ };
+ const ordinary = {
+ id: 'ordinary', kind: 'rect',
+ x: 0.7 + S / 3, y: 0.7, w: 0.1, h: 0.1,
+ };
+ const spaces = [{ id: 'free-transform', rooms: [], decor: [
+ structuredClone(furniture), structuredClone(image), structuredClone(ordinary),
+ ] }];
+ const result = alignAllToGrid(spaces, {});
+ assert.deepEqual(result.spaces[0].decor[0], furniture);
+ assert.deepEqual(result.spaces[0].decor[1], image);
+ assert.notDeepEqual(result.spaces[0].decor[2], ordinary,
+ 'ordinary decor stays governed by the grid contract');
+ assert.equal(result.report.total, 1);
+ assert.equal(result.report.moved, 1);
+ assert.equal(result.report.maxSpace, 'free-transform');
+});
+
test('alignAllToGrid puts every grid-bound element on a node', () => {
const { spaces, layout, report } = alignAllToGrid(detuned().spaces, detunedLayout());
const sp = spaces[0];
diff --git a/test/coincident-partitions.test.mjs b/test/coincident-partitions.test.mjs
index b0a3bfaf..4482aa8c 100644
--- a/test/coincident-partitions.test.mjs
+++ b/test/coincident-partitions.test.mjs
@@ -135,7 +135,7 @@ test('issue 276 fails closed when two hosted openings would overlap after rehost
assert.ok(result.config.spaces[0].openings.every((opening) => opening.host?.id === 'redundant'));
});
-test('issue 276 reconciliation is owned by Optimize and room finalization only', () => {
+test('issue 276 reconciliation is owned only by explicit maintenance/finalization boundaries', () => {
const input = clone(fixture);
const secondSpace = clone(input.spaces[0]);
secondSpace.id = 'offset-shared-wall-second';
@@ -167,6 +167,7 @@ test('issue 276 reconciliation is owned by Optimize and room finalization only',
.sort();
assert.deepEqual(owners, [
'coincident-partitions.ts', 'houseplan-editor-runtime.ts', 'plan-optimizer.ts',
+ 'writer-fixed-point.ts',
],
'render/pointer modules must not import or invoke either maintenance owner');
});
diff --git a/test/fixtures/477-writer-fixed-point-writers.json b/test/fixtures/477-writer-fixed-point-writers.json
new file mode 100644
index 00000000..e17cf0a6
--- /dev/null
+++ b/test/fixtures/477-writer-fixed-point-writers.json
@@ -0,0 +1,34 @@
+{
+ "schema": 1,
+ "issue": 477,
+ "cases": [
+ { "owner": "_markupClick", "class": "intermediate-exception", "witness": "test/draft-live-preflight.test.mjs" },
+ { "owner": "_finalizeWallChainPartitions", "class": "fixed-point", "witness": "test/writer-fixed-point.test.mjs" },
+ { "owner": "_applyGeometryState", "class": "fixed-point-history", "witness": "test/writer-fixed-point.test.mjs" },
+ { "owner": "_columnClick", "class": "fixed-point", "witness": "test/plan-optimizer.test.mjs" },
+ { "owner": "_savePhysicalDialog", "class": "fixed-point", "witness": "test/plan-optimizer.test.mjs" },
+ { "owner": "_deletePhysicalSelection", "class": "fixed-point", "witness": "test/plan-optimizer.test.mjs" },
+ { "owner": "_confirmPartitionDelete", "class": "fixed-point", "witness": "test/partition-openings.test.mjs" },
+ { "owner": "_physicalUp", "class": "fixed-point", "witness": "test/plan-optimizer.test.mjs" },
+ { "owner": "_physicalRotateUp", "class": "fixed-point", "witness": "test/plan-optimizer.test.mjs" },
+ { "owner": "_rszUp", "class": "fixed-point", "witness": "test/resize-optimize.test.mjs" },
+ { "owner": "_confirmRoomDelete", "class": "fixed-point-references", "witness": "test/writer-fixed-point.test.mjs" },
+ { "owner": "_wallThickApply", "class": "fixed-point", "witness": "test/wall-thickness.test.mjs" },
+ { "owner": "_opPointerUp", "class": "fixed-point", "witness": "test/partition-openings.test.mjs" },
+ { "owner": "_saveOpening", "class": "fixed-point", "witness": "test/partition-openings.test.mjs" },
+ { "owner": "_deleteOpening", "class": "fixed-point", "witness": "test/partition-openings.test.mjs" },
+ { "owner": "_commitMerge", "class": "fixed-point-references", "witness": "test/writer-fixed-point.test.mjs" },
+ { "owner": "_applyWallFaceBatch", "class": "fixed-point", "witness": "test/coincident-partitions.test.mjs" },
+ { "owner": "_commitRoom", "class": "fixed-point", "witness": "test/coincident-partitions.test.mjs" },
+ { "owner": "_decorCommitDraft", "class": "fixed-point", "witness": "test/align-grid.test.mjs" },
+ { "owner": "_dmUp", "class": "fixed-point", "witness": "test/align-grid.test.mjs" },
+ { "owner": "_decorSaveText", "class": "fixed-point", "witness": "test/align-grid.test.mjs" },
+ { "owner": "_decorSaveShape", "class": "fixed-point", "witness": "test/align-grid.test.mjs" },
+ { "owner": "_dtUp", "class": "fixed-point", "witness": "test/align-grid.test.mjs" },
+ { "owner": "_deleteDecor", "class": "fixed-point", "witness": "test/align-grid.test.mjs" },
+ { "owner": "_furnPlace", "class": "continuous-transform-exemption", "witness": "test/align-grid.test.mjs" },
+ { "owner": "_saveBackdropDialog", "class": "fixed-point", "witness": "test/align-grid.test.mjs" },
+ { "owner": "_bdReset", "class": "fixed-point", "witness": "test/align-grid.test.mjs" },
+ { "owner": "_bdUp", "class": "fixed-point", "witness": "test/align-grid.test.mjs" }
+ ]
+}
diff --git a/test/wall-union-isolation.test.mjs b/test/wall-union-isolation.test.mjs
index f39a2575..5f284af3 100644
--- a/test/wall-union-isolation.test.mjs
+++ b/test/wall-union-isolation.test.mjs
@@ -128,7 +128,8 @@ test('#278 production source routes physical writers through one barrier and dec
assert.doesNotMatch(source, /_commitPhysicalGeometry\(this\._t\('history\.decor_/);
assert.match(source, /this\._rszSpaceCandidateRenderable\(preview\.space, preview\.sp\)/);
assert.match(source, /this\._checkSpacePhysicalGeometry\(candidate, spaceId\)\.ok/);
- assert.match(source, /if \(physicalChanged\)[\s\S]{0,1500}_pendingPhysicalWrites\.set\(state\.spaceId/,
+ assert.match(source,
+ /if \(physicalChanged\)[\s\S]{0,2500}_pendingPhysicalWrites\.set\((?:state|target)\.spaceId/,
'physical Undo/Redo must retain the deferred-write barrier');
assert.match(source, /if \(configChanged\)[\s\S]{0,300}_pendingPhysicalWrites\.clear\(\)/,
'an external baseline must invalidate pending local approvals');
diff --git a/test/writer-fixed-point.test.mjs b/test/writer-fixed-point.test.mjs
new file mode 100644
index 00000000..f62e5eac
--- /dev/null
+++ b/test/writer-fixed-point.test.mjs
@@ -0,0 +1,262 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { existsSync, readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import ts from 'typescript';
+
+import { finalizeWallChainSpace } from '../test-build/writer-fixed-point.js';
+import {
+ captureMarkerRoomReferences, restoreMarkerRoomReferences, rewriteMarkerRoomReferences,
+} from '../test-build/room-reference-transaction.js';
+import { optimizePlans, PLAN_MODEL_VERSION } from '../test-build/plan-optimizer.js';
+import { geometryOpenCuts } from '../test-build/plan-geometry-preflight.js';
+import { commitWallSegmentModel } from '../test-build/wall-segment-model.js';
+import {
+ GRID_PITCH, GRID_STEP_N, spaceModels,
+} from '../test-build/space-geometry.js';
+
+const NORM_W = 1000;
+const clone = (value) => structuredClone(value);
+const configOf = (space, markers = []) => ({
+ model_version: PLAN_MODEL_VERSION,
+ spaces: [space], markers, settings: {},
+});
+const finish = (config, seedIds) => {
+ const model = spaceModels(config)[0];
+ const raw = config.spaces[0];
+ const result = finalizeWallChainSpace(
+ raw, model, geometryOpenCuts(raw, model), seedIds,
+ {
+ pitch: GRID_STEP_N,
+ cellCm: Number(raw.cell_cm) > 0 ? Number(raw.cell_cm) : 5,
+ gridPitch: GRID_PITCH,
+ coordScale: NORM_W,
+ },
+ );
+ const committed = commitWallSegmentModel({ ...config, spaces: [result.space] }).config;
+ return { config: committed, report: result.report };
+};
+
+test('#477 finishes a two/three-segment collinear chain at the Optimize fixed point', () => {
+ for (const count of [2, 3]) {
+ const partitions = Array.from({ length: count }, (_, index) => ({
+ id: `chain-${index}`,
+ a: [index / count, 0.5], b: [(index + 1) / count, 0.5], cm: 15,
+ }));
+ const input = configOf({
+ id: 'chain', cell_cm: 5, rooms: [], partitions,
+ });
+ const before = clone(input);
+ const result = finish(input, partitions.map((partition) => partition.id));
+ assert.deepEqual(input, before, 'the finalizer must not mutate the live candidate');
+ assert.equal(result.report.partitionsMerged, count - 1);
+ assert.equal(result.config.spaces[0].partitions.length, 1);
+ assert.deepEqual(result.config.spaces[0].partitions[0], {
+ id: 'chain-0', a: [0, 0.5], b: [1, 0.5], cm: 15,
+ });
+ const optimized = optimizePlans(result.config, {});
+ assert.equal(optimized.changed, false);
+ assert.deepEqual(optimized.config, result.config);
+ }
+});
+
+test('#477 seed scope merges the touched chain but leaves unrelated historical seams alone', () => {
+ const input = configOf({
+ id: 'bounded', cell_cm: 5, rooms: [], partitions: [
+ { id: 'old-a', a: [0, 0.1], b: [0.25, 0.1], cm: 15 },
+ { id: 'old-b', a: [0.25, 0.1], b: [0.5, 0.1], cm: 15 },
+ { id: 'new-a', a: [0, 0.8], b: [0.25, 0.8], cm: 20 },
+ { id: 'new-b', a: [0.25, 0.8], b: [0.5, 0.8], cm: 20 },
+ ],
+ });
+ const result = finish(input, ['new-a', 'new-b']);
+ assert.equal(result.report.partitionsMerged, 1);
+ assert.deepEqual(result.config.spaces[0].partitions.map((partition) => partition.id),
+ ['old-a', 'old-b', 'new-a']);
+});
+
+test('#477 a missing writer seed cannot reconcile unrelated coincident partitions', () => {
+ const legacy = JSON.parse(readFileSync(
+ new URL('./fixtures/276-coincident-partition.json', import.meta.url), 'utf8',
+ ));
+ const baseline = optimizePlans({ ...legacy, spaces: [{
+ ...legacy.spaces[0], partitions: [], openings: [],
+ }] }, {}).config;
+ const input = clone(baseline);
+ input.spaces[0].partitions = clone(legacy.spaces[0].partitions);
+ input.spaces[0].openings = clone(legacy.spaces[0].openings);
+ const before = clone(input.spaces[0]);
+
+ const result = finish(input, ['writer-seed-that-no-longer-exists']);
+ assert.equal(result.report.partitionsReconciled, 0);
+ assert.deepEqual(result.config.spaces[0], before);
+});
+
+test('#477 finishes a positive coincident wall with opening rehost at the Optimize fixed point', () => {
+ const legacy = JSON.parse(readFileSync(
+ new URL('./fixtures/276-coincident-partition.json', import.meta.url), 'utf8',
+ ));
+ const baseline = optimizePlans({ ...legacy, spaces: [{
+ ...legacy.spaces[0], partitions: [], openings: [],
+ }] }, {}).config;
+ const raw = baseline.spaces[0];
+ raw.partitions = clone(legacy.spaces[0].partitions);
+ raw.openings = clone(legacy.spaces[0].openings);
+ const beforeOpening = clone(raw.openings[0]);
+
+ const result = finish(baseline, ['redundant']);
+ assert.equal(result.report.partitionsReconciled, 1);
+ assert.equal(result.report.openingsRehosted, 1);
+ assert.equal(result.config.spaces[0].partitions, undefined);
+ const opening = result.config.spaces[0].openings[0];
+ assert.equal(opening.host.kind, 'wall');
+ assert.equal(opening.x, 121 / 240);
+ assert.equal(opening.y, 0.5);
+ assert.equal(opening.length, beforeOpening.length);
+ assert.equal(opening.contact, beforeOpening.contact);
+ assert.deepEqual(opening.future_field, beforeOpening.future_field);
+ const optimized = optimizePlans(result.config, {});
+ assert.equal(optimized.changed, false);
+ assert.deepEqual(optimized.config, result.config);
+});
+
+test('#477 unsafe coincidence is fail-closed and byte-equivalent', () => {
+ const legacy = JSON.parse(readFileSync(
+ new URL('./fixtures/276-coincident-partition.json', import.meta.url), 'utf8',
+ ));
+ const current = optimizePlans({ ...legacy, spaces: [{
+ ...legacy.spaces[0], partitions: [], openings: [],
+ }] }, {}).config;
+ const withCarrier = () => {
+ const candidate = clone(current);
+ candidate.spaces[0].partitions = clone(legacy.spaces[0].partitions);
+ candidate.spaces[0].openings = clone(legacy.spaces[0].openings);
+ return candidate;
+ };
+ const variants = [];
+ const unknown = withCarrier();
+ unknown.spaces[0].partitions[0].future_semantics = true;
+ variants.push(unknown);
+ const column = withCarrier();
+ column.spaces[0].wall_columns = [{
+ id: 'column', shape: 'circle', center: [121 / 240, 0.5], cm: 20,
+ }];
+ variants.push(column);
+ const orphan = withCarrier();
+ orphan.spaces[0].openings[0].host.t = 2;
+ variants.push(orphan);
+
+ for (const input of variants) {
+ const before = clone(input.spaces[0]);
+ const result = finish(input, ['redundant']);
+ assert.equal(result.report.partitionsReconciled, 0);
+ assert.deepEqual(result.config.spaces[0], before);
+ }
+});
+
+test('#477 delete/merge rewrites direct and cross-space vacuum room references only', () => {
+ const markers = [
+ { id: 'direct', space: 's1', room_id: 'drop', hidden: true, future: { keep: 1 } },
+ { id: 'vac', space: 's2', vacuum: {
+ entity: 'vacuum.bot', segment_map: { 1: 'drop', 2: 'keep', 3: 'elsewhere' },
+ calibration: { keep: true },
+ } },
+ { id: 'unrelated', space: 's1', room_id: 'keep', custom: 7 },
+ ];
+ const merged = rewriteMarkerRoomReferences(markers, {
+ kind: 'merge', dropId: 'drop', keepId: 'keep',
+ });
+ assert.equal(merged.changed, 2);
+ assert.equal(merged.markers[0].room_id, 'keep');
+ assert.deepEqual(merged.markers[1].vacuum.segment_map,
+ { 1: 'keep', 2: 'keep', 3: 'elsewhere' });
+ assert.deepEqual(merged.markers[0].future, { keep: 1 });
+ assert.deepEqual(merged.markers[1].vacuum.calibration, { keep: true });
+ assert.deepEqual(merged.markers[2], markers[2]);
+
+ const later = clone(merged.markers);
+ later[0].future.keep = 2;
+ later[1].vacuum.calibration.keep = 'later';
+ restoreMarkerRoomReferences(later, merged.before);
+ assert.equal(later[0].room_id, 'drop');
+ assert.equal(later[0].future.keep, 2, 'unrelated later marker fields survive Undo');
+ assert.deepEqual(later[1].vacuum.segment_map,
+ { 1: 'drop', 2: 'keep', 3: 'elsewhere' });
+ assert.equal(later[1].vacuum.calibration.keep, 'later');
+
+ const deleted = rewriteMarkerRoomReferences(markers, { kind: 'delete', roomId: 'drop' });
+ assert.equal('room_id' in deleted.markers[0], false);
+ assert.deepEqual(deleted.markers[1].vacuum.segment_map,
+ { 2: 'keep', 3: 'elsewhere' });
+ assert.deepEqual(captureMarkerRoomReferences(markers, ['direct', 'vac']), deleted.before);
+
+ const onlyMap = rewriteMarkerRoomReferences([{
+ id: 'only-map', vacuum: { segment_map: { 9: 'drop' } },
+ }], { kind: 'delete', roomId: 'drop' });
+ assert.equal('vacuum' in onlyMap.markers[0], false);
+});
+
+test('#477 source contract routes every explicit chain finish through one finalizer', () => {
+ const runtime = readFileSync(new URL('../src/houseplan-editor-runtime.ts', import.meta.url), 'utf8');
+ const card = readFileSync(new URL('../src/houseplan-card.ts', import.meta.url), 'utf8');
+ const transaction = readFileSync(new URL('../src/draft-live-commit.ts', import.meta.url), 'utf8');
+ const finishTransaction = transaction.slice(
+ transaction.indexOf('export function commitWallChainFinishGeometry'),
+ transaction.indexOf('/** #461 bounded transaction'),
+ );
+ assert.match(runtime, /public _finishWallChain\(\): boolean[\s\S]*?_finalizeWallChainPartitions/);
+ assert.match(runtime, /_finishWallChain\(\)[\s\S]{0,300}btn\.reset/);
+ assert.match(runtime, /if \(!accepted\.length\)[\s\S]{0,300}_finalizeWallChainPartitions/);
+ assert.match(runtime, /_keepClosedAsPartitions[\s\S]*?_finalizeWallChainPartitions/);
+ assert.match(card, /_slideTo[\s\S]{0,500}_finishWallChain\(\)/);
+ assert.match(card, /_onHashChange[\s\S]{0,500}_finishWallChain\(\)/);
+ assert.match(card, /Escape releases the active wall chain[\s\S]{0,250}_finishWallChain\(\)/);
+ assert.doesNotMatch(runtime, /_markupClick[\s\S]{0,1200}_finalizeWallChainPartitions/,
+ 'the latency-critical terminal click must not run the finalizer');
+ assert.match(finishTransaction, /if \(!safe\) return rejectUnsafe\(runtime, before\);/);
+ assert.ok(
+ finishTransaction.indexOf('if (!safe) return rejectUnsafe(runtime, before);')
+ < finishTransaction.indexOf('adoptWallSegmentModelCandidateInPlace'),
+ 'the finish candidate must pass the physical guard before live adoption',
+ );
+});
+
+test('#477 executable writer manifest rejects an unclassified geometry writer', () => {
+ const manifest = JSON.parse(readFileSync(
+ new URL('./fixtures/477-writer-fixed-point-writers.json', import.meta.url), 'utf8',
+ ));
+ assert.equal(manifest.schema, 1);
+ const byOwner = new Map(manifest.cases.map((entry) => [entry.owner, entry]));
+ assert.equal(byOwner.size, manifest.cases.length, 'writer owners must be unique');
+ const repo = fileURLToPath(new URL('..', import.meta.url));
+ for (const entry of manifest.cases) {
+ assert.ok(entry.class && entry.witness, `incomplete manifest row: ${entry.owner}`);
+ assert.equal(existsSync(`${repo}/${entry.witness}`), true, `missing witness: ${entry.witness}`);
+ }
+
+ const source = readFileSync(new URL('../src/houseplan-editor-runtime.ts', import.meta.url), 'utf8');
+ const file = ts.createSourceFile(
+ 'houseplan-editor-runtime.ts', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS,
+ );
+ const discovered = new Set();
+ const visit = (node) => {
+ if (ts.isCallExpression(node)) {
+ const expression = node.expression.getText(file);
+ if (expression.endsWith('._commitPhysicalGeometry')
+ || expression.endsWith('._recordGeometry')) {
+ let owner = node.parent;
+ while (owner && !ts.isMethodDeclaration(owner) && !ts.isPropertyDeclaration(owner)) {
+ owner = owner.parent;
+ }
+ const name = owner?.name?.getText(file);
+ if (name && name !== '_commitPhysicalGeometry') discovered.add(name);
+ }
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(file);
+ assert.deepEqual(
+ [...discovered].filter((owner) => !byOwner.has(owner)), [],
+ 'every new geometry writer must declare its fixed-point witness or exception',
+ );
+});
diff --git a/tsconfig.test.json b/tsconfig.test.json
index 0c670fb8..0eea0885 100644
--- a/tsconfig.test.json
+++ b/tsconfig.test.json
@@ -33,14 +33,14 @@
"src/serialized-write-queue.ts",
"src/align-grid.ts",
"src/plan-optimizer.ts", "src/plan-optimize-write.ts", "src/space-reference-repair.ts", "src/space-deletion.ts", "src/space-copy.ts", "src/space-copy-runtime.ts",
- "src/plan-geometry-preflight.ts",
+ "src/plan-geometry-preflight.ts", "src/draft-live-preflight.ts", "src/draft-live-commit.ts",
"src/furniture.ts", "src/decor-assets.ts",
"src/floating-surface.ts", "src/floating-surface-controller.ts", "src/help-behavior.ts", "src/support-feedback.ts",
"src/hp-help.ts", "src/hp-dialog.ts", "src/hp-color-opacity.ts", "src/danger-confirm.ts",
"src/opening-placement.ts", "src/opening-dimensions.ts", "src/partition-openings.ts", "src/plan-snap-overlay.ts", "src/wall-face-graph.ts", "src/wall-face-repair.ts", "src/room-deletion.ts", "src/render/opening-symbol.ts",
"src/wall-thickness.ts",
"src/wall-segment-model.ts",
- "src/wall-merge.ts",
+ "src/wall-merge.ts", "src/writer-fixed-point.ts", "src/room-reference-transaction.ts",
"src/physical-geometry.ts",
"src/labs.ts", "src/iso-projection.ts", "src/iso-walls.ts", "src/iso-openings.ts", "src/iso-overlays.ts", "src/iso-scene-render.ts",
"src/open-spans.ts",