Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96e5311baf | ||
|
|
16eddacebf | ||
|
|
382d6e04f2 | ||
|
|
bffc4d0acc | ||
|
|
4a8da8ad0c | ||
|
|
888b6c9b79 | ||
|
|
2407e09456 | ||
|
|
984d9af232 | ||
|
|
1d67e8ceba | ||
|
|
c56f1a5ba9 |
No files matched your search
@@ -4,8 +4,29 @@ All notable changes to NextFloor, newest first. Every release lists what is **Ad
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Utility overview follows topology (Symcon 0.4.3):** List buildings inside a selected branch and storeys inside a building, with the matching immediate-child breakdown for locations and the all-locations view. Keep the current selection's totals above the view and use its actual name/path in the summary and side heading. Open child groups through the existing topology navigation and retain native area/room/device breakdowns at floor level, outdoor-owner counters, manual floor overrides, periods, trends, live zero values and Err: subtotals. Use a shared native-category discovery context for parent and child subtotals so linked categories in other buildings cannot inflate an individual building row. Preserve shared-source deduplication and legacy plans.
|
||||
|
||||
- **Unambiguous editor hierarchy (Symcon 0.4.1):** Move location, branch and building management into a separate Hierarchy dialog. Choose the building above the plan and add storeys only inside that selection; leave the right panel for existing floor, room and device properties. Group the room list by its linked native Symcon category, retain explicit room-name adoption and show the selected room's floor path. Building or metadata selection never reassigns floors or creates a storey. Preserve an empty building selection across refreshes and last-storey deletion, clear old plan selections on navigation and reject stale room edits. Replace the implicit floor-assignment dropdown with a dialog that names and captures the selected floor and changes its parent only when explicitly applied. Keep floor reordering and the lower-floor tracing layer inside the selected building or location's outside plan. Preserve legacy IDs, data points, per-location outdoors and permission keys.
|
||||
|
||||
- **Symcon version notices (Symcon 0.3.3):** Hide Home Assistant restart/companion-cache version banners in the Symcon designer, label the version tooltip for the Symcon module and rebuild the designer with the current release version. Actual load/save errors remain visible.
|
||||
|
||||
- **Native account form (Symcon 0.3.2):** Serialize every row of Symcon's iterable form List variables before saving rights, fixing rejected or lost room/device/object grants. Move the password and reset action below the user name. Reload all three tables and their target choices on account changes, preserving missing plan targets for their owner and clearing password/new-user inputs. Correct the designer button and documentation: `link:` opens a browser, whereas IPSView's internal Pro Console tab is a dedicated console integration, not a general module API.
|
||||
|
||||
### Added
|
||||
|
||||
- **Branch overviews, scoped outdoors and room moves (Symcon 0.4.2):** Select entire locations or branches above the editor, with read-only plan overviews and scoped 3D scenes. Create independent outdoor plans at location, branch and building level; preserve legacy location references, unique navigation keys, owner paths, thumbnails, isolated live values, stack ranks and roof exclusions through saves and backups. Add an explicit room-move dialog with destination building/storey and adjustable position, retaining room IDs, native links, openings, contained furniture/devices/notes and related geometry. Reject stale selections and duplicate destination devices before changing the plan. Migrate existing room/device grants only for unique stable identities when their floor changes, preserving permission levels and undo without granting access to additional users.
|
||||
|
||||
- **Five-level site topology (Symcon 0.4.0):** Add optional location → branch → building → floor → room groups with editor creation, naming, reassignment and protected removal. Preserve existing floor/room IDs and native grants when enabling the hierarchy. Each location owns an independent outdoor plan. Designer and tile navigation drill into the selected branch, keep the upper room menu hidden until a floor is selected, frame previews from the node's own geometry and clip room previews. Scope live values and utility overviews to the selected group, keep floor explosion/automatic roofs within each building, and limit whole-building transforms to its floors. Native permission choices expose complete paths. Persist topology and outdoor membership through schema validation and backups.
|
||||
|
||||
- **Hydronic status bindings (Symcon 0.3.1):** Add native object-tree status selection for individual heating/cooling circuits, every fresh-water cascade unit and the common plant. Floating cards and detail dialogs preserve formatted Integer aliases, including zero, live updates, unavailable values, archive access and scoped user permissions. Status readings remain read-only, hide unlinked rows and truncate long labels without widening cards; existing single stations retain their links when promoted to cascades.
|
||||
|
||||
- **Native accounts and scoped access (Symcon 0.3.0):** Add stable password login, hashed instance-local accounts managed exclusively in the native module form, admin editor access and independent global/room/placed-device/native-object view and control grants. Preserve whole-building geometry while removing unauthorized live bindings and values, restrict user-wide access to the visualization's data, and authorize archives, bulk actions, images, editor operations and transport ownership on the server. Add revocable HttpOnly sessions, CSRF checks, throttling, optional remembered login, password reset and one-use console admin tickets; tiles no longer carry admin credentials. User sessions do not persist private admin drafts in shared browser storage.
|
||||
- **Garden paving materials (Symcon 0.3.0):** Add paving stones, spaced garden stepping slabs and irregular natural-stone paths with independent scale/rotation, locally generated 3D textures and matching editor types.
|
||||
|
||||
- **Per-area texture controls (Symcon 0.2.30):** Set outdoor pattern size (5–2000%, 100% preserves the original metre scale) and rotation independently for every area. Persist and duplicate the settings, wrap rotation and bound scale, and apply inverse sampling transforms to solid/transparent and sloped geometry without altering outlines or neighbors. Legacy plans retain the original appearance; an info popup explains the controls.
|
||||
|
||||
- **Outdoor snapping and surface textures (Symcon 0.2.29):** Snap outdoor outlines to nearby corners and edges when drawing, moving or resizing, preserving whole-area geometry and Alt bypass. Add street, sidewalk, gravel, river and stream surfaces with schema persistence; river/stream areas default to cutting through surrounding surfaces. All outdoor materials use local metre-scaled procedural textures with distance filtering, including paving joints, asphalt grain, pebbles, vegetation, earth, wood and water ripples. Textures compose with floor fading, slopes, transparency and scene themes without external assets.
|
||||
|
||||
- **Fresh-water cascades with storage links (Symcon 0.2.28):** Rebuild the 3D station around separate primary and potable-water paths and a plate exchanger. Add up to 16 named parallel units with independent native temperature, power, pump and isolation-valve links; preserve legacy single-station bindings on edit. Share the supply/return, hot/cold-water and optional circulation headers, keep one compact cascade overlay, and open per-station readouts/commands with archive trends and existing read-only guards. Link a placed same-floor buffer through two primary-only pipes that follow placement and floor transforms; removal releases connections and subscriptions. Buffer colour layers interpolate measured probes only. Adding/removing units adjusts width and never sends device commands or invents parent utility totals.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
|
||||
var m={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",fr:"6312d0f61ebf",hu:"27ba348531dc",it:"1b705e76dd00",nb:"c5ea24fb9ef6",nl:"b64142c67c2e",pl:"8527a4930402",pt:"31857a2d2277",ro:"e3cb5f449f0f",sk:"320611594db0",sl:"8071691ceda3",sv:"711b911ec8da",tr:"7c83ce1c3372",zh:"50518d9f494e"};var M=globalThis,N=M.ShadowRoot&&(M.ShadyCSS===void 0||M.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,U=Symbol(),pe=new WeakMap,R=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==U)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(N&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=pe.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&pe.set(t,e))}return e}toString(){return this.cssText}},fe=i=>new R(typeof i=="string"?i:i+"",void 0,U),j=(i,...e)=>{let t=i.length===1?i[0]:e.reduce((n,r,o)=>n+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+i[o+1],i[0]);return new R(t,i,U)},ge=(i,e)=>{if(N)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),r=M.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}},q=N?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return fe(t)})(i):i;var{is:Ge,defineProperty:Oe,getOwnPropertyDescriptor:Ie,getOwnPropertyNames:Ze,getOwnPropertySymbols:Ve,getPrototypeOf:Ue}=Object,C=globalThis,be=C.trustedTypes,je=be?be.emptyScript:"",qe=C.reactiveElementPolyfillSupport,F=(i,e)=>i,J={toAttribute(i,e){switch(e){case Boolean:i=i?je:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},ke=(i,e)=>!Ge(i,e),we={attribute:!0,type:String,converter:J,reflect:!1,useDefault:!1,hasChanged:ke};Symbol.metadata??=Symbol("metadata"),C.litPropertyMetadata??=new WeakMap;var b=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=we){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){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Oe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:o}=Ie(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){let s=r?.call(this);o?.call(this,a),this.requestUpdate(e,s,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??we}static _$Ei(){if(this.hasOwnProperty(F("elementProperties")))return;let e=Ue(this);e.finalize(),e.l!==void 0&&(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"))){let t=this.properties,n=[...Ze(t),...Ve(t)];for(let r of n)this.createProperty(r,t[r])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,r]of t)this.elementProperties.set(n,r)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let r=this._$Eu(t,n);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let r of n)t.unshift(q(r))}else e!==void 0&&t.push(q(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?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),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ge(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.Line truncated
|
||||
\f\r]`,x=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Se=/-->/g,Ae=/>/g,S=RegExp(`>|${X}(?:([^\\s"'>=/]+)(${X}*=${X}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),De=/'/g,ze=/"/g,Fe=/^(?:script|style|textarea|title)$/i,oe=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),l=oe(1),ut=oe(2),mt=oe(3),z=Symbol.for("lit-noChange"),d=Symbol.for("lit-nothing"),Ee=new WeakMap,A=D.createTreeWalker(D,129);function xe(i,e){if(!ie(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ye!==void 0?ye.createHTML(e):e}var Ye=(i,e)=>{let t=i.length-1,n=[],r,o=e===2?"<svg>":e===3?"<math>":"",a=x;for(let s=0;s<t;s++){let h=i[s],u,p,_=-1,g=0;for(;g<h.length&&(a.lastIndex=g,p=a.exec(h),p!==null);)g=a.lastIndex,a===x?p[1]==="!--"?a=Se:p[1]!==void 0?a=Ae:p[2]!==void 0?(Fe.test(p[2])&&(r=RegExp("</"+p[2],"g")),a=S):p[3]!==void 0&&(a=S):a===S?p[0]===">"?(a=r??x,_=-1):p[1]===void 0?_=-2:(_=a.lastIndex-p[2].length,u=p[1],a=p[3]===void 0?S:p[3]==='"'?ze:De):a===ze||a===De?a=S:a===Se||a===Ae?a=x:(a=S,r=void 0);let k=a===S&&i[s+1].startsWith("/>")?" ":"";o+=a===x?h+Je:_>=0?(n.push(u),h.slice(0,_)+Te+h.slice(_)+v+k):h+v+(_===-2?s:k)}return[xe(i,o+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]},B=class i{constructor({strings:e,_$litType$:t},n){let r;this.parts=[];let o=0,a=0,s=e.length-1,h=this.parts,[u,p]=Ye(e,t);if(this.el=i.createElement(u,n),A.currentNode=this.el.content,t===2||t===3){let _=this.el.content.firstChild;_.replaceWith(..._.childNodes)}for(;(r=A.nextNode())!==null&&h.length<s;){if(r.nodeType===1){if(r.hasAttributes())for(let _ of r.getAttributeNames())if(_.endsWith(Te)){let g=p[a++],k=r.getAttribute(_).split(v),$=/([.?@])?(.*)/.exec(g);h.push({type:1,index:o,name:$[2],strings:k,ctor:$[1]==="."?Q:$[1]==="?"?ee:$[1]==="@"?te:T}),r.removeAttribute(_)}else _.startsWith(v)&&(h.push({type:6,index:o}),r.removeAttribute(_));if(Fe.test(r.tagName)){let _=r.textContent.split(v),g=_.length-1;if(g>0){r.textContent=K?K.emptyScript:"";for(let k=0;k<g;k++)r.append(_[k],H()),A.nextNode(),h.push({type:2,index:++o});r.append(_[g],H())}}}else if(r.nodeType===8)if(r.data===Re)h.push({type:2,index:o});else{let _=-1;for(;(_=r.data.indexOf(v,_+1))!==-1;)h.push({type:7,index:o}),_+=v.length-1}o++}}static createElement(e,t){let n=D.createElement("template");return n.innerHTML=e,n}};function E(i,e,t=i,n){if(e===z)return e;let r=n!==void 0?t._$Co?.[n]:t._$Cl,o=W(e)?void 0:e._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(i),r._$AT(i,t,n)),n!==void 0?(t._$Co??=[])[n]=r:t._$Cl=r),r!==void 0&&(e=E(i,r._$AS(i,e.values),r,n)),e}var Y=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??D).importNode(t,!0);A.currentNode=r;let o=A.nextNode(),a=0,s=0,h=n[0];for(;h!==void 0;){if(a===h.index){let u;h.type===2?u=new P(o,o.nextSibling,this,e):h.type===1?u=new h.ctor(o,h.name,h.strings,this,e):h.type===6&&(u=new ne(o,this,e)),this._$AV.push(u),h=n[++s]}a!==h?.index&&(o=A.nextNode(),a++)}return A.currentNode=D,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}},P=class i{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=d,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=E(this,e,t),W(e)?e===d||e==null||e===""?(this._$AH!==d&&this._$AR(),this._$AH=d):e!==this._$AH&&e!==z&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Xe(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!==d&&W(this._$AH)?this._$AA.nextSibling.data=e:this.T(D.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=B.createElement(xe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let o=new Y(r,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=Ee.get(e.strings);return t===void 0&&Ee.set(e.strings,t=new B(e)),t}k(e){ie(this._$AH)||(this._$AH=[],this._$AR());let t=this._$AH,n,r=0;for(let o of e)r===t.length?t.push(n=new i(this.O(H()),this.O(H()),this,this.options)):n=t[r],n._$AI(o),r++;r<t.length&&(this._$AR(n&&n._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let n=ve(e).nextSibling;ve(e).remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,o){this.type=1,this._$AH=d,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=o,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):thLine truncated
|
||||
var m={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",fr:"6312d0f61ebf",hu:"27ba348531dc",it:"1b705e76dd00",nb:"c5ea24fb9ef6",nl:"b64142c67c2e",pl:"8527a4930402",pt:"31857a2d2277",ro:"e3cb5f449f0f",sk:"320611594db0",sl:"8071691ceda3",sv:"711b911ec8da",tr:"7c83ce1c3372",zh:"50518d9f494e"};var M=globalThis,N=M.ShadowRoot&&(M.ShadyCSS===void 0||M.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,U=Symbol(),pe=new WeakMap,R=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==U)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(N&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=pe.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&pe.set(t,e))}return e}toString(){return this.cssText}},fe=i=>new R(typeof i=="string"?i:i+"",void 0,U),j=(i,...e)=>{let t=i.length===1?i[0]:e.reduce((n,r,o)=>n+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+i[o+1],i[0]);return new R(t,i,U)},ge=(i,e)=>{if(N)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),r=M.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}},q=N?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return fe(t)})(i):i;var{is:Ge,defineProperty:Oe,getOwnPropertyDescriptor:Ie,getOwnPropertyNames:Ze,getOwnPropertySymbols:Ve,getPrototypeOf:Ue}=Object,C=globalThis,be=C.trustedTypes,je=be?be.emptyScript:"",qe=C.reactiveElementPolyfillSupport,x=(i,e)=>i,J={toAttribute(i,e){switch(e){case Boolean:i=i?je:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},ke=(i,e)=>!Ge(i,e),we={attribute:!0,type:String,converter:J,reflect:!1,useDefault:!1,hasChanged:ke};Symbol.metadata??=Symbol("metadata"),C.litPropertyMetadata??=new WeakMap;var b=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=we){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){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Oe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:o}=Ie(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){let s=r?.call(this);o?.call(this,a),this.requestUpdate(e,s,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??we}static _$Ei(){if(this.hasOwnProperty(x("elementProperties")))return;let e=Ue(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(x("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(x("properties"))){let t=this.properties,n=[...Ze(t),...Ve(t)];for(let r of n)this.createProperty(r,t[r])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,r]of t)this.elementProperties.set(n,r)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let r=this._$Eu(t,n);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let r of n)t.unshift(q(r))}else e!==void 0&&t.push(q(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?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),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ge(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.Line truncated
|
||||
\f\r]`,F=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Se=/-->/g,Ae=/>/g,S=RegExp(`>|${X}(?:([^\\s"'>=/]+)(${X}*=${X}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),De=/'/g,ze=/"/g,xe=/^(?:script|style|textarea|title)$/i,oe=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),l=oe(1),ut=oe(2),mt=oe(3),z=Symbol.for("lit-noChange"),d=Symbol.for("lit-nothing"),Ee=new WeakMap,A=D.createTreeWalker(D,129);function Fe(i,e){if(!ie(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ye!==void 0?ye.createHTML(e):e}var Ye=(i,e)=>{let t=i.length-1,n=[],r,o=e===2?"<svg>":e===3?"<math>":"",a=F;for(let s=0;s<t;s++){let h=i[s],u,p,_=-1,g=0;for(;g<h.length&&(a.lastIndex=g,p=a.exec(h),p!==null);)g=a.lastIndex,a===F?p[1]==="!--"?a=Se:p[1]!==void 0?a=Ae:p[2]!==void 0?(xe.test(p[2])&&(r=RegExp("</"+p[2],"g")),a=S):p[3]!==void 0&&(a=S):a===S?p[0]===">"?(a=r??F,_=-1):p[1]===void 0?_=-2:(_=a.lastIndex-p[2].length,u=p[1],a=p[3]===void 0?S:p[3]==='"'?ze:De):a===ze||a===De?a=S:a===Se||a===Ae?a=F:(a=S,r=void 0);let k=a===S&&i[s+1].startsWith("/>")?" ":"";o+=a===F?h+Je:_>=0?(n.push(u),h.slice(0,_)+Te+h.slice(_)+v+k):h+v+(_===-2?s:k)}return[Fe(i,o+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]},B=class i{constructor({strings:e,_$litType$:t},n){let r;this.parts=[];let o=0,a=0,s=e.length-1,h=this.parts,[u,p]=Ye(e,t);if(this.el=i.createElement(u,n),A.currentNode=this.el.content,t===2||t===3){let _=this.el.content.firstChild;_.replaceWith(..._.childNodes)}for(;(r=A.nextNode())!==null&&h.length<s;){if(r.nodeType===1){if(r.hasAttributes())for(let _ of r.getAttributeNames())if(_.endsWith(Te)){let g=p[a++],k=r.getAttribute(_).split(v),$=/([.?@])?(.*)/.exec(g);h.push({type:1,index:o,name:$[2],strings:k,ctor:$[1]==="."?Q:$[1]==="?"?ee:$[1]==="@"?te:T}),r.removeAttribute(_)}else _.startsWith(v)&&(h.push({type:6,index:o}),r.removeAttribute(_));if(xe.test(r.tagName)){let _=r.textContent.split(v),g=_.length-1;if(g>0){r.textContent=K?K.emptyScript:"";for(let k=0;k<g;k++)r.append(_[k],H()),A.nextNode(),h.push({type:2,index:++o});r.append(_[g],H())}}}else if(r.nodeType===8)if(r.data===Re)h.push({type:2,index:o});else{let _=-1;for(;(_=r.data.indexOf(v,_+1))!==-1;)h.push({type:7,index:o}),_+=v.length-1}o++}}static createElement(e,t){let n=D.createElement("template");return n.innerHTML=e,n}};function E(i,e,t=i,n){if(e===z)return e;let r=n!==void 0?t._$Co?.[n]:t._$Cl,o=W(e)?void 0:e._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(i),r._$AT(i,t,n)),n!==void 0?(t._$Co??=[])[n]=r:t._$Cl=r),r!==void 0&&(e=E(i,r._$AS(i,e.values),r,n)),e}var Y=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??D).importNode(t,!0);A.currentNode=r;let o=A.nextNode(),a=0,s=0,h=n[0];for(;h!==void 0;){if(a===h.index){let u;h.type===2?u=new P(o,o.nextSibling,this,e):h.type===1?u=new h.ctor(o,h.name,h.strings,this,e):h.type===6&&(u=new ne(o,this,e)),this._$AV.push(u),h=n[++s]}a!==h?.index&&(o=A.nextNode(),a++)}return A.currentNode=D,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}},P=class i{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=d,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=E(this,e,t),W(e)?e===d||e==null||e===""?(this._$AH!==d&&this._$AR(),this._$AH=d):e!==this._$AH&&e!==z&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Xe(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!==d&&W(this._$AH)?this._$AA.nextSibling.data=e:this.T(D.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=B.createElement(Fe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let o=new Y(r,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=Ee.get(e.strings);return t===void 0&&Ee.set(e.strings,t=new B(e)),t}k(e){ie(this._$AH)||(this._$AH=[],this._$AR());let t=this._$AH,n,r=0;for(let o of e)r===t.length?t.push(n=new i(this.O(H()),this.O(H()),this,this.options)):n=t[r],n._$AI(o),r++;r<t.length&&(this._$AR(n&&n._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let n=ve(e).nextSibling;ve(e).remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,o){this.type=1,this._$AH=d,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=o,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):thLine truncated
|
||||
<input type="checkbox" .checked=${e} @change=${o=>r(rt(o))} />
|
||||
<span>${i.t(t)}${n?l`<small>${i.t(n)}</small>`:d}</span>
|
||||
</label>`}var c=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r)),le=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r||void 0));function w(i,e,t,n,r){return l`<label class="field"
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
|
||||
var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,nt=Symbol(),_t=new WeakMap,D=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==nt)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o,n=this.t;if(G&&t===void 0){let i=n!==void 0&&n.length===1;i&&(t=_t.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&_t.set(n,t))}return t}toString(){return this.cssText}},wt=r=>new D(typeof r=="string"?r:r+"",void 0,nt),y=(r,...t)=>{let n=r.length===1?r[0]:t.reduce((i,e,o)=>i+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(e)+r[o+1],r[0]);return new D(n,r,nt)},St=(r,t)=>{if(G)r.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(let n of t){let i=document.createElement("style"),e=Y.litNonce;e!==void 0&&i.setAttribute("nonce",e),i.textContent=n.cssText,r.appendChild(i)}},it=G?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let n="";for(let i of t.cssRules)n+=i.cssText;return wt(n)})(r):r;var{is:Jt,defineProperty:Xt,getOwnPropertyDescriptor:Yt,getOwnPropertyNames:Gt,getOwnPropertySymbols:Qt,getPrototypeOf:te}=Object,Q=globalThis,At=Q.trustedTypes,ee=At?At.emptyScript:"",ne=Q.reactiveElementPolyfillSupport,V=(r,t)=>r,rt={toAttribute(r,t){switch(t){case Boolean:r=r?ee:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let n=r;switch(t){case Boolean:n=r!==null;break;case Number:n=r===null?null:Number(r);break;case Object:case Array:try{n=JSON.parse(r)}catch{n=null}}return n}},Ht=(r,t)=>!Jt(r,t),Et={attribute:!0,type:String,converter:rt,reflect:!1,useDefault:!1,hasChanged:Ht};Symbol.metadata??=Symbol("metadata"),Q.litPropertyMetadata??=new WeakMap;var w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=Et){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){let i=Symbol(),e=this.getPropertyDescriptor(t,i,n);e!==void 0&&Xt(this.prototype,t,e)}}static getPropertyDescriptor(t,n,i){let{get:e,set:o}=Yt(this.prototype,t)??{get(){return this[n]},set(s){this[n]=s}};return{get:e,set(s){let c=e?.call(this);o?.call(this,s),this.requestUpdate(t,c,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Et}static _$Ei(){if(this.hasOwnProperty(V("elementProperties")))return;let t=te(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(V("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(V("properties"))){let n=this.properties,i=[...Gt(n),...Qt(n)];for(let e of i)this.createProperty(e,n[e])}let t=this[Symbol.metadata];if(t!==null){let n=litPropertyMetadata.get(t);if(n!==void 0)for(let[i,e]of n)this.elementProperties.set(i,e)}this._$Eh=new Map;for(let[n,i]of this.elementProperties){let e=this._$Eu(n,i);e!==void 0&&this._$Eh.set(e,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let n=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let e of i)n.unshift(it(e))}else t!==void 0&&n.push(it(t));return n}static _$Eu(t,n){let i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.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(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,n=this.constructor.elementProperties;for(let i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return St(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){let i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(e!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:rt).toAttribute(n,i.type);this._$Em=t,o==null?this.removeAttribute(e):this.setAttriLine truncated
|
||||
\f\r]`,j=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Rt=/-->/g,Nt=/>/g,k=RegExp(`>|${ot}(?:([^\\s"'>=/]+)(${ot}*=${ot}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),Pt=/'/g,Mt=/"/g,zt=/^(?:script|style|textarea|title)$/i,pt=r=>(t,...n)=>({_$litType$:r,strings:t,values:n}),d=pt(1),ye=pt(2),ve=pt(3),N=Symbol.for("lit-noChange"),a=Symbol.for("lit-nothing"),Tt=new WeakMap,C=R.createTreeWalker(R,129);function Ut(r,t){if(!ht(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ct!==void 0?Ct.createHTML(t):t}var oe=(r,t)=>{let n=r.length-1,i=[],e,o=t===2?"<svg>":t===3?"<math>":"",s=j;for(let c=0;c<n;c++){let l=r[c],h,p,u=-1,m=0;for(;m<l.length&&(s.lastIndex=m,p=s.exec(l),p!==null);)m=s.lastIndex,s===j?p[1]==="!--"?s=Rt:p[1]!==void 0?s=Nt:p[2]!==void 0?(zt.test(p[2])&&(e=RegExp("</"+p[2],"g")),s=k):p[3]!==void 0&&(s=k):s===k?p[0]===">"?(s=e??j,u=-1):p[1]===void 0?u=-2:(u=s.lastIndex-p[2].length,h=p[1],s=p[3]===void 0?k:p[3]==='"'?Mt:Pt):s===Mt||s===Pt?s=k:s===Rt||s===Nt?s=j:(s=k,e=void 0);let $=s===k&&r[c+1].startsWith("/>")?" ":"";o+=s===j?l+ie:u>=0?(i.push(h),l.slice(0,u)+Ot+l.slice(u)+A+$):l+A+(u===-2?c:$)}return[Ut(r,o+(r[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},K=class r{constructor({strings:t,_$litType$:n},i){let e;this.parts=[];let o=0,s=0,c=t.length-1,l=this.parts,[h,p]=oe(t,n);if(this.el=r.createElement(h,i),C.currentNode=this.el.content,n===2||n===3){let u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(e=C.nextNode())!==null&&l.length<c;){if(e.nodeType===1){if(e.hasAttributes())for(let u of e.getAttributeNames())if(u.endsWith(Ot)){let m=p[s++],$=e.getAttribute(u).split(A),_=/([.?@])?(.*)/.exec(m);l.push({type:1,index:o,name:_[2],strings:$,ctor:_[1]==="."?at:_[1]==="?"?lt:_[1]==="@"?ct:M}),e.removeAttribute(u)}else u.startsWith(A)&&(l.push({type:6,index:o}),e.removeAttribute(u));if(zt.test(e.tagName)){let u=e.textContent.split(A),m=u.length-1;if(m>0){e.textContent=tt?tt.emptyScript:"";for(let $=0;$<m;$++)e.append(u[$],B()),C.nextNode(),l.push({type:2,index:++o});e.append(u[m],B())}}}else if(e.nodeType===8)if(e.data===Ft)l.push({type:2,index:o});else{let u=-1;for(;(u=e.data.indexOf(A,u+1))!==-1;)l.push({type:7,index:o}),u+=A.length-1}o++}}static createElement(t,n){let i=R.createElement("template");return i.innerHTML=t,i}};function P(r,t,n=r,i){if(t===N)return t;let e=i!==void 0?n._$Co?.[i]:n._$Cl,o=I(t)?void 0:t._$litDirective$;return e?.constructor!==o&&(e?._$AO?.(!1),o===void 0?e=void 0:(e=new o(r),e._$AT(r,n,i)),i!==void 0?(n._$Co??=[])[i]=e:n._$Cl=e),e!==void 0&&(t=P(r,e._$AS(r,t.values),e,i)),t}var st=class{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:n},parts:i}=this._$AD,e=(t?.creationScope??R).importNode(n,!0);C.currentNode=e;let o=C.nextNode(),s=0,c=0,l=i[0];for(;l!==void 0;){if(s===l.index){let h;l.type===2?h=new W(o,o.nextSibling,this,t):l.type===1?h=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(h=new ut(o,this,t)),this._$AV.push(h),l=i[++c]}s!==l?.index&&(o=C.nextNode(),s++)}return C.currentNode=R,e}p(t){let n=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}},W=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,n,i,e){this.type=2,this._$AH=a,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=i,this.options=e,this._$Cv=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,n=this._$AM;return n!==void 0&&t?.nodeType===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=P(this,t,n),I(t)?t===a||t==null||t===""?(this._$AH!==a&&this._$AR(),this._$AH=a):t!==this._$AH&&t!==N&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):re(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==a&&I(this._$AH)?this._$AA.nextSibling.data=t:this.T(R.createTextNode(t)),this._$AH=t}$(t){let{values:n,_$litType$:i}=t,e=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=K.createElement(Ut(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===e)this._$AH.p(n);else{let o=new st(e,this),s=o.u(this.options);o.p(n),this.T(s),this._$AH=o}}_$AC(t){let n=Tt.get(t.strings);return n===void 0&&Tt.set(t.strings,n=new K(t)),n}k(t){ht(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,i,e=0;for(let o of t)e===n.length?n.push(i=new r(this.O(B()),this.O(B()),this,this.options)):i=n[e],i._$AI(o),e++;e<n.length&&(this._$AR(i&&i._$AB.nextSibling,e),n.length=e)}_$AR(t=this._$AA.nextSibling,n){for(this._$AP?.(!1,!0,n);t!==this._$AB;){let i=kt(t).nextSibling;kt(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},M=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,e,o){this.type=1,this._$AH=a,this._$AN=void 0,this.element=t,this.name=n,this._$AM=e,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=Line truncated
|
||||
var G=globalThis,Q=G.ShadowRoot&&(G.ShadyCSS===void 0||G.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,it=Symbol(),wt=new WeakMap,j=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==it)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o,n=this.t;if(Q&&t===void 0){let i=n!==void 0&&n.length===1;i&&(t=wt.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&wt.set(n,t))}return t}toString(){return this.cssText}},At=r=>new j(typeof r=="string"?r:r+"",void 0,it),y=(r,...t)=>{let n=r.length===1?r[0]:t.reduce((i,e,s)=>i+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(e)+r[s+1],r[0]);return new j(n,r,it)},St=(r,t)=>{if(Q)r.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(let n of t){let i=document.createElement("style"),e=G.litNonce;e!==void 0&&i.setAttribute("nonce",e),i.textContent=n.cssText,r.appendChild(i)}},rt=Q?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let n="";for(let i of t.cssRules)n+=i.cssText;return At(n)})(r):r;var{is:Xt,defineProperty:Yt,getOwnPropertyDescriptor:Gt,getOwnPropertyNames:Qt,getOwnPropertySymbols:te,getPrototypeOf:ee}=Object,tt=globalThis,Et=tt.trustedTypes,ne=Et?Et.emptyScript:"",ie=tt.reactiveElementPolyfillSupport,B=(r,t)=>r,st={toAttribute(r,t){switch(t){case Boolean:r=r?ne:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let n=r;switch(t){case Boolean:n=r!==null;break;case Number:n=r===null?null:Number(r);break;case Object:case Array:try{n=JSON.parse(r)}catch{n=null}}return n}},kt=(r,t)=>!Xt(r,t),Ht={attribute:!0,type:String,converter:st,reflect:!1,useDefault:!1,hasChanged:kt};Symbol.metadata??=Symbol("metadata"),tt.litPropertyMetadata??=new WeakMap;var w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=Ht){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){let i=Symbol(),e=this.getPropertyDescriptor(t,i,n);e!==void 0&&Yt(this.prototype,t,e)}}static getPropertyDescriptor(t,n,i){let{get:e,set:s}=Gt(this.prototype,t)??{get(){return this[n]},set(o){this[n]=o}};return{get:e,set(o){let c=e?.call(this);s?.call(this,o),this.requestUpdate(t,c,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ht}static _$Ei(){if(this.hasOwnProperty(B("elementProperties")))return;let t=ee(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(B("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(B("properties"))){let n=this.properties,i=[...Qt(n),...te(n)];for(let e of i)this.createProperty(e,n[e])}let t=this[Symbol.metadata];if(t!==null){let n=litPropertyMetadata.get(t);if(n!==void 0)for(let[i,e]of n)this.elementProperties.set(i,e)}this._$Eh=new Map;for(let[n,i]of this.elementProperties){let e=this._$Eu(n,i);e!==void 0&&this._$Eh.set(e,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let n=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let e of i)n.unshift(rt(e))}else t!==void 0&&n.push(rt(t));return n}static _$Eu(t,n){let i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.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(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,n=this.constructor.elementProperties;for(let i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return St(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){let i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(e!==void 0&&i.reflect===!0){let s=(i.converter?.toAttribute!==void 0?i.converter:st).toAttribute(n,i.type);this._$Em=t,s==null?this.removeAttribute(e):this.setALine truncated
|
||||
\f\r]`,I=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Nt=/-->/g,Pt=/>/g,k=RegExp(`>|${ot}(?:([^\\s"'>=/]+)(${ot}*=${ot}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),Mt=/'/g,Tt=/"/g,Ut=/^(?:script|style|textarea|title)$/i,ft=r=>(t,...n)=>({_$litType$:r,strings:t,values:n}),d=ft(1),ve=ft(2),xe=ft(3),N=Symbol.for("lit-noChange"),a=Symbol.for("lit-nothing"),Ot=new WeakMap,C=R.createTreeWalker(R,129);function Lt(r,t){if(!pt(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Rt!==void 0?Rt.createHTML(t):t}var oe=(r,t)=>{let n=r.length-1,i=[],e,s=t===2?"<svg>":t===3?"<math>":"",o=I;for(let c=0;c<n;c++){let l=r[c],h,p,u=-1,g=0;for(;g<l.length&&(o.lastIndex=g,p=o.exec(l),p!==null);)g=o.lastIndex,o===I?p[1]==="!--"?o=Nt:p[1]!==void 0?o=Pt:p[2]!==void 0?(Ut.test(p[2])&&(e=RegExp("</"+p[2],"g")),o=k):p[3]!==void 0&&(o=k):o===k?p[0]===">"?(o=e??I,u=-1):p[1]===void 0?u=-2:(u=o.lastIndex-p[2].length,h=p[1],o=p[3]===void 0?k:p[3]==='"'?Tt:Mt):o===Tt||o===Mt?o=k:o===Nt||o===Pt?o=I:(o=k,e=void 0);let $=o===k&&r[c+1].startsWith("/>")?" ":"";s+=o===I?l+re:u>=0?(i.push(h),l.slice(0,u)+Ft+l.slice(u)+S+$):l+S+(u===-2?c:$)}return[Lt(r,s+(r[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},q=class r{constructor({strings:t,_$litType$:n},i){let e;this.parts=[];let s=0,o=0,c=t.length-1,l=this.parts,[h,p]=oe(t,n);if(this.el=r.createElement(h,i),C.currentNode=this.el.content,n===2||n===3){let u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(e=C.nextNode())!==null&&l.length<c;){if(e.nodeType===1){if(e.hasAttributes())for(let u of e.getAttributeNames())if(u.endsWith(Ft)){let g=p[o++],$=e.getAttribute(u).split(S),_=/([.?@])?(.*)/.exec(g);l.push({type:1,index:s,name:_[2],strings:$,ctor:_[1]==="."?lt:_[1]==="?"?ct:_[1]==="@"?ut:T}),e.removeAttribute(u)}else u.startsWith(S)&&(l.push({type:6,index:s}),e.removeAttribute(u));if(Ut.test(e.tagName)){let u=e.textContent.split(S),g=u.length-1;if(g>0){e.textContent=et?et.emptyScript:"";for(let $=0;$<g;$++)e.append(u[$],K()),C.nextNode(),l.push({type:2,index:++s});e.append(u[g],K())}}}else if(e.nodeType===8)if(e.data===zt)l.push({type:2,index:s});else{let u=-1;for(;(u=e.data.indexOf(S,u+1))!==-1;)l.push({type:7,index:s}),u+=S.length-1}s++}}static createElement(t,n){let i=R.createElement("template");return i.innerHTML=t,i}};function M(r,t,n=r,i){if(t===N)return t;let e=i!==void 0?n._$Co?.[i]:n._$Cl,s=W(t)?void 0:t._$litDirective$;return e?.constructor!==s&&(e?._$AO?.(!1),s===void 0?e=void 0:(e=new s(r),e._$AT(r,n,i)),i!==void 0?(n._$Co??=[])[i]=e:n._$Cl=e),e!==void 0&&(t=M(r,e._$AS(r,t.values),e,i)),t}var at=class{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:n},parts:i}=this._$AD,e=(t?.creationScope??R).importNode(n,!0);C.currentNode=e;let s=C.nextNode(),o=0,c=0,l=i[0];for(;l!==void 0;){if(o===l.index){let h;l.type===2?h=new Z(s,s.nextSibling,this,t):l.type===1?h=new l.ctor(s,l.name,l.strings,this,t):l.type===6&&(h=new dt(s,this,t)),this._$AV.push(h),l=i[++c]}o!==l?.index&&(s=C.nextNode(),o++)}return C.currentNode=R,e}p(t){let n=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}},Z=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,n,i,e){this.type=2,this._$AH=a,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=i,this.options=e,this._$Cv=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,n=this._$AM;return n!==void 0&&t?.nodeType===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=M(this,t,n),W(t)?t===a||t==null||t===""?(this._$AH!==a&&this._$AR(),this._$AH=a):t!==this._$AH&&t!==N&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):se(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==a&&W(this._$AH)?this._$AA.nextSibling.data=t:this.T(R.createTextNode(t)),this._$AH=t}$(t){let{values:n,_$litType$:i}=t,e=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=q.createElement(Lt(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===e)this._$AH.p(n);else{let s=new at(e,this),o=s.u(this.options);s.p(n),this.T(o),this._$AH=s}}_$AC(t){let n=Ot.get(t.strings);return n===void 0&&Ot.set(t.strings,n=new q(t)),n}k(t){pt(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,i,e=0;for(let s of t)e===n.length?n.push(i=new r(this.O(K()),this.O(K()),this,this.options)):i=n[e],i._$AI(s),e++;e<n.length&&(this._$AR(i&&i._$AB.nextSibling,e),n.length=e)}_$AR(t=this._$AA.nextSibling,n){for(this._$AP?.(!1,!0,n);t!==this._$AB;){let i=Ct(t).nextSibling;Ct(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,e,s){this.type=1,this._$AH=a,this._$AN=void 0,this.element=t,this.name=n,this._$AM=e,this.options=s,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=Line truncated
|
||||
:host {
|
||||
--nf-text: var(--primary-text-color, #e1e1e1);
|
||||
--nf-muted: var(--secondary-text-color, #9b9b9b);
|
||||
@@ -29,7 +29,7 @@ var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&
|
||||
font-family: var(--nf-font);
|
||||
color: var(--nf-text);
|
||||
}
|
||||
`,Ve=y`
|
||||
`,je=y`
|
||||
:host([readable]) {
|
||||
--secondary-text-color: var(--primary-text-color, #e1e1e1);
|
||||
--divider-color: color-mix(in srgb, var(--primary-text-color, #e1e1e1) 40%, transparent);
|
||||
@@ -40,7 +40,7 @@ var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&
|
||||
:host([readable]) .nf-overlay {
|
||||
zoom: 1.2;
|
||||
}
|
||||
`,je=y`
|
||||
`,Be=y`
|
||||
/* a group of switches: one rounded pill, the active one tinted with the accent */
|
||||
.nf-seg {
|
||||
display: inline-flex;
|
||||
@@ -203,32 +203,33 @@ var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&
|
||||
min-height: 40px;
|
||||
}
|
||||
}
|
||||
`;function gt(r,t){let n=new Set;return t.flatMap(i=>{let e=String(r?.states[i]?.attributes.symcon_source_entity||i),o=r?.states[e]?.attributes,s=Number(o?.symcon_id);return!s||!o?.symcon_archive||n.has(s)?[]:(n.add(s),[e])})}var Vt,bt=class extends v{static properties={hass:{attribute:!1},ids:{attribute:!1},label:{attribute:!1},busy:{state:!0},error:{state:!0}};constructor(){super(),this.ids=[],this.label="",this.busy=!1,this.error=""}async open(t){t.stopPropagation(),this.busy=!0,this.error="";try{let n=new URL("./nextfloor-trend.js?v=84417e0b2573",import.meta.url).href;await(await(Vt??=import(n).catch(e=>{throw Vt=void 0,e}))).openTrend(this.hass,this.ids,this.label)}catch(n){this.error=n instanceof Error?n.message:String(n)}finally{this.busy=!1}}render(){if(!gt(this.hass,this.ids).length)return a;let t=this.label?`Trend anzeigen: ${this.label}`:"Trend anzeigen";return d`<button type="button" title=${t} aria-label=${t} aria-haspopup="dialog" ?disabled=${this.busy} @pointerdown=${n=>n.stopPropagation()} @click=${n=>{this.open(n)}}>
|
||||
`;function bt(r,t){let n=new Set;return t.flatMap(i=>{let e=String(r?.states[i]?.attributes.symcon_source_entity||i),s=r?.states[e]?.attributes,o=Number(s?.symcon_id);return!o||!s?.symcon_archive||n.has(o)?[]:(n.add(o),[e])})}var jt,yt=class extends v{static properties={hass:{attribute:!1},ids:{attribute:!1},label:{attribute:!1},busy:{state:!0},error:{state:!0}};constructor(){super(),this.ids=[],this.label="",this.busy=!1,this.error=""}async open(t){t.stopPropagation(),this.busy=!0,this.error="";try{let n=new URL("./nextfloor-trend.js?v=84417e0b2573",import.meta.url).href;await(await(jt??=import(n).catch(e=>{throw jt=void 0,e}))).openTrend(this.hass,this.ids,this.label)}catch(n){this.error=n instanceof Error?n.message:String(n)}finally{this.busy=!1}}render(){if(!bt(this.hass,this.ids).length)return a;let t=this.label?`Trend anzeigen: ${this.label}`:"Trend anzeigen";return d`<button type="button" title=${t} aria-label=${t} aria-haspopup="dialog" ?disabled=${this.busy} @pointerdown=${n=>n.stopPropagation()} @click=${n=>{this.open(n)}}>
|
||||
<svg width="12" height="12" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M3 2v15h15M5 13l4-5 4 2 4-6"/></svg>
|
||||
</button>${this.error?d`<span role="alert">${this.error}</span>`:a}`}static styles=y`:host{position:relative;display:inline-flex;flex:0 0 18px;width:18px;height:18px;vertical-align:middle;margin-left:3px;font-weight:normal;line-height:0}button{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:18px;height:18px;padding:2px;border:0;border-radius:3px;background:transparent;color:var(--nf-accent,#40c8ff);opacity:.8;cursor:pointer}svg{display:block;flex-shrink:0}button:hover,button:focus-visible{opacity:1;background:#40c8ff18}button:focus-visible{outline:1px solid currentColor;outline-offset:1px}button:disabled{opacity:.4}span{position:absolute;right:0;top:22px;z-index:10;box-sizing:border-box;width:200px;padding:8px;border:1px solid #ff9b9b50;border-radius:6px;background:var(--nf-chrome-solid,#1c1c1c);font:12px/1.4 system-ui;color:#ff9b9b;white-space:normal}`};customElements.get("nf-trend-button")||customElements.define("nf-trend-button",bt);function X(r,t,n=""){let i=gt(r,t);return i.length?d`<nf-trend-button .hass=${r} .ids=${i} .label=${n}></nf-trend-button>`:a}var pe={heating_manifold:"Heiz-/K\xFChlkreisverteiler",buffer_tank:"Pufferspeicher",freshwater_station:"Frischwasserstation"},Bt=r=>r.name||pe[r.type],It=r=>r.name||{heating:"Heizkreis",cooling:"K\xFChlkreis",changeover:"Heizen / K\xFChlen",pump:"Vorschubpumpe"}[r.kind],Kt=(r,t)=>t.kind==="pump"?"Pumpenkreis":t.kind==="cooling"?"K\xFChlen":t.kind==="heating"?"Heizen":g(t.mode_entity)&&b(r.states[t.mode_entity])===null?"Betriebsart \u2013":Number(g(t.mode_entity)?b(r.states[t.mode_entity]):0)===(t.cooling_value??1)?"K\xFChlen":"Heizen",et=(r,t,n)=>[f(r,"Vorlauf",t),f(r,"R\xFCcklauf",n)].filter(i=>i!==null),yt=(r,t,n)=>{let i=E(r,t),e=E(r,n);return i===null||e===null?a:d`<div class="reading delta"><span>ΔT · VL − RL</span><b>${(i-e).toLocaleString(r.language,{maximumFractionDigits:1})} K</b></div>`};function Wt(r,t){let n=F(t),i=t.type==="freshwater_station"?[]:et(r,n.flow,n.return);if(t.type==="buffer_tank"&&i.unshift(...[...n.sensors??[]].sort((e,o)=>o.level-e.level).flatMap(e=>{let o=f(r,e.name||"F\xFChler",e.entity);return o?[o]:[]})),t.type==="freshwater_station"){let e=f(r,"Zirkulation",n.circulation_temperature);e&&i.push(e)}for(let e of t.values??[]){let o=f(r,e.label||String(e.entity&&r.states[e.entity]?.attributes.friendly_name||"Wert"),e.entity);o&&i.push({...o,icon:e.icon})}return i}function qt(r,t){return[...et(r,t.flow,t.return),...[["Kaltwasser",t.cold_water],["Trinkwarmwasser",t.hot_water],["Pumpenleistung",t.power]].flatMap(([n,i])=>{let e=f(r,n,i);return e?[e]:[]})]}var vt=(r,t)=>`K${t+1} \xB7 ${r.name||`Station ${t+1}`}`,H=(r,t)=>d`<div class="reading" data-source=${t.id}><span>${t.icon?.startsWith("mdi:")?d`<ha-icon icon=${t.icon}></ha-icon>`:t.icon||a} ${t.label}</span><b>${t.text}${X(r,[t.id],t.label)}</b></div>`;function L(r,t,n){let i=S(r,n);return i.id?d`<div class="reading" data-source=${i.id}><span>${t}<small>${i.feedback?"Ist":"Soll"}</small></span><b><i class="lamp" style=${`background:${i.running===null?"#888":i.running?"#6fe1a2":"#465361"}`}></i>${U(r.states[i.id])}${X(r,[i.id],t)}</b></div>`:a}var Zt=y`
|
||||
</button>${this.error?d`<span role="alert">${this.error}</span>`:a}`}static styles=y`:host{position:relative;display:inline-flex;flex:0 0 18px;width:18px;height:18px;vertical-align:middle;margin-left:3px;font-weight:normal;line-height:0}button{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:18px;height:18px;padding:2px;border:0;border-radius:3px;background:transparent;color:var(--nf-accent,#40c8ff);opacity:.8;cursor:pointer}svg{display:block;flex-shrink:0}button:hover,button:focus-visible{opacity:1;background:#40c8ff18}button:focus-visible{outline:1px solid currentColor;outline-offset:1px}button:disabled{opacity:.4}span{position:absolute;right:0;top:22px;z-index:10;box-sizing:border-box;width:200px;padding:8px;border:1px solid #ff9b9b50;border-radius:6px;background:var(--nf-chrome-solid,#1c1c1c);font:12px/1.4 system-ui;color:#ff9b9b;white-space:normal}`};customElements.get("nf-trend-button")||customElements.define("nf-trend-button",yt);function D(r,t,n=""){let i=bt(r,t);return i.length?d`<nf-trend-button .hass=${r} .ids=${i} .label=${n}></nf-trend-button>`:a}var fe={heating_manifold:"Heiz-/K\xFChlkreisverteiler",buffer_tank:"Pufferspeicher",freshwater_station:"Frischwasserstation"},It=r=>r.name||fe[r.type],Kt=r=>r.name||{heating:"Heizkreis",cooling:"K\xFChlkreis",changeover:"Heizen / K\xFChlen",pump:"Vorschubpumpe"}[r.kind],Wt=(r,t)=>t.kind==="pump"?"Pumpenkreis":t.kind==="cooling"?"K\xFChlen":t.kind==="heating"?"Heizen":f(t.mode_entity)&&b(r.states[t.mode_entity])===null?"Betriebsart \u2013":Number(f(t.mode_entity)?b(r.states[t.mode_entity]):0)===(t.cooling_value??1)?"K\xFChlen":"Heizen",nt=(r,t,n)=>[m(r,"Vorlauf",t),m(r,"R\xFCcklauf",n)].filter(i=>i!==null),vt=(r,t,n)=>{let i=E(r,t),e=E(r,n);return i===null||e===null?a:d`<div class="reading delta"><span>ΔT · VL − RL</span><b>${(i-e).toLocaleString(r.language,{maximumFractionDigits:1})} K</b></div>`};function qt(r,t){let n=z(t),i=t.type==="freshwater_station"?[]:nt(r,n.flow,n.return);if(t.type==="buffer_tank"&&i.unshift(...[...n.sensors??[]].sort((e,s)=>s.level-e.level).flatMap(e=>{let s=m(r,e.name||"F\xFChler",e.entity);return s?[s]:[]})),t.type==="freshwater_station"){let e=m(r,"Zirkulation",n.circulation_temperature);e&&i.push(e)}for(let e of t.values??[]){let s=m(r,e.label||String(e.entity&&r.states[e.entity]?.attributes.friendly_name||"Wert"),e.entity);s&&i.push({...s,icon:e.icon})}return i}function Zt(r,t){return[...nt(r,t.flow,t.return),...[["Kaltwasser",t.cold_water],["Trinkwarmwasser",t.hot_water],["Pumpenleistung",t.power]].flatMap(([n,i])=>{let e=m(r,n,i);return e?[e]:[]})]}var xt=(r,t)=>`K${t+1} \xB7 ${r.name||`Station ${t+1}`}`,H=(r,t)=>d`<div class="reading" data-source=${t.id}><span>${t.icon?.startsWith("mdi:")?d`<ha-icon icon=${t.icon}></ha-icon>`:t.icon||a} ${t.label}</span><b>${t.text}${D(r,[t.id],t.label)}</b></div>`,P=(r,t,n="Status")=>{let i=m(r,n,t);return i?d`<div class="reading status-reading" data-source=${i.id}><span>${n}</span><b><span class="status-text" title=${i.text}>${i.text}</span>${D(r,[i.id],n)}</b></div>`:a};function V(r,t,n){let i=A(r,n);return i.id?d`<div class="reading" data-source=${i.id}><span>${t}<small>${i.feedback?"Ist":"Soll"}</small></span><b><i class="lamp" style=${`background:${i.running===null?"#888":i.running?"#6fe1a2":"#465361"}`}></i>${L(r.states[i.id])}${D(r,[i.id],t)}</b></div>`:a}var Jt=y`
|
||||
:host{display:block;color:var(--nf-text);font:12px/1.4 system-ui,sans-serif;min-width:170px;max-width:300px}
|
||||
button{font:inherit;color:inherit;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:7px;padding:5px 8px;cursor:pointer}button:disabled,input:disabled{opacity:.45;cursor:default}button:focus-visible,input:focus-visible{outline:2px solid var(--nf-accent);outline-offset:2px}
|
||||
.title{display:block;width:100%;padding:0 0 5px;border:0;background:none;font-weight:600;text-align:left;white-space:normal}.content{max-height:250px;overflow:auto;overscroll-behavior:contain}.circuit{border-top:1px solid var(--nf-line);padding:5px 0}.circuit-name{font-size:11px;font-weight:600;margin-bottom:3px}.reading{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;min-height:22px}.reading>span{color:var(--nf-muted);white-space:normal}.reading b{display:flex;align-items:center;justify-content:flex-end;white-space:nowrap;font-variant-numeric:tabular-nums;font-weight:500}.reading small{font-size:9px;margin-left:5px;opacity:.75}.delta{font-size:10px}.lamp{display:inline-block;flex:none;width:6px;height:6px;border-radius:50%;margin-right:5px}.empty{color:var(--nf-muted);font-size:11px;white-space:normal;margin:5px 0}nf-trend-button{margin-left:3px}
|
||||
.status-reading{grid-template-columns:auto minmax(0,1fr)}.status-reading b{min-width:0}.status-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.circuit-name small,h3 small{font-size:10px;color:var(--nf-muted);font-weight:normal;margin-left:5px}
|
||||
ha-icon{--mdc-icon-size:13px;width:13px;height:13px;vertical-align:middle}
|
||||
dialog{box-sizing:border-box;width:min(620px,calc(100vw - 24px));max-width:none;max-height:calc(100dvh - 24px);padding:0;color:var(--nf-text);background:var(--nf-chrome-solid,#1c1c1c);border:1px solid var(--nf-line);border-radius:14px;box-shadow:0 20px 70px #0008;font:13px/1.4 system-ui,sans-serif}dialog::backdrop{background:#050b16a6;backdrop-filter:blur(3px)}header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 18px;border-bottom:1px solid var(--nf-line)}h2{font-size:17px;margin:0}.body{padding:12px 18px;max-height:calc(100dvh - 120px);overflow:auto;overscroll-behavior:contain}h3{font-size:13px;margin:12px 0 7px}fieldset{min-width:0;margin:8px 0;padding:10px;border:1px solid var(--nf-line);border-radius:9px}legend{font-size:12px;color:var(--nf-muted)}.command{display:flex;align-items:center;gap:12px;margin-top:8px}.command input[type=range]{flex:1;min-width:0;accent-color:var(--nf-accent)}.command input[type=number]{width:90px;box-sizing:border-box;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:6px;color:inherit;padding:5px}.command output{font-variant-numeric:tabular-nums;min-width:45px;text-align:right}.error{color:#ff9b9b}.readonly{color:var(--nf-muted);font-size:11px;margin:4px 0}.body .reading{padding:4px 0}.body .circuit{padding-bottom:12px}
|
||||
`,xt=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean}};render(){if(!this.hass||!this.item)return a;let t=F(this.item),n=Wt(this.hass,this.item),i=this.item.type==="freshwater_station"?O(this.item):[];return d`<button class="title" @click=${()=>jt(this.hass,this.item,this.readOnly)} aria-haspopup="dialog">${Bt(this.item)} ⚙</button><div class="content">
|
||||
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit"><div class="circuit-name">${It(e)} <small>${Kt(this.hass,e)}</small></div>${q(e)?L(this.hass,"Pumpe",e.pump):a}${Z(e)?L(this.hass,"Ventil",e.valve):a}${et(this.hass,e.flow,e.return).map(o=>H(this.hass,o))}${f(this.hass,"Leistung",e.power)?H(this.hass,f(this.hass,"Leistung",e.power)):a}</section>`):a}
|
||||
${i.length>1?d`<small class="cascade-count">Kaskade · ${i.length} Stationen</small>${i.map((e,o)=>{let s=S(this.hass,e.pump),c=f(this.hass,"Trinkwarmwasser",e.hot_water)||f(this.hass,"Vorlauf",e.flow);return d`<div class="station-summary" data-station=${e.id}><button class="station-name" @click=${()=>jt(this.hass,this.item,this.readOnly,e.id)}><i class="lamp" title=${`Pumpe: ${s.id?U(this.hass.states[s.id]):"\u2013"}`} style=${`background:${s.running===null?"#888":s.running?"#6fe1a2":"#a82638"}`}></i>${vt(e,o)}</button><b>${c?.text||"\u2013"}</b>${c?X(this.hass,[c.id],`${vt(e,o)} \xB7 ${c.label}`):a}</div>`})}`:i.map(e=>d`<section class="circuit">${qt(this.hass,e).map(o=>H(this.hass,o))}${L(this.hass,"Ladepumpe",e.pump)}${T(e)?L(this.hass,"Kaskadenventil",e.valve):a}</section>`)}
|
||||
${n.map(e=>H(this.hass,e))}${this.item.type==="freshwater_station"?L(this.hass,"Zirkulationspumpe",t.circulation):a}
|
||||
${this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"&&!n.length?d`<p class="empty">Noch keine Fühler verknüpft</p>`:a}
|
||||
</div>`}static styles=[mt,Zt,y`.cascade-count{color:var(--nf-muted)}.station-summary{display:grid;grid-template-columns:minmax(0,1fr) auto 18px;align-items:center;gap:6px;width:100%;padding:5px 0;font-size:11px}.station-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0;background:none;border:0;text-align:left}.station-summary b{white-space:nowrap;font-variant-numeric:tabular-nums}`]},$t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean},focusStation:{attribute:!1},pending:{state:!0},error:{state:!0}};constructor(){super(),this.pending=new Set,this.error="",this.readOnly=!1}async show(){await this.updateComplete,this.shadowRoot.querySelector("dialog").showModal(),this.focusStation&&this.shadowRoot.querySelector(`[data-station="${CSS.escape(this.focusStation)}"]`)?.scrollIntoView({block:"start"})}async send(t,n){let i=this.hass.states[t];if(!(this.readOnly||!i?.attributes.symcon_has_action||b(i)===null||this.pending.has(t))){this.pending=new Set([...this.pending,t]),this.error="";try{await this.hass.callService("symcon","set_value",{entity_id:t,value:n})}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.pending=new Set([...this.pending].filter(e=>e!==t))}}}control(t,n){if(!g(n?.command)&&!g(n?.feedback))return a;let i=g(n?.command)?n.command:null,e=i?this.hass.states[i]:void 0,o=e?.attributes,s=b(e),c=!!i&&!!o?.symcon_has_action&&s!==null&&!this.readOnly&&!this.pending.has(i),l=Number(o?.symcon_min??0),h=Number(o?.symcon_max??100),p=Number(o?.symcon_step||(o?.symcon_variable_type===1?1:.1)),u=z(e),m=$=>{let _=$.target;i&&_.value.trim()&&_.checkValidity()&&Number.isFinite(_.valueAsNumber)&&this.send(i,_.valueAsNumber)};return d`<fieldset data-control=${t}><legend>${t}</legend>${L(this.hass,t,n)}
|
||||
${i?d`<div class="reading"><span>Befehl / Sollwert</span><b>${U(e)}${X(this.hass,[i],`${t} \xB7 Sollwert`)}</b></div>
|
||||
${o?.symcon_variable_type===0?d`<div class="command"><button data-command=${i} ?disabled=${!c} @click=${()=>{this.send(i,!J(e))}}>${J(e)?"Ausschalten / Schlie\xDFen":"Einschalten / \xD6ffnen"}</button></div>`:[1,2].includes(Number(o?.symcon_variable_type))?d`<div class="command"><input type="range" aria-label=${`${t} Sollwert`} data-command=${i} min=${l} max=${h} step=${p} .value=${String(u??l)} ?disabled=${!c} @change=${m}/><input type="number" aria-label=${`${t} nativer Sollwert`} min=${l} max=${h} step=${p} .value=${u===null?"":String(u)} ?disabled=${!c} @change=${m}/></div>`:a}
|
||||
${this.readOnly?d`<p class="readonly">Historische Ansicht · nur Anzeige</p>`:o?.symcon_has_action?a:d`<p class="readonly">Nur Anzeige · keine Symcon-Schaltaktion hinterlegt</p>`}`:a}
|
||||
</fieldset>`}render(){if(!this.hass||!this.item)return a;let t=F(this.item),n=Wt(this.hass,this.item),i=this.item.type==="freshwater_station"?O(this.item):[];return d`<dialog @close=${()=>{this.remove(),x===this&&(x=null)}} @keydown=${e=>e.stopPropagation()}><header><h2>${Bt(this.item)}</h2><button aria-label="Schließen" @click=${()=>this.shadowRoot.querySelector("dialog").close()}>×</button></header><div class="body">
|
||||
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit" data-circuit=${e.id}><h3>${It(e)} <small>${Kt(this.hass,e)}</small></h3>${q(e)?this.control("Pumpe",e.pump):a}${Z(e)?this.control("Ventil",e.valve):a}${et(this.hass,e.flow,e.return).map(o=>H(this.hass,o))}${yt(this.hass,e.flow,e.return)}${f(this.hass,"Pumpenleistung",e.power)?H(this.hass,f(this.hass,"Pumpenleistung",e.power)):a}</section>`):a}
|
||||
${i.map((e,o)=>d`<details class="freshwater-unit" data-station=${e.id} ?open=${o===0||this.focusStation===e.id}><summary>${vt(e,o)}</summary>${qt(this.hass,e).map(s=>H(this.hass,s))}${yt(this.hass,e.flow,e.return)}${this.control("Ladepumpe",e.pump)}${T(e)?this.control("Kaskadenventil",e.valve):a}</details>`)}
|
||||
${n.map(e=>H(this.hass,e))}${this.item.type==="buffer_tank"?yt(this.hass,t.flow,t.return):a}
|
||||
`,$t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean}};render(){if(!this.hass||!this.item)return a;let t=z(this.item),n=qt(this.hass,this.item),i=this.item.type==="freshwater_station"?F(this.item):[];return d`<button class="title" @click=${()=>Bt(this.hass,this.item,this.readOnly)} aria-haspopup="dialog">${It(this.item)} ⚙</button><div class="content">${P(this.hass,t.status,"Anlagenstatus")}
|
||||
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit"><div class="circuit-name">${Kt(e)} <small>${Wt(this.hass,e)}</small></div>${P(this.hass,e.status)}${J(e)?V(this.hass,"Pumpe",e.pump):a}${X(e)?V(this.hass,"Ventil",e.valve):a}${nt(this.hass,e.flow,e.return).map(s=>H(this.hass,s))}${m(this.hass,"Leistung",e.power)?H(this.hass,m(this.hass,"Leistung",e.power)):a}</section>`):a}
|
||||
${i.length>1?d`<small class="cascade-count">Kaskade · ${i.length} Stationen</small>${i.map((e,s)=>{let o=A(this.hass,e.pump),c=m(this.hass,"Trinkwarmwasser",e.hot_water)||m(this.hass,"Vorlauf",e.flow);return d`<div class="station-summary" data-station=${e.id}><button class="station-name" @click=${()=>Bt(this.hass,this.item,this.readOnly,e.id)}><i class="lamp" title=${`Pumpe: ${o.id?L(this.hass.states[o.id]):"\u2013"}`} style=${`background:${o.running===null?"#888":o.running?"#6fe1a2":"#a82638"}`}></i>${xt(e,s)}</button><b>${c?.text||"\u2013"}</b>${c?D(this.hass,[c.id],`${xt(e,s)} \xB7 ${c.label}`):a}${P(this.hass,e.status)}</div>`})}`:i.map(e=>d`<section class="circuit">${P(this.hass,e.status)}${Zt(this.hass,e).map(s=>H(this.hass,s))}${V(this.hass,"Ladepumpe",e.pump)}${O(e)?V(this.hass,"Kaskadenventil",e.valve):a}</section>`)}
|
||||
${n.map(e=>H(this.hass,e))}${this.item.type==="freshwater_station"?V(this.hass,"Zirkulationspumpe",t.circulation):a}
|
||||
${this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"&&!n.length&&!f(t.status)?d`<p class="empty">Noch keine Fühler verknüpft</p>`:a}
|
||||
</div>`}static styles=[gt,Jt,y`.cascade-count{color:var(--nf-muted)}.station-summary{display:grid;grid-template-columns:minmax(0,1fr) auto 18px;align-items:center;gap:6px;width:100%;padding:5px 0;font-size:11px}.station-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0;background:none;border:0;text-align:left}.station-summary>.status-reading{grid-column:1/-1}.station-summary b{white-space:nowrap;font-variant-numeric:tabular-nums}`]},_t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean},focusStation:{attribute:!1},pending:{state:!0},error:{state:!0}};constructor(){super(),this.pending=new Set,this.error="",this.readOnly=!1}async show(){await this.updateComplete,this.shadowRoot.querySelector("dialog").showModal(),this.focusStation&&this.shadowRoot.querySelector(`[data-station="${CSS.escape(this.focusStation)}"]`)?.scrollIntoView({block:"start"})}async send(t,n){let i=this.hass.states[t];if(!(this.readOnly||!i?.attributes.symcon_has_action||b(i)===null||this.pending.has(t))){this.pending=new Set([...this.pending,t]),this.error="";try{await this.hass.callService("symcon","set_value",{entity_id:t,value:n})}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.pending=new Set([...this.pending].filter(e=>e!==t))}}}control(t,n){if(!f(n?.command)&&!f(n?.feedback))return a;let i=f(n?.command)?n.command:null,e=i?this.hass.states[i]:void 0,s=e?.attributes,o=b(e),c=!!i&&!!s?.symcon_has_action&&o!==null&&!this.readOnly&&!this.pending.has(i),l=Number(s?.symcon_min??0),h=Number(s?.symcon_max??100),p=Number(s?.symcon_step||(s?.symcon_variable_type===1?1:.1)),u=U(e),g=$=>{let _=$.target;i&&_.value.trim()&&_.checkValidity()&&Number.isFinite(_.valueAsNumber)&&this.send(i,_.valueAsNumber)};return d`<fieldset data-control=${t}><legend>${t}</legend>${V(this.hass,t,n)}
|
||||
${i?d`<div class="reading"><span>Befehl / Sollwert</span><b>${L(e)}${D(this.hass,[i],`${t} \xB7 Sollwert`)}</b></div>
|
||||
${s?.symcon_variable_type===0?d`<div class="command"><button data-command=${i} ?disabled=${!c} @click=${()=>{this.send(i,!Y(e))}}>${Y(e)?"Ausschalten / Schlie\xDFen":"Einschalten / \xD6ffnen"}</button></div>`:[1,2].includes(Number(s?.symcon_variable_type))?d`<div class="command"><input type="range" aria-label=${`${t} Sollwert`} data-command=${i} min=${l} max=${h} step=${p} .value=${String(u??l)} ?disabled=${!c} @change=${g}/><input type="number" aria-label=${`${t} nativer Sollwert`} min=${l} max=${h} step=${p} .value=${u===null?"":String(u)} ?disabled=${!c} @change=${g}/></div>`:a}
|
||||
${this.readOnly?d`<p class="readonly">Historische Ansicht · nur Anzeige</p>`:s?.symcon_has_action?a:d`<p class="readonly">Nur Anzeige · keine Symcon-Schaltaktion hinterlegt</p>`}`:a}
|
||||
</fieldset>`}render(){if(!this.hass||!this.item)return a;let t=z(this.item),n=qt(this.hass,this.item),i=this.item.type==="freshwater_station"?F(this.item):[];return d`<dialog @close=${()=>{this.remove(),x===this&&(x=null)}} @keydown=${e=>e.stopPropagation()}><header><h2>${It(this.item)}</h2><button aria-label="Schließen" @click=${()=>this.shadowRoot.querySelector("dialog").close()}>×</button></header><div class="body">${P(this.hass,t.status,"Anlagenstatus")}
|
||||
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit" data-circuit=${e.id}><h3>${Kt(e)} <small>${Wt(this.hass,e)}</small></h3>${P(this.hass,e.status)}${J(e)?this.control("Pumpe",e.pump):a}${X(e)?this.control("Ventil",e.valve):a}${nt(this.hass,e.flow,e.return).map(s=>H(this.hass,s))}${vt(this.hass,e.flow,e.return)}${m(this.hass,"Pumpenleistung",e.power)?H(this.hass,m(this.hass,"Pumpenleistung",e.power)):a}</section>`):a}
|
||||
${i.map((e,s)=>d`<details class="freshwater-unit" data-station=${e.id} ?open=${s===0||this.focusStation===e.id}><summary>${xt(e,s)}</summary>${P(this.hass,e.status)}${Zt(this.hass,e).map(o=>H(this.hass,o))}${vt(this.hass,e.flow,e.return)}${this.control("Ladepumpe",e.pump)}${O(e)?this.control("Kaskadenventil",e.valve):a}</details>`)}
|
||||
${n.map(e=>H(this.hass,e))}${this.item.type==="buffer_tank"?vt(this.hass,t.flow,t.return):a}
|
||||
${this.item.type==="freshwater_station"?this.control("Zirkulationspumpe",t.circulation):a}
|
||||
${!n.length&&this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"?d`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>`:a}
|
||||
${!n.length&&!f(t.status)&&this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"?d`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>`:a}
|
||||
${this.error?d`<p class="error" role="alert">${this.error}</p>`:a}
|
||||
</div></dialog>`}static styles=[mt,Zt,y`:host{max-width:none;min-width:0}.freshwater-unit{border-bottom:1px solid var(--nf-line);padding:8px 0}.freshwater-unit>summary{cursor:pointer;font-weight:600;padding:4px 0}`]},x=null;function en(){x?.remove(),x=null}async function jt(r,t,n=!1,i){x?.remove();let e=document.createElement("nf-hydronic-dialog");x=e,Object.assign(e,{hass:r,item:t,readOnly:n,focusStation:i}),document.body.append(e),await e.show()}function nn(r,t,n=!1){if(!x)return;let i=t.floors.flatMap(e=>e.furniture).find(e=>e.id===x.item.id);if(!i||!Dt(i.type)){x.remove(),x=null;return}Object.assign(x,{hass:r,item:i,readOnly:n})}customElements.get("nf-hydronic-card")||customElements.define("nf-hydronic-card",xt);customElements.get("nf-hydronic-dialog")||customElements.define("nf-hydronic-dialog",$t);export{en as closeHydronic,he as hydronicVisual,jt as openHydronic,nn as refreshHydronic};
|
||||
</div></dialog>`}static styles=[gt,Jt,y`:host{max-width:none;min-width:0}.freshwater-unit{border-bottom:1px solid var(--nf-line);padding:8px 0}.freshwater-unit>summary{cursor:pointer;font-weight:600;padding:4px 0}`]},x=null;function nn(){x?.remove(),x=null}async function Bt(r,t,n=!1,i){x?.remove();let e=document.createElement("nf-hydronic-dialog");x=e,Object.assign(e,{hass:r,item:t,readOnly:n,focusStation:i}),document.body.append(e),await e.show()}function rn(r,t,n=!1){if(!x)return;let i=t.floors.flatMap(e=>e.furniture).find(e=>e.id===x.item.id);if(!i||!Vt(i.type)){x.remove(),x=null;return}Object.assign(x,{hass:r,item:i,readOnly:n})}customElements.get("nf-hydronic-card")||customElements.define("nf-hydronic-card",$t);customElements.get("nf-hydronic-dialog")||customElements.define("nf-hydronic-dialog",_t);export{nn as closeHydronic,pe as hydronicVisual,Bt as openHydronic,rn as refreshHydronic};
|
||||
/*! Bundled license information:
|
||||
|
||||
@lit/reactive-element/css-tag.js:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -10,7 +10,7 @@ import re
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
MAX_FLOORS = 20
|
||||
MAX_FLOORS = 128
|
||||
MAX_ROOMS = 200
|
||||
MAX_POINTS = 200
|
||||
MAX_ITEMS = 1000
|
||||
@@ -369,13 +369,14 @@ _CHARGING_STATION = {
|
||||
_FRESHWATER_STATION = {
|
||||
vol.Required("id"): _ID,
|
||||
vol.Required("name"): vol.All(str, vol.Length(max=100)),
|
||||
**{vol.Optional(key): _ENTITY_REF for key in ("flow", "return", "hot_water", "cold_water", "power")},
|
||||
**{vol.Optional(key): _ENTITY_REF for key in ("flow", "return", "hot_water", "cold_water", "power", "status")},
|
||||
vol.Optional("pump"): _HYDRONIC_CONTROL,
|
||||
vol.Optional("valve"): _HYDRONIC_CONTROL,
|
||||
vol.Optional("has_valve"): bool,
|
||||
}
|
||||
_HYDRONIC = {
|
||||
vol.Optional("card"): bool,
|
||||
vol.Optional("status"): _ENTITY_REF,
|
||||
vol.Optional("circuits"): vol.All(
|
||||
[
|
||||
{
|
||||
@@ -387,7 +388,7 @@ _HYDRONIC = {
|
||||
vol.Optional("valve_type"): vol.In(["mixing", "two_way"]),
|
||||
vol.Optional("pump"): _HYDRONIC_CONTROL,
|
||||
vol.Optional("valve"): _HYDRONIC_CONTROL,
|
||||
**{vol.Optional(key): _ENTITY_REF for key in ("flow", "return", "power", "mode_entity")},
|
||||
**{vol.Optional(key): _ENTITY_REF for key in ("flow", "return", "power", "mode_entity", "status")},
|
||||
vol.Optional("cooling_value"): vol.All(vol.Coerce(int), vol.Range(min=-2147483648, max=2147483647)),
|
||||
}
|
||||
],
|
||||
@@ -622,6 +623,9 @@ OUTDOOR_TYPES = [
|
||||
"terrace",
|
||||
"path",
|
||||
"driveway",
|
||||
"pavers",
|
||||
"stepping_stones",
|
||||
"natural_stone",
|
||||
"street",
|
||||
"sidewalk",
|
||||
"gravel",
|
||||
@@ -666,6 +670,13 @@ OUTDOOR_SCHEMA = vol.Schema(
|
||||
vol.Optional("slope_dir", default="x"): vol.In(["x", "-x", "z", "-z"]),
|
||||
# how opaque the area is drawn (None = fully)
|
||||
vol.Optional("opacity", default=None): vol.Any(None, vol.All(vol.Coerce(float), vol.Range(min=0.1, max=1))),
|
||||
# per-area pattern size and rotation; None keeps legacy appearance
|
||||
vol.Optional("texture_scale", default=None): vol.Any(
|
||||
None, vol.All(vol.Coerce(float), vol.Range(min=0.05, max=20))
|
||||
),
|
||||
vol.Optional("texture_rotation", default=None): vol.Any(
|
||||
None, vol.All(vol.Coerce(float), vol.Range(min=-360, max=360))
|
||||
),
|
||||
# fences and pergolas: the closing edge is left out; pergola: X-bracing on the sides
|
||||
vol.Optional("open", default=False): bool,
|
||||
vol.Optional("bracing", default=False): bool,
|
||||
@@ -844,6 +855,10 @@ FLOOR_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required("id"): _ID,
|
||||
vol.Required("name"): _NAME,
|
||||
vol.Optional("building_id"): vol.Any(None, _ID),
|
||||
vol.Optional("outdoor_location_id"): vol.Any(None, _ID),
|
||||
vol.Optional("outdoor_branch_id"): vol.Any(None, _ID),
|
||||
vol.Optional("outdoor_building_id"): vol.Any(None, _ID),
|
||||
vol.Required("elevation"): vol.All(vol.Coerce(float), vol.Range(min=-100, max=500)),
|
||||
vol.Required("height"): vol.All(vol.Coerce(float), vol.Range(min=1, max=20)),
|
||||
vol.Required("cut_height"): vol.All(vol.Coerce(float), vol.Range(min=0.2, max=20)),
|
||||
@@ -1188,9 +1203,26 @@ PRESENCE_SCHEMA = vol.Schema(
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
|
||||
TOPOLOGY_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required("locations"): vol.All(
|
||||
[{vol.Required("id"): _ID, vol.Required("name"): _NAME}], vol.Length(max=128)
|
||||
),
|
||||
vol.Required("branches"): vol.All(
|
||||
[{vol.Required("id"): _ID, vol.Required("name"): _NAME, vol.Required("location_id"): _ID}],
|
||||
vol.Length(max=256),
|
||||
),
|
||||
vol.Required("buildings"): vol.All(
|
||||
[{vol.Required("id"): _ID, vol.Required("name"): _NAME, vol.Required("branch_id"): _ID}],
|
||||
vol.Length(max=512),
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
BUILDING_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required("version"): 1,
|
||||
vol.Optional("topology"): TOPOLOGY_SCHEMA,
|
||||
vol.Required("floors"): vol.All([FLOOR_SCHEMA], vol.Length(max=MAX_FLOORS)),
|
||||
vol.Required("settings"): SETTINGS_SCHEMA,
|
||||
vol.Optional("energy", default=lambda: dict(ENERGY_DEFAULTS)): ENERGY_SCHEMA,
|
||||
|
||||
+2
-1
@@ -116,7 +116,8 @@ function copySymconAssets() {
|
||||
// Metered-device detail discovery adds about 2 KB; keep a small, explicit margin.
|
||||
// Charging telemetry, native time/duration formatting and labels add another 5 KB.
|
||||
// Zoom detail levels and bounded device-card layouts add about 1.5 KB.
|
||||
const BUDGET = { "nextfloor.js": 682 * 1024, "nextfloor-3d.js": 1000 * 1024, "nextfloor-editor.js": 720 * 1024, "nextfloor-card-editor.js": 240 * 1024, "nextfloor-trend.js": 100 * 1024, "nextfloor-hydronics.js": 100 * 1024 };
|
||||
// Native per-device read-only presentation and account guards add about 2 KB.
|
||||
const BUDGET = { "nextfloor.js": 705 * 1024, "nextfloor-3d.js": 1000 * 1024, "nextfloor-editor.js": 720 * 1024, "nextfloor-card-editor.js": 240 * 1024, "nextfloor-trend.js": 100 * 1024, "nextfloor-hydronics.js": 100 * 1024 };
|
||||
|
||||
copyAssets();
|
||||
copySymconAssets();
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { canControl } from "./access.ts";
|
||||
import { entity, hassOf } from "./entities/fixtures.ts";
|
||||
import { symconControl } from "./symcon-controls.ts";
|
||||
|
||||
test("native read-only flags survive role aliases; missing or forbidden targets have no controls", () => {
|
||||
const st = entity("sensor.10", "30", { symcon_id: 10, symcon_variable_type: 2, symcon_numeric_value: 30, symcon_can_control: false });
|
||||
const alias = symconControl(st, "light")!;
|
||||
const h = hassOf([st, alias, entity("switch.20", "on", { symcon_can_control: true })], {}, { symconObjects: [] });
|
||||
assert.equal(canControl(h, "sensor.10"), false);
|
||||
assert.equal(canControl(h, "light.10"), false);
|
||||
assert.equal(canControl(h, "switch.20"), true);
|
||||
assert.equal(canControl(h, "switch.999"), false);
|
||||
assert.equal(canControl(hassOf([st]), "sensor.10"), true, "HA behavior stays independent of Symcon roles");
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
|
||||
/** Presentation guard only. The Symcon API independently checks every requested native target. */
|
||||
export function canControl(hass: HomeAssistant | undefined, id: string): boolean {
|
||||
if (!hass || hass.symconObjects === undefined) return true;
|
||||
return !!hass.states[id] && hass.states[id].attributes.symcon_can_control !== false && hass.states[id].attributes.symcon_has_action !== false;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { onPluginsChanged } from "./plugins/registry.ts";
|
||||
import { normalizeBuilding, type Building } from "./model.ts";
|
||||
import { setPacks, type FurniturePack } from "./packs.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
import { isSymcon } from "./entities/symcon-values.ts";
|
||||
|
||||
export type SaveState = "idle" | "saving" | "saved" | "error";
|
||||
|
||||
@@ -111,6 +112,7 @@ export class BuildingController implements ReactiveController {
|
||||
|
||||
/** A local edit: visible at once, sent after a short pause. */
|
||||
edit(building: Building): void {
|
||||
if (this.hass && isSymcon(this.hass) && !this.hass.user?.is_admin) return;
|
||||
this.building = building;
|
||||
void loadPlugins(building.settings.plugins);
|
||||
this.waiting = building;
|
||||
@@ -179,7 +181,7 @@ export class BuildingController implements ReactiveController {
|
||||
} catch (error) {
|
||||
this.saveState = "error";
|
||||
this.saveError = messageOf(error);
|
||||
storeDraft({ building, savedAt: Date.now() }); // after a restart it can be restored and saved
|
||||
if (!isSymcon(hass)) storeDraft({ building, savedAt: Date.now() }); // Symcon sessions do not leave private plans in shared browser storage.
|
||||
}
|
||||
this.host.requestUpdate();
|
||||
}
|
||||
@@ -221,7 +223,7 @@ export class BuildingController implements ReactiveController {
|
||||
this.backendVersion = fetched.version ?? null;
|
||||
this.revision = fetched.revision;
|
||||
this.error = null;
|
||||
if (this.draft === null && !this.waiting) this.draft = loadDraft();
|
||||
if (!isSymcon(this.hass) && this.draft === null && !this.waiting) this.draft = loadDraft();
|
||||
} catch (error) {
|
||||
this.error = messageOf(error);
|
||||
}
|
||||
|
||||
+25
-4
@@ -21,6 +21,7 @@ import type { HomeAssistant } from "./types.ts";
|
||||
import { withCoverControls } from "./entities/cover-controls.ts";
|
||||
import { withSymconWeather } from "./symcon-weather.ts";
|
||||
import { isSymcon } from "./entities/symcon-values.ts";
|
||||
import { ALL_TOPOLOGY, floorSelection, isOutdoorFloor, outsideFloor, topologyOutsideFloors, topologyParent, type TopologySelection } from "./topology.ts";
|
||||
import type { WallMode } from "./viewer/viewer3d.ts";
|
||||
import { lookNow } from "./themes.ts";
|
||||
|
||||
@@ -44,6 +45,7 @@ export class NextFloorCard extends LitElement {
|
||||
hass: { attribute: false },
|
||||
_config: { state: true },
|
||||
_roomId: { state: true },
|
||||
_topologyGroup: { state: true },
|
||||
_floorId: { state: true },
|
||||
_walls: { state: true },
|
||||
_heat: { state: true },
|
||||
@@ -64,6 +66,7 @@ export class NextFloorCard extends LitElement {
|
||||
/** The configured start room has been opened once the building arrived. */
|
||||
private roomApplied = false;
|
||||
/** The floor chosen in the card: null is the house, undefined means none was chosen so the configured floor applies. */
|
||||
private declare _topologyGroup: TopologySelection;
|
||||
private declare _floorId: string | null | undefined;
|
||||
/** Choices made with the card's own switches; null means as configured. */
|
||||
private declare _walls: WallMode | null;
|
||||
@@ -93,6 +96,7 @@ export class NextFloorCard extends LitElement {
|
||||
super();
|
||||
this._roomId = null;
|
||||
this._floorId = undefined;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._walls = null;
|
||||
this._heat = null;
|
||||
this._explode = null;
|
||||
@@ -111,6 +115,7 @@ export class NextFloorCard extends LitElement {
|
||||
private returnHome(): void {
|
||||
this._roomId = this._config?.room ?? null;
|
||||
this._floorId = undefined;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this.view3d()?.resetView();
|
||||
if (this._config?.idle_orbit) this._orbit = true;
|
||||
}
|
||||
@@ -156,6 +161,7 @@ export class NextFloorCard extends LitElement {
|
||||
this._own = config;
|
||||
this._config = withTemplate(config, this.data.building?.settings.card_templates as CardTemplates | undefined);
|
||||
this._floorId = undefined;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._walls = null;
|
||||
this._heat = null;
|
||||
this._explode = null;
|
||||
@@ -199,8 +205,20 @@ export class NextFloorCard extends LitElement {
|
||||
}
|
||||
|
||||
/** One level up: room, then floor, then the house. */
|
||||
private topologySelection(): TopologySelection {
|
||||
const b=this.plan(),id=this.stage().floorId;
|
||||
return b&&id?floorSelection(b,id,this._roomId===OUTSIDE?null:this._roomId):this._topologyGroup;
|
||||
}
|
||||
|
||||
private openTopology(s:TopologySelection):void {
|
||||
const b=this.plan();if(!b)return;
|
||||
this._floorId=s.kind==="room"?s.floorId??null:s.kind==="floor"?s.id??null:outsideFloor(b,s)?.id??null;
|
||||
this._roomId=s.kind==="room"?s.id??null:null;this._topologyGroup=s;
|
||||
}
|
||||
|
||||
private back(): void {
|
||||
if (this._roomId) this._roomId = null;
|
||||
else if(this.plan()?.topology)this.openTopology(topologyParent(this.plan()!,this.topologySelection()));
|
||||
else if (this.canSwitch) this._floorId = null;
|
||||
}
|
||||
|
||||
@@ -224,7 +242,7 @@ export class NextFloorCard extends LitElement {
|
||||
const c = this._config;
|
||||
// the configured floor is where the card starts; with floor pictures the user can switch
|
||||
const chosen = this._floorId === undefined ? (c?.floor ?? null) : this._floorId;
|
||||
const floorId = b && b.floors.length === 1 ? b.floors[0].id : b?.floors.some((f) => f.id === chosen) ? chosen : null;
|
||||
const floorId = b && !b.topology && b.floors.length === 1 ? b.floors[0].id : b?.floors.some((f) => f.id === chosen) ? chosen : null;
|
||||
// the floor pictures have a house button of their own; a room with its panel has a close button
|
||||
const panelOpen = !!this._roomId && c?.room_panel !== false;
|
||||
const canGoBack = (!!this._roomId && c?.room_panel === false) || (!this.thumbs && this.canSwitch && !this._roomId && !!floorId && (b?.floors.length ?? 0) > 1);
|
||||
@@ -270,6 +288,7 @@ export class NextFloorCard extends LitElement {
|
||||
private renderRoomButtons(s: Stage): TemplateResult | typeof nothing {
|
||||
const b = this.plan();
|
||||
if (!this._config?.room_buttons || !b || this._clean) return nothing;
|
||||
if(b.topology&&(!s.floorId||isOutdoorFloor(b.floors.find((f)=>f.id===s.floorId))))return nothing;
|
||||
const groups = roomButtons(b, s.floorId);
|
||||
if (!groups.length) return nothing;
|
||||
const several = groups.length > 1;
|
||||
@@ -278,7 +297,7 @@ export class NextFloorCard extends LitElement {
|
||||
this._roomId = roomId === this._roomId ? null : roomId;
|
||||
};
|
||||
// Outside: the house view with the garden's and the roof's devices in the panel
|
||||
const outside = outsideEntities(this.hass, b.floors).length > 0;
|
||||
const outside = !b.topology&&outsideEntities(this.hass, b.floors).length > 0;
|
||||
const openOutside = () => {
|
||||
if (this.canSwitch) this._floorId = null;
|
||||
this._roomId = this._roomId === OUTSIDE ? null : OUTSIDE;
|
||||
@@ -322,6 +341,7 @@ export class NextFloorCard extends LitElement {
|
||||
return html`<nf-view3d
|
||||
.hass=${withSymconWeather(withCoverControls(this.hass, b.floors), b.settings)}
|
||||
.building=${b}
|
||||
.topologySelection=${this.topologySelection()}
|
||||
.packs=${this.data.packs}
|
||||
.floorId=${s.floorId}
|
||||
.roomId=${this._roomId === OUTSIDE ? null : this._roomId}
|
||||
@@ -388,9 +408,10 @@ export class NextFloorCard extends LitElement {
|
||||
this._roomId = null;
|
||||
} else if (e.detail.roomId) this._roomId = e.detail.roomId === this._roomId ? null : e.detail.roomId;
|
||||
}}
|
||||
@topology-tap=${(e: CustomEvent<TopologySelection>)=>{if(this.canSwitch)this.openTopology(e.detail);}}
|
||||
@floor-tap=${(e: CustomEvent<{ floorId: string | null }>) => {
|
||||
this._floorId = e.detail.floorId;
|
||||
this._roomId = null;
|
||||
this._roomId = null;this._topologyGroup=ALL_TOPOLOGY;
|
||||
}}
|
||||
@back=${() => this.back()}
|
||||
></nf-view3d>`;
|
||||
@@ -404,7 +425,7 @@ export class NextFloorCard extends LitElement {
|
||||
.hass=${withCoverControls(this.hass, b.floors)}
|
||||
.room=${b.floors.flatMap((f) => f.rooms).find((r) => r.id === this._roomId) ?? null}
|
||||
.floor=${b.floors.find((f) => f.rooms.some((r) => r.id === this._roomId)) ?? null}
|
||||
.outside=${this._roomId === OUTSIDE ? outsideEntities(this.hass, b.floors) : null}
|
||||
.outside=${this._roomId === OUTSIDE ? outsideEntities(this.hass, topologyOutsideFloors(b,this.topologySelection())) : null}
|
||||
.confirmEntities=${confirmEntities(this.hass, b.floors)}
|
||||
.phrases=${b.settings.announce_phrases ?? null}
|
||||
@close=${() => (this._roomId = null)}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { editorFloors, editorScopeChoices, editorScopeFromKey, editorScopeKey, moveSelectedFloor, reconcileEditorContext, scopeForFloor, selectEditorScope, type EditorScope } from "./editor/editor-context.ts";
|
||||
import "./editor/hierarchy-manager.ts";
|
||||
import { floorSelection, floorTopologyPath, isOutdoorFloor, normalizeTopology, topologyFloors, topologyItems } from "../topology.ts";
|
||||
// 2D editor: floors, rooms (rectangles and free shapes), snapping, undo, background template.
|
||||
|
||||
import { html, LitElement, nothing, svg, type PropertyValues, type TemplateResult } from "lit";
|
||||
@@ -75,6 +78,7 @@ import "./editor/wall-view.ts";
|
||||
import "./editor/ble-locate.ts";
|
||||
import { LibraryState, renderLibrary, renderPreview, type LibraryActions } from "./editor/forms/library.ts";
|
||||
import { arcFreeWall, arcRoomEdge, insertCorner } from "./editor/ops/rooms.ts";
|
||||
import { moveRoomToFloor, roomMovePosition } from "./editor/ops/room-move.ts";
|
||||
import type { ArcActions, ArcEdit } from "./editor/forms/arc.ts";
|
||||
import { dragStep, facingAngle, gridPositionAfter, hasLeftStart, headingAngle, outlineWithCornerAt, shifted, steppedDelta, straightEnd } from "./editor/ops/drags.ts";
|
||||
import { snapOutdoorMove, snapToPlan, type SnapOptions } from "./editor/ops/snapping.ts";
|
||||
@@ -83,7 +87,7 @@ import { devicesLayer, furnitureLayer, notesLayer } from "./editor/canvas/items.
|
||||
import { dimensionsLayer } from "./editor/canvas/plan.ts";
|
||||
import { renderNoteForm } from "./editor/forms/note.ts";
|
||||
import { openingsLayer } from "./editor/canvas/openings.ts";
|
||||
import { cutMarksLayer, floorBelowLayer, freeWallsLayer, gridLayer, meterLayer, outdoorHandlesLayer, outdoorLayer, roomHandlesLayer, roomsLayer, wallsLayer } from "./editor/canvas/plan.ts";
|
||||
import { cutMarksLayer, floorBelowLayer, freeWallsLayer, gridLayer, meterLayer, outdoorHandlesLayer, outdoorLayer, roomHandlesLayer, roomsLayer, scopeOverviewLayer, wallsLayer } from "./editor/canvas/plan.ts";
|
||||
import { renderEdgeHeights, type EdgeActions } from "./editor/forms/edges.ts";
|
||||
import { clearWallSlope, cutEdge, joinAtCut, moveCut, setPartHeight, setWallHeight, setWallSlope, setWallThickness } from "./editor/ops/edges.ts";
|
||||
import { renderDeviceForm, type DeviceActions } from "./editor/forms/device.ts";
|
||||
@@ -204,6 +208,9 @@ export class NfEditor extends LitElement {
|
||||
_tour: { state: true },
|
||||
_sideOpen: { state: true },
|
||||
_floorId: { state: true },
|
||||
_editorScope: { state: true },
|
||||
_floorMove: { state: true },
|
||||
_roomMove: { state: true },
|
||||
_energyNote: { state: true },
|
||||
_ctx: { state: true },
|
||||
_fixedHint: { state: true },
|
||||
@@ -260,6 +267,9 @@ export class NfEditor extends LitElement {
|
||||
private tourChecked = false;
|
||||
private declare _sideOpen: boolean;
|
||||
private declare _floorId: string | null;
|
||||
private declare _editorScope: EditorScope | null;
|
||||
private declare _floorMove: {floorId:string;targetId:string} | null;
|
||||
private declare _roomMove: {sourceId:string;roomId:string;buildingId:string;targetId:string;x:number;z:number;error:string} | null;
|
||||
/** What the import from the energy dashboard did (shown under its button). */
|
||||
private declare _energyNote: string | null;
|
||||
/** Open context menu (right-click, long press) at a plan point, for one item. */
|
||||
@@ -326,6 +336,7 @@ export class NfEditor extends LitElement {
|
||||
this.narrow = false;
|
||||
this.roomLabels = true;
|
||||
this._floorId = null;
|
||||
this._editorScope=null;this._floorMove=null;this._roomMove=null;
|
||||
this._arcEdit = null;
|
||||
this._routeDraft = null;
|
||||
this.roof.sectionId = null;
|
||||
@@ -633,7 +644,7 @@ export class NfEditor extends LitElement {
|
||||
const next = structuredClone(this._doc);
|
||||
if (!moveFurnitureToFloor(next, from, id, floorId)) return;
|
||||
this.setDoc(next);
|
||||
this._floorId = floorId;
|
||||
this.adoptFloor(floorId);
|
||||
this.selectItem("furniture", id);
|
||||
}
|
||||
|
||||
@@ -679,7 +690,7 @@ export class NfEditor extends LitElement {
|
||||
return new RoofController({
|
||||
host: this.host,
|
||||
floorId: () => editor._floorId,
|
||||
setFloorId: (id) => (editor._floorId = id),
|
||||
setFloorId: (id) => editor.adoptFloor(id),
|
||||
confirm: (text) => confirm(text),
|
||||
refresh: () => editor.requestUpdate(),
|
||||
});
|
||||
@@ -703,7 +714,7 @@ export class NfEditor extends LitElement {
|
||||
|
||||
/** What the roof and solar forms need. */
|
||||
private roofDeps(): RoofPanelDeps {
|
||||
return { host: this.host, roof: this.roof, floorId: this._floorId, setFloorId: (id) => (this._floorId = id), toggleLockPlan: () => this.toggleLockPlan() };
|
||||
return { host: this.host, roof: this.roof, floorId: this._floorId, setFloorId: (id) => this.adoptFloor(id), toggleLockPlan: () => this.toggleLockPlan() };
|
||||
}
|
||||
|
||||
private makeBackup(): BackupService {
|
||||
@@ -718,7 +729,7 @@ export class NfEditor extends LitElement {
|
||||
t: (key, vars) => editor.t(key, vars),
|
||||
adopt: (building) => {
|
||||
editor.setDoc(building);
|
||||
editor._floorId = building.floors[0]?.id ?? null;
|
||||
editor._editorScope=null;editor.adoptFloor(building.floors[0]?.id??null);
|
||||
editor.selectItem("room", null);
|
||||
editor.fit();
|
||||
},
|
||||
@@ -782,9 +793,11 @@ export class NfEditor extends LitElement {
|
||||
}
|
||||
this._doc = this.building;
|
||||
this._doc3d = this.building;
|
||||
if (!this._doc.floors.some((f) => f.id === this._floorId)) this._floorId = this._doc.floors[0]?.id ?? null;
|
||||
this.syncEditorContext();
|
||||
if (!this.floor?.rooms.some((r) => r.id === this.sel.room)) this.sel.room = null;
|
||||
}
|
||||
if(changed.has("_doc"))this.syncEditorContext();
|
||||
if(changed.has("_size")&&(this._editorScope?.kind==="branch"||this._editorScope?.kind==="location"))this.fit();
|
||||
}
|
||||
|
||||
protected firstUpdated(): void {
|
||||
@@ -1053,6 +1066,7 @@ export class NfEditor extends LitElement {
|
||||
<nf-view3d
|
||||
.hass=${this.hass ? withSymconWeather(withCoverControls(this.hass, this._doc3d.floors), this._doc3d.settings) : undefined}
|
||||
.building=${this._doc3d}
|
||||
.topologySelection=${this._editorScope}
|
||||
.floorId=${this.houseTool ? null : this._floorId}
|
||||
.roomId=${null}
|
||||
.wallMode=${this.houseTool ? "auto" : this._wall3d}
|
||||
@@ -1089,11 +1103,11 @@ export class NfEditor extends LitElement {
|
||||
}}
|
||||
@device-move=${this.onDeviceMoved3d}
|
||||
@floor-tap=${(e: CustomEvent<{ floorId: string | null }>) => {
|
||||
if (e.detail.floorId) this._floorId = e.detail.floorId;
|
||||
if (e.detail.floorId) this.adoptFloor(e.detail.floorId);
|
||||
this._sideOpen = false;
|
||||
}}
|
||||
@room-tap=${(e: CustomEvent<{ floorId: string; roomId: string | null }>) => {
|
||||
if (e.detail.floorId) this._floorId = e.detail.floorId;
|
||||
if (e.detail.floorId) this.adoptFloor(e.detail.floorId);
|
||||
if (e.detail.roomId) this.selectFrom3d("room", e.detail.roomId);
|
||||
else this._sideOpen = false;
|
||||
}}
|
||||
@@ -1123,6 +1137,137 @@ export class NfEditor extends LitElement {
|
||||
|
||||
// ------------------------------------------------------------------ document helpers
|
||||
|
||||
private clearPlanSelection(): void {
|
||||
this.cancelPick();
|
||||
this.selectItem("room",null);
|
||||
this._note=null;this._draft=[];this._cursor=null;this._ctx=null;this._wallView=null;this.drag=null;this._fixedHint=false;
|
||||
this.side.floorCopy=null;this.side.floorMenu=false;
|
||||
this.side.shiftX=0;this.side.shiftZ=0;
|
||||
}
|
||||
|
||||
private syncEditorContext(): void {
|
||||
const next=reconcileEditorContext(this._doc,{scope:this._editorScope,floorId:this._floorId});
|
||||
if(next.floorId===this._floorId&&editorScopeKey(next.scope)===editorScopeKey(this._editorScope))return;
|
||||
this._editorScope=next.scope;this._floorId=next.floorId;this.clearPlanSelection();
|
||||
}
|
||||
|
||||
private adoptFloor(id:string|null):void {
|
||||
const f=id?this._doc.floors.find((f)=>f.id===id):undefined;
|
||||
if(id&&!f)return;
|
||||
this._floorId=f?.id??null;
|
||||
if(f)this._editorScope=this._doc.topology?scopeForFloor(f):null;
|
||||
this.clearPlanSelection();
|
||||
}
|
||||
|
||||
private selectBuilding(scope:EditorScope):void {
|
||||
const valid=editorScopeFromKey(this._doc,editorScopeKey(scope));if(!valid)return;
|
||||
const next=selectEditorScope(this._doc,valid);
|
||||
this._editorScope=next.scope;this._floorId=next.floorId;
|
||||
if(scope.kind==="branch"||scope.kind==="location")this._tool="select";
|
||||
this.reframe3d=true;
|
||||
this.clearPlanSelection();this.fit();
|
||||
}
|
||||
|
||||
private openHierarchy():void {
|
||||
const dialog=this.renderRoot.querySelector<HTMLDialogElement>(".nf-hierarchy-dialog");
|
||||
if(dialog&&!dialog.open)dialog.showModal();
|
||||
}
|
||||
|
||||
private async openFloorMove():Promise<void> {
|
||||
if(!this.isAdmin||!this.floor||isOutdoorFloor(this.floor)||!this._doc.topology)return;
|
||||
this._floorMove={floorId:this.floor.id,targetId:""};await this.updateComplete;
|
||||
const dialog=this.renderRoot.querySelector<HTMLDialogElement>(".nf-floor-move-dialog");
|
||||
if(dialog&&!dialog.open)dialog.showModal();
|
||||
}
|
||||
|
||||
private applyFloorMove():void {
|
||||
if(!this.isAdmin||!this._floorMove)return;
|
||||
const {floorId,targetId}=this._floorMove,next=structuredClone(this._doc);
|
||||
if(!moveSelectedFloor(next,this.floor?.id??null,floorId,targetId))return;
|
||||
this.setDoc(next);this.adoptFloor(floorId);this.fit();
|
||||
this.renderRoot.querySelector<HTMLDialogElement>(".nf-floor-move-dialog")?.close();
|
||||
}
|
||||
|
||||
private async openRoomMove():Promise<void> {
|
||||
if(!this.isAdmin||!this.floor||!this.room)return;
|
||||
this._roomMove={sourceId:this.floor.id,roomId:this.room.id,buildingId:"",targetId:"",x:0,z:0,error:""};
|
||||
await this.updateComplete;
|
||||
this.renderRoot.querySelector<HTMLDialogElement>(".nf-room-move-dialog")?.showModal();
|
||||
}
|
||||
|
||||
private applyRoomMove():void {
|
||||
const move=this._roomMove;
|
||||
if(!this.isAdmin||!move||move.sourceId!==this.floor?.id||move.roomId!==this.room?.id)return;
|
||||
const next=structuredClone(this._doc),target=next.floors.find((f)=>f.id===move.targetId);
|
||||
if(!target||target.building_id!==move.buildingId)return;
|
||||
const error=moveRoomToFloor(next,move.sourceId,move.roomId,move.targetId,[move.x,move.z]);
|
||||
if(error){this._roomMove={...move,error};return;}
|
||||
this.setDoc(next);this.adoptFloor(move.targetId);this.selectItem("room",move.roomId);this.fit();
|
||||
this.renderRoot.querySelector<HTMLDialogElement>(".nf-room-move-dialog")?.close();
|
||||
}
|
||||
|
||||
private renderRoomMoveDialog():TemplateResult {
|
||||
const move=this._roomMove,source=this._doc.floors.find((f)=>f.id===move?.sourceId),room=source?.rooms.find((r)=>r.id===move?.roomId);
|
||||
const buildings=editorScopeChoices(this._doc).filter(([key])=>key.startsWith("building:"));
|
||||
const floors=this._doc.floors.filter((f)=>!isOutdoorFloor(f)&&f.building_id===move?.buildingId&&f.id!==move?.sourceId);
|
||||
return html`<dialog class="nf-room-move-dialog" aria-label="Raum verschieben" @close=${(e:Event)=>{if(!(e.target as HTMLDialogElement).open)this._roomMove=null;}} @keydown=${(e:KeyboardEvent)=>e.stopPropagation()}>
|
||||
<header><h2>Raum verschieben</h2><button class="nf-btn" aria-label="Schließen" @click=${()=>this.renderRoot.querySelector<HTMLDialogElement>(".nf-room-move-dialog")?.close()}>×</button></header>
|
||||
${move&&source&&room?html`<p>${floorTopologyPath(this._doc,source)} / ${room.name}</p>
|
||||
<div class="nf-form">
|
||||
<label class="nf-field nf-wide">Zielgebäude<select class="nf-room-move-building" @change=${(e:Event)=>this._roomMove={...move,buildingId:(e.target as HTMLSelectElement).value,targetId:"",error:""}}>
|
||||
<option value="" .selected=${!move.buildingId}>Gebäude auswählen</option>${buildings.map(([key,name])=>html`<option value=${key.slice(9)} .selected=${move.buildingId===key.slice(9)}>${name}</option>`)}
|
||||
</select></label>
|
||||
<label class="nf-field nf-wide">Zieletage<select class="nf-room-move-floor" ?disabled=${!move.buildingId} @change=${(e:Event)=>{const targetId=(e.target as HTMLSelectElement).value,f=floors.find((f)=>f.id===targetId),[x,z]=f?roomMovePosition(f):[0,0];this._roomMove={...move,targetId,x,z,error:""};}}>
|
||||
<option value="" .selected=${!move.targetId}>${move.buildingId&&!floors.length?"Keine andere Etage in diesem Gebäude":"Etage auswählen"}</option>${floors.map((f)=>html`<option value=${f.id} .selected=${move.targetId===f.id}>${f.name}</option>`)}
|
||||
</select></label>
|
||||
${(["x","z"] as const).map((axis)=>html`<label class="nf-field">${axis.toUpperCase()} (m)<input class="nf-room-move-${axis}" type="number" step="0.05" .value=${String(move[axis])} ?disabled=${!move.targetId} @change=${(e:Event)=>this._roomMove={...move,[axis]:(e.target as HTMLInputElement).valueAsNumber,error:""}} /></label>`)}
|
||||
${hint("Der Raum wird zusammen mit seinen Türen, Fenstern, Möbeln, platzierten Geräten und Notizen verschoben. Datenpunktverknüpfungen bleiben erhalten. X und Z bestimmen die linke obere Ecke auf der Zieletage; vorgeschlagen wird ein freier Platz neben den vorhandenen Räumen.","nf-wide")}
|
||||
${move.error?html`<p class="nf-room-move-error nf-wide" role="alert">${move.error}</p>`:nothing}
|
||||
</div>
|
||||
<button class="nf-btn nf-primary nf-room-move-apply" ?disabled=${!this.isAdmin||!floors.some((f)=>f.id===move.targetId)||![move.x,move.z].every(Number.isFinite)||this.floor?.id!==move.sourceId||this.room?.id!==move.roomId} @click=${()=>this.applyRoomMove()}>Raum „${room.name}“ verschieben</button>`:nothing}
|
||||
</dialog>`;
|
||||
}
|
||||
|
||||
private renderEditorNavigation():TemplateResult|typeof nothing {
|
||||
if(!this._doc.topology)return isSymcon(this.hass)?html`<div class="nf-editor-context"><button class="nf-btn nf-hierarchy-open" @click=${()=>this.openHierarchy()}>Hierarchie</button></div>`:nothing;
|
||||
const scope=this._editorScope,choices=editorScopeChoices(this._doc),floors=editorFloors(this._doc,scope);
|
||||
const overview=scope?.kind==="branch"||scope?.kind==="location";
|
||||
const label=choices.find(([key])=>key===editorScopeKey(scope))?.[1]??"Ansicht auswählen";
|
||||
return html`<div class="nf-editor-context">
|
||||
<div class="nf-editor-building-row"><label>Ansicht<select class="nf-editor-building-select" aria-label="Ort, Niederlassung oder Gebäude" title=${label} @change=${(e:Event)=>{const s=editorScopeFromKey(this._doc,(e.target as HTMLSelectElement).value);if(s)this.selectBuilding(s);}}>
|
||||
${!scope?html`<option value="">Ansicht auswählen</option>`:nothing}
|
||||
${choices.map(([key,name])=>html`<option value=${key} .selected=${key===editorScopeKey(scope)}>${key.startsWith("branch:")?"Niederlassung · ":key.startsWith("location:")?"Ort · ":""}${name}</option>`)}
|
||||
</select></label><button class="nf-btn nf-hierarchy-open" @click=${()=>this.openHierarchy()}>Hierarchie</button></div>
|
||||
<nav class="nf-editor-floor-nav" aria-label="Untergeordnete Pläne">
|
||||
<span class="nf-muted">${overview?"Auswahl":scope?.kind==="outside"?"Außenplan":"Etagen"}</span>
|
||||
${overview?topologyItems(this._doc,scope).map((n)=>html`<button class="nf-chip" data-editor-scope=${n.key} @click=${()=>this.selectBuilding(n.selection as EditorScope)}>${n.name}</button>`):[...floors].reverse().map((f)=>html`<button class="nf-chip" data-editor-floor=${f.id} aria-pressed=${f.id===this._floorId} @click=${()=>{this.adoptFloor(f.id);this.fit();}}>${f.name}</button>`)}
|
||||
${scope?.kind==="building"?topologyItems(this._doc,scope).filter((n)=>n.selection.kind==="outside").map((n)=>html`<button class="nf-chip" data-editor-scope=${n.key} @click=${()=>this.selectBuilding(n.selection as EditorScope)}>🌳 Außen</button>`):nothing}
|
||||
${scope?.kind==="building"?html`<button class="nf-btn nf-editor-add-floor" ?disabled=${!this.isAdmin} @click=${()=>this.addFloor(null)}>+ Etage</button>`:nothing}
|
||||
${this.floor&&!isOutdoorFloor(this.floor)?html`<button class="nf-link nf-editor-move-floor" ?disabled=${!this.isAdmin} @click=${()=>void this.openFloorMove()}>Ausgewählte Etage verschieben…</button>`:nothing}
|
||||
</nav>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private renderHierarchyDialogs():TemplateResult {
|
||||
const move=this._floorMove,source=move?this._doc.floors.find((f)=>f.id===move.floorId):undefined;
|
||||
const targets=editorScopeChoices(this._doc).filter(([key])=>key.startsWith("building:")&&key!==`building:${source?.building_id}`);
|
||||
return html`<dialog class="nf-hierarchy-dialog" aria-label="Hierarchie verwalten" @keydown=${(e:KeyboardEvent)=>e.stopPropagation()}>
|
||||
<header><h2>Hierarchie verwalten</h2><button class="nf-btn" aria-label="Schließen" @click=${()=>this.renderRoot.querySelector<HTMLDialogElement>(".nf-hierarchy-dialog")?.close()}>×</button></header>
|
||||
<nf-hierarchy-manager .doc=${this._doc} .admin=${this.isAdmin} .suggestedName=${this.hass?.symconTitle?.trim()||"Gebäude 1"}
|
||||
@hierarchy-change=${(e:CustomEvent<{building:Building}>)=>{e.stopPropagation();if(this.isAdmin)this.setDoc(e.detail.building);}}
|
||||
@hierarchy-open=${(e:CustomEvent<EditorScope>)=>{e.stopPropagation();this.selectBuilding(e.detail);this.renderRoot.querySelector<HTMLDialogElement>(".nf-hierarchy-dialog")?.close();}}></nf-hierarchy-manager>
|
||||
</dialog>
|
||||
<dialog class="nf-floor-move-dialog" aria-label="Ausgewählte Etage verschieben" @close=${(e:Event)=>{if(!(e.target as HTMLDialogElement).open)this._floorMove=null;}} @keydown=${(e:KeyboardEvent)=>e.stopPropagation()}>
|
||||
<header><h2>Ausgewählte Etage verschieben</h2><button class="nf-btn" aria-label="Schließen" @click=${()=>this.renderRoot.querySelector<HTMLDialogElement>(".nf-floor-move-dialog")?.close()}>×</button></header>
|
||||
${move&&source?html`<p class="nf-floor-move-source">${floorTopologyPath(this._doc,source)}</p>
|
||||
<label class="nf-field">Zielgebäude<select class="nf-floor-move-target" @change=${(e:Event)=>this._floorMove={...move,targetId:(e.target as HTMLSelectElement).value}}>
|
||||
<option value="" .selected=${!move.targetId}>Zielgebäude auswählen</option>
|
||||
${targets.map(([key,name])=>html`<option value=${key.slice(9)} .selected=${move.targetId===key.slice(9)}>${name}</option>`)}
|
||||
</select></label>
|
||||
<button class="nf-btn nf-primary nf-floor-move-apply" ?disabled=${!this.isAdmin||!move.targetId||source.id!==this.floor?.id||!targets.some(([key])=>key===`building:${move.targetId}`)} @click=${()=>this.applyFloorMove()}>Etage „${source.name}“ verschieben</button>`:nothing}
|
||||
</dialog>`;
|
||||
}
|
||||
|
||||
private get floor(): Floor | undefined {
|
||||
return this._doc?.floors.find((f) => f.id === this._floorId);
|
||||
}
|
||||
@@ -1138,7 +1283,9 @@ export class NfEditor extends LitElement {
|
||||
/** Replace the document; `base` (the state before the change) goes into the undo history. */
|
||||
private setDoc(next: Building, base: Building | null = this._doc): void {
|
||||
if (base) this.history.record(base);
|
||||
if(next.topology)normalizeTopology(next);
|
||||
this._doc = next;
|
||||
this.syncEditorContext();
|
||||
this.syncHistoryButtons();
|
||||
this.dispatchEvent(new CustomEvent("building-changed", { detail: { building: next }, bubbles: true, composed: true }));
|
||||
}
|
||||
@@ -1169,7 +1316,7 @@ export class NfEditor extends LitElement {
|
||||
|
||||
private restore(doc: Building): void {
|
||||
this._doc = doc;
|
||||
if (!doc.floors.some((f) => f.id === this._floorId)) this._floorId = doc.floors[0]?.id ?? null;
|
||||
this.syncEditorContext();
|
||||
if (!this.floor?.rooms.some((r) => r.id === this.sel.room)) this.sel.room = null;
|
||||
this.sel.corner = null;
|
||||
this.syncHistoryButtons();
|
||||
@@ -1210,7 +1357,8 @@ export class NfEditor extends LitElement {
|
||||
}
|
||||
|
||||
private fit(): void {
|
||||
const pts = this.floor?.rooms.flatMap((r) => r.points) ?? [];
|
||||
const floors=this.floor?[this.floor]:this._doc.topology?editorFloors(this._doc,this._editorScope):[];
|
||||
const pts = floors.flatMap((f)=>[...f.rooms.flatMap((r)=>r.points),...f.outdoor.flatMap((a)=>a.points),...f.furniture.map((p):Vec2=>[p.x,p.z]),...f.placements.map((p):Vec2=>[p.x,p.z])]);
|
||||
const b = pts.length ? bounds(pts) : { x0: 0, z0: 0, x1: 10, z1: 8 };
|
||||
const margin = 1.5;
|
||||
const w = b.x1 - b.x0 + 2 * margin;
|
||||
@@ -1250,6 +1398,8 @@ export class NfEditor extends LitElement {
|
||||
// ------------------------------------------------------------------ pointer input
|
||||
|
||||
private onPointerDown(e: PointerEvent): void {
|
||||
const overview=(e.target as Element)?.closest("[data-overview-floor]")?.getAttribute("data-overview-floor");
|
||||
if(overview){this.adoptFloor(overview);this.fit();return;}
|
||||
// a form is waiting for one place on the plan: this tap is it
|
||||
if (this._pick) {
|
||||
const [sx, sy] = this.localPoint(e);
|
||||
@@ -2158,6 +2308,8 @@ export class NfEditor extends LitElement {
|
||||
|
||||
private readonly onKey = (e: KeyboardEvent) => {
|
||||
const path = e.composedPath();
|
||||
const overview=path.find((el)=>el instanceof Element&&el.hasAttribute("data-overview-floor")) as Element|undefined;
|
||||
if(overview&&(e.key==="Enter"||e.key===" ")){e.preventDefault();this.adoptFloor(overview.getAttribute("data-overview-floor"));this.fit();return;}
|
||||
if (path.some((el) => el instanceof HTMLInputElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement)) return;
|
||||
if (!this.isConnected || !this.offsetParent) return;
|
||||
if (e.key === "Escape" && this._pick) {
|
||||
@@ -2226,8 +2378,8 @@ export class NfEditor extends LitElement {
|
||||
const next = structuredClone(this._doc);
|
||||
next.floors = next.floors.filter((f) => f.id !== floor.id);
|
||||
this.setDoc(next);
|
||||
this._floorId = next.floors[0]?.id ?? null;
|
||||
this.sel.room = null;
|
||||
this.syncEditorContext();
|
||||
this.clearPlanSelection();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ roof sections
|
||||
@@ -2254,7 +2406,7 @@ export class NfEditor extends LitElement {
|
||||
${outdoorHandlesLayer(ctx, this.outdoorArea, this._tool)}
|
||||
${room && this._tool === "select" ? cutMarksLayer(ctx, room) : nothing}
|
||||
${headroomLayer(ctx, floor)}`
|
||||
: nothing}
|
||||
: this._doc.topology?scopeOverviewLayer(ctx,editorFloors(this._doc,this._editorScope)):nothing}
|
||||
${this._tool === "roof" ? svg`${roofSectionsLayer(ctx, this.roof)}${roofWindowsLayer(ctx, this.roof)}${chimneysLayer(ctx, this.roof)}` : this._tool === "energy" ? svg`${roofSectionsLayer(ctx, this.roof)}${solarLayer(ctx, this.roof)}${energyRoutesLayer(ctx, this.floor, this._doc.energy.routes ?? [], this._routeDraft)}${energyMarkersLayer(ctx, this.floor, this.sel.furniture)}` : nothing}
|
||||
${draftLayer(ctx, sketch, this._tool, this._draft, this._cursor)} ${guidesLayer(ctx, this._guides, this._size)}`;
|
||||
}
|
||||
@@ -2321,13 +2473,15 @@ export class NfEditor extends LitElement {
|
||||
|
||||
// ------------------------------------------------------------------ floors and rooms
|
||||
|
||||
private addFloor(from: HassFloor | null = null): void {
|
||||
const floor = newFloorFor(this._doc, from, { first: this.t("default_floor"), next: (n) => this.t("new_floor", { n }) });
|
||||
private addFloor(from: HassFloor | null = null, parent?: string): void {
|
||||
if(!this.isAdmin)return;
|
||||
const target=parent??(this._editorScope?.kind==="building"?this._editorScope.id:undefined);
|
||||
if(this._doc.topology&&(!target||!this._doc.topology.buildings.some((g)=>g.id===target)))return;
|
||||
const floor = newFloorFor(this._doc, from, { first: this.t("default_floor"), next: (n) => this.t("new_floor", { n }) }, target);
|
||||
const next = structuredClone(this._doc);
|
||||
next.floors = floorsWith(next.floors, floor);
|
||||
this.setDoc(next);
|
||||
this._floorId = floor.id;
|
||||
this.sel.room = null;
|
||||
this.adoptFloor(floor.id);
|
||||
this.side.floorMenu = false;
|
||||
this.fit();
|
||||
}
|
||||
@@ -2349,8 +2503,7 @@ export class NfEditor extends LitElement {
|
||||
const next = structuredClone(this._doc);
|
||||
next.floors = floorsWith(next.floors, copy);
|
||||
this.setDoc(next);
|
||||
this._floorId = copy.id;
|
||||
this.sel.room = null;
|
||||
this.adoptFloor(copy.id);
|
||||
this.side.floorCopy = null;
|
||||
this.fit();
|
||||
}
|
||||
@@ -2358,7 +2511,11 @@ export class NfEditor extends LitElement {
|
||||
private moveFloor(direction: -1 | 1): void {
|
||||
const id = this._floorId;
|
||||
if (!id) return;
|
||||
const order = floorsSwapped(this._doc.floors, id, direction);
|
||||
const siblings = editorFloors(this._doc, this._editorScope);
|
||||
const reordered = floorsSwapped(siblings, id, direction);
|
||||
const ids = new Set(siblings.map((f) => f.id));
|
||||
let at = 0;
|
||||
const order = this._doc.floors.map((f) => ids.has(f.id) ? reordered[at++] : f);
|
||||
if (order.every((f, i) => f.id === this._doc.floors[i].id)) return;
|
||||
const next = structuredClone(this._doc);
|
||||
next.floors = order.map((f) => next.floors.find((x) => x.id === f.id)!);
|
||||
@@ -2368,10 +2525,7 @@ export class NfEditor extends LitElement {
|
||||
private floorActions(): FloorActions {
|
||||
return {
|
||||
openFloor: (id) => {
|
||||
this._floorId = id;
|
||||
this.sel.room = null;
|
||||
this.sel.corner = null;
|
||||
this._draft = [];
|
||||
this.adoptFloor(id);
|
||||
this.fit();
|
||||
},
|
||||
print: () => this.printPlan(),
|
||||
@@ -2390,13 +2544,14 @@ export class NfEditor extends LitElement {
|
||||
private roomActions(room: Room): RoomActions {
|
||||
return {
|
||||
select: (id) => this.selectItem("room", id),
|
||||
patch: (patch) => this.updateRoom(patch),
|
||||
setArea: (id) => this.setArea(id),
|
||||
patch: (patch) => { if(this.room?.id===room.id)this.updateRoom(patch); },
|
||||
setArea: (id) => { if(this.room?.id===room.id)this.setArea(id); },
|
||||
setRect: (field, value) => this.setRect(field, value),
|
||||
setCorner: (index, axis, value) => this.setPoint(index, axis, value),
|
||||
removeCorner: (index) => this.deleteVertex(index),
|
||||
duplicate: () => this.duplicateRoom(),
|
||||
remove: () => this.deleteRoom(),
|
||||
move: () => {if(this.room?.id===room.id)void this.openRoomMove();},
|
||||
rememberView: () => this.rememberRoomView(),
|
||||
applyPackage: (pkg) => this.applyPackage(room, pkg),
|
||||
openSpots: () => {
|
||||
@@ -2621,7 +2776,7 @@ export class NfEditor extends LitElement {
|
||||
}
|
||||
|
||||
private shiftScope(): Scope {
|
||||
return { floorId: this._floorId, allFloors: this.side.shiftAll };
|
||||
return { floorId: this._floorId, allFloors: this.side.shiftAll, ...(this._doc.topology&&this._floorId?{floorIds:topologyFloors(this._doc,floorSelection(this._doc,this._floorId),true).map((f)=>f.id)}:{}) };
|
||||
}
|
||||
|
||||
/** Moves everything on the floor (or on every floor) by the typed distance. */
|
||||
@@ -2722,7 +2877,7 @@ export class NfEditor extends LitElement {
|
||||
}
|
||||
|
||||
private openEnergyDevice(floor: Floor, item: Furniture): void {
|
||||
this._floorId = floor.id;
|
||||
this.adoptFloor(floor.id);
|
||||
this.roof.solarId = null;
|
||||
this.selectItem("furniture", item.id);
|
||||
this.showPoint(item.x, item.z);
|
||||
@@ -3159,12 +3314,16 @@ export class NfEditor extends LitElement {
|
||||
const floor = this.floor;
|
||||
const walls = floor ? generateWalls(floor.rooms, { exterior: this._doc.settings.wall_exterior, interior: this._doc.settings.wall_interior }, floor.walls ?? []) : null;
|
||||
return html`
|
||||
${this.renderHierarchyDialogs()}
|
||||
${this.renderRoomMoveDialog()}
|
||||
${renderPreview(this.host, this.lib.preview)}
|
||||
${this._wallView
|
||||
? html`<nf-wall-view .host=${this.host} .doc=${this._doc} .roomId=${this._wallView.roomId} .edge=${this._wallView.edge} @close=${() => (this._wallView = null)}></nf-wall-view>`
|
||||
: nothing}
|
||||
<div class="nf-editor ${this.narrow ? "nf-narrow" : ""}">
|
||||
<div class="nf-main">
|
||||
<div class="nf-editor-head">
|
||||
${this.renderEditorNavigation()}
|
||||
<div class="nf-toolbar">
|
||||
${this.narrow
|
||||
? html`<select class="nf-tool-select" aria-label=${this.t("tool_select")} ?disabled=${!floor} @change=${(e: Event) => {
|
||||
@@ -3207,6 +3366,7 @@ export class NfEditor extends LitElement {
|
||||
</div>
|
||||
${walls?.warnings.length ? html`<span class="nf-warn">${this.t("overlap_warning")}</span>` : nothing}
|
||||
</div>
|
||||
</div>
|
||||
<div class="nf-stage-pair ${this._split ? "nf-split" : ""}" style=${this._split && !this.narrow ? `--nf-split:${Math.round(this._splitRatio * 100)}%` : ""}>
|
||||
<div class="nf-canvas-wrap">
|
||||
${this.houseTool ? html`<div class="nf-tool-note">${this.t(this._tool === "energy" ? "energy_only_note" : "roof_only_note")}</div>` : nothing}
|
||||
@@ -3225,7 +3385,7 @@ export class NfEditor extends LitElement {
|
||||
${this.planLayers(floor, walls?.walls ?? null)}
|
||||
</svg>
|
||||
${this.renderContext()}
|
||||
${this._pick || this._fixedHint ? html`<p class="nf-hint ${this._fixedHint ? "nf-hint-fixed" : ""}">${this._pick ? this.t("robot_cal_doing") : this.t("fixed_drag_hint")}</p>` : html`<div class="nf-hint">${hint(!floor ? this.t("hint_empty") : this.t(`hint_${this._tool}` as I18nKey))}</div>`}
|
||||
${this._pick || this._fixedHint ? html`<p class="nf-hint ${this._fixedHint ? "nf-hint-fixed" : ""}">${this._pick ? this.t("robot_cal_doing") : this.t("fixed_drag_hint")}</p>` : html`<div class="nf-hint">${hint(!floor ? this._doc.topology ? "Wähle oben ein Gebäude und lege dort mit + Etage ein Stockwerk an. Ort, Niederlassung und Gebäude verwaltest du über Hierarchie." : this.t("hint_empty") : this.t(`hint_${this._tool}` as I18nKey))}</div>`}
|
||||
<button class="nf-keys-open" title=${this.t("keys_title")} aria-label=${this.t("keys_title")} @click=${() => (this._keys = true)}>?</button>
|
||||
${this.isAdmin
|
||||
? renderTour((k, vars) => this.t(k, vars), this._tour, (step) => {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { bounds, centroid, isFixed, polygonArea, roomsReachingUp, type Floor, ty
|
||||
import type { Wall } from "../../../geometry/walls.ts";
|
||||
import { edgePlus, pointsAttribute, type CanvasContext } from "./context.ts";
|
||||
import { formatArea, formatLength } from "../../../units.ts";
|
||||
import { isOutdoorFloor } from "../../../topology.ts";
|
||||
|
||||
type Layer = TemplateResult | typeof nothing;
|
||||
|
||||
@@ -40,7 +41,8 @@ export function gridLayer(ctx: CanvasContext, size: { w: number; h: number }): L
|
||||
|
||||
/** The rooms of the floor below, faintly, as orientation; rooms below that rise through this floor are hatched – it stays open there. */
|
||||
export function floorBelowLayer(ctx: CanvasContext): Layer {
|
||||
const floors = ctx.host.doc.floors;
|
||||
const current=ctx.host.doc.floors.find((f)=>f.id===ctx.floorId);
|
||||
const floors = ctx.host.doc.topology?ctx.host.doc.floors.filter((f)=>isOutdoorFloor(current)?f.id===current?.id:!isOutdoorFloor(f)&&f.building_id===current?.building_id):ctx.host.doc.floors;
|
||||
const at = floors.findIndex((f) => f.id === ctx.floorId);
|
||||
const below = at > 0 ? floors[at - 1] : undefined;
|
||||
if (!below) return nothing;
|
||||
@@ -50,6 +52,18 @@ export function floorBelowLayer(ctx: CanvasContext): Layer {
|
||||
)}</g>`;
|
||||
}
|
||||
|
||||
/** Read-only overview; clicking an outline first opens its actual floor for editing. */
|
||||
export function scopeOverviewLayer(ctx: CanvasContext, floors: readonly Floor[]): Layer {
|
||||
return svg`<g class="nf-scope-overview">${floors.map((f)=>{
|
||||
const points=[...f.rooms.flatMap((r)=>r.points),...f.outdoor.flatMap((a)=>a.points)];
|
||||
const c=points.length?centroid(points):null;
|
||||
return svg`<g data-overview-floor=${f.id} tabindex="0" role="button" aria-label=${f.name}>
|
||||
<title>${f.name}</title>${[...f.rooms.map((r)=>r.points),...f.outdoor.map((a)=>a.points)].map((p)=>svg`<polygon points=${pointsAttribute(ctx,p)} />`)}
|
||||
${c?svg`<text x=${ctx.toScreen(c)[0]} y=${ctx.toScreen(c)[1]}>${f.name}</text>`:nothing}
|
||||
</g>`;
|
||||
})}</g>`;
|
||||
}
|
||||
|
||||
/** The wall pieces; outer ones are drawn stronger, and walls lower than the floor lighter. */
|
||||
export function wallsLayer(ctx: CanvasContext, walls: readonly Wall[]): Layer {
|
||||
const full = ctx.host.floor?.height ?? 2.5;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { emptyBuilding, newFloor } from "../../model.ts";
|
||||
import { box } from "../../entities/fixtures.ts";
|
||||
import { editorFloors, editorScopeChoices, editorScopeFromKey, moveSelectedFloor, reconcileEditorContext, selectEditorScope } from "./editor-context.ts";
|
||||
import { newFloorFor } from "./ops/floors.ts";
|
||||
|
||||
function project(){
|
||||
const b=emptyBuilding();b.topology={locations:[{id:"u",name:"Urbach"}],branches:[{id:"nl",name:"Zentrale",location_id:"u"}],buildings:[{id:"a",name:"RAS19",branch_id:"nl"},{id:"b",name:"RAS21",branch_id:"nl"},{id:"empty",name:"Neu",branch_id:"nl"}]};
|
||||
b.floors=[{...newFloor("eg-a","EG",0),building_id:"a",rooms:[box("it",0,0,5,5,"symcon-category-100")]},{...newFloor("eg-b","EG",0),building_id:"b"}];return b;
|
||||
}
|
||||
test("choosing a building is pure navigation and exposes only its own storeys",()=>{
|
||||
const b=project(),before=structuredClone(b),scope={kind:"building" as const,id:"b"};
|
||||
assert.deepEqual(selectEditorScope(b,scope),{scope,floorId:"eg-b"});
|
||||
assert.deepEqual(editorFloors(b,scope).map((f)=>f.id),["eg-b"]);assert.deepEqual(b,before);
|
||||
});
|
||||
test("an explicitly selected empty building stays empty across reloads, metadata edits and changes in another building",()=>{
|
||||
const b=project(),context=selectEditorScope(b,{kind:"building",id:"empty"});
|
||||
assert.equal(context.floorId,null);assert.deepEqual(reconcileEditorContext(b,context),context);
|
||||
b.topology!.locations[0].name="Urbach neu";b.floors.push({...newFloor("og-a","OG",3),building_id:"a"});
|
||||
assert.deepEqual(reconcileEditorContext(JSON.parse(JSON.stringify(b)),context),context);
|
||||
assert.deepEqual(reconcileEditorContext(b,{...context,floorId:"eg-a"}),context,"a foreign floor never becomes the implicit edit target");
|
||||
const added=newFloorFor(b,null,{first:"EG",next:(n)=>`Etage ${n}`},context.scope!.id);
|
||||
assert.equal(added.building_id,"empty");assert.equal(added.elevation,0);
|
||||
});
|
||||
test("deleting the last storey keeps its building selected instead of jumping to another building",()=>{
|
||||
const b=project(),context=selectEditorScope(b,{kind:"building",id:"b"});b.floors=b.floors.filter((f)=>f.id!=="eg-b");
|
||||
assert.deepEqual(reconcileEditorContext(b,context),{scope:{kind:"building",id:"b"},floorId:null});
|
||||
});
|
||||
test("floor reparenting requires the exact captured floor to still be selected and preserves room/data IDs",()=>{
|
||||
const b=project(),before=structuredClone(b);
|
||||
assert.equal(moveSelectedFloor(b,"eg-b","eg-a","empty"),false);assert.deepEqual(b,before);
|
||||
assert.equal(moveSelectedFloor(b,null,"eg-a","empty"),false);assert.deepEqual(b,before);
|
||||
assert.equal(moveSelectedFloor(b,"eg-a","eg-a","missing"),false);assert.deepEqual(b,before);
|
||||
assert.equal(moveSelectedFloor(b,"eg-a","eg-a","empty"),true);
|
||||
assert.deepEqual(b.floors[0],{...before.floors[0],building_id:"empty"});assert.deepEqual(b.floors[1],before.floors[1]);
|
||||
});
|
||||
test("location outside plans are separate editor scopes and cannot be silently turned into storeys",()=>{
|
||||
const b=project();b.floors.push({...newFloor("garden","Außen",0),outdoor_location_id:"u",building_id:null});
|
||||
const scope={kind:"outside" as const,id:"u"};assert.deepEqual(editorFloors(b,scope).map((f)=>f.id),["garden"]);
|
||||
assert.equal(moveSelectedFloor(b,"garden","garden","a"),false);
|
||||
assert.deepEqual(editorScopeFromKey(b,"outside:u"),scope);assert.equal(editorScopeFromKey(b,"building:unknown"),null);
|
||||
assert.deepEqual(editorScopeChoices(b),[["location:u","Urbach"],["branch:nl","Urbach / Zentrale"],["building:a","Urbach / Zentrale / RAS19"],["building:b","Urbach / Zentrale / RAS21"],["building:empty","Urbach / Zentrale / Neu"],["outside:u","Urbach / Außen"]]);
|
||||
});
|
||||
|
||||
test("selecting an entire location or branch shows its descendants without an implicit editable floor",()=>{
|
||||
const b=project(),before=structuredClone(b),scope={kind:"branch" as const,id:"nl"};
|
||||
const context=selectEditorScope(b,scope);
|
||||
assert.deepEqual(context,{scope,floorId:null});assert.deepEqual(reconcileEditorContext(b,context),context);
|
||||
assert.deepEqual(editorFloors(b,scope).map((f)=>f.id),["eg-a","eg-b"]);
|
||||
assert.deepEqual(selectEditorScope(b,{kind:"location",id:"u"}).floorId,null);
|
||||
assert.deepEqual(b,before);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { Building, Floor } from "../../model.ts";
|
||||
import { isOutdoorFloor, outdoorOwner, outsideFloor, outsideSelection, topologyFloors, topologyKey, topologyPath, type OutsideOwnerKind } from "../../topology.ts";
|
||||
|
||||
export interface EditorScope { kind: "location" | "branch" | "building" | "outside"; id: string; ownerKind?: OutsideOwnerKind }
|
||||
export interface EditorContext { scope: EditorScope | null; floorId: string | null }
|
||||
export const editorScopeKey = (s: EditorScope | null): string => s ? topologyKey(s) : "";
|
||||
|
||||
export function scopeForFloor(f: Floor | undefined): EditorScope | null {
|
||||
if(!f)return null;
|
||||
const owner=outdoorOwner(f);
|
||||
return owner ? outsideSelection(owner) as EditorScope : f.building_id ? {kind:"building",id:f.building_id} : null;
|
||||
}
|
||||
export function editorScopeExists(b: Building, s: EditorScope | null): boolean {
|
||||
if(!s||!b.topology)return false;
|
||||
return s.kind==="outside"?!!outsideFloor(b,s):b.topology[s.kind==="building"?"buildings":s.kind==="branch"?"branches":"locations"].some((g)=>g.id===s.id);
|
||||
}
|
||||
export function editorFloors(b: Building, s: EditorScope | null): Floor[] {
|
||||
if (!b.topology) return b.floors;
|
||||
if (!editorScopeExists(b,s)) return [];
|
||||
return topologyFloors(b,s!).filter((f)=>s!.kind!=="building"||!isOutdoorFloor(f));
|
||||
}
|
||||
/** Navigation returns a context only: choosing a building never edits a floor's parent. */
|
||||
export function selectEditorScope(b: Building, s: EditorScope): EditorContext {
|
||||
return {scope:s,floorId:s.kind==="branch"||s.kind==="location"?null:editorFloors(b,s)[0]?.id??null};
|
||||
}
|
||||
/** In particular an empty, explicitly selected building must never fall back to another building's first floor. */
|
||||
export function reconcileEditorContext(b: Building, current: EditorContext): EditorContext {
|
||||
if (!b.topology) return {scope:null,floorId:b.floors.some((f)=>f.id===current.floorId)?current.floorId:b.floors[0]?.id??null};
|
||||
const scope = editorScopeExists(b,current.scope) ? current.scope : scopeForFloor(b.floors.find((f)=>f.id===current.floorId)??b.floors[0])
|
||||
?? (b.topology.buildings[0]?{kind:"building" as const,id:b.topology.buildings[0].id}:null);
|
||||
const floors=editorFloors(b,scope);
|
||||
if(scope?.kind==="branch"||scope?.kind==="location")return {scope,floorId:null};
|
||||
return {scope,floorId:floors.some((f)=>f.id===current.floorId)?current.floorId:floors[0]?.id??null};
|
||||
}
|
||||
export function editorScopeChoices(b: Building): [string,string][] {
|
||||
const t=b.topology;if(!t)return [];
|
||||
const scopes:EditorScope[]=[...t.locations.map((l):EditorScope=>({kind:"location",id:l.id})),...t.branches.map((n):EditorScope=>({kind:"branch",id:n.id})),...t.buildings.map((g):EditorScope=>({kind:"building",id:g.id})),...b.floors.filter(isOutdoorFloor).map((f)=>scopeForFloor(f)!)];
|
||||
return scopes.map((s)=>[editorScopeKey(s),topologyPath(b,s).slice(1).map((n)=>n.name).join(" / ")]);
|
||||
}
|
||||
export function editorScopeFromKey(b: Building, key: string): EditorScope | null {
|
||||
const [kind,...rest]=key.split(":"),ownerKind=kind==="outside"&&rest.length>1?rest.shift() as OutsideOwnerKind:undefined,id=rest.join(":");
|
||||
const s=["building","branch","location","outside"].includes(kind)?{kind,id,...(ownerKind?{ownerKind}:{})} as EditorScope:null;
|
||||
return editorScopeExists(b,s)?s:null;
|
||||
}
|
||||
/** Explicitly moves the captured, still-selected floor; stale dialogs cannot reassign another floor. */
|
||||
export function moveSelectedFloor(b: Building, selectedFloorId: string|null, sourceFloorId: string, buildingId: string): boolean {
|
||||
const f=b.floors.find((f)=>f.id===sourceFloorId);
|
||||
if(selectedFloorId!==sourceFloorId||!f||isOutdoorFloor(f)||!b.topology?.buildings.some((g)=>g.id===buildingId)||f.building_id===buildingId)return false;
|
||||
f.building_id=buildingId;return true;
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { formatArea } from "../../../units.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
import { freeHaFloors, linkableHaFloors, unplacedAreas } from "../ops/floors.ts";
|
||||
import type { SideState } from "../side-state.ts";
|
||||
import { isOutdoorFloor } from "../../../topology.ts";
|
||||
|
||||
/** What the floor form makes the editor do. */
|
||||
export interface FloorActions {
|
||||
@@ -48,9 +49,10 @@ function areaRow(host: EditorHost, floor: Floor, floorActions: FloorActions): Te
|
||||
/** The chips of the floors, top floor first, and the button that adds one: straight away, or after choosing a floor of Home Assistant. */
|
||||
function floorChips(host: EditorHost, state: SideState, floorActions: FloorActions, selected: string | null): TemplateResult {
|
||||
const free = freeHaFloors(host.doc, host.hass?.floors);
|
||||
const shown=host.doc.floors.filter((f)=>!host.doc.topology||!host.floor||(isOutdoorFloor(host.floor)?f.id===host.floor.id:f.building_id===host.floor.building_id&&!isOutdoorFloor(f)));
|
||||
const addClicked = () => (free.length > 0 ? (state.floorMenu = !state.floorMenu) : floorActions.addFloor(null));
|
||||
return html`<div class="nf-floor-list">
|
||||
${[...host.doc.floors].reverse().map((f) => html`<button class="nf-chip" aria-pressed=${f.id === selected} @click=${() => floorActions.openFloor(f.id)}>${f.name}</button>`)}
|
||||
${[...shown].reverse().map((f) => html`<button class="nf-chip" aria-pressed=${f.id === selected} @click=${() => floorActions.openFloor(f.id)}>${f.name}</button>`)}
|
||||
${host.admin ? html`<button class="nf-btn" aria-expanded=${state.floorMenu} @click=${addClicked}>+ ${host.t("add_floor")}</button>` : nothing}
|
||||
</div>
|
||||
${host.admin && state.floorMenu
|
||||
@@ -75,7 +77,7 @@ function shiftRow(host: EditorHost, state: SideState, floorActions: FloorActions
|
||||
${floor.start_view ? html`<button class="nf-btn" title=${host.t("floor_start_view_reset")} @click=${() => host.change((_, f) => (f.start_view = null))}>↺</button>` : nothing}
|
||||
<label class="nf-check nf-wide" title=${host.t("floor_shift_all_hint")}
|
||||
><input type="checkbox" .checked=${state.shiftAll} @change=${(e: Event) => (state.shiftAll = (e.target as HTMLInputElement).checked)} />
|
||||
${host.t("floor_shift_all")}</label
|
||||
${host.doc.topology ? isOutdoorFloor(floor) ? "Gesamten Außenplan mitnehmen" : "Alle Stockwerke dieses Gebäudes mitnehmen" : host.t("floor_shift_all")}</label
|
||||
>
|
||||
</div>`;
|
||||
}
|
||||
@@ -115,7 +117,7 @@ function utilityMeters(host: EditorHost, floor: Floor): TemplateResult {
|
||||
|
||||
function floorForm(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor): TemplateResult {
|
||||
const t = host.t;
|
||||
const update = (patch: Partial<Floor>) => host.change((_, f) => Object.assign(f, patch));
|
||||
const update = (patch: Partial<Floor>) => { if(host.floor?.id===floor.id)host.change((_, f) => Object.assign(f, patch)); };
|
||||
const links = linkableHaFloors(host.doc, floor, host.hass?.floors);
|
||||
const lacking = unplacedAreas(host.doc, floor, host.hass?.areas);
|
||||
const haChoices: [string, string][] = [["", t("no_ha_floor")], ...links.map((f): [string, string] => [f.floor_id, f.name])];
|
||||
@@ -149,7 +151,7 @@ function floorForm(host: EditorHost, state: SideState, floorActions: FloorAction
|
||||
/** The "Floors" section of the side panel. */
|
||||
export function renderFloors(host: EditorHost, state: SideState, floorActions: FloorActions, floor: Floor | undefined, selectedId: string | null): TemplateResult {
|
||||
return html`<section>
|
||||
<h3>${host.t("floors")}</h3>
|
||||
${floorChips(host, state, floorActions, selectedId)} ${floor ? floorForm(host, state, floorActions, floor) : nothing}
|
||||
<h3>${host.doc.topology&&floor?`${host.t("floor")} · ${floor.name}`:host.t("floors")}</h3>
|
||||
${host.doc.topology?nothing:floorChips(host, state, floorActions, selectedId)} ${floor ? floorForm(host, state, floorActions, floor) : nothing}
|
||||
</section>`;
|
||||
}
|
||||
@@ -29,6 +29,7 @@ export function renderFreshwaterForm(host: EditorHost, item: Furniture, update:
|
||||
const patch=(p:Partial<FreshwaterStation>)=>save(stations.map((old)=>old.id===s.id?{...old,...p}:old));
|
||||
return html`<details class="nf-freshwater-station" data-station=${s.id} ?open=${i===0}><summary>K${i+1} · ${s.name||`Station ${i+1}`}</summary><div class="nf-form">
|
||||
${textField(host,"Name",s.name,(name)=>patch({name}),{wide:true,maxlength:100})}
|
||||
${ref("Status (optional)",s.status,[0,1,2,3],(status)=>patch({status}))}
|
||||
${numeric("Vorlauf",s.flow,(flow)=>patch({flow}))}${numeric("Rücklauf",s.return,(back)=>patch({return:back}))}
|
||||
${numeric("Trinkwarmwasser",s.hot_water,(hot_water)=>patch({hot_water}))}${numeric("Kaltwasser",s.cold_water,(cold_water)=>patch({cold_water}))}
|
||||
${control("Ladepumpe",s.pump,(pump)=>patch({pump}))}
|
||||
|
||||
@@ -25,6 +25,7 @@ export function renderHydronicForm(host: EditorHost, item: Furniture, update: (p
|
||||
return html`<details class="nf-hydronic-circuit" data-circuit=${c.id} ?open=${i === 0}><summary>${c.name || `Kreis ${i + 1}`}</summary><div class="nf-form">
|
||||
${textField(host, "Name", c.name, (name) => patch({ name }), { wide: true, maxlength: 100 })}
|
||||
${selectField(host, "Kreisart", c.kind, [["heating", "Heizkreis"], ["cooling", "Kühlkreis"], ["changeover", "Heizen / Kühlen"], ["pump", "Einspeise- / Vorschubpumpe (ohne Ventil)"]], (kind) => patch({ kind, ...(kind === "pump" ? { has_pump: true, has_valve: false } : {}) }), { wide: true })}
|
||||
${ref("Status (optional)", c.status, [0, 1, 2, 3], (status) => patch({ status }))}
|
||||
${c.kind !== "pump" ? html`${checkField(host, "Pumpe vorhanden", hasPump(c), (has_pump) => patch({ has_pump }))}${checkField(host, "Ventil vorhanden", hasValve(c), (has_valve) => patch({ has_valve }))}` : nothing}
|
||||
${hasPump(c) ? control("Pumpe", c.pump, (pump) => patch({ pump })) : nothing}
|
||||
${hasValve(c) ? selectField(host, "Ventilbauart", c.valve_type ?? "mixing", [["mixing", "Mischer (Dreiwegeventil)"], ["two_way", "Durchgangsventil (Zweiwege)" ]], (valve_type) => patch({ valve_type }), { wide: true }) : nothing}
|
||||
@@ -36,6 +37,7 @@ export function renderHydronicForm(host: EditorHost, item: Furniture, update: (p
|
||||
</div></details>`;
|
||||
};
|
||||
return html`<section class="nf-hydronic-form">
|
||||
<div class="nf-form">${ref("Anlagenstatus (optional)", h.status, [0, 1, 2, 3], (status) => set({ status }))}</div>
|
||||
<div class="nf-form">${checkField(host, "Schwebende 3D-Kachel", h.card !== false, (card) => set({ card }))}${pinShiftField(host, item.pin_offset, (pin_offset) => update({ pin_offset }))}${hint("Verknüpfe jeden Datenpunkt über den Objektbaum. Namen und Pfade schränken die Auswahl nicht ein. Nicht verknüpfte Werte bleiben in der 3D-Kachel ausgeblendet. Das Bauteil öffnet beim Antippen seine Werte und Bedienung.", "nf-wide")}</div>
|
||||
${item.type === "heating_manifold" ? html`${repeat(h.circuits ?? [], (c) => c.id, circuit)}<button class="nf-btn nf-hydronic-add" title="Bis zu 32 Kreise" ?disabled=${!host.admin || (h.circuits?.length ?? 0) >= 32} @click=${() => set({ circuits: [...(h.circuits ?? []), newCircuit(uid("circuit"), `Kreis ${(h.circuits?.length ?? 0) + 1}`)] })}>+ Kreis hinzufügen</button>` : nothing}
|
||||
${item.type === "buffer_tank" ? html`<div class="nf-form">${temperatures}${hint("Die sieben Startplätze liegen von oben nach unten. Höhe 100 % liegt oben, 0 % unten. Fühlerplätze können ergänzt, entfernt und frei in der Höhe positioniert werden; die Anzeige sortiert sie von oben nach unten.", "nf-wide")}</div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { html, nothing, type TemplateResult } from "lit";
|
||||
import { formatNumber, type I18nKey } from "../../../i18n.ts";
|
||||
import { bounds, cutsOut, isAxisRect, uid, type FenceGate, type FreeWall, OUTDOOR_TOP, OUTDOOR_TYPES, outdoorStanding, SLOPE_DIRS, type Direction, type OutdoorArea, type OutdoorType, type SlopeDir, type Vec2 } from "../../../model.ts";
|
||||
import { bounds, cutsOut, isAxisRect, uid, type FenceGate, type FreeWall, OUTDOOR_TOP, OUTDOOR_TYPES, outdoorStanding, outdoorTextureSettings, SLOPE_DIRS, type Direction, type OutdoorArea, type OutdoorType, type SlopeDir, type Vec2 } from "../../../model.ts";
|
||||
import { checkField, entityField, hint, numberField, selectField, toThousandths } from "../fields.ts";
|
||||
import { entityOptions } from "../entities.ts";
|
||||
import type { EditorHost } from "../host.ts";
|
||||
@@ -24,12 +24,22 @@ export function renderOutdoorForm(host: EditorHost, area: OutdoorArea, actions:
|
||||
const t = host.t;
|
||||
const set = (patch: Partial<OutdoorArea>) => actions.update(patch);
|
||||
const box = bounds(area.points);
|
||||
const texture = outdoorTextureSettings(area);
|
||||
const types = OUTDOOR_TYPES.map((type): [OutdoorType, string] => [type, t(`out_${type}` as I18nKey)]);
|
||||
const slopeDirs = SLOPE_DIRS.map((d): [SlopeDir, string] => [d, t(`slope_${d.replace("-", "n")}` as I18nKey)]);
|
||||
return html`<section>
|
||||
<div class="nf-h3row"><h3>${t("outdoor")}</h3>${actions.lockButton}</div>
|
||||
<div class="nf-form">
|
||||
${selectField(host, t("outdoor_type"), area.type, types, (type) => set({ type }), { wide: true })}
|
||||
${numberField(host, t("outdoor_texture_scale"), texture.scale * 100, (v) => {
|
||||
const { scale } = outdoorTextureSettings({ texture_scale: v / 100 });
|
||||
set({ texture_scale: scale === 1 ? null : scale });
|
||||
}, 5, 5)}
|
||||
${numberField(host, t("outdoor_texture_rotation"), texture.rotation, (v) => {
|
||||
const { rotation } = outdoorTextureSettings({ texture_rotation: v });
|
||||
set({ texture_rotation: rotation || null });
|
||||
}, 5)}
|
||||
${hint(t("outdoor_texture_hint"))}
|
||||
${selectField(host, t("area"), area.area_id ?? "", [["", t("no_area")], ...Object.values(host.hass?.areas ?? {}).sort((a, b) => a.name.localeCompare(b.name)).map((a): [string, string] => [a.area_id, a.name])], (id) => set({ area_id: id || null }), { wide: true, title: t("outdoor_area_hint") })}
|
||||
${area.type === "pool" || area.type === "wild" || area.type === "bed"
|
||||
? html`${entityField(host, t("pool_temp"), area.temp_entity ?? null, undefined, entityOptions(host.hass, (id) => id.startsWith("sensor.") && host.hass?.states[id]?.attributes.device_class === "temperature"), (v) => set({ temp_entity: v && v !== "none" ? v : null }))}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { countsAsLiving, roomArea } from "../../../geometry/living-area.ts";
|
||||
import { roomSpeaker } from "../../../live/announce.ts";
|
||||
import { isSymcon } from "../../../entities/symcon-values.ts";
|
||||
import { renderSymconRoomMeters } from "../symcon-fields.ts";
|
||||
import { floorTopologyPath } from "../../../topology.ts";
|
||||
|
||||
/** What the room form makes the editor do, and the parts of it that the editor still draws itself. */
|
||||
export interface RoomActions {
|
||||
@@ -27,6 +28,7 @@ export interface RoomActions {
|
||||
removeCorner(index: number): void;
|
||||
duplicate(): void;
|
||||
remove(): void;
|
||||
move(): void;
|
||||
rememberView(): void;
|
||||
applyPackage(pkg: PackageId): void;
|
||||
openSpots(): void;
|
||||
@@ -46,7 +48,10 @@ export function renderRoomList(host: EditorHost, floor: Floor, actions: Pick<Roo
|
||||
return html`<section>
|
||||
<h3>${host.t("rooms")}</h3>
|
||||
<div class="nf-room-list">
|
||||
${floor.rooms.map(
|
||||
${isSymcon(host.hass)?[...new Set(floor.rooms.map((r)=>r.area_id??""))].map((id)=>html`<div class="nf-room-area-group" data-area-id=${id}>
|
||||
<h4>${id?areaLeafName(host.hass,id)||host.hass?.areas?.[id]?.name||"Verknüpfter Bereich":"Ohne verknüpften Bereich"}</h4>
|
||||
${floor.rooms.filter((r)=>(r.area_id??"")===id).map((room)=>html`<button class="nf-row" @click=${()=>actions.select(room.id)}><span>${room.name}</span><span class="nf-muted">${formatArea(host.hass,polygonArea(room.points))}</span></button>`)}
|
||||
</div>`):floor.rooms.map(
|
||||
(room) => html`<button class="nf-row" @click=${() => actions.select(room.id)}>
|
||||
<span>${room.name}</span><span class="nf-muted">${formatArea(host.hass, polygonArea(room.points))}</span>
|
||||
</button>`,
|
||||
@@ -159,9 +164,12 @@ export function renderRoomForm(host: EditorHost, state: SideState, room: Room, a
|
||||
html`<button class="nf-btn" @click=${() => actions.applyPackage(pkg)}><b>${t(`pkg_${pkg}` as I18nKey)}</b><span>${t(`pkg_${pkg}_desc` as I18nKey)}</span></button>`;
|
||||
return html`<section>
|
||||
<div class="nf-h3row"><h3>${t("room")}</h3>${actions.lockButton}</div>
|
||||
${host.doc.topology&&host.floor?html`<div class="nf-room-context" title=${floorTopologyPath(host.doc,host.floor)}>${floorTopologyPath(host.doc,host.floor)}</div>`:nothing}
|
||||
${host.doc.topology?html`<button class="nf-btn nf-room-move-open" ?disabled=${!host.admin} @click=${()=>actions.move()}>Raum verschieben…</button>`:nothing}
|
||||
<div class="nf-form">
|
||||
${textField(host, t("room_name"), room.name, (v) => actions.patch({ name: v }), { wide: true })}
|
||||
${selectField(host, t("area"), room.area_id ?? "", areaChoices, (id) => actions.setArea(id), { wide: true })}
|
||||
${selectField(host, isSymcon(host.hass)?"Bereich (Symcon)":t("area"), room.area_id ?? "", areaChoices, (id) => actions.setArea(id), { wide: true })}
|
||||
${isSymcon(host.hass)?hint("Der Raum gehört zur oben gewählten Etage und damit zu deren Gebäude. Hier verknüpfst du seine Symcon-Bereichskategorie. Mehrere Räume derselben Etage können dieselbe Kategorie verwenden. Der Objektbaum und der Raumname werden dadurch nicht verändert.","nf-wide"):nothing}
|
||||
${isSymcon(host.hass) && room.area_id ? html`<button type="button" class="nf-btn nf-wide nf-take-area-name" ?disabled=${!host.admin || !areaLeafName(host.hass, room.area_id)} @click=${() => actions.patch({ name: areaLeafName(host.hass, room.area_id!) })}>Bereichsnamen übernehmen</button>` : nothing}
|
||||
${(room.sub_areas ?? []).map((a) => html`<span class="nf-chip nf-wide">${host.hass?.areas?.[a]?.name ?? a} <button class="nf-btn nf-field-btn" ?disabled=${!host.admin} title=${t("delete")} @click=${() => actions.patch({ sub_areas: (room.sub_areas ?? []).filter((x) => x !== a).length ? (room.sub_areas ?? []).filter((x) => x !== a) : null })}>✕</button></span>`)}
|
||||
${room.area_id
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { css, html, LitElement, nothing, type PropertyValues } from "lit";
|
||||
import { uid, type Building, type PlanTopology } from "../../model.ts";
|
||||
import { addTopologyOutside, enableTopology, isOutdoorFloor, outsideFloor, outsideSelection, type OutsideOwner } from "../../topology.ts";
|
||||
import { tokens } from "../../styles.ts";
|
||||
import { hint } from "./fields.ts";
|
||||
import type { EditorScope } from "./editor-context.ts";
|
||||
|
||||
/** Metadata only. Picking a row never reassigns floors or creates a storey. */
|
||||
class HierarchyManager extends LitElement {
|
||||
static properties = { doc:{attribute:false}, admin:{type:Boolean}, suggestedName:{attribute:false},
|
||||
locationId:{state:true}, branchId:{state:true}, buildingId:{state:true} };
|
||||
declare doc: Building;
|
||||
declare admin: boolean;
|
||||
declare suggestedName: string;
|
||||
private declare locationId: string;
|
||||
private declare branchId: string;
|
||||
private declare buildingId: string;
|
||||
constructor(){super();this.admin=false;this.suggestedName="Gebäude 1";this.locationId="";this.branchId="";this.buildingId="";}
|
||||
|
||||
protected willUpdate(_changed:PropertyValues){
|
||||
const t=this.doc?.topology;if(!t)return;
|
||||
if(!t.locations.some((l)=>l.id===this.locationId))this.locationId=t.locations[0]?.id??"";
|
||||
const branches=t.branches.filter((n)=>n.location_id===this.locationId);
|
||||
if(!branches.some((n)=>n.id===this.branchId))this.branchId=branches[0]?.id??"";
|
||||
const buildings=t.buildings.filter((g)=>g.branch_id===this.branchId);
|
||||
if(!buildings.some((g)=>g.id===this.buildingId))this.buildingId=buildings[0]?.id??"";
|
||||
}
|
||||
private edit(change:(b:Building,t:PlanTopology)=>void){
|
||||
if(!this.admin||!this.doc?.topology)return;
|
||||
const next=structuredClone(this.doc);change(next,next.topology!);this.publish(next);
|
||||
}
|
||||
private publish(next:Building){this.doc=next;this.dispatchEvent(new CustomEvent("hierarchy-change",{detail:{building:next},bubbles:true,composed:true}));}
|
||||
private open(scope:EditorScope){this.dispatchEvent(new CustomEvent("hierarchy-open",{detail:scope,bubbles:true,composed:true}));}
|
||||
private outsideButton(owner:OutsideOwner){
|
||||
const found=!!outsideFloor(this.doc,outsideSelection(owner));
|
||||
return html`<button class="outside outside-${owner.kind}" ?disabled=${!this.admin&&!found} @click=${()=>{
|
||||
if(!found)this.edit((b)=>{addTopologyOutside(b,owner);});
|
||||
this.open(outsideSelection(owner) as EditorScope);
|
||||
}}>🌳 ${found?"Außenplan öffnen":"Außenplan anlegen"}</button>`;
|
||||
}
|
||||
private name(label:string,value:string,save:(name:string)=>void){
|
||||
return html`<label>${label}<input maxlength="100" .value=${value} ?disabled=${!this.admin} @change=${(e:Event)=>save((e.target as HTMLInputElement).value.trim())}/></label>`;
|
||||
}
|
||||
render(){
|
||||
const t=this.doc?.topology;
|
||||
if(!t)return html`<div class="setup">${hint("Vorhandene Etagen werden einem ersten Ort, einer Niederlassung und einem Gebäude zugeordnet. Geometrie, Raumverknüpfungen und Benutzerrechte bleiben erhalten.")}
|
||||
<button class="setup-button" ?disabled=${!this.admin} @click=${()=>{const b=structuredClone(this.doc);enableTopology(b,this.suggestedName);this.publish(b);}}>Hierarchie einrichten</button></div>`;
|
||||
const l=t.locations.find((l)=>l.id===this.locationId),n=t.branches.find((n)=>n.id===this.branchId),g=t.buildings.find((g)=>g.id===this.buildingId);
|
||||
return html`<div class="help">${hint("Hier pflegst du Ort, Niederlassung und Gebäude. Die Listen wechseln nur die Auswahl. Etagen legst du anschließend oben im Editor im gewählten Gebäude an. Räume und ihre Symcon-Bereichskategorie bearbeitest du rechts auf der ausgewählten Etage.")}</div>
|
||||
<div class="columns">
|
||||
<section aria-label="Orte"><h3>Orte</h3><div class="items">${t.locations.map((s)=>html`<button class="pick" data-location=${s.id} aria-pressed=${s.id===this.locationId} @click=${()=>{this.locationId=s.id;this.branchId="";this.buildingId="";}}>${s.name}</button>`)}</div>
|
||||
<button class="add-location" ?disabled=${!this.admin} @click=${()=>{const id=uid("location");this.edit((_,p)=>p.locations.push({id,name:`Ort ${p.locations.length+1}`}));this.locationId=id;this.branchId="";this.buildingId="";}}>+ Ort</button>
|
||||
${l?html`<div class="details">${this.name("Name des Ortes",l.name,(name)=>{if(this.locationId===l.id)this.edit((_,p)=>{p.locations.find((s)=>s.id===l.id)!.name=name;});})}
|
||||
<button class="open-location primary" @click=${()=>this.open({kind:"location",id:l.id})}>Ort im Editor anzeigen</button>
|
||||
${this.outsideButton({kind:"location",id:l.id})}
|
||||
<button class="delete" ?disabled=${!this.admin||t.branches.some((s)=>s.location_id===l.id)||this.doc.floors.some((f)=>f.outdoor_location_id===l.id)} @click=${()=>this.edit((_,p)=>{p.locations=p.locations.filter((s)=>s.id!==l.id);})}>Ort entfernen</button>
|
||||
</div>`:nothing}
|
||||
</section>
|
||||
<section aria-label="Niederlassungen"><h3>Niederlassungen</h3><div class="items">${t.branches.filter((s)=>s.location_id===this.locationId).map((s)=>html`<button class="pick" data-branch=${s.id} aria-pressed=${s.id===this.branchId} @click=${()=>{this.branchId=s.id;this.buildingId="";}}>${s.name}</button>`)}</div>
|
||||
<button class="add-branch" ?disabled=${!this.admin||!l} @click=${()=>{if(!l)return;const id=uid("branch");this.edit((_,p)=>p.branches.push({id,name:`Niederlassung ${p.branches.length+1}`,location_id:l.id}));this.branchId=id;this.buildingId="";}}>+ Niederlassung</button>
|
||||
${n?html`<div class="details">${this.name("Name der Niederlassung",n.name,(name)=>{if(this.branchId===n.id)this.edit((_,p)=>{p.branches.find((s)=>s.id===n.id)!.name=name;});})}
|
||||
<label>Ort der Niederlassung<select ?disabled=${!this.admin} .value=${n.location_id} @change=${(e:Event)=>{const id=(e.target as HTMLSelectElement).value;if(this.branchId!==n.id||!t.locations.some((l)=>l.id===id))return;this.edit((_,p)=>{p.branches.find((s)=>s.id===n.id)!.location_id=id;});this.locationId=id;}}>${t.locations.map((l)=>html`<option value=${l.id} .selected=${l.id===n.location_id}>${l.name}</option>`)}</select></label>
|
||||
<button class="open-branch primary" @click=${()=>this.open({kind:"branch",id:n.id})}>Niederlassung im Editor anzeigen</button>
|
||||
${this.outsideButton({kind:"branch",id:n.id})}
|
||||
<button class="delete" ?disabled=${!this.admin||t.buildings.some((s)=>s.branch_id===n.id)||this.doc.floors.some((f)=>f.outdoor_branch_id===n.id)} @click=${()=>this.edit((_,p)=>{p.branches=p.branches.filter((s)=>s.id!==n.id);})}>Niederlassung entfernen</button>
|
||||
</div>`:nothing}
|
||||
</section>
|
||||
<section aria-label="Gebäude"><h3>Gebäude</h3><div class="items">${t.buildings.filter((s)=>s.branch_id===this.branchId).map((s)=>html`<button class="pick" data-building=${s.id} aria-pressed=${s.id===this.buildingId} @click=${()=>this.buildingId=s.id}>${s.name}<small>${this.doc.floors.filter((f)=>!isOutdoorFloor(f)&&f.building_id===s.id).length} Etagen</small></button>`)}</div>
|
||||
<button class="add-building" ?disabled=${!this.admin||!n} @click=${()=>{if(!n)return;const id=uid("building");this.edit((_,p)=>p.buildings.push({id,name:`Gebäude ${p.buildings.length+1}`,branch_id:n.id}));this.buildingId=id;}}>+ Gebäude</button>
|
||||
${g?html`<div class="details">${this.name("Name des Gebäudes",g.name,(name)=>{if(this.buildingId===g.id)this.edit((_,p)=>{p.buildings.find((s)=>s.id===g.id)!.name=name;});})}
|
||||
<label>Niederlassung des Gebäudes<select ?disabled=${!this.admin} .value=${g.branch_id} @change=${(e:Event)=>{const id=(e.target as HTMLSelectElement).value,branch=t.branches.find((s)=>s.id===id);if(this.buildingId!==g.id||!branch)return;this.edit((_,p)=>{p.buildings.find((s)=>s.id===g.id)!.branch_id=id;});this.branchId=id;this.locationId=branch.location_id;}}>${t.branches.map((s)=>html`<option value=${s.id} .selected=${s.id===g.branch_id}>${t.locations.find((l)=>l.id===s.location_id)?.name} / ${s.name}</option>`)}</select></label>
|
||||
<button class="open-building primary" @click=${()=>this.open({kind:"building",id:g.id})}>Im Editor auswählen</button>
|
||||
${this.outsideButton({kind:"building",id:g.id})}
|
||||
<button class="delete" ?disabled=${!this.admin||this.doc.floors.some((f)=>f.building_id===g.id||f.outdoor_building_id===g.id)} @click=${()=>this.edit((_,p)=>{p.buildings=p.buildings.filter((s)=>s.id!==g.id);})}>Gebäude entfernen</button>
|
||||
</div>`:nothing}
|
||||
</section>
|
||||
</div>`;
|
||||
}
|
||||
static styles=[tokens,css`
|
||||
:host{display:block;font:13px/1.4 system-ui;color:var(--nf-text)}button,input,select{box-sizing:border-box;font:inherit;color:inherit;background:var(--nf-fill,#ffffff08);border:1px solid var(--nf-line);border-radius:8px;padding:8px 10px;min-width:0}button{cursor:pointer}button:disabled,input:disabled,select:disabled{opacity:.45;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--nf-accent);outline-offset:2px}.columns{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}.help{margin-bottom:8px}section{min-width:0;border:1px solid var(--nf-line);border-radius:12px;padding:12px}h3{font-size:14px;margin:0 0 10px}.items{display:grid;align-content:start;gap:5px;min-height:100px;max-height:240px;overflow:auto;margin-bottom:10px}.pick{text-align:left;display:flex;justify-content:space-between;gap:8px;overflow-wrap:anywhere}.pick[aria-pressed=true]{border-color:var(--nf-accent);background:color-mix(in srgb,var(--nf-accent) 15%,transparent)}small{white-space:nowrap;color:var(--nf-muted)}.details{display:grid;gap:10px;margin-top:18px;padding-top:12px;border-top:1px solid var(--nf-line)}label{display:grid;gap:5px;font-size:12px;color:var(--nf-muted)}input,select{width:100%;color:var(--nf-text)}.delete{color:var(--nf-muted)}.primary{border-color:var(--nf-accent)}.setup{display:flex;gap:10px;align-items:center}@media(max-width:720px){.columns{grid-template-columns:1fr}.items{min-height:0;max-height:140px}.details{margin-top:10px}section{padding:10px}}
|
||||
`];
|
||||
}
|
||||
if(!customElements.get("nf-hierarchy-manager"))customElements.define("nf-hierarchy-manager",HierarchyManager);
|
||||
@@ -3,12 +3,15 @@
|
||||
|
||||
import { floorElevation, newFloor, uid, type Building, type Floor, type Furniture } from "../../../model.ts";
|
||||
import type { HassArea, HassFloor } from "../../../types.ts";
|
||||
import { isOutdoorFloor, outdoorOwner, topologyKey } from "../../../topology.ts";
|
||||
|
||||
/** A new floor, named after a Home Assistant floor when it comes from one, and placed at that floor's level or on top of the house. */
|
||||
export function newFloorFor(doc: Building, from: HassFloor | null, names: { first: string; next(n: number): string }): Floor {
|
||||
const count = doc.floors.length;
|
||||
export function newFloorFor(doc: Building, from: HassFloor | null, names: { first: string; next(n: number): string }, parent?: string | null): Floor {
|
||||
const building_id = doc.topology ? parent || doc.topology.buildings[0]?.id : undefined;
|
||||
const floors = doc.topology ? doc.floors.filter((f)=>!isOutdoorFloor(f)&&f.building_id===building_id) : doc.floors;
|
||||
const count = floors.length;
|
||||
const name = from?.name ?? (count === 0 ? names.first : names.next(count));
|
||||
return { ...newFloor(uid("floor"), name, floorElevation(doc.floors, from?.level)), ha_floor: from?.floor_id ?? null };
|
||||
return { ...newFloor(uid("floor"), name, floorElevation(floors, from?.level)), ha_floor: from?.floor_id ?? null, ...(building_id?{building_id}:{}) };
|
||||
}
|
||||
|
||||
/** The floors with a new one slotted in below the first floor that lies higher: floors are kept from bottom to top. */
|
||||
@@ -65,7 +68,8 @@ export interface FloorCopyOptions {
|
||||
*/
|
||||
export function copyOfFloor(doc: Building, floor: Floor, name: string, options: FloorCopyOptions, id: (prefix: string) => string = uid): Floor {
|
||||
const copy = structuredClone(floor);
|
||||
const top = doc.floors.reduce((max, f) => Math.max(max, f.elevation + f.height), floor.elevation + floor.height);
|
||||
const owner=outdoorOwner(floor);
|
||||
const top = doc.floors.filter((f)=>!doc.topology||(owner?topologyKey(outdoorOwner(f)??{kind:"all"})===topologyKey(owner):!isOutdoorFloor(f)&&f.building_id===floor.building_id)).reduce((max, f) => Math.max(max, f.elevation + f.height), floor.elevation + floor.height);
|
||||
const rooms = new Map<string, string>();
|
||||
const walls = new Map<string, string>();
|
||||
copy.id = id("floor");
|
||||
|
||||
@@ -31,6 +31,11 @@ test("a floor opening is the drawn rectangle, and an outdoor area its outline; c
|
||||
assert.equal(area.type, "lawn");
|
||||
assert.equal(area.points[2][1], 1.235);
|
||||
assert.deepEqual(copyOfOutdoorArea(area).points[0], [0.5, 0.5]);
|
||||
const textured = { ...area, texture_scale: 2.5, texture_rotation: 45 };
|
||||
const copy = copyOfOutdoorArea(textured);
|
||||
assert.equal(copy.texture_scale, 2.5);
|
||||
assert.equal(copy.texture_rotation, 45);
|
||||
assert.notEqual(copy.id, textured.id);
|
||||
});
|
||||
|
||||
test("new furniture has its type's size, and stairs reach to the floor above", () => {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { emptyBuilding, newFloor, type Placement } from "../../../model.ts";
|
||||
import { box, opening } from "../../../entities/fixtures.ts";
|
||||
import { moveRoomToFloor, roomMovePosition } from "./room-move.ts";
|
||||
|
||||
function project(){
|
||||
const b=emptyBuilding(),a={...newFloor("a","EG",0),building_id:"a"},z={...newFloor("z","OG",3),building_id:"z"};
|
||||
a.rooms=[{...box("it",0,0,5,5,"symcon-category-100"),name:"IT",climate:{temperature:"sensor.1"},start_view:{theta:1,phi:1,radius:5,target:{x:2,y:0,z:3}}},box("stay",8,0,12,5)];
|
||||
a.furniture=[{id:"f",type:"desk",variant:null,x:1,z:1,w:1,d:1,h:1,rotation:20,power:"sensor.2"},{id:"stay-f",type:"desk",variant:null,x:9,z:2,w:1,d:1,h:1,rotation:0}];
|
||||
a.placements=[{entity_id:"light.1",x:2,z:2,y:1},{entity_id:"sensor.outside",x:2,z:2,y:1,outside:true},{entity_id:"light.stay",x:9,z:2,y:1}] as Placement[];
|
||||
a.openings=[opening("door","it","door"),opening("stay-o","stay","door")];
|
||||
a.walls=[{id:"partition",a:[1,1],b:[2,1],height:2.5,thickness:0.1}];
|
||||
a.notes=[{id:"n",text:"Filter",x:3,z:3},{id:"stay-n",text:"Elsewhere",x:10,z:2}];
|
||||
z.rooms=[box("target",20,20,25,25)];b.floors=[a,z,newFloor("other","Unchanged",0)];
|
||||
b.energy.routes=[{key:"grid",points:[{floor_id:"a",x:1,z:1},{floor_id:"a",x:9,z:1}]}];return b;
|
||||
}
|
||||
test("moving a room transfers its geometry, openings, contents and links once and preserves unrelated rooms",()=>{
|
||||
const b=project(),before=structuredClone(b),pos=roomMovePosition(b.floors[1]);assert.deepEqual(pos,[26,20]);
|
||||
assert.equal(moveRoomToFloor(b,"a","it","z",pos),null);
|
||||
const [a,z]=b.floors,r=z.rooms.find((r)=>r.id==="it")!;
|
||||
assert.deepEqual(a.rooms,[before.floors[0].rooms[1]]);assert.equal(r.area_id,"symcon-category-100");assert.equal(r.climate?.temperature,"sensor.1");
|
||||
assert.deepEqual(r.points,[[26,20],[31,20],[31,25],[26,25]]);assert.deepEqual(r.start_view?.target,{x:28,y:0,z:23});
|
||||
assert.deepEqual(z.furniture,[{...before.floors[0].furniture[0],x:27,z:21}]);assert.deepEqual(a.furniture,[before.floors[0].furniture[1]]);
|
||||
assert.deepEqual(z.placements,[{...before.floors[0].placements[0],x:28,z:22}]);assert.deepEqual(a.placements,before.floors[0].placements.slice(1));
|
||||
assert.equal(z.openings[0].id,"door");assert.equal(z.openings[0].room_id,"it");assert.deepEqual(a.openings,[before.floors[0].openings[1]]);
|
||||
assert.deepEqual(z.walls?.[0].a,[27,21]);assert.equal(a.walls?.length,0);assert.deepEqual(z.notes,[{id:"n",text:"Filter",x:29,z:23}]);
|
||||
assert.deepEqual(b.energy.routes?.[0].points,[{floor_id:"z",x:27,z:21},{floor_id:"a",x:9,z:1}]);
|
||||
assert.deepEqual(b.floors[2],before.floors[2]);
|
||||
});
|
||||
test("invalid targets, duplicate devices and stale room IDs reject the entire move before any mutation",()=>{
|
||||
for(const invalid of ["same","missing","outdoor","duplicate","room","position"]){
|
||||
const b=project();if(invalid==="outdoor")b.floors[1].outdoor_branch_id="hq";
|
||||
if(invalid==="duplicate")b.floors[1].placements.push({...b.floors[0].placements[0]});
|
||||
const before=structuredClone(b);
|
||||
assert.ok(moveRoomToFloor(b,"a",invalid==="room"?"gone":"it",invalid==="same"?"a":invalid==="missing"?"gone":"z",invalid==="position"?[NaN,0]:[0,0]));assert.deepEqual(b,before);
|
||||
}
|
||||
});
|
||||
test("a shared free wall remains for its other room and only the moved opening gets a new wall host",()=>{
|
||||
const b=project(),a=b.floors[0];a.walls=[{id:"shared",a:[1,1],b:[4,1],height:2.5,thickness:0.1}];
|
||||
a.openings=[{...opening("own","it","door"),wall:"shared"},{...opening("other","stay","window"),wall:"shared"}];
|
||||
const original=structuredClone(a.walls[0]);assert.equal(moveRoomToFloor(b,"a","it","z",[26,20]),null);
|
||||
assert.deepEqual(a.walls,[original]);assert.equal(a.openings[0].wall,"shared");assert.notEqual(b.floors[1].openings[0].wall,"shared");
|
||||
assert.equal(b.floors[1].openings[0].wall,b.floors[1].walls![0].id);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { bounds, pointInPolygon, uid, type Building, type Floor, type Vec2 } from "../../../model.ts";
|
||||
import { isOutdoorFloor } from "../../../topology.ts";
|
||||
|
||||
/** Offer a free spot next to the target plan; the dialog lets the user adjust both coordinates. */
|
||||
export function roomMovePosition(target: Floor): Vec2 {
|
||||
const points=target.rooms.flatMap((r)=>r.points);
|
||||
if(!points.length)return [0,0];
|
||||
const box=bounds(points);return [box.x1+1,box.z0];
|
||||
}
|
||||
|
||||
/** Move, never copy, the room and its contents. A rejected operation leaves the document untouched. */
|
||||
export function moveRoomToFloor(b: Building, sourceId: string, roomId: string, targetId: string, position: Vec2): string | null {
|
||||
const source=b.floors.find((f)=>f.id===sourceId),target=b.floors.find((f)=>f.id===targetId);
|
||||
const room=source?.rooms.find((r)=>r.id===roomId);
|
||||
if(!source||!target||!room)return "Raum oder Zieletage ist nicht mehr vorhanden.";
|
||||
if(source===target||isOutdoorFloor(target))return "Bitte eine andere Gebäudeetage auswählen.";
|
||||
if(!position.every(Number.isFinite))return "Die Zielposition muss aus gültigen Zahlen bestehen.";
|
||||
const belongs=(x:number,z:number)=>source.rooms.find((r)=>pointInPolygon([x,z],r.points))?.id===roomId;
|
||||
const furniture=source.furniture.filter((p)=>belongs(p.x,p.z));
|
||||
const placements=source.placements.filter((p)=>!p.outside&&belongs(p.x,p.z));
|
||||
const notes=(source.notes??[]).filter((p)=>belongs(p.x,p.z));
|
||||
const openings=source.openings.filter((o)=>o.room_id===roomId);
|
||||
if(target.rooms.some((r)=>r.id===roomId)||furniture.some((p)=>target.furniture.some((q)=>q.id===p.id))||placements.some((p)=>target.placements.some((q)=>q.entity_id===p.entity_id))||openings.some((o)=>target.openings.some((q)=>q.id===o.id))||notes.some((n)=>target.notes?.some((q)=>q.id===n.id)))return "Die Zieletage enthält bereits einen Raum oder ein Gerät mit derselben Kennung.";
|
||||
|
||||
const originalPoints=room.points,box=bounds(originalPoints),dx=position[0]-box.x0,dz=position[1]-box.z0;
|
||||
const at=([x,z]:Vec2):Vec2=>[Math.round((x+dx)*1000)/1000,Math.round((z+dz)*1000)/1000];
|
||||
const shift=(p:{x:number;z:number})=>[p.x,p.z]=at([p.x,p.z]);
|
||||
const movingWalls=new Set<string>(),copiedWalls=new Map<string,string>();
|
||||
let wallConflict=false;
|
||||
const walls=(source.walls??[]).flatMap((w)=>{
|
||||
const own=openings.some((o)=>o.wall===w.id),shared=source.openings.some((o)=>o.wall===w.id&&o.room_id!==roomId);
|
||||
if(!own&&(shared||!belongs(w.a[0],w.a[1])||!belongs(w.b[0],w.b[1])))return [];
|
||||
if(shared){const id=uid("wall");copiedWalls.set(w.id,id);return [{...structuredClone(w),id}];}
|
||||
if(target.walls?.some((q)=>q.id===w.id)){wallConflict=true;return [];}
|
||||
movingWalls.add(w.id);return [w];
|
||||
});
|
||||
if(wallConflict||openings.some((o)=>o.wall&&!movingWalls.has(o.wall)&&!copiedWalls.has(o.wall)))return "Eine zugehörige Wand kann nicht eindeutig auf die Zieletage verschoben werden.";
|
||||
|
||||
source.rooms=source.rooms.filter((r)=>r!==room);target.rooms.push(room);
|
||||
const transfer=<T>(items:T[],from:T[],to:T[]):T[]=>{const set=new Set(items);to.push(...items);return from.filter((p)=>!set.has(p));};
|
||||
source.furniture=transfer(furniture,source.furniture,target.furniture);
|
||||
source.placements=transfer(placements,source.placements,target.placements);
|
||||
source.openings=transfer(openings,source.openings,target.openings);
|
||||
if(notes.length){target.notes??=[];source.notes=transfer(notes,source.notes??[],target.notes);}
|
||||
if(walls.length){source.walls=(source.walls??[]).filter((w)=>!movingWalls.has(w.id));target.walls??=[];target.walls.push(...walls);}
|
||||
room.points=room.points.map(at);
|
||||
if(room.start_view?.target)shift(room.start_view.target);
|
||||
for(const item of [...furniture,...placements,...notes])shift(item);
|
||||
for(const w of walls){w.a=at(w.a);w.b=at(w.b);}
|
||||
for(const o of openings)if(o.wall&&copiedWalls.has(o.wall))o.wall=copiedWalls.get(o.wall)!;
|
||||
for(const route of b.energy.routes??[])for(const p of route.points)if(p.floor_id===sourceId&&pointInPolygon([p.x,p.z],originalPoints)){p.floor_id=targetId;shift(p);}
|
||||
return null;
|
||||
}
|
||||
@@ -44,12 +44,14 @@ function mapHouseExtras(doc: Building, at: PointMap): void {
|
||||
export interface Scope {
|
||||
floorId: string | null;
|
||||
allFloors: boolean;
|
||||
/** Optional building/location boundary for a multi-building project. */
|
||||
floorIds?: readonly string[];
|
||||
}
|
||||
|
||||
function apply(doc: Building, scope: Scope, at: PointMap, turns: boolean): void {
|
||||
if (scope.allFloors) {
|
||||
for (const floor of doc.floors) mapFloor(floor, at, turns);
|
||||
mapHouseExtras(doc, at);
|
||||
for (const floor of doc.floors) if (!scope.floorIds || scope.floorIds.includes(floor.id)) mapFloor(floor, at, turns);
|
||||
if (!scope.floorIds || doc.floors.every((f)=>scope.floorIds!.includes(f.id))) mapHouseExtras(doc, at);
|
||||
} else {
|
||||
const floor = doc.floors.find((f) => f.id === scope.floorId);
|
||||
if (floor) mapFloor(floor, at, turns);
|
||||
@@ -63,7 +65,7 @@ export function translate(doc: Building, scope: Scope, dx: number, dz: number):
|
||||
|
||||
/** The middle of the box around the rooms of the scope, or null when there are none. */
|
||||
export function pivotOf(doc: Building, scope: Scope): Vec2 | null {
|
||||
const floors = scope.allFloors ? doc.floors : doc.floors.filter((f) => f.id === scope.floorId);
|
||||
const floors = scope.allFloors ? doc.floors.filter((f)=>!scope.floorIds||scope.floorIds.includes(f.id)) : doc.floors.filter((f) => f.id === scope.floorId);
|
||||
const points = floors.flatMap((f) => f.rooms.flatMap((r) => r.points));
|
||||
if (points.length === 0) return null;
|
||||
const [xs, zs] = [points.map((p) => p[0]), points.map((p) => p[1])];
|
||||
|
||||
@@ -2,6 +2,17 @@ import { css } from "lit";
|
||||
|
||||
/** The editor's own styles: the plan canvas, the side panel with its forms and libraries, the 3D pane and the phone layout. */
|
||||
export const editorStyles = css`
|
||||
.nf-scope-overview [data-overview-floor]{cursor:pointer}.nf-scope-overview polygon{fill:#03a9f41a;stroke:#03a9f4;stroke-width:1.5}.nf-scope-overview [data-overview-floor]:hover polygon,.nf-scope-overview [data-overview-floor]:focus polygon{fill:#03a9f44d}.nf-scope-overview text{fill:var(--nf-text);font-size:11px;text-anchor:middle;pointer-events:none}.nf-room-move-open{width:100%;margin-bottom:12px}.nf-room-move-error{color:var(--nf-warm)}
|
||||
.nf-editor-context{display:grid;gap:8px;padding:10px 12px;border-bottom:1px solid var(--nf-line)}
|
||||
.nf-editor-building-row,.nf-editor-floor-nav{display:flex;gap:8px;align-items:center;flex-wrap:wrap;min-width:0}
|
||||
.nf-editor-building-row>label{display:flex;gap:8px;align-items:center;font-size:12px;min-width:0;flex:1}
|
||||
.nf-editor-building-select{font:inherit;color:var(--nf-text);background:var(--nf-chrome-solid);border:1px solid var(--nf-line);border-radius:8px;padding:7px 10px;min-width:0;width:min(100%,480px)}
|
||||
.nf-editor-floor-nav{font-size:12px}.nf-editor-floor-nav .nf-editor-move-floor{margin-left:auto;font-size:11px}
|
||||
.nf-hierarchy-dialog,.nf-floor-move-dialog,.nf-room-move-dialog{box-sizing:border-box;width:min(1050px,calc(100vw - 24px));max-height:calc(100dvh - 24px);overflow:auto;padding:18px;border:1px solid var(--nf-line);border-radius:14px;color:var(--nf-text);background:var(--nf-chrome-solid,#1c1c1c);box-shadow:0 20px 70px #0008;font:13px/1.4 system-ui}
|
||||
.nf-hierarchy-dialog::backdrop,.nf-floor-move-dialog::backdrop,.nf-room-move-dialog::backdrop{background:#050b16a6;backdrop-filter:blur(3px)}
|
||||
.nf-hierarchy-dialog>header,.nf-floor-move-dialog>header,.nf-room-move-dialog>header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:16px}.nf-hierarchy-dialog h2,.nf-floor-move-dialog h2,.nf-room-move-dialog h2{font-size:17px;margin:0}
|
||||
.nf-floor-move-dialog,.nf-room-move-dialog{width:min(650px,calc(100vw - 24px))}.nf-floor-move-source,.nf-room-move-dialog p{overflow-wrap:anywhere}.nf-floor-move-dialog>.nf-btn,.nf-room-move-dialog>.nf-btn{margin-top:16px}
|
||||
.nf-room-area-group h4{font-size:11px;color:var(--nf-muted);margin:12px 0 4px}.nf-room-context{font-size:11px;color:var(--nf-muted);margin:4px 0 12px;overflow-wrap:anywhere}
|
||||
.nf-value-links h4 { margin: 12px 0; }
|
||||
.nf-value-add { min-width: 30px; font-size: 18px; padding: 3px 8px; }
|
||||
.nf-value-link { padding: 8px 0; border-bottom: 1px solid var(--nf-line); }
|
||||
@@ -981,6 +992,15 @@ export const editorStyles = css`
|
||||
fill: rgba(184, 163, 130, 0.24);
|
||||
stroke: rgba(184, 163, 130, 0.65);
|
||||
}
|
||||
.nf-out-pavers polygon,
|
||||
.nf-out-natural_stone polygon {
|
||||
fill: rgba(170, 160, 135, 0.22);
|
||||
stroke: rgba(170, 160, 135, 0.6);
|
||||
}
|
||||
.nf-out-stepping_stones polygon {
|
||||
fill: rgba(130, 170, 110, 0.18);
|
||||
stroke: rgba(160, 190, 140, 0.55);
|
||||
}
|
||||
.nf-free-wall {
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@ function stationRows(hass:HomeAssistant,station:FreshwaterStation):HydronicReadi
|
||||
}
|
||||
const stationName=(station:FreshwaterStation,i:number)=>`K${i+1} · ${station.name||`Station ${i+1}`}`;
|
||||
const rowTemplate = (hass: HomeAssistant, row: HydronicReading) => html`<div class="reading" data-source=${row.id}><span>${row.icon?.startsWith("mdi:") ? html`<ha-icon icon=${row.icon}></ha-icon>` : row.icon || nothing} ${row.label}</span><b>${row.text}${trendButton(hass, [row.id], row.label)}</b></div>`;
|
||||
const statusRow = (hass: HomeAssistant, id?: string | null, label = "Status") => {
|
||||
const row = hydronicReading(hass, label, id);
|
||||
return row ? html`<div class="reading status-reading" data-source=${row.id}><span>${label}</span><b><span class="status-text" title=${row.text}>${row.text}</span>${trendButton(hass, [row.id], label)}</b></div>` : nothing;
|
||||
};
|
||||
function controlRow(hass: HomeAssistant, label: string, binding?: HydronicControl) {
|
||||
const state = readControl(hass, binding);
|
||||
return state.id ? html`<div class="reading" data-source=${state.id}><span>${label}<small>${state.feedback ? "Ist" : "Soll"}</small></span><b><i class="lamp" style=${`background:${state.running === null ? "#888" : state.running ? "#6fe1a2" : "#465361"}`}></i>${nativeText(hass.states[state.id])}${trendButton(hass, [state.id], label)}</b></div>` : nothing;
|
||||
@@ -40,6 +44,7 @@ const styles = css`
|
||||
:host{display:block;color:var(--nf-text);font:12px/1.4 system-ui,sans-serif;min-width:170px;max-width:300px}
|
||||
button{font:inherit;color:inherit;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:7px;padding:5px 8px;cursor:pointer}button:disabled,input:disabled{opacity:.45;cursor:default}button:focus-visible,input:focus-visible{outline:2px solid var(--nf-accent);outline-offset:2px}
|
||||
.title{display:block;width:100%;padding:0 0 5px;border:0;background:none;font-weight:600;text-align:left;white-space:normal}.content{max-height:250px;overflow:auto;overscroll-behavior:contain}.circuit{border-top:1px solid var(--nf-line);padding:5px 0}.circuit-name{font-size:11px;font-weight:600;margin-bottom:3px}.reading{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;min-height:22px}.reading>span{color:var(--nf-muted);white-space:normal}.reading b{display:flex;align-items:center;justify-content:flex-end;white-space:nowrap;font-variant-numeric:tabular-nums;font-weight:500}.reading small{font-size:9px;margin-left:5px;opacity:.75}.delta{font-size:10px}.lamp{display:inline-block;flex:none;width:6px;height:6px;border-radius:50%;margin-right:5px}.empty{color:var(--nf-muted);font-size:11px;white-space:normal;margin:5px 0}nf-trend-button{margin-left:3px}
|
||||
.status-reading{grid-template-columns:auto minmax(0,1fr)}.status-reading b{min-width:0}.status-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.circuit-name small,h3 small{font-size:10px;color:var(--nf-muted);font-weight:normal;margin-left:5px}
|
||||
ha-icon{--mdc-icon-size:13px;width:13px;height:13px;vertical-align:middle}
|
||||
dialog{box-sizing:border-box;width:min(620px,calc(100vw - 24px));max-width:none;max-height:calc(100dvh - 24px);padding:0;color:var(--nf-text);background:var(--nf-chrome-solid,#1c1c1c);border:1px solid var(--nf-line);border-radius:14px;box-shadow:0 20px 70px #0008;font:13px/1.4 system-ui,sans-serif}dialog::backdrop{background:#050b16a6;backdrop-filter:blur(3px)}header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 18px;border-bottom:1px solid var(--nf-line)}h2{font-size:17px;margin:0}.body{padding:12px 18px;max-height:calc(100dvh - 120px);overflow:auto;overscroll-behavior:contain}h3{font-size:13px;margin:12px 0 7px}fieldset{min-width:0;margin:8px 0;padding:10px;border:1px solid var(--nf-line);border-radius:9px}legend{font-size:12px;color:var(--nf-muted)}.command{display:flex;align-items:center;gap:12px;margin-top:8px}.command input[type=range]{flex:1;min-width:0;accent-color:var(--nf-accent)}.command input[type=number]{width:90px;box-sizing:border-box;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:6px;color:inherit;padding:5px}.command output{font-variant-numeric:tabular-nums;min-width:45px;text-align:right}.error{color:#ff9b9b}.readonly{color:var(--nf-muted);font-size:11px;margin:4px 0}.body .reading{padding:4px 0}.body .circuit{padding-bottom:12px}
|
||||
@@ -51,14 +56,14 @@ class HydronicCard extends LitElement {
|
||||
render() {
|
||||
if (!this.hass || !this.item) return nothing;
|
||||
const h = hydronicConfig(this.item), rows = rootRows(this.hass, this.item),stations=this.item.type==="freshwater_station"?freshwaterStations(this.item):[];
|
||||
return html`<button class="title" @click=${() => openHydronic(this.hass, this.item, this.readOnly)} aria-haspopup="dialog">${nameOf(this.item)} ⚙</button><div class="content">
|
||||
${this.item.type === "heating_manifold" ? (h.circuits ?? []).map((c) => html`<section class="circuit"><div class="circuit-name">${titleOf(c)} <small>${modeOf(this.hass, c)}</small></div>${hasPump(c) ? controlRow(this.hass, "Pumpe", c.pump) : nothing}${hasValve(c) ? controlRow(this.hass, "Ventil", c.valve) : nothing}${parts(this.hass, c.flow, c.return).map((r) => rowTemplate(this.hass, r))}${hydronicReading(this.hass, "Leistung", c.power) ? rowTemplate(this.hass, hydronicReading(this.hass, "Leistung", c.power)!) : nothing}</section>`) : nothing}
|
||||
${stations.length>1?html`<small class="cascade-count">Kaskade · ${stations.length} Stationen</small>${stations.map((s,i)=>{const pump=readControl(this.hass,s.pump),row=hydronicReading(this.hass,"Trinkwarmwasser",s.hot_water)||hydronicReading(this.hass,"Vorlauf",s.flow);return html`<div class="station-summary" data-station=${s.id}><button class="station-name" @click=${()=>openHydronic(this.hass,this.item,this.readOnly,s.id)}><i class="lamp" title=${`Pumpe: ${pump.id?nativeText(this.hass.states[pump.id]):"–"}`} style=${`background:${pump.running===null?"#888":pump.running?"#6fe1a2":"#a82638"}`}></i>${stationName(s,i)}</button><b>${row?.text||"–"}</b>${row?trendButton(this.hass,[row.id],`${stationName(s,i)} · ${row.label}`):nothing}</div>`;})}`:stations.map((s)=>html`<section class="circuit">${stationRows(this.hass,s).map((r)=>rowTemplate(this.hass,r))}${controlRow(this.hass,"Ladepumpe",s.pump)}${stationHasValve(s)?controlRow(this.hass,"Kaskadenventil",s.valve):nothing}</section>`)}
|
||||
return html`<button class="title" @click=${() => openHydronic(this.hass, this.item, this.readOnly)} aria-haspopup="dialog">${nameOf(this.item)} ⚙</button><div class="content">${statusRow(this.hass,h.status,"Anlagenstatus")}
|
||||
${this.item.type === "heating_manifold" ? (h.circuits ?? []).map((c) => html`<section class="circuit"><div class="circuit-name">${titleOf(c)} <small>${modeOf(this.hass, c)}</small></div>${statusRow(this.hass,c.status)}${hasPump(c) ? controlRow(this.hass, "Pumpe", c.pump) : nothing}${hasValve(c) ? controlRow(this.hass, "Ventil", c.valve) : nothing}${parts(this.hass, c.flow, c.return).map((r) => rowTemplate(this.hass, r))}${hydronicReading(this.hass, "Leistung", c.power) ? rowTemplate(this.hass, hydronicReading(this.hass, "Leistung", c.power)!) : nothing}</section>`) : nothing}
|
||||
${stations.length>1?html`<small class="cascade-count">Kaskade · ${stations.length} Stationen</small>${stations.map((s,i)=>{const pump=readControl(this.hass,s.pump),row=hydronicReading(this.hass,"Trinkwarmwasser",s.hot_water)||hydronicReading(this.hass,"Vorlauf",s.flow);return html`<div class="station-summary" data-station=${s.id}><button class="station-name" @click=${()=>openHydronic(this.hass,this.item,this.readOnly,s.id)}><i class="lamp" title=${`Pumpe: ${pump.id?nativeText(this.hass.states[pump.id]):"–"}`} style=${`background:${pump.running===null?"#888":pump.running?"#6fe1a2":"#a82638"}`}></i>${stationName(s,i)}</button><b>${row?.text||"–"}</b>${row?trendButton(this.hass,[row.id],`${stationName(s,i)} · ${row.label}`):nothing}${statusRow(this.hass,s.status)}</div>`;})}`:stations.map((s)=>html`<section class="circuit">${statusRow(this.hass,s.status)}${stationRows(this.hass,s).map((r)=>rowTemplate(this.hass,r))}${controlRow(this.hass,"Ladepumpe",s.pump)}${stationHasValve(s)?controlRow(this.hass,"Kaskadenventil",s.valve):nothing}</section>`)}
|
||||
${rows.map((r) => rowTemplate(this.hass, r))}${this.item.type === "freshwater_station" ? controlRow(this.hass, "Zirkulationspumpe", h.circulation) : nothing}
|
||||
${this.item.type !== "heating_manifold" && this.item.type!=="freshwater_station" && !rows.length ? html`<p class="empty">Noch keine Fühler verknüpft</p>` : nothing}
|
||||
${this.item.type !== "heating_manifold" && this.item.type!=="freshwater_station" && !rows.length && !realRef(h.status) ? html`<p class="empty">Noch keine Fühler verknüpft</p>` : nothing}
|
||||
</div>`;
|
||||
}
|
||||
static styles = [tokens, styles,css`.cascade-count{color:var(--nf-muted)}.station-summary{display:grid;grid-template-columns:minmax(0,1fr) auto 18px;align-items:center;gap:6px;width:100%;padding:5px 0;font-size:11px}.station-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0;background:none;border:0;text-align:left}.station-summary b{white-space:nowrap;font-variant-numeric:tabular-nums}`];
|
||||
static styles = [tokens, styles,css`.cascade-count{color:var(--nf-muted)}.station-summary{display:grid;grid-template-columns:minmax(0,1fr) auto 18px;align-items:center;gap:6px;width:100%;padding:5px 0;font-size:11px}.station-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0;background:none;border:0;text-align:left}.station-summary>.status-reading{grid-column:1/-1}.station-summary b{white-space:nowrap;font-variant-numeric:tabular-nums}`];
|
||||
}
|
||||
|
||||
class HydronicDialog extends LitElement {
|
||||
@@ -93,12 +98,12 @@ class HydronicDialog extends LitElement {
|
||||
render() {
|
||||
if (!this.hass || !this.item) return nothing;
|
||||
const h = hydronicConfig(this.item), rows = rootRows(this.hass, this.item),stations=this.item.type==="freshwater_station"?freshwaterStations(this.item):[];
|
||||
return html`<dialog @close=${() => { this.remove(); if (activeDialog === this) activeDialog = null; }} @keydown=${(e: Event) => e.stopPropagation()}><header><h2>${nameOf(this.item)}</h2><button aria-label="Schließen" @click=${() => this.shadowRoot!.querySelector("dialog")!.close()}>×</button></header><div class="body">
|
||||
${this.item.type === "heating_manifold" ? (h.circuits ?? []).map((c) => html`<section class="circuit" data-circuit=${c.id}><h3>${titleOf(c)} <small>${modeOf(this.hass, c)}</small></h3>${hasPump(c) ? this.control("Pumpe", c.pump) : nothing}${hasValve(c) ? this.control("Ventil", c.valve) : nothing}${parts(this.hass, c.flow, c.return).map((r) => rowTemplate(this.hass, r))}${delta(this.hass, c.flow, c.return)}${hydronicReading(this.hass, "Pumpenleistung", c.power) ? rowTemplate(this.hass, hydronicReading(this.hass, "Pumpenleistung", c.power)!) : nothing}</section>`) : nothing}
|
||||
${stations.map((s,i)=>html`<details class="freshwater-unit" data-station=${s.id} ?open=${i===0||this.focusStation===s.id}><summary>${stationName(s,i)}</summary>${stationRows(this.hass,s).map((r)=>rowTemplate(this.hass,r))}${delta(this.hass,s.flow,s.return)}${this.control("Ladepumpe",s.pump)}${stationHasValve(s)?this.control("Kaskadenventil",s.valve):nothing}</details>`)}
|
||||
return html`<dialog @close=${() => { this.remove(); if (activeDialog === this) activeDialog = null; }} @keydown=${(e: Event) => e.stopPropagation()}><header><h2>${nameOf(this.item)}</h2><button aria-label="Schließen" @click=${() => this.shadowRoot!.querySelector("dialog")!.close()}>×</button></header><div class="body">${statusRow(this.hass,h.status,"Anlagenstatus")}
|
||||
${this.item.type === "heating_manifold" ? (h.circuits ?? []).map((c) => html`<section class="circuit" data-circuit=${c.id}><h3>${titleOf(c)} <small>${modeOf(this.hass, c)}</small></h3>${statusRow(this.hass,c.status)}${hasPump(c) ? this.control("Pumpe", c.pump) : nothing}${hasValve(c) ? this.control("Ventil", c.valve) : nothing}${parts(this.hass, c.flow, c.return).map((r) => rowTemplate(this.hass, r))}${delta(this.hass, c.flow, c.return)}${hydronicReading(this.hass, "Pumpenleistung", c.power) ? rowTemplate(this.hass, hydronicReading(this.hass, "Pumpenleistung", c.power)!) : nothing}</section>`) : nothing}
|
||||
${stations.map((s,i)=>html`<details class="freshwater-unit" data-station=${s.id} ?open=${i===0||this.focusStation===s.id}><summary>${stationName(s,i)}</summary>${statusRow(this.hass,s.status)}${stationRows(this.hass,s).map((r)=>rowTemplate(this.hass,r))}${delta(this.hass,s.flow,s.return)}${this.control("Ladepumpe",s.pump)}${stationHasValve(s)?this.control("Kaskadenventil",s.valve):nothing}</details>`)}
|
||||
${rows.map((r) => rowTemplate(this.hass, r))}${this.item.type === "buffer_tank" ? delta(this.hass, h.flow, h.return) : nothing}
|
||||
${this.item.type === "freshwater_station" ? this.control("Zirkulationspumpe", h.circulation) : nothing}
|
||||
${!rows.length && this.item.type !== "heating_manifold" && this.item.type!=="freshwater_station" ? html`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>` : nothing}
|
||||
${!rows.length && !realRef(h.status) && this.item.type !== "heating_manifold" && this.item.type!=="freshwater_station" ? html`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>` : nothing}
|
||||
${this.error ? html`<p class="error" role="alert">${this.error}</p>` : nothing}
|
||||
</div></dialog>`;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// up/stop/down for blinds, on/off for switches, with a slider and a way to the full details.
|
||||
|
||||
import { css, html, LitElement, nothing } from "lit";
|
||||
import { canControl } from "../access.ts";
|
||||
import { assumedCover, type CarState, entityName, isUnavailable, kindOf } from "../devices.ts";
|
||||
import { translate, type I18nKey } from "../i18n.ts";
|
||||
import { openMoreInfo, stateText } from "../markers.ts";
|
||||
@@ -73,6 +74,7 @@ export class NfQuickMenu extends LitElement {
|
||||
}
|
||||
|
||||
private call(domain: string, service: string, data: Record<string, unknown> = {}): void {
|
||||
if (!canControl(this.hass, this.entity)) return;
|
||||
void this.hass.callService(domain, service, { entity_id: this.entity, ...data });
|
||||
}
|
||||
|
||||
@@ -262,7 +264,7 @@ export class NfQuickMenu extends LitElement {
|
||||
if (!st) return nothing;
|
||||
const kind = kindOf(this.entity);
|
||||
// a cover without feedback (a garage remote) stays unknown, but its buttons still work
|
||||
const body = isUnavailable(st) && !assumedCover(st)
|
||||
const body = !canControl(this.hass, this.entity) || (isUnavailable(st) && !assumedCover(st))
|
||||
? html`<p class="qm-note">${stateText(this.hass, st)}</p>`
|
||||
: kind === "light"
|
||||
? this.renderLight(st)
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ROOM_HVAC_FIELDS } from "../entities/room-hvac.ts";
|
||||
import { nativeBool, nativeNumber, nativeText, nativeValue } from "../entities/symcon-values.ts";
|
||||
import { controls, tokens } from "../styles.ts";
|
||||
import { trendButton } from "./trend-button.ts";
|
||||
import { canControl } from "../access.ts";
|
||||
|
||||
interface SchedulePoint { hour: number; minute: number; second: number; action: number }
|
||||
interface ScheduleGroup { id: number; days: number; points: SchedulePoint[] }
|
||||
@@ -20,6 +21,7 @@ export class NfRoomHvac extends LitElement {
|
||||
constructor() { super(); this._pending = new Set(); this._error = ""; }
|
||||
|
||||
private async send(id: string, domain: string, service: string, data: Record<string, unknown>) {
|
||||
if (!canControl(this.hass, id)) return;
|
||||
this._pending = new Set([...this._pending, id]);
|
||||
this._error = "";
|
||||
try { await this.hass.callService(domain, service, { entity_id: id, ...data }); }
|
||||
@@ -47,7 +49,7 @@ export class NfRoomHvac extends LitElement {
|
||||
const days = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"];
|
||||
const time = (p: SchedulePoint) => `${String(p.hour).padStart(2, "0")}:${String(p.minute).padStart(2, "0")}${p.second ? `:${String(p.second).padStart(2, "0")}` : ""}`;
|
||||
return html`<details class="schedule"><summary>${String(st.attributes.friendly_name ?? "Schaltuhr")}</summary>
|
||||
<label class="nf-check"><input type="checkbox" .checked=${st.state === "on"} ?disabled=${this._pending.has(id)} @change=${(e: Event) => void this.send(id, "schedule", "set_active", { active: (e.target as HTMLInputElement).checked })} /> Aktiv</label>
|
||||
<label class="nf-check"><input type="checkbox" .checked=${st.state === "on"} ?disabled=${this._pending.has(id) || !canControl(this.hass, id)} @change=${(e: Event) => void this.send(id, "schedule", "set_active", { active: (e.target as HTMLInputElement).checked })} /> Aktiv</label>
|
||||
${next > 0 ? html`<p class="next">Nächster Schaltpunkt: ${new Date(next * 1000).toLocaleString(this.hass.language)}${nextAction ? ` · ${nextAction.name}` : ""}</p>` : nothing}
|
||||
${groups.length ? groups.map((group) => html`<div class="schedule-group"><b>${days.filter((_, i) => group.days & (1 << i)).join(" · ")}</b><div class="points">
|
||||
${[...group.points].sort((a, b) => a.hour * 3600 + a.minute * 60 + a.second - (b.hour * 3600 + b.minute * 60 + b.second)).map((point) => {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// scenes and scripts). Shown next to the 3D view when a room is selected.
|
||||
|
||||
import { css, html, LitElement, nothing, svg, type TemplateResult } from "lit";
|
||||
import { canControl } from "../access.ts";
|
||||
import { assumedCover, entityName, groupByDevice, groupCovers, isActive, isUnavailable, kindOf, roomClimateSensors, roomClimateValue, roomPanelEntities, fromCelsius, tempUnit, type DeviceKind, roomEntities } from "../devices.ts";
|
||||
import { formatNumber, translate, type I18nKey } from "../i18n.ts";
|
||||
import { iconPath } from "../icons.ts";
|
||||
@@ -239,7 +240,7 @@ export class NfRoomPanel extends LitElement {
|
||||
if (!quietSince || minutes < EMPTY_MINUTES) return nothing;
|
||||
return html`<div class="nf-rp-shade">
|
||||
<span>💡 ${this.t("empty_lights_hint", { n: lightsOn.length, min: minutes })}</span>
|
||||
<button class="nf-btn nf-rp-small" @click=${() => this.call("light", "turn_off", { entity_id: lightsOn.map((l) => l.entity_id) })}>${this.t("empty_lights_off")}</button>
|
||||
<button class="nf-btn nf-rp-small" ?disabled=${!lightsOn.some((l) => canControl(this.hass, l.entity_id))} @click=${() => this.call("light", "turn_off", { entity_id: lightsOn.filter((l) => canControl(this.hass, l.entity_id)).map((l) => l.entity_id) })}>${this.t("empty_lights_off")}</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -254,6 +255,7 @@ export class NfRoomPanel extends LitElement {
|
||||
if (!open.length) return nothing;
|
||||
const down = () => {
|
||||
for (const c of heating) {
|
||||
if (!canControl(this.hass, c.entity_id)) continue;
|
||||
const modes = (c.attributes.hvac_modes as string[] | undefined) ?? [];
|
||||
if (modes.includes("off")) this.call("climate", "set_hvac_mode", { entity_id: c.entity_id, hvac_mode: "off" });
|
||||
else if (typeof c.attributes.min_temp === "number") this.call("climate", "set_temperature", { entity_id: c.entity_id, temperature: c.attributes.min_temp });
|
||||
@@ -261,7 +263,7 @@ export class NfRoomPanel extends LitElement {
|
||||
};
|
||||
return html`<div class="nf-rp-shade nf-rp-open-heat">
|
||||
<span>🪟 ${this.t("open_heating_hint", { n: open.length })}</span>
|
||||
<button class="nf-btn nf-rp-small" @click=${down}>${this.t("open_heating_off")}</button>
|
||||
<button class="nf-btn nf-rp-small" ?disabled=${!heating.some((c) => canControl(this.hass, c.entity_id))} @click=${down}>${this.t("open_heating_off")}</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -281,7 +283,7 @@ export class NfRoomPanel extends LitElement {
|
||||
const pos = st.attributes.current_position;
|
||||
return typeof pos === "number" ? pos > 30 : st.state === "open";
|
||||
};
|
||||
const covers = [...new Set(sunnyWindowsNow(this.building, this.floor, room, { latitude, longitude }).flatMap((o) => [o.cover, o.cover2].filter(open)))];
|
||||
const covers = [...new Set(sunnyWindowsNow(this.building, this.floor, room, { latitude, longitude }).flatMap((o) => [o.cover, o.cover2].filter(open)))].filter((id) => canControl(this.hass, id));
|
||||
if (!covers.length) return nothing;
|
||||
return html`<div class="nf-rp-shade">
|
||||
<span>☀ ${this.t("shade_hint", { n: covers.length, temp: `${formatNumber(this.hass, fromCelsius(this.hass, temp), 1)} ${tempUnit(this.hass)}` })}</span>
|
||||
@@ -366,6 +368,8 @@ export class NfRoomPanel extends LitElement {
|
||||
}
|
||||
|
||||
private call(domain: string, service: string, data: Record<string, unknown>): void {
|
||||
const ids = Array.isArray(data.entity_id) ? data.entity_id : [data.entity_id];
|
||||
if (ids.some((id) => typeof id !== "string" || !canControl(this.hass, id))) return;
|
||||
void this.hass.callService(domain, service, data);
|
||||
}
|
||||
|
||||
@@ -373,7 +377,7 @@ export class NfRoomPanel extends LitElement {
|
||||
private renderClean(room: Room) {
|
||||
const id = room.clean_entity;
|
||||
const st = id ? this.hass.states[id] : undefined;
|
||||
if (!id || !st) return nothing;
|
||||
if (!id || !st || !canControl(this.hass, id)) return nothing;
|
||||
const domain = id.slice(0, id.indexOf("."));
|
||||
const run = () => (domain === "script" ? this.call("script", "turn_on", { entity_id: id }) : this.call(domain, "press", { entity_id: id }));
|
||||
return html`<div class="nf-rp-alloff"><button class="nf-btn nf-rp-small" ?disabled=${isUnavailable(st)} title=${this.t("room_clean_run_hint")} @click=${run}>🧹 ${this.t("room_clean_run")}</button></div>`;
|
||||
@@ -381,7 +385,7 @@ export class NfRoomPanel extends LitElement {
|
||||
|
||||
/** Switches off what is on in the room and offers to undo it for ten seconds. */
|
||||
private allOff(states: HassEntity[]): void {
|
||||
const plan = allOffPlan(states);
|
||||
const plan = allOffPlan(states.filter((st) => canControl(this.hass, st.entity_id)));
|
||||
for (const c of plan.off) this.call(c.domain, c.service, c.data);
|
||||
this._undo = plan.undo;
|
||||
clearTimeout(this.undoTimer);
|
||||
@@ -397,7 +401,7 @@ export class NfRoomPanel extends LitElement {
|
||||
/** "Everything off" while something is on, and its undo right after. */
|
||||
private renderAllOff(states: HassEntity[]): TemplateResult | typeof nothing {
|
||||
if (this._undo) return html`<div class="nf-rp-alloff"><span>${this.t("all_off_done")}</span><button class="nf-btn nf-rp-small" @click=${() => this.undoAllOff()}>↶ ${this.t("all_off_undo")}</button></div>`;
|
||||
const { count } = allOffPlan(states);
|
||||
const { count } = allOffPlan(states.filter((st) => canControl(this.hass, st.entity_id)));
|
||||
if (count < 2) return nothing;
|
||||
return html`<div class="nf-rp-alloff"><button class="nf-btn nf-rp-small" title=${this.t("all_off_hint")} @click=${() => this.allOff(states)}>⏻ ${this.t("all_off_n", { n: count })}</button></div>`;
|
||||
}
|
||||
@@ -435,7 +439,7 @@ export class NfRoomPanel extends LitElement {
|
||||
role="switch"
|
||||
aria-checked=${on ? "true" : "false"}
|
||||
aria-label=${this.name(st.entity_id)}
|
||||
?disabled=${isUnavailable(st)}
|
||||
?disabled=${isUnavailable(st) || !canControl(this.hass, st.entity_id)}
|
||||
@click=${guarded}
|
||||
></button>`;
|
||||
}
|
||||
@@ -470,7 +474,7 @@ export class NfRoomPanel extends LitElement {
|
||||
const switches = by(["switch", "fan", "lock"]);
|
||||
const sensors = by(["sensor", "binary"]);
|
||||
const scenes = by(["scene", "script"]);
|
||||
const facts = this.facts(climates);
|
||||
const facts = room.symcon_read_room === false ? [] : this.facts(climates);
|
||||
const lightsOn = lights.filter((l) => l.state === "on");
|
||||
return html`<section class="nf-rp" aria-label=${room.name}>
|
||||
<header class="nf-rp-head">
|
||||
@@ -491,7 +495,9 @@ export class NfRoomPanel extends LitElement {
|
||||
<nf-utility-report .hass=${this.hass} .readings=${roomUtilityReadings(this.hass, room, this.building?.floors.flatMap((f) => f.rooms))}></nf-utility-report>
|
||||
${this.renderAllOff([...lights, ...media, ...switches])}
|
||||
${this.renderClean(room)}
|
||||
${!room.area_id && !outside && !(isSymcon(this.hass) && hvacRefs.length)
|
||||
${room.symcon_read_room === false
|
||||
? html`<p class="nf-rp-note">${this.t(ids.length ? "access_room_devices" : "access_room_geometry")}</p>`
|
||||
: !room.area_id && !outside && !(isSymcon(this.hass) && hvacRefs.length)
|
||||
? html`<p class="nf-rp-note">${this.t("panel_no_area")}</p>`
|
||||
: !ids.length && !(isSymcon(this.hass) && hvacRefs.length)
|
||||
? html`<p class="nf-rp-note">${this.t("panel_empty")}</p>`
|
||||
@@ -517,13 +523,13 @@ export class NfRoomPanel extends LitElement {
|
||||
${lights.length
|
||||
? this.section(
|
||||
"panel_lights",
|
||||
[...lights.map((st) => this.lightRow(st)), ...(room ? [this.renderMoods(room, lights)] : [])],
|
||||
html`${lightsOn.length < lights.length
|
||||
? html`<button class="nf-btn nf-rp-small" @click=${() => this.call("light", "turn_on", { entity_id: lights.filter((l) => !isUnavailable(l)).map((l) => l.entity_id) })}>
|
||||
[...lights.map((st) => canControl(this.hass, st.entity_id) ? this.lightRow(st) : this.sensorRow(st)), ...(room && lights.some((st) => canControl(this.hass, st.entity_id)) ? [this.renderMoods(room, lights)] : [])],
|
||||
html`${lights.some((l) => l.state !== "on" && canControl(this.hass, l.entity_id))
|
||||
? html`<button class="nf-btn nf-rp-small" ?disabled=${!lights.some((l) => canControl(this.hass, l.entity_id))} @click=${() => this.call("light", "turn_on", { entity_id: lights.filter((l) => !isUnavailable(l) && canControl(this.hass, l.entity_id)).map((l) => l.entity_id) })}>
|
||||
${this.t("panel_all_on")}
|
||||
</button>`
|
||||
: nothing}${lightsOn.length
|
||||
? html`<button class="nf-btn nf-rp-small" @click=${() => this.call("light", "turn_off", { entity_id: lightsOn.map((l) => l.entity_id) })}>
|
||||
: nothing}${lightsOn.some((l) => canControl(this.hass, l.entity_id))
|
||||
? html`<button class="nf-btn nf-rp-small" ?disabled=${!lightsOn.some((l) => canControl(this.hass, l.entity_id))} @click=${() => this.call("light", "turn_off", { entity_id: lightsOn.filter((l) => canControl(this.hass, l.entity_id)).map((l) => l.entity_id) })}>
|
||||
${this.t("panel_all_off")}
|
||||
</button>`
|
||||
: nothing}`,
|
||||
@@ -532,20 +538,20 @@ export class NfRoomPanel extends LitElement {
|
||||
${covers.length
|
||||
? this.section(
|
||||
"panel_covers",
|
||||
covers.map((st) => this.coverRow(st)),
|
||||
covers.length > 1 && groupCovers(covers, this.confirmEntities).length
|
||||
? html`<button class="nf-btn nf-rp-small" @click=${() => this.call("cover", "open_cover", { entity_id: groupCovers(covers, this.confirmEntities) })}>
|
||||
covers.map((st) => canControl(this.hass, st.entity_id) ? this.coverRow(st) : this.sensorRow(st)),
|
||||
covers.length > 1 && groupCovers(covers.filter((c) => canControl(this.hass, c.entity_id)), this.confirmEntities).length
|
||||
? html`<button class="nf-btn nf-rp-small" @click=${() => this.call("cover", "open_cover", { entity_id: groupCovers(covers.filter((c) => canControl(this.hass, c.entity_id)), this.confirmEntities) })}>
|
||||
${this.t("panel_all_open")}</button
|
||||
><button class="nf-btn nf-rp-small" @click=${() => this.call("cover", "close_cover", { entity_id: groupCovers(covers, this.confirmEntities) })}>
|
||||
><button class="nf-btn nf-rp-small" @click=${() => this.call("cover", "close_cover", { entity_id: groupCovers(covers.filter((c) => canControl(this.hass, c.entity_id)), this.confirmEntities) })}>
|
||||
${this.t("panel_all_close")}
|
||||
</button>`
|
||||
: nothing,
|
||||
)
|
||||
: nothing}
|
||||
${isSymcon(this.hass) ? html`<nf-room-hvac .hass=${this.hass} .room=${room}></nf-room-hvac>` : nothing}
|
||||
${climates.length ? this.section("panel_climate", climates.map((st) => this.climateRow(st))) : nothing}
|
||||
${media.length ? this.section("panel_media", media.map((st) => this.mediaRow(st))) : nothing}
|
||||
${switches.length ? this.section("panel_switches", switches.map((st) => this.switchRow(st))) : nothing}
|
||||
${climates.length ? this.section("panel_climate", climates.map((st) => canControl(this.hass, st.entity_id) ? this.climateRow(st) : this.sensorRow(st))) : nothing}
|
||||
${media.length ? this.section("panel_media", media.map((st) => canControl(this.hass, st.entity_id) ? this.mediaRow(st) : this.sensorRow(st))) : nothing}
|
||||
${switches.length ? this.section("panel_switches", switches.map((st) => canControl(this.hass, st.entity_id) ? this.switchRow(st) : this.sensorRow(st))) : nothing}
|
||||
${sensors.length ? this.section("panel_sensors", sensors.map((st) => this.sensorRow(st))) : nothing}
|
||||
${this.extraValues(room)}
|
||||
${!isSymcon(this.hass) && canAnnounce(this.hass) && roomHasSpeaker(this.hass, this.floor, room) ? this.announceSection(room) : nothing}
|
||||
|
||||
@@ -3,22 +3,26 @@ import { UTILITY_KINDS, type Floor } from "../model.ts";
|
||||
import type { HomeAssistant } from "../types.ts";
|
||||
import { buildingUtilityReadings, floorUtilityAreas, floorUtilityReadings, UTILITY_ICONS, UTILITY_LABELS, utilityMetricLabel, utilityText, type UtilityReading } from "../utilities.ts";
|
||||
import { trendButton } from "./trend-button.ts";
|
||||
import { topologyKey, type TopologySelection } from "../topology.ts";
|
||||
import type { UtilityScope } from "../utility-scope.ts";
|
||||
|
||||
/** Building → floors, floor → native areas → rooms → placed devices with a linked power value. */
|
||||
/** Logical groups → their children, floor → native areas → rooms → metered devices. */
|
||||
class NfUtilityOverview extends LitElement {
|
||||
static properties = { hass: { attribute: false }, floors: { attribute: false }, floorId: { attribute: false }, inline: { type: Boolean, reflect: true }, compact: { type: Boolean }, folded: { state: true } };
|
||||
static properties = { hass: { attribute: false }, floors: { attribute: false }, floorId: { attribute: false }, scope: { attribute: false }, inline: { type: Boolean, reflect: true }, compact: { type: Boolean }, folded: { state: true } };
|
||||
declare hass: HomeAssistant;
|
||||
declare floors: readonly Floor[];
|
||||
declare floorId: string | null;
|
||||
declare inline: boolean;
|
||||
declare compact: boolean;
|
||||
declare scope: UtilityScope | null;
|
||||
private declare folded: boolean | null;
|
||||
|
||||
constructor() { super(); this.floors = []; this.floorId = null; this.inline = false; this.compact = false; this.folded = null; }
|
||||
constructor() { super(); this.floors = []; this.floorId = null; this.scope=null; this.inline = false; this.compact = false; this.folded = null; }
|
||||
private value(row: UtilityReading | undefined) {
|
||||
return row ? html`<span class="value" title=${`${utilityMetricLabel(row)}${row.manual ? " · eigener Zähler" : ""}`}><b>${utilityText(this.hass, row)}</b>${row.period !== "total" ? html`<small>${({ day: "heute", month: "Monat", year: "Jahr" })[row.period]}</small>` : nothing}${trendButton(this.hass, row.sources, `${UTILITY_LABELS[row.kind]} · ${utilityMetricLabel(row)}`)}</span>` : nothing;
|
||||
}
|
||||
private open(id: string, room: boolean) { this.dispatchEvent(new CustomEvent("utility-open", { detail: { floorId: room ? this.floorId : id, roomId: room ? id : null }, bubbles: true, composed: true })); }
|
||||
private openTopology(selection:TopologySelection){this.dispatchEvent(new CustomEvent("utility-topology-open",{detail:selection,bubbles:true,composed:true}));}
|
||||
|
||||
private rows(readings: UtilityReading[]) {
|
||||
return UTILITY_KINDS.map((kind) => {
|
||||
@@ -30,23 +34,25 @@ class NfUtilityOverview extends LitElement {
|
||||
render() {
|
||||
if (!this.hass) return nothing;
|
||||
const rooms = this.floors.flatMap((f) => f.rooms), floor = this.floors.find((f) => f.id === this.floorId);
|
||||
const scope=this.scope,areaMode=scope?scope.floorId!==null:!!floor;
|
||||
const name=scope?.name||floor?.name||"Gesamtgebäude",path=scope?.path||name,heading=scope?.heading||(floor?"Bereiche":"Stockwerke");
|
||||
if (this.inline) {
|
||||
const rows = floor ? floorUtilityReadings(this.hass, floor, rooms) : buildingUtilityReadings(this.hass, this.floors);
|
||||
const rows = scope?.totals??(floor ? floorUtilityReadings(this.hass, floor, rooms) : buildingUtilityReadings(this.hass, this.floors));
|
||||
return html`${UTILITY_KINDS.map((kind) => {
|
||||
const readings = rows.filter((r) => r.kind === kind);
|
||||
return readings.length ? html`<div class="meter" aria-label=${`${floor?.name || "Gesamtgebäude"} · ${UTILITY_LABELS[kind]}`}><span class="medium" title=${floor?.name || "Gesamtgebäude"}>${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</span><div class="values">${readings.map((r) => this.value(r))}</div></div>` : nothing;
|
||||
return readings.length ? html`<div class="meter" aria-label=${`${name} · ${UTILITY_LABELS[kind]}`}><span class="medium" title=${path}>${UTILITY_ICONS[kind]} ${UTILITY_LABELS[kind]}</span><div class="values">${readings.map((r) => this.value(r))}</div></div>` : nothing;
|
||||
})}`;
|
||||
}
|
||||
const entries = floor ? floorUtilityAreas(this.hass, floor, rooms, true).map((area) => ({ ...area, hasDetails: area.rooms.length > 0 }))
|
||||
: [...this.floors].sort((a, b) => b.elevation - a.elevation).map((f) => ({ id: f.id, name: f.name, path: "", readings: floorUtilityReadings(this.hass, f, rooms), rooms: [], hasDetails: floorUtilityAreas(this.hass, f, rooms, true).length > 0 }));
|
||||
const shown = entries.filter((e) => e.readings.length || e.hasDetails);
|
||||
const entries = scope?.entries??(floor ? floorUtilityAreas(this.hass, floor, rooms, true).map((area) => ({ ...area, hasDetails: area.rooms.length > 0,selection:null }))
|
||||
: [...this.floors].sort((a, b) => b.elevation - a.elevation).map((f) => ({ id: f.id, name: f.name, path: "", readings: floorUtilityReadings(this.hass, f, rooms), rooms: [], hasDetails: floorUtilityAreas(this.hass, f, rooms, true).length > 0,selection:null })));
|
||||
const shown = scope?entries:entries.filter((e) => e.readings.length || ("hasDetails" in e&&e.hasDetails));
|
||||
if (!shown.length) return nothing;
|
||||
const folded = this.folded ?? this.compact;
|
||||
return html`<section class="panel" aria-label=${floor ? "Bereichszähler" : "Stockwerkszähler"}>
|
||||
<button class="heading" aria-expanded=${!folded} @click=${() => { this.folded = !folded; }}><span>${floor ? "Bereiche" : "Stockwerke"}<small>${floor?.name || "Gesamtgebäude"}</small></span><span aria-hidden="true">${folded ? "+" : "−"}</span></button>
|
||||
return html`<section class="panel" aria-label=${`${heading} · ${name}`}>
|
||||
<button class="heading" title=${path} aria-expanded=${!folded} @click=${() => { this.folded = !folded; }}><span>${heading}<small>${name}</small></span><span aria-hidden="true">${folded ? "+" : "−"}</span></button>
|
||||
${folded ? nothing : html`<div class="entries"><div class="columns"><span></span><span title="Leistung bzw. Durchfluss">Leistung</span><span>Energie / Verbrauch</span></div>
|
||||
${shown.map((entry) => html`<section class="entry" data-area=${floor ? entry.id : nothing}>
|
||||
${floor ? html`<div class="entry-name area-name" title=${entry.path || entry.name}>${entry.name}</div>` : html`<button class="entry-name" title=${entry.name} @click=${() => this.open(entry.id, false)}>${entry.name}</button>`}
|
||||
${shown.map((entry) => html`<section class="entry" data-area=${areaMode ? entry.id : nothing} data-topology-kind=${entry.selection?.kind??nothing} data-topology-key=${entry.selection?topologyKey(entry.selection):nothing}>
|
||||
${areaMode ? html`<div class="entry-name area-name" title=${entry.path || entry.name}>${entry.name}</div>` : html`<button class="entry-name" title=${entry.path||entry.name} @click=${() => entry.selection?this.openTopology(entry.selection):this.open(entry.id, false)}>${entry.name}</button>`}
|
||||
${this.rows(entry.readings)}
|
||||
${entry.rooms.map((room) => html`<section class="room-entry" data-room=${room.id}><button class="entry-name" title=${room.name} @click=${() => this.open(room.id, true)}><span aria-hidden="true">↳</span> ${room.name}</button>${this.rows(room.readings)}
|
||||
${room.devices.map((device) => html`<section class="device-entry" data-device=${device.id}><div class="entry-name device-name" title=${device.name}><span aria-hidden="true">↳</span> ${device.name}</div>${this.rows(device.readings)}</section>`)}
|
||||
@@ -71,7 +77,8 @@ class NfUtilityOverview extends LitElement {
|
||||
button { color:inherit; font:inherit; border:0; background:none; cursor:pointer; text-align:left; }
|
||||
button:focus-visible { outline:2px solid var(--nf-accent); outline-offset:-2px; }
|
||||
.heading { display:flex; flex-shrink:0; align-items:center; justify-content:space-between; gap:12px; width:100%; padding:8px 10px; font-weight:600; }
|
||||
.heading small { display:block; color:var(--nf-muted); font-size:10px; font-weight:normal; }
|
||||
.heading>span:first-child { min-width:0; overflow:hidden; }
|
||||
.heading small { display:block; color:var(--nf-muted); font-size:10px; font-weight:normal; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.entries { min-height:0; max-height:min(50vh,480px); overflow:auto; padding:0 10px 8px; }
|
||||
.columns,.row { display:grid; grid-template-columns:54px minmax(0,1fr) minmax(0,1.2fr); align-items:center; gap:5px; }
|
||||
.columns { color:var(--nf-muted); font-size:9px; text-align:right; margin-bottom:2px; }
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { ALL_TOPOLOGY, floorSelection, topologyFloors, topologyItems, type TopologySelection } from "../topology.ts";
|
||||
import { topologyNavigation } from "./view3d/topology-navigation.ts";
|
||||
// Lit wrapper around the lazily loaded 3D viewer.
|
||||
|
||||
import { changeMoments, hassAt, loadHistory, replayable, type History } from "../live/time-travel.ts";
|
||||
import { canControl } from "../access.ts";
|
||||
import { sunPosition, todayAt } from "../sun-position.ts";
|
||||
import { dayCurves, statesRead, type DayCurves } from "../live/day-curves.ts";
|
||||
import { backdropStyle } from "../backdrop.ts";
|
||||
@@ -56,9 +59,10 @@ import { fixtureGlow } from "../entities/kinds.ts";
|
||||
import { coverTiltEntity } from "../entities/covers.ts";
|
||||
import { isSymcon, isSymconVariable, nativeBool, nativeText } from "../entities/symcon-values.ts";
|
||||
import { WEATHER_VARIABLE_LABELS } from "../symcon-weather.ts";
|
||||
import { floorUtilityAreas, floorUtilityReadings, utilityText } from "../utilities.ts";
|
||||
import { floorUtilityReadings, utilityText } from "../utilities.ts";
|
||||
import "./utility-report.ts";
|
||||
import "./utility-overview.ts";
|
||||
import { utilityScope } from "../utility-scope.ts";
|
||||
import { trendButton } from "./trend-button.ts";
|
||||
import { deviceValuesText } from "../entities/device-values.ts";
|
||||
import { furnitureShown, hiddenFurniture, withoutHidden } from "../entities/visibility.ts";
|
||||
@@ -156,6 +160,7 @@ export class NfView3d extends LitElement {
|
||||
buttons: { attribute: false },
|
||||
_thumbs: { state: true },
|
||||
floorThumbs: { attribute: false },
|
||||
topologySelection: { attribute: false },
|
||||
clean: { attribute: false },
|
||||
cleanButton: { attribute: false },
|
||||
clock: { attribute: false },
|
||||
@@ -288,6 +293,9 @@ export class NfView3d extends LitElement {
|
||||
private declare _blend: number;
|
||||
/** Floor switcher with small pictures of the floors (panel and card; off with a fixed floor). */
|
||||
declare floorThumbs: boolean;
|
||||
declare topologySelection: TopologySelection | null;
|
||||
private topologyImages = new Map<string,string>();
|
||||
private scopedFor: {source:Building;key:string;plan:Building}|null=null;
|
||||
/** Clean view: only the stage – no energy values, thumbnails, legend, scene chips or search (the host hides its own bars). */
|
||||
declare clean: boolean;
|
||||
/** Show the eye button that toggles the clean view (the host listens for "clean-toggle"). */
|
||||
@@ -492,6 +500,7 @@ export class NfView3d extends LitElement {
|
||||
this.buttons = null;
|
||||
this._thumbs = [];
|
||||
this.floorThumbs = true;
|
||||
this.topologySelection=null;
|
||||
this.clean = false;
|
||||
this.cleanButton = false;
|
||||
this.clock = null;
|
||||
@@ -697,13 +706,13 @@ export class NfView3d extends LitElement {
|
||||
// a feature pack may have arrived with them (Energiefluss): the cables and modules follow
|
||||
this.syncDevices(true);
|
||||
}
|
||||
if (changed.has("building") && this.building) {
|
||||
if (["building","topologySelection","floorId"].some((k)=>changed.has(k)) && this.building) {
|
||||
// a new start view (just remembered in the editor) shows right away in the house view
|
||||
const start = JSON.stringify(this.startViewOf());
|
||||
const startChanged = this.shownStartView !== undefined && this.shownStartView !== start;
|
||||
this.shownStartView = start;
|
||||
v.setStartView(this.startViewOf());
|
||||
v.setBuilding(this.shownBuilding(this.hass));
|
||||
v.setStartView(this.building.topology&&this.topologyFocus.kind!=="all"?null:this.startViewOf());
|
||||
const previous=this.shownFor?.shown,shown=this.shownBuilding(this.hass);if(shown!==previous)v.setBuilding(shown);
|
||||
v.setMap(this.building?.settings.map, this.building?.settings.north ?? 0);
|
||||
if (startChanged && this.floorId === null) v.resetView();
|
||||
}
|
||||
@@ -711,14 +720,14 @@ export class NfView3d extends LitElement {
|
||||
v.setStartView(this.startViewOf());
|
||||
if (this.floorId === null) v.resetView();
|
||||
}
|
||||
if (changed.has("building") || changed.has("theme") || changed.has("floorThumbs") || changed.has("packs")) this.scheduleThumbs();
|
||||
if (changed.has("building") || changed.has("theme") || changed.has("floorThumbs") || changed.has("packs") || changed.has("topologySelection") || changed.has("floorId") || changed.has("roomId")) this.scheduleThumbs();
|
||||
// markers shown by kind outside the opened room change with the room
|
||||
const byRoom = this.markersOutside ? ["markersOutside", "floorId", "roomId"] : ["markersOutside"];
|
||||
const forced = this.pluginsDirty || ["building", "markerMode", "heatMode", "flows", "alerts", "dimmed", "holograms", "roomLabels", "floorId", "roomId", ...byRoom].some((k) => changed.has(k));
|
||||
const forced = this.pluginsDirty || ["building", "topologySelection", "markerMode", "heatMode", "flows", "alerts", "dimmed", "holograms", "roomLabels", "floorId", "roomId", ...byRoom].some((k) => changed.has(k));
|
||||
this.pluginsDirty = false;
|
||||
if (forced || changed.has("hass")) this.syncDevices(forced);
|
||||
if (changed.has("autoOrbit")) v.setAutoOrbit(this.autoOrbit ? 0.06 : 0);
|
||||
if (changed.has("_thumbs") || changed.has("_narrowStage") || changed.has("_phoneStage")) v.setLabelInset(this._thumbs.length && !this._phoneStage ? (this.narrowThumbs ? 136 : 184) : 0);
|
||||
if (changed.has("_thumbs") || changed.has("_narrowStage") || changed.has("_phoneStage") || changed.has("building")) v.setLabelInset(this.building?.topology||(this._thumbs.length&&!this._phoneStage) ? (this.narrowThumbs ? 136 : 184) : 0);
|
||||
if (changed.has("floorId")) v.setFloor(this.floorId);
|
||||
if (changed.has("roomId") && (this.roomId || changed.get("roomId"))) v.selectRoom(this.roomId);
|
||||
if (changed.has("outsideOpen") && changed.get("outsideOpen") !== undefined) {
|
||||
@@ -795,8 +804,19 @@ export class NfView3d extends LitElement {
|
||||
}
|
||||
|
||||
/** The building as the 3D view draws it: without the pieces whose visibility condition is not met. */
|
||||
private get topologyFocus(): TopologySelection {
|
||||
return this.building&&this.floorId?floorSelection(this.building,this.floorId,this.roomId):this.topologySelection??ALL_TOPOLOGY;
|
||||
}
|
||||
|
||||
private scopeBuilding(): Building {
|
||||
const b=this.building!;if(!b.topology)return b;
|
||||
const floors=topologyFloors(b,this.topologyFocus,true),key=floors.map((f)=>f.id).join("|");
|
||||
if(this.scopedFor?.source!==b||this.scopedFor.key!==key)this.scopedFor={source:b,key,plan:{...b,floors}};
|
||||
return this.scopedFor.plan;
|
||||
}
|
||||
|
||||
private shownBuilding(hass: HomeAssistant | undefined): Building {
|
||||
const b = this.building!;
|
||||
const b = this.scopeBuilding();
|
||||
const hidden = hiddenFurniture(hass, b);
|
||||
const layers = b.floors.filter((f) => f.layer && this.hiddenLayers.has(f.id)).map((f) => f.id);
|
||||
const key = [...hidden, ...layers.map((id) => `layer:${id}`)].join(",");
|
||||
@@ -838,7 +858,7 @@ export class NfView3d extends LitElement {
|
||||
|
||||
private syncDevices(force: boolean): void {
|
||||
const v = this.viewer;
|
||||
const b = this.building;
|
||||
const b = this.building?this.scopeBuilding():null;
|
||||
if (!v || !b || !this.hass) return;
|
||||
// time travel: the same view, fed with the states of the moment shown
|
||||
const travel = this._travel;
|
||||
@@ -863,7 +883,7 @@ export class NfView3d extends LitElement {
|
||||
const changed = force || this.watched.some((id) => this.shownStates.get(id) !== hass.states[id]);
|
||||
if (!changed) return;
|
||||
// a piece shown only while a helper is on (seasonal decoration) comes and goes with it
|
||||
if (hiddenFurniture(hass, b).join(",") !== this.shownFor?.key) v.setBuilding(this.shownBuilding(hass));
|
||||
const previous=this.shownFor?.shown,shown=this.shownBuilding(hass);if(shown!==previous)v.setBuilding(shown);
|
||||
this.shownStates = new Map(this.watched.map((id) => [id, hass.states[id]]));
|
||||
this.syncHydronics(v, b, hass);
|
||||
this.refreshToday(b);
|
||||
@@ -1070,7 +1090,7 @@ export class NfView3d extends LitElement {
|
||||
private jumpTo(a: Alert): void {
|
||||
// an own warning: its details, or what was chosen for it (switch the entity, go to its room)
|
||||
if (a.kind === "own" && a.tap !== "room") {
|
||||
if (a.tap === "toggle") void this.hass.callService("homeassistant", "toggle", { entity_id: a.entity });
|
||||
if (a.tap === "toggle" && canControl(this.hass, a.entity)) void this.hass.callService("homeassistant", "toggle", { entity_id: a.entity });
|
||||
else openMoreInfo(this, a.entity);
|
||||
return;
|
||||
}
|
||||
@@ -1091,7 +1111,7 @@ export class NfView3d extends LitElement {
|
||||
const room = floor?.rooms.find((r) => r.id === roomId);
|
||||
if (!b || !hass || !floor || !room) return;
|
||||
const mode = roomToggleMode(b.settings.room_double_tap, this.roomDoubleTap);
|
||||
const lights = roomToggleLights(hass, floor, room, this.furnitureLinks, this.confirmSet, mode);
|
||||
const lights = roomToggleLights(hass, floor, room, this.furnitureLinks, this.confirmSet, mode).filter((id) => canControl(hass, id));
|
||||
if (!lights.length) return;
|
||||
const anyOn = lights.some((id) => hass.states[id]?.state === "on");
|
||||
void hass.callService("homeassistant", anyOn ? "turn_off" : "turn_on", { entity_id: lights });
|
||||
@@ -1104,6 +1124,7 @@ export class NfView3d extends LitElement {
|
||||
}
|
||||
|
||||
private runScene(id: string): void {
|
||||
if (!canControl(this.hass, id)) return;
|
||||
void this.hass.callService(id.split(".")[0], "turn_on", { entity_id: id });
|
||||
this._sceneFired = id;
|
||||
setTimeout(() => (this._sceneFired = null), 600);
|
||||
@@ -1736,12 +1757,12 @@ export class NfView3d extends LitElement {
|
||||
private scheduleThumbs(delay = 600): void {
|
||||
clearTimeout(this.thumbTimer);
|
||||
const floors = this.building?.floors.filter((f) => f.rooms.length).length ?? 0;
|
||||
if (!this.floorThumbs || floors < 2) {
|
||||
if (!this.floorThumbs || (!this.building?.topology && floors < 2)) {
|
||||
this._thumbs = [];
|
||||
return;
|
||||
}
|
||||
// at most every few seconds, however often lamps change (the tablet level waits longer)
|
||||
const wait = Math.max(delay, this.thumbsAt + (this._low ? 8000 : 4000) - Date.now());
|
||||
const wait = this.building?.topology ? delay : Math.max(delay, this.thumbsAt + (this._low ? 8000 : 4000) - Date.now());
|
||||
this.thumbTimer = setTimeout(() => {
|
||||
// at night (kiosk) the pictures are drawn once and then rest
|
||||
if (!this.viewer || (this.dimmed && this._thumbs.length)) return;
|
||||
@@ -1751,7 +1772,11 @@ export class NfView3d extends LitElement {
|
||||
return;
|
||||
}
|
||||
this.thumbsAt = Date.now();
|
||||
this._thumbs = this.viewer.floorThumbnails(this.narrowThumbs ? 104 : 150, this.narrowThumbs ? 78 : 112);
|
||||
if(this.building?.topology){
|
||||
const nodes=topologyItems(this.building,this.topologyFocus);
|
||||
for(const t of this.viewer.scopeThumbnails(nodes,this.narrowThumbs?104:150,this.narrowThumbs?78:112))this.topologyImages.set(t.key,t.url);
|
||||
this.requestUpdate();
|
||||
}else this._thumbs = this.viewer.floorThumbnails(this.narrowThumbs ? 104 : 150, this.narrowThumbs ? 78 : 112);
|
||||
}, wait);
|
||||
}
|
||||
|
||||
@@ -1760,6 +1785,9 @@ export class NfView3d extends LitElement {
|
||||
}
|
||||
|
||||
private renderThumbs() {
|
||||
if(this.floorThumbs&&this.building?.topology){
|
||||
return topologyNavigation(this.building,this.topologyFocus,this.topologyImages,(s)=>this.fire("topology-tap",s),this._thumbsCompact,()=>{this._thumbsCompact=!this._thumbsCompact;try{localStorage.setItem("nextfloor.thumbs_compact",this._thumbsCompact?"1":"0");}catch{}},this.narrowThumbs,this._shortStage);
|
||||
}
|
||||
if (!this._thumbs.length || !this.building || this._phoneStage) return nothing;
|
||||
const names = new Map(this.building.floors.map((f) => [f.id, f.name]));
|
||||
// the highest floor on top
|
||||
@@ -1802,7 +1830,7 @@ export class NfView3d extends LitElement {
|
||||
const st = this.hass?.states[entityId];
|
||||
if (phase === "start") {
|
||||
// devices that ask before switching are not moved by a swipe (it turns the view instead)
|
||||
if (!st || isUnavailable(st) || this.confirmSet.has(entityId)) return false;
|
||||
if (!st || isUnavailable(st) || !canControl(this.hass, entityId) || this.confirmSet.has(entityId)) return false;
|
||||
const kind = kindOf(entityId);
|
||||
if (kind === "light" && lightAbilities(st).dim) {
|
||||
const pct = st.state === "on" ? (typeof st.attributes.brightness === "number" ? Math.round((st.attributes.brightness as number) / 2.55) : 100) : 0;
|
||||
@@ -1843,6 +1871,7 @@ export class NfView3d extends LitElement {
|
||||
}
|
||||
|
||||
private applySwipe(): void {
|
||||
if (this._swipe && !canControl(this.hass, this._swipe.entity)) return;
|
||||
const s = this._swipe;
|
||||
if (!s || !this.hass) return;
|
||||
if (s.kind === "light") {
|
||||
@@ -2002,8 +2031,8 @@ export class NfView3d extends LitElement {
|
||||
if (!this._central) return star;
|
||||
const floor = this.floorId ? b.floors.find((f) => f.id === this.floorId) : undefined;
|
||||
const floors = floor ? [floor] : b.floors;
|
||||
const lights = floors.flatMap((f) => floorControls(hass, f).lights);
|
||||
const covers = floors.flatMap((f) => floorControls(hass, f).covers);
|
||||
const lights = floors.flatMap((f) => floorControls(hass, f).lights).filter((id) => canControl(hass, id));
|
||||
const covers = floors.flatMap((f) => floorControls(hass, f).covers).filter((id) => canControl(hass, id));
|
||||
const lightsOn = lights.filter((id) => hass.states[id]?.state === "on").length;
|
||||
const house = !floor;
|
||||
// house-wide: the first tap arms the button ("sure?"), the second runs it
|
||||
@@ -2050,7 +2079,7 @@ export class NfView3d extends LitElement {
|
||||
return html`<button
|
||||
class="nf-chip"
|
||||
aria-pressed=${on || this._sceneFired === id}
|
||||
?disabled=${isUnavailable(st)}
|
||||
?disabled=${isUnavailable(st) || !canControl(hass, id)}
|
||||
@click=${() => {
|
||||
void hass.callService(domain, service, { entity_id: id });
|
||||
this._sceneFired = id;
|
||||
@@ -2357,6 +2386,10 @@ export class NfView3d extends LitElement {
|
||||
return;
|
||||
}
|
||||
const kind = kindOf(entityId);
|
||||
if (this.hass.symconObjects !== undefined && !canControl(this.hass, entityId)) {
|
||||
if (this.hass.states[entityId]) this._menu = { entity: entityId, x, y };
|
||||
return;
|
||||
}
|
||||
// blinds have no single on/off: a tap opens their quick menu (up, positions, stop, down); speakers and TVs open theirs
|
||||
// (play, skip, volume, sources and the stations set for them)
|
||||
if (kind === "cover" || kind === "media") {
|
||||
@@ -2798,11 +2831,12 @@ export class NfView3d extends LitElement {
|
||||
|
||||
/** Native utility readings for the current building/floor scope. */
|
||||
private utilityOverview(inline: boolean) {
|
||||
const b = this.building;
|
||||
const b = this.building?this.scopeBuilding():null;
|
||||
if (!b || !isSymcon(this.hass) || !this.showEnergy || this.clean || this.roomId || this.panelOpen || (!inline && !this._utilityOverviewVisible)) return nothing;
|
||||
const rooms = b.floors.flatMap((f) => f.rooms), floors = this.floorId ? b.floors.filter((f) => f.id === this.floorId) : b.floors;
|
||||
if (!floors.some((f) => floorUtilityReadings(this.hass, f, rooms).length || floorUtilityAreas(this.hass, f, rooms, true).length)) return nothing;
|
||||
return html`<nf-utility-overview ?inline=${inline} .hass=${this.hass} .floors=${b.floors} .floorId=${this.floorId} .compact=${this._narrowStage}
|
||||
const scope=utilityScope(this.hass,this.building!,this.topologyFocus);
|
||||
if(!scope.totals.length&&!scope.entries.length)return nothing;
|
||||
return html`<nf-utility-overview ?inline=${inline} .hass=${this.hass} .floors=${b.floors} .floorId=${this.floorId} .scope=${scope} .compact=${this._narrowStage}
|
||||
@utility-topology-open=${(e:CustomEvent<TopologySelection>)=>{e.stopPropagation();this.fire("topology-tap",e.detail);}}
|
||||
@utility-open=${(e: CustomEvent<{ floorId: string; roomId: string | null }>) => { e.stopPropagation(); if (e.detail.roomId) this.openRoom(e.detail.floorId, e.detail.roomId); else this.fire("floor-tap", { floorId: e.detail.floorId }); }}></nf-utility-overview>`;
|
||||
}
|
||||
|
||||
@@ -2819,7 +2853,7 @@ export class NfView3d extends LitElement {
|
||||
if (isSymcon(this.hass) && this.building?.settings.rain_sensor && this.building.settings.rain_sensor !== "none") weather.push(["Regensensor", this.building.settings.rain_sensor]);
|
||||
const weatherValues = weather.length ? html`<button class="nf-energy-item nf-flow-toggle nf-weather-values" aria-label="Wetterwerte anzeigen" title="Wetterwerte anzeigen" aria-haspopup="dialog" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-weather-dialog")?.showModal()}><span>Wetter</span><b aria-hidden="true">⛅</b></button>
|
||||
<dialog class="nf-weather-dialog" aria-label="Wetterwerte" @keydown=${(event: KeyboardEvent) => event.stopPropagation()}><header><b>Wetter</b><button type="button" class="nf-chip" aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-weather-dialog")?.close()}>×</button></header>${weather.map(([label, id]) => html`<p><span>${label}</span><b>${nativeText(this.hass.states[id])}${trendButton(this.hass, [id], label)}</b></p>`)}</dialog>` : nothing;
|
||||
const floors = isSymcon(this.hass) ? (this.building?.floors ?? []).filter((f) => !this.floorId || f.id === this.floorId).map((f) => ({ floor: f, readings: floorUtilityReadings(this.hass, f, this.building?.floors.flatMap((x) => x.rooms)) })).filter((f) => f.readings.length) : [];
|
||||
const floors = isSymcon(this.hass) ? (this.building?this.scopeBuilding().floors:[]).filter((f) => !this.floorId || f.id === this.floorId).map((f) => ({ floor: f, readings: floorUtilityReadings(this.hass, f, this.building?.floors.flatMap((x) => x.rooms)) })).filter((f) => f.readings.length) : [];
|
||||
const utilities = floors.length ? html`<button class="nf-energy-item nf-flow-toggle nf-utility-toggle" aria-label="Stockwerkszähler anzeigen" title="Stockwerkszähler anzeigen" aria-haspopup="dialog" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-utility-dialog")?.showModal()}><span>Stockwerkszähler</span><b aria-hidden="true">⚡ 💧</b></button>
|
||||
<dialog class="nf-weather-dialog nf-utility-dialog" aria-label="Stockwerkszähler" @keydown=${(event: KeyboardEvent) => event.stopPropagation()}><header><b>Stockwerkszähler</b><button type="button" class="nf-chip" aria-label="Schließen" @click=${() => this.renderRoot.querySelector<HTMLDialogElement>(".nf-utility-dialog")?.close()}>×</button></header>${floors.map(({ floor, readings }) => html`<h3>${floor.name}</h3><nf-utility-report .hass=${this.hass} .readings=${readings}></nf-utility-report>`)}</dialog>` : nothing;
|
||||
return [overviewToggle, summary, ...people, weatherValues, utilities, ...ids
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { html, nothing } from "lit";
|
||||
import type { Building } from "../../model.ts";
|
||||
import { ALL_TOPOLOGY, topologyItems, topologyKey, topologyPath, type TopologySelection } from "../../topology.ts";
|
||||
|
||||
export function topologyNavigation(b:Building,selection:TopologySelection,images:ReadonlyMap<string,string>,select:(s:TopologySelection)=>void,compact:boolean,fold:()=>void,narrow:boolean,short:boolean) {
|
||||
const path=topologyPath(b,selection),items=topologyItems(b,selection);
|
||||
const symbols={all:"⌂",location:"⌖",branch:"◇",building:"▥",floor:"▤",room:"□",outside:"🌳"};
|
||||
return html`<nav class="nf-thumbs nf-topology-navigation ${narrow?"nf-thumbs-small":""} ${short?"nf-thumbs-short":""} ${compact?"nf-thumbs-compact":""}" aria-label="Topologie">
|
||||
<style>.nf-topology-crumbs{display:grid;gap:3px}.nf-topology-crumbs button{min-width:0;text-align:left;padding:5px 7px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10px}.nf-topology-navigation .nf-thumb>span{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nf-topology-placeholder{height:74px;display:grid;place-items:center;font-size:25px;opacity:.45}.nf-topology-navigation{overflow:auto;overscroll-behavior:contain;max-height:calc(100% - 130px)}.nf-topology-navigation .nf-thumbs-fold{position:static;align-self:flex-start;flex-shrink:0}.nf-topology-navigation .nf-thumb-house{flex-shrink:0}.nf-topology-navigation .nf-thumb{flex-shrink:0}</style>
|
||||
<button class="nf-thumbs-fold" aria-label=${compact?"Topologie aufklappen":"Topologie einklappen"} @click=${fold}>${compact?"▸":"◂"}</button>
|
||||
<button class="nf-thumb nf-thumb-house" aria-pressed=${selection.kind==="all"} @click=${()=>select(ALL_TOPOLOGY)}>⌂ <span>Alle Orte</span></button>
|
||||
${path.length>1?html`<div class="nf-topology-crumbs">${path.slice(1).map((n)=>html`<button class="nf-chip" data-topology-key=${n.key} title=${path.slice(1,path.indexOf(n)+1).map((p)=>p.name).join(" / ")} aria-current=${n===path.at(-1)?"location":nothing} @click=${()=>select(n.selection)}>${symbols[n.selection.kind]} ${n.name}</button>`)}</div>`:nothing}
|
||||
${items.map((n)=>html`<button class="nf-thumb" data-topology-key=${n.key} data-topology-kind=${n.selection.kind} aria-pressed=${topologyKey(selection)===n.key} title=${n.name} @click=${()=>select(n.selection)}>
|
||||
${compact?nothing:images.get(n.key)?html`<img src=${images.get(n.key)!} alt=""/>`:html`<div class="nf-topology-placeholder" aria-hidden="true">${symbols[n.selection.kind]}</div>`}
|
||||
<span>${n.name}</span>
|
||||
</button>`)}
|
||||
</nav>`;
|
||||
}
|
||||
@@ -30,6 +30,21 @@ test("independent station feedback keeps zero/offline values and never falls bac
|
||||
visual=hydronicVisual(h,f,"g",.7);assert.equal(visual.stations?.[0].pump,null);assert.equal(visual.stations?.[0].temperatures[3],null);assert.equal(visual.stations?.[1].pump,true);
|
||||
});
|
||||
|
||||
test("shared and individual station statuses survive migration and persistence; removal releases only that unit",()=>{
|
||||
const original={status:"lock.10",flow:"cover.1"};
|
||||
const legacy=freshwaterStations(item({hydronic:original}));
|
||||
const hydronic=withFreshwaterStations(original,[{...legacy[0],status:"light.11"},{...newFreshwaterStation("second"),status:"cover.12"}]);
|
||||
const f=item({hydronic});
|
||||
assert.equal(hydronic.status,"lock.10");
|
||||
const b=normalizeBuilding(JSON.parse(JSON.stringify({...emptyBuilding(),floors:[floorWith([],{furniture:[f]})]})));
|
||||
assert.deepEqual(b.floors[0].furniture[0].hydronic,JSON.parse(JSON.stringify(hydronic)));
|
||||
assert.deepEqual(hydronicRefs(f).sort(),["lock.10","light.11","cover.12","cover.1"].sort());
|
||||
hydronic.stations=hydronic.stations!.slice(0,1);
|
||||
assert.ok(!hydronicRefs(f).includes("cover.12"));
|
||||
assert.ok(hydronicRefs(f).includes("lock.10"));
|
||||
assert.equal(newFreshwaterStation("new").status,undefined);
|
||||
});
|
||||
|
||||
test("all cascade and common circulation links are watched; removed stations and disabled valves release their refs",()=>{
|
||||
const f=item({hydronic:{buffer_id:"buffer-object",stations:[{id:"a",name:"A",flow:"cover.1",pump:{command:"light.2",feedback:"lock.3"},valve:{command:"cover.4",feedback:"light.5"},power:"climate.6"},{id:"b",name:"B",hot_water:"sensor.7",cold_water:"sensor.8"}],circulation:{feedback:"sensor.9"}}});
|
||||
const b={...emptyBuilding(),floors:[floorWith([],{furniture:[f]})]},h=hassOf([],{}, {symconObjects:[]});
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { HydronicConfig, HydronicControl } from "./hydronic-model.ts";
|
||||
export const MAX_FRESHWATER_STATIONS = 16;
|
||||
export interface FreshwaterStation {
|
||||
id: string; name: string;
|
||||
status?: string | null;
|
||||
flow?: string | null; return?: string | null; hot_water?: string | null; cold_water?: string | null; power?: string | null;
|
||||
pump?: HydronicControl; valve?: HydronicControl; has_valve?: boolean;
|
||||
}
|
||||
|
||||
@@ -11,11 +11,13 @@ export interface HydronicCircuit {
|
||||
valve_type?: "mixing" | "two_way";
|
||||
pump?: HydronicControl; valve?: HydronicControl;
|
||||
flow?: EntityRef; return?: EntityRef; power?: EntityRef;
|
||||
status?: EntityRef;
|
||||
mode_entity?: EntityRef; cooling_value?: number;
|
||||
}
|
||||
export interface HydronicProbe { id: string; name: string; entity: EntityRef; level: number }
|
||||
export interface HydronicConfig {
|
||||
card?: boolean;
|
||||
status?: EntityRef;
|
||||
circuits?: HydronicCircuit[];
|
||||
sensors?: HydronicProbe[];
|
||||
flow?: EntityRef; return?: EntityRef;
|
||||
@@ -41,9 +43,9 @@ const controlRefs = (c: HydronicControl | undefined) => [c?.command, c?.feedback
|
||||
export function hydronicRefs(item: Pick<Furniture, "type" | "hydronic">): string[] {
|
||||
if (!isHydronic(item.type)) return [];
|
||||
const h = hydronicConfig(item);
|
||||
return [...new Set([...(item.type === "freshwater_station" ? [] : [h.flow, h.return]),
|
||||
...(item.type === "heating_manifold" ? (h.circuits ?? []).flatMap((c) => [c.flow, c.return, c.power, c.mode_entity, ...(hasPump(c) ? controlRefs(c.pump) : []), ...(hasValve(c) ? controlRefs(c.valve) : [])]) : []),
|
||||
return [...new Set([h.status, ...(item.type === "freshwater_station" ? [] : [h.flow, h.return]),
|
||||
...(item.type === "heating_manifold" ? (h.circuits ?? []).flatMap((c) => [c.status, c.flow, c.return, c.power, c.mode_entity, ...(hasPump(c) ? controlRefs(c.pump) : []), ...(hasValve(c) ? controlRefs(c.valve) : [])]) : []),
|
||||
...(item.type === "buffer_tank" ? (h.sensors ?? []).map((s) => s.entity) : []),
|
||||
...(item.type === "freshwater_station" ? [h.circulation_temperature, ...controlRefs(h.circulation), ...freshwaterStations(item).flatMap((s) => [s.flow, s.return, s.hot_water, s.cold_water, s.power, ...controlRefs(s.pump), ...(stationHasValve(s) ? controlRefs(s.valve) : [])])] : []),
|
||||
...(item.type === "freshwater_station" ? [h.circulation_temperature, ...controlRefs(h.circulation), ...freshwaterStations(item).flatMap((s) => [s.status, s.flow, s.return, s.hot_water, s.cold_water, s.power, ...controlRefs(s.pump), ...(stationHasValve(s) ? controlRefs(s.valve) : [])])] : []),
|
||||
].filter(realRef))];
|
||||
}
|
||||
@@ -9,6 +9,26 @@ import { watchedEntities } from "./components/view3d/watch-list.ts";
|
||||
const piece = (type: string, extra: Partial<Furniture> = {}): Furniture => { const [w,d,h] = FURNITURE_SIZE[type as keyof typeof FURNITURE_SIZE]; return { id: "hyd", type, x: 0, z: 0, w,d,h,rotation:0,variant:null, ...extra }; };
|
||||
const native = (id: string, value: number | boolean, extra: Record<string, unknown> = {}) => entity(id, "open", { symcon_id: 123, symcon_variable_type: typeof value === "boolean" ? 0 : 2, symcon_value: value, symcon_min: 0, symcon_max: 100, ...extra });
|
||||
|
||||
test("hydronic status retains native integer aliases, including zero, and shows missing readings explicitly", () => {
|
||||
const h = hassOf([native("cover.arbitrary", 0, {symcon_variable_type:1, symcon_formatted:"Bereitschaft", symcon_has_action:true})]);
|
||||
assert.equal(hydronicReading(h, "Status", "cover.arbitrary")!.text, "Bereitschaft");
|
||||
h.states["cover.arbitrary"] = native("cover.arbitrary", 7, {symcon_variable_type:1, symcon_formatted:"Warmwasserbereitung"});
|
||||
assert.equal(hydronicReading(h, "Status", "cover.arbitrary")!.text, "Warmwasserbereitung");
|
||||
h.states["cover.arbitrary"].state = "unavailable";
|
||||
assert.equal(hydronicReading(h, "Status", "cover.arbitrary")!.text, "–");
|
||||
assert.equal(hydronicReading(h, "Status", null), null);
|
||||
});
|
||||
|
||||
test("plant and circuit statuses persist and are watched even for valve-free pumps without other bindings", () => {
|
||||
const item = piece("heating_manifold", {hydronic:{status:"lock.42",circuits:[{...newCircuit("feed"),kind:"pump",status:"cover.43"}]}});
|
||||
const b = normalizeBuilding(JSON.parse(JSON.stringify({...emptyBuilding(),floors:[floorWith([],{furniture:[item]})]})));
|
||||
assert.deepEqual(b.floors[0].furniture[0].hydronic,item.hydronic);
|
||||
const watched = watchedEntities({hass:hassOf([]),building:b,openingLinks:new Map(),furnitureLinks:new Map(),needsRoomSensors:false,alertSources:null,weatherEntityId:null});
|
||||
assert.ok(["lock.42","cover.43"].every((id)=>watched.includes(id)));
|
||||
item.hydronic!.circuits![0].status = null;
|
||||
assert.deepEqual(hydronicRefs(item),["lock.42"]);
|
||||
});
|
||||
|
||||
test("a buffer starts with seven unique probes from top to bottom and remains freely configurable after persistence", () => {
|
||||
const item = piece("buffer_tank", { hydronic: defaultHydronic("buffer_tank") });
|
||||
item.hydronic!.sensors!.forEach((s, i) => assert.ok(Math.abs(s.level - (6 - i) / 6) < 1e-10));
|
||||
|
||||
@@ -1134,6 +1134,14 @@ const DE = {
|
||||
out_path: "Weg",
|
||||
out_driveway: "Einfahrt",
|
||||
out_street: "Straße",
|
||||
out_pavers: "Pflastersteine",
|
||||
access_room_devices: "Hier sind nur die einzeln freigegebenen Geräte sichtbar.",
|
||||
access_room_geometry: "Für diesen Raum sind keine Zustände freigegeben.",
|
||||
out_stepping_stones: "Trittplatten",
|
||||
out_natural_stone: "Natursteinweg",
|
||||
outdoor_texture_scale: "Texturmaßstab (%)",
|
||||
outdoor_texture_rotation: "Texturdrehung (°)",
|
||||
outdoor_texture_hint: "100 % ist die Originalgröße. 200 % macht das Muster doppelt so groß, 50 % halb so groß (5–2000 %). Die Drehung verändert nur die Textur dieser Fläche. Standard: 100 % und 0°.",
|
||||
out_sidewalk: "Gehweg",
|
||||
out_gravel: "Schotterfläche",
|
||||
out_river: "Fluss",
|
||||
@@ -1556,6 +1564,7 @@ const DE = {
|
||||
lamp_hint_pendant: "Höhe = Abhängung unter der Decke. Antippen in 3D schaltet, lange drücken öffnet die Details.",
|
||||
theme: "Look",
|
||||
version_hint: "Installierte Version von NextFloor – Oberfläche; die Integration in Home Assistant meldet {backend}",
|
||||
symcon_version_hint: "Installierte Version von NextFloor – Oberfläche; das Symcon-Modul meldet {backend}",
|
||||
accent: "Akzentfarbe",
|
||||
accent_hint: "Eigene Akzentfarbe: Linien und Leuchtkanten im Neon-Look, Knöpfe und Pins – ↺ setzt das Neon-Cyan zurück",
|
||||
accent_reset: "Zurück zu Cyan",
|
||||
@@ -3204,6 +3213,14 @@ const EN: Record<Key, string> = {
|
||||
out_path: "Path",
|
||||
out_driveway: "Driveway",
|
||||
out_street: "Street",
|
||||
out_pavers: "Paving stones",
|
||||
access_room_devices: "Only individually authorized devices are visible here.",
|
||||
access_room_geometry: "No live data is shared for this room.",
|
||||
out_stepping_stones: "Stepping stones",
|
||||
out_natural_stone: "Natural stone path",
|
||||
outdoor_texture_scale: "Texture scale (%)",
|
||||
outdoor_texture_rotation: "Texture rotation (°)",
|
||||
outdoor_texture_hint: "100% is the original size. 200% doubles the pattern size, 50% halves it (5–2000%). Rotation changes only this area's texture. Defaults: 100% and 0°.",
|
||||
out_sidewalk: "Sidewalk",
|
||||
out_gravel: "Gravel",
|
||||
out_river: "River",
|
||||
@@ -3626,6 +3643,7 @@ const EN: Record<Key, string> = {
|
||||
lamp_hint_pendant: "Height = drop below the ceiling. Tap in 3D to switch, long press for details.",
|
||||
theme: "Look",
|
||||
version_hint: "Installed version of NextFloor – the frontend; the integration in Home Assistant reports {backend}",
|
||||
symcon_version_hint: "Installed version of NextFloor – the frontend; the Symcon module reports {backend}",
|
||||
accent: "Accent colour",
|
||||
accent_hint: "An accent colour of your own: lines and glowing edges in the neon look, buttons and pins – ↺ brings the neon cyan back",
|
||||
accent_reset: "Back to cyan",
|
||||
|
||||
+32
-1
@@ -9,6 +9,7 @@ import type { LampModel } from "./viewer/viewer3d.ts";
|
||||
import type { FurnitureColors } from "./furniture-colors.ts";
|
||||
import type { ShowWhen } from "./entities/visibility.ts";
|
||||
import type { HydronicConfig } from "./hydronic-model.ts";
|
||||
import { normalizeTopology } from "./topology.ts";
|
||||
|
||||
export type Vec2 = [number, number];
|
||||
|
||||
@@ -49,6 +50,8 @@ export type WeatherVariableKey = typeof WEATHER_VARIABLE_KEYS[number];
|
||||
export type WallHeight = number | null | (number | null)[];
|
||||
|
||||
export interface Room {
|
||||
/** Viewer-only Symcon access metadata; absent in the admin's stored project. */
|
||||
symcon_read_room?: boolean;
|
||||
/** Room temperature, humidity and CO2: chosen sensors instead of the automatic pick. */
|
||||
climate?: RoomClimate | null;
|
||||
/** Show temperature, humidity and CO2 in a floating glass card over this room. */
|
||||
@@ -432,6 +435,13 @@ export interface Background {
|
||||
export interface Floor {
|
||||
id: string;
|
||||
name: string;
|
||||
/** Logical parent; coordinates and IDs remain unchanged when a floor moves in the topology. */
|
||||
building_id?: string | null;
|
||||
/** A separate outdoor plan belonging directly to a location, outside the building/storey hierarchy. */
|
||||
outdoor_location_id?: string | null;
|
||||
/** Independent outdoor plans may also belong to a branch or building. Exactly one outdoor owner is set. */
|
||||
outdoor_branch_id?: string | null;
|
||||
outdoor_building_id?: string | null;
|
||||
elevation: number;
|
||||
height: number;
|
||||
cut_height: number;
|
||||
@@ -909,7 +919,7 @@ export type WeatherEffect = (typeof WEATHER_EFFECTS)[number];
|
||||
/** The effects shown when the plan does not say: everything but fog (fog greys the whole scene). */
|
||||
export const DEFAULT_WEATHER_EFFECTS: WeatherEffect[] = ["rain", "snow", "clouds", "lightning", "sky"];
|
||||
|
||||
export const OUTDOOR_TYPES = ["lawn", "terrace", "path", "driveway", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola"] as const;
|
||||
export const OUTDOOR_TYPES = ["lawn", "terrace", "path", "driveway", "pavers", "stepping_stones", "natural_stone", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola"] as const;
|
||||
export type OutdoorType = (typeof OUTDOOR_TYPES)[number];
|
||||
|
||||
/** Top of each kind of outdoor area above ground level (pool: its water, below). */
|
||||
@@ -918,6 +928,9 @@ export const OUTDOOR_TOP: Record<OutdoorType, number> = {
|
||||
terrace: 0.12,
|
||||
path: 0.02,
|
||||
driveway: 0.02,
|
||||
pavers: 0.025,
|
||||
stepping_stones: 0.025,
|
||||
natural_stone: 0.03,
|
||||
street: 0.02,
|
||||
sidewalk: 0.12,
|
||||
gravel: 0.018,
|
||||
@@ -1024,6 +1037,10 @@ export interface OutdoorArea {
|
||||
gates?: FenceGate[];
|
||||
/** How opaque the area is drawn, 0.1 … 1 (null = fully): a driveway above a cellar can be seen through. The outline stays. */
|
||||
opacity?: number | null;
|
||||
/** Size of the outdoor texture pattern (1 = original, 2 = twice as large). */
|
||||
texture_scale?: number | null;
|
||||
/** Clockwise texture rotation in degrees; independent of the outline. */
|
||||
texture_rotation?: number | null;
|
||||
}
|
||||
|
||||
/** A gate in a fence: a gap in one edge of its outline with a garden gate (one leaf), a double gate or a sliding gate. */
|
||||
@@ -1044,6 +1061,13 @@ export interface FenceGate {
|
||||
/** Whether an area leaves a hole in the areas around it: water areas default to on. */
|
||||
export const cutsOut = (a: OutdoorArea): boolean => a.cut ?? (a.type === "pool" || a.type === "river" || a.type === "stream");
|
||||
|
||||
/** Valid texture settings for old plans and imported data as well as editor inputs. */
|
||||
export function outdoorTextureSettings(a: Pick<OutdoorArea, "texture_scale" | "texture_rotation">): { scale: number; rotation: number } {
|
||||
const scale = Number.isFinite(a.texture_scale) ? Math.max(0.05, Math.min(20, a.texture_scale!)) : 1;
|
||||
const rotation = Number.isFinite(a.texture_rotation) ? ((a.texture_rotation! % 360) + 360) % 360 : 0;
|
||||
return { scale, rotation };
|
||||
}
|
||||
|
||||
/** Energy flow: meter position and power sensors (W). Grid positive = import, battery positive = discharging. */
|
||||
export interface EnergySettings {
|
||||
meter: { floor_id: string; x: number; z: number } | null;
|
||||
@@ -1102,8 +1126,14 @@ export interface PresenceLink {
|
||||
room?: string | null;
|
||||
}
|
||||
|
||||
export interface PlanLocation { id: string; name: string }
|
||||
export interface PlanBranch { id: string; name: string; location_id: string }
|
||||
export interface PlanBuilding { id: string; name: string; branch_id: string }
|
||||
export interface PlanTopology { locations: PlanLocation[]; branches: PlanBranch[]; buildings: PlanBuilding[] }
|
||||
|
||||
export interface Building {
|
||||
version: 1;
|
||||
topology?: PlanTopology;
|
||||
floors: Floor[];
|
||||
settings: BuildingSettings;
|
||||
energy: EnergySettings;
|
||||
@@ -1669,6 +1699,7 @@ export function normalizeBuilding(b: Building): Building {
|
||||
}));
|
||||
}
|
||||
uniqueIds(b);
|
||||
if (b.topology) normalizeTopology(b);
|
||||
return b;
|
||||
}
|
||||
|
||||
|
||||
+44
-6
@@ -24,6 +24,7 @@ import type { HomeAssistant } from "./types.ts";
|
||||
import { withCoverControls } from "./entities/cover-controls.ts";
|
||||
import { withSymconWeather } from "./symcon-weather.ts";
|
||||
import { isSymcon } from "./entities/symcon-values.ts";
|
||||
import { ALL_TOPOLOGY, floorSelection, isOutdoorFloor, outsideFloor, outsideSelection, topologyOutsideFloors, topologyParent, topologyPath, type TopologySelection, type OutsideOwner } from "./topology.ts";
|
||||
import { allOffPlan, floorSwitchables, type ServiceCall } from "./live/all-off.ts";
|
||||
import type { FloorStack, Quality, WallMode } from "./viewer/viewer3d.ts";
|
||||
|
||||
@@ -38,6 +39,7 @@ export class NextFloorPanel extends LitElement {
|
||||
panel: { attribute: false },
|
||||
_mode: { state: true },
|
||||
_editorReady: { state: true },
|
||||
_topologyGroup: { state: true },
|
||||
_floorId: { state: true },
|
||||
_roomId: { state: true },
|
||||
_wallMode: { state: true },
|
||||
@@ -63,6 +65,7 @@ export class NextFloorPanel extends LitElement {
|
||||
private declare _mode: Mode;
|
||||
/** The editor bundle has been loaded (it is fetched when the editor or the extensions page opens first). */
|
||||
private declare _editorReady: boolean;
|
||||
private declare _topologyGroup: TopologySelection;
|
||||
private declare _floorId: string | null;
|
||||
private declare _roomId: string | null;
|
||||
private declare _wallMode: WallMode;
|
||||
@@ -98,6 +101,7 @@ export class NextFloorPanel extends LitElement {
|
||||
this._mode = "view";
|
||||
this._editorReady = !!customElements.get("nf-editor");
|
||||
this._floorId = null;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._roomId = null;
|
||||
this._wallMode = "auto";
|
||||
this._prefs = this.store.load(location.search);
|
||||
@@ -165,6 +169,7 @@ export class NextFloorPanel extends LitElement {
|
||||
const building = this.data.building;
|
||||
if (building && this._floorId && !building.floors.some((f) => f.id === this._floorId)) {
|
||||
this._floorId = null;
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._roomId = null;
|
||||
}
|
||||
}
|
||||
@@ -174,12 +179,25 @@ export class NextFloorPanel extends LitElement {
|
||||
}
|
||||
|
||||
private setMode(mode: Mode): void {
|
||||
if (mode !== "view" && !this.isAdmin) return;
|
||||
if (mode === this._mode) return;
|
||||
if (mode === "view") void this.data.flush();
|
||||
this._mode = mode;
|
||||
}
|
||||
|
||||
private topologySelection(building: Building): TopologySelection {
|
||||
return this._floorId ? floorSelection(building,this._floorId,this._roomId) : this._topologyGroup;
|
||||
}
|
||||
|
||||
private openTopology(selection: TopologySelection): void {
|
||||
const b=this.data.building;if(!b)return;
|
||||
this._roomId=selection.kind==="room"?selection.id??null:null;
|
||||
this._floorId=selection.kind==="room"?selection.floorId??null:selection.kind==="floor"?selection.id??null:outsideFloor(b,selection)?.id??null;
|
||||
this._topologyGroup=selection;this._outside=false;
|
||||
}
|
||||
|
||||
private openFloor(floorId: string | null): void {
|
||||
this._topologyGroup=ALL_TOPOLOGY;
|
||||
this._floorId = floorId;
|
||||
this._roomId = null;
|
||||
this._outside = false;
|
||||
@@ -187,6 +205,7 @@ export class NextFloorPanel extends LitElement {
|
||||
|
||||
/** The devices of Outside, worked out again only when the plan or the registry changes. */
|
||||
private outsideIds(building: Building): string[] {
|
||||
if(building.topology)return outsideEntities(this.hass,topologyOutsideFloors(building,this.topologySelection(building)),building.settings.outside_hidden);
|
||||
const m = this.outsideMemo;
|
||||
if (m && m.building === building && m.entities === this.hass.entities) return m.ids;
|
||||
const ids = outsideEntities(this.hass, building.floors, building.settings.outside_hidden);
|
||||
@@ -195,7 +214,15 @@ export class NextFloorPanel extends LitElement {
|
||||
}
|
||||
|
||||
/** Opens Outside over the house view (or closes it again). */
|
||||
private openOutside(): void {
|
||||
private openOutside(floorId?: string): void {
|
||||
const b=this.data.building;
|
||||
if(b?.topology){
|
||||
const path=topologyPath(b,floorId?floorSelection(b,floorId):this.topologySelection(b));
|
||||
const direct=path.find((n)=>n.selection.kind==="outside")?.selection;
|
||||
const owner=[...path].reverse().find((n)=>["building","branch","location"].includes(n.selection.kind)&&outsideFloor(b,outsideSelection(n.selection as OutsideOwner)));
|
||||
const target=direct??(owner?outsideSelection(owner.selection as OutsideOwner):path.find((n)=>n.selection.kind==="location")?.selection);
|
||||
if(target){const open=!this._outside;this.openTopology(target);this._outside=open;}return;
|
||||
}
|
||||
const open = !this._outside;
|
||||
this.openFloor(null);
|
||||
this._outside = open;
|
||||
@@ -204,7 +231,7 @@ export class NextFloorPanel extends LitElement {
|
||||
private onRoomTap(e: CustomEvent<{ floorId: string; roomId: string | null }>): void {
|
||||
const { floorId, roomId } = e.detail;
|
||||
// an outdoor area's pin opens Outside
|
||||
if (roomId === "nf-outside") return this.openOutside();
|
||||
if (roomId === "nf-outside") return this.openOutside(floorId);
|
||||
// in the house view, or on another floor, a tap opens the whole floor first and the rooms come next
|
||||
if ((this.data.building?.floors.length ?? 0) > 1 && floorId && this._floorId !== floorId) return this.openFloor(floorId);
|
||||
if (roomId) {
|
||||
@@ -256,6 +283,7 @@ export class NextFloorPanel extends LitElement {
|
||||
private back(): void {
|
||||
if (this._outside) this._outside = false;
|
||||
else if (this._roomId) this._roomId = null;
|
||||
else if(this.data.building?.topology && this.topologySelection(this.data.building).kind!=="all")this.openTopology(topologyParent(this.data.building,this.topologySelection(this.data.building)));
|
||||
else if (this._floorId && (this.data.building?.floors.length ?? 0) > 1) this._floorId = null;
|
||||
else this.view3d()?.resetView();
|
||||
}
|
||||
@@ -388,7 +416,7 @@ export class NextFloorPanel extends LitElement {
|
||||
${this.isAdmin && this.hass.symconRefresh ? html`<button class="nf-btn nf-reload-variables" ?disabled=${this._variablesLoading} aria-busy=${this._variablesLoading} @click=${() => void this.reloadVariables()}>↻ ${this.t(this._variablesLoading ? "symcon_variables_loading" : "symcon_variables_reload")}</button>` : nothing}
|
||||
${this._mode === "view" && building?.floors.some((f) => f.rooms.length) ? this.renderViewOptions() : nothing}
|
||||
${this._mode === "editor" && saveState !== "idle" ? html`<span class="nf-save nf-save-${saveState}">${this.t(saveLabel)}</span>` : nothing}
|
||||
<span class="nf-version" title=${this.t("version_hint", { backend: this.data.backendVersion ?? "?" })}>v${this.data.frontendVersion}</span>
|
||||
<span class="nf-version" title=${this.t(isSymcon(this.hass) ? "symcon_version_hint" : "version_hint", { backend: this.data.backendVersion ?? "?" })}>v${this.data.frontendVersion}</span>
|
||||
</header>`;
|
||||
}
|
||||
|
||||
@@ -397,7 +425,7 @@ export class NextFloorPanel extends LitElement {
|
||||
const d = this.data;
|
||||
const notices: TemplateResult[] = [];
|
||||
if (this._variablesNotice) notices.push(html`<div class="nf-notice ${this._variablesError ? "nf-notice-error" : ""}" role=${this._variablesError ? "alert" : "status"}>${this._variablesNotice}</div>`);
|
||||
if (d.needsRestart) {
|
||||
if (!isSymcon(this.hass) && d.needsRestart) {
|
||||
// an old bundle in the browser or the companion app is cured by a reload, not by a restart
|
||||
notices.push(
|
||||
d.versionGap === "frontend"
|
||||
@@ -486,6 +514,14 @@ export class NextFloorPanel extends LitElement {
|
||||
|
||||
/** The bar of floors and rooms above the stage. */
|
||||
private renderNav(building: Building) {
|
||||
if(building.topology){
|
||||
const floor=building.floors.find((f)=>f.id===this._floorId);
|
||||
if(!floor||isOutdoorFloor(floor))return nothing;
|
||||
return html`<nav class="nf-nav nf-topology-floor-nav" aria-label=${floor.name}>
|
||||
${floor.rooms.map((room)=>html`<button class="nf-chip nf-room-chip" aria-pressed=${room.id===this._roomId} @click=${()=>{this._roomId=this._roomId===room.id?null:room.id;this._outside=false;}}>${room.name}</button>`)}
|
||||
${this.allOffChip(building)}
|
||||
</nav>`;
|
||||
}
|
||||
const shown: Floor[] = building.floors.filter((f) => !this._floorId || f.id === this._floorId);
|
||||
const several = building.floors.length > 1;
|
||||
const wrap = this._prefs.navWrap;
|
||||
@@ -572,7 +608,7 @@ export class NextFloorPanel extends LitElement {
|
||||
}
|
||||
|
||||
private renderView(building: Building) {
|
||||
if (!building.floors.some((f) => f.rooms.length)) {
|
||||
if (!building.floors.some((f) => f.rooms.length || f.outdoor.length || f.furniture.length)) {
|
||||
return html`<div class="nf-empty">
|
||||
<p>${this.t(this.isAdmin ? (building.floors.length ? "no_rooms_admin" : "no_building_admin") : "no_building")}</p>
|
||||
${this.isAdmin ? html`<button class="nf-btn nf-primary" @click=${() => this.setMode("editor")}>${this.t("open_editor")}</button>` : nothing}
|
||||
@@ -589,6 +625,7 @@ export class NextFloorPanel extends LitElement {
|
||||
class="nf-body"
|
||||
.hass=${withSymconWeather(withCoverControls(this.hass, building.floors), building.settings)}
|
||||
.building=${building}
|
||||
.topologySelection=${this.topologySelection(building)}
|
||||
.packs=${this.data.packs}
|
||||
.floorStack=${p.floorStack}
|
||||
.roomLabels=${p.roomNames}
|
||||
@@ -597,7 +634,7 @@ export class NextFloorPanel extends LitElement {
|
||||
@clean-toggle=${() => this.setPref("clean", !p.clean)}
|
||||
?weather=${p.weather}
|
||||
.panelOpen=${!!this._roomId || this._outside}
|
||||
.floorId=${building.floors.length > 1 ? this._floorId : (building.floors[0]?.id ?? null)}
|
||||
.floorId=${building.topology || building.floors.length > 1 ? this._floorId : (building.floors[0]?.id ?? null)}
|
||||
.roomId=${this._roomId}
|
||||
.outsideOpen=${this._outside}
|
||||
.wallMode=${this._wallMode}
|
||||
@@ -631,6 +668,7 @@ export class NextFloorPanel extends LitElement {
|
||||
.quality=${p.quality}
|
||||
?showStats=${p.stats}
|
||||
@room-tap=${this.onRoomTap}
|
||||
@topology-tap=${(e: CustomEvent<TopologySelection>) => this.openTopology(e.detail)}
|
||||
@floor-tap=${(e: CustomEvent<{ floorId: string | null }>) => this.openFloor(e.detail.floorId)}
|
||||
@back=${() => this.back()}
|
||||
></nf-view3d>
|
||||
|
||||
@@ -1,12 +1,33 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { callSymcon } from "./symcon-api.ts";
|
||||
import { callSymcon, SymconAuthError } from "./symcon-api.ts";
|
||||
import { SymconBridge } from "./symcon-bridge.ts";
|
||||
|
||||
const settings = { endpoint: "/hook/fixture", token: "test-only" };
|
||||
const CHUNK_BYTES = 128 * 1024;
|
||||
const id = "0123456789abcdef0123456789abcdef";
|
||||
|
||||
test("authenticated calls use cookie credentials and a CSRF header, with no credential in the URL", async (context) => {
|
||||
context.mock.method(globalThis, "fetch", async (url: string, init: RequestInit) => {
|
||||
assert.equal(url, "/hook/fixture/api"); assert.equal(init.credentials, "same-origin");
|
||||
assert.equal((init.headers as Record<string, string>)["X-NextFloor-CSRF"], "csrf-fixture");
|
||||
return new Response("{\"revision\":1}");
|
||||
});
|
||||
assert.deepEqual(await callSymcon({ endpoint: "/hook/fixture", csrf: "csrf-fixture" }, "building/get"), { revision: 1 });
|
||||
});
|
||||
|
||||
test("an expired session is distinguished from a forbidden operation", async (context) => {
|
||||
context.mock.method(globalThis, "fetch", async () => new Response('{"error":"authentication_required"}', { status: 401 }));
|
||||
await assert.rejects(callSymcon({ endpoint: "/hook/fixture", csrf: "csrf-fixture" }, "bootstrap"), SymconAuthError);
|
||||
});
|
||||
|
||||
test("a replaced session clears stale tabs, while a denied control does not sign the user out", async (context) => {
|
||||
const mock = context.mock.method(globalThis, "fetch", async () => new Response('{"error":"csrf_invalid"}', { status: 403 }));
|
||||
await assert.rejects(callSymcon({ endpoint: "/hook/fixture", csrf: "old-csrf" }, "bootstrap"), SymconAuthError);
|
||||
mock.mock.mockImplementation(async () => new Response('{"error":"control_forbidden"}', { status: 403 }));
|
||||
await assert.rejects(callSymcon({ endpoint: "/hook/fixture", csrf: "current-csrf" }, "variables/action"), (e: Error) => !(e instanceof SymconAuthError) && e.message === "control_forbidden");
|
||||
});
|
||||
|
||||
test("small replies remain compatible and transport negotiation is explicit", async (context) => {
|
||||
context.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
|
||||
const request = JSON.parse(String(init.body));
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
// Bounded WebHook responses: Symcon's default PHP output limit is 1 MiB per request.
|
||||
export interface SymconEndpoint {
|
||||
endpoint: string;
|
||||
token: string;
|
||||
/** Legacy fixture/old-client support; current hosts authenticate with an HttpOnly cookie. */
|
||||
token?: string;
|
||||
csrf?: string;
|
||||
}
|
||||
|
||||
export class SymconAuthError extends Error {}
|
||||
|
||||
interface Transfer {
|
||||
id: string;
|
||||
bytes: number;
|
||||
@@ -15,13 +19,14 @@ const TRANSPORT = "nextfloor-chunks-v1";
|
||||
const MAX_TRANSFER_BYTES = 64 * 1024 * 1024;
|
||||
|
||||
async function request(settings: SymconEndpoint, action: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {
|
||||
const response = await fetch(`${settings.endpoint}/api?token=${encodeURIComponent(settings.token)}`, {
|
||||
const response = await fetch(`${settings.endpoint}/api${settings.csrf ? "" : settings.token ? `?token=${encodeURIComponent(settings.token)}` : ""}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||
headers: { "Content-Type": "application/json", Accept: "application/json", ...(settings.csrf ? { "X-NextFloor-CSRF": settings.csrf } : {}) },
|
||||
credentials: "same-origin",
|
||||
body: JSON.stringify({ ...payload, action, transport: TRANSPORT }),
|
||||
});
|
||||
const raw = await response.text();
|
||||
if (response.status === 401) throw new SymconAuthError("Die Anmeldung ist abgelaufen. Bitte erneut anmelden.");
|
||||
let body: unknown;
|
||||
try {
|
||||
body = JSON.parse(raw);
|
||||
@@ -33,6 +38,8 @@ async function request(settings: SymconEndpoint, action: string, payload: Record
|
||||
}
|
||||
if (!response.ok || !body || typeof body !== "object" || "error" in body) {
|
||||
const error = body && typeof body === "object" && "error" in body ? (body as { error?: unknown }).error : `HTTP ${response.status}`;
|
||||
// Another tab can replace the shared cookie with a different account. Clear this tab's old data too.
|
||||
if (error === "csrf_invalid") throw new SymconAuthError("Die Anmeldung hat sich geändert. Bitte erneut laden.");
|
||||
throw new Error(String(error));
|
||||
}
|
||||
return body as Record<string, unknown>;
|
||||
|
||||
@@ -20,6 +20,24 @@ test("configured view names are exposed to the header with a safe empty-name fal
|
||||
assert.equal(new SymconBridge().snapshot().symconTitle, "NextFloor");
|
||||
});
|
||||
|
||||
test("server roles control editor access and read-only role aliases cannot send commands", async (context) => {
|
||||
mockWindow(context);
|
||||
let commands = 0;
|
||||
context.mock.method(globalThis, "fetch", async (_url: string, init: RequestInit) => {
|
||||
const request = JSON.parse(String(init.body));
|
||||
if (request.action === "variables/action") { commands++; return new Response("{}"); }
|
||||
return new Response(JSON.stringify({ access: { id: "reader", name: "Leser", is_admin: false }, state_revision: 1, building_revision: 1, areas: [], objects: [],
|
||||
variables: [{ entity_id: "sensor.10", name: "Wert", state: "30", path: "Büro / Wert", attributes: { symcon_id: 10, symcon_variable_type: 2, symcon_numeric_value: 30, symcon_can_control: false } }] }));
|
||||
});
|
||||
const bridge = new SymconBridge();
|
||||
try {
|
||||
const h = await bridge.start();
|
||||
assert.equal(h.user?.is_admin, false); assert.equal(h.user?.name, "Leser");
|
||||
await assert.rejects(h.callService("light", "turn_on", { entity_id: "light.10" }), /nur die Anzeige/);
|
||||
assert.equal(commands, 0);
|
||||
} finally { bridge.stop(); }
|
||||
});
|
||||
|
||||
test("numeric control roles stay selectable in the real tree without duplicating automatic device lists", async (context) => {
|
||||
mockWindow(context);
|
||||
context.mock.method(globalThis, "fetch", async () => new Response(JSON.stringify({ state_revision: 1, building_revision: 1, areas: [{ area_id: "room", name: "Raum" }],
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
// only ever shows and selects their object-tree path. The numeric object id stays an implementation detail.
|
||||
|
||||
import type { HassArea, HassEntity, HassEntityEntry, HomeAssistant, SymconObject } from "./types.ts";
|
||||
import { callSymcon as call } from "./symcon-api.ts";
|
||||
import { callSymcon as call, SymconAuthError } from "./symcon-api.ts";
|
||||
import { symconControl } from "./symcon-controls.ts";
|
||||
|
||||
interface SymconConfig {
|
||||
endpoint: string;
|
||||
token: string;
|
||||
token?: string;
|
||||
csrf?: string;
|
||||
user?: { id: string; name: string; is_admin: boolean; view_all?: boolean; control_all?: boolean; can_control?: boolean };
|
||||
language?: string;
|
||||
title?: string;
|
||||
}
|
||||
@@ -26,6 +28,7 @@ interface SymconVariable {
|
||||
}
|
||||
|
||||
interface Bootstrap {
|
||||
access?: { id: string; name: string; is_admin: boolean };
|
||||
state_revision: number;
|
||||
building_revision: number;
|
||||
variables: SymconVariable[];
|
||||
@@ -52,7 +55,7 @@ declare global {
|
||||
|
||||
function config(): SymconConfig {
|
||||
const settings = window.__NEXTFLOOR_SYMCON__;
|
||||
if (!settings?.endpoint || !settings.token) throw new Error("NextFloor Symcon host configuration is missing");
|
||||
if (!settings?.endpoint || (!settings.csrf && !settings.token)) throw new Error("NextFloor Symcon host configuration is missing");
|
||||
return settings;
|
||||
}
|
||||
|
||||
@@ -62,6 +65,7 @@ function config(): SymconConfig {
|
||||
* unauthenticated JSON-RPC port to the browser. The module returns only variables from the object tree.
|
||||
*/
|
||||
export class SymconBridge {
|
||||
onExpired?: () => void;
|
||||
private readonly settings = config();
|
||||
private readonly changeListeners = new Set<Listener>();
|
||||
private readonly buildingListeners = new Set<BuildingListener>();
|
||||
@@ -76,7 +80,7 @@ export class SymconBridge {
|
||||
|
||||
private readonly facade: HomeAssistant = {
|
||||
language: this.settings.language || navigator.language || "de",
|
||||
user: { is_admin: true, name: this.settings.title || "IP-Symcon" },
|
||||
user: this.settings.user ?? { is_admin: false, name: "IP-Symcon" },
|
||||
states: this.states,
|
||||
entities: this.entities,
|
||||
areas: this.areas,
|
||||
@@ -106,10 +110,13 @@ export class SymconBridge {
|
||||
/** Read the initial object tree and begin refreshing changed values. */
|
||||
async start(): Promise<HomeAssistant> {
|
||||
const initial = await call<Bootstrap>(this.settings, "bootstrap");
|
||||
if (initial.access) this.facade.user = initial.access;
|
||||
this.apply(initial);
|
||||
this.stateRevision = initial.state_revision;
|
||||
this.buildingRevision = initial.building_revision;
|
||||
this.timer = setInterval(() => void this.refresh().catch(() => undefined), 800);
|
||||
this.timer = setInterval(() => void this.refresh().catch((error) => {
|
||||
if (error instanceof SymconAuthError) { this.stop(); this.states = {}; this.entities = {}; this.onExpired?.(); }
|
||||
}), 800);
|
||||
return this.snapshot();
|
||||
}
|
||||
|
||||
@@ -204,13 +211,15 @@ export class SymconBridge {
|
||||
}
|
||||
|
||||
private async callService(domain: string, service: string, data: Record<string, unknown> = {}): Promise<unknown> {
|
||||
const ids = Array.isArray(data.entity_id) ? data.entity_id : [data.entity_id];
|
||||
if (ids.some((id) => typeof id !== "string" || this.states[id]?.attributes.symcon_can_control === false)) throw new Error("Für dieses Gerät ist nur die Anzeige freigegeben.");
|
||||
return call(this.settings, "variables/action", { domain, service, data });
|
||||
}
|
||||
|
||||
/** Mesh uploads are intentionally not exposed until the Symcon asset store exists. Other paths stay same-origin. */
|
||||
private fetchWithToken(path: string, init: Record<string, unknown> = {}): Promise<Response> {
|
||||
const url = new URL(path, window.location.origin);
|
||||
url.searchParams.set("token", this.settings.token);
|
||||
if (!this.settings.csrf && this.settings.token) url.searchParams.set("token", this.settings.token);
|
||||
return fetch(url, { ...init, credentials: "same-origin" });
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
import "./main.ts";
|
||||
import { SymconBridge } from "./symcon-bridge.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
import { SymconAuthError } from "./symcon-api.ts";
|
||||
|
||||
type SymconPanel = HTMLElement & { hass: HomeAssistant; narrow: boolean };
|
||||
type SymconCard = HTMLElement & { hass: HomeAssistant; setConfig(config: Record<string, unknown>): void };
|
||||
@@ -13,7 +14,11 @@ function pageMode(): "designer" | "tile" {
|
||||
}
|
||||
|
||||
async function mount(): Promise<void> {
|
||||
// Old admin drafts must not survive a switch to a more restricted account in the same browser.
|
||||
try { localStorage.removeItem("nextfloor.unsaved"); } catch { /* storage may be disabled */ }
|
||||
const bridge = new SymconBridge();
|
||||
const settings = window.__NEXTFLOOR_SYMCON__!;
|
||||
bridge.onExpired = () => { document.body.replaceChildren(); window.location.replace(`${settings.endpoint}/login?mode=${pageMode()}`); };
|
||||
const hass = await bridge.start();
|
||||
const tile = pageMode() === "tile";
|
||||
const app = (tile ? document.createElement("nextfloor-card") : document.createElement("nextfloor-panel")) as SymconCard & SymconPanel;
|
||||
@@ -22,15 +27,25 @@ async function mount(): Promise<void> {
|
||||
if (tile) {
|
||||
(app as SymconCard).setConfig({ type: "custom:nextfloor-card", fill: true, room_buttons: true, controls: true, weather: false, announcements: false });
|
||||
} else {
|
||||
(app as SymconPanel).narrow = false;
|
||||
(app as SymconPanel).narrow = window.innerWidth < 870;
|
||||
}
|
||||
document.body.replaceChildren(app);
|
||||
const resize = () => { if (!tile) (app as SymconPanel).narrow = window.innerWidth < 870; };
|
||||
window.addEventListener("resize", resize);
|
||||
const bar = document.createElement("nav"); bar.className = "nf-session-bar"; bar.setAttribute("aria-label", "Benutzerkonto");
|
||||
const identity = document.createElement("span"); identity.textContent = `${hass.user?.name ?? ""} · ${hass.user?.is_admin ? "Administrator" : settings.user?.can_control === false ? "Nur ansehen" : settings.user?.control_all ? "Bedienung" : settings.user?.view_all ? "Ansicht und freigegebene Bedienung" : "Freigegebene Räume / Geräte"}`;
|
||||
const form = document.createElement("form"); form.method = "post"; form.action = `${settings.endpoint}/logout?mode=${pageMode()}`;
|
||||
const csrf = document.createElement("input"); csrf.type = "hidden"; csrf.name = "csrf"; csrf.value = settings.csrf || "";
|
||||
const logout = document.createElement("button"); logout.type = "submit"; logout.textContent = "Abmelden";
|
||||
form.append(csrf, logout); bar.append(identity, form);
|
||||
document.body.replaceChildren(bar, app);
|
||||
bridge.onChange(() => {
|
||||
app.hass = bridge.snapshot();
|
||||
});
|
||||
window.addEventListener("pagehide", () => bridge.stop(), { once: true });
|
||||
window.addEventListener("pagehide", () => { bridge.stop(); window.removeEventListener("resize", resize); document.body.replaceChildren(); }, { once: true });
|
||||
window.addEventListener("pageshow", (event) => { if (event.persisted) location.reload(); });
|
||||
}
|
||||
|
||||
void mount().catch((error: unknown) => {
|
||||
if (error instanceof SymconAuthError) { window.location.replace(`${window.__NEXTFLOOR_SYMCON__!.endpoint}/login?mode=${pageMode()}`); return; }
|
||||
document.body.textContent = `NextFloor konnte nicht geladen werden: ${error instanceof Error ? error.message : String(error)}`;
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { emptyBuilding, newFloor, normalizeBuilding } from "./model.ts";
|
||||
import { ALL_TOPOLOGY, addLocationOutside, addTopologyOutside, enableTopology, floorSelection, floorTopologyPath, isOutdoorFloor, normalizeTopology, outsideSelection, topologyFloors, topologyItems, topologyKey, topologyOutsideFloors, topologyParent, topologyPath, topologyTree } from "./topology.ts";
|
||||
import { copyOfFloor, newFloorFor } from "./components/editor/ops/floors.ts";
|
||||
import { translate } from "./components/editor/ops/transform.ts";
|
||||
import { box } from "./entities/fixtures.ts";
|
||||
import { buildRoof } from "./viewer/roof.ts";
|
||||
|
||||
function project(){
|
||||
const b=emptyBuilding();
|
||||
b.topology={locations:[{id:"urbach",name:"Urbach"},{id:"ulm",name:"Ulm"}],branches:[{id:"hq",name:"Zentrale",location_id:"urbach"},{id:"west",name:"West",location_id:"urbach"},{id:"south",name:"Süd",location_id:"ulm"}],buildings:[{id:"ras19",name:"RAS19",branch_id:"hq"},{id:"ras21",name:"RAS21",branch_id:"west"},{id:"ulm1",name:"RAS19",branch_id:"south"}]};
|
||||
b.floors=[{...newFloor("eg","EG",0),building_id:"ras19",rooms:[{...box("it",0,0,4,3),name:"IT"}]},{...newFloor("og","OG",3),building_id:"ras19"},{...newFloor("west-eg","EG",0),building_id:"ras21",rooms:[{...box("it-west",30,0,4,3),name:"IT"}]},{...newFloor("ulm-eg","EG",0),building_id:"ulm1",rooms:[{...box("it-ulm",60,0,4,3),name:"IT"}]}];
|
||||
return b;
|
||||
}
|
||||
|
||||
test("legacy plans are unchanged until topology is enabled; enabling preserves geometry, links and stable grant keys",()=>{
|
||||
const b=emptyBuilding();b.floors=[{...newFloor("old","EG",0),rooms:[{...box("room",0,0,4,3),area_id:"symcon-category-100"}]}];
|
||||
normalizeBuilding(b);const before=structuredClone(b);assert.equal(b.topology,undefined);
|
||||
enableTopology(b,"RAS19");assert.equal(b.topology!.buildings[0].name,"RAS19");
|
||||
assert.equal(b.floors[0].id,"old");assert.deepEqual(b.floors[0].rooms,before.floors[0].rooms);
|
||||
const t=structuredClone(b.topology);enableTopology(b);assert.deepEqual(b.topology,t);
|
||||
});
|
||||
|
||||
test("location / branch / building / floor / room is a full unambiguous path even with repeated labels",()=>{
|
||||
const b=project();
|
||||
assert.equal(floorTopologyPath(b,b.floors[0]),"Urbach / Zentrale / RAS19 / EG");
|
||||
assert.deepEqual(topologyPath(b,{kind:"room",id:"it",floorId:"eg"}).slice(1).map((n)=>n.name),["Urbach","Zentrale","RAS19","EG","IT"]);
|
||||
assert.deepEqual(topologyItems(b,{kind:"location",id:"urbach"}).map((n)=>n.name),["Zentrale","West"]);
|
||||
assert.deepEqual(topologyItems(b,{kind:"building",id:"ras19"}).map((n)=>n.name),["OG","EG"]);
|
||||
assert.deepEqual(topologyItems(b,{kind:"floor",id:"eg"}).map((n)=>n.name),["IT"]);
|
||||
assert.deepEqual(topologyParent(b,{kind:"building",id:"ras19"}),{kind:"branch",id:"hq"});
|
||||
assert.deepEqual(topologyParent(b,{kind:"location",id:"urbach"}),ALL_TOPOLOGY);
|
||||
});
|
||||
|
||||
test("scope membership excludes other branches and locations, and selected floor stacks stay inside their building",()=>{
|
||||
const b=project(),ids=(s:Parameters<typeof topologyFloors>[1],stack=false)=>topologyFloors(b,s,stack).map((f)=>f.id);
|
||||
assert.deepEqual(ids({kind:"location",id:"urbach"}),["eg","og","west-eg"]);
|
||||
assert.deepEqual(ids({kind:"branch",id:"hq"}),["eg","og"]);
|
||||
assert.deepEqual(ids({kind:"floor",id:"eg"}),["eg"]);
|
||||
assert.deepEqual(ids({kind:"room",id:"it",floorId:"eg"},true),["eg","og"]);
|
||||
assert.deepEqual(ids({kind:"building",id:"ulm1"}),["ulm-eg"]);
|
||||
assert.deepEqual(topologyPath(b,{kind:"building",id:"deleted"}).map((n)=>n.selection.kind),["all"]);
|
||||
});
|
||||
|
||||
test("each location has a separate outdoor plan, with no building parent or duplicated creation",()=>{
|
||||
const b=project(),a=addLocationOutside(b,"urbach"),z=addLocationOutside(b,"ulm");
|
||||
assert.notEqual(a.id,z.id);assert.equal(addLocationOutside(b,"urbach"),a);assert.equal(a.building_id,null);
|
||||
assert.deepEqual(topologyFloors(b,{kind:"outside",id:"urbach"}).map((f)=>f.id),[a.id]);
|
||||
assert.ok(!topologyFloors(b,{kind:"building",id:"ras19"}).includes(a));
|
||||
assert.ok(!topologyFloors(b,{kind:"location",id:"urbach"}).includes(z));
|
||||
assert.deepEqual(floorSelection(b,a.id),{kind:"outside",id:"urbach"});
|
||||
assert.equal(topologyItems(b,{kind:"location",id:"urbach"}).at(-1)!.selection.kind,"outside");
|
||||
a.rooms=[box("patio",0,0,4,3)];
|
||||
assert.equal(topologyPath(b,{kind:"room",id:"patio",floorId:a.id}).at(-1)!.name,"patio");
|
||||
assert.deepEqual(topologyFloors(b,{kind:"room",id:"patio",floorId:a.id},true).map((f)=>f.id),[a.id]);
|
||||
assert.deepEqual(topologyOutsideFloors(b,{kind:"outside",id:"urbach"}).map((f)=>f.id),["eg","og","west-eg",a.id]);
|
||||
assert.deepEqual(topologyOutsideFloors(b,{kind:"floor",id:"ulm-eg"}).map((f)=>f.id),["ulm-eg",z.id]);
|
||||
});
|
||||
|
||||
test("topology and memberships survive roundtrip; orphan parents are repaired without dropping a floor",()=>{
|
||||
const b=project();addLocationOutside(b,"urbach");
|
||||
const saved=normalizeBuilding(JSON.parse(JSON.stringify(b)));assert.deepEqual(saved.topology,b.topology);
|
||||
assert.equal(saved.floors[0].building_id,"ras19");
|
||||
saved.floors[0].building_id="removed-building";saved.topology!.branches[0].location_id="removed-location";
|
||||
normalizeTopology(saved);
|
||||
assert.ok(saved.topology!.buildings.some((g)=>g.id==="removed-building"));
|
||||
assert.ok(saved.topology!.locations.some((l)=>l.id==="removed-location"));
|
||||
assert.deepEqual(new Set(topologyTree(saved).floorIds),new Set(saved.floors.map((f)=>f.id)));
|
||||
});
|
||||
|
||||
test("new/copied floors use their own building's elevation; a whole-building move leaves other sites unchanged",()=>{
|
||||
const b=project();b.floors[3].elevation=50;
|
||||
const f=newFloorFor(b,null,{first:"EG",next:(n)=>`Etage ${n}`},"ras19");
|
||||
assert.equal(f.building_id,"ras19");assert.equal(f.elevation,5.75);
|
||||
assert.equal(copyOfFloor(b,b.floors[0],"Kopie",{furniture:false,devices:false,outdoor:false}).elevation,5.5);
|
||||
const other=structuredClone(b.floors[3]);
|
||||
translate(b,{floorId:"eg",allFloors:true,floorIds:topologyFloors(b,{kind:"building",id:"ras19"}).map((f)=>f.id)},10,20);
|
||||
assert.deepEqual(b.floors[0].rooms[0].points[0],[10,20]);assert.deepEqual(b.floors[3],other);
|
||||
});
|
||||
|
||||
test("automatic roofs cover each building independently and leave location outdoors uncovered",()=>{
|
||||
const b=project();b.settings.roof={type:"flat",pitch:0,overhang:.2};addLocationOutside(b,"urbach");
|
||||
assert.deepEqual(buildRoof(b).map((p)=>p.floor.building_id).sort(),["ras19","ras21","ulm1"]);
|
||||
assert.equal(buildRoof({...b,floors:b.floors.filter((f)=>!!f.outdoor_location_id)}).length,0);
|
||||
});
|
||||
|
||||
test("locations, branches and buildings own independent outdoor plans with unambiguous paths and scene membership",()=>{
|
||||
const b=project(),location=addLocationOutside(b,"urbach"),branch=addTopologyOutside(b,{kind:"branch",id:"hq"}),building=addTopologyOutside(b,{kind:"building",id:"ras19"});
|
||||
assert.equal(addTopologyOutside(b,{kind:"branch",id:"hq"}),branch);
|
||||
assert.equal(addTopologyOutside(b,{kind:"building",id:"ras19"}),building);
|
||||
assert.deepEqual(topologyPath(b,floorSelection(b,branch.id)).slice(1).map((n)=>n.name),["Urbach","Zentrale","Außen"]);
|
||||
assert.equal(floorTopologyPath(b,building),"Urbach / Zentrale / RAS19 / Außen");
|
||||
assert.deepEqual(topologyParent(b,floorSelection(b,building.id)),{kind:"building",id:"ras19"});
|
||||
const branchIds=topologyFloors(b,{kind:"branch",id:"hq"}).map((f)=>f.id);
|
||||
assert.ok(branchIds.includes(branch.id)&&branchIds.includes(building.id)&&!branchIds.includes(location.id)&&!branchIds.includes("west-eg"));
|
||||
assert.deepEqual(topologyFloors(b,floorSelection(b,branch.id)).map((f)=>f.id),[branch.id]);
|
||||
building.rooms=[box("garden-room",0,0,3,3)];
|
||||
assert.deepEqual(topologyFloors(b,floorSelection(b,building.id,"garden-room"),true).map((f)=>f.id),[building.id],"a room in an outdoor plan does not accidentally render indoor floors");
|
||||
assert.deepEqual(new Set(topologyOutsideFloors(b,floorSelection(b,building.id)).map((f)=>f.id)),new Set(["eg","og",building.id]));
|
||||
assert.equal(new Set(["location","branch","building"].map((kind)=>topologyKey(outsideSelection({kind:kind as "location"|"branch"|"building",id:"same"})))).size,3);
|
||||
normalizeBuilding(b);const saved=normalizeBuilding(JSON.parse(JSON.stringify(b)));
|
||||
assert.equal(saved.floors.find((f)=>f.id===branch.id)?.outdoor_branch_id,"hq");
|
||||
assert.equal(saved.floors.find((f)=>f.id===building.id)?.outdoor_building_id,"ras19");
|
||||
b.settings.roof.type="gable";
|
||||
assert.equal(buildRoof({...b,floors:b.floors.filter(isOutdoorFloor)}).length,0);
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { newFloor, uid, type Building, type Floor, type PlanTopology } from "./model.ts";
|
||||
|
||||
export type TopologyKind = "all" | "location" | "branch" | "building" | "floor" | "room" | "outside";
|
||||
export type OutsideOwnerKind = "location" | "branch" | "building";
|
||||
export interface OutsideOwner { kind: OutsideOwnerKind; id: string }
|
||||
export interface TopologySelection { kind: TopologyKind; id?: string; floorId?: string; ownerKind?: OutsideOwnerKind }
|
||||
export interface TopologyNode {
|
||||
key: string; name: string; selection: TopologySelection; floorIds: string[]; children: TopologyNode[];
|
||||
room?: { floorId: string; roomId: string };
|
||||
}
|
||||
export const ALL_TOPOLOGY: TopologySelection = { kind: "all" };
|
||||
export const topologyKey = (s: TopologySelection): string => [s.kind, s.ownerKind, s.floorId, s.id].filter(Boolean).join(":");
|
||||
export function outdoorOwner(f: Floor | undefined): OutsideOwner | null {
|
||||
return f?.outdoor_building_id ? {kind:"building",id:f.outdoor_building_id}
|
||||
: f?.outdoor_branch_id ? {kind:"branch",id:f.outdoor_branch_id}
|
||||
: f?.outdoor_location_id ? {kind:"location",id:f.outdoor_location_id} : null;
|
||||
}
|
||||
export const isOutdoorFloor = (f: Floor | undefined): boolean => !!outdoorOwner(f);
|
||||
export const outsideSelection = (owner: OutsideOwner): TopologySelection => ({kind:"outside",id:owner.id,...(owner.kind!=="location"?{ownerKind:owner.kind}:{})});
|
||||
export function outsideFloor(b: Building, s: TopologySelection): Floor | undefined {
|
||||
return s.kind==="outside" ? b.floors.find((f)=>{const o=outdoorOwner(f);return o?.kind===(s.ownerKind??"location")&&o.id===s.id;}) : undefined;
|
||||
}
|
||||
|
||||
/** Enable the hierarchy without moving geometry or changing the stable floor/room IDs used by grants. */
|
||||
export function enableTopology(b: Building, name = "Gebäude 1"): void {
|
||||
if (b.topology) return;
|
||||
const location = uid("location"), branch = uid("branch"), building = uid("building");
|
||||
b.topology = { locations:[{id:location,name:"Ort 1"}], branches:[{id:branch,name:"Niederlassung 1",location_id:location}], buildings:[{id:building,name,branch_id:branch}] };
|
||||
for (const f of b.floors) f.building_id = building;
|
||||
}
|
||||
|
||||
/** Recover orphan parents rather than silently hiding their floors after an imported/older plan. */
|
||||
export function normalizeTopology(b: Building): void {
|
||||
const t = b.topology!;
|
||||
t.locations ??= []; t.branches ??= []; t.buildings ??= [];
|
||||
const location = (id?: string) => {
|
||||
id ||= t.locations[0]?.id || uid("location");
|
||||
if (!t.locations.some((x)=>x.id===id)) t.locations.push({id,name:"Ort"});
|
||||
return id;
|
||||
};
|
||||
const branch = (id?: string) => {
|
||||
id ||= t.branches[0]?.id || uid("branch");
|
||||
if (!t.branches.some((x)=>x.id===id)) t.branches.push({id,name:"Niederlassung",location_id:location()});
|
||||
return id;
|
||||
};
|
||||
const building = (id?: string | null) => {
|
||||
id ||= t.buildings[0]?.id || uid("building");
|
||||
if (!t.buildings.some((x)=>x.id===id)) t.buildings.push({id,name:"Gebäude",branch_id:branch()});
|
||||
return id;
|
||||
};
|
||||
for (const s of t.branches) s.location_id = location(s.location_id);
|
||||
for (const s of t.buildings) s.branch_id = branch(s.branch_id);
|
||||
for (const f of b.floors) {
|
||||
const owner=outdoorOwner(f);
|
||||
if (owner) {
|
||||
const id=owner.kind==="building"?building(owner.id):owner.kind==="branch"?branch(owner.id):location(owner.id);
|
||||
f.outdoor_location_id=owner.kind==="location"?id:null;
|
||||
f.outdoor_branch_id=owner.kind==="branch"?id:null;
|
||||
f.outdoor_building_id=owner.kind==="building"?id:null;
|
||||
f.building_id=null;
|
||||
} else f.building_id=building(f.building_id);
|
||||
}
|
||||
}
|
||||
|
||||
export function addLocationOutside(b: Building, locationId: string): Floor {
|
||||
return addTopologyOutside(b,{kind:"location",id:locationId});
|
||||
}
|
||||
export function addTopologyOutside(b: Building, owner: OutsideOwner): Floor {
|
||||
const found=outsideFloor(b,outsideSelection(owner));
|
||||
if(found)return found;
|
||||
const f={...newFloor(uid("outside"),"Außen",0),[owner.kind==="building"?"outdoor_building_id":owner.kind==="branch"?"outdoor_branch_id":"outdoor_location_id"]:owner.id,building_id:null};
|
||||
b.floors.push(f);return f;
|
||||
}
|
||||
|
||||
export function floorSelection(b: Building, floorId: string, roomId?: string | null): TopologySelection {
|
||||
const f=b.floors.find((f)=>f.id===floorId);
|
||||
const owner=outdoorOwner(f);
|
||||
return roomId ? {kind:"room",id:roomId,floorId} : owner ? outsideSelection(owner) : {kind:"floor",id:floorId};
|
||||
}
|
||||
|
||||
export function topologyTree(b: Building): TopologyNode {
|
||||
const make=(kind:TopologyKind,id:string|undefined,name:string,children:TopologyNode[]=[],floorIds=children.flatMap((c)=>c.floorIds),room?:TopologyNode["room"]):TopologyNode=>{
|
||||
const selection:TopologySelection={kind,...(id?{id}:{}),...(room?{floorId:room.floorId}:{})};
|
||||
return {key:topologyKey(selection),name,selection,floorIds:[...new Set(floorIds)],children,...(room?{room}:{})};
|
||||
};
|
||||
const floorNode=(f:Floor)=>make("floor",f.id,f.name,f.rooms.map((r)=>make("room",r.id,r.name,[],[f.id],{floorId:f.id,roomId:r.id})),[f.id]);
|
||||
if(!b.topology)return make("all",undefined,"Alle Etagen",[...b.floors].sort((a,z)=>z.elevation-a.elevation).map(floorNode));
|
||||
const t=b.topology;
|
||||
const withOutside=(owner:OutsideOwner,children:TopologyNode[]):TopologyNode[]=>{
|
||||
const f=outsideFloor(b,outsideSelection(owner));if(!f)return children;
|
||||
const node=make("outside",owner.id,"Außen",f.rooms.map((r)=>make("room",r.id,r.name,[],[f.id],{floorId:f.id,roomId:r.id})),[f.id]);
|
||||
node.selection=outsideSelection(owner);node.key=topologyKey(node.selection);
|
||||
return [...children,node];
|
||||
};
|
||||
const buildingNode=(g:PlanTopology["buildings"][number]):TopologyNode=>{
|
||||
const floors=b.floors.filter((f)=>!isOutdoorFloor(f)&&f.building_id===g.id).sort((a,z)=>z.elevation-a.elevation);
|
||||
return make("building",g.id,g.name,withOutside({kind:"building",id:g.id},floors.map(floorNode)));
|
||||
};
|
||||
const branchNode=(n:PlanTopology["branches"][number]):TopologyNode=>make("branch",n.id,n.name,
|
||||
withOutside({kind:"branch",id:n.id},t.buildings.filter((g)=>g.branch_id===n.id).map(buildingNode)));
|
||||
return make("all",undefined,"Alle Orte",t.locations.map((l)=>make("location",l.id,l.name,
|
||||
withOutside({kind:"location",id:l.id},t.branches.filter((n)=>n.location_id===l.id).map(branchNode)))));
|
||||
}
|
||||
|
||||
export function topologyPath(b:Building,s:TopologySelection):TopologyNode[] {
|
||||
const root=topologyTree(b),key=topologyKey(s);
|
||||
const visit=(node:TopologyNode):TopologyNode[]|null=>{
|
||||
if(node.key===key)return [node];
|
||||
for(const c of node.children){const path=visit(c);if(path)return [node,...path];}
|
||||
return null;
|
||||
};
|
||||
return visit(root)??[root];
|
||||
}
|
||||
export const topologyNode=(b:Building,s:TopologySelection):TopologyNode=>topologyPath(b,s).at(-1)!;
|
||||
export const topologyParent=(b:Building,s:TopologySelection):TopologySelection=>topologyPath(b,s).at(-2)?.selection??ALL_TOPOLOGY;
|
||||
export function topologyItems(b:Building,s:TopologySelection):TopologyNode[] {
|
||||
const path=topologyPath(b,s),node=path.at(-1)!;
|
||||
return node.selection.kind==="room" ? path.at(-2)!.children : !node.children.length&&["floor","outside"].includes(node.selection.kind)?[node]:node.children;
|
||||
}
|
||||
/** A floor/room keeps its own building's stack; higher levels isolate exactly their descendants. */
|
||||
export function topologyFloors(b:Building,s:TopologySelection,withStack=false):Floor[] {
|
||||
if(!b.topology||s.kind==="all")return b.floors;
|
||||
const path=topologyPath(b,s);
|
||||
const node=(withStack&&(s.kind==="floor"||s.kind==="room")?path.find((n)=>n.selection.kind==="outside")??path.find((n)=>n.selection.kind==="building"):null)??path.at(-1)!;
|
||||
const ids=new Set(node.floorIds);return b.floors.filter((f)=>ids.has(f.id));
|
||||
}
|
||||
export const topologyPlan=(b:Building,s:TopologySelection,withStack=false):Building=>({...b,floors:topologyFloors(b,s,withStack)});
|
||||
/** Outside views cover only their owner's descendants, including legacy outdoor pins on indoor floors. */
|
||||
export function topologyOutsideFloors(b:Building,s:TopologySelection):Floor[] {
|
||||
if(!b.topology)return b.floors;
|
||||
const path=topologyPath(b,s),outside=path.find((n)=>n.selection.kind==="outside");
|
||||
if(outside){const owner=topologyParent(b,outside.selection);return topologyFloors(b,owner);}
|
||||
const location=path.find((n)=>n.selection.kind==="location");
|
||||
return location?topologyFloors(b,location.selection):[];
|
||||
}
|
||||
export function floorTopologyPath(b:Building,f:Floor):string {
|
||||
return b.topology?topologyPath(b,floorSelection(b,f.id)).slice(1).map((n)=>n.name).join(" / "):f.name;
|
||||
}
|
||||
export const emptyTopology=():PlanTopology=>({locations:[],branches:[],buildings:[]});
|
||||
@@ -190,8 +190,7 @@ export function floorUtilityReadings(hass: HomeAssistant, floor: Floor, rooms: r
|
||||
}
|
||||
|
||||
/** Sum the effective floor meters; shared native sources count only once for the building. */
|
||||
export function buildingUtilityReadings(hass: HomeAssistant, floors: readonly Floor[]): UtilityReading[] {
|
||||
const rooms = floors.flatMap((f) => f.rooms);
|
||||
export function buildingUtilityReadings(hass: HomeAssistant, floors: readonly Floor[], rooms: readonly Room[] = floors.flatMap((f) => f.rooms)): UtilityReading[] {
|
||||
const sources = floors.flatMap((f) => floorUtilityReadings(hass, f, rooms).flatMap((r) => r.sources.map((id) => ({ kind: r.kind, metric: r.metric, period: r.period, id }))));
|
||||
return readings(hass, sources);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { emptyBuilding, newFloor, UTILITY_KINDS, type UtilityKind } from "./model.ts";
|
||||
import { box, entity, hassOf } from "./entities/fixtures.ts";
|
||||
import { addTopologyOutside, outsideSelection } from "./topology.ts";
|
||||
import { utilityScope } from "./utility-scope.ts";
|
||||
import type { HomeAssistant, SymconObject } from "./types.ts";
|
||||
|
||||
function project(){
|
||||
const b=emptyBuilding(),states:ReturnType<typeof entity>[]=[];
|
||||
b.topology={locations:[{id:"u",name:"Urbach"},{id:"x",name:"Ulm"}],branches:[{id:"hq",name:"Zentrale",location_id:"u"},{id:"other",name:"Andere Niederlassung",location_id:"u"},{id:"south",name:"Süd",location_id:"x"}],buildings:[{id:"a",name:"RAS19",branch_id:"hq"},{id:"b",name:"RAS21",branch_id:"hq"},{id:"foreign",name:"Fremd",branch_id:"other"},{id:"distant",name:"Fern",branch_id:"south"}]};
|
||||
b.floors=[...[["a-eg","a",1],["a-og","a",2],["b-eg","b",3],["foreign-eg","foreign",40],["distant-eg","distant",100]].map(([id,parent,n],i)=>{
|
||||
const f={...newFloor(String(id),i===1?"OG":"EG",i===1?3:0),building_id:String(parent)};
|
||||
for(const [k,kind]of UTILITY_KINDS.entries()){
|
||||
const power=`sensor.${1000+i*100+k*2}`,energy=`sensor.${1001+i*100+k*2}`;
|
||||
const st=(id:string,value:number,unit:string)=>entity(id,String(value),{symcon_id:Number(id.slice(7)),symcon_variable_type:2,symcon_value:value,unit_of_measurement:unit});
|
||||
states.push(st(power,Number(n)*(k+1),kind==="water"||kind==="gas"?"m³/h":"kW"),st(energy,Number(n)*10*(k+1),kind==="water"||kind==="gas"?"m³":"kWh"));
|
||||
f.utility_meters={...f.utility_meters,[kind]:{power,energy}};
|
||||
}return f;
|
||||
})];
|
||||
const hass=hassOf(states,{}, {symconObjects:[],language:"de"});return {b,hass};
|
||||
}
|
||||
const value=(scope:ReturnType<typeof utilityScope>,kind:UtilityKind,metric:"power"|"energy")=>scope.totals.find((r)=>r.kind===kind&&r.metric===metric)?.value;
|
||||
|
||||
test("a branch lists its buildings with both metrics for all media and sums only its own descendants",()=>{
|
||||
const {b,hass}=project(),scope=utilityScope(hass,b,{kind:"branch",id:"hq"});
|
||||
assert.equal(scope.heading,"Gebäude");assert.equal(scope.name,"Zentrale");assert.equal(scope.floorId,null);
|
||||
assert.deepEqual(scope.entries.map((e)=>[e.name,e.selection]),[["RAS19",{kind:"building",id:"a"}],["RAS21",{kind:"building",id:"b"}]]);
|
||||
for(const [i,kind]of UTILITY_KINDS.entries()){
|
||||
assert.equal(value(scope,kind,"power"),6*(i+1)*(kind==="water"||kind==="gas"?1:1000));
|
||||
assert.equal(value(scope,kind,"energy"),60*(i+1));
|
||||
assert.equal(scope.entries[0].readings.find((r)=>r.kind===kind&&r.metric==="energy")?.value,30*(i+1));
|
||||
}
|
||||
});
|
||||
test("building, location and root overviews show their immediate level and floors retain their area breakdown",()=>{
|
||||
const {b,hass}=project(),building=utilityScope(hass,b,{kind:"building",id:"a"});
|
||||
assert.equal(building.heading,"Stockwerke");assert.equal(building.name,"RAS19");
|
||||
assert.deepEqual(building.entries.map((e)=>e.selection),[{kind:"floor",id:"a-og"},{kind:"floor",id:"a-eg"}]);
|
||||
assert.ok(building.entries[0].readings.every((r)=>r.manual),"a storey's own meter keeps its override metadata in the building breakdown");
|
||||
assert.equal(value(building,"electricity","energy"),30);
|
||||
assert.equal(utilityScope(hass,b,{kind:"location",id:"u"}).heading,"Niederlassungen");
|
||||
assert.deepEqual(utilityScope(hass,b,{kind:"location",id:"u"}).entries.map((e)=>e.name),["Zentrale","Andere Niederlassung"]);
|
||||
assert.equal(utilityScope(hass,b,{kind:"all"}).heading,"Orte");
|
||||
const floor=utilityScope(hass,b,{kind:"floor",id:"a-eg"});assert.equal(floor.heading,"Bereiche");assert.equal(floor.floorId,"a-eg");assert.equal(value(floor,"electricity","energy"),10);
|
||||
});
|
||||
test("owned outdoor meters are separate children and do not leak into neighbouring building totals",()=>{
|
||||
const {b,hass}=project(),yard=addTopologyOutside(b,{kind:"branch",id:"hq"}),terrace=addTopologyOutside(b,{kind:"building",id:"a"});
|
||||
yard.utility_meters={electricity:{energy:"sensor.1001"}};terrace.utility_meters={electricity:{energy:"sensor.1201"}};
|
||||
const branch=utilityScope(hass,b,{kind:"branch",id:"hq"}),building=utilityScope(hass,b,{kind:"building",id:"a"});
|
||||
assert.deepEqual(branch.entries.at(-1)?.selection,outsideSelection({kind:"branch",id:"hq"}));
|
||||
assert.deepEqual(building.entries.at(-1)?.selection,outsideSelection({kind:"building",id:"a"}));
|
||||
assert.equal(value(branch,"electricity","energy"),60,"a shared native variable is counted once across indoor and outdoor floor aliases");
|
||||
assert.equal(value(building,"electricity","energy"),60);
|
||||
assert.equal(value(utilityScope(hass,b,outsideSelection({kind:"branch",id:"hq"})),"electricity","energy"),10);
|
||||
});
|
||||
test("live readings retain zero, error subtotals, periods, unit conversions and archive source identities",()=>{
|
||||
const {b,hass}=project();b.floors[0].utility_meters!.electricity!.power="sensor.1000";
|
||||
hass.states["sensor.1001"].attributes.friendly_name="Verbrauch heute";
|
||||
hass.states["sensor.1101"]={...hass.states["sensor.1101"],state:"unavailable"};
|
||||
hass.states["sensor.1000"]={...hass.states["sensor.1000"],state:"0",attributes:{...hass.states["sensor.1000"].attributes,symcon_value:0}};
|
||||
const first=utilityScope(hass,b,{kind:"branch",id:"hq"});
|
||||
assert.equal(first.entries[0].readings.find((r)=>r.kind==="electricity"&&r.metric==="power")?.value,2000);
|
||||
const energy=first.entries[0].readings.filter((r)=>r.kind==="electricity"&&r.metric==="energy");
|
||||
assert.deepEqual(energy.map((r)=>[r.period,r.value,r.incomplete]),[["day",10,false],["total",null,true]]);
|
||||
assert.ok(energy[0].sources.includes("sensor.1001"));
|
||||
const changed={...hass,states:{...hass.states,"sensor.1200":{...hass.states["sensor.1200"],state:"0",attributes:{...hass.states["sensor.1200"].attributes,symcon_value:0}}}} as HomeAssistant;
|
||||
assert.equal(value(utilityScope(changed,b,{kind:"branch",id:"hq"}),"electricity","power"),2000);
|
||||
});
|
||||
test("native categories in other buildings remain excluded from every child subtotal as well as the header",()=>{
|
||||
const {b,hass}=project();for(const f of b.floors)f.utility_meters=null;
|
||||
b.floors[0].rooms=[box("parent-room",0,0,4,4,"symcon-category-10")];b.floors[2].rooms=[box("child-room",0,0,4,4,"symcon-category-20")];
|
||||
const node=(id:number,parent:number,name:string,type=0,extra={})=>({object_id:id,parent_id:parent,name,path:name,object_type:type,hidden:false,position:0,icon:"",...extra}) as SymconObject;
|
||||
hass.symconObjects=[node(10,0,"Parent"),node(11,10,"Strom"),node(12,11,"Leistung",2,{entity_id:"sensor.1000"}),node(20,10,"Child"),node(21,20,"Strom"),node(22,21,"Leistung",2,{entity_id:"sensor.1200"})];
|
||||
const scope=utilityScope(hass,b,{kind:"branch",id:"hq"});
|
||||
assert.deepEqual(scope.entries.map((e)=>e.readings[0].value),[1000,3000]);assert.equal(value(scope,"electricity","power"),4000);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { Building } from "./model.ts";
|
||||
import type { HomeAssistant } from "./types.ts";
|
||||
import { floorSelection, outsideFloor, topologyPath, type TopologySelection } from "./topology.ts";
|
||||
import { buildingUtilityReadings, floorUtilityAreas, floorUtilityReadings, type UtilityArea, type UtilityReading } from "./utilities.ts";
|
||||
|
||||
export interface UtilityScopeEntry {
|
||||
id: string; name: string; path: string; readings: UtilityReading[];
|
||||
rooms: UtilityArea["rooms"]; selection: TopologySelection | null;
|
||||
}
|
||||
export interface UtilityScope {
|
||||
name: string; path: string; heading: string; floorId: string | null;
|
||||
totals: UtilityReading[]; entries: UtilityScopeEntry[];
|
||||
}
|
||||
|
||||
/** Use logical descendants for totals and immediate children for the right-hand breakdown. */
|
||||
export function utilityScope(hass: HomeAssistant, b: Building, selection: TopologySelection): UtilityScope {
|
||||
// A shared discovery context keeps nested native categories in other buildings out of every subtotal.
|
||||
const rooms=b.floors.flatMap((f)=>f.rooms);
|
||||
const floorId=selection.kind==="room"?selection.floorId:selection.kind==="floor"?selection.id:outsideFloor(b,selection)?.id;
|
||||
const floor=b.floors.find((f)=>f.id===floorId);
|
||||
if(floor){
|
||||
const path=b.topology?topologyPath(b,floorSelection(b,floor.id)).slice(1).map((n)=>n.name).join(" / "):floor.name;
|
||||
return {name:floor.name,path,heading:"Bereiche",floorId:floor.id,totals:floorUtilityReadings(hass,floor,rooms),
|
||||
entries:floorUtilityAreas(hass,floor,rooms,true).map((area)=>({...area,selection:null}))};
|
||||
}
|
||||
if(!b.topology){
|
||||
const entries=[...b.floors].sort((a,z)=>z.elevation-a.elevation).map((f)=>({id:f.id,name:f.name,path:f.name,readings:floorUtilityReadings(hass,f,rooms),rooms:[],selection:floorSelection(b,f.id)}));
|
||||
return {name:"Gesamtgebäude",path:"Gesamtgebäude",heading:"Stockwerke",floorId:null,totals:buildingUtilityReadings(hass,b.floors,rooms),
|
||||
entries:entries.filter((e)=>e.readings.length||floorUtilityAreas(hass,b.floors.find((f)=>f.id===e.id)!,rooms,true).length)};
|
||||
}
|
||||
const path=topologyPath(b,selection),node=path.at(-1)!;
|
||||
const floorsFor=(ids:readonly string[])=>{const selected=new Set(ids);return b.floors.filter((f)=>selected.has(f.id));};
|
||||
const entries=node.children.map((child)=>{
|
||||
const floors=floorsFor(child.floorIds);
|
||||
return {id:child.key,name:child.name,path:[...path.slice(1).map((n)=>n.name),child.name].join(" / "),
|
||||
readings:(child.selection.kind==="floor"||child.selection.kind==="outside")&&floors.length===1?floorUtilityReadings(hass,floors[0],rooms):buildingUtilityReadings(hass,floors,rooms),rooms:[],selection:child.selection,
|
||||
hasDetails:floors.some((f)=>floorUtilityAreas(hass,f,rooms,true).length)};
|
||||
}).filter((e)=>e.readings.length||e.hasDetails);
|
||||
const heading=({all:"Orte",location:"Niederlassungen",branch:"Gebäude",building:"Stockwerke"} as Record<string,string>)[node.selection.kind]??"Bereiche";
|
||||
return {name:node.name,path:path.slice(1).map((n)=>n.name).join(" / ")||node.name,heading,floorId:null,
|
||||
totals:buildingUtilityReadings(hass,floorsFor(node.floorIds),rooms),entries};
|
||||
}
|
||||
@@ -42,6 +42,7 @@ export function flipWinding(buf: GeoBuffer, from: number): void {
|
||||
swapped(buf.uv, tri * 6, 2);
|
||||
swapped(buf.tile, tri * 6, 2);
|
||||
swapped(buf.surface, tri * 3, 1);
|
||||
swapped(buf.surfaceTransform, tri * 6, 2);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ export class GeoBuffer {
|
||||
tile: number[] | null;
|
||||
/** Outdoor material IDs, allocated only for buffers that contain outdoor geometry. */
|
||||
surface: number[] | null = null;
|
||||
/** Outdoor texture scale and rotation (radians), two numbers per vertex. */
|
||||
surfaceTransform: number[] | null = null;
|
||||
|
||||
constructor(uvs = false, tiles = false) {
|
||||
this.uv = uvs ? [] : null;
|
||||
@@ -42,6 +44,7 @@ export class GeoBuffer {
|
||||
this.uv?.push(...(uv ?? [0.5, 0.5, 0.5, 0.5, 0.5, 0.5]));
|
||||
this.tile?.push(...tile, ...tile, ...tile);
|
||||
this.surface?.push(0, 0, 0);
|
||||
this.surfaceTransform?.push(1, 0, 1, 0, 1, 0);
|
||||
}
|
||||
|
||||
/** The number of triangles. */
|
||||
@@ -57,6 +60,7 @@ export class GeoBuffer {
|
||||
if (this.uv) geometry.setAttribute("uv", attribute(this.uv, 2));
|
||||
if (this.tile) geometry.setAttribute("tile", attribute(this.tile, 2));
|
||||
if (this.surface) geometry.setAttribute("surface", attribute(this.surface, 1));
|
||||
if (this.surfaceTransform) geometry.setAttribute("surfaceTransform", attribute(this.surfaceTransform, 2));
|
||||
geometry.computeBoundingSphere();
|
||||
return geometry;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ interface Vertex {
|
||||
uv: number[] | null;
|
||||
tile: number[] | null;
|
||||
surface: number;
|
||||
surfaceTransform: number[] | null;
|
||||
}
|
||||
|
||||
const blend = (a: number[], b: number[], t: number) => a.map((x, i) => x + (b[i] - x) * t);
|
||||
@@ -18,7 +19,7 @@ const blend = (a: number[], b: number[], t: number) => a.map((x, i) => x + (b[i]
|
||||
/** The point where an edge crosses the height `cut`; colours and uvs are interpolated. */
|
||||
function crossing(a: Vertex, b: Vertex, cut: number): Vertex {
|
||||
const t = (cut - a.p[1]) / (b.p[1] - a.p[1]);
|
||||
return { p: blend(a.p, b.p, t), c: blend(a.c, b.c, t), uv: a.uv && b.uv ? blend(a.uv, b.uv, t) : null, tile: a.tile, surface: a.surface };
|
||||
return { p: blend(a.p, b.p, t), c: blend(a.c, b.c, t), uv: a.uv && b.uv ? blend(a.uv, b.uv, t) : null, tile: a.tile, surface: a.surface, surfaceTransform: a.surfaceTransform };
|
||||
}
|
||||
|
||||
function readVertex(buf: GeoBuffer, v: number): Vertex {
|
||||
@@ -28,6 +29,7 @@ function readVertex(buf: GeoBuffer, v: number): Vertex {
|
||||
uv: buf.uv ? buf.uv.slice(v * 2, v * 2 + 2) : null,
|
||||
tile: buf.tile ? buf.tile.slice(v * 2, v * 2 + 2) : null,
|
||||
surface: buf.surface?.[v] ?? 0,
|
||||
surfaceTransform: buf.surfaceTransform?.slice(v * 2, v * 2 + 2) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -40,6 +42,7 @@ function overwriteTriangle(buf: GeoBuffer, tri: number, corners: Vertex[], fold:
|
||||
if (buf.tile && corner.tile) corner.tile.forEach((x, i) => (buf.tile![v * 2 + i] = x));
|
||||
buf.f[v] = fold;
|
||||
if (buf.surface) buf.surface[v] = corner.surface;
|
||||
if (buf.surfaceTransform && corner.surfaceTransform) corner.surfaceTransform.forEach((x, i) => (buf.surfaceTransform![v * 2 + i] = x));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -51,6 +54,7 @@ function appendTriangle(buf: GeoBuffer, corners: Vertex[], fold: number): void {
|
||||
buf.uv?.push(...(corner.uv ?? [0.5, 0.5]));
|
||||
buf.tile?.push(...(corner.tile ?? [0, 1]));
|
||||
buf.surface?.push(corner.surface);
|
||||
buf.surfaceTransform?.push(...(corner.surfaceTransform ?? [1, 0]));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -82,16 +82,23 @@ test("cutAbove keeps colours and uvs along the new edge", () => {
|
||||
test("cutting geometry retains outdoor surface IDs and appending furniture uses a neutral material", () => {
|
||||
const buf = new GeoBuffer();
|
||||
buf.surface = [];
|
||||
buf.surfaceTransform = [];
|
||||
buf.tri([0, 0, 0], [1, 2, 0], [0, 0, 1], grey);
|
||||
buf.surface.fill(12);
|
||||
buf.surfaceTransform = [2, 0.5, 2, 0.5, 2, 0.5];
|
||||
cutAbove(buf, 0, 1, FURN_OFFSET);
|
||||
assert.equal(buf.surface.length, buf.p.length / 3);
|
||||
assert.ok(buf.surface.every((id) => id === 12));
|
||||
assert.equal(buf.surfaceTransform.length, buf.p.length / 3 * 2);
|
||||
assert.ok(buf.surfaceTransform.every((value, i) => value === (i % 2 === 0 ? 2 : 0.5)));
|
||||
buf.tri([4, 0, 0], [5, 2, 0], [4, 0, 1], grey);
|
||||
assert.deepEqual(buf.surface.slice(-3), [0, 0, 0]);
|
||||
assert.deepEqual(buf.surfaceTransform.slice(-6), [1, 0, 1, 0, 1, 0]);
|
||||
cutAbove(buf, buf.count - 1, 1, FURN_OFFSET);
|
||||
assert.equal(buf.surface.length, buf.p.length / 3);
|
||||
assert.deepEqual(buf.surface.slice(-6), [0, 0, 0, 0, 0, 0]);
|
||||
assert.equal(buf.surfaceTransform.length, buf.p.length / 3 * 2);
|
||||
assert.deepEqual(buf.surfaceTransform.slice(-12), [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]);
|
||||
});
|
||||
|
||||
test("cutAbove only touches triangles from the given one on", () => {
|
||||
|
||||
@@ -15,6 +15,9 @@ export const LOOKS: Record<OutdoorType, Look> = {
|
||||
terrace: { color: 0x1c1b30, side: 0x161628, edge: 0x5b7cff, edgeAlpha: 0.32 },
|
||||
path: { color: 0x1b2234, side: 0x151b29, edge: 0x5b7cff, edgeAlpha: 0.22 },
|
||||
driveway: { color: 0x171d2c, side: 0x121725, edge: 0x5b7cff, edgeAlpha: 0.18 },
|
||||
pavers: { color: 0x48453f, side: 0x292720, edge: 0xa59d88, edgeAlpha: 0.25 },
|
||||
stepping_stones: { color: 0x55574b, side: 0x292f22, edge: 0x9eaf83, edgeAlpha: 0.22 },
|
||||
natural_stone: { color: 0x514a3d, side: 0x29261f, edge: 0xb1a38a, edgeAlpha: 0.25 },
|
||||
street: { color: 0x24272d, side: 0x15181e, edge: 0x9aa4b2, edgeAlpha: 0.25 },
|
||||
sidewalk: { color: 0x48505b, side: 0x29313b, edge: 0xaebbc9, edgeAlpha: 0.28 },
|
||||
gravel: { color: 0x514b3e, side: 0x2a2822, edge: 0xb8a882, edgeAlpha: 0.26 },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { newFloor, OUTDOOR_TOP, OUTDOOR_TYPES, type Floor, type OutdoorArea, type Vec2 } from "../../model.ts";
|
||||
import { newFloor, OUTDOOR_TOP, OUTDOOR_TYPES, outdoorTextureSettings, type Floor, type OutdoorArea, type Vec2 } from "../../model.ts";
|
||||
import { GeoBuffer, LineBuffer } from "../geo.ts";
|
||||
import { counterClockwise, pushBeam, pushPost } from "./beams.ts";
|
||||
import { outdoorHoles, outdoorOpacity, outdoorSurface, pushOutdoor } from "./outdoor.ts";
|
||||
@@ -54,10 +54,35 @@ test("every outdoor type has a texture ID; later furniture stays untextured and
|
||||
assert.ok(buf.surface!.slice(-30).every((id) => id === 0), "later geometry never inherits the outdoor texture");
|
||||
const g = buf.geometry();
|
||||
assert.equal(g.getAttribute("surface").count, g.getAttribute("position").count);
|
||||
assert.equal(g.getAttribute("surfaceTransform").count, g.getAttribute("position").count);
|
||||
g.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test("texture settings default old plans, bound pattern size and wrap rotations", () => {
|
||||
assert.deepEqual(outdoorTextureSettings({}), { scale: 1, rotation: 0 });
|
||||
assert.deepEqual(outdoorTextureSettings({ texture_scale: null, texture_rotation: null }), { scale: 1, rotation: 0 });
|
||||
assert.deepEqual(outdoorTextureSettings({ texture_scale: 2.5, texture_rotation: -90 }), { scale: 2.5, rotation: 270 });
|
||||
assert.deepEqual(outdoorTextureSettings({ texture_scale: 0, texture_rotation: 720 }), { scale: 0.05, rotation: 0 });
|
||||
assert.equal(outdoorTextureSettings({ texture_scale: 100 }).scale, 20);
|
||||
assert.deepEqual(outdoorTextureSettings({ texture_scale: NaN, texture_rotation: Infinity }), { scale: 1, rotation: 0 });
|
||||
});
|
||||
|
||||
test("scale and rotation stay per area, preserve geometry and reach transparent sloped surfaces", () => {
|
||||
const plain = area("terrace", square(0, 0, 4, 3));
|
||||
const changed = { ...plain, texture_scale: 2.5, texture_rotation: 45 };
|
||||
assert.deepEqual(build(plain).buf.p, build(changed).buf.p, "the outline and all mesh coordinates stay unchanged");
|
||||
const solid = new GeoBuffer(), ghosts = new Map<number, GeoBuffer>();
|
||||
pushOutdoor(solid, new LineBuffer(), floorWith(plain, area("sidewalk", square(5, 0, 9, 3), { texture_scale: 0.5, texture_rotation: 90 }), { ...changed, opacity: 0.4, slope: 0.3 }), ghosts, () => new GeoBuffer());
|
||||
for (let v = 0; v < solid.surface!.length; v++) {
|
||||
const id = solid.surface![v];
|
||||
assert.deepEqual(solid.surfaceTransform!.slice(v * 2, v * 2 + 2), id === OUTDOOR_MATERIAL.terrace ? [1, 0] : [0.5, Math.PI / 2]);
|
||||
}
|
||||
const ghost = ghosts.get(0.4)!;
|
||||
assert.equal(ghost.surfaceTransform!.length, ghost.p.length / 3 * 2);
|
||||
for (let v = 0; v < ghost.p.length / 3; v++) assert.deepEqual(ghost.surfaceTransform!.slice(v * 2, v * 2 + 2), [2.5, Math.PI / 4]);
|
||||
});
|
||||
|
||||
test("river and stream cut through a surrounding lawn, can be sloped, and preserve transparency", () => {
|
||||
for (const type of ["river", "stream"] as const) {
|
||||
const water = area(type, square(1, 1, 3, 2), { slope: 0.3, offset: 0.2, opacity: 0.4 });
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// patches cut out of it.
|
||||
|
||||
import { Color } from "three";
|
||||
import { bounds, cutsOut, groundLevel, isAxisRect, OUTDOOR_TOP, outdoorDrop, outdoorStanding, pointInPolygon, type Floor, type OutdoorArea, type Vec2 } from "../../model.ts";
|
||||
import { bounds, cutsOut, groundLevel, isAxisRect, OUTDOOR_TOP, outdoorDrop, outdoorStanding, outdoorTextureSettings, pointInPolygon, type Floor, type OutdoorArea, type Vec2 } from "../../model.ts";
|
||||
import { ALWAYS, pushPrism, shade, triangulate, type GeoBuffer, type LineBuffer } from "../geo.ts";
|
||||
import { counterClockwise, pushBeam, pushPost } from "./beams.ts";
|
||||
import { gateLayout, gatesOnEdge } from "./gates.ts";
|
||||
@@ -194,6 +194,7 @@ export function outdoorOpacity(area: OutdoorArea): number {
|
||||
export function pushOutdoor(buf: GeoBuffer, lines: LineBuffer, floor: Floor, ghosts?: Map<number, GeoBuffer>, makeBuffer?: () => GeoBuffer): void {
|
||||
// The shared wall shader also serves floors without outdoor areas: supply a neutral ID there.
|
||||
buf.surface ??= Array(buf.p.length / 3).fill(0);
|
||||
buf.surfaceTransform ??= Array.from({ length: (buf.p.length / 3) * 2 }, (_, i) => i % 2 === 0 ? 1 : 0);
|
||||
const ground = groundLevel(floor);
|
||||
const areas = floor.outdoor ?? [];
|
||||
areas.forEach((area, index) => {
|
||||
@@ -209,6 +210,7 @@ export function pushOutdoor(buf: GeoBuffer, lines: LineBuffer, floor: Floor, gho
|
||||
target = ghosts.get(opacity)!;
|
||||
}
|
||||
target.surface ??= Array(target.p.length / 3).fill(0);
|
||||
target.surfaceTransform ??= Array.from({ length: (target.p.length / 3) * 2 }, (_, i) => i % 2 === 0 ? 1 : 0);
|
||||
const firstVertex = target.p.length / 3;
|
||||
const context: Context = {
|
||||
buf: target,
|
||||
@@ -229,5 +231,10 @@ export function pushOutdoor(buf: GeoBuffer, lines: LineBuffer, floor: Floor, gho
|
||||
else if (area.type === "pergola") buildPergola(context);
|
||||
else buildBlock(context, areas, index);
|
||||
target.surface.fill(OUTDOOR_MATERIAL[area.type], firstVertex);
|
||||
const texture = outdoorTextureSettings(area);
|
||||
for (let v = firstVertex; v < target.p.length / 3; v++) {
|
||||
target.surfaceTransform[v * 2] = texture.scale;
|
||||
target.surfaceTransform[v * 2 + 1] = texture.rotation * Math.PI / 180;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -5,11 +5,13 @@ import type { OutdoorType } from "../../model.ts";
|
||||
export const OUTDOOR_MATERIAL: Record<OutdoorType, number> = {
|
||||
lawn: 1, terrace: 2, path: 3, driveway: 4, pool: 5, bed: 6, wild: 7,
|
||||
hedge: 8, fence: 9, pergola: 9, street: 10, sidewalk: 11, gravel: 12, river: 13, stream: 14,
|
||||
pavers: 15, stepping_stones: 16, natural_stone: 17,
|
||||
};
|
||||
|
||||
const TEXTURE = /* glsl */ `
|
||||
varying vec3 vNfGround;
|
||||
varying float vNfSurface;
|
||||
varying vec2 vNfSurfaceTransform;
|
||||
float nfGrain(vec2 p) {
|
||||
return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453);
|
||||
}
|
||||
@@ -28,10 +30,11 @@ float nfJoint(float v, float width) {
|
||||
}
|
||||
// Keep the material recognizable in the day look: its general theme otherwise maps dark asphalt to near-white.
|
||||
vec3 nfOutdoorDay(float kind) {
|
||||
if (kind > 14.5) return kind < 15.5 ? vec3(0.30, 0.28, 0.25) : kind < 16.5 ? vec3(0.38, 0.38, 0.32) : vec3(0.34, 0.30, 0.24);
|
||||
if (kind < 1.5 || (kind > 6.5 && kind < 8.5)) return kind > 7.5 ? vec3(0.055, 0.17, 0.07) : vec3(0.12, 0.28, 0.08);
|
||||
if (kind < 2.5) return vec3(0.38, 0.32, 0.25);
|
||||
if (kind < 4.5) return kind < 3.5 ? vec3(0.36, 0.34, 0.30) : vec3(0.23, 0.25, 0.27);
|
||||
if ((kind > 4.5 && kind < 5.5) || kind > 12.5) return vec3(0.035, 0.22, 0.28);
|
||||
if ((kind > 4.5 && kind < 5.5) || (kind > 12.5 && kind < 14.5)) return vec3(0.035, 0.22, 0.28);
|
||||
if (kind < 6.5) return vec3(0.15, 0.09, 0.045);
|
||||
if (kind < 9.5) return vec3(0.27, 0.15, 0.065);
|
||||
if (kind < 10.5) return vec3(0.07, 0.075, 0.085);
|
||||
@@ -59,7 +62,33 @@ vec3 nfOutdoorTexture(vec3 position, float kind) {
|
||||
// Project onto the dominant face, so raised beds, hedge sides and timber have texture too.
|
||||
vec3 n = abs(cross(dFdx(position), dFdy(position)));
|
||||
vec2 p = n.y >= max(n.x, n.z) ? position.xz : (n.x > n.z ? position.zy : position.xy);
|
||||
// Sample with the inverse transform: increasing scale enlarges the visible pattern.
|
||||
float angle = vNfSurfaceTransform.y;
|
||||
float c = cos(angle), s = sin(angle);
|
||||
p = vec2(c * p.x + s * p.y, -s * p.x + c * p.y) / max(vNfSurfaceTransform.x, 0.05);
|
||||
float broad = nfNoise(p * 1.7);
|
||||
if (kind > 16.5) return nfPebbles(p * 2.3, false);
|
||||
if (kind > 15.5) {
|
||||
// Separate garden slabs with generous green gaps; texture scale changes slab size and spacing together.
|
||||
vec2 cell = p / 0.85;
|
||||
cell.x += mod(floor(cell.y), 2.0) * 0.12;
|
||||
vec2 f = fract(cell), aa = max(fwidth(cell), vec2(0.001));
|
||||
vec2 lo = smoothstep(vec2(0.12), vec2(0.12) + aa, f);
|
||||
vec2 hi = 1.0 - smoothstep(vec2(0.88) - aa, vec2(0.88), f);
|
||||
float slab = lo.x * lo.y * hi.x * hi.y;
|
||||
vec3 stone = vec3(0.85 + nfGrain(floor(cell)) * 0.24) * (0.9 + nfNoise(p * 32.0) * 0.18);
|
||||
vec3 grass = vec3(0.23, 0.62, 0.18) * (0.8 + broad * 0.4);
|
||||
return mix(grass, stone, slab);
|
||||
}
|
||||
if (kind > 14.5) {
|
||||
vec2 cell = p / vec2(0.2, 0.16);
|
||||
cell.x += mod(floor(cell.y), 2.0) * 0.5;
|
||||
float wobble = (nfNoise(p * 14.0) - 0.5) * 0.08;
|
||||
float seam = max(nfJoint(cell.x + wobble, 0.03), nfJoint(cell.y + wobble, 0.03));
|
||||
float bevel = max(nfJoint(cell.x + wobble, 0.1), nfJoint(cell.y + wobble, 0.1));
|
||||
float variation = 0.7 + nfGrain(floor(cell)) * 0.55;
|
||||
return vec3(mix(variation * (1.0 - bevel * 0.18), 0.28, seam * nfDetail(cell)));
|
||||
}
|
||||
if (kind < 1.5 || (kind > 6.5 && kind < 8.5)) {
|
||||
if (kind > 7.5) return nfPebbles(p * 14.0, true);
|
||||
float blades = nfNoise(p * vec2(65, 24));
|
||||
@@ -76,7 +105,7 @@ vec3 nfOutdoorTexture(vec3 position, float kind) {
|
||||
float grain = mix(1.0, 0.88 + nfNoise(p * 80.0) * 0.24, nfDetail(p * 80.0));
|
||||
return vec3(mix(variation, 0.35, joint * nfDetail(tile)) * grain);
|
||||
}
|
||||
if ((kind > 4.5 && kind < 5.5) || kind > 12.5) {
|
||||
if ((kind > 4.5 && kind < 5.5) || (kind > 12.5 && kind < 14.5)) {
|
||||
// Water: broad ripples and smaller crossing highlights, with a tighter scale in streams.
|
||||
vec2 water = p * (kind > 13.5 ? 1.8 : 1.0);
|
||||
float wave = sin(water.x * 8.0 + sin(water.y * 3.0) + broad * 3.0);
|
||||
@@ -107,8 +136,8 @@ export function outdoorTextured<T extends Material>(material: T): T {
|
||||
material.onBeforeCompile = (shader, renderer) => {
|
||||
previous(shader, renderer);
|
||||
shader.vertexShader = shader.vertexShader
|
||||
.replace("#include <common>", "#include <common>\nattribute float surface;\nvarying vec3 vNfGround;\nvarying float vNfSurface;")
|
||||
.replace("#include <begin_vertex>", "#include <begin_vertex>\nvNfGround = position;\nvNfSurface = surface;");
|
||||
.replace("#include <common>", "#include <common>\nattribute float surface;\nattribute vec2 surfaceTransform;\nvarying vec3 vNfGround;\nvarying float vNfSurface;\nvarying vec2 vNfSurfaceTransform;")
|
||||
.replace("#include <begin_vertex>", "#include <begin_vertex>\nvNfGround = position;\nvNfSurface = surface;\nvNfSurfaceTransform = surfaceTransform;");
|
||||
shader.fragmentShader = shader.fragmentShader.replace("#include <common>", `#include <common>\n${TEXTURE}`)
|
||||
.replace("#include <opaque_fragment>", `if (vNfSurface > 0.5) {
|
||||
if (uTheme == 2) outgoingLight = nfOutdoorDay(vNfSurface) * (0.7 + dot(outgoingLight, vec3(0.299, 0.587, 0.114)) * 0.4);
|
||||
@@ -116,6 +145,6 @@ export function outdoorTextured<T extends Material>(material: T): T {
|
||||
}
|
||||
#include <opaque_fragment>`);
|
||||
};
|
||||
material.customProgramCacheKey = () => `${previousKey()}-outdoor-textures-1`;
|
||||
material.customProgramCacheKey = () => `${previousKey()}-outdoor-textures-2`;
|
||||
return material;
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
// house view only; the viewer lifts it and fades it out when the camera zooms in.
|
||||
|
||||
import type { Building } from "../../model.ts";
|
||||
import { isOutdoorFloor } from "../../topology.ts";
|
||||
import { pushChimneys, pushRoofWindows, pushSolar, type RoofWindowState } from "./fittings.ts";
|
||||
import { buildSections } from "./sections.ts";
|
||||
import { buildSingleRoof } from "./single.ts";
|
||||
@@ -10,6 +11,15 @@ import type { RoofGeometry } from "./types.ts";
|
||||
/** The roof in parts per floor; each part moves with its floor when the floors are pulled apart. */
|
||||
export function buildRoof(b: Building, windows: ReadonlyMap<string, RoofWindowState> = new Map()): RoofGeometry[] {
|
||||
const roof = b.settings.roof;
|
||||
// Automatic roofs belong to independent buildings, never to a location's outdoor plan or the global highest storey.
|
||||
if (b.topology && roof?.type !== "custom") {
|
||||
const groups = new Map<string, typeof b.floors>();
|
||||
for (const f of b.floors) if (!isOutdoorFloor(f)) {
|
||||
const id = f.building_id ?? "legacy";
|
||||
groups.set(id, [...(groups.get(id) ?? []), f]);
|
||||
}
|
||||
return [...groups.values()].flatMap((floors) => buildRoof({ ...b, topology: undefined, floors }, windows));
|
||||
}
|
||||
const single = roof?.type === "custom" ? null : buildSingleRoof(b);
|
||||
const parts = roof?.type === "custom" ? buildSections(b, roof.sections ?? [], roof.overhang) : single ? [single] : [];
|
||||
pushSolar(b, parts);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isOutdoorFloor, type TopologyNode } from "../topology.ts";
|
||||
// 3D view (separate bundle, loaded on demand). Renders only when something changes.
|
||||
//
|
||||
// Floors are shown in three levels: the whole house (floors pulled apart or stacked), one floor
|
||||
@@ -26,6 +27,7 @@ import {
|
||||
OrthographicCamera,
|
||||
PerspectiveCamera,
|
||||
Points,
|
||||
Plane,
|
||||
PlaneGeometry,
|
||||
Raycaster,
|
||||
RepeatWrapping,
|
||||
@@ -1911,7 +1913,7 @@ export class NextFloorViewer {
|
||||
}
|
||||
this.floors.push({
|
||||
floor,
|
||||
rank: ordered.indexOf(floor),
|
||||
rank: b.topology ? isOutdoorFloor(floor) ? 0 : ordered.filter((f)=>!isOutdoorFloor(f)&&f.building_id===floor.building_id).indexOf(floor) : ordered.indexOf(floor),
|
||||
group,
|
||||
geo,
|
||||
floorMesh,
|
||||
@@ -2486,6 +2488,12 @@ export class NextFloorViewer {
|
||||
const box = new Box3();
|
||||
for (const fv of this.activeFloors()) {
|
||||
const y0 = fv.floor.elevation + fv.ty;
|
||||
for (const area of fv.floor.outdoor) for (const [x,z] of area.points) {
|
||||
box.expandByPoint(new Vector3(x,y0,z));box.expandByPoint(new Vector3(x,y0+Math.max(1,area.height??0),z));
|
||||
}
|
||||
if(!fv.floor.rooms.length)for(const m of fv.floor.furniture){
|
||||
box.expandByPoint(new Vector3(m.x-m.w/2,y0,m.z-m.d/2));box.expandByPoint(new Vector3(m.x+m.w/2,y0+(m.mount_y??0)+m.h,m.z+m.d/2));
|
||||
}
|
||||
for (const room of fv.floor.rooms) {
|
||||
for (const [x, z] of room.points) {
|
||||
box.expandByPoint(new Vector3(x, y0, z));
|
||||
@@ -2941,93 +2949,52 @@ export class NextFloorViewer {
|
||||
* the same renderer, so nothing is uploaded twice; the view is restored afterwards.
|
||||
*/
|
||||
floorThumbnails(width = 200, height = 150): { floorId: string; url: string }[] {
|
||||
const floors = this.floors.filter((fv) => fv.floor.rooms.some((r) => r.points.length >= 3));
|
||||
if (!floors.length) return [];
|
||||
const scale = this.lowQuality ? 1 : Math.min(2, window.devicePixelRatio || 1);
|
||||
const w = Math.round(width * scale);
|
||||
const h = Math.round(height * scale);
|
||||
const target = new WebGLRenderTarget(w, h);
|
||||
target.texture.colorSpace = SRGBColorSpace;
|
||||
const camera = new OrthographicCamera(-1, 1, 1, -1, 0.1, 400);
|
||||
const saved = this.floors.map((fv) => ({ fv, visible: fv.group.visible, y: fv.y, o: fv.o, standing: fv.mask.standing.value, glass: fv.mask.glass.value }));
|
||||
const roofVisible = this.roof?.group.visible ?? false;
|
||||
const ghostVisible = this.ghost?.visible ?? false;
|
||||
const clear = this.renderer.getClearAlpha();
|
||||
const pixels = new Uint8Array(w * h * 4);
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
const out: { floorId: string; url: string }[] = [];
|
||||
return this.scopeThumbnails(this.floors.filter((fv)=>fv.floor.rooms.some((r)=>r.points.length>=3)).map((fv)=>({key:fv.floor.id,floorIds:[fv.floor.id]})),width,height).map((t)=>({floorId:t.key,url:t.url}));
|
||||
}
|
||||
|
||||
/** Draw only a topology node's floors and frame its own geometry; rooms additionally clip neighbouring geometry. */
|
||||
scopeThumbnails(nodes: readonly Pick<TopologyNode,"key"|"floorIds"|"room">[], width=150,height=112):{key:string;url:string}[] {
|
||||
if(!nodes.length||!this.floors.length)return [];
|
||||
const scale=this.lowQuality?1:Math.min(2,window.devicePixelRatio||1),w=Math.round(width*scale),h=Math.round(height*scale);
|
||||
const target=new WebGLRenderTarget(w,h);target.texture.colorSpace=SRGBColorSpace;
|
||||
const camera=new OrthographicCamera(-1,1,1,-1,.1,4000);
|
||||
const saved=this.floors.map((fv)=>({fv,visible:fv.group.visible,y:fv.y,o:fv.o,standing:fv.mask.standing.value,glass:fv.mask.glass.value}));
|
||||
const floorGroups=new Set(this.floors.map((f)=>f.group));
|
||||
const others=[...this.scene.children.filter((c)=>c!==this.root),...this.root.children.filter((c)=>!floorGroups.has(c as Group))].filter((c)=>!(c as Object3D & {isLight?:boolean}).isLight).map((node)=>({node,visible:node.visible}));
|
||||
const clear=this.renderer.getClearAlpha(),planes=this.renderer.clippingPlanes;
|
||||
const pixels=new Uint8Array(w*h*4),canvas=document.createElement("canvas");canvas.width=w;canvas.height=h;
|
||||
const ctx=canvas.getContext("2d")!,out:{key:string;url:string}[]=[];
|
||||
try {
|
||||
if (this.roof) this.roof.group.visible = false;
|
||||
if (this.ghost) this.ghost.visible = false;
|
||||
for(const x of others)x.node.visible=false;
|
||||
this.renderer.setClearAlpha(0);
|
||||
for (const fv of floors) {
|
||||
for (const other of this.floors) other.group.visible = other === fv;
|
||||
fv.y = 0;
|
||||
fv.o = 1;
|
||||
this.applyFloor(fv);
|
||||
fv.group.visible = true;
|
||||
fv.mask.standing.value = 0;
|
||||
fv.mask.glass.value = 0;
|
||||
// fit the floor's rooms (with the cut walls) into the picture
|
||||
const pts = fv.floor.rooms.flatMap((r) => r.points);
|
||||
const y0 = fv.floor.elevation;
|
||||
const box = new Box3(
|
||||
new Vector3(Math.min(...pts.map((p) => p[0])) - 0.3, y0, Math.min(...pts.map((p) => p[1])) - 0.3),
|
||||
new Vector3(Math.max(...pts.map((p) => p[0])) + 0.3, y0 + Math.min(fv.floor.cut_height, fv.floor.height), Math.max(...pts.map((p) => p[1])) + 0.3),
|
||||
);
|
||||
const center = box.getCenter(new Vector3());
|
||||
const theta = -0.6;
|
||||
const phi = 0.8;
|
||||
const dir = new Vector3(Math.sin(phi) * Math.sin(theta), Math.cos(phi), Math.sin(phi) * Math.cos(theta));
|
||||
camera.position.copy(center).addScaledVector(dir, 100);
|
||||
camera.lookAt(center);
|
||||
camera.updateMatrixWorld();
|
||||
let rx = 0.5;
|
||||
let ry = 0.5;
|
||||
for (const x of [box.min.x, box.max.x])
|
||||
for (const y of [box.min.y, box.max.y])
|
||||
for (const z of [box.min.z, box.max.z]) {
|
||||
const p = new Vector3(x, y, z).applyMatrix4(camera.matrixWorldInverse);
|
||||
rx = Math.max(rx, Math.abs(p.x));
|
||||
ry = Math.max(ry, Math.abs(p.y));
|
||||
for(const node of nodes){
|
||||
const ids=new Set(node.floorIds),selected=this.floors.filter((f)=>ids.has(f.floor.id));
|
||||
const box=new Box3();
|
||||
for(const fv of this.floors){
|
||||
const visible=ids.has(fv.floor.id);fv.group.visible=visible;if(!visible)continue;
|
||||
fv.y=0;fv.o=1;this.applyFloor(fv);fv.group.visible=true;fv.mask.standing.value=0;fv.mask.glass.value=0;
|
||||
const f=fv.floor,room=node.room&&node.room.floorId===f.id?f.rooms.find((r)=>r.id===node.room!.roomId):null;
|
||||
const points=room?room.points:[...f.rooms.flatMap((r)=>r.points),...f.outdoor.flatMap((a)=>a.points),...(f.walls??[]).flatMap((wall)=>[wall.a,wall.b]),...f.furniture.flatMap((m)=>[[m.x-m.w/2,m.z-m.d/2],[m.x+m.w/2,m.z+m.d/2]] as Vec2[])];
|
||||
for(const [x,z] of points){box.expandByPoint(new Vector3(x,f.elevation,z));box.expandByPoint(new Vector3(x,f.elevation+Math.min(f.cut_height,f.height),z));}
|
||||
}
|
||||
// keep the picture's aspect ratio
|
||||
const aspect = w / h;
|
||||
if (rx / ry > aspect) ry = rx / aspect;
|
||||
else rx = ry * aspect;
|
||||
camera.left = -rx * 1.05;
|
||||
camera.right = rx * 1.05;
|
||||
camera.top = ry * 1.05;
|
||||
camera.bottom = -ry * 1.05;
|
||||
camera.updateProjectionMatrix();
|
||||
this.renderer.setRenderTarget(target);
|
||||
this.renderer.clear();
|
||||
this.renderer.render(this.scene, camera);
|
||||
this.renderer.readRenderTargetPixels(target, 0, 0, w, h, pixels);
|
||||
// the target's rows start at the bottom
|
||||
const img = ctx.createImageData(w, h);
|
||||
for (let row = 0; row < h; row++) img.data.set(pixels.subarray((h - 1 - row) * w * 4, (h - row) * w * 4), row * w * 4);
|
||||
ctx.putImageData(img, 0, 0);
|
||||
out.push({ floorId: fv.floor.id, url: canvas.toDataURL("image/png") });
|
||||
if(!selected.length||box.isEmpty())continue;
|
||||
box.expandByScalar(.25);
|
||||
this.renderer.clippingPlanes=node.room?[new Plane(new Vector3(1,0,0),-box.min.x),new Plane(new Vector3(-1,0,0),box.max.x),new Plane(new Vector3(0,0,1),-box.min.z),new Plane(new Vector3(0,0,-1),box.max.z)]:[];
|
||||
const center=box.getCenter(new Vector3()),theta=-.6,phi=.8,dir=new Vector3(Math.sin(phi)*Math.sin(theta),Math.cos(phi),Math.sin(phi)*Math.cos(theta));
|
||||
camera.position.copy(center).addScaledVector(dir,Math.max(100,box.getSize(new Vector3()).length()*2));camera.lookAt(center);camera.updateMatrixWorld();
|
||||
let rx=.5,ry=.5;
|
||||
for(const x of [box.min.x,box.max.x])for(const y of [box.min.y,box.max.y])for(const z of [box.min.z,box.max.z]){const p=new Vector3(x,y,z).applyMatrix4(camera.matrixWorldInverse);rx=Math.max(rx,Math.abs(p.x));ry=Math.max(ry,Math.abs(p.y));}
|
||||
const aspect=w/h;if(rx/ry>aspect)ry=rx/aspect;else rx=ry*aspect;
|
||||
camera.left=-rx*1.05;camera.right=rx*1.05;camera.top=ry*1.05;camera.bottom=-ry*1.05;camera.updateProjectionMatrix();
|
||||
this.renderer.setRenderTarget(target);this.renderer.clear();this.renderer.render(this.scene,camera);this.renderer.readRenderTargetPixels(target,0,0,w,h,pixels);
|
||||
const img=ctx.createImageData(w,h);for(let row=0;row<h;row++)img.data.set(pixels.subarray((h-1-row)*w*4,(h-row)*w*4),row*w*4);ctx.putImageData(img,0,0);
|
||||
out.push({key:node.key,url:canvas.toDataURL("image/png")});
|
||||
}
|
||||
} finally {
|
||||
this.renderer.setRenderTarget(null);
|
||||
this.renderer.setClearAlpha(clear);
|
||||
for (const s of saved) {
|
||||
s.fv.y = s.y;
|
||||
s.fv.o = s.o;
|
||||
s.fv.mask.standing.value = s.standing;
|
||||
s.fv.mask.glass.value = s.glass;
|
||||
this.applyFloor(s.fv);
|
||||
s.fv.group.visible = s.visible;
|
||||
}
|
||||
if (this.roof) this.roof.group.visible = roofVisible;
|
||||
if (this.ghost) this.ghost.visible = ghostVisible;
|
||||
target.dispose();
|
||||
this.invalidate();
|
||||
}finally{
|
||||
this.renderer.setRenderTarget(null);this.renderer.setClearAlpha(clear);this.renderer.clippingPlanes=planes;
|
||||
for(const s of saved){s.fv.y=s.y;s.fv.o=s.o;s.fv.mask.standing.value=s.standing;s.fv.mask.glass.value=s.glass;this.applyFloor(s.fv);s.fv.group.visible=s.visible;}
|
||||
for(const x of others)x.node.visible=x.visible;
|
||||
target.dispose();this.invalidate();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
// Real PHP WebHook, cookies and hostile API requests; then actual password login and viewer/editor UIs.
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { createServer } from "node:net";
|
||||
import { mkdtempSync, mkdirSync, existsSync, readFileSync, rmSync, rmdirSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { createHash } from "node:crypto";
|
||||
import puppeteer from "puppeteer-core";
|
||||
|
||||
const root = resolve(import.meta.dirname, ".."), out = join(root, "preview/screenshots"); mkdirSync(out, { recursive: true });
|
||||
const dir = mkdtempSync(join(tmpdir(), "nextfloor-auth-")), stateFile = join(dir, "state.json");
|
||||
const portProbe = createServer(); await new Promise((done) => portProbe.listen(0, "127.0.0.1", done));
|
||||
const port = portProbe.address().port; await new Promise((done) => portProbe.close(done));
|
||||
const base = `http://127.0.0.1:${port}`, hook = "/hook/nextfloor/12345";
|
||||
const php = spawn(process.env.PHP_PATH || "C:/xampp/php/php.exe", ["-S", `127.0.0.1:${port}`, join(root, "symcon/tests/auth-router.php")], {
|
||||
cwd: root, windowsHide: true, env: { ...process.env, NEXTFLOOR_TEST_STATE: stateFile }, stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let logs = "", browser; php.stdout.on("data", (data) => logs += data); php.stderr.on("data", (data) => logs += data);
|
||||
const delay = (ms) => new Promise((done) => setTimeout(done, ms));
|
||||
class Client {
|
||||
cookies = new Map(); csrf = ""; setCookies = [];
|
||||
async request(path, init = {}) {
|
||||
const response = await fetch(base + path, { ...init, redirect: "manual", headers: { ...init.headers, Cookie: [...this.cookies].map(([k, v]) => `${k}=${v}`).join("; ") } });
|
||||
this.setCookies = response.headers.getSetCookie();
|
||||
for (const cookie of this.setCookies) { const [pair] = cookie.split(";"), at = pair.indexOf("="); this.cookies.set(pair.slice(0, at), pair.slice(at + 1)); }
|
||||
return response;
|
||||
}
|
||||
async login(name, password = `${name}-test-password`, remember = false) {
|
||||
const page = await this.request(hook + "/login"), text = await page.text();
|
||||
const nonce = /name="csrf" value="([a-f0-9]+)"/.exec(text)?.[1]; assert.ok(nonce, text.slice(0, 250));
|
||||
const result = await this.request(hook + "/login", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Origin: base }, body: new URLSearchParams({ username: name, password, csrf: nonce, ...(remember ? { remember: "1" } : {}) }) });
|
||||
if (result.status === 303) {
|
||||
assert.ok(this.setCookies.some((c) => /^NFSC_Session_/.test(c) && /HttpOnly/i.test(c) && /SameSite=Strict/i.test(c)), "session cookie protection");
|
||||
const html = await (await this.request(hook + "/designer")).text();
|
||||
const config = JSON.parse(/window\.__NEXTFLOOR_SYMCON__=(.*?);<\/script>/s.exec(html)?.[1] ?? "null");
|
||||
assert.ok(config?.csrf); assert.equal(config.token, undefined); this.csrf = config.csrf;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
api(action, payload = {}, extraHeaders = {}) {
|
||||
return this.request(hook + "/api", { method: "POST", headers: { "Content-Type": "application/json", "X-NextFloor-CSRF": this.csrf, Origin: base, ...extraHeaders }, body: JSON.stringify({ ...payload, action, transport: "nextfloor-chunks-v1" }) });
|
||||
}
|
||||
async json(action, payload = {}) {
|
||||
const response = await this.api(action, payload), text = await response.text();
|
||||
assert.equal(response.status, 200, text); return JSON.parse(text);
|
||||
}
|
||||
}
|
||||
try {
|
||||
let ready = false;
|
||||
for (let i = 0; i < 100; i++) { try { ready = (await fetch(base + "/__test/state")).ok; } catch {} if (ready) break; await delay(100); }
|
||||
assert.ok(ready, logs.slice(-2000));
|
||||
const anonymous = new Client();
|
||||
assert.equal((await anonymous.request(hook + "/")).status, 303);
|
||||
assert.equal((await anonymous.api("bootstrap")).status, 401);
|
||||
assert.equal((await anonymous.request(hook + "/assets/nextfloor-designer.js")).status, 401);
|
||||
assert.equal((await anonymous.request(hook + "/api?token=old-reusable-token", { method: "POST", body: '{"action":"bootstrap"}' })).status, 401);
|
||||
|
||||
const reader = new Client(); assert.equal((await reader.login("reader", undefined, true)).status, 303);
|
||||
let response = await reader.api("bootstrap"); const boot = await response.json();
|
||||
assert.equal(boot.access.is_admin, false); assert.equal(boot.access.name, "reader");
|
||||
assert.equal(boot.variables.length, 9); assert.ok(boot.variables.every((v) => v.attributes.symcon_can_control === false));
|
||||
assert.ok(!boot.variables.some((v) => v.attributes.symcon_id === 888), "all-view permission excludes unrelated Symcon secrets");
|
||||
const attributes = JSON.parse(readFileSync(stateFile, "utf8")).attributes;
|
||||
const rawCookie = reader.cookies.get("NFSC_Session_12345");
|
||||
assert.ok(JSON.parse(attributes.Sessions)[createHash("sha256").update(rawCookie).digest("hex")]);
|
||||
assert.ok(!JSON.stringify(attributes).includes(rawCookie)); assert.ok(!JSON.stringify(attributes).includes("reader-test-password"));
|
||||
assert.ok(Object.values(JSON.parse(attributes.Sessions)).some((s) => s.expires > Date.now() / 1000 + 25 * 86400), "remembered sessions survive browser restarts");
|
||||
for (const action of ["building/save", "history/get", "backup/export", "packs/import", "image/set"]) assert.equal((await reader.api(action, { building: {} })).status, 403, action);
|
||||
assert.equal((await reader.api("variables/action", { domain: "light", service: "toggle", data: { entity_id: "light.101" } })).status, 403);
|
||||
assert.equal((await reader.api("bootstrap", {}, { "X-NextFloor-CSRF": "wrong" })).status, 403);
|
||||
assert.equal((await reader.api("bootstrap", {}, { Origin: "http://attacker.invalid" })).status, 403);
|
||||
assert.equal((await reader.request(hook + "/assets/nextfloor-editor.js")).status, 403);
|
||||
const csrfOnly = new Client(); csrfOnly.csrf = reader.csrf; assert.equal((await csrfOnly.api("bootstrap")).status, 401);
|
||||
|
||||
const office = new Client(); assert.equal((await office.login("office")).status, 303);
|
||||
const restricted = await office.json("bootstrap");
|
||||
assert.deepEqual(restricted.variables.map((v) => v.attributes.symcon_id).sort((a, b) => a - b), [101, 102, 103, 104, 105]);
|
||||
const plan = (await office.json("building/get")).building;
|
||||
assert.equal(plan.floors[0].rooms.length, 2); assert.equal(plan.floors[0].rooms[1].climate.temperature, "none");
|
||||
assert.equal(plan.floors[0].placements[1].entity_id, "none");
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
assert.equal((await office.api("archive/trend", { entity_id: "sensor.204", start: now - 3600, end: now })).status, 403);
|
||||
assert.equal((await office.api("archive/trend", { entity_id: "sensor.104", start: now - 3600, end: now })).status, 200);
|
||||
const before = (await (await fetch(base + "/__test/state")).json()).writes.length;
|
||||
assert.equal((await office.api("variables/action", { domain: "light", service: "turn_off", data: { entity_id: ["light.101", "light.201"] } })).status, 403);
|
||||
assert.equal((await (await fetch(base + "/__test/state")).json()).writes.length, before, "no partial writes from mixed bulk targets");
|
||||
assert.equal((await office.api("variables/action", { domain: "cover", service: "close_cover", data: { entity_id: "cover.201" } })).status, 403);
|
||||
assert.equal((await office.api("variables/action", { domain: "light", service: "turn_off", data: { entity_id: "light.101" } })).status, 200);
|
||||
assert.equal((await office.api("variables/action", { domain: "schedule", service: "set_active", data: { entity_id: "schedule.105", active: false } })).status, 200);
|
||||
|
||||
const device = new Client(); assert.equal((await device.login("device")).status, 303);
|
||||
assert.deepEqual((await device.json("bootstrap")).variables.map((v) => v.attributes.symcon_id).sort(), [102, 103]);
|
||||
assert.equal((await device.api("variables/action", { domain: "light", service: "turn_on", data: { entity_id: "light.101" } })).status, 403);
|
||||
assert.equal((await device.api("image/get", { image_id: "unreferenced-secret" })).status, 403);
|
||||
|
||||
// Native console recovery does not depend on knowing any NextFloor password.
|
||||
const consoleClient = new Client(), consoleURL = (await (await fetch(base + "/__test/console")).json()).url;
|
||||
assert.equal((await consoleClient.request(consoleURL)).status, 303);
|
||||
assert.equal((await new Client().request(consoleURL)).status, 401, "ticket replay");
|
||||
const html = await (await consoleClient.request(hook + "/designer")).text();
|
||||
consoleClient.csrf = JSON.parse(/window\.__NEXTFLOOR_SYMCON__=(.*?);<\/script>/s.exec(html)[1]).csrf;
|
||||
assert.equal((await consoleClient.json("bootstrap")).access.is_admin, true);
|
||||
|
||||
// A console password reset revokes remembered sessions immediately, including copied cookies.
|
||||
await fetch(base + "/__test/reset", { method: "POST", body: JSON.stringify({ name: "reader", password: "reader-new-test-password" }) });
|
||||
assert.equal((await reader.api("bootstrap")).status, 401);
|
||||
const oldPassword = new Client(); assert.equal((await oldPassword.login("reader")).status, 401);
|
||||
const resetReader = new Client(); assert.equal((await resetReader.login("reader", "reader-new-test-password")).status, 303);
|
||||
const copiedCookie = new Client(); copiedCookie.cookies = new Map(resetReader.cookies); copiedCookie.csrf = resetReader.csrf;
|
||||
assert.equal((await resetReader.request(hook + "/logout", { method: "POST", headers: { Origin: base, "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ csrf: resetReader.csrf }) })).status, 303);
|
||||
assert.equal((await copiedCookie.api("bootstrap")).status, 401);
|
||||
const brute = new Client();
|
||||
for (let i = 0; i < 8; i++) assert.equal((await brute.login("unknown", "invalid-test-password")).status, 401);
|
||||
assert.equal((await brute.login("unknown", "invalid-test-password")).status, 429);
|
||||
|
||||
const executablePath = [process.env.CHROME_PATH, "C:/Program Files/Google/Chrome/Application/chrome.exe", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p) => p && existsSync(p));
|
||||
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
|
||||
const errors = [];
|
||||
for (const [name, password] of [["reader", "reader-new-test-password"], ["office", "office-test-password"], ["device", "device-test-password"], ["admin", "admin-test-password"]]) {
|
||||
const context = await browser.createBrowserContext(), page = await context.newPage(); await page.setViewport({ width: 1440, height: 1000 });
|
||||
page.on("pageerror", (e) => errors.push(String(e)));
|
||||
await page.goto(base + hook + "/", { waitUntil: "networkidle0" });
|
||||
if (name === "reader") {
|
||||
await page.screenshot({ path: join(out, "symcon-login.png") });
|
||||
await page.setViewport({ width: 390, height: 844 }); await page.screenshot({ path: join(out, "symcon-login-mobile.png") });
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
|
||||
await page.setViewport({ width: 1440, height: 1000 });
|
||||
}
|
||||
await page.type("#username", name); await page.type("#password", password);
|
||||
const [navigation] = await Promise.all([page.waitForNavigation({ waitUntil: "networkidle0" }), page.click('button[type="submit"]')]);
|
||||
assert.ok(navigation.status() < 400, `Browser login failed: ${navigation.status()} ${await page.evaluate(() => document.body.innerText)}`);
|
||||
await page.waitForFunction(() => document.querySelector("nextfloor-panel")?.shadowRoot?.querySelector("nf-view3d")?.viewer).catch(async (e) => {
|
||||
await page.screenshot({ path: join(out, `symcon-access-${name}-failure.png`) });
|
||||
console.log("Mount failure", name, errors, await page.evaluate(() => ({ body: document.body.innerText.slice(0, 1500), panel: document.querySelector("nextfloor-panel")?.shadowRoot?.textContent.slice(-1800) })));
|
||||
throw e;
|
||||
});
|
||||
const info = await page.evaluate(() => {
|
||||
window.authPanel = document.querySelector("nextfloor-panel");
|
||||
return { admin: window.authPanel.hass.user.is_admin, editor: [...window.authPanel.shadowRoot.querySelectorAll("[role=tab]")].some((b) => b.textContent.includes("Editor")), ids: Object.keys(window.authPanel.hass.states) };
|
||||
});
|
||||
assert.equal(info.admin, name === "admin"); assert.equal(info.editor, name === "admin");
|
||||
if (name !== "admin") {
|
||||
await page.evaluate(() => window.authPanel.shadowRoot.querySelector("nf-view3d").dispatchEvent(new CustomEvent("room-tap", { detail: { floorId: "eg", roomId: "office2" }, bubbles: true, composed: true })));
|
||||
await page.waitForFunction(() => document.querySelector("nextfloor-panel").shadowRoot.querySelector("nf-room-panel")?.shadowRoot?.querySelector(".nf-rp"));
|
||||
const buttons = await page.evaluate(() => [...window.authPanel.shadowRoot.querySelector("nf-room-panel").shadowRoot.querySelectorAll(".nf-switch")].map((b) => ({ disabled: b.disabled, name: b.getAttribute("aria-label") })));
|
||||
if (name === "reader") assert.deepEqual(buttons, [], "readers get readouts, not switches");
|
||||
else {
|
||||
assert.ok(buttons.some((b) => !b.disabled)); assert.ok(!info.ids.includes("light.201"));
|
||||
await page.evaluate(() => window.authPanel.shadowRoot.querySelector("nf-room-panel").shadowRoot.querySelector(".nf-switch:not(:disabled)").click());
|
||||
await page.evaluate(() => window.authPanel.shadowRoot.querySelector("nf-view3d").dispatchEvent(new CustomEvent("room-tap", { detail: { floorId: "eg", roomId: "office3" }, bubbles: true, composed: true })));
|
||||
await page.waitForFunction(() => window.authPanel.shadowRoot.querySelector("nf-room-panel")?.room?.id === "office3");
|
||||
const forbiddenRoom = await page.evaluate(() => { const r = window.authPanel.shadowRoot.querySelector("nf-room-panel").shadowRoot; return { text: r.textContent, switches: r.querySelectorAll(".nf-switch").length }; });
|
||||
assert.match(forbiddenRoom.text, /keine Zustände freigegeben/); assert.equal(forbiddenRoom.switches, 0); assert.doesNotMatch(forbiddenRoom.text, /26[,.]7/);
|
||||
await page.screenshot({ path: join(out, `symcon-access-${name}-blocked-room.png`) });
|
||||
await page.evaluate(() => window.authPanel.shadowRoot.querySelector("nf-view3d").dispatchEvent(new CustomEvent("room-tap", { detail: { floorId: "eg", roomId: "office2" }, bubbles: true, composed: true })));
|
||||
}
|
||||
} else {
|
||||
await page.evaluate(() => [...window.authPanel.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.includes("Editor")).click());
|
||||
await page.waitForFunction(() => window.authPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot);
|
||||
}
|
||||
await page.screenshot({ path: join(out, `symcon-access-${name}.png`) });
|
||||
if (name === "admin") {
|
||||
const switched = new Client(); assert.equal((await switched.login("reader", "reader-new-test-password")).status, 303);
|
||||
await context.setCookie({ name: "NFSC_Session_12345", value: switched.cookies.get("NFSC_Session_12345"), url: base + hook + "/", path: hook + "/", httpOnly: true, sameSite: "Strict" });
|
||||
await page.waitForFunction(() => document.querySelector("nextfloor-panel")?.hass?.user?.name === "reader");
|
||||
assert.equal(await page.evaluate(() => document.querySelector("nextfloor-panel").hass.user.is_admin), false, "a shared-cookie account switch removes stale admin data in other tabs");
|
||||
}
|
||||
if (name === "reader") {
|
||||
await Promise.all([page.waitForNavigation({ waitUntil: "networkidle0" }), page.click('.nf-session-bar button')]);
|
||||
await page.waitForSelector("#username"); await page.goBack({ waitUntil: "networkidle0" });
|
||||
await page.waitForSelector("#username"); assert.equal(await page.$("nextfloor-panel"), null, "back navigation cannot restore the old account's view");
|
||||
}
|
||||
await context.close();
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("OK: real PHP login/cookies/CSRF, remembered session reset/logout/replay/throttling, room/device/native scopes, alias and archive/bulk/admin guards, console recovery, plus real reader/operator/admin browser UIs");
|
||||
} catch (e) {
|
||||
console.error(logs.split("\n").filter((line) => /error|warning|fatal/i.test(line)).slice(-12).join("\n")); throw e;
|
||||
} finally {
|
||||
await browser?.close(); php.kill(); await new Promise((done) => { if (php.exitCode !== null) done(); else php.once("exit", done); });
|
||||
if (existsSync(stateFile)) rmSync(stateFile); rmdirSync(dir);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// Regression coverage for the editor workflow: metadata separately, navigation without writes,
|
||||
// storeys created inside the selected building, native category links and explicit storey moves.
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer } from "node:http";
|
||||
import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { extname, join, relative, resolve } from "node:path";
|
||||
import puppeteer from "puppeteer-core";
|
||||
|
||||
const root = resolve(import.meta.dirname, ".."), out = join(root, "preview/screenshots");
|
||||
mkdirSync(out, { recursive: true });
|
||||
const server = createServer((req, res) => {
|
||||
const file = resolve(root, `.${decodeURIComponent(new URL(req.url, "http://localhost").pathname)}`);
|
||||
if (relative(root, file).startsWith("..") || !existsSync(file)) return res.writeHead(404).end();
|
||||
res.writeHead(200, { "content-type": ({ ".html": "text/html", ".js": "text/javascript", ".json": "application/json" })[extname(file)] ?? "application/octet-stream" }).end(readFileSync(file));
|
||||
});
|
||||
await new Promise((done) => server.listen(0, "127.0.0.1", done));
|
||||
let browser;
|
||||
try {
|
||||
const executablePath = [process.env.CHROME_PATH, "C:/Program Files/Google/Chrome/Application/chrome.exe", "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p) => p && existsSync(p));
|
||||
browser = await puppeteer.launch({ executablePath, headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] });
|
||||
const page = await browser.newPage(), errors = [];
|
||||
page.on("pageerror", (e) => errors.push(String(e)));
|
||||
await page.setViewport({ width: 1440, height: 1000 });
|
||||
await page.goto(`http://127.0.0.1:${server.address().port}/preview/index.html?noshowcase`, { waitUntil: "networkidle0" });
|
||||
await page.waitForFunction(() => window.nfPanel?.data.building?.floors.length);
|
||||
await page.evaluate(async () => {
|
||||
const p = window.nfPanel, b = structuredClone(p.data.building), base = b.floors[0];
|
||||
const room = (id, name, area_id) => ({ id, name, area_id, points: [[0, 0], [6, 0], [6, 5], [0, 5]], floor_material: "wood" });
|
||||
const floor = (id, building_id, rooms) => ({ ...structuredClone(base), id, name: "EG", building_id, rooms, elevation: 0, openings: [], furniture: [], placements: [], outdoor: [], walls: [], notes: [], background: null, utility_meters: null, power_entity: null, start_view: null });
|
||||
b.topology = { locations: [{ id: "u", name: "Urbach" }], branches: [{ id: "nl", name: "Zentrale", location_id: "u" }], buildings: [{ id: "a", name: "RAS19", branch_id: "nl" }, { id: "b", name: "RAS21", branch_id: "nl" }, { id: "empty", name: "Neubau", branch_id: "nl" }] };
|
||||
b.floors = [floor("eg-a", "a", [room("it-a", "IT", "symcon-category-100")]), floor("eg-b", "b", [room("it-b", "Büro", "symcon-category-200")])];
|
||||
b.settings.roof.type = "none"; b.settings.lock_plan = false; b.settings.start_view = null;
|
||||
window.editorProject = structuredClone(b);
|
||||
p.data.edit(b);
|
||||
p.hass = { ...p.hass, language: "de", symconObjects: [], symconTitle: "Standorte", floors: {}, areas: { "symcon-category-100": { area_id: "symcon-category-100", name: "Urbach / RAS19 / EG / IT" }, "symcon-category-200": { area_id: "symcon-category-200", name: "Urbach / RAS21 / EG / Technik" } }, states: {}, user: { ...p.hass.user, is_admin: true } };
|
||||
await p.updateComplete;
|
||||
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b) => b.textContent.includes("Editor")).click();
|
||||
});
|
||||
await page.waitForFunction(() => window.nfPanel.shadowRoot.querySelector("nf-editor")?.shadowRoot.querySelector(".nf-editor-building-select"));
|
||||
await page.evaluate(() => {
|
||||
window.e = window.nfPanel.shadowRoot.querySelector("nf-editor");
|
||||
window.settle = async () => { await e.updateComplete; await window.nfPanel.updateComplete; await e.updateComplete; };
|
||||
window.pickBuilding = async (id) => { const s = e.shadowRoot.querySelector(".nf-editor-building-select"); s.value = `building:${id}`; s.dispatchEvent(new Event("change", { bubbles: true })); await settle(); };
|
||||
window.manager = () => e.shadowRoot.querySelector("nf-hierarchy-manager");
|
||||
window.writes = 0; e.addEventListener("building-changed", () => window.writes++);
|
||||
});
|
||||
const initial = await page.evaluate(() => JSON.stringify(e._doc.floors));
|
||||
await page.evaluate(async () => { await pickBuilding("b"); e.moveFloor(-1); await settle(); await pickBuilding("empty"); });
|
||||
assert.deepEqual(await page.evaluate(() => ({ floor: e._floorId, scope: e._editorScope.id, chips: e.shadowRoot.querySelectorAll("[data-editor-floor]").length, writes })), { floor: null, scope: "empty", chips: 0, writes: 0 });
|
||||
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), initial, "building selection must not change or save floor assignments");
|
||||
await page.evaluate(async () => { const b = structuredClone(e._doc); b.topology.locations[0].name = "Urbach neu"; const p = window.nfPanel; p.data.building = b; p.requestUpdate(); await settle(); });
|
||||
assert.equal(await page.evaluate(() => e._floorId), null, "empty selection must survive a data refresh");
|
||||
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-editor-add-floor").click(); await settle(); window.addedFloor = e._floorId; });
|
||||
assert.deepEqual(await page.evaluate(() => ({ parent: e.floor.building_id, elevation: e.floor.elevation })), { parent: "empty", elevation: 0 });
|
||||
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors.filter((f) => f.id !== window.addedFloor))), initial);
|
||||
|
||||
// Native category selection remains a property of the selected room, never a building assignment.
|
||||
await page.evaluate(async () => { await pickBuilding("a"); e.shadowRoot.querySelector(".nf-room-list .nf-row").click(); await settle(); window.oldRoomActions = e.roomActions(e.room); });
|
||||
assert.match(await page.evaluate(() => e.shadowRoot.querySelector(".nf-room-context").textContent), /Urbach neu \/ Zentrale \/ RAS19 \/ EG/);
|
||||
assert.equal(await page.evaluate(() => !!e.shadowRoot.querySelector("aside nf-hierarchy-manager, aside .nf-topology-form")), false);
|
||||
await page.evaluate(async () => {
|
||||
const label = [...e.shadowRoot.querySelectorAll("label.nf-field")].find((l) => l.textContent.trim().startsWith("Bereich (Symcon)"));
|
||||
const s = label.querySelector("select"); s.value = "symcon-category-200"; s.dispatchEvent(new Event("change", { bubbles: true })); await settle();
|
||||
});
|
||||
assert.deepEqual(await page.evaluate(() => [e.room.name, e.room.area_id, e.floor.building_id]), ["IT", "symcon-category-200", "a"]);
|
||||
await page.screenshot({ path: join(out, "symcon-editor-building.png") });
|
||||
await page.evaluate(async () => { await pickBuilding("b"); window.beforeStale = JSON.stringify(e._doc); oldRoomActions.setArea("symcon-category-100"); oldRoomActions.patch({ name: "WRONG ROOM" }); await settle(); });
|
||||
assert.equal(await page.evaluate(() => JSON.stringify(e._doc)), await page.evaluate(() => window.beforeStale), "stale room form must not mutate a room in a different building");
|
||||
assert.equal(await page.evaluate(() => e.sel.room), null);
|
||||
|
||||
// A separate move dialog names and captures the selected floor; picking a target has no side effects.
|
||||
await page.evaluate(async () => { await pickBuilding("a"); e.shadowRoot.querySelector(".nf-editor-move-floor").click(); await settle(); });
|
||||
await page.waitForFunction(() => e.shadowRoot.querySelector(".nf-floor-move-dialog").open);
|
||||
const beforeMove = await page.evaluate(() => JSON.stringify(e._doc.floors));
|
||||
await page.evaluate(async () => { const s = e.shadowRoot.querySelector(".nf-floor-move-target"); s.value = "b"; s.dispatchEvent(new Event("change", { bubbles: true })); await settle(); });
|
||||
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), beforeMove);
|
||||
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-floor-move-dialog header button").click(); await settle(); });
|
||||
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), beforeMove);
|
||||
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-editor-move-floor").click(); await settle(); const s = e.shadowRoot.querySelector(".nf-floor-move-target"); s.value = "b"; s.dispatchEvent(new Event("change", { bubbles: true })); await settle(); e.shadowRoot.querySelector(".nf-floor-move-apply").click(); await settle(); });
|
||||
const expectedMove = JSON.parse(beforeMove); expectedMove.find((f) => f.id === "eg-a").building_id = "b";
|
||||
assert.deepEqual(await page.evaluate(() => e._doc.floors), expectedMove);
|
||||
assert.deepEqual(await page.evaluate(() => [e._editorScope.id, e._floorId]), ["b", "eg-a"]);
|
||||
|
||||
// Metadata creation is isolated from storey creation, even when opening a new empty building.
|
||||
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-hierarchy-open").click(); await settle(); });
|
||||
assert.equal(await page.evaluate(() => e.shadowRoot.querySelector(".nf-hierarchy-dialog").open), true);
|
||||
const beforeMetadata = await page.evaluate(() => JSON.stringify(e._doc.floors));
|
||||
await page.evaluate(async () => {
|
||||
const click = async (sel) => { manager().shadowRoot.querySelector(sel).click(); await manager().updateComplete; await settle(); await manager().updateComplete; };
|
||||
const rename = async (label, value) => { const input = [...manager().shadowRoot.querySelectorAll("label")].find((l) => l.textContent.startsWith(label)).querySelector("input"); input.value = value; input.dispatchEvent(new Event("change", { bubbles: true })); await settle(); await manager().updateComplete; };
|
||||
window.beforePickWrites = writes;
|
||||
await click('[data-building="empty"]'); await click('[data-building="b"]');
|
||||
if (writes !== beforePickWrites) throw new Error("Metadata selection must not write the plan");
|
||||
await click(".add-location"); await rename("Name des Ortes", "Stuttgart");
|
||||
await click(".add-branch"); await rename("Name der Niederlassung", "Werk");
|
||||
await click(".add-building"); await rename("Name des Gebäudes", "Halle 2");
|
||||
window.newMetadataBuilding = manager().buildingId;
|
||||
});
|
||||
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), beforeMetadata);
|
||||
await page.screenshot({ path: join(out, "symcon-editor-hierarchy.png") });
|
||||
await page.evaluate(async () => { manager().shadowRoot.querySelector(".open-building").click(); await settle(); });
|
||||
assert.deepEqual(await page.evaluate(() => [e._editorScope.id, e._floorId, e.shadowRoot.querySelector(".nf-hierarchy-dialog").open]), [await page.evaluate(() => window.newMetadataBuilding), null, false]);
|
||||
assert.equal(await page.evaluate(() => JSON.stringify(e._doc.floors)), beforeMetadata);
|
||||
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-editor-add-floor").click(); await settle(); });
|
||||
assert.equal(await page.evaluate(() => e.floor.building_id), await page.evaluate(() => window.newMetadataBuilding));
|
||||
|
||||
// Each location's outdoor plan is an explicit action, outside any building's storeys.
|
||||
await page.evaluate(async () => {
|
||||
const locations = e._doc.topology.locations.map((l) => l.id);
|
||||
for (const id of locations) { e.shadowRoot.querySelector(".nf-hierarchy-open").click(); await settle(); manager().shadowRoot.querySelector(`[data-location="${id}"]`).click(); await manager().updateComplete; manager().shadowRoot.querySelector(".outside").click(); await settle(); }
|
||||
});
|
||||
assert.equal(await page.evaluate(() => new Set(e._doc.floors.filter((f) => f.outdoor_location_id).map((f) => f.outdoor_location_id)).size), 2);
|
||||
assert.equal(await page.evaluate(() => !!e.shadowRoot.querySelector(".nf-editor-add-floor")), false, "outdoor plans do not add indoor storeys");
|
||||
|
||||
// Branches and buildings get their own outdoor plans, alongside existing location plans.
|
||||
for(const kind of ["branch","building"]){
|
||||
await page.evaluate(async(kind)=>{
|
||||
e.shadowRoot.querySelector(".nf-hierarchy-open").click();await settle();
|
||||
manager().shadowRoot.querySelector('[data-location="u"]').click();await manager().updateComplete;
|
||||
manager().shadowRoot.querySelector('[data-branch="nl"]').click();await manager().updateComplete;
|
||||
manager().shadowRoot.querySelector('[data-building="b"]').click();await manager().updateComplete;
|
||||
manager().shadowRoot.querySelector(`.outside-${kind}`).click();await settle();
|
||||
},kind);
|
||||
assert.equal(await page.evaluate(()=>e._editorScope.ownerKind),kind);
|
||||
assert.equal(await page.evaluate(()=>e.floor.building_id),null);
|
||||
assert.equal(await page.evaluate(()=>e.floor.outdoor_location_id),null);
|
||||
}
|
||||
await page.evaluate(async()=>{
|
||||
window.beforeGroup=JSON.stringify(e._doc);window.beforeGroupWrites=writes;
|
||||
const s=e.shadowRoot.querySelector(".nf-editor-building-select");s.value="branch:nl";s.dispatchEvent(new Event("change",{bubbles:true}));await settle();
|
||||
e._split=true;await settle();
|
||||
});
|
||||
assert.equal(await page.evaluate(()=>e._floorId),null,"branch overview must not implicitly edit a floor");
|
||||
assert.equal(await page.evaluate(()=>JSON.stringify(e._doc)),await page.evaluate(()=>window.beforeGroup));
|
||||
assert.equal(await page.evaluate(()=>writes),await page.evaluate(()=>window.beforeGroupWrites));
|
||||
assert.equal(await page.evaluate(()=>!!e.shadowRoot.querySelector(".nf-editor-add-floor")),false);
|
||||
assert.ok(await page.evaluate(()=>e.shadowRoot.querySelector('[data-editor-scope="outside:branch:nl"]')));
|
||||
await page.waitForFunction(()=>e.shadowRoot.querySelector("nf-view3d")?.viewer);
|
||||
assert.deepEqual(await page.evaluate(()=>e.shadowRoot.querySelector("nf-view3d").viewer.floors.map((f)=>f.floor.id).sort()),await page.evaluate(()=>{
|
||||
const buildings=new Set(e._doc.topology.buildings.filter((g)=>g.branch_id==="nl").map((g)=>g.id));
|
||||
return e._doc.floors.filter((f)=>buildings.has(f.building_id)||f.outdoor_branch_id==="nl"||buildings.has(f.outdoor_building_id)).map((f)=>f.id).sort();
|
||||
}));
|
||||
await page.screenshot({path:join(out,"symcon-editor-branch-overview.png")});
|
||||
|
||||
// A complete room move is explicit, cancellable and rejects a duplicate target device with visible feedback.
|
||||
await page.evaluate(async()=>{
|
||||
e._split=false;await pickBuilding("b");e.adoptFloor("eg-a");e.selectItem("room","it-a");
|
||||
e.change((b,f)=>{f.furniture.push({id:"moved-desk",type:"desk",variant:null,x:1,z:1,w:1,d:1,h:1,rotation:0,power:"sensor.100"});f.placements.push({entity_id:"switch.100",x:2,z:2,y:1});b.floors.find((f)=>f.id===window.addedFloor).placements.push({entity_id:"switch.100",x:0,z:0,y:1});});await settle();
|
||||
window.moveBefore=JSON.stringify(e._doc);e.shadowRoot.querySelector(".nf-room-move-open").click();await settle();
|
||||
window.chooseRoomTarget=async()=>{const g=e.shadowRoot.querySelector(".nf-room-move-building");g.value="empty";g.dispatchEvent(new Event("change",{bubbles:true}));await settle();const f=e.shadowRoot.querySelector(".nf-room-move-floor");f.value=window.addedFloor;f.dispatchEvent(new Event("change",{bubbles:true}));await settle();};
|
||||
await chooseRoomTarget();
|
||||
});
|
||||
assert.equal(await page.evaluate(()=>JSON.stringify(e._doc)),await page.evaluate(()=>window.moveBefore));
|
||||
await page.evaluate(async()=>{e.shadowRoot.querySelector(".nf-room-move-apply").click();await settle();});
|
||||
assert.match(await page.evaluate(()=>e.shadowRoot.querySelector(".nf-room-move-error").textContent),/Kennung/);
|
||||
assert.equal(await page.evaluate(()=>JSON.stringify(e._doc)),await page.evaluate(()=>window.moveBefore));
|
||||
await page.evaluate(async()=>{e.shadowRoot.querySelector(".nf-room-move-dialog header button").click();await settle();e.change((b)=>{b.floors.find((f)=>f.id===window.addedFloor).placements=[];});await settle();window.moveBefore=JSON.stringify(e._doc);e.shadowRoot.querySelector(".nf-room-move-open").click();await settle();await chooseRoomTarget();});
|
||||
await page.waitForFunction(()=>e.shadowRoot.querySelector(".nf-room-move-dialog").open&&e.shadowRoot.querySelector(".nf-room-move-floor"));
|
||||
await page.screenshot({path:join(out,"symcon-editor-room-move.png")});
|
||||
await page.evaluate(async()=>{e.shadowRoot.querySelector(".nf-room-move-dialog header button").click();await settle();});
|
||||
assert.equal(await page.evaluate(()=>JSON.stringify(e._doc)),await page.evaluate(()=>window.moveBefore),"cancelling a room move must preserve the full plan");
|
||||
await page.evaluate(async()=>{e.shadowRoot.querySelector(".nf-room-move-open").click();await settle();await chooseRoomTarget();e.shadowRoot.querySelector(".nf-room-move-apply").click();await settle();});
|
||||
const moved=await page.evaluate(()=>[e._floorId,e.room?.id,e.room?.name,e.room?.area_id,e.floor?.furniture[0]?.id,e.floor?.furniture[0]?.power,e.floor?.placements[0]?.entity_id]);
|
||||
if(!moved.at(-1))console.log(await page.evaluate(()=>({move:e._roomMove,floors:e._doc.floors.map((f)=>({id:f.id,rooms:f.rooms.map((r)=>({id:r.id,points:r.points})),devices:f.placements,furniture:f.furniture.map((f)=>({id:f.id,x:f.x,z:f.z}))}))})));
|
||||
assert.deepEqual(moved,[await page.evaluate(()=>window.addedFloor),"it-a","IT","symcon-category-200","moved-desk","sensor.100","switch.100"]);
|
||||
assert.equal(await page.evaluate(()=>e._doc.floors.find((f)=>f.id==="eg-a").rooms.length),0);
|
||||
assert.equal(await page.evaluate(()=>e._doc.floors.find((f)=>f.id==="eg-a").furniture.length),0);
|
||||
|
||||
await page.setViewport({ width: 390, height: 844 });
|
||||
await page.evaluate(async () => { e.shadowRoot.querySelector(".nf-hierarchy-open").click(); await settle(); });
|
||||
assert.ok(await page.evaluate(() => { const d = e.shadowRoot.querySelector(".nf-hierarchy-dialog"), r = d.getBoundingClientRect(); return r.left >= 0 && r.right <= innerWidth && r.height <= innerHeight && d.scrollWidth <= d.clientWidth; }), "hierarchy dialog must fit a phone without horizontal scrolling");
|
||||
await page.screenshot({ path: join(out, "symcon-editor-hierarchy-mobile.png") });
|
||||
|
||||
// Legacy setup is explicit and preserves stable IDs, geometry and native category links.
|
||||
await page.evaluate(async () => {
|
||||
e.shadowRoot.querySelector(".nf-hierarchy-dialog").close(); const p = window.nfPanel, b = structuredClone(window.editorProject); delete b.topology; for (const f of b.floors) delete f.building_id; window.legacyFloors = structuredClone(b.floors); p.data.edit(b); await settle();
|
||||
e.shadowRoot.querySelector(".nf-hierarchy-open").click(); await settle(); manager().shadowRoot.querySelector(".setup-button").click(); await settle();
|
||||
});
|
||||
assert.deepEqual(await page.evaluate(() => e._doc.floors.map(({ building_id, ...f }) => f)), await page.evaluate(() => window.legacyFloors));
|
||||
assert.equal(await page.evaluate(() => new Set(e._doc.floors.map((f) => f.building_id)).size), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("OK: separate hierarchy dialog, pure building/branch navigation and scoped 3D overview, selected-building storeys, native room links, floor moves, independent location/branch/building outdoors, explicit/cancelled room moves with contents and duplicate-device feedback, legacy migration and mobile layout");
|
||||
} finally {
|
||||
await browser?.close(); await new Promise((done) => server.close(done));
|
||||
}
|
||||
@@ -33,6 +33,9 @@ try{
|
||||
point(505,"cover",true);point(506,"climate",false,"",{symcon_has_action:true});point(507,"light",73,"%",{symcon_variable_type:1});
|
||||
point(508,"cover",0,"",{symcon_variable_type:1,symcon_has_action:true,symcon_max:255,symcon_step:1});point(509,"cover",48,"W");
|
||||
point(510,"lock",true);point(511,"cover",false,"",{symcon_has_action:true});point(512,"sensor",47.1,"°C");point(520,"cover",49.3,"°C");point(521,"light",false);point(522,"cover",true,"",{symcon_has_action:true});
|
||||
point(530,"cover",0,"",{symcon_variable_type:1,symcon_formatted:"Bereitschaft",symcon_has_action:true,symcon_archive:{id:999,counter:false}});
|
||||
point(531,"light",7,"",{symcon_variable_type:1,symcon_formatted:"Warmwasserbereitung",symcon_has_action:true});
|
||||
point(532,"lock",2,"",{symcon_variable_type:1,symcon_formatted:"Automatik"});
|
||||
for(let i=0;i<7;i++)point(601+i,"cover",65-i*7,"°C");
|
||||
const buffer={id:"buffer",type:"buffer_tank",name:"Puffer",x:1.2,z:0,w:.85,d:.85,h:1.85,rotation:0,variant:null,hydronic:{sensors:Array.from({length:7},(_,i)=>({id:`p${i}`,name:`Fühler ${i+1}`,entity:`cover.${601+i}`,level:1-i/6}))}};
|
||||
const fresh={id:"fresh",type:"freshwater_station",name:"Frischwasser",x:-2,z:0,w:.65,d:.28,h:.9,rotation:0,variant:null,mount_y:.7,hydronic:{flow:"cover.501",return:"light.502",hot_water:"climate.503",pump:{feedback:"cover.505"},circulation:{feedback:"lock.510",command:"cover.511"},circulation_temperature:"sensor.512",buffer_id:"buffer"}};
|
||||
@@ -58,6 +61,10 @@ try{
|
||||
};
|
||||
const unit=()=>e.shadowRoot.querySelector(".nf-freshwater-station");
|
||||
if(e._doc.floors[0].furniture[0].hydronic.stations)throw new Error("Merely opening an old single station must not rewrite its data");
|
||||
await window.pickFresh(e.shadowRoot.querySelector(".nf-hydronic-form"),"Anlagenstatus",532);
|
||||
await window.pickFresh(unit(),"Status",530);
|
||||
const single=document.createElement("nf-hydronic-card");Object.assign(single,{hass:p.hass,item:e._doc.floors[0].furniture[0]});document.body.append(single);await single.updateComplete;
|
||||
if(!single.shadowRoot.querySelector('[data-source="cover.530"]')?.textContent.includes("Bereitschaft")||!single.shadowRoot.querySelector('[data-source="lock.532"]')?.textContent.includes("Automatik"))throw new Error("Single-station/plant aliases missing");single.remove();
|
||||
await window.pickFresh(unit(),"Kaltwasser",504);await window.pickFresh(unit(),"Pumpenleistung",509);
|
||||
const pump=()=>[...unit().querySelectorAll(".nf-hydronic-control")].find((c)=>c.querySelector("summary").textContent==="Ladepumpe");pump().open=true;
|
||||
await window.pickFresh(pump(),"Befehl",506);
|
||||
@@ -66,9 +73,10 @@ try{
|
||||
for(let i=0;i<3;i++){e.shadowRoot.querySelector(".nf-freshwater-add").click();await window.settleFresh();}
|
||||
const cfg=e._doc.floors[0].furniture[0].hydronic;
|
||||
if(cfg.stations.length!==4||cfg.stations[0].flow!=="cover.501"||cfg.flow!==undefined||cfg.pump!==undefined)throw new Error("Single-station migration lost links or left ghost shared data");
|
||||
if(!cfg.stations.slice(1).every((s)=>!s.flow&&!s.pump))throw new Error("New cascade modules must not copy another station's datapoints");
|
||||
if(!cfg.stations.slice(1).every((s)=>!s.flow&&!s.pump&&!s.status))throw new Error("New cascade modules must not copy another station's datapoints");
|
||||
window.secondFresh=cfg.stations[1].id;window.firstFresh=cfg.stations[0].id;
|
||||
const second=()=>e.shadowRoot.querySelector(`[data-station="${window.secondFresh}"]`);second().open=true;
|
||||
await window.pickFresh(second(),"Status",531);
|
||||
await window.pickFresh(second(),"Trinkwarmwasser",520);
|
||||
const pump2=()=>[...second().querySelectorAll(".nf-hydronic-control")].find((c)=>c.querySelector("summary").textContent==="Ladepumpe");pump2().open=true;
|
||||
await window.pickFresh(pump2(),"Rückmeldung",521);await window.pickFresh(pump2(),"Befehl",522);
|
||||
@@ -88,19 +96,23 @@ try{
|
||||
await page.waitForFunction(()=>window.freshView.shadowRoot.querySelector('nf-hydronic-card')?.shadowRoot?.querySelectorAll(".station-summary").length===4);
|
||||
assert.equal(await page.evaluate(()=>window.freshView._liveCards.filter((c)=>c.kind==="hydronic"&&c.item.id==="fresh").length),1,"the cascade never creates one floating overlay per module");
|
||||
assert.equal(await page.evaluate(()=>[...window.freshView.shadowRoot.querySelectorAll("nf-hydronic-card")].find((c)=>c.item.id==="fresh").shadowRoot.querySelector(".station-summary nf-trend-button")?.ids[0]),"climate.503","the compact cascade retains native archive access beside its displayed value");
|
||||
assert.ok(await page.evaluate(()=>["cover.520","light.521","cover.522","cover.509"].every((id)=>window.freshView.watched.includes(id))));
|
||||
assert.ok(await page.evaluate(()=>["cover.520","light.521","cover.522","cover.509","cover.530","light.531","lock.532"].every((id)=>window.freshView.watched.includes(id))));
|
||||
assert.deepEqual(await page.evaluate(()=>{const card=[...window.freshView.shadowRoot.querySelectorAll("nf-hydronic-card")].find((c)=>c.item.id==="fresh");return [...card.shadowRoot.querySelectorAll(".station-summary")].map((s)=>s.querySelector(".status-text")?.textContent??null);}),["Bereitschaft","Warmwasserbereitung",null,null],"cascade statuses stay with their own station; unlinked rows stay hidden");
|
||||
await page.evaluate(()=>{const card=[...window.freshView.shadowRoot.querySelectorAll("nf-hydronic-card")].find((c)=>c.item.id==="fresh");card.shadowRoot.querySelectorAll(".station-name")[1].click();});
|
||||
await page.waitForFunction(()=>document.querySelector("nf-hydronic-dialog")?.shadowRoot.querySelector("dialog")?.open);
|
||||
assert.equal(await page.evaluate(()=>document.querySelector("nf-hydronic-dialog").shadowRoot.querySelector(`[data-station="${window.secondFresh}"]`).open),true);
|
||||
assert.deepEqual(await page.evaluate(()=>{const r=document.querySelector("nf-hydronic-dialog").shadowRoot;return [r.querySelector('[data-source="cover.530"] .status-text')?.textContent,r.querySelector('[data-source="light.531"] .status-text')?.textContent,r.querySelector('[data-source="lock.532"] .status-text')?.textContent,r.querySelector('[data-source="cover.530"] nf-trend-button')?.ids[0],r.querySelectorAll('[data-command="cover.530"],[data-command="light.531"]').length];}),["Bereitschaft","Warmwasserbereitung","Automatik","cover.530",0],"native aliases and archive access are read-only even on writable integer variables");
|
||||
await page.evaluate(()=>document.querySelector("nf-hydronic-dialog").shadowRoot.querySelector('[data-command="cover.522"]').click());
|
||||
assert.deepEqual(await page.evaluate(()=>window.freshWrites.at(-1)),{domain:"symcon",service:"set_value",data:{entity_id:"cover.522",value:false}},"only the selected station's native command is written");
|
||||
await page.evaluate(()=>{const input=document.querySelector("nf-hydronic-dialog").shadowRoot.querySelector('[data-command="cover.508"]');input.value="0";input.dispatchEvent(new Event("change",{bubbles:true}));});
|
||||
assert.deepEqual(await page.evaluate(()=>window.freshWrites.at(-1)),{domain:"symcon",service:"set_value",data:{entity_id:"cover.508",value:0}},"native zero and 0…255 valve ranges remain unchanged");
|
||||
await page.evaluate(()=>{const p=window.nfPanel,states={...p.hass.states};states["cover.505"]={...states["cover.505"],state:"unavailable"};states["climate.503"]={...states["climate.503"],attributes:{...states["climate.503"].attributes,symcon_value:0,symcon_formatted:"0 °C"}};p.hass={...p.hass,states};});
|
||||
await page.evaluate(()=>{const p=window.nfPanel,states={...p.hass.states};states["cover.505"]={...states["cover.505"],state:"unavailable"};states["cover.530"]={...states["cover.530"],attributes:{...states["cover.530"].attributes,symcon_value:7,symcon_formatted:"Ladebetrieb"}};states["light.531"]={...states["light.531"],state:"unavailable"};states["climate.503"]={...states["climate.503"],attributes:{...states["climate.503"].attributes,symcon_value:0,symcon_formatted:"0 °C"}};p.hass={...p.hass,states};});
|
||||
await page.waitForFunction(()=>document.querySelector("nf-hydronic-dialog").shadowRoot.querySelector('[data-source="climate.503"]')?.textContent.includes("0 °C"));
|
||||
await page.waitForFunction(()=>window.freshView.viewer.hydronicLayer.group.getObjectByName("hydronic-fresh").getObjectByName("hydronic-pumpState-station-0").material.color.getHex()===0x72787e);
|
||||
assert.equal(await page.evaluate(()=>window.freshView.viewer.hydronicLayer.group.getObjectByName("hydronic-fresh").getObjectByName("hydronic-pumpState-station-0").material.color.getHex()),0x72787e);
|
||||
assert.equal(await page.evaluate(()=>window.freshView.viewer.hydronicLayer.group.getObjectByName("hydronic-fresh").getObjectByName("hydronic-pumpState-station-1").material.color.getHex()),0xa82638,"another station remains stopped, not unavailable");
|
||||
await page.waitForFunction(()=>document.querySelector("nf-hydronic-dialog").shadowRoot.querySelector('[data-source="cover.530"] .status-text')?.textContent==="Ladebetrieb");
|
||||
await page.waitForFunction(()=>{const card=[...window.freshView.shadowRoot.querySelectorAll("nf-hydronic-card")].find((c)=>c.item.id==="fresh");return card.shadowRoot.querySelector('[data-source="cover.530"] .status-text')?.textContent==="Ladebetrieb"&&card.shadowRoot.querySelector('[data-source="light.531"] .status-text')?.textContent==="–";});
|
||||
await page.setViewport({width:390,height:844});
|
||||
assert.ok(await page.evaluate(()=>{const r=document.querySelector("nf-hydronic-dialog").shadowRoot.querySelector("dialog").getBoundingClientRect();return r.left>=0&&r.right<=innerWidth&&r.top>=0&&r.bottom<=innerHeight;}));
|
||||
await page.screenshot({path:join(out,"symcon-freshwater-mobile.png")});
|
||||
@@ -114,7 +126,8 @@ try{
|
||||
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b)=>b.textContent.trim()==="3D").click();
|
||||
});
|
||||
await page.waitForFunction(()=>window.nfPanel.shadowRoot.querySelector("nf-view3d")?.watched&&!window.nfPanel.shadowRoot.querySelector("nf-view3d").watched.includes("cover.520"));
|
||||
assert.ok(await page.evaluate(()=>!window.nfPanel.shadowRoot.querySelector("nf-view3d").watched.includes("light.531")),"removed station releases its status subscription");
|
||||
await page.evaluate(async()=>{const p=window.nfPanel,b=structuredClone(p.data.building);b.floors[0].furniture=b.floors[0].furniture.filter((f)=>f.id!=="buffer");p.data.edit(b);await p.updateComplete;});
|
||||
await page.waitForFunction(()=>!window.nfPanel.shadowRoot.querySelector("nf-view3d").viewer.hydronicLayer.group.getObjectByName("hydronic-connection-fresh"));
|
||||
assert.deepEqual(errors,[]);console.log("OK: legacy migration; four independent native stations; primary-only storage connections; compact cascade card; own commands/zero/offline feedback; archive readouts; removal/resize/subscription cleanup and mobile dialog");
|
||||
assert.deepEqual(errors,[]);console.log("OK: native status picker/aliases, plant/single/cascade read-only statuses, live zero/offline status, archive access and scoped subscriptions; legacy migration; four independent native stations; primary-only storage connections; compact cascade card; own commands/zero/offline feedback; archive readouts; removal/resize/subscription cleanup and mobile dialog");
|
||||
}finally{await browser?.close();await new Promise((done)=>server.close(done));}
|
||||
@@ -41,6 +41,8 @@ try {
|
||||
variable(601,"Garagenwert Pumpenbefehl",false,"cover",{symcon_has_action:true}); variable(602,"Rückmeldung Vorschub",true,"lock");
|
||||
variable(603,"Ventil Soll",128,"light",{symcon_variable_type:1,symcon_max:255,symcon_step:1,symcon_has_action:true}); variable(604,"Ventil Ist",32,"climate",{unit_of_measurement:"%",symcon_formatted:"32 %"});
|
||||
variable(605,"Vorlauf beliebiger Name",42.3,"cover",{unit_of_measurement:"°C",symcon_archive:{id:999,counter:false}}); variable(606,"Rücklauf",34.1,"light",{unit_of_measurement:"°C"});
|
||||
variable(608,"Garagenwert",0,"cover",{symcon_variable_type:1,symcon_formatted:"Bereitschaft",symcon_has_action:true});
|
||||
variable(609,"Objekt",2,"lock",{symcon_variable_type:1,symcon_formatted:"Automatik"});
|
||||
for(let i=0;i<8;i++) variable(701+i,`Speicherfühler ${i+1}`,60-i*5,i%2?"climate":"cover",{unit_of_measurement:"°C"});
|
||||
for(const [id,name,value] of [[801,"Frischwasser Vorlauf",70],[802,"Frischwasser Rücklauf",35],[803,"Zirkulationstemperatur",45],[804,"Trinkwarmwasser",52]]) variable(id,name,value,"sensor",{unit_of_measurement:"°C"});
|
||||
variable(805,"Zirkulationsbefehl",false,"switch",{symcon_has_action:true}); variable(806,"Zirkulationsrückmeldung",true,"cover");
|
||||
@@ -75,6 +77,8 @@ try {
|
||||
row.click();await native.updateComplete;native.shadowRoot.querySelector(".apply").click();await window.editorSettle();
|
||||
};
|
||||
const circuit=()=>e.shadowRoot.querySelector('.nf-hydronic-circuit[data-circuit="c1"]');
|
||||
await window.pickHydronic(circuit(),"Status",608,"Garagenwert");
|
||||
await window.pickHydronic(e.shadowRoot.querySelector(".nf-hydronic-form"),"Anlagenstatus",609,"Objekt");
|
||||
const pumpToggle=[...circuit().querySelectorAll("label.nf-check")].find((l)=>l.textContent.includes("Pumpe vorhanden"));pumpToggle.querySelector("input").click();await window.editorSettle();
|
||||
const valveType=()=>[...circuit().querySelectorAll("label.nf-field")].find((l)=>l.textContent.trim().startsWith("Ventilbauart")).querySelector("select");
|
||||
valveType().value="two_way";valveType().dispatchEvent(new Event("change",{bubbles:true}));await window.editorSettle();
|
||||
@@ -124,6 +128,8 @@ try {
|
||||
await page.waitForFunction(()=>window.nfPanel.shadowRoot.querySelector("nf-view3d")?.shadowRoot.querySelectorAll("nf-hydronic-card").length===3);
|
||||
await page.evaluate(()=>window.hydView=window.nfPanel.shadowRoot.querySelector("nf-view3d"));
|
||||
await page.waitForFunction(()=>[...window.hydView.shadowRoot.querySelectorAll("nf-hydronic-card")].every((c)=>c.shadowRoot?.querySelector(".title")));
|
||||
assert.deepEqual(await page.evaluate(()=>{const card=[...window.hydView.shadowRoot.querySelectorAll("nf-hydronic-card")].find((c)=>c.item.id==="manifold");return [...card.shadowRoot.querySelectorAll(".status-text")].map((s)=>s.textContent);}),["Automatik","Bereitschaft"],"manifold and circuit display native aliases, including zero, independently of names/domain");
|
||||
assert.ok(await page.evaluate(()=>["cover.608","lock.609"].every((id)=>window.hydView.watched.includes(id))));
|
||||
assert.ok(requests.some((r)=>/nextfloor-hydronics\.js\?v=[a-f0-9]{12}/.test(r)),"the lazy chunk has a content hash");
|
||||
assert.equal(await page.evaluate(()=>window.nfPanel.data.building.floors[0].furniture.find((f)=>f.id==="buffer").hydronic.sensors.length),8);
|
||||
await page.waitForFunction(()=>window.hydView.viewer?.hydronicLayer.group.children.length===3);
|
||||
|
||||
@@ -66,7 +66,7 @@ try {
|
||||
await drag([7.12, 0.14], [9.1, 2.2]);
|
||||
const drawn = await page.evaluate(() => window.outdoorEditor._doc.floors[0].outdoor.at(-1));
|
||||
assert.ok(drawn.points.some(([x, z]) => x === 7.03 && z === 0.07), "new rectangle starts at the adjacent exact corner");
|
||||
for (const [type, label] of [["street", "Straße"], ["sidewalk", "Gehweg"], ["gravel", "Schotterfläche"], ["river", "Fluss"], ["stream", "Bach"]]) {
|
||||
for (const [type, label] of [["street", "Straße"], ["sidewalk", "Gehweg"], ["gravel", "Schotterfläche"], ["river", "Fluss"], ["stream", "Bach"], ["pavers", "Pflastersteine"], ["stepping_stones", "Trittplatten"], ["natural_stone", "Natursteinweg"]]) {
|
||||
const stored = await page.evaluate(async ({ type, label, id }) => {
|
||||
const e = window.outdoorEditor; e._tool = "select"; e.selectItem("outdoor", id); await e.updateComplete;
|
||||
const input = [...e.shadowRoot.querySelectorAll("select")].find((s) => [...s.options].some((o) => o.value === type && o.textContent === label));
|
||||
@@ -76,13 +76,33 @@ try {
|
||||
}, { type, label, id: drawn.id });
|
||||
assert.equal(stored, type);
|
||||
}
|
||||
const textureEdit = await page.evaluate(async (id) => {
|
||||
const e = window.outdoorEditor;
|
||||
const setNumber = async (label, value) => {
|
||||
const field = [...e.shadowRoot.querySelectorAll("label.nf-field")].find((l) => l.textContent.trim().startsWith(label));
|
||||
const input = field?.querySelector("input"); if (!input) throw new Error(`Missing ${label}`);
|
||||
input.value = String(value); input.dispatchEvent(new Event("change", { bubbles: true })); await e.updateComplete;
|
||||
};
|
||||
await setNumber("Texturmaßstab", 250); await setNumber("Texturdrehung", -90);
|
||||
let a = e._doc.floors[0].outdoor.find((a) => a.id === id);
|
||||
const custom = [a.texture_scale, a.texture_rotation];
|
||||
await setNumber("Texturmaßstab", 0); const minimum = e._doc.floors[0].outdoor.find((a) => a.id === id).texture_scale;
|
||||
await setNumber("Texturmaßstab", 100); await setNumber("Texturdrehung", 360);
|
||||
a = e._doc.floors[0].outdoor.find((a) => a.id === id);
|
||||
const reset = [a.texture_scale, a.texture_rotation];
|
||||
await setNumber("Texturmaßstab", 250); await setNumber("Texturdrehung", 45);
|
||||
const doc = JSON.parse(JSON.stringify(e._doc)); e.setDoc(doc); await e.updateComplete;
|
||||
const saved = doc.floors[0].outdoor.find((a) => a.id === id);
|
||||
return { custom, minimum, reset, saved: [saved.texture_scale, saved.texture_rotation], neighbor: doc.floors[0].outdoor.find((a) => a.id === "neighbor").texture_scale ?? null };
|
||||
}, drawn.id);
|
||||
assert.deepEqual(textureEdit, { custom: [2.5, 270], minimum: 0.05, reset: [null, null], saved: [2.5, 45], neighbor: null });
|
||||
await page.screenshot({ path: join(out, "symcon-outdoor-editor.png") });
|
||||
await page.evaluate(async () => {
|
||||
const p = window.nfPanel, b = structuredClone(window.outdoorEditor._doc), f = b.floors[0];
|
||||
const types = ["lawn", "terrace", "path", "driveway", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola"];
|
||||
const types = ["lawn", "terrace", "path", "driveway", "street", "sidewalk", "gravel", "river", "stream", "pool", "bed", "wild", "hedge", "fence", "pergola", "pavers", "stepping_stones", "natural_stone"];
|
||||
f.outdoor = types.map((type, i) => {
|
||||
const x = (i % 5) * 5, z = Math.floor(i / 5) * 4;
|
||||
return { id: type, type, points: [[x, z], [x + 4, z], [x + 4, z + 3], [x, z + 3]], ...(type === "sidewalk" ? { slope: 0.25 } : {}), ...(type === "stream" ? { opacity: 0.6 } : {}) };
|
||||
return { id: type, type, points: [[x, z], [x + 4, z], [x + 4, z + 3], [x, z + 3]], ...(type === "terrace" ? { texture_scale: 2.5, texture_rotation: 45 } : {}), ...(type === "sidewalk" ? { slope: 0.25, texture_scale: 0.5, texture_rotation: 90 } : {}), ...(type === "stream" ? { opacity: 0.6, texture_scale: 1.5, texture_rotation: 330 } : {}) };
|
||||
});
|
||||
f.rooms = [{ id: "reference", name: "Referenz", points: [[-2, -2], [-1, -2], [-1, -1], [-2, -1]], area_id: null, floor_material: "plain" }];
|
||||
f.furniture = []; p.data.edit(b); await p.updateComplete;
|
||||
@@ -94,14 +114,14 @@ try {
|
||||
await page.evaluate(() => {
|
||||
window.outdoorView = window.nfPanel.shadowRoot.querySelector("nf-view3d");
|
||||
window.nfPanel.openFloor(window.outdoorFloor);
|
||||
window.outdoorView.viewer.showView({ target: { x: 12, y: 0, z: 5.5 }, radius: 25, phi: 0.65, theta: 0.1 }, 0);
|
||||
window.outdoorView.viewer.showView({ target: { x: 12, y: 0, z: 7.5 }, radius: 29, phi: 0.65, theta: 0.1 }, 0);
|
||||
});
|
||||
for (const theme of ["neon", "day", "blueprint"]) {
|
||||
await page.evaluate((theme) => { const v = window.outdoorView.viewer; v.setTheme(theme); v.invalidate(); }, theme);
|
||||
await page.evaluate(() => new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(done))));
|
||||
await page.screenshot({ path: join(out, `symcon-outdoor-${theme}.png`) });
|
||||
}
|
||||
for (const [name, x, z] of [["street", 22, 1.5], ["gravel", 7, 5.5], ["lawn", 2, 1.5]]) {
|
||||
for (const [name, x, z] of [["street", 22, 1.5], ["gravel", 7, 5.5], ["lawn", 2, 1.5], ["terrace", 7, 1.5], ["pavers", 2, 13.5], ["stepping-stones", 7, 13.5], ["natural-stone", 12, 13.5]]) {
|
||||
await page.evaluate(({ x, z }) => {
|
||||
const v = window.outdoorView.viewer; v.setTheme("day"); v.showView({ target: { x, y: 0, z }, radius: 5, phi: 0.65, theta: 0.1 }, 0);
|
||||
}, { x, z });
|
||||
@@ -111,14 +131,27 @@ try {
|
||||
const gpu = await page.evaluate(() => {
|
||||
const v = window.outdoorView.viewer;
|
||||
let textured = 0, neutral = 0;
|
||||
const transforms = {};
|
||||
v.scene.traverse((o) => {
|
||||
const ids = o.geometry?.getAttribute("surface");
|
||||
if (ids) { for (const kind of ids.array) kind > 0 ? textured++ : neutral++; }
|
||||
if (ids) {
|
||||
const settings = o.geometry.getAttribute("surfaceTransform");
|
||||
if (!settings || settings.count !== ids.count) throw new Error("Outdoor texture transform buffer mismatch");
|
||||
for (let i = 0; i < ids.count; i++) {
|
||||
const kind = ids.getX(i); kind > 0 ? textured++ : neutral++;
|
||||
if (kind > 0) (transforms[kind] ??= []).push([settings.getX(i), settings.getY(i)]);
|
||||
}
|
||||
}
|
||||
});
|
||||
return { textured, neutral, programs: v.renderer.info.programs.map((p) => p.diagnostics?.runnable !== false) };
|
||||
return { textured, neutral, transforms, programs: v.renderer.info.programs.map((p) => p.diagnostics?.runnable !== false) };
|
||||
});
|
||||
for (const [id, scale, rotation] of [[2, 2.5, Math.PI / 4], [11, 0.5, Math.PI / 2], [14, 1.5, 330 * Math.PI / 180]]) {
|
||||
assert.ok(gpu.transforms[id]?.length > 0);
|
||||
assert.ok(gpu.transforms[id].every(([s, r]) => s === scale && Math.abs(r - rotation) < 1e-6));
|
||||
}
|
||||
assert.ok(gpu.textured > 0); assert.ok(gpu.programs.every(Boolean)); assert.deepEqual(errors, []);
|
||||
console.log("OK: pointer drawing/moving/corner snapping, Alt bypass, five persisted surface types, metre-scaled textures compiled in all three themes, sloped and transparent surfaces", gpu);
|
||||
delete gpu.transforms;
|
||||
console.log("OK: outdoor snapping, surface types, per-area texture size/rotation/reset/persistence, independent GPU transforms in all three themes including sloped and transparent surfaces", gpu);
|
||||
} finally {
|
||||
await browser?.close(); await new Promise((done) => server.close(done));
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
// Actual designer and tile UI, hierarchy isolation, per-location outdoors and scoped GPU previews.
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer } from "node:http";
|
||||
import { existsSync,mkdirSync,readFileSync } from "node:fs";
|
||||
import { extname,join,relative,resolve } from "node:path";
|
||||
import puppeteer from "puppeteer-core";
|
||||
const root=resolve(import.meta.dirname,".."),out=join(root,"preview/screenshots");mkdirSync(out,{recursive:true});
|
||||
const server=createServer((req,res)=>{const file=resolve(root,`.${decodeURIComponent(new URL(req.url,"http://localhost").pathname)}`);if(relative(root,file).startsWith("..")||!existsSync(file))return res.writeHead(404).end();res.writeHead(200,{"content-type":({".html":"text/html",".js":"text/javascript",".json":"application/json"})[extname(file)]??"application/octet-stream"}).end(readFileSync(file));});
|
||||
await new Promise((done)=>server.listen(0,"127.0.0.1",done));let browser;
|
||||
try{
|
||||
const executablePath=[process.env.CHROME_PATH,"C:/Program Files/Google/Chrome/Application/chrome.exe","C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"].find((p)=>p&&existsSync(p));
|
||||
browser=await puppeteer.launch({executablePath,headless:true,args:["--use-angle=swiftshader","--enable-unsafe-swiftshader"]});
|
||||
const page=await browser.newPage(),errors=[];
|
||||
page.on("pageerror",(e)=>errors.push(String(e)));page.on("console",(m)=>{if(m.type()==="error"&&/THREE|WebGL|shader|GL_INVALID/i.test(m.text()))errors.push(m.text());});
|
||||
await page.setViewport({width:1440,height:1000});
|
||||
await page.goto(`http://127.0.0.1:${server.address().port}/preview/index.html?noshowcase`,{waitUntil:"networkidle0"});
|
||||
await page.waitForFunction(()=>window.nfPanel?.data.building?.floors.length);
|
||||
await page.evaluate(async()=>{
|
||||
const p=window.nfPanel,b=structuredClone(p.data.building),base=b.floors[0];
|
||||
const room=(id,name,x,z,w,d,material)=>({id,name,area_id:null,points:[[x,z],[x+w,z],[x+w,z+d],[x,z+d]],floor_material:material,climate_card:false});
|
||||
const floor=(id,name,building_id,elevation,rooms)=>({...structuredClone(base),id,name,building_id,elevation,rooms,openings:[],placements:[],furniture:[],outdoor:[],walls:[],notes:[],background:null,start_view:null,utility_meters:null,power_entity:null});
|
||||
b.topology={locations:[{id:"urbach",name:"Urbach"},{id:"ulm",name:"Ulm"}],branches:[{id:"hq",name:"Zentrale",location_id:"urbach"},{id:"west",name:"West",location_id:"urbach"},{id:"south",name:"Süd",location_id:"ulm"}],buildings:[{id:"ras19",name:"RAS19",branch_id:"hq"},{id:"ras21",name:"RAS21",branch_id:"west"},{id:"ulm1",name:"RAS19",branch_id:"south"}]};
|
||||
b.floors=[floor("eg","EG","ras19",0,[room("it","IT",0,0,7,5,"wood"),room("tech","Technik",7,0,3,5,"tiles")]),floor("og","OG","ras19",3,[room("office","Büro",0,0,10,5,"carpet")]),floor("west-eg","EG","ras21",0,[room("west-it","IT West",35,0,5,8,"concrete")]),floor("ulm-eg","EG","ulm1",0,[room("ulm-it","IT Ulm",90,0,6,6,"tiles")])];
|
||||
for(const [id,location,x,type]of[["outside-a","urbach",-10,"lawn"],["outside-b","ulm",105,"gravel"]]){const f=floor(id,"Außen",null,0,[]);f.outdoor_location_id=location;f.outdoor=[{id:`area-${id}`,type,temp_entity:location==="urbach"?"sensor.901":"sensor.902",points:[[x,-3],[x+8,-3],[x+8,6],[x,6]]}];b.floors.push(f);}
|
||||
b.floors[0].outdoor=[{id:"legacy-a",type:"terrace",points:[[10,0],[13,0],[13,4],[10,4]],temp_entity:"sensor.903"}];
|
||||
b.floors[3].outdoor=[{id:"legacy-b",type:"terrace",points:[[96,0],[99,0],[99,4],[96,4]],temp_entity:"sensor.904"}];
|
||||
b.settings.roof.type="none";b.settings.start_view=null;b.settings.lock_plan=false;for(const k of Object.keys(b.energy))b.energy[k]=null;
|
||||
window.topologyProject=structuredClone(b);p.data.edit(b);p.hass={...p.hass,language:"de",symconObjects:[],symconTitle:"Topologie",states:Object.fromEntries([901,902,903,904].map((id)=>[`sensor.${id}`,{entity_id:`sensor.${id}`,state:"21",attributes:{symcon_id:id,symcon_variable_type:2,symcon_value:21,symcon_formatted:"21 °C",friendly_name:id===901?"Außen Urbach":"Außen Ulm",unit_of_measurement:"°C"}}])),user:{...p.hass.user,is_admin:true}};await p.updateComplete;
|
||||
[...p.shadowRoot.querySelectorAll("[role=tab]")].find((b)=>b.textContent.trim()==="3D").click();
|
||||
});
|
||||
await page.waitForFunction(()=>window.nfPanel.shadowRoot.querySelector("nf-view3d")?.viewer);
|
||||
await page.evaluate(()=>{window.topoHost=window.nfPanel;window.topoView=()=>window.topoHost.shadowRoot.querySelector("nf-view3d");});
|
||||
const select=async(kind,id,ownerKind)=>{
|
||||
const key=[kind,ownerKind,id].filter(Boolean).join(":");
|
||||
await page.waitForFunction((key)=>window.topoView().shadowRoot.querySelector(`.nf-thumb[data-topology-key="${key}"]`),{},key);
|
||||
await page.evaluate((key)=>window.topoView().shadowRoot.querySelector(`.nf-thumb[data-topology-key="${key}"]`).click(),key);
|
||||
await page.waitForFunction((kind,id,owner)=>window.topoView().topologySelection?.kind===kind&&window.topoView().topologySelection?.id===id&&(window.topoView().topologySelection?.ownerKind??null)===(owner??null),{},kind,id,ownerKind);
|
||||
};
|
||||
const noTopMenu=async()=>assert.equal(await page.evaluate(()=>!!window.topoHost.shadowRoot.querySelector("nav.nf-nav,.nf-card-rooms")),false,"upper room menu is absent above the floor level and outdoors");
|
||||
const scene=()=>page.evaluate(()=>window.topoView().viewer.floors.map((f)=>f.floor.id).sort());
|
||||
await page.waitForFunction(()=>window.topoView().shadowRoot.querySelectorAll('[data-topology-kind="location"] img').length===2);
|
||||
assert.deepEqual(await page.evaluate(()=>window.topoView().viewer.floors.filter((f)=>f.floor.id!=="og").map((f)=>f.rank)),[0,0,0,0,0],"each building and outdoor plan starts at its own ground level in the exploded overview");
|
||||
await noTopMenu();await page.screenshot({path:join(out,"symcon-topology-locations.png")});
|
||||
await select("location","urbach");await noTopMenu();assert.deepEqual(await scene(),["eg","og","outside-a","west-eg"]);
|
||||
assert.deepEqual(await page.evaluate(()=>[...window.topoView().shadowRoot.querySelectorAll(".nf-thumb[data-topology-kind]")].map((b)=>b.querySelector("span").textContent.trim())),["Zentrale","West","Außen"]);
|
||||
await select("branch","hq");await noTopMenu();assert.deepEqual(await scene(),["eg","og"]);
|
||||
await select("building","ras19");await noTopMenu();assert.deepEqual(await scene(),["eg","og"]);
|
||||
await page.waitForFunction(()=>window.topoView().shadowRoot.querySelectorAll('[data-topology-kind="floor"] img').length===2);
|
||||
await page.screenshot({path:join(out,"symcon-topology-building.png")});
|
||||
await select("floor","eg");
|
||||
await page.waitForFunction(()=>window.nfPanel.shadowRoot.querySelectorAll(".nf-topology-floor-nav .nf-room-chip").length===2);
|
||||
assert.deepEqual(await page.evaluate(()=>[...window.nfPanel.shadowRoot.querySelectorAll(".nf-topology-floor-nav .nf-room-chip")].map((b)=>b.textContent.trim())),["IT","Technik"]);
|
||||
await page.waitForFunction(()=>window.topoView().shadowRoot.querySelectorAll('[data-topology-kind="room"] img').length===2);
|
||||
const thumbState=await page.evaluate(()=>{
|
||||
const v=window.topoView().viewer,states=()=>v.floors.map((f)=>({id:f.floor.id,y:f.y,o:f.o,visible:f.group.visible,standing:f.mask.standing.value,glass:f.mask.glass.value}));
|
||||
const before=states(),render=v.renderer.render.bind(v.renderer),renders=[];
|
||||
v.renderer.render=(scene,camera)=>{renders.push({floors:v.floors.filter((f)=>f.group.visible).map((f)=>f.floor.id),planes:v.renderer.clippingPlanes.length,frustum:camera.right-camera.left});return render(scene,camera);};
|
||||
const result=v.scopeThumbnails([{key:"room:eg:it",floorIds:["eg"],room:{floorId:"eg",roomId:"it"}},{key:"floor:eg",floorIds:["eg"]}]);v.renderer.render=render;
|
||||
return {before,after:states(),renders,images:result.map((r)=>r.url)};
|
||||
});
|
||||
assert.deepEqual(thumbState.after,thumbState.before,"GPU previews restore the live floor masks, positions and visibility");
|
||||
assert.deepEqual(thumbState.renders.map((r)=>r.floors),[["eg"],["eg"]]);assert.equal(thumbState.renders[0].planes,4);assert.equal(thumbState.renders[1].planes,0);
|
||||
assert.ok(thumbState.renders[0].frustum<thumbState.renders[1].frustum,"the room preview frames the room instead of its whole floor");assert.notEqual(thumbState.images[0],thumbState.images[1]);
|
||||
await page.screenshot({path:join(out,"symcon-topology-floor-rooms.png")});
|
||||
await page.evaluate(()=>window.topoView().shadowRoot.querySelector('.nf-thumb[data-topology-key="room:eg:it"]').click());
|
||||
await page.waitForFunction(()=>window.nfPanel.shadowRoot.querySelector("nf-room-panel")?.room?.id==="it");
|
||||
assert.deepEqual(await page.evaluate(()=>[...window.topoView().shadowRoot.querySelectorAll(".nf-topology-crumbs button")].map((b)=>b.textContent.trim().slice(2))),["Urbach","Zentrale","RAS19","EG","IT"]);
|
||||
await page.evaluate(()=>window.topoView().shadowRoot.querySelector(".nf-thumb-house").click());
|
||||
await select("location","urbach");await select("outside","urbach");await noTopMenu();assert.deepEqual(await scene(),["outside-a"]);
|
||||
await page.waitForFunction(()=>window.topoView().shadowRoot.querySelector('[data-topology-kind="outside"] img'));
|
||||
await page.screenshot({path:join(out,"symcon-topology-outside.png")});
|
||||
await page.evaluate(()=>window.topoView().shadowRoot.querySelector(".nf-thumb-house").click());
|
||||
await select("location","ulm");await select("outside","ulm");assert.deepEqual(await scene(),["outside-b"]);await noTopMenu();
|
||||
|
||||
await page.evaluate(()=>{window.topoView().shadowRoot.querySelector(".nf-thumb-house").click();});
|
||||
await page.evaluate(()=>window.topoView().dispatchEvent(new CustomEvent("room-tap",{detail:{floorId:"outside-a",roomId:"nf-outside"},bubbles:true,composed:true})));
|
||||
await page.waitForFunction(()=>window.nfPanel._outside===true&&window.nfPanel._floorId==="outside-a");
|
||||
assert.deepEqual(await scene(),["outside-a"]);
|
||||
assert.deepEqual(await page.evaluate(()=>window.nfPanel.shadowRoot.querySelector("nf-room-panel").outside.slice().sort()),["sensor.901","sensor.903"],"a direct outdoor pin selects only its location's values, even from the all-locations view");
|
||||
await page.evaluate(()=>window.nfPanel.shadowRoot.querySelector("nf-room-panel").dispatchEvent(new CustomEvent("close",{bubbles:true,composed:true})));
|
||||
|
||||
await page.evaluate(async()=>{const p=window.nfPanel,b=structuredClone(window.topologyProject);b.floors=b.floors.filter((f)=>f.id!=="outside-a");p.data.edit(b);await p.updateComplete;window.topoView().dispatchEvent(new CustomEvent("room-tap",{detail:{floorId:"eg",roomId:"nf-outside"},bubbles:true,composed:true}));});
|
||||
await page.waitForFunction(()=>window.nfPanel._outside===true&&window.nfPanel._floorId===null&&window.nfPanel._topologyGroup.id==="urbach");
|
||||
assert.deepEqual(await page.evaluate(()=>window.nfPanel.shadowRoot.querySelector("nf-room-panel").outside),["sensor.903"],"legacy outdoor pins stay within their location even without a dedicated outdoor floor");
|
||||
await page.evaluate(()=>window.nfPanel.shadowRoot.querySelector("nf-room-panel").dispatchEvent(new CustomEvent("close",{bubbles:true,composed:true})));
|
||||
|
||||
// Branch/building outdoor views have separate scenes, breadcrumbs, values and pin targets.
|
||||
await page.evaluate(async()=>{
|
||||
const p=window.nfPanel,b=structuredClone(window.topologyProject),base=b.floors.find((f)=>f.id==="outside-a");
|
||||
for(const [id,field,parent,sensor]of[["outside-hq","outdoor_branch_id","hq",905],["outside-ras19","outdoor_building_id","ras19",906]]){
|
||||
const f={...structuredClone(base),id,outdoor_location_id:null,[field]:parent};f.outdoor[0].id=id;f.outdoor[0].temp_entity=`sensor.${sensor}`;b.floors.push(f);
|
||||
p.hass={...p.hass,states:{...p.hass.states,[`sensor.${sensor}`]:{entity_id:`sensor.${sensor}`,state:"22",attributes:{symcon_id:sensor,symcon_variable_type:2,symcon_value:22,symcon_formatted:"22 °C",unit_of_measurement:"°C"}}}};
|
||||
}
|
||||
window.topologyProject=structuredClone(b);p.data.edit(b);p.openTopology({kind:"all"});await p.updateComplete;
|
||||
});
|
||||
await select("location","urbach");await select("branch","hq");assert.deepEqual(await scene(),["eg","og","outside-hq","outside-ras19"]);await noTopMenu();
|
||||
await select("outside","hq","branch");assert.deepEqual(await scene(),["outside-hq"]);await noTopMenu();
|
||||
await page.evaluate(()=>window.topoView().dispatchEvent(new CustomEvent("room-tap",{detail:{floorId:"outside-hq",roomId:"nf-outside"},bubbles:true,composed:true})));
|
||||
await page.waitForFunction(()=>window.nfPanel._outside&&window.nfPanel.shadowRoot.querySelector("nf-room-panel")?.outside?.includes("sensor.905"));
|
||||
assert.deepEqual(await page.evaluate(()=>window.nfPanel.shadowRoot.querySelector("nf-room-panel").outside.slice().sort()),["sensor.903","sensor.905","sensor.906"]);
|
||||
await page.evaluate(()=>{window.nfPanel.shadowRoot.querySelector("nf-room-panel").dispatchEvent(new CustomEvent("close",{bubbles:true,composed:true}));window.topoView().shadowRoot.querySelector('.nf-topology-crumbs [data-topology-key="branch:hq"]').click();});
|
||||
await select("building","ras19");await select("outside","ras19","building");assert.deepEqual(await scene(),["outside-ras19"]);await noTopMenu();
|
||||
await page.evaluate(()=>window.topoView().dispatchEvent(new CustomEvent("room-tap",{detail:{floorId:"outside-ras19",roomId:"nf-outside"},bubbles:true,composed:true})));
|
||||
await page.waitForFunction(()=>window.nfPanel._outside&&window.nfPanel.shadowRoot.querySelector("nf-room-panel")?.outside?.includes("sensor.906"));
|
||||
assert.deepEqual(await page.evaluate(()=>window.nfPanel.shadowRoot.querySelector("nf-room-panel").outside.slice().sort()),["sensor.903","sensor.906"]);
|
||||
await page.screenshot({path:join(out,"symcon-topology-building-outside.png")});
|
||||
|
||||
// Utility panels drill into immediate logical children; totals use exactly the selected descendants.
|
||||
await page.evaluate(async()=>{
|
||||
const p=window.nfPanel,b=structuredClone(window.topologyProject),states={...p.hass.states};
|
||||
b.topology.buildings.find((g)=>g.id==="ras21").branch_id="hq";
|
||||
for(const [i,[id,power,energy]]of[["eg",100,10],["og",200,20],["west-eg",500,50],["ulm-eg",9000,900],["outside-hq",150,15],["outside-ras19",50,5],["outside-a",1000,100]].entries()){
|
||||
const f=b.floors.find((f)=>f.id===id),powerId=`sensor.${9501+i*2}`,energyId=`sensor.${9502+i*2}`;
|
||||
f.utility_meters={electricity:{power:powerId,energy:energyId}};
|
||||
for(const [eid,value,unit]of[[powerId,power,"W"],[energyId,energy,"kWh"]])states[eid]={entity_id:eid,state:String(value),attributes:{symcon_id:Number(eid.slice(7)),symcon_variable_type:2,symcon_value:value,unit_of_measurement:unit,friendly_name:unit==="W"?"Leistung":"Verbrauch",symcon_archive:{id:999,counter:false}}};
|
||||
}
|
||||
window.topologyProject=structuredClone(b);p.hass={...p.hass,states};p.data.edit(b);p.openTopology({kind:"branch",id:"hq"});await p.updateComplete;
|
||||
window.utilityPanel=()=>window.topoView().shadowRoot.querySelector('.nf-utility-right nf-utility-overview');
|
||||
window.utilityBar=()=>window.topoView().shadowRoot.querySelector('nf-utility-overview[inline]');
|
||||
});
|
||||
const overview=async(heading,name,names,power,energy)=>{
|
||||
await page.waitForFunction((heading,name,names,power,energy)=>{
|
||||
const root=window.utilityPanel()?.shadowRoot,bar=window.utilityBar()?.shadowRoot;
|
||||
return root?.querySelector('.heading')?.textContent.includes(heading)&&root?.querySelector('.heading small')?.textContent===name
|
||||
&&JSON.stringify([...root.querySelectorAll('.entry>.entry-name')].map((el)=>el.textContent.trim()))===JSON.stringify(names)
|
||||
&&bar?.textContent.includes(power)&&bar?.textContent.includes(energy);
|
||||
},{},heading,name,names,power,energy);
|
||||
};
|
||||
const utilityClick=async(key)=>{await page.evaluate((key)=>window.utilityPanel().shadowRoot.querySelector(`[data-topology-key="${key}"]>.entry-name`).click(),key);};
|
||||
await overview("Gebäude","Zentrale",["RAS19","RAS21","Außen"],"1 kW","100 kWh");
|
||||
assert.deepEqual(await page.evaluate(()=>[...window.utilityPanel().shadowRoot.querySelector('[data-topology-key="building:ras19"]').querySelectorAll('.value b')].map((el)=>el.textContent)),["350 W","35 kWh"]);
|
||||
assert.ok(await page.evaluate(()=>window.utilityPanel().shadowRoot.querySelector('nf-trend-button')?.ids.length));
|
||||
await page.screenshot({path:join(out,"symcon-utilities-branch.png")});
|
||||
await utilityClick("building:ras19");await overview("Stockwerke","RAS19",["OG","EG","Außen"],"350 W","35 kWh");
|
||||
await page.screenshot({path:join(out,"symcon-utilities-building.png")});
|
||||
await utilityClick("floor:og");
|
||||
await page.waitForFunction(()=>window.topoView().floorId==="og"&&window.utilityBar()?.shadowRoot.textContent.includes("20 kWh"));
|
||||
assert.match(await page.evaluate(()=>window.utilityBar().shadowRoot.textContent),/200 W/);
|
||||
await page.evaluate(()=>window.nfPanel.openTopology({kind:"branch",id:"hq"}));
|
||||
await overview("Gebäude","Zentrale",["RAS19","RAS21","Außen"],"1 kW","100 kWh");
|
||||
await page.evaluate(async()=>{const p=window.nfPanel,states={...p.hass.states};for(const id of ["sensor.9501","sensor.9502"])states[id]={...states[id],state:"0",attributes:{...states[id].attributes,symcon_value:0}};p.hass={...p.hass,states};await p.updateComplete;});
|
||||
await overview("Gebäude","Zentrale",["RAS19","RAS21","Außen"],"900 W","90 kWh");
|
||||
await page.evaluate(async()=>{const p=window.nfPanel,states={...p.hass.states};for(const id of ["sensor.9505","sensor.9506"])states[id]={...states[id],state:"unavailable"};p.hass={...p.hass,states};await p.updateComplete;});
|
||||
await overview("Gebäude","Zentrale",["RAS19","RAS21","Außen"],"Err: 400 W","Err: 40 kWh");
|
||||
assert.match(await page.evaluate(()=>window.utilityPanel().shadowRoot.querySelector('[data-topology-key="building:ras21"]').textContent),/Err: –/);
|
||||
await page.evaluate(()=>window.topoView().shadowRoot.querySelector('.nf-utility-overview-toggle').click());
|
||||
await page.waitForFunction(()=>!window.utilityPanel()&&window.utilityBar().shadowRoot.textContent.includes("Err: 40 kWh"));
|
||||
await page.evaluate(async()=>{
|
||||
window.topoView().shadowRoot.querySelector('.nf-utility-overview-toggle').click();
|
||||
const p=window.nfPanel,states={...p.hass.states};for(const [id,value]of[["sensor.9501",100],["sensor.9502",10],["sensor.9505",500],["sensor.9506",50]])states[id]={...states[id],state:String(value),attributes:{...states[id].attributes,symcon_value:value}};p.hass={...p.hass,states};await p.updateComplete;
|
||||
p.openTopology({kind:"location",id:"urbach"});
|
||||
});
|
||||
await overview("Niederlassungen","Urbach",["Zentrale","Außen"],"2 kW","200 kWh");
|
||||
|
||||
// The HTML-SDK tile uses the same hierarchy and hides its own upper menu until a floor is selected.
|
||||
await page.evaluate(async()=>{const p=window.nfPanel,card=document.createElement("nextfloor-card");card.setConfig({type:"custom:nextfloor-card",fill:true,room_buttons:true,controls:true});card.hass=p.hass;card.style.cssText="display:block;height:850px";document.body.append(card);await card.updateComplete;card.data.edit(structuredClone(window.topologyProject));p.style.display="none";window.topoHost=card;window.topoCard=card;await card.updateComplete;});
|
||||
await page.waitForFunction(()=>window.topoView()?.viewer&&window.topoView().shadowRoot.querySelector('[data-topology-kind="location"]'));
|
||||
await noTopMenu();await select("location","urbach");await select("branch","hq");await select("building","ras19");await noTopMenu();await select("floor","eg");
|
||||
await page.waitForFunction(()=>window.topoCard.shadowRoot.querySelectorAll(".nf-card-rooms button").length===2);
|
||||
await page.evaluate(()=>window.topoView().shadowRoot.querySelector('.nf-topology-crumbs [data-topology-key="building:ras19"]').click());
|
||||
await select("outside","ras19","building");await noTopMenu();assert.deepEqual(await scene(),["outside-ras19"]);
|
||||
await page.evaluate(()=>window.topoView().shadowRoot.querySelector('.nf-topology-crumbs [data-topology-key="branch:hq"]').click());
|
||||
await overview("Gebäude","Zentrale",["RAS19","RAS21","Außen"],"1 kW","100 kWh");
|
||||
await utilityClick("building:ras19");await overview("Stockwerke","RAS19",["OG","EG","Außen"],"350 W","35 kWh");
|
||||
await page.evaluate(()=>window.topoView().shadowRoot.querySelector(".nf-thumb-house").click());await noTopMenu();
|
||||
await page.setViewport({width:390,height:844});
|
||||
await page.waitForFunction(()=>window.topoView().shadowRoot.querySelectorAll('[data-topology-kind="location"] img').length===2);
|
||||
assert.ok(await page.evaluate(()=>{const r=window.topoView().shadowRoot.querySelector('[data-topology-kind="location"]').getBoundingClientRect();return r.left>=0&&r.right<=innerWidth&&r.width>30;}));
|
||||
await page.screenshot({path:join(out,"symcon-topology-tile-mobile.png")});
|
||||
assert.deepEqual(errors,[]);console.log("OK: five-level designer/tile navigation, upper menu only at floor level, scene isolation by branch/location/building, separate location outdoors, clipped room previews and exact renderer restoration, mobile navigation");
|
||||
}finally{await browser?.close();await new Promise((done)=>server.close(done));}
|
||||
+44
-44
@@ -1,11 +1,11 @@
|
||||
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
|
||||
var pr=globalThis,mr=pr.ShadowRoot&&(pr.ShadyCSS===void 0||pr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ma=Symbol(),Lc=new WeakMap,hs=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==Ma)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(mr&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=Lc.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&Lc.set(t,e))}return e}toString(){return this.cssText}},Nc=i=>new hs(typeof i=="string"?i:i+"",void 0,Ma),wa=(i,...e)=>{let t=i.length===1?i[0]:e.reduce((n,s,r)=>n+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+i[r+1],i[0]);return new hs(t,i,Ma)},Dc=(i,e)=>{if(mr)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),s=pr.litNonce;s!==void 0&&n.setAttribute("nonce",s),n.textContent=t.cssText,i.appendChild(n)}},Ea=mr?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return Nc(t)})(i):i;var{is:wd,defineProperty:Ed,getOwnPropertyDescriptor:Td,getOwnPropertyNames:Ad,getOwnPropertySymbols:Rd,getPrototypeOf:Cd}=Object,gr=globalThis,Uc=gr.trustedTypes,Pd=Uc?Uc.emptyScript:"",Id=gr.reactiveElementPolyfillSupport,us=(i,e)=>i,Ta={toAttribute(i,e){switch(e){case Boolean:i=i?Pd:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},Oc=(i,e)=>!wd(i,e),Fc={attribute:!0,type:String,converter:Ta,reflect:!1,useDefault:!1,hasChanged:Oc};Symbol.metadata??=Symbol("metadata"),gr.litPropertyMetadata??=new WeakMap;var En=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=Fc){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){let n=Symbol(),s=this.getPropertyDescriptor(e,n,t);s!==void 0&&Ed(this.prototype,e,s)}}static getPropertyDescriptor(e,t,n){let{get:s,set:r}=Td(this.prototype,e)??{get(){return this[t]},set(o){this[t]=o}};return{get:s,set(o){let a=s?.call(this);r?.call(this,o),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Fc}static _$Ei(){if(this.hasOwnProperty(us("elementProperties")))return;let e=Cd(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(us("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(us("properties"))){let t=this.properties,n=[...Ad(t),...Rd(t)];for(let s of n)this.createProperty(s,t[s])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,s]of t)this.elementProperties.set(n,s)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let s=this._$Eu(t,n);s!==void 0&&this._$Eh.set(s,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let s of n)t.unshift(Ea(s))}else e!==void 0&&t.push(Ea(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?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),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Dc(e,this.constructor.elementStyles),e}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,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,n);if(s!==void 0&&n.reflect===!0){let r=(n.converter?.toAttribute!==void 0?n.converter:Ta).toAttribute(t,n.type);this._$Em=e,r==null?this.removeAttrLine truncated
|
||||
var pr=globalThis,mr=pr.ShadowRoot&&(pr.ShadyCSS===void 0||pr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ma=Symbol(),Lc=new WeakMap,hs=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==Ma)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(mr&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=Lc.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&Lc.set(t,e))}return e}toString(){return this.cssText}},Nc=i=>new hs(typeof i=="string"?i:i+"",void 0,Ma),wa=(i,...e)=>{let t=i.length===1?i[0]:e.reduce((n,s,r)=>n+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+i[r+1],i[0]);return new hs(t,i,Ma)},Dc=(i,e)=>{if(mr)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),s=pr.litNonce;s!==void 0&&n.setAttribute("nonce",s),n.textContent=t.cssText,i.appendChild(n)}},Ea=mr?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return Nc(t)})(i):i;var{is:wd,defineProperty:Ed,getOwnPropertyDescriptor:Td,getOwnPropertyNames:Ad,getOwnPropertySymbols:Rd,getPrototypeOf:Cd}=Object,gr=globalThis,Uc=gr.trustedTypes,Pd=Uc?Uc.emptyScript:"",Id=gr.reactiveElementPolyfillSupport,us=(i,e)=>i,Ta={toAttribute(i,e){switch(e){case Boolean:i=i?Pd:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},Oc=(i,e)=>!wd(i,e),Fc={attribute:!0,type:String,converter:Ta,reflect:!1,useDefault:!1,hasChanged:Oc};Symbol.metadata??=Symbol("metadata"),gr.litPropertyMetadata??=new WeakMap;var Tn=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=Fc){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){let n=Symbol(),s=this.getPropertyDescriptor(e,n,t);s!==void 0&&Ed(this.prototype,e,s)}}static getPropertyDescriptor(e,t,n){let{get:s,set:r}=Td(this.prototype,e)??{get(){return this[t]},set(o){this[t]=o}};return{get:s,set(o){let a=s?.call(this);r?.call(this,o),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Fc}static _$Ei(){if(this.hasOwnProperty(us("elementProperties")))return;let e=Cd(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(us("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(us("properties"))){let t=this.properties,n=[...Ad(t),...Rd(t)];for(let s of n)this.createProperty(s,t[s])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,s]of t)this.elementProperties.set(n,s)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let s=this._$Eu(t,n);s!==void 0&&this._$Eh.set(s,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let s of n)t.unshift(Ea(s))}else e!==void 0&&t.push(Ea(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?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),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Dc(e,this.constructor.elementStyles),e}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,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,n);if(s!==void 0&&n.reflect===!0){let r=(n.converter?.toAttribute!==void 0?n.converter:Ta).toAttribute(t,n.type);this._$Em=e,r==null?this.removeAttrLine truncated
|
||||
\f\r]`,ds=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,zc=/-->/g,Vc=/>/g,oi=RegExp(`>|${Aa}(?:([^\\s"'>=/]+)(${Aa}*=${Aa}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),Gc=/'/g,Hc=/"/g,qc=/^(?:script|style|textarea|title)$/i,Ua=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),qe=Ua(1),X_=Ua(2),q_=Ua(3),ci=Symbol.for("lit-noChange"),Qe=Symbol.for("lit-nothing"),Wc=new WeakMap,ai=li.createTreeWalker(li,129);function Yc(i,e){if(!Da(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return kc!==void 0?kc.createHTML(e):e}var Dd=(i,e)=>{let t=i.length-1,n=[],s,r=e===2?"<svg>":e===3?"<math>":"",o=ds;for(let a=0;a<t;a++){let l=i[a],c,u,d=-1,f=0;for(;f<l.length&&(o.lastIndex=f,u=o.exec(l),u!==null);)f=o.lastIndex,o===ds?u[1]==="!--"?o=zc:u[1]!==void 0?o=Vc:u[2]!==void 0?(qc.test(u[2])&&(s=RegExp("</"+u[2],"g")),o=oi):u[3]!==void 0&&(o=oi):o===oi?u[0]===">"?(o=s??ds,d=-1):u[1]===void 0?d=-2:(d=o.lastIndex-u[2].length,c=u[1],o=u[3]===void 0?oi:u[3]==='"'?Hc:Gc):o===Hc||o===Gc?o=oi:o===zc||o===Vc?o=ds:(o=oi,s=void 0);let h=o===oi&&i[a+1].startsWith("/>")?" ":"";r+=o===ds?l+Ld:d>=0?(n.push(c),l.slice(0,d)+$c+l.slice(d)+zn+h):l+zn+(d===-2?a:h)}return[Yc(i,r+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]},ms=class i{constructor({strings:e,_$litType$:t},n){let s;this.parts=[];let r=0,o=0,a=e.length-1,l=this.parts,[c,u]=Dd(e,t);if(this.el=i.createElement(c,n),ai.currentNode=this.el.content,t===2||t===3){let d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(s=ai.nextNode())!==null&&l.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(let d of s.getAttributeNames())if(d.endsWith($c)){let f=u[o++],h=s.getAttribute(d).split(zn),g=/([.?@])?(.*)/.exec(f);l.push({type:1,index:r,name:g[2],strings:h,ctor:g[1]==="."?Ca:g[1]==="?"?Pa:g[1]==="@"?Ia:Ri}),s.removeAttribute(d)}else d.startsWith(zn)&&(l.push({type:6,index:r}),s.removeAttribute(d));if(qc.test(s.tagName)){let d=s.textContent.split(zn),f=d.length-1;if(f>0){s.textContent=_r?_r.emptyScript:"";for(let h=0;h<f;h++)s.append(d[h],fs()),ai.nextNode(),l.push({type:2,index:++r});s.append(d[f],fs())}}}else if(s.nodeType===8)if(s.data===Xc)l.push({type:2,index:r});else{let d=-1;for(;(d=s.data.indexOf(zn,d+1))!==-1;)l.push({type:7,index:r}),d+=zn.length-1}r++}}static createElement(e,t){let n=li.createElement("template");return n.innerHTML=e,n}};function Ai(i,e,t=i,n){if(e===ci)return e;let s=n!==void 0?t._$Co?.[n]:t._$Cl,r=ps(e)?void 0:e._$litDirective$;return s?.constructor!==r&&(s?._$AO?.(!1),r===void 0?s=void 0:(s=new r(i),s._$AT(i,t,n)),n!==void 0?(t._$Co??=[])[n]=s:t._$Cl=s),s!==void 0&&(e=Ai(i,s._$AS(i,e.values),s,n)),e}var Ra=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,s=(e?.creationScope??li).importNode(t,!0);ai.currentNode=s;let r=ai.nextNode(),o=0,a=0,l=n[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new gs(r,r.nextSibling,this,e):l.type===1?c=new l.ctor(r,l.name,l.strings,this,e):l.type===6&&(c=new La(r,this,e)),this._$AV.push(c),l=n[++a]}o!==l?.index&&(r=ai.nextNode(),o++)}return ai.currentNode=li,s}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}},gs=class i{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,s){this.type=2,this._$AH=Qe,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=s,this._$Cv=s?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Ai(this,e,t),ps(e)?e===Qe||e==null||e===""?(this._$AH!==Qe&&this._$AR(),this._$AH=Qe):e!==this._$AH&&e!==ci&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Nd(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!==Qe&&ps(this._$AH)?this._$AA.nextSibling.data=e:this.T(li.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,s=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=ms.createElement(Yc(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===s)this._$AH.p(t);else{let r=new Ra(s,this),o=r.u(this.options);r.p(t),this.T(o),this._$AH=r}}_$AC(e){let t=Wc.get(e.strings);return t===void 0&&Wc.set(e.strings,t=new ms(e)),t}k(e){Da(this._$AH)||(this._$AH=[],this._$AR());let t=this._$AH,n,s=0;for(let r of e)s===t.length?t.push(n=new i(this.O(fs()),this.O(fs()),this,this.options)):n=t[s],n._$AI(r),s++;s<t.length&&(this._$AR(n&&n._$AB.nextSibling,s),t.length=s)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let n=Bc(e).nextSibling;Bc(e).remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},Ri=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,s,r){this.type=1,this._$AH=Qe,this._$AN=void 0,this.element=e,this.name=t,this._$AM=s,this.options=r,n.length>2||n[0]!==""||n[1]!=="Line truncated
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),Gc=/'/g,Hc=/"/g,qc=/^(?:script|style|textarea|title)$/i,Ua=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),qe=Ua(1),X_=Ua(2),q_=Ua(3),ci=Symbol.for("lit-noChange"),je=Symbol.for("lit-nothing"),Wc=new WeakMap,ai=li.createTreeWalker(li,129);function Yc(i,e){if(!Da(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return kc!==void 0?kc.createHTML(e):e}var Dd=(i,e)=>{let t=i.length-1,n=[],s,r=e===2?"<svg>":e===3?"<math>":"",o=ds;for(let a=0;a<t;a++){let l=i[a],c,u,d=-1,f=0;for(;f<l.length&&(o.lastIndex=f,u=o.exec(l),u!==null);)f=o.lastIndex,o===ds?u[1]==="!--"?o=zc:u[1]!==void 0?o=Vc:u[2]!==void 0?(qc.test(u[2])&&(s=RegExp("</"+u[2],"g")),o=oi):u[3]!==void 0&&(o=oi):o===oi?u[0]===">"?(o=s??ds,d=-1):u[1]===void 0?d=-2:(d=o.lastIndex-u[2].length,c=u[1],o=u[3]===void 0?oi:u[3]==='"'?Hc:Gc):o===Hc||o===Gc?o=oi:o===zc||o===Vc?o=ds:(o=oi,s=void 0);let h=o===oi&&i[a+1].startsWith("/>")?" ":"";r+=o===ds?l+Ld:d>=0?(n.push(c),l.slice(0,d)+$c+l.slice(d)+zn+h):l+zn+(d===-2?a:h)}return[Yc(i,r+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]},ms=class i{constructor({strings:e,_$litType$:t},n){let s;this.parts=[];let r=0,o=0,a=e.length-1,l=this.parts,[c,u]=Dd(e,t);if(this.el=i.createElement(c,n),ai.currentNode=this.el.content,t===2||t===3){let d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(s=ai.nextNode())!==null&&l.length<a;){if(s.nodeType===1){if(s.hasAttributes())for(let d of s.getAttributeNames())if(d.endsWith($c)){let f=u[o++],h=s.getAttribute(d).split(zn),g=/([.?@])?(.*)/.exec(f);l.push({type:1,index:r,name:g[2],strings:h,ctor:g[1]==="."?Ca:g[1]==="?"?Pa:g[1]==="@"?Ia:Ri}),s.removeAttribute(d)}else d.startsWith(zn)&&(l.push({type:6,index:r}),s.removeAttribute(d));if(qc.test(s.tagName)){let d=s.textContent.split(zn),f=d.length-1;if(f>0){s.textContent=_r?_r.emptyScript:"";for(let h=0;h<f;h++)s.append(d[h],fs()),ai.nextNode(),l.push({type:2,index:++r});s.append(d[f],fs())}}}else if(s.nodeType===8)if(s.data===Xc)l.push({type:2,index:r});else{let d=-1;for(;(d=s.data.indexOf(zn,d+1))!==-1;)l.push({type:7,index:r}),d+=zn.length-1}r++}}static createElement(e,t){let n=li.createElement("template");return n.innerHTML=e,n}};function Ai(i,e,t=i,n){if(e===ci)return e;let s=n!==void 0?t._$Co?.[n]:t._$Cl,r=ps(e)?void 0:e._$litDirective$;return s?.constructor!==r&&(s?._$AO?.(!1),r===void 0?s=void 0:(s=new r(i),s._$AT(i,t,n)),n!==void 0?(t._$Co??=[])[n]=s:t._$Cl=s),s!==void 0&&(e=Ai(i,s._$AS(i,e.values),s,n)),e}var Ra=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,s=(e?.creationScope??li).importNode(t,!0);ai.currentNode=s;let r=ai.nextNode(),o=0,a=0,l=n[0];for(;l!==void 0;){if(o===l.index){let c;l.type===2?c=new gs(r,r.nextSibling,this,e):l.type===1?c=new l.ctor(r,l.name,l.strings,this,e):l.type===6&&(c=new La(r,this,e)),this._$AV.push(c),l=n[++a]}o!==l?.index&&(r=ai.nextNode(),o++)}return ai.currentNode=li,s}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}},gs=class i{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,s){this.type=2,this._$AH=je,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=s,this._$Cv=s?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Ai(this,e,t),ps(e)?e===je||e==null||e===""?(this._$AH!==je&&this._$AR(),this._$AH=je):e!==this._$AH&&e!==ci&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Nd(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!==je&&ps(this._$AH)?this._$AA.nextSibling.data=e:this.T(li.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,s=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=ms.createElement(Yc(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===s)this._$AH.p(t);else{let r=new Ra(s,this),o=r.u(this.options);r.p(t),this.T(o),this._$AH=r}}_$AC(e){let t=Wc.get(e.strings);return t===void 0&&Wc.set(e.strings,t=new ms(e)),t}k(e){Da(this._$AH)||(this._$AH=[],this._$AR());let t=this._$AH,n,s=0;for(let r of e)s===t.length?t.push(n=new i(this.O(fs()),this.O(fs()),this,this.options)):n=t[s],n._$AI(r),s++;s<t.length&&(this._$AR(n&&n._$AB.nextSibling,s),t.length=s)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let n=Bc(e).nextSibling;Bc(e).remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},Ri=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,s,r){this.type=1,this._$AH=je,this._$AN=void 0,this.element=e,this.name=t,this._$AM=s,this.options=r,n.length>2||n[0]!==""||n[1]!=="Line truncated
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
||||
}`,Af=`void main() {
|
||||
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
||||
}`,xn=class extends Jn{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Tf,this.fragmentShader=Af,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=wi(e.uniforms),this.uniformsGroups=Ef(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let s in this.uniforms){let o=this.uniforms[s].value;o&&o.isTexture?t.uniforms[s]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[s]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[s]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[s]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[s]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[s]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[s]={type:"m4",value:o.toArray()}:t.uniforms[s]={value:o}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let s=e.uniforms[n];switch(this.uniforms[n]={},s.type){case"t":this.uniforms[n].value=t[s.value]||null;break;case"c":this.uniforms[n].value=new Ie().setHex(s.value);break;case"v2":this.uniforms[n].value=new ze().fromArray(s.value);break;case"v3":this.uniforms[n].value=new B().fromArray(s.value);break;case"v4":this.uniforms[n].value=new ht().fromArray(s.value);break;case"m3":this.uniforms[n].value=new Le().fromArray(s.value);break;case"m4":this.uniforms[n].value=new ot().fromArray(s.value);break;default:this.uniforms[n].value=s.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let n in e.extensions)this.extensions[n]=e.extensions[n];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},uo=class extends xn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}};var fo=class extends Jn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=ru,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},po=class extends Jn{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function zi(i,e){return!i||i.constructor===e?i:typeof e.BYTES_PER_ELEMENT=="number"?new e(i):Array.prototype.slice.call(i)}function Vr(i){return i!==void 0&&i.inTangents!==void 0&&i.outTangents!==void 0}var Qn=class{constructor(e,t,n,s){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=s!==void 0?s:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,s=t[n],r=t[n-1];n:{e:{let o;t:{i:if(!(e<s)){for(let a=n+2;;){if(s===void 0){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(r=s,s=t[++n],e<s)break e}o=t.length;break t}if(!(e>=r)){let a=t[1];e<a&&(n=2,r=a);for(let l=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleVal
Line truncated
|
||||
}`,xn=class extends Jn{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Tf,this.fragmentShader=Af,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=wi(e.uniforms),this.uniformsGroups=Ef(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let s in this.uniforms){let o=this.uniforms[s].value;o&&o.isTexture?t.uniforms[s]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[s]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[s]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[s]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[s]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[s]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[s]={type:"m4",value:o.toArray()}:t.uniforms[s]={value:o}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(let n in e.uniforms){let s=e.uniforms[n];switch(this.uniforms[n]={},s.type){case"t":this.uniforms[n].value=t[s.value]||null;break;case"c":this.uniforms[n].value=new Ie().setHex(s.value);break;case"v2":this.uniforms[n].value=new ze().fromArray(s.value);break;case"v3":this.uniforms[n].value=new B().fromArray(s.value);break;case"v4":this.uniforms[n].value=new ht().fromArray(s.value);break;case"m3":this.uniforms[n].value=new Le().fromArray(s.value);break;case"m4":this.uniforms[n].value=new ot().fromArray(s.value);break;default:this.uniforms[n].value=s.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(let n in e.extensions)this.extensions[n]=e.extensions[n];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}},uo=class extends xn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}};var fo=class extends Jn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=ru,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},po=class extends Jn{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}};function zi(i,e){return!i||i.constructor===e?i:typeof e.BYTES_PER_ELEMENT=="number"?new e(i):Array.prototype.slice.call(i)}function Vr(i){return i!==void 0&&i.inTangents!==void 0&&i.outTangents!==void 0}var jn=class{constructor(e,t,n,s){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=s!==void 0?s:new t.constructor(n),this.sampleValues=t,this.valueSize=n,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,n=this._cachedIndex,s=t[n],r=t[n-1];n:{e:{let o;t:{i:if(!(e<s)){for(let a=n+2;;){if(s===void 0){if(e<r)break i;return n=t.length,this._cachedIndex=n,this.copySampleValue_(n-1)}if(n===a)break;if(r=s,s=t[++n],e<s)break e}o=t.length;break t}if(!(e>=r)){let a=t[1];e<a&&(n=2,r=a);for(let l=n-2;;){if(r===void 0)return this._cachedIndex=0,this.copySampleVal
Line truncated
|
||||
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
|
||||
#endif`,Gf=`#ifdef USE_ALPHAHASH
|
||||
const float ALPHA_HASH_SCALE = 0.05;
|
||||
@@ -110,10 +110,10 @@ var pr=globalThis,mr=pr.ShadowRoot&&(pr.ShadyCSS===void 0||pr.ShadyCSS.nativeSha
|
||||
#endif`,Kf=`vec3 transformed = vec3( position );
|
||||
#ifdef USE_ALPHAHASH
|
||||
vPosition = vec3( position );
|
||||
#endif`,Qf=`vec3 objectNormal = vec3( normal );
|
||||
#endif`,jf=`vec3 objectNormal = vec3( normal );
|
||||
#ifdef USE_TANGENT
|
||||
vec3 objectTangent = vec3( tangent.xyz );
|
||||
#endif`,jf=`float G_BlinnPhong_Implicit( ) {
|
||||
#endif`,Qf=`float G_BlinnPhong_Implicit( ) {
|
||||
return 0.25;
|
||||
}
|
||||
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
|
||||
@@ -429,7 +429,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
|
||||
outgoingLight += envColor.xyz * specularStrength * reflectivity;
|
||||
#endif
|
||||
#endif
|
||||
#endif`,vp=`#ifdef USE_ENVMAP
|
||||
#endif`,yp=`#ifdef USE_ENVMAP
|
||||
uniform float envMapIntensity;
|
||||
uniform mat3 envMapRotation;
|
||||
uniform samplerCube envMap;
|
||||
@@ -439,7 +439,7 @@ vec4 sRGBTransferOETF( in vec4 value ) {
|
||||
return ENVMAP_MAX_LOD * r * ( 2.0 - r );
|
||||
}
|
||||
#endif
|
||||
#endif`,yp=`#ifdef USE_ENVMAP
|
||||
#endif`,vp=`#ifdef USE_ENVMAP
|
||||
uniform float reflectivity;
|
||||
#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
|
||||
#define ENV_WORLDPOS
|
||||
@@ -1566,9 +1566,9 @@ vec3 getLightProbeGridIrradiance( highp sampler3D probesSH, vec3 probesMin, vec3
|
||||
#ifdef USE_METALNESSMAP
|
||||
vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
|
||||
metalnessFactor *= texelMetalness.b;
|
||||
#endif`,Qp=`#ifdef USE_METALNESSMAP
|
||||
#endif`,jp=`#ifdef USE_METALNESSMAP
|
||||
uniform sampler2D metalnessMap;
|
||||
#endif`,jp=`#ifdef USE_INSTANCING_MORPH
|
||||
#endif`,Qp=`#ifdef USE_INSTANCING_MORPH
|
||||
float morphTargetInfluences[ MORPHTARGETS_COUNT ];
|
||||
float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
|
||||
for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
|
||||
@@ -1830,14 +1830,14 @@ float perspectiveDepthToViewZ( const in float depth, const in float near, const
|
||||
mvPosition = modelViewMatrix * mvPosition;
|
||||
gl_Position = projectionMatrix * mvPosition;`,xm=`#ifdef DITHERING
|
||||
gl_FragColor.rgb = dithering( gl_FragColor.rgb );
|
||||
#endif`,vm=`#ifdef DITHERING
|
||||
#endif`,ym=`#ifdef DITHERING
|
||||
vec3 dithering( vec3 color ) {
|
||||
float grid_position = rand( gl_FragCoord.xy );
|
||||
vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
|
||||
dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
|
||||
return color + dither_shift_RGB;
|
||||
}
|
||||
#endif`,ym=`float roughnessFactor = roughness;
|
||||
#endif`,vm=`float roughnessFactor = roughness;
|
||||
#ifdef USE_ROUGHNESSMAP
|
||||
vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
|
||||
roughnessFactor *= texelRoughness.g;
|
||||
@@ -2956,7 +2956,7 @@ void main() {
|
||||
gl_FragColor = texture2D( tEquirect, sampleUV );
|
||||
#include <tonemapping_fragment>
|
||||
#include <colorspace_fragment>
|
||||
}`,Qm=`uniform float scale;
|
||||
}`,jm=`uniform float scale;
|
||||
attribute float lineDistance;
|
||||
varying float vLineDistance;
|
||||
#include <common>
|
||||
@@ -2978,7 +2978,7 @@ void main() {
|
||||
#include <logdepthbuf_vertex>
|
||||
#include <clipping_planes_vertex>
|
||||
#include <fog_vertex>
|
||||
}`,jm=`uniform vec3 diffuse;
|
||||
}`,Qm=`uniform vec3 diffuse;
|
||||
uniform float opacity;
|
||||
uniform float dashSize;
|
||||
uniform float totalSize;
|
||||
@@ -3798,7 +3798,7 @@ void main() {
|
||||
#include <logdepthbuf_vertex>
|
||||
#include <clipping_planes_vertex>
|
||||
#include <fog_vertex>
|
||||
}`,vg=`uniform vec3 diffuse;
|
||||
}`,yg=`uniform vec3 diffuse;
|
||||
uniform float opacity;
|
||||
#include <common>
|
||||
#include <uv_pars_fragment>
|
||||
@@ -3823,7 +3823,7 @@ void main() {
|
||||
#include <tonemapping_fragment>
|
||||
#include <colorspace_fragment>
|
||||
#include <fog_fragment>
|
||||
}`,ke={alphahash_fragment:Vf,alphahash_pars_fragment:Gf,alphamap_fragment:Hf,alphamap_pars_fragment:Wf,alphatest_fragment:$f,alphatest_pars_fragment:Xf,aomap_fragment:qf,aomap_pars_fragment:Yf,batching_pars_vertex:Zf,batching_vertex:Jf,begin_vertex:Kf,beginnormal_vertex:Qf,bsdfs:jf,iridescence_fragment:ep,bumpmap_pars_fragment:tp,clipping_planes_fragment:np,clipping_planes_pars_fragment:ip,clipping_planes_pars_vertex:sp,clipping_planes_vertex:rp,color_fragment:op,color_pars_fragment:ap,color_pars_vertex:lp,color_vertex:cp,common:hp,defaultnormal_vertex:up,displacementmap_pars_vertex:dp,displacementmap_vertex:fp,emissivemap_fragment:pp,emissivemap_pars_fragment:mp,colorspace_fragment:gp,colorspace_pars_fragment:_p,envmap_fragment:xp,envmap_common_pars_fragment:vp,envmap_pars_fragment:yp,envmap_pars_vertex:bp,envmap_physical_pars_fragment:Lp,envmap_vertex:Sp,fog_vertex:Mp,fog_pars_vertex:wp,fog_fragment:Ep,fog_pars_fragment:Tp,gradientmap_pars_fragment:Ap,lightmap_pars_fragment:Rp,lights_lambert_fragment:Cp,lights_lambert_pars_fragment:Pp,lights_pars_begin:Ip,lights_toon_fragment:Np,lights_toon_pars_fragment:Dp,lights_phong_fragment:Up,lights_phong_pars_fragment:Fp,lights_physical_fragment:Op,lights_physical_pars_fragment:Bp,lights_fragment_begin:kp,lights_fragment_maps:zp,lights_fragment_end:Vp,lightprobes_pars_fragment:Gp,logdepthbuf_fragment:Hp,logdepthbuf_pars_fragment:Wp,logdepthbuf_pars_vertex:$p,logdepthbuf_vertex:Xp,map_fragment:qp,map_pars_fragment:Yp,map_particle_fragment:Zp,map_particle_pars_fragment:Jp,metalnessmap_fragment:Kp,metalnessmap_pars_fragment:Qp,morphinstance_vertex:jp,morphcolor_vertex:em,morphnormal_vertex:tm,morphtarget_pars_vertex:nm,morphtarget_vertex:im,normal_fragment_begin:sm,normal_fragment_maps:rm,normal_pars_fragment:om,normal_pars_vertex:am,normal_vertex:lm,normalmap_pars_fragment:cm,clearcoat_normal_fragment_begin:hm,clearcoat_normal_fragment_maps:um,clearcoat_pars_fragment:dm,iridescence_pars_fragment:fm,opaque_fragment:pm,packing:mm,premultiplied_alpha_fragment:gm,project_vertex:_m,dithering_fragment:xm,dithering_pars_fragment:vm,roughnessmap_fragment:ym,roughnessmap_pars_fragment:bm,shadowmap_pars_fragment:Sm,shadowmap_pars_vertex:Mm,shadowmap_vertex:wm,shadowmask_pars_fragment:Em,skinbase_vertex:Tm,skinning_pars_vertex:Am,skinning_vertex:Rm,skinnormal_vertex:Cm,specularmap_fragment:Pm,specularmap_pars_fragment:Im,tonemapping_fragment:Lm,tonemapping_pars_fragment:Nm,transmission_fragment:Dm,transmission_pars_fragment:Um,uv_pars_fragment:Fm,uv_pars_vertex:Om,uv_vertex:Bm,worldpos_vertex:km,background_vert:zm,background_frag:Vm,backgroundCube_vert:Gm,backgroundCube_frag:Hm,cube_vert:Wm,cube_frag:$m,depth_vert:Xm,depth_frag:qm,distance_vert:Ym,distance_frag:Zm,equirect_vert:Jm,equirect_frag:Km,linedashed_vert:Qm,linedashed_frag:jm,meshbasic_vert:eg,meshbasic_frag:tg,meshlambert_vert:ng,meshlambert_frag:ig,meshmatcap_vert:sg,meshmatcap_frag:rg,meshnormal_vert:og,meshnormal_frag:ag,meshphong_vert:lg,meshphong_frag:cg,meshphysical_vert:hg,meshphysical_frag:ug,meshtoon_vert:dg,meshtoon_frag:fg,points_vert:pg,points_frag:mg,shadow_vert:gg,shadow_frag:_g,sprite_vert:xg,sprite_frag:vg},pe={common:{diffuse:{value:new Ie(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Le},alphaMap:{value:null},alphaMapTransform:{value:new Le},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Le}},envmap:{envMap:{value:null},envMapRotation:{value:new Le},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Le}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Le}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Le},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Le},normalScale:{value:new ze(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Le},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Le}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Le}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Le}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ie(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],pr
Line truncated
|
||||
}`,ke={alphahash_fragment:Vf,alphahash_pars_fragment:Gf,alphamap_fragment:Hf,alphamap_pars_fragment:Wf,alphatest_fragment:$f,alphatest_pars_fragment:Xf,aomap_fragment:qf,aomap_pars_fragment:Yf,batching_pars_vertex:Zf,batching_vertex:Jf,begin_vertex:Kf,beginnormal_vertex:jf,bsdfs:Qf,iridescence_fragment:ep,bumpmap_pars_fragment:tp,clipping_planes_fragment:np,clipping_planes_pars_fragment:ip,clipping_planes_pars_vertex:sp,clipping_planes_vertex:rp,color_fragment:op,color_pars_fragment:ap,color_pars_vertex:lp,color_vertex:cp,common:hp,defaultnormal_vertex:up,displacementmap_pars_vertex:dp,displacementmap_vertex:fp,emissivemap_fragment:pp,emissivemap_pars_fragment:mp,colorspace_fragment:gp,colorspace_pars_fragment:_p,envmap_fragment:xp,envmap_common_pars_fragment:yp,envmap_pars_fragment:vp,envmap_pars_vertex:bp,envmap_physical_pars_fragment:Lp,envmap_vertex:Sp,fog_vertex:Mp,fog_pars_vertex:wp,fog_fragment:Ep,fog_pars_fragment:Tp,gradientmap_pars_fragment:Ap,lightmap_pars_fragment:Rp,lights_lambert_fragment:Cp,lights_lambert_pars_fragment:Pp,lights_pars_begin:Ip,lights_toon_fragment:Np,lights_toon_pars_fragment:Dp,lights_phong_fragment:Up,lights_phong_pars_fragment:Fp,lights_physical_fragment:Op,lights_physical_pars_fragment:Bp,lights_fragment_begin:kp,lights_fragment_maps:zp,lights_fragment_end:Vp,lightprobes_pars_fragment:Gp,logdepthbuf_fragment:Hp,logdepthbuf_pars_fragment:Wp,logdepthbuf_pars_vertex:$p,logdepthbuf_vertex:Xp,map_fragment:qp,map_pars_fragment:Yp,map_particle_fragment:Zp,map_particle_pars_fragment:Jp,metalnessmap_fragment:Kp,metalnessmap_pars_fragment:jp,morphinstance_vertex:Qp,morphcolor_vertex:em,morphnormal_vertex:tm,morphtarget_pars_vertex:nm,morphtarget_vertex:im,normal_fragment_begin:sm,normal_fragment_maps:rm,normal_pars_fragment:om,normal_pars_vertex:am,normal_vertex:lm,normalmap_pars_fragment:cm,clearcoat_normal_fragment_begin:hm,clearcoat_normal_fragment_maps:um,clearcoat_pars_fragment:dm,iridescence_pars_fragment:fm,opaque_fragment:pm,packing:mm,premultiplied_alpha_fragment:gm,project_vertex:_m,dithering_fragment:xm,dithering_pars_fragment:ym,roughnessmap_fragment:vm,roughnessmap_pars_fragment:bm,shadowmap_pars_fragment:Sm,shadowmap_pars_vertex:Mm,shadowmap_vertex:wm,shadowmask_pars_fragment:Em,skinbase_vertex:Tm,skinning_pars_vertex:Am,skinning_vertex:Rm,skinnormal_vertex:Cm,specularmap_fragment:Pm,specularmap_pars_fragment:Im,tonemapping_fragment:Lm,tonemapping_pars_fragment:Nm,transmission_fragment:Dm,transmission_pars_fragment:Um,uv_pars_fragment:Fm,uv_pars_vertex:Om,uv_vertex:Bm,worldpos_vertex:km,background_vert:zm,background_frag:Vm,backgroundCube_vert:Gm,backgroundCube_frag:Hm,cube_vert:Wm,cube_frag:$m,depth_vert:Xm,depth_frag:qm,distance_vert:Ym,distance_frag:Zm,equirect_vert:Jm,equirect_frag:Km,linedashed_vert:jm,linedashed_frag:Qm,meshbasic_vert:eg,meshbasic_frag:tg,meshlambert_vert:ng,meshlambert_frag:ig,meshmatcap_vert:sg,meshmatcap_frag:rg,meshnormal_vert:og,meshnormal_frag:ag,meshphong_vert:lg,meshphong_frag:cg,meshphysical_vert:hg,meshphysical_frag:ug,meshtoon_vert:dg,meshtoon_frag:fg,points_vert:pg,points_frag:mg,shadow_vert:gg,shadow_frag:_g,sprite_vert:xg,sprite_frag:yg},pe={common:{diffuse:{value:new Ie(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Le},alphaMap:{value:null},alphaMapTransform:{value:new Le},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Le}},envmap:{envMap:{value:null},envMapRotation:{value:new Le},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Le}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Le}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Le},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Le},normalScale:{value:new ze(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Le},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Le}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Le}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Le}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ie(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},sunLights:{value:[],properties:{direction:{},color:{}}},sunLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},sunShadowMatrix:{value:[]},sunShadowCascade:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],pr
Line truncated
|
||||
|
||||
varying vec3 vWorldDirection;
|
||||
|
||||
@@ -3858,7 +3858,7 @@ void main() {
|
||||
gl_FragColor = texture2D( tEquirect, sampleUV );
|
||||
|
||||
}
|
||||
`},s=new Ji(5,5,5),r=new xn({name:"CubemapFromEquirect",uniforms:wi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Ot,blending:yi});r.uniforms.tEquirect.value=t;let o=new Xt(s,r),a=t.minFilter;return t.minFilter===Dn&&(t.minFilter=Ft),new Qi(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){let r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,s);e.setRenderTarget(r)}},Au=256,Tg=3,Ag=20,Ju=256,Ku=16,Rg=3,Cg=new B,Pg=new Ie,ma=class i{constructor(e){this._renderer=e,this._cubeSize=0,this._sourceTarget=null,this._cubeCamera=new Qi(1,10,null),this._boxMesh=new Xt(new Ji(5,5,5),null),this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null,this._integrationMaterial=null}fromScene(e,t=0,n=.1,s=100,r={}){let{size:o=256,position:a=Cg}=r,l=this._renderer;this._setSize(o);let c=this._allocateTarget(),u=this._getSourceTarget(!0);t>0&&(u.texture.mipmapsAutoUpdate=!1);let d=l.autoClear,f=l.autoClearColor,h=l.autoClearDepth,g=l.autoClearStencil,v=e.background;l.autoClear=!0,l.autoClearColor=!0,l.autoClearDepth=!0,l.autoClearStencil=!0,v===null&&(e.background=l.getClearColor(Pg));let p=new Qi(n,s,u);return p.position.copy(a),p.update(l,e),l.autoClear=d,l.autoClearColor=f,l.autoClearDepth=h,l.autoClearStencil=g,e.background=v,t>0&&(u.texture.mipmapsAutoUpdate=!0,this._blur(c,t)),this._applyPMREM(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Pu(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Cu(),this._compileMaterial(this._equirectMaterial))}dispose(){this._sourceTarget!==null&&this._sourceTarget.dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._integrationMaterial!==null&&this._integrationMaterial.dispose(),this._boxMesh.geometry.dispose()}static lodToRoughness(e,t){return t>0?1-Math.sqrt(1-e/t):0}_setSize(e){this._cubeSize=Math.max(Au,xu(e))}_fromTexture(e,t){e.mapping===Si||e.mapping===ts?this._setSize(e.image.length===0?Au:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4);let n=t||this._allocateTarget();return this._textureToCubemap(e),this._applyPMREM(n),n}_allocateTarget(){let e=this._cubeSize,t=Ru(e,!1,!1),n=Math.log2(e)-Tg;for(let s=0;s<=n;s++)t.texture.mipmaps.push({width:e>>s,height:e>>s});return t.texture.name="PMREM",t.texture.isPMREMTexture=!0,t}_getSourceTarget(e=!1){let t=this._cubeSize,n=this._sourceTarget;return(n===null||n.width!==t||e&&n.depthBuffer===!1)&&(n!==null&&n.dispose(),this._sourceTarget=Ru(t,!0,e)),this._sourceTarget}_compileMaterial(e){this._boxMesh.material=e,this._renderer.compile(this._boxMesh,this._cubeCamera.children[0])}_renderCube(e,t,n){let s=this._boxMesh,r=this._cubeCamera;s.material=n,r.renderTarget=e,r.activeMipmapLevel=t;let o=e.width>>t;e.viewport.set(0,0,o,o),r.update(this._renderer,s),e.viewport.set(0,0,e.width,e.height)}_textureToCubemap(e){let t;e.mapping===Si||e.mapping===ts?(this._cubemapMaterial===null&&(this._cubemapMaterial=Pu()),t=this._cubemapMaterial,t.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):(this._equirectMaterial===null&&(this._equirectMaterial=Cu()),t=this._equirectMaterial),t.uniforms.envMap.value=e,this._renderCube(this._getSourceTarget(),0,t)}_applyPMREM(e){this._ggxMaterial===null&&(this._ggxMaterial=Ig(),this._integrationMaterial=Lg());let t=this._cubeSize,n=e.texture.mipmaps.length-1,s=this._ggxMaterial.uniforms;s.envMap.value=this._sourceTarget.texture;let r=this._integrationMaterial.uniforms;r.envMap.value=this._sourceTarget.texture,r.sourceLod.value=Math.log2(t/Ku);for(let o=0;o<=n;o++){let a=i.lodToRoughness(o,n);if(o>n-Rg)r.roughness.value=a,this._renderCube(e,o,this._integrationMaterial);else{let l=a>0?Math.log2(t)+.5*Math.log2(6/(Ju*Math.pow(a,4)))+.5:0;s.roughness.value=a,s.lodBias.value=l,this._renderCube(e,o,this._ggxMaterial)}}}_blur(e,t){this._blurMaterial===null&&(this._blurMaterial=Ng());let n=this._blurMaterial,s=n.uniforms,r=this._sourceTarget;s.sigma.value=Math.min(t,Math.PI)/Math.SQRT2,s.envMap.value=r.texture,this._renderCube(e,0,n),s.envMap.value=e.texture,this._renderCube(r,0,n)}};function Ru(i,e,t){return new nr(i,{minFilter:Dn,generateMipmaps:e,type:hn,colorSpace:Es,depthBuffer:t})}function ir(i,e,t){return new xn({name:i,uniforms:e,vertexShader:ke.cube_vert,fragmentShader:t,side:Ot,blending:yi,depthTest:!1,depthWrite:!1})}function Ig(){return ir("PMREMGGXConvolution",{envMap:{value:null},roughness:{value:0},lodBias:{value:0}},`
|
||||
`},s=new Ji(5,5,5),r=new xn({name:"CubemapFromEquirect",uniforms:wi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Ot,blending:vi});r.uniforms.tEquirect.value=t;let o=new Xt(s,r),a=t.minFilter;return t.minFilter===Un&&(t.minFilter=Ft),new ji(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){let r=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,s);e.setRenderTarget(r)}},Au=256,Tg=3,Ag=20,Ju=256,Ku=16,Rg=3,Cg=new B,Pg=new Ie,ma=class i{constructor(e){this._renderer=e,this._cubeSize=0,this._sourceTarget=null,this._cubeCamera=new ji(1,10,null),this._boxMesh=new Xt(new Ji(5,5,5),null),this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null,this._integrationMaterial=null}fromScene(e,t=0,n=.1,s=100,r={}){let{size:o=256,position:a=Cg}=r,l=this._renderer;this._setSize(o);let c=this._allocateTarget(),u=this._getSourceTarget(!0);t>0&&(u.texture.mipmapsAutoUpdate=!1);let d=l.autoClear,f=l.autoClearColor,h=l.autoClearDepth,g=l.autoClearStencil,y=e.background;l.autoClear=!0,l.autoClearColor=!0,l.autoClearDepth=!0,l.autoClearStencil=!0,y===null&&(e.background=l.getClearColor(Pg));let p=new ji(n,s,u);return p.position.copy(a),p.update(l,e),l.autoClear=d,l.autoClearColor=f,l.autoClearDepth=h,l.autoClearStencil=g,e.background=y,t>0&&(u.texture.mipmapsAutoUpdate=!0,this._blur(c,t)),this._applyPMREM(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Pu(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Cu(),this._compileMaterial(this._equirectMaterial))}dispose(){this._sourceTarget!==null&&this._sourceTarget.dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._integrationMaterial!==null&&this._integrationMaterial.dispose(),this._boxMesh.geometry.dispose()}static lodToRoughness(e,t){return t>0?1-Math.sqrt(1-e/t):0}_setSize(e){this._cubeSize=Math.max(Au,xu(e))}_fromTexture(e,t){e.mapping===Si||e.mapping===ts?this._setSize(e.image.length===0?Au:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4);let n=t||this._allocateTarget();return this._textureToCubemap(e),this._applyPMREM(n),n}_allocateTarget(){let e=this._cubeSize,t=Ru(e,!1,!1),n=Math.log2(e)-Tg;for(let s=0;s<=n;s++)t.texture.mipmaps.push({width:e>>s,height:e>>s});return t.texture.name="PMREM",t.texture.isPMREMTexture=!0,t}_getSourceTarget(e=!1){let t=this._cubeSize,n=this._sourceTarget;return(n===null||n.width!==t||e&&n.depthBuffer===!1)&&(n!==null&&n.dispose(),this._sourceTarget=Ru(t,!0,e)),this._sourceTarget}_compileMaterial(e){this._boxMesh.material=e,this._renderer.compile(this._boxMesh,this._cubeCamera.children[0])}_renderCube(e,t,n){let s=this._boxMesh,r=this._cubeCamera;s.material=n,r.renderTarget=e,r.activeMipmapLevel=t;let o=e.width>>t;e.viewport.set(0,0,o,o),r.update(this._renderer,s),e.viewport.set(0,0,e.width,e.height)}_textureToCubemap(e){let t;e.mapping===Si||e.mapping===ts?(this._cubemapMaterial===null&&(this._cubemapMaterial=Pu()),t=this._cubemapMaterial,t.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):(this._equirectMaterial===null&&(this._equirectMaterial=Cu()),t=this._equirectMaterial),t.uniforms.envMap.value=e,this._renderCube(this._getSourceTarget(),0,t)}_applyPMREM(e){this._ggxMaterial===null&&(this._ggxMaterial=Ig(),this._integrationMaterial=Lg());let t=this._cubeSize,n=e.texture.mipmaps.length-1,s=this._ggxMaterial.uniforms;s.envMap.value=this._sourceTarget.texture;let r=this._integrationMaterial.uniforms;r.envMap.value=this._sourceTarget.texture,r.sourceLod.value=Math.log2(t/Ku);for(let o=0;o<=n;o++){let a=i.lodToRoughness(o,n);if(o>n-Rg)r.roughness.value=a,this._renderCube(e,o,this._integrationMaterial);else{let l=a>0?Math.log2(t)+.5*Math.log2(6/(Ju*Math.pow(a,4)))+.5:0;s.roughness.value=a,s.lodBias.value=l,this._renderCube(e,o,this._ggxMaterial)}}}_blur(e,t){this._blurMaterial===null&&(this._blurMaterial=Ng());let n=this._blurMaterial,s=n.uniforms,r=this._sourceTarget;s.sigma.value=Math.min(t,Math.PI)/Math.SQRT2,s.envMap.value=r.texture,this._renderCube(e,0,n),s.envMap.value=e.texture,this._renderCube(r,0,n)}};function Ru(i,e,t){return new nr(i,{minFilter:Un,generateMipmaps:e,type:hn,colorSpace:Es,depthBuffer:t})}function ir(i,e,t){return new xn({name:i,uniforms:e,vertexShader:ke.cube_vert,fragmentShader:t,side:Ot,blending:vi,depthTest:!1,depthWrite:!1})}function Ig(){return ir("PMREMGGXConvolution",{envMap:{value:null},roughness:{value:0},lodBias:{value:0}},`
|
||||
|
||||
#define GGX_SAMPLES ${Ju}u
|
||||
|
||||
@@ -4077,7 +4077,7 @@ void main() {
|
||||
gl_FragColor = vec4( textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ).rgb, 1.0 );
|
||||
|
||||
}
|
||||
`)}function Dg(i){let e=new WeakMap,t=new WeakMap,n=null;function s(f,h=!1){return f==null?null:h?o(f):r(f)}function r(f){if(f&&f.isTexture){let h=f.mapping;if(h===Ro||h===Co)if(e.has(f)){let g=e.get(f).texture;return a(g,f.mapping)}else{let g=f.image;if(g&&g.height>0){let v=new nr(g.height);return v.fromEquirectangularTexture(i,f),e.set(f,v),f.addEventListener("dispose",c),a(v.texture,f.mapping)}else return null}}return f}function o(f){if(f&&f.isTexture&&f.isPMREMTexture!==!0){let h=f.mapping,g=h===Ro||h===Co,v=h===Si||h===ts;if(g||v){let p=t.get(f),m=p!==void 0?p.texture.pmremVersion:0;if(f.isRenderTargetTexture&&f.pmremVersion!==m)return n===null&&(n=new ma(i)),p=g?n.fromEquirectangular(f,p):n.fromCubemap(f,p),p.texture.pmremVersion=f.pmremVersion,t.set(f,p),p.texture;if(p!==void 0)return p.texture;{let b=f.image;return g&&b&&b.height>0||v&&b&&l(b)?(n===null&&(n=new ma(i)),p=g?n.fromEquirectangular(f):n.fromCubemap(f),p.texture.pmremVersion=f.pmremVersion,t.set(f,p),f.addEventListener("dispose",u),p.texture):null}}}return f}function a(f,h){return h===Ro?f.mapping=Si:h===Co&&(f.mapping=ts),f}function l(f){let h=0,g=6;for(let v=0;v<g;v++)f[v]!==void 0&&h++;return h===g}function c(f){let h=f.target;h.removeEventListener("dispose",c);let g=e.get(h);g!==void 0&&(e.delete(h),g.dispose())}function u(f){let h=f.target;h.removeEventListener("dispose",u);let g=t.get(h);g!==void 0&&(t.delete(h),g.dispose())}function d(){e=new WeakMap,t=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:s,dispose:d}}function Ug(i){let e={};function t(n){if(e[n]!==void 0)return e[n];let s=i.getExtension(n);return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){let s=t(n);return s===null&&Ms("WebGLRenderer: "+n+" extension not supported."),s}}}function Fg(i,e,t,n){let s={},r=new WeakMap,o=new FinalizationRegistry(g=>delete s[g]);function a(g){l(g.target)}function l(g){g.index!==null&&e.remove(g.index);for(let p in g.attributes)e.remove(g.attributes[p]);g.removeEventListener("dispose",a),delete s[g.id],o.unregister(g);let v=r.get(g);v&&(e.remove(v),r.delete(g)),n.releaseStatesOfGeometry(g),g.isInstancedBufferGeometry===!0&&delete g._maxInstanceCount,t.memory.geometries--}function c(g,v){return s[v.id]!==void 0||(v.addEventListener("dispose",a),s[v.id]=new WeakRef(v),o.register(v,v.id,v),t.memory.geometries++),v}function u(g){let v=g.attributes;for(let p in v)e.update(v[p],i.ARRAY_BUFFER)}function d(g){let v=g.index,p=g.attributes.position,m=0;if(p===void 0)return;let b=v!==null?v.array.length:p.array.length/3-1,w=p.count>=65535?Ls:Is,S=new w(Math.ceil(b/3)*6,1),A=S.array;if(v!==null){let _=v.array;m=v.version;for(let M=0,U=0;M<b;M+=3){let I=_[M+0],N=_[M+1],k=_[M+2];A[U++]=I,A[U++]=N,A[U++]=N,A[U++]=k,A[U++]=k,A[U++]=I}}else{m=p.version;for(let _=0,M=0;_<b;_+=3){let U=_+0,I=_+1,N=_+2;A[M++]=U,A[M++]=I,A[M++]=I,A[M++]=N,A[M++]=N,A[M++]=U}}S.version=m;let T=r.get(g);T&&e.remove(T),r.set(g,S)}function f(g){let v=r.get(g);if(v){let p=g.index;p!==null&&v.version<p.version&&d(g)}else d(g);return r.get(g)}function h(){for(let g in s){let v=s[g].deref();v!==void 0&&l(v)}}return{get:c,update:u,getWireframeAttribute:f,dispose:h}}function Og(i,e,t){let n;function s(d){n=d}let r,o;function a(d){r=d.type,o=d.bytesPerElement}function l(d,f){i.drawElements(n,f,r,d*o),t.update(f,n,1)}function c(d,f,h){h!==0&&(i.drawElementsInstanced(n,f,r,d*o,h),t.update(f,n,h))}function u(d,f,h){if(h===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,d,0,h);let v=0;for(let p=0;p<h;p++)v+=f[p];t.update(v,n,1)}this.setMode=s,this.setIndex=a,this.render=l,this.renderInstances=c,this.renderMultiDraw=u}function Bg(i){let e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,o,a){switch(t.calls++,o){case i.TRIANGLES:t.triangles+=a*(r/3);break;case i.LINES:t.lines+=a*(r/2);break;case i.LINE_STRIP:t.lines+=a*(r-1);break;case i.LINE_LOOP:t.lines+=a*r;break;case i.POINTS:t.points+=a*r;break;default:Pe("WebGLInfo: Unknown draw mode:",o);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function kg(i,e,t){let n=new WeakMap,s=new ht;function r(o,a,l){let c=o.morphTargetInfluences,u=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,d=u!==void 0?u.length:0,f=n.get(a);if(f===void 0||f.count!==d){let U=function(){_.dispose(),n.delete(a),a.removeEventListener("dispose",U)};f!==void 0&&f.texture.dispose();let h=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,v=a.morphAttributes.color!==void 0,p=a.morphAttributes.position||[],m=a.morphAttributes.normal||[],b=a.morphAttributes.color||[],w=0;h===!0&&(w=1),g===!0&&(w=2),v===!0&&(w=3);let S=a.attributes.position.count*w,
Line truncated
|
||||
`)}function Dg(i){let e=new WeakMap,t=new WeakMap,n=null;function s(f,h=!1){return f==null?null:h?o(f):r(f)}function r(f){if(f&&f.isTexture){let h=f.mapping;if(h===Ro||h===Co)if(e.has(f)){let g=e.get(f).texture;return a(g,f.mapping)}else{let g=f.image;if(g&&g.height>0){let y=new nr(g.height);return y.fromEquirectangularTexture(i,f),e.set(f,y),f.addEventListener("dispose",c),a(y.texture,f.mapping)}else return null}}return f}function o(f){if(f&&f.isTexture&&f.isPMREMTexture!==!0){let h=f.mapping,g=h===Ro||h===Co,y=h===Si||h===ts;if(g||y){let p=t.get(f),m=p!==void 0?p.texture.pmremVersion:0;if(f.isRenderTargetTexture&&f.pmremVersion!==m)return n===null&&(n=new ma(i)),p=g?n.fromEquirectangular(f,p):n.fromCubemap(f,p),p.texture.pmremVersion=f.pmremVersion,t.set(f,p),p.texture;if(p!==void 0)return p.texture;{let b=f.image;return g&&b&&b.height>0||y&&b&&l(b)?(n===null&&(n=new ma(i)),p=g?n.fromEquirectangular(f):n.fromCubemap(f),p.texture.pmremVersion=f.pmremVersion,t.set(f,p),f.addEventListener("dispose",u),p.texture):null}}}return f}function a(f,h){return h===Ro?f.mapping=Si:h===Co&&(f.mapping=ts),f}function l(f){let h=0,g=6;for(let y=0;y<g;y++)f[y]!==void 0&&h++;return h===g}function c(f){let h=f.target;h.removeEventListener("dispose",c);let g=e.get(h);g!==void 0&&(e.delete(h),g.dispose())}function u(f){let h=f.target;h.removeEventListener("dispose",u);let g=t.get(h);g!==void 0&&(t.delete(h),g.dispose())}function d(){e=new WeakMap,t=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:s,dispose:d}}function Ug(i){let e={};function t(n){if(e[n]!==void 0)return e[n];let s=i.getExtension(n);return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){let s=t(n);return s===null&&Ms("WebGLRenderer: "+n+" extension not supported."),s}}}function Fg(i,e,t,n){let s={},r=new WeakMap,o=new FinalizationRegistry(g=>delete s[g]);function a(g){l(g.target)}function l(g){g.index!==null&&e.remove(g.index);for(let p in g.attributes)e.remove(g.attributes[p]);g.removeEventListener("dispose",a),delete s[g.id],o.unregister(g);let y=r.get(g);y&&(e.remove(y),r.delete(g)),n.releaseStatesOfGeometry(g),g.isInstancedBufferGeometry===!0&&delete g._maxInstanceCount,t.memory.geometries--}function c(g,y){return s[y.id]!==void 0||(y.addEventListener("dispose",a),s[y.id]=new WeakRef(y),o.register(y,y.id,y),t.memory.geometries++),y}function u(g){let y=g.attributes;for(let p in y)e.update(y[p],i.ARRAY_BUFFER)}function d(g){let y=g.index,p=g.attributes.position,m=0;if(p===void 0)return;let b=y!==null?y.array.length:p.array.length/3-1,w=p.count>=65535?Ls:Is,S=new w(Math.ceil(b/3)*6,1),A=S.array;if(y!==null){let _=y.array;m=y.version;for(let M=0,U=0;M<b;M+=3){let I=_[M+0],N=_[M+1],k=_[M+2];A[U++]=I,A[U++]=N,A[U++]=N,A[U++]=k,A[U++]=k,A[U++]=I}}else{m=p.version;for(let _=0,M=0;_<b;_+=3){let U=_+0,I=_+1,N=_+2;A[M++]=U,A[M++]=I,A[M++]=I,A[M++]=N,A[M++]=N,A[M++]=U}}S.version=m;let T=r.get(g);T&&e.remove(T),r.set(g,S)}function f(g){let y=r.get(g);if(y){let p=g.index;p!==null&&y.version<p.version&&d(g)}else d(g);return r.get(g)}function h(){for(let g in s){let y=s[g].deref();y!==void 0&&l(y)}}return{get:c,update:u,getWireframeAttribute:f,dispose:h}}function Og(i,e,t){let n;function s(d){n=d}let r,o;function a(d){r=d.type,o=d.bytesPerElement}function l(d,f){i.drawElements(n,f,r,d*o),t.update(f,n,1)}function c(d,f,h){h!==0&&(i.drawElementsInstanced(n,f,r,d*o,h),t.update(f,n,h))}function u(d,f,h){if(h===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,d,0,h);let y=0;for(let p=0;p<h;p++)y+=f[p];t.update(y,n,1)}this.setMode=s,this.setIndex=a,this.render=l,this.renderInstances=c,this.renderMultiDraw=u}function Bg(i){let e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,o,a){switch(t.calls++,o){case i.TRIANGLES:t.triangles+=a*(r/3);break;case i.LINES:t.lines+=a*(r/2);break;case i.LINE_STRIP:t.lines+=a*(r-1);break;case i.LINE_LOOP:t.lines+=a*r;break;case i.POINTS:t.points+=a*r;break;default:Pe("WebGLInfo: Unknown draw mode:",o);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function kg(i,e,t){let n=new WeakMap,s=new ht;function r(o,a,l){let c=o.morphTargetInfluences,u=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,d=u!==void 0?u.length:0,f=n.get(a);if(f===void 0||f.count!==d){let U=function(){_.dispose(),n.delete(a),a.removeEventListener("dispose",U)};f!==void 0&&f.texture.dispose();let h=a.morphAttributes.position!==void 0,g=a.morphAttributes.normal!==void 0,y=a.morphAttributes.color!==void 0,p=a.morphAttributes.position||[],m=a.morphAttributes.normal||[],b=a.morphAttributes.color||[],w=0;h===!0&&(w=1),g===!0&&(w=2),y===!0&&(w=3);let S=a.attributes.position.count*w,
Line truncated
|
||||
precision highp float;
|
||||
|
||||
uniform mat4 modelViewMatrix;
|
||||
@@ -4123,7 +4123,7 @@ void main() {
|
||||
#ifdef SRGB_TRANSFER
|
||||
gl_FragColor = sRGBTransferOETF( gl_FragColor );
|
||||
#endif
|
||||
}`,depthTest:!1,depthWrite:!1}),f=new Xt(u,d),h=new Eo(-1,1,1,-1,0,1),g=null,v=null,p=!1,m,b=null,w=[],S=!1;this.setSize=function(A,T){o.setSize(A,T),a!==null&&a.setSize(A,T),l!==null&&l.setSize(A,T);for(let _=0;_<w.length;_++){let M=w[_];M.setSize&&M.setSize(A,T)}},this.setEffects=function(A){w=A,S=w.length>0&&w[0].isRenderPass===!0;let T=o.width,_=o.height;w.length>0&&a===null&&(a=new Ht(T,_,{type:hn,depthBuffer:!1,stencilBuffer:!1}),l=new Ht(T,_,{type:hn,depthBuffer:!1,stencilBuffer:!1}));let M=s===!0&&w.some(U=>U.needsDepthTexture===!0);M!==(o.depthTexture!==null)&&(M===!0&&c===null&&(c=new Nn(T,_),r===!0&&(c.format=Un,c.type=Mi)),o.dispose(),o.depthTexture=M?c:null,o.resolveDepthBuffer=M,o.storeMultisampledDepthBuffer=M);for(let U=0;U<w.length;U++){let I=w[U];I.setSize&&I.setSize(T,_),M&&I.needsDepthTexture===!0&&I.setDepthTexture&&I.setDepthTexture(c)}},this.begin=function(A,T){if(p||A.toneMapping===yn&&w.length===0)return!1;if(b=T,T!==null){let _=T.width,M=T.height;(o.width!==_||o.height!==M)&&this.setSize(_,M)}return S===!1&&A.setRenderTarget(o),m=A.toneMapping,A.toneMapping=yn,!0},this.hasRenderPass=function(){return S},this.end=function(A,T){A.toneMapping=m,p=!0;let _=o,M=a;for(let U=0;U<w.length;U++){let I=w[U];I.enabled!==!1&&(I.render(A,M,_,T),I.needsSwap!==!1&&(_=M,M=M===a?l:a))}if(g!==A.outputColorSpace||v!==A.toneMapping){g=A.outputColorSpace,v=A.toneMapping,d.defines={},We.getTransfer(g)===Ze&&(d.defines.SRGB_TRANSFER="");let U=Vg[v];U&&(d.defines[U]=""),d.needsUpdate=!0}d.uniforms.tDiffuse.value=_.texture,A.setRenderTarget(b),A.render(f,h),b=null,p=!1},this.isCompositing=function(){return p},this.dispose=function(){o.dispose(),a!==null&&a.dispose(),l!==null&&l.dispose(),u.dispose(),d.dispose()}}var Qu=new kt,ju=new Nn(1,1),ed=new Ds(1),td=new Cs,nd=new ro,id=new Ns,Iu=[],Lu=[],Nu=new Float32Array(16),Du=new Float32Array(9),Uu=new Float32Array(4);function ss(i,e,t){let n=i[0];if(n<=0||n>0)return i;let s=e*t,r=Iu[s];if(r===void 0&&(r=new Float32Array(s),Iu[s]=r),e!==0){n.toArray(r,0);for(let o=1,a=0;o!==e;++o)a+=t,i[o].toArray(r,a)}return r}function _t(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function xt(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function _a(i,e){let t=Lu[e];t===void 0&&(t=new Int32Array(e),Lu[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function Hg(i,e){let t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function Wg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(_t(t,e))return;i.uniform2fv(this.addr,e),xt(t,e)}}function $g(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(_t(t,e))return;i.uniform3fv(this.addr,e),xt(t,e)}}function Xg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(_t(t,e))return;i.uniform4fv(this.addr,e),xt(t,e)}}function qg(i,e){let t=this.cache,n=e.elements;if(n===void 0){if(_t(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),xt(t,e)}else{if(_t(t,n))return;Uu.set(n),i.uniformMatrix2fv(this.addr,!1,Uu),xt(t,n)}}function Yg(i,e){let t=this.cache,n=e.elements;if(n===void 0){if(_t(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),xt(t,e)}else{if(_t(t,n))return;Du.set(n),i.uniformMatrix3fv(this.addr,!1,Du),xt(t,n)}}function Zg(i,e){let t=this.cache,n=e.elements;if(n===void 0){if(_t(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),xt(t,e)}else{if(_t(t,n))return;Nu.set(n),i.uniformMatrix4fv(this.addr,!1,Nu),xt(t,n)}}function Jg(i,e){let t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function Kg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(_t(t,e))return;i.uniform2iv(this.addr,e),xt(t,e)}}function Qg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(_t(t,e))return;i.uniform3iv(this.addr,e),xt(t,e)}}function jg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(_t(t,e))return;i.uniform4iv(this.addr,e),xt(t,e)}}function e0(i,e){let t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function t0(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(_t(t,e))return;i.uniform2uiv(this.addr,e),xt(t,e)}}function n0(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(_t(t,e))return;i.uniform3uiv(thi
Line truncated
|
||||
}`,depthTest:!1,depthWrite:!1}),f=new Xt(u,d),h=new Eo(-1,1,1,-1,0,1),g=null,y=null,p=!1,m,b=null,w=[],S=!1;this.setSize=function(A,T){o.setSize(A,T),a!==null&&a.setSize(A,T),l!==null&&l.setSize(A,T);for(let _=0;_<w.length;_++){let M=w[_];M.setSize&&M.setSize(A,T)}},this.setEffects=function(A){w=A,S=w.length>0&&w[0].isRenderPass===!0;let T=o.width,_=o.height;w.length>0&&a===null&&(a=new Ht(T,_,{type:hn,depthBuffer:!1,stencilBuffer:!1}),l=new Ht(T,_,{type:hn,depthBuffer:!1,stencilBuffer:!1}));let M=s===!0&&w.some(U=>U.needsDepthTexture===!0);M!==(o.depthTexture!==null)&&(M===!0&&c===null&&(c=new Dn(T,_),r===!0&&(c.format=Fn,c.type=Mi)),o.dispose(),o.depthTexture=M?c:null,o.resolveDepthBuffer=M,o.storeMultisampledDepthBuffer=M);for(let U=0;U<w.length;U++){let I=w[U];I.setSize&&I.setSize(T,_),M&&I.needsDepthTexture===!0&&I.setDepthTexture&&I.setDepthTexture(c)}},this.begin=function(A,T){if(p||A.toneMapping===vn&&w.length===0)return!1;if(b=T,T!==null){let _=T.width,M=T.height;(o.width!==_||o.height!==M)&&this.setSize(_,M)}return S===!1&&A.setRenderTarget(o),m=A.toneMapping,A.toneMapping=vn,!0},this.hasRenderPass=function(){return S},this.end=function(A,T){A.toneMapping=m,p=!0;let _=o,M=a;for(let U=0;U<w.length;U++){let I=w[U];I.enabled!==!1&&(I.render(A,M,_,T),I.needsSwap!==!1&&(_=M,M=M===a?l:a))}if(g!==A.outputColorSpace||y!==A.toneMapping){g=A.outputColorSpace,y=A.toneMapping,d.defines={},We.getTransfer(g)===Ze&&(d.defines.SRGB_TRANSFER="");let U=Vg[y];U&&(d.defines[U]=""),d.needsUpdate=!0}d.uniforms.tDiffuse.value=_.texture,A.setRenderTarget(b),A.render(f,h),b=null,p=!1},this.isCompositing=function(){return p},this.dispose=function(){o.dispose(),a!==null&&a.dispose(),l!==null&&l.dispose(),u.dispose(),d.dispose()}}var ju=new kt,Qu=new Dn(1,1),ed=new Ds(1),td=new Cs,nd=new ro,id=new Ns,Iu=[],Lu=[],Nu=new Float32Array(16),Du=new Float32Array(9),Uu=new Float32Array(4);function ss(i,e,t){let n=i[0];if(n<=0||n>0)return i;let s=e*t,r=Iu[s];if(r===void 0&&(r=new Float32Array(s),Iu[s]=r),e!==0){n.toArray(r,0);for(let o=1,a=0;o!==e;++o)a+=t,i[o].toArray(r,a)}return r}function _t(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function xt(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function _a(i,e){let t=Lu[e];t===void 0&&(t=new Int32Array(e),Lu[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function Hg(i,e){let t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function Wg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(_t(t,e))return;i.uniform2fv(this.addr,e),xt(t,e)}}function $g(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(_t(t,e))return;i.uniform3fv(this.addr,e),xt(t,e)}}function Xg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(_t(t,e))return;i.uniform4fv(this.addr,e),xt(t,e)}}function qg(i,e){let t=this.cache,n=e.elements;if(n===void 0){if(_t(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),xt(t,e)}else{if(_t(t,n))return;Uu.set(n),i.uniformMatrix2fv(this.addr,!1,Uu),xt(t,n)}}function Yg(i,e){let t=this.cache,n=e.elements;if(n===void 0){if(_t(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),xt(t,e)}else{if(_t(t,n))return;Du.set(n),i.uniformMatrix3fv(this.addr,!1,Du),xt(t,n)}}function Zg(i,e){let t=this.cache,n=e.elements;if(n===void 0){if(_t(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),xt(t,e)}else{if(_t(t,n))return;Nu.set(n),i.uniformMatrix4fv(this.addr,!1,Nu),xt(t,n)}}function Jg(i,e){let t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function Kg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(_t(t,e))return;i.uniform2iv(this.addr,e),xt(t,e)}}function jg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(_t(t,e))return;i.uniform3iv(this.addr,e),xt(t,e)}}function Qg(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(_t(t,e))return;i.uniform4iv(this.addr,e),xt(t,e)}}function e0(i,e){let t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function t0(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(_t(t,e))return;i.uniform2uiv(this.addr,e),xt(t,e)}}function n0(i,e){let t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(_t(t,e))return;i.uniform3uiv(thi
Line truncated
|
||||
`),n=[],s=Math.max(e-6,0),r=Math.min(e+6,t.length);for(let o=s;o<r;o++){let a=o+1;n.push(`${a===e?">":" "} ${a}: ${t[o]}`)}return n.join(`
|
||||
`)}var Bu=new Le;function N0(i){We._getMatrix(Bu,We.workingColorSpace,i);let e=`mat3( ${Bu.elements.map(t=>t.toFixed(4))} )`;switch(We.getTransfer(i)){case Ts:return[e,"LinearTransferOETF"];case Ze:return[e,"sRGBTransferOETF"];default:return Re("WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function ku(i,e,t){let n=i.getShaderParameter(e,i.COMPILE_STATUS),r=(i.getShaderInfoLog(e)||"").trim();if(n&&r==="")return"";let o=/ERROR: 0:(\d+)/.exec(r);if(o){let a=parseInt(o[1]);return t.toUpperCase()+`
|
||||
|
||||
@@ -4153,28 +4153,28 @@ void main() {
|
||||
`;return i.precision==="highp"?e+=`
|
||||
#define HIGH_PRECISION`:i.precision==="mediump"?e+=`
|
||||
#define MEDIUM_PRECISION`:i.precision==="lowp"&&(e+=`
|
||||
#define LOW_PRECISION`),e}var $0={[$s]:"SHADOWMAP_TYPE_PCF",[ji]:"SHADOWMAP_TYPE_VSM"};function X0(i){return $0[i.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}var q0={[ts]:"ENVMAP_MODE_REFRACTION"};function Y0(i){return i.envMap===!1?"ENVMAP_MODE_REFLECTION":q0[i.envMapMode]||"ENVMAP_MODE_REFLECTION"}var Z0={[Tl]:"ENVMAP_BLENDING_MULTIPLY",[nu]:"ENVMAP_BLENDING_MIX",[iu]:"ENVMAP_BLENDING_ADD"};function J0(i){return i.envMap===!1?"ENVMAP_BLENDING_NONE":Z0[i.combine]||"ENVMAP_BLENDING_NONE"}function K0(i,e,t,n){let s=i.getContext(),r=t.defines,o=t.vertexShader,a=t.fragmentShader,l=X0(t),c=t.envMapPMREM===!0?"ENVMAP_TYPE_PMREM":"ENVMAP_TYPE_CUBE",u=Y0(t),d=J0(t),f=B0(t),h=k0(r),g=s.createProgram(),v,p,m=t.glslVersion?"#version "+t.glslVersion+`
|
||||
`:"";t.isRawShaderMaterial?(v=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,h].filter(tr).join(`
|
||||
`),v.length>0&&(v+=`
|
||||
#define LOW_PRECISION`),e}var $0={[$s]:"SHADOWMAP_TYPE_PCF",[Qi]:"SHADOWMAP_TYPE_VSM"};function X0(i){return $0[i.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}var q0={[ts]:"ENVMAP_MODE_REFRACTION"};function Y0(i){return i.envMap===!1?"ENVMAP_MODE_REFLECTION":q0[i.envMapMode]||"ENVMAP_MODE_REFLECTION"}var Z0={[Tl]:"ENVMAP_BLENDING_MULTIPLY",[nu]:"ENVMAP_BLENDING_MIX",[iu]:"ENVMAP_BLENDING_ADD"};function J0(i){return i.envMap===!1?"ENVMAP_BLENDING_NONE":Z0[i.combine]||"ENVMAP_BLENDING_NONE"}function K0(i,e,t,n){let s=i.getContext(),r=t.defines,o=t.vertexShader,a=t.fragmentShader,l=X0(t),c=t.envMapPMREM===!0?"ENVMAP_TYPE_PMREM":"ENVMAP_TYPE_CUBE",u=Y0(t),d=J0(t),f=B0(t),h=k0(r),g=s.createProgram(),y,p,m=t.glslVersion?"#version "+t.glslVersion+`
|
||||
`:"";t.isRawShaderMaterial?(y=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,h].filter(tr).join(`
|
||||
`),y.length>0&&(y+=`
|
||||
`),p=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,h].filter(tr).join(`
|
||||
`),p.length>0&&(p+=`
|
||||
`)):(v=[Hu(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,h,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.diffuseRoughnessMap?"#define USE_DIFFUSE_ROUGHNESSMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.diffuseRoughnessMapUv?"#define DIFFUSE_ROUGHNESSMAP_UV "+t.diffuseRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexNormals?"#define HAS_NORMAL":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_
Line truncated
|
||||
`)):(y=[Hu(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,h,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.diffuseRoughnessMap?"#define USE_DIFFUSE_ROUGHNESSMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.diffuseRoughnessMapUv?"#define DIFFUSE_ROUGHNESSMAP_UV "+t.diffuseRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexNormals?"#define HAS_NORMAL":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_
Line truncated
|
||||
`].filter(tr).join(`
|
||||
`),p=[Hu(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,h,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+d:"",t.envMapPMREM?"#define ENVMAP_MAX_LOD "+t.envMapMaxLod+".0":"",t.envMapPMREM?"#define ENVMAP_SIZE "+t.envMapSize+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.diffuseRoughness?"#define USE_DIFFUSE_ROUGHNESS":"",t.diffuseRoughnessMap?"#define USE_DIFFUSE_ROUGHNESSMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.retroreflection?"#define USE_RETROREFLECTION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==yn?"#define TONE_MAPPING":"",t.toneMapping!==yn?ke.tonemapping_pars_fragment:"",t.toneMapping!==yn?F0("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",ke.colorspace_pars_fragment,D0("linearToOutputTexel",t.outputColorSpace),O0(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
|
||||
`),p=[Hu(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,h,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.envMap?"#define "+d:"",t.envMapPMREM?"#define ENVMAP_MAX_LOD "+t.envMapMaxLod+".0":"",t.envMapPMREM?"#define ENVMAP_SIZE "+t.envMapSize+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.diffuseRoughness?"#define USE_DIFFUSE_ROUGHNESS":"",t.diffuseRoughnessMap?"#define USE_DIFFUSE_ROUGHNESSMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.retroreflection?"#define USE_RETROREFLECTION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==vn?"#define TONE_MAPPING":"",t.toneMapping!==vn?ke.tonemapping_pars_fragment:"",t.toneMapping!==vn?F0("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",ke.colorspace_pars_fragment,D0("linearToOutputTexel",t.outputColorSpace),O0(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
|
||||
`].filter(tr).join(`
|
||||
`)),o=cc(o),o=zu(o,t),o=Vu(o,t),a=cc(a),a=zu(a,t),a=Vu(a,t),o=Gu(o),a=Gu(a),t.isRawShaderMaterial!==!0&&(m=`#version 300 es
|
||||
`,v=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(`
|
||||
`,y=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(`
|
||||
`)+`
|
||||
`+v,p=["#define varying in",t.glslVersion===Xl?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Xl?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
|
||||
`+y,p=["#define varying in",t.glslVersion===Xl?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===Xl?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
|
||||
`)+`
|
||||
`+p);let b=m+v+o,w=m+p+a,S=Ou(s,s.VERTEX_SHADER,b),A=Ou(s,s.FRAGMENT_SHADER,w);s.attachShader(g,S),s.attachShader(g,A),t.index0AttributeName!==void 0?s.bindAttribLocation(g,0,t.index0AttributeName):t.hasPositionAttribute===!0&&s.bindAttribLocation(g,0,"position"),s.linkProgram(g);function T(I){if(i.debug.checkShaderErrors){let N=s.getProgramInfoLog(g)||"",k=s.getShaderInfoLog(S)||"",$=s.getShaderInfoLog(A)||"",P=N.trim(),W=k.trim(),J=$.trim(),V=!0,te=!0;if(s.getProgramParameter(g,s.LINK_STATUS)===!1)if(V=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(s,g,S,A);else{let H=ku(s,S,"vertex"),Q=ku(s,A,"fragment");Pe("WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(g,s.VALIDATE_STATUS)+`
|
||||
`+p);let b=m+y+o,w=m+p+a,S=Ou(s,s.VERTEX_SHADER,b),A=Ou(s,s.FRAGMENT_SHADER,w);s.attachShader(g,S),s.attachShader(g,A),t.index0AttributeName!==void 0?s.bindAttribLocation(g,0,t.index0AttributeName):t.hasPositionAttribute===!0&&s.bindAttribLocation(g,0,"position"),s.linkProgram(g);function T(I){if(i.debug.checkShaderErrors){let N=s.getProgramInfoLog(g)||"",k=s.getShaderInfoLog(S)||"",$=s.getShaderInfoLog(A)||"",P=N.trim(),W=k.trim(),J=$.trim(),V=!0,te=!0;if(s.getProgramParameter(g,s.LINK_STATUS)===!1)if(V=!1,typeof i.debug.onShaderError=="function")i.debug.onShaderError(s,g,S,A);else{let H=ku(s,S,"vertex"),j=ku(s,A,"fragment");Pe("WebGLProgram: Shader Error "+s.getError()+" - VALIDATE_STATUS "+s.getProgramParameter(g,s.VALIDATE_STATUS)+`
|
||||
|
||||
Material Name: `+I.name+`
|
||||
Material Type: `+I.type+`
|
||||
|
||||
Program Info Log: `+P+`
|
||||
`+H+`
|
||||
`+Q)}else P!==""?Re("WebGLProgram: Program Info Log:",P):(W===""||J==="")&&(te=!1);te&&(I.diagnostics={runnable:V,programLog:P,vertexShader:{log:W,prefix:v},fragmentShader:{log:J,prefix:p}})}s.deleteShader(S),s.deleteShader(A),_=new is(s,g),M=z0(s,g)}let _;this.getUniforms=function(){return _===void 0&&T(this),_};let M;this.getAttributes=function(){return M===void 0&&T(this),M};let U=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return U===!1&&(U=s.getProgramParameter(g,P0)),U},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=I0++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=S,this.fragmentShader=A,this}var Q0=0,hc=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,n){let s=this._getShaderCacheForMaterial(e);return s.has(t)===!1&&(s.add(t),t.usedTimes++),s.has(n)===!1&&(s.add(n),n.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new uc(e),t.set(e,n)),n}},uc=class{constructor(e){this.id=Q0++,this.code=e,this.usedTimes=0}};function j0(i){return i===ni||i===Ks||i===Qs}function e_(i,e,t,n,s,r){let o=new qi,a=new hc,l=new Set,c=[],u=new Map,d=n.logarithmicDepthBuffer,f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function h(_){return l.add(_),_===0?"uv":`uv${_}`}function g(_,M,U,I,N,k){let $=I.fog,P=N.geometry,W=_.isMeshStandardMaterial||_.isMeshLambertMaterial||_.isMeshPhongMaterial?I.environment:null,J=_.isMeshStandardMaterial||_.isMeshLambertMaterial&&!_.envMap||_.isMeshPhongMaterial&&!_.envMap,V=e.get(_.envMap||W,J),te=f[_.type],H=n.precision;_.precision!==null&&(H=n.getMaxPrecision(_.precision),H!==_.precision&&Re("WebGLProgram.getParameters:",_.precision,"not supported, using",H,"instead."));let Q=P.morphAttributes.position||P.morphAttributes.normal||P.morphAttributes.color,j=Q!==void 0?Q.length:0,Se=0;P.morphAttributes.position!==void 0&&(Se=1),P.morphAttributes.normal!==void 0&&(Se=2),P.morphAttributes.color!==void 0&&(Se=3);let De,Y,me,ve;if(te){let fe=Sn[te];De=fe.vertexShader,Y=fe.fragmentShader}else{De=_.vertexShader,Y=_.fragmentShader;let fe=a.getVertexShaderStage(_),Ke=a.getFragmentShaderStage(_);a.update(_,fe,Ke),me=fe.id,ve=Ke.id}let Te=i.getRenderTarget(),ge=i.state.buffers.depth.getReversed(),Fe=N.isInstancedMesh===!0,ut=N.isBatchedMesh===!0,Ce=!!_.map,Je=!!_.matcap,et=!!V,Ve=et&&V.isPMREMTexture===!0,Tt=!!_.aoMap,mt=!!_.lightMap,Bt=!!_.bumpMap&&_.wireframe===!1,at=!!_.normalMap,dn=!!_.displacementMap,vt=!!_.emissiveMap,Zt=!!_.metalnessMap,Jt=!!_.roughnessMap,Kt=_.anisotropy>0,L=_.clearcoat>0,Qt=_.diffuseRoughness>0,st=_.dispersion>0,rt=_.retroreflectivity>0,de=_.iridescence>0,gt=_.sheen>0,Ae=_.transmission>0,Ne=Kt&&!!_.anisotropyMap,E=L&&!!_.clearcoatMap,x=L&&!!_.clearcoatNormalMap,F=L&&!!_.clearcoatRoughnessMap,ee=Qt&&!!_.diffuseRoughnessMap,K=de&&!!_.iridescenceMap,re=de&&!!_.iridescenceThicknessMap,he=gt&&!!_.sheenColorMap,X=gt&&!!_.sheenRoughnessMap,q=!!_.specularMap,ae=!!_.specularColorMap,R=!!_.specularIntensityMap,Z=Ae&&!!_.transmissionMap,G=Ae&&!!_.thicknessMap,le=!!_.gradientMap,ie=!!_.alphaMap,oe=_.alphaTest>0,we=!!_.alphaHash,Be=!!_.extensions,ne=yn;_.toneMapped&&(Te===null||Te.isXRRenderTarget===!0)&&(ne=i.toneMapping);let Ee=Ve?V.isCompressedCubeTexture?V.image[0].mipmaps:V.mipmaps:null,Oe={shaderID:te,shaderType:_.type,shaderName:_.name,vertexShader:De,fragmentShader:Y,defines:_.defines,customVertexShaderID:me,customFragmentShaderID:ve,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:H,batching:ut,batchingColor:ut&&N._colorsTexture!==null,instancing:Fe,instancingColor:Fe&&N.instanceColor!==null,instancingMorph:Fe&&N.morphTexture!==null,outputColorSpace:Te===null?i.outputColorSpace:Te.isXRRenderTarget===!0?Te.texture.colorSpace:We.workingColorSpace,alphaToCoverage:!!_.alphaToCoverage,map:Ce,matcap:Je,envMap:et,envMapMode:et&&V.mapping,envMapPMREM:Ve,envMapMaxLod:Ve?Ee.length-1:null,envMapSize:Ve?Ee[0].width:null,aoMap:Tt,lightMap:mt,bumpMap:Bt,normalMap:at,displacementMap:dn,emissiveMap:vt,normalMap
Line truncated
|
||||
`+j)}else P!==""?Re("WebGLProgram: Program Info Log:",P):(W===""||J==="")&&(te=!1);te&&(I.diagnostics={runnable:V,programLog:P,vertexShader:{log:W,prefix:y},fragmentShader:{log:J,prefix:p}})}s.deleteShader(S),s.deleteShader(A),_=new is(s,g),M=z0(s,g)}let _;this.getUniforms=function(){return _===void 0&&T(this),_};let M;this.getAttributes=function(){return M===void 0&&T(this),M};let U=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return U===!1&&(U=s.getProgramParameter(g,P0)),U},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=I0++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=S,this.fragmentShader=A,this}var j0=0,hc=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,n){let s=this._getShaderCacheForMaterial(e);return s.has(t)===!1&&(s.add(t),t.usedTimes++),s.has(n)===!1&&(s.add(n),n.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new uc(e),t.set(e,n)),n}},uc=class{constructor(e){this.id=j0++,this.code=e,this.usedTimes=0}};function Q0(i){return i===ni||i===Ks||i===js}function e_(i,e,t,n,s,r){let o=new qi,a=new hc,l=new Set,c=[],u=new Map,d=n.logarithmicDepthBuffer,f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function h(_){return l.add(_),_===0?"uv":`uv${_}`}function g(_,M,U,I,N,k){let $=I.fog,P=N.geometry,W=_.isMeshStandardMaterial||_.isMeshLambertMaterial||_.isMeshPhongMaterial?I.environment:null,J=_.isMeshStandardMaterial||_.isMeshLambertMaterial&&!_.envMap||_.isMeshPhongMaterial&&!_.envMap,V=e.get(_.envMap||W,J),te=f[_.type],H=n.precision;_.precision!==null&&(H=n.getMaxPrecision(_.precision),H!==_.precision&&Re("WebGLProgram.getParameters:",_.precision,"not supported, using",H,"instead."));let j=P.morphAttributes.position||P.morphAttributes.normal||P.morphAttributes.color,Q=j!==void 0?j.length:0,Se=0;P.morphAttributes.position!==void 0&&(Se=1),P.morphAttributes.normal!==void 0&&(Se=2),P.morphAttributes.color!==void 0&&(Se=3);let De,Y,me,ye;if(te){let fe=Sn[te];De=fe.vertexShader,Y=fe.fragmentShader}else{De=_.vertexShader,Y=_.fragmentShader;let fe=a.getVertexShaderStage(_),Ke=a.getFragmentShaderStage(_);a.update(_,fe,Ke),me=fe.id,ye=Ke.id}let Te=i.getRenderTarget(),ge=i.state.buffers.depth.getReversed(),Fe=N.isInstancedMesh===!0,ut=N.isBatchedMesh===!0,Ce=!!_.map,Je=!!_.matcap,et=!!V,Ve=et&&V.isPMREMTexture===!0,Tt=!!_.aoMap,mt=!!_.lightMap,Bt=!!_.bumpMap&&_.wireframe===!1,at=!!_.normalMap,dn=!!_.displacementMap,yt=!!_.emissiveMap,Zt=!!_.metalnessMap,Jt=!!_.roughnessMap,Kt=_.anisotropy>0,L=_.clearcoat>0,jt=_.diffuseRoughness>0,st=_.dispersion>0,rt=_.retroreflectivity>0,de=_.iridescence>0,gt=_.sheen>0,Ae=_.transmission>0,Ne=Kt&&!!_.anisotropyMap,E=L&&!!_.clearcoatMap,x=L&&!!_.clearcoatNormalMap,F=L&&!!_.clearcoatRoughnessMap,ee=jt&&!!_.diffuseRoughnessMap,K=de&&!!_.iridescenceMap,re=de&&!!_.iridescenceThicknessMap,he=gt&&!!_.sheenColorMap,X=gt&&!!_.sheenRoughnessMap,q=!!_.specularMap,ae=!!_.specularColorMap,R=!!_.specularIntensityMap,Z=Ae&&!!_.transmissionMap,G=Ae&&!!_.thicknessMap,le=!!_.gradientMap,ie=!!_.alphaMap,oe=_.alphaTest>0,we=!!_.alphaHash,Be=!!_.extensions,ne=vn;_.toneMapped&&(Te===null||Te.isXRRenderTarget===!0)&&(ne=i.toneMapping);let Ee=Ve?V.isCompressedCubeTexture?V.image[0].mipmaps:V.mipmaps:null,Oe={shaderID:te,shaderType:_.type,shaderName:_.name,vertexShader:De,fragmentShader:Y,defines:_.defines,customVertexShaderID:me,customFragmentShaderID:ye,isRawShaderMaterial:_.isRawShaderMaterial===!0,glslVersion:_.glslVersion,precision:H,batching:ut,batchingColor:ut&&N._colorsTexture!==null,instancing:Fe,instancingColor:Fe&&N.instanceColor!==null,instancingMorph:Fe&&N.morphTexture!==null,outputColorSpace:Te===null?i.outputColorSpace:Te.isXRRenderTarget===!0?Te.texture.colorSpace:We.workingColorSpace,alphaToCoverage:!!_.alphaToCoverage,map:Ce,matcap:Je,envMap:et,envMapMode:et&&V.mapping,envMapPMREM:Ve,envMapMaxLod:Ve?Ee.length-1:null,envMapSize:Ve?Ee[0].width:null,aoMap:Tt,lightMap:mt,bumpMap:Bt,normalMap:at,displacementMap:dn,emissiveMap:yt,normalMap
Line truncated
|
||||
gl_Position = vec4( position, 1.0 );
|
||||
}`,u_=`uniform sampler2D shadow_pass;
|
||||
uniform vec2 resolution;
|
||||
@@ -4201,12 +4201,12 @@ void main() {
|
||||
squared_mean = squared_mean / samples;
|
||||
float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
|
||||
gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
|
||||
}`,d_=[new B(1,0,0),new B(-1,0,0),new B(0,1,0),new B(0,-1,0),new B(0,0,1),new B(0,0,-1)],f_=[new B(0,-1,0),new B(0,-1,0),new B(0,0,1),new B(0,0,-1),new B(0,-1,0),new B(0,-1,0)],qu=new ot,er=new B,rc=new B;function p_(i,e,t){let n=new _i,s=new ze,r=new ze,o=new ht,a=new fo,l=new po,c={},u=t.maxTextureSize,d={[ti]:Ot,[Ot]:ti,[vn]:vn},f=new xn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ze},radius:{value:4}},vertexShader:h_,fragmentShader:u_}),h=f.clone();h.defines.HORIZONTAL_PASS=1;let g=new $t;g.setAttribute("position",new mn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let v=new Xt(g,f),p=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=$s;let m=this.type;this.render=function(T,_,M){if(p.enabled===!1||p.autoUpdate===!1&&p.needsUpdate===!1||T.length===0)return;this.type===Oh&&(Re("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=$s);let U=i.getRenderTarget(),I=i.getActiveCubeFace(),N=i.getActiveMipmapLevel(),k=i.state;k.setBlending(yi),k.buffers.depth.getReversed()===!0?k.buffers.color.setClear(0,0,0,0):k.buffers.color.setClear(1,1,1,1),k.buffers.depth.setTest(!0),k.setScissorTest(!1);let $=m!==this.type;$&&_.traverse(function(P){P.material&&(Array.isArray(P.material)?P.material.forEach(W=>W.needsUpdate=!0):P.material.needsUpdate=!0)});for(let P=0,W=T.length;P<W;P++){let J=T[P],V=J.shadow;if(V===void 0){Re("WebGLShadowMap:",J,"has no shadow.");continue}if(V.autoUpdate===!1&&V.needsUpdate===!1)continue;s.copy(V.mapSize);let te=V.getFrameExtents();s.multiply(te),r.copy(V.mapSize),(s.x>u||s.y>u)&&(s.x>u&&(r.x=Math.floor(u/te.x),s.x=r.x*te.x,V.mapSize.x=r.x),s.y>u&&(r.y=Math.floor(u/te.y),s.y=r.y*te.y,V.mapSize.y=r.y));let H=i.state.buffers.depth.getReversed();if(V.camera._reversedDepth=H,V.map===null||$===!0){if(V.map!==null&&(V.map.depthTexture!==null&&(V.map.depthTexture.dispose(),V.map.depthTexture=null),V.map.dispose()),this.type===ji){if(J.isPointLight){Re("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}V.map=new Ht(s.x,s.y,{format:ni,type:hn,minFilter:Ft,magFilter:Ft,generateMipmaps:!1}),V.map.texture.name=J.name+".shadowMap",V.map.depthTexture=new Nn(s.x,s.y,cn),V.map.depthTexture.name=J.name+".shadowMapDepth",V.map.depthTexture.format=Ln,V.map.depthTexture.compareFunction=null,V.map.depthTexture.minFilter=wt,V.map.depthTexture.magFilter=wt}else J.isPointLight?(V.map=new nr(s.x),V.map.depthTexture=new Ds(s.x,ln)):(V.map=new Ht(s.x,s.y),V.map.depthTexture=new Nn(s.x,s.y,ln)),V.map.depthTexture.name=J.name+".shadowMap",V.map.depthTexture.format=Ln,this.type===$s?(V.map.depthTexture.compareFunction=H?Wl:Hl,V.map.depthTexture.minFilter=Ft,V.map.depthTexture.magFilter=Ft):(V.map.depthTexture.compareFunction=null,V.map.depthTexture.minFilter=wt,V.map.depthTexture.magFilter=wt);V.camera.updateProjectionMatrix()}V.map.isWebGLCubeRenderTarget!==!0&&(V.map.width!==s.x||V.map.height!==s.y)&&V.map.setSize(s.x,s.y);let Q=V.map.isWebGLCubeRenderTarget?6:V.getViewportCount();J.isPointLight!==!0&&V.updateMatrices(J,M);let j=(V.camera.layers.mask&4294967294)!==0?V.camera.layers:M.layers;for(let Se=0;Se<Q;Se++){let De=V.getCamera(Se);if(J.isPointLight){let Y=V.camera,me=V.matrix,ve=J.distance||Y.far;ve!==Y.far&&(Y.far=ve,Y.updateProjectionMatrix()),er.setFromMatrixPosition(J.matrixWorld),Y.position.copy(er),rc.copy(Y.position),rc.add(d_[Se]),Y.up.copy(f_[Se]),Y.lookAt(rc),Y.updateMatrixWorld(),me.makeTranslation(-er.x,-er.y,-er.z),qu.multiplyMatrices(Y.projectionMatrix,Y.matrixWorldInverse),V._frustum.setFromProjectionMatrix(qu,Y.coordinateSystem,Y.reversedDepth)}if(V.map.isWebGLCubeRenderTarget)i.setRenderTarget(V.map,Se),i.clear();else{Se===0&&(i.setRenderTarget(V.map),i.clear());let Y=V.getViewport(Se);o.set(r.x*Y.x,r.y*Y.y,r.x*Y.z,r.y*Y.w),k.viewport(o)}n=V.getFrustum(Se),S(_,M,De,J,j,this.type)}V.isPointLightShadow!==!0&&this.type===ji&&b(V,M),V.needsUpdate=!1}m=this.type,p.needsUpdate=!1,i.setRenderTarget(U,I,N)};function b(T,_){let M=e.update(v);f.defines.VSM_SAMPLES!==T.blurSamples&&(f.defines.VSM_SAMPLES=T.blurSamples,h.defines.VSM_SAMPLES=T.blurSamples,f.needsUpdate=!0,h.needsUpdate=!0),T.mapPass===null?T.mapPass=new Ht(s.x,s.y,{format:ni,type:hn}):(T.mapPass.width!==T.map.width||T.mapPass.height!==T.map.height)&&T.mapPass.setSize(T.map.width,T.map.height),f.uniforms.shadow_pass.value=T.map.depthTexture,f.uniforms.resolution.value.set(T.map.width,T.map.height),f.uniforms.radius.value=T.radius,i.setRenderTarget(T.mapPass),i.clear(),i.renderBufferDirect(_,null,M,f,v,null),h.uniforms.shadow_pass.value=T.mapPass.texture,h.uniforms.resolution.value.set(T.map.width,T.map.height),h.uniforms.radius.value=T.radius,i.setRenderTarget(T.map),i.clear(),i.renderBufferDirect(_,null,M,h,v,null)}function w(T,_,M,U){let I=null,N=M.isPointLight===!0?T.customDistanceMaterial:T.customDepthMaterial;if(N!==void 0)I=N;else if(I=M.isPointLight===!0?l:a,i.localClipping
Line truncated
|
||||
}`,d_=[new B(1,0,0),new B(-1,0,0),new B(0,1,0),new B(0,-1,0),new B(0,0,1),new B(0,0,-1)],f_=[new B(0,-1,0),new B(0,-1,0),new B(0,0,1),new B(0,0,-1),new B(0,-1,0),new B(0,-1,0)],qu=new ot,er=new B,rc=new B;function p_(i,e,t){let n=new _i,s=new ze,r=new ze,o=new ht,a=new fo,l=new po,c={},u=t.maxTextureSize,d={[ti]:Ot,[Ot]:ti,[yn]:yn},f=new xn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ze},radius:{value:4}},vertexShader:h_,fragmentShader:u_}),h=f.clone();h.defines.HORIZONTAL_PASS=1;let g=new $t;g.setAttribute("position",new mn(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let y=new Xt(g,f),p=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=$s;let m=this.type;this.render=function(T,_,M){if(p.enabled===!1||p.autoUpdate===!1&&p.needsUpdate===!1||T.length===0)return;this.type===Oh&&(Re("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=$s);let U=i.getRenderTarget(),I=i.getActiveCubeFace(),N=i.getActiveMipmapLevel(),k=i.state;k.setBlending(vi),k.buffers.depth.getReversed()===!0?k.buffers.color.setClear(0,0,0,0):k.buffers.color.setClear(1,1,1,1),k.buffers.depth.setTest(!0),k.setScissorTest(!1);let $=m!==this.type;$&&_.traverse(function(P){P.material&&(Array.isArray(P.material)?P.material.forEach(W=>W.needsUpdate=!0):P.material.needsUpdate=!0)});for(let P=0,W=T.length;P<W;P++){let J=T[P],V=J.shadow;if(V===void 0){Re("WebGLShadowMap:",J,"has no shadow.");continue}if(V.autoUpdate===!1&&V.needsUpdate===!1)continue;s.copy(V.mapSize);let te=V.getFrameExtents();s.multiply(te),r.copy(V.mapSize),(s.x>u||s.y>u)&&(s.x>u&&(r.x=Math.floor(u/te.x),s.x=r.x*te.x,V.mapSize.x=r.x),s.y>u&&(r.y=Math.floor(u/te.y),s.y=r.y*te.y,V.mapSize.y=r.y));let H=i.state.buffers.depth.getReversed();if(V.camera._reversedDepth=H,V.map===null||$===!0){if(V.map!==null&&(V.map.depthTexture!==null&&(V.map.depthTexture.dispose(),V.map.depthTexture=null),V.map.dispose()),this.type===Qi){if(J.isPointLight){Re("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}V.map=new Ht(s.x,s.y,{format:ni,type:hn,minFilter:Ft,magFilter:Ft,generateMipmaps:!1}),V.map.texture.name=J.name+".shadowMap",V.map.depthTexture=new Dn(s.x,s.y,cn),V.map.depthTexture.name=J.name+".shadowMapDepth",V.map.depthTexture.format=Nn,V.map.depthTexture.compareFunction=null,V.map.depthTexture.minFilter=wt,V.map.depthTexture.magFilter=wt}else J.isPointLight?(V.map=new nr(s.x),V.map.depthTexture=new Ds(s.x,ln)):(V.map=new Ht(s.x,s.y),V.map.depthTexture=new Dn(s.x,s.y,ln)),V.map.depthTexture.name=J.name+".shadowMap",V.map.depthTexture.format=Nn,this.type===$s?(V.map.depthTexture.compareFunction=H?Wl:Hl,V.map.depthTexture.minFilter=Ft,V.map.depthTexture.magFilter=Ft):(V.map.depthTexture.compareFunction=null,V.map.depthTexture.minFilter=wt,V.map.depthTexture.magFilter=wt);V.camera.updateProjectionMatrix()}V.map.isWebGLCubeRenderTarget!==!0&&(V.map.width!==s.x||V.map.height!==s.y)&&V.map.setSize(s.x,s.y);let j=V.map.isWebGLCubeRenderTarget?6:V.getViewportCount();J.isPointLight!==!0&&V.updateMatrices(J,M);let Q=(V.camera.layers.mask&4294967294)!==0?V.camera.layers:M.layers;for(let Se=0;Se<j;Se++){let De=V.getCamera(Se);if(J.isPointLight){let Y=V.camera,me=V.matrix,ye=J.distance||Y.far;ye!==Y.far&&(Y.far=ye,Y.updateProjectionMatrix()),er.setFromMatrixPosition(J.matrixWorld),Y.position.copy(er),rc.copy(Y.position),rc.add(d_[Se]),Y.up.copy(f_[Se]),Y.lookAt(rc),Y.updateMatrixWorld(),me.makeTranslation(-er.x,-er.y,-er.z),qu.multiplyMatrices(Y.projectionMatrix,Y.matrixWorldInverse),V._frustum.setFromProjectionMatrix(qu,Y.coordinateSystem,Y.reversedDepth)}if(V.map.isWebGLCubeRenderTarget)i.setRenderTarget(V.map,Se),i.clear();else{Se===0&&(i.setRenderTarget(V.map),i.clear());let Y=V.getViewport(Se);o.set(r.x*Y.x,r.y*Y.y,r.x*Y.z,r.y*Y.w),k.viewport(o)}n=V.getFrustum(Se),S(_,M,De,J,Q,this.type)}V.isPointLightShadow!==!0&&this.type===Qi&&b(V,M),V.needsUpdate=!1}m=this.type,p.needsUpdate=!1,i.setRenderTarget(U,I,N)};function b(T,_){let M=e.update(y);f.defines.VSM_SAMPLES!==T.blurSamples&&(f.defines.VSM_SAMPLES=T.blurSamples,h.defines.VSM_SAMPLES=T.blurSamples,f.needsUpdate=!0,h.needsUpdate=!0),T.mapPass===null?T.mapPass=new Ht(s.x,s.y,{format:ni,type:hn}):(T.mapPass.width!==T.map.width||T.mapPass.height!==T.map.height)&&T.mapPass.setSize(T.map.width,T.map.height),f.uniforms.shadow_pass.value=T.map.depthTexture,f.uniforms.resolution.value.set(T.map.width,T.map.height),f.uniforms.radius.value=T.radius,i.setRenderTarget(T.mapPass),i.clear(),i.renderBufferDirect(_,null,M,f,y,null),h.uniforms.shadow_pass.value=T.mapPass.texture,h.uniforms.resolution.value.set(T.map.width,T.map.height),h.uniforms.radius.value=T.radius,i.setRenderTarget(T.map),i.clear(),i.renderBufferDirect(_,null,M,h,y,null)}function w(T,_,M,U){let I=null,N=M.isPointLight===!0?T.customDistanceMaterial:T.customDepthMaterial;if(N!==void 0)I=N;else if(I=M.isPointLight===!0?l:a,i.localClipping
Line truncated
|
||||
void main() {
|
||||
|
||||
gl_Position = vec4( position, 1.0 );
|
||||
|
||||
}`,v_=`
|
||||
}`,y_=`
|
||||
uniform sampler2DArray depthColor;
|
||||
uniform float depthWidth;
|
||||
uniform float depthHeight;
|
||||
@@ -4225,10 +4225,10 @@ void main() {
|
||||
|
||||
}
|
||||
|
||||
}`,dc=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new Us(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new xn({vertexShader:x_,fragmentShader:v_,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Xt(new zs(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},fc=class extends gn{constructor(e,t){super();let n=this,s=null,r=1,o=null,a="local-floor",l=1,c=null,u=null,d=null,f=null,h=null,g=null,v=typeof XRWebGLBinding<"u",p=new dc,m={},b=t.getContextAttributes(),w=null,S=null,A=[],T=[],_=new ze,M=null,U=null,I=new Ut;I.viewport=new ht;let N=new Ut;N.viewport=new ht;let k=[I,N],$=new To,P=null,W=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Y){let me=A[Y];return me===void 0&&(me=new Yi,A[Y]=me),me.getTargetRaySpace()},this.getControllerGrip=function(Y){let me=A[Y];return me===void 0&&(me=new Yi,A[Y]=me),me.getGripSpace()},this.getHand=function(Y){let me=A[Y];return me===void 0&&(me=new Yi,A[Y]=me),me.getHandSpace()};function J(Y){let me=T.indexOf(Y.inputSource);if(me===-1)return;let ve=A[me];ve!==void 0&&(ve.update(Y.inputSource,Y.frame,c||o),ve.dispatchEvent({type:Y.type,data:Y.inputSource}))}function V(){s.removeEventListener("select",J),s.removeEventListener("selectstart",J),s.removeEventListener("selectend",J),s.removeEventListener("squeeze",J),s.removeEventListener("squeezestart",J),s.removeEventListener("squeezeend",J),s.removeEventListener("end",V),s.removeEventListener("inputsourceschange",te);for(let Y=0;Y<A.length;Y++){let me=T[Y];me!==null&&(T[Y]=null,A[Y].disconnect(me))}P=null,W=null,p.reset();for(let Y in m)delete m[Y];if(e.setRenderTarget(w),h=null,f=null,d=null,s=null,S=null,De.stop(),n.isPresenting=!1,e.setPixelRatio(M),e.setSize(_.width,_.height,!1),U!==null){let Y=U.camera;Y.fov=U.fov,Y.zoom=U.zoom,Y.updateProjectionMatrix(),U=null}n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Y){r=Y,n.isPresenting===!0&&Re("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Y){a=Y,n.isPresenting===!0&&Re("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||o},this.setReferenceSpace=function(Y){c=Y},this.getBaseLayer=function(){return f!==null?f:h},this.getBinding=function(){return d===null&&v&&(d=new XRWebGLBinding(s,t)),d},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(Y){if(s=Y,s!==null){if(w=e.getRenderTarget(),s.addEventListener("select",J),s.addEventListener("selectstart",J),s.addEventListener("selectend",J),s.addEventListener("squeeze",J),s.addEventListener("squeezestart",J),s.addEventListener("squeezeend",J),s.addEventListener("end",V),s.addEventListener("inputsourceschange",te),b.xrCompatible!==!0&&await t.makeXRCompatible(),M=e.getPixelRatio(),e.getSize(_),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let ve=null,Te=null,ge=null;b.depth&&(ge=b.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,ve=b.stencil?Un:Ln,Te=b.stencil?Mi:ln);let Fe={colorFormat:t.RGBA8,depthFormat:ge,scaleFactor:r};d=this.getBinding(),f=d.createProjectionLayer(Fe),s.updateRenderState({layers:[f]}),e.setPixelRatio(1),e.setSize(f.textureWidth,f.textureHeight,!1),S=new Ht(f.textureWidth,f.textureHeight,{format:un,type:Yt,depthTexture:new Nn(f.textureWidth,f.textureHeight,Te,void 0,void 0,void 0,void 0,void 0,void 0,ve),stencilBuffer:b.stencil,colorSpace:e.outputColorSpace,samples:b.antialias?4:0,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1,storeMultisampledDepthBuffer:f.ignoreDepthValues===!1,storeMultisampledStencilBuffer:f.ignoreDepthValues===!1})}else{let ve={antialias:b.antialias,alpha:!0,depth:b.depth,stencil:b.stencil,framebufferScaleFactor:r};h=new XRWebGLLayer(s,t,ve),s.updateRenderState({baseLayer:h}),e.setPixelRatio(1),e.setSize(h.framebufferWidth,h.framebufferHeight,!1),S=new Ht(h.framebufferWidth,h.framebufferHeight,{format:un,type:Yt,colorSpace:e.outputColorSpace,stencilBuffer:b.stencil,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1,storeMultisampledDepthBuffer:h.ignoreDepthValues===!1,storeMultisampledStencilBuffer:h.ignoreDepthValues===!1})}S.isXRRenderTarget=!0,this.setFoveation(l),c=null,o=await s.requestReferenceSpace(a),De.setContext(s),De.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return p.getDepthTexture()};function te(Y){for(let me=0;me<Y.removed.length;me++){let ve=Y.removed[
Line truncated
|
||||
}`,dc=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new Us(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new xn({vertexShader:x_,fragmentShader:y_,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Xt(new zs(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},fc=class extends gn{constructor(e,t){super();let n=this,s=null,r=1,o=null,a="local-floor",l=1,c=null,u=null,d=null,f=null,h=null,g=null,y=typeof XRWebGLBinding<"u",p=new dc,m={},b=t.getContextAttributes(),w=null,S=null,A=[],T=[],_=new ze,M=null,U=null,I=new Ut;I.viewport=new ht;let N=new Ut;N.viewport=new ht;let k=[I,N],$=new To,P=null,W=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Y){let me=A[Y];return me===void 0&&(me=new Yi,A[Y]=me),me.getTargetRaySpace()},this.getControllerGrip=function(Y){let me=A[Y];return me===void 0&&(me=new Yi,A[Y]=me),me.getGripSpace()},this.getHand=function(Y){let me=A[Y];return me===void 0&&(me=new Yi,A[Y]=me),me.getHandSpace()};function J(Y){let me=T.indexOf(Y.inputSource);if(me===-1)return;let ye=A[me];ye!==void 0&&(ye.update(Y.inputSource,Y.frame,c||o),ye.dispatchEvent({type:Y.type,data:Y.inputSource}))}function V(){s.removeEventListener("select",J),s.removeEventListener("selectstart",J),s.removeEventListener("selectend",J),s.removeEventListener("squeeze",J),s.removeEventListener("squeezestart",J),s.removeEventListener("squeezeend",J),s.removeEventListener("end",V),s.removeEventListener("inputsourceschange",te);for(let Y=0;Y<A.length;Y++){let me=T[Y];me!==null&&(T[Y]=null,A[Y].disconnect(me))}P=null,W=null,p.reset();for(let Y in m)delete m[Y];if(e.setRenderTarget(w),h=null,f=null,d=null,s=null,S=null,De.stop(),n.isPresenting=!1,e.setPixelRatio(M),e.setSize(_.width,_.height,!1),U!==null){let Y=U.camera;Y.fov=U.fov,Y.zoom=U.zoom,Y.updateProjectionMatrix(),U=null}n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Y){r=Y,n.isPresenting===!0&&Re("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Y){a=Y,n.isPresenting===!0&&Re("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||o},this.setReferenceSpace=function(Y){c=Y},this.getBaseLayer=function(){return f!==null?f:h},this.getBinding=function(){return d===null&&y&&(d=new XRWebGLBinding(s,t)),d},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(Y){if(s=Y,s!==null){if(w=e.getRenderTarget(),s.addEventListener("select",J),s.addEventListener("selectstart",J),s.addEventListener("selectend",J),s.addEventListener("squeeze",J),s.addEventListener("squeezestart",J),s.addEventListener("squeezeend",J),s.addEventListener("end",V),s.addEventListener("inputsourceschange",te),b.xrCompatible!==!0&&await t.makeXRCompatible(),M=e.getPixelRatio(),e.getSize(_),y&&"createProjectionLayer"in XRWebGLBinding.prototype){let ye=null,Te=null,ge=null;b.depth&&(ge=b.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,ye=b.stencil?Fn:Nn,Te=b.stencil?Mi:ln);let Fe={colorFormat:t.RGBA8,depthFormat:ge,scaleFactor:r};d=this.getBinding(),f=d.createProjectionLayer(Fe),s.updateRenderState({layers:[f]}),e.setPixelRatio(1),e.setSize(f.textureWidth,f.textureHeight,!1),S=new Ht(f.textureWidth,f.textureHeight,{format:un,type:Yt,depthTexture:new Dn(f.textureWidth,f.textureHeight,Te,void 0,void 0,void 0,void 0,void 0,void 0,ye),stencilBuffer:b.stencil,colorSpace:e.outputColorSpace,samples:b.antialias?4:0,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1,storeMultisampledDepthBuffer:f.ignoreDepthValues===!1,storeMultisampledStencilBuffer:f.ignoreDepthValues===!1})}else{let ye={antialias:b.antialias,alpha:!0,depth:b.depth,stencil:b.stencil,framebufferScaleFactor:r};h=new XRWebGLLayer(s,t,ye),s.updateRenderState({baseLayer:h}),e.setPixelRatio(1),e.setSize(h.framebufferWidth,h.framebufferHeight,!1),S=new Ht(h.framebufferWidth,h.framebufferHeight,{format:un,type:Yt,colorSpace:e.outputColorSpace,stencilBuffer:b.stencil,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1,storeMultisampledDepthBuffer:h.ignoreDepthValues===!1,storeMultisampledStencilBuffer:h.ignoreDepthValues===!1})}S.isXRRenderTarget=!0,this.setFoveation(l),c=null,o=await s.requestReferenceSpace(a),De.setContext(s),De.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return p.getDepthTexture()};function te(Y){for(let me=0;me<Y.removed.length;me++){let ye=Y.removed[
Line truncated
|
||||
>${e}
|
||||
<input type="number" .value=${String(t)} step=${s.step??.5} min=${s.min??Qe} max=${s.max??Qe} @change=${r=>{let o=Number(r.target.value);Number.isFinite(o)&&n(o)}} />
|
||||
</label>`}text(e,t,n,s={}){return qe`<label class="field wide" title=${s.hint??Qe}
|
||||
<input type="number" .value=${String(t)} step=${s.step??.5} min=${s.min??je} max=${s.max??je} @change=${r=>{let o=Number(r.target.value);Number.isFinite(o)&&n(o)}} />
|
||||
</label>`}text(e,t,n,s={}){return qe`<label class="field wide" title=${s.hint??je}
|
||||
>${e}
|
||||
<input type="text" .value=${t} maxlength=${s.max??80} @change=${r=>n(r.target.value.trim())} />
|
||||
</label>`}check(e,t,n){return qe`<label class="check wide"><input type="checkbox" .checked=${t} @change=${s=>n(s.target.checked)} /> ${e}</label>`}select(e,t,n,s){return qe`<label class="field"
|
||||
@@ -4244,7 +4244,7 @@ void main() {
|
||||
>
|
||||
${a.map(([l,c])=>qe`<option value=${l} ?selected=${l===o}>${c}</option>`)}
|
||||
</select>
|
||||
${r?qe`<input type="color" .value=${t} @input=${l=>n(l.target.value)} />`:Qe}
|
||||
${r?qe`<input type="color" .value=${t} @input=${l=>n(l.target.value)} />`:je}
|
||||
</span>
|
||||
</label>`}render(){let e=ih(this._pack),t=sh(e);return qe`<header>
|
||||
<div>
|
||||
@@ -4257,7 +4257,7 @@ void main() {
|
||||
<button @click=${()=>this.save()} ?disabled=${t.length>0}>${se("save")}</button>
|
||||
<button class="primary" @click=${()=>this._dialog="submit"}>${se("submit")}</button>
|
||||
</header>
|
||||
${this._note?qe`<div class="note" @click=${()=>this._note=null}>${this._note}</div>`:Qe}
|
||||
${this._note?qe`<div class="note" @click=${()=>this._note=null}>${this._note}</div>`:je}
|
||||
<main>
|
||||
<aside class="left">${this.renderPack()} ${this.renderItems()} ${this.renderItem()}</aside>
|
||||
<section class="stage">
|
||||
@@ -4275,7 +4275,7 @@ void main() {
|
||||
<aside class="right">${this.renderParts()} ${this.renderPart()}</aside>
|
||||
</main>
|
||||
<footer>${this.renderProblems(e)}</footer>
|
||||
${this._dialog==="submit"?this.renderSubmit(t):Qe}`}renderPack(){let e=this._pack;return qe`<h2>${se("pack")}</h2>
|
||||
${this._dialog==="submit"?this.renderSubmit(t):je}`}renderPack(){let e=this._pack;return qe`<h2>${se("pack")}</h2>
|
||||
<div class="form">
|
||||
${this.text(se("pack_name"),e.name,t=>this.change(n=>n.name=t))}
|
||||
${this.text(se("publisher"),e.publisher,t=>this.change(n=>n.publisher=t))}
|
||||
@@ -4287,7 +4287,7 @@ void main() {
|
||||
</label>
|
||||
</div>`}renderItems(){return qe`<h2>${se("items")}</h2>
|
||||
<div class="list">
|
||||
${this._pack.items.map((e,t)=>qe`<button class="entry" aria-pressed=${t===this._item} @click=${()=>(this._item=t,this._part=-1)}>${e.name[ya]||e.name.en||e.id}</button>`)}
|
||||
${this._pack.items.map((e,t)=>qe`<button class="entry" aria-pressed=${t===this._item} @click=${()=>(this._item=t,this._part=-1)}>${e.name[va]||e.name.en||e.id}</button>`)}
|
||||
</div>
|
||||
<div class="row">
|
||||
<select
|
||||
@@ -4305,9 +4305,9 @@ void main() {
|
||||
${this.text(se("item_id"),e.id,o=>this.changeItem(a=>a.id=o.toLowerCase()),{max:40})}
|
||||
${this.num(se("width"),ls(t*100),r(0),{step:1,min:1})} ${this.num(se("depth"),ls(n*100),r(1),{step:1,min:1})}
|
||||
${this.num(se("height"),ls(s*100),r(2),{step:1,min:1})}
|
||||
${this.select(se("mount"),e.mount??"floor",jc.map(o=>[o,se(`mount_${o}`)]),o=>this.changeItem(a=>a.mount=o==="floor"?void 0:o))}
|
||||
${e.mount==="wall"?this.num(se("wall_y"),ls((e.wall_y??1)*100),o=>this.changeItem(a=>a.wall_y=Math.min(3,Math.max(0,o/100))),{step:1,min:0}):Qe}
|
||||
${this.select(se("light"),e.light??"",[["",se("light_none")],...Qc.map(o=>[o,o])],o=>this.changeItem(a=>a.light=o||void 0))}
|
||||
${this.select(se("mount"),e.mount??"floor",Qc.map(o=>[o,se(`mount_${o}`)]),o=>this.changeItem(a=>a.mount=o==="floor"?void 0:o))}
|
||||
${e.mount==="wall"?this.num(se("wall_y"),ls((e.wall_y??1)*100),o=>this.changeItem(a=>a.wall_y=Math.min(3,Math.max(0,o/100))),{step:1,min:0}):je}
|
||||
${this.select(se("light"),e.light??"",[["",se("light_none")],...jc.map(o=>[o,o])],o=>this.changeItem(a=>a.light=o||void 0))}
|
||||
${this.check(se("electric"),!!e.electric,o=>this.changeItem(a=>a.electric=o||void 0))}
|
||||
${this.check(se("surface"),!!e.surface,o=>this.changeItem(a=>a.surface=o||void 0))}
|
||||
${this.check(se("stretch"),!!e.stretch,o=>this.changeItem(a=>a.stretch=o||void 0))}
|
||||
@@ -4321,11 +4321,11 @@ void main() {
|
||||
${this.num(se("x"),t.x,n("x"))} ${this.num(se("z"),t.z,n("z"))} ${this.num(se("y"),t.y,n("y"))} ${this.num(se("w"),t.w,n("w"),{min:.1})}
|
||||
${this.num(se("d"),t.d,n("d"),{min:.1})} ${this.num(se("h"),t.h,n("h"),{min:.1})}
|
||||
${this.num(se("rot"),e.rot??0,r=>this.changePart(o=>o.rot=r?Math.max(-360,Math.min(360,r)):void 0),{step:5})}
|
||||
${e.shape==="cyl"?this.select(se("axis"),e.axis??"y",["y","x","z"].map(r=>[r,se(`axis_${r}`)]),r=>this.changePart(o=>o.axis=r==="y"?void 0:r)):Qe}
|
||||
${e.shape==="cyl"?this.select(se("axis"),e.axis??"y",["y","x","z"].map(r=>[r,se(`axis_${r}`)]),r=>this.changePart(o=>o.axis=r==="y"?void 0:r)):je}
|
||||
${e.shape==="loft"?qe`${this.num(se("top_w"),s(e.tw,e.w),r=>this.changePart(o=>o.tw=Math.min(1,Math.max(.001,r/100))),{step:1})}
|
||||
${this.num(se("top_d"),s(e.td,e.d),r=>this.changePart(o=>o.td=Math.min(1,Math.max(.001,r/100))),{step:1})}
|
||||
${this.num(se("top_x"),s(e.tx,e.x),r=>this.changePart(o=>o.tx=Math.min(.5,Math.max(-.5,r/100))),{step:1})}`:Qe}
|
||||
${e.shape==="sweep"?this.renderStations(e):Qe}
|
||||
${this.num(se("top_x"),s(e.tx,e.x),r=>this.changePart(o=>o.tx=Math.min(.5,Math.max(-.5,r/100))),{step:1})}`:je}
|
||||
${e.shape==="sweep"?this.renderStations(e):je}
|
||||
${this.colorField(se("color"),e.color,r=>this.changePart(o=>o.color=r??"body"))}
|
||||
${this.colorField(se("top"),e.top,r=>this.changePart(o=>o.top=r),!0)}
|
||||
${this.select(se("edges"),e.edges===!0?"soft":e.edges?e.edges:"none",[["none",se("edges_none")],["soft",se("edges_soft")],["glow",se("edges_glow")],["faint",se("edges_faint")]],r=>this.changePart(o=>o.edges=r==="none"?void 0:r==="soft"?!0:r))}
|
||||
@@ -4349,7 +4349,7 @@ void main() {
|
||||
>
|
||||
${se("add_station")}
|
||||
</button>
|
||||
</div>`}renderProblems(e){if(!e.length)return qe`<p class="ok">✓ ${se("ok")}</p>`;let t=n=>{if(n==="pack")return se("where_pack");let[,s,,r]=n.match(/item:(\d+)(\/part:(\d+))?/)??[],o=this._pack.items[Number(s)],a=o?o.name[ya]||o.id:"?";return r===void 0?a:`${a} \xB7 ${se("part")} ${Number(r)+1}`};return qe`<h2>${se("check")}</h2>
|
||||
</div>`}renderProblems(e){if(!e.length)return qe`<p class="ok">✓ ${se("ok")}</p>`;let t=n=>{if(n==="pack")return se("where_pack");let[,s,,r]=n.match(/item:(\d+)(\/part:(\d+))?/)??[],o=this._pack.items[Number(s)],a=o?o.name[va]||o.id:"?";return r===void 0?a:`${a} \xB7 ${se("part")} ${Number(r)+1}`};return qe`<h2>${se("check")}</h2>
|
||||
<ul>
|
||||
${e.map(n=>qe`<li class=${n.key==="outside"?"warn":"error"}><b>${t(n.where)}</b>: ${se(n.key,n.vars)}</li>`)}
|
||||
</ul>`}renderSubmit(e){return qe`<div class="dialog" role="dialog" aria-modal="true">
|
||||
@@ -4620,7 +4620,7 @@ void main() {
|
||||
border: 0;
|
||||
}
|
||||
}
|
||||
`};customElements.define("nf-builder",yc);export{yc as NfBuilder};
|
||||
`};customElements.define("nf-builder",vc);export{vc as NfBuilder};
|
||||
/*! Bundled license information:
|
||||
|
||||
@lit/reactive-element/css-tag.js:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
|
||||
var m={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",fr:"6312d0f61ebf",hu:"27ba348531dc",it:"1b705e76dd00",nb:"c5ea24fb9ef6",nl:"b64142c67c2e",pl:"8527a4930402",pt:"31857a2d2277",ro:"e3cb5f449f0f",sk:"320611594db0",sl:"8071691ceda3",sv:"711b911ec8da",tr:"7c83ce1c3372",zh:"50518d9f494e"};var M=globalThis,N=M.ShadowRoot&&(M.ShadyCSS===void 0||M.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,U=Symbol(),pe=new WeakMap,R=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==U)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(N&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=pe.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&pe.set(t,e))}return e}toString(){return this.cssText}},fe=i=>new R(typeof i=="string"?i:i+"",void 0,U),j=(i,...e)=>{let t=i.length===1?i[0]:e.reduce((n,r,o)=>n+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+i[o+1],i[0]);return new R(t,i,U)},ge=(i,e)=>{if(N)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),r=M.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}},q=N?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return fe(t)})(i):i;var{is:Ge,defineProperty:Oe,getOwnPropertyDescriptor:Ie,getOwnPropertyNames:Ze,getOwnPropertySymbols:Ve,getPrototypeOf:Ue}=Object,C=globalThis,be=C.trustedTypes,je=be?be.emptyScript:"",qe=C.reactiveElementPolyfillSupport,F=(i,e)=>i,J={toAttribute(i,e){switch(e){case Boolean:i=i?je:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},ke=(i,e)=>!Ge(i,e),we={attribute:!0,type:String,converter:J,reflect:!1,useDefault:!1,hasChanged:ke};Symbol.metadata??=Symbol("metadata"),C.litPropertyMetadata??=new WeakMap;var b=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=we){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){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Oe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:o}=Ie(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){let s=r?.call(this);o?.call(this,a),this.requestUpdate(e,s,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??we}static _$Ei(){if(this.hasOwnProperty(F("elementProperties")))return;let e=Ue(this);e.finalize(),e.l!==void 0&&(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"))){let t=this.properties,n=[...Ze(t),...Ve(t)];for(let r of n)this.createProperty(r,t[r])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,r]of t)this.elementProperties.set(n,r)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let r=this._$Eu(t,n);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let r of n)t.unshift(q(r))}else e!==void 0&&t.push(q(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?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),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ge(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.Line truncated
|
||||
\f\r]`,x=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Se=/-->/g,Ae=/>/g,S=RegExp(`>|${X}(?:([^\\s"'>=/]+)(${X}*=${X}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),De=/'/g,ze=/"/g,Fe=/^(?:script|style|textarea|title)$/i,oe=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),l=oe(1),ut=oe(2),mt=oe(3),z=Symbol.for("lit-noChange"),d=Symbol.for("lit-nothing"),Ee=new WeakMap,A=D.createTreeWalker(D,129);function xe(i,e){if(!ie(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ye!==void 0?ye.createHTML(e):e}var Ye=(i,e)=>{let t=i.length-1,n=[],r,o=e===2?"<svg>":e===3?"<math>":"",a=x;for(let s=0;s<t;s++){let h=i[s],u,p,_=-1,g=0;for(;g<h.length&&(a.lastIndex=g,p=a.exec(h),p!==null);)g=a.lastIndex,a===x?p[1]==="!--"?a=Se:p[1]!==void 0?a=Ae:p[2]!==void 0?(Fe.test(p[2])&&(r=RegExp("</"+p[2],"g")),a=S):p[3]!==void 0&&(a=S):a===S?p[0]===">"?(a=r??x,_=-1):p[1]===void 0?_=-2:(_=a.lastIndex-p[2].length,u=p[1],a=p[3]===void 0?S:p[3]==='"'?ze:De):a===ze||a===De?a=S:a===Se||a===Ae?a=x:(a=S,r=void 0);let k=a===S&&i[s+1].startsWith("/>")?" ":"";o+=a===x?h+Je:_>=0?(n.push(u),h.slice(0,_)+Te+h.slice(_)+v+k):h+v+(_===-2?s:k)}return[xe(i,o+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]},B=class i{constructor({strings:e,_$litType$:t},n){let r;this.parts=[];let o=0,a=0,s=e.length-1,h=this.parts,[u,p]=Ye(e,t);if(this.el=i.createElement(u,n),A.currentNode=this.el.content,t===2||t===3){let _=this.el.content.firstChild;_.replaceWith(..._.childNodes)}for(;(r=A.nextNode())!==null&&h.length<s;){if(r.nodeType===1){if(r.hasAttributes())for(let _ of r.getAttributeNames())if(_.endsWith(Te)){let g=p[a++],k=r.getAttribute(_).split(v),$=/([.?@])?(.*)/.exec(g);h.push({type:1,index:o,name:$[2],strings:k,ctor:$[1]==="."?Q:$[1]==="?"?ee:$[1]==="@"?te:T}),r.removeAttribute(_)}else _.startsWith(v)&&(h.push({type:6,index:o}),r.removeAttribute(_));if(Fe.test(r.tagName)){let _=r.textContent.split(v),g=_.length-1;if(g>0){r.textContent=K?K.emptyScript:"";for(let k=0;k<g;k++)r.append(_[k],H()),A.nextNode(),h.push({type:2,index:++o});r.append(_[g],H())}}}else if(r.nodeType===8)if(r.data===Re)h.push({type:2,index:o});else{let _=-1;for(;(_=r.data.indexOf(v,_+1))!==-1;)h.push({type:7,index:o}),_+=v.length-1}o++}}static createElement(e,t){let n=D.createElement("template");return n.innerHTML=e,n}};function E(i,e,t=i,n){if(e===z)return e;let r=n!==void 0?t._$Co?.[n]:t._$Cl,o=W(e)?void 0:e._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(i),r._$AT(i,t,n)),n!==void 0?(t._$Co??=[])[n]=r:t._$Cl=r),r!==void 0&&(e=E(i,r._$AS(i,e.values),r,n)),e}var Y=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??D).importNode(t,!0);A.currentNode=r;let o=A.nextNode(),a=0,s=0,h=n[0];for(;h!==void 0;){if(a===h.index){let u;h.type===2?u=new P(o,o.nextSibling,this,e):h.type===1?u=new h.ctor(o,h.name,h.strings,this,e):h.type===6&&(u=new ne(o,this,e)),this._$AV.push(u),h=n[++s]}a!==h?.index&&(o=A.nextNode(),a++)}return A.currentNode=D,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}},P=class i{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=d,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=E(this,e,t),W(e)?e===d||e==null||e===""?(this._$AH!==d&&this._$AR(),this._$AH=d):e!==this._$AH&&e!==z&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Xe(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!==d&&W(this._$AH)?this._$AA.nextSibling.data=e:this.T(D.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=B.createElement(xe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let o=new Y(r,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=Ee.get(e.strings);return t===void 0&&Ee.set(e.strings,t=new B(e)),t}k(e){ie(this._$AH)||(this._$AH=[],this._$AR());let t=this._$AH,n,r=0;for(let o of e)r===t.length?t.push(n=new i(this.O(H()),this.O(H()),this,this.options)):n=t[r],n._$AI(o),r++;r<t.length&&(this._$AR(n&&n._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let n=ve(e).nextSibling;ve(e).remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,o){this.type=1,this._$AH=d,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=o,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):thLine truncated
|
||||
var m={cs:"4be67fcd522e",da:"0fe66a82bf2a",es:"bd89dffd1355",fi:"9a17bc084f56",fr:"6312d0f61ebf",hu:"27ba348531dc",it:"1b705e76dd00",nb:"c5ea24fb9ef6",nl:"b64142c67c2e",pl:"8527a4930402",pt:"31857a2d2277",ro:"e3cb5f449f0f",sk:"320611594db0",sl:"8071691ceda3",sv:"711b911ec8da",tr:"7c83ce1c3372",zh:"50518d9f494e"};var M=globalThis,N=M.ShadowRoot&&(M.ShadyCSS===void 0||M.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,U=Symbol(),pe=new WeakMap,R=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==U)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(N&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=pe.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&pe.set(t,e))}return e}toString(){return this.cssText}},fe=i=>new R(typeof i=="string"?i:i+"",void 0,U),j=(i,...e)=>{let t=i.length===1?i[0]:e.reduce((n,r,o)=>n+(a=>{if(a._$cssResult$===!0)return a.cssText;if(typeof a=="number")return a;throw Error("Value passed to 'css' function must be a 'css' function result: "+a+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(r)+i[o+1],i[0]);return new R(t,i,U)},ge=(i,e)=>{if(N)i.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),r=M.litNonce;r!==void 0&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}},q=N?i=>i:i=>i instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return fe(t)})(i):i;var{is:Ge,defineProperty:Oe,getOwnPropertyDescriptor:Ie,getOwnPropertyNames:Ze,getOwnPropertySymbols:Ve,getPrototypeOf:Ue}=Object,C=globalThis,be=C.trustedTypes,je=be?be.emptyScript:"",qe=C.reactiveElementPolyfillSupport,x=(i,e)=>i,J={toAttribute(i,e){switch(e){case Boolean:i=i?je:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,e){let t=i;switch(e){case Boolean:t=i!==null;break;case Number:t=i===null?null:Number(i);break;case Object:case Array:try{t=JSON.parse(i)}catch{t=null}}return t}},ke=(i,e)=>!Ge(i,e),we={attribute:!0,type:String,converter:J,reflect:!1,useDefault:!1,hasChanged:ke};Symbol.metadata??=Symbol("metadata"),C.litPropertyMetadata??=new WeakMap;var b=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=we){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){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&Oe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:o}=Ie(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){let s=r?.call(this);o?.call(this,a),this.requestUpdate(e,s,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??we}static _$Ei(){if(this.hasOwnProperty(x("elementProperties")))return;let e=Ue(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(x("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(x("properties"))){let t=this.properties,n=[...Ze(t),...Ve(t)];for(let r of n)this.createProperty(r,t[r])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,r]of t)this.elementProperties.set(n,r)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let r=this._$Eu(t,n);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let r of n)t.unshift(q(r))}else e!==void 0&&t.push(q(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?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),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return ge(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.Line truncated
|
||||
\f\r]`,F=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Se=/-->/g,Ae=/>/g,S=RegExp(`>|${X}(?:([^\\s"'>=/]+)(${X}*=${X}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),De=/'/g,ze=/"/g,xe=/^(?:script|style|textarea|title)$/i,oe=i=>(e,...t)=>({_$litType$:i,strings:e,values:t}),l=oe(1),ut=oe(2),mt=oe(3),z=Symbol.for("lit-noChange"),d=Symbol.for("lit-nothing"),Ee=new WeakMap,A=D.createTreeWalker(D,129);function Fe(i,e){if(!ie(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ye!==void 0?ye.createHTML(e):e}var Ye=(i,e)=>{let t=i.length-1,n=[],r,o=e===2?"<svg>":e===3?"<math>":"",a=F;for(let s=0;s<t;s++){let h=i[s],u,p,_=-1,g=0;for(;g<h.length&&(a.lastIndex=g,p=a.exec(h),p!==null);)g=a.lastIndex,a===F?p[1]==="!--"?a=Se:p[1]!==void 0?a=Ae:p[2]!==void 0?(xe.test(p[2])&&(r=RegExp("</"+p[2],"g")),a=S):p[3]!==void 0&&(a=S):a===S?p[0]===">"?(a=r??F,_=-1):p[1]===void 0?_=-2:(_=a.lastIndex-p[2].length,u=p[1],a=p[3]===void 0?S:p[3]==='"'?ze:De):a===ze||a===De?a=S:a===Se||a===Ae?a=F:(a=S,r=void 0);let k=a===S&&i[s+1].startsWith("/>")?" ":"";o+=a===F?h+Je:_>=0?(n.push(u),h.slice(0,_)+Te+h.slice(_)+v+k):h+v+(_===-2?s:k)}return[Fe(i,o+(i[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),n]},B=class i{constructor({strings:e,_$litType$:t},n){let r;this.parts=[];let o=0,a=0,s=e.length-1,h=this.parts,[u,p]=Ye(e,t);if(this.el=i.createElement(u,n),A.currentNode=this.el.content,t===2||t===3){let _=this.el.content.firstChild;_.replaceWith(..._.childNodes)}for(;(r=A.nextNode())!==null&&h.length<s;){if(r.nodeType===1){if(r.hasAttributes())for(let _ of r.getAttributeNames())if(_.endsWith(Te)){let g=p[a++],k=r.getAttribute(_).split(v),$=/([.?@])?(.*)/.exec(g);h.push({type:1,index:o,name:$[2],strings:k,ctor:$[1]==="."?Q:$[1]==="?"?ee:$[1]==="@"?te:T}),r.removeAttribute(_)}else _.startsWith(v)&&(h.push({type:6,index:o}),r.removeAttribute(_));if(xe.test(r.tagName)){let _=r.textContent.split(v),g=_.length-1;if(g>0){r.textContent=K?K.emptyScript:"";for(let k=0;k<g;k++)r.append(_[k],H()),A.nextNode(),h.push({type:2,index:++o});r.append(_[g],H())}}}else if(r.nodeType===8)if(r.data===Re)h.push({type:2,index:o});else{let _=-1;for(;(_=r.data.indexOf(v,_+1))!==-1;)h.push({type:7,index:o}),_+=v.length-1}o++}}static createElement(e,t){let n=D.createElement("template");return n.innerHTML=e,n}};function E(i,e,t=i,n){if(e===z)return e;let r=n!==void 0?t._$Co?.[n]:t._$Cl,o=W(e)?void 0:e._$litDirective$;return r?.constructor!==o&&(r?._$AO?.(!1),o===void 0?r=void 0:(r=new o(i),r._$AT(i,t,n)),n!==void 0?(t._$Co??=[])[n]=r:t._$Cl=r),r!==void 0&&(e=E(i,r._$AS(i,e.values),r,n)),e}var Y=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??D).importNode(t,!0);A.currentNode=r;let o=A.nextNode(),a=0,s=0,h=n[0];for(;h!==void 0;){if(a===h.index){let u;h.type===2?u=new P(o,o.nextSibling,this,e):h.type===1?u=new h.ctor(o,h.name,h.strings,this,e):h.type===6&&(u=new ne(o,this,e)),this._$AV.push(u),h=n[++s]}a!==h?.index&&(o=A.nextNode(),a++)}return A.currentNode=D,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings!==void 0?(n._$AI(e,n,t),t+=n.strings.length-2):n._$AI(e[t])),t++}},P=class i{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=d,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=E(this,e,t),W(e)?e===d||e==null||e===""?(this._$AH!==d&&this._$AR(),this._$AH=d):e!==this._$AH&&e!==z&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Xe(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!==d&&W(this._$AH)?this._$AA.nextSibling.data=e:this.T(D.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n=="number"?this._$AC(e):(n.el===void 0&&(n.el=B.createElement(Fe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let o=new Y(r,this),a=o.u(this.options);o.p(t),this.T(a),this._$AH=o}}_$AC(e){let t=Ee.get(e.strings);return t===void 0&&Ee.set(e.strings,t=new B(e)),t}k(e){ie(this._$AH)||(this._$AH=[],this._$AR());let t=this._$AH,n,r=0;for(let o of e)r===t.length?t.push(n=new i(this.O(H()),this.O(H()),this,this.options)):n=t[r],n._$AI(o),r++;r<t.length&&(this._$AR(n&&n._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let n=ve(e).nextSibling;ve(e).remove(),e=n}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,o){this.type=1,this._$AH=d,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=o,n.length>2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):thLine truncated
|
||||
<input type="checkbox" .checked=${e} @change=${o=>r(rt(o))} />
|
||||
<span>${i.t(t)}${n?l`<small>${i.t(n)}</small>`:d}</span>
|
||||
</label>`}var c=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r)),le=(i,e,t,n)=>f(i,i.value[e],t,n,r=>i.set(e,r||void 0));function w(i,e,t,n,r){return l`<label class="field"
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
/*! NextFloor, MIT licence. Includes three.js (MIT) and Lit (BSD-3-Clause); see LICENSE and THIRD_PARTY_NOTICES.md */
|
||||
var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,nt=Symbol(),_t=new WeakMap,D=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==nt)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o,n=this.t;if(G&&t===void 0){let i=n!==void 0&&n.length===1;i&&(t=_t.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&_t.set(n,t))}return t}toString(){return this.cssText}},wt=r=>new D(typeof r=="string"?r:r+"",void 0,nt),y=(r,...t)=>{let n=r.length===1?r[0]:t.reduce((i,e,o)=>i+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(e)+r[o+1],r[0]);return new D(n,r,nt)},St=(r,t)=>{if(G)r.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(let n of t){let i=document.createElement("style"),e=Y.litNonce;e!==void 0&&i.setAttribute("nonce",e),i.textContent=n.cssText,r.appendChild(i)}},it=G?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let n="";for(let i of t.cssRules)n+=i.cssText;return wt(n)})(r):r;var{is:Jt,defineProperty:Xt,getOwnPropertyDescriptor:Yt,getOwnPropertyNames:Gt,getOwnPropertySymbols:Qt,getPrototypeOf:te}=Object,Q=globalThis,At=Q.trustedTypes,ee=At?At.emptyScript:"",ne=Q.reactiveElementPolyfillSupport,V=(r,t)=>r,rt={toAttribute(r,t){switch(t){case Boolean:r=r?ee:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let n=r;switch(t){case Boolean:n=r!==null;break;case Number:n=r===null?null:Number(r);break;case Object:case Array:try{n=JSON.parse(r)}catch{n=null}}return n}},Ht=(r,t)=>!Jt(r,t),Et={attribute:!0,type:String,converter:rt,reflect:!1,useDefault:!1,hasChanged:Ht};Symbol.metadata??=Symbol("metadata"),Q.litPropertyMetadata??=new WeakMap;var w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=Et){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){let i=Symbol(),e=this.getPropertyDescriptor(t,i,n);e!==void 0&&Xt(this.prototype,t,e)}}static getPropertyDescriptor(t,n,i){let{get:e,set:o}=Yt(this.prototype,t)??{get(){return this[n]},set(s){this[n]=s}};return{get:e,set(s){let c=e?.call(this);o?.call(this,s),this.requestUpdate(t,c,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Et}static _$Ei(){if(this.hasOwnProperty(V("elementProperties")))return;let t=te(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(V("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(V("properties"))){let n=this.properties,i=[...Gt(n),...Qt(n)];for(let e of i)this.createProperty(e,n[e])}let t=this[Symbol.metadata];if(t!==null){let n=litPropertyMetadata.get(t);if(n!==void 0)for(let[i,e]of n)this.elementProperties.set(i,e)}this._$Eh=new Map;for(let[n,i]of this.elementProperties){let e=this._$Eu(n,i);e!==void 0&&this._$Eh.set(e,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let n=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let e of i)n.unshift(it(e))}else t!==void 0&&n.push(it(t));return n}static _$Eu(t,n){let i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.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(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,n=this.constructor.elementProperties;for(let i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return St(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){let i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(e!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:rt).toAttribute(n,i.type);this._$Em=t,o==null?this.removeAttribute(e):this.setAttriLine truncated
|
||||
\f\r]`,j=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Rt=/-->/g,Nt=/>/g,k=RegExp(`>|${ot}(?:([^\\s"'>=/]+)(${ot}*=${ot}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),Pt=/'/g,Mt=/"/g,zt=/^(?:script|style|textarea|title)$/i,pt=r=>(t,...n)=>({_$litType$:r,strings:t,values:n}),d=pt(1),ye=pt(2),ve=pt(3),N=Symbol.for("lit-noChange"),a=Symbol.for("lit-nothing"),Tt=new WeakMap,C=R.createTreeWalker(R,129);function Ut(r,t){if(!ht(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Ct!==void 0?Ct.createHTML(t):t}var oe=(r,t)=>{let n=r.length-1,i=[],e,o=t===2?"<svg>":t===3?"<math>":"",s=j;for(let c=0;c<n;c++){let l=r[c],h,p,u=-1,m=0;for(;m<l.length&&(s.lastIndex=m,p=s.exec(l),p!==null);)m=s.lastIndex,s===j?p[1]==="!--"?s=Rt:p[1]!==void 0?s=Nt:p[2]!==void 0?(zt.test(p[2])&&(e=RegExp("</"+p[2],"g")),s=k):p[3]!==void 0&&(s=k):s===k?p[0]===">"?(s=e??j,u=-1):p[1]===void 0?u=-2:(u=s.lastIndex-p[2].length,h=p[1],s=p[3]===void 0?k:p[3]==='"'?Mt:Pt):s===Mt||s===Pt?s=k:s===Rt||s===Nt?s=j:(s=k,e=void 0);let $=s===k&&r[c+1].startsWith("/>")?" ":"";o+=s===j?l+ie:u>=0?(i.push(h),l.slice(0,u)+Ot+l.slice(u)+A+$):l+A+(u===-2?c:$)}return[Ut(r,o+(r[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},K=class r{constructor({strings:t,_$litType$:n},i){let e;this.parts=[];let o=0,s=0,c=t.length-1,l=this.parts,[h,p]=oe(t,n);if(this.el=r.createElement(h,i),C.currentNode=this.el.content,n===2||n===3){let u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(e=C.nextNode())!==null&&l.length<c;){if(e.nodeType===1){if(e.hasAttributes())for(let u of e.getAttributeNames())if(u.endsWith(Ot)){let m=p[s++],$=e.getAttribute(u).split(A),_=/([.?@])?(.*)/.exec(m);l.push({type:1,index:o,name:_[2],strings:$,ctor:_[1]==="."?at:_[1]==="?"?lt:_[1]==="@"?ct:M}),e.removeAttribute(u)}else u.startsWith(A)&&(l.push({type:6,index:o}),e.removeAttribute(u));if(zt.test(e.tagName)){let u=e.textContent.split(A),m=u.length-1;if(m>0){e.textContent=tt?tt.emptyScript:"";for(let $=0;$<m;$++)e.append(u[$],B()),C.nextNode(),l.push({type:2,index:++o});e.append(u[m],B())}}}else if(e.nodeType===8)if(e.data===Ft)l.push({type:2,index:o});else{let u=-1;for(;(u=e.data.indexOf(A,u+1))!==-1;)l.push({type:7,index:o}),u+=A.length-1}o++}}static createElement(t,n){let i=R.createElement("template");return i.innerHTML=t,i}};function P(r,t,n=r,i){if(t===N)return t;let e=i!==void 0?n._$Co?.[i]:n._$Cl,o=I(t)?void 0:t._$litDirective$;return e?.constructor!==o&&(e?._$AO?.(!1),o===void 0?e=void 0:(e=new o(r),e._$AT(r,n,i)),i!==void 0?(n._$Co??=[])[i]=e:n._$Cl=e),e!==void 0&&(t=P(r,e._$AS(r,t.values),e,i)),t}var st=class{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:n},parts:i}=this._$AD,e=(t?.creationScope??R).importNode(n,!0);C.currentNode=e;let o=C.nextNode(),s=0,c=0,l=i[0];for(;l!==void 0;){if(s===l.index){let h;l.type===2?h=new W(o,o.nextSibling,this,t):l.type===1?h=new l.ctor(o,l.name,l.strings,this,t):l.type===6&&(h=new ut(o,this,t)),this._$AV.push(h),l=i[++c]}s!==l?.index&&(o=C.nextNode(),s++)}return C.currentNode=R,e}p(t){let n=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}},W=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,n,i,e){this.type=2,this._$AH=a,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=i,this.options=e,this._$Cv=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,n=this._$AM;return n!==void 0&&t?.nodeType===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=P(this,t,n),I(t)?t===a||t==null||t===""?(this._$AH!==a&&this._$AR(),this._$AH=a):t!==this._$AH&&t!==N&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):re(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==a&&I(this._$AH)?this._$AA.nextSibling.data=t:this.T(R.createTextNode(t)),this._$AH=t}$(t){let{values:n,_$litType$:i}=t,e=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=K.createElement(Ut(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===e)this._$AH.p(n);else{let o=new st(e,this),s=o.u(this.options);o.p(n),this.T(s),this._$AH=o}}_$AC(t){let n=Tt.get(t.strings);return n===void 0&&Tt.set(t.strings,n=new K(t)),n}k(t){ht(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,i,e=0;for(let o of t)e===n.length?n.push(i=new r(this.O(B()),this.O(B()),this,this.options)):i=n[e],i._$AI(o),e++;e<n.length&&(this._$AR(i&&i._$AB.nextSibling,e),n.length=e)}_$AR(t=this._$AA.nextSibling,n){for(this._$AP?.(!1,!0,n);t!==this._$AB;){let i=kt(t).nextSibling;kt(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},M=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,e,o){this.type=1,this._$AH=a,this._$AN=void 0,this.element=t,this.name=n,this._$AM=e,this.options=o,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=Line truncated
|
||||
var G=globalThis,Q=G.ShadowRoot&&(G.ShadyCSS===void 0||G.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,it=Symbol(),wt=new WeakMap,j=class{constructor(t,n,i){if(this._$cssResult$=!0,i!==it)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=n}get styleSheet(){let t=this.o,n=this.t;if(Q&&t===void 0){let i=n!==void 0&&n.length===1;i&&(t=wt.get(n)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),i&&wt.set(n,t))}return t}toString(){return this.cssText}},At=r=>new j(typeof r=="string"?r:r+"",void 0,it),y=(r,...t)=>{let n=r.length===1?r[0]:t.reduce((i,e,s)=>i+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(e)+r[s+1],r[0]);return new j(n,r,it)},St=(r,t)=>{if(Q)r.adoptedStyleSheets=t.map(n=>n instanceof CSSStyleSheet?n:n.styleSheet);else for(let n of t){let i=document.createElement("style"),e=G.litNonce;e!==void 0&&i.setAttribute("nonce",e),i.textContent=n.cssText,r.appendChild(i)}},rt=Q?r=>r:r=>r instanceof CSSStyleSheet?(t=>{let n="";for(let i of t.cssRules)n+=i.cssText;return At(n)})(r):r;var{is:Xt,defineProperty:Yt,getOwnPropertyDescriptor:Gt,getOwnPropertyNames:Qt,getOwnPropertySymbols:te,getPrototypeOf:ee}=Object,tt=globalThis,Et=tt.trustedTypes,ne=Et?Et.emptyScript:"",ie=tt.reactiveElementPolyfillSupport,B=(r,t)=>r,st={toAttribute(r,t){switch(t){case Boolean:r=r?ne:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,t){let n=r;switch(t){case Boolean:n=r!==null;break;case Number:n=r===null?null:Number(r);break;case Object:case Array:try{n=JSON.parse(r)}catch{n=null}}return n}},kt=(r,t)=>!Xt(r,t),Ht={attribute:!0,type:String,converter:st,reflect:!1,useDefault:!1,hasChanged:kt};Symbol.metadata??=Symbol("metadata"),tt.litPropertyMetadata??=new WeakMap;var w=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,n=Ht){if(n.state&&(n.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((n=Object.create(n)).wrapped=!0),this.elementProperties.set(t,n),!n.noAccessor){let i=Symbol(),e=this.getPropertyDescriptor(t,i,n);e!==void 0&&Yt(this.prototype,t,e)}}static getPropertyDescriptor(t,n,i){let{get:e,set:s}=Gt(this.prototype,t)??{get(){return this[n]},set(o){this[n]=o}};return{get:e,set(o){let c=e?.call(this);s?.call(this,o),this.requestUpdate(t,c,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??Ht}static _$Ei(){if(this.hasOwnProperty(B("elementProperties")))return;let t=ee(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(B("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(B("properties"))){let n=this.properties,i=[...Qt(n),...te(n)];for(let e of i)this.createProperty(e,n[e])}let t=this[Symbol.metadata];if(t!==null){let n=litPropertyMetadata.get(t);if(n!==void 0)for(let[i,e]of n)this.elementProperties.set(i,e)}this._$Eh=new Map;for(let[n,i]of this.elementProperties){let e=this._$Eu(n,i);e!==void 0&&this._$Eh.set(e,n)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){let n=[];if(Array.isArray(t)){let i=new Set(t.flat(1/0).reverse());for(let e of i)n.unshift(rt(e))}else t!==void 0&&n.push(rt(t));return n}static _$Eu(t,n){let i=n.attribute;return i===!1?void 0:typeof i=="string"?i:typeof t=="string"?t.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(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){let t=new Map,n=this.constructor.elementProperties;for(let i of n.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){let t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return St(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,n,i){this._$AK(t,i)}_$ET(t,n){let i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(e!==void 0&&i.reflect===!0){let s=(i.converter?.toAttribute!==void 0?i.converter:st).toAttribute(n,i.type);this._$Em=t,s==null?this.removeAttribute(e):this.setALine truncated
|
||||
\f\r]`,I=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Nt=/-->/g,Pt=/>/g,k=RegExp(`>|${ot}(?:([^\\s"'>=/]+)(${ot}*=${ot}*(?:[^
|
||||
\f\r"'\`<>=]|("|')|))|$)`,"g"),Mt=/'/g,Tt=/"/g,Ut=/^(?:script|style|textarea|title)$/i,ft=r=>(t,...n)=>({_$litType$:r,strings:t,values:n}),d=ft(1),ve=ft(2),xe=ft(3),N=Symbol.for("lit-noChange"),a=Symbol.for("lit-nothing"),Ot=new WeakMap,C=R.createTreeWalker(R,129);function Lt(r,t){if(!pt(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return Rt!==void 0?Rt.createHTML(t):t}var oe=(r,t)=>{let n=r.length-1,i=[],e,s=t===2?"<svg>":t===3?"<math>":"",o=I;for(let c=0;c<n;c++){let l=r[c],h,p,u=-1,g=0;for(;g<l.length&&(o.lastIndex=g,p=o.exec(l),p!==null);)g=o.lastIndex,o===I?p[1]==="!--"?o=Nt:p[1]!==void 0?o=Pt:p[2]!==void 0?(Ut.test(p[2])&&(e=RegExp("</"+p[2],"g")),o=k):p[3]!==void 0&&(o=k):o===k?p[0]===">"?(o=e??I,u=-1):p[1]===void 0?u=-2:(u=o.lastIndex-p[2].length,h=p[1],o=p[3]===void 0?k:p[3]==='"'?Tt:Mt):o===Tt||o===Mt?o=k:o===Nt||o===Pt?o=I:(o=k,e=void 0);let $=o===k&&r[c+1].startsWith("/>")?" ":"";s+=o===I?l+re:u>=0?(i.push(h),l.slice(0,u)+Ft+l.slice(u)+S+$):l+S+(u===-2?c:$)}return[Lt(r,s+(r[n]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},q=class r{constructor({strings:t,_$litType$:n},i){let e;this.parts=[];let s=0,o=0,c=t.length-1,l=this.parts,[h,p]=oe(t,n);if(this.el=r.createElement(h,i),C.currentNode=this.el.content,n===2||n===3){let u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(e=C.nextNode())!==null&&l.length<c;){if(e.nodeType===1){if(e.hasAttributes())for(let u of e.getAttributeNames())if(u.endsWith(Ft)){let g=p[o++],$=e.getAttribute(u).split(S),_=/([.?@])?(.*)/.exec(g);l.push({type:1,index:s,name:_[2],strings:$,ctor:_[1]==="."?lt:_[1]==="?"?ct:_[1]==="@"?ut:T}),e.removeAttribute(u)}else u.startsWith(S)&&(l.push({type:6,index:s}),e.removeAttribute(u));if(Ut.test(e.tagName)){let u=e.textContent.split(S),g=u.length-1;if(g>0){e.textContent=et?et.emptyScript:"";for(let $=0;$<g;$++)e.append(u[$],K()),C.nextNode(),l.push({type:2,index:++s});e.append(u[g],K())}}}else if(e.nodeType===8)if(e.data===zt)l.push({type:2,index:s});else{let u=-1;for(;(u=e.data.indexOf(S,u+1))!==-1;)l.push({type:7,index:s}),u+=S.length-1}s++}}static createElement(t,n){let i=R.createElement("template");return i.innerHTML=t,i}};function M(r,t,n=r,i){if(t===N)return t;let e=i!==void 0?n._$Co?.[i]:n._$Cl,s=W(t)?void 0:t._$litDirective$;return e?.constructor!==s&&(e?._$AO?.(!1),s===void 0?e=void 0:(e=new s(r),e._$AT(r,n,i)),i!==void 0?(n._$Co??=[])[i]=e:n._$Cl=e),e!==void 0&&(t=M(r,e._$AS(r,t.values),e,i)),t}var at=class{constructor(t,n){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=n}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){let{el:{content:n},parts:i}=this._$AD,e=(t?.creationScope??R).importNode(n,!0);C.currentNode=e;let s=C.nextNode(),o=0,c=0,l=i[0];for(;l!==void 0;){if(o===l.index){let h;l.type===2?h=new Z(s,s.nextSibling,this,t):l.type===1?h=new l.ctor(s,l.name,l.strings,this,t):l.type===6&&(h=new dt(s,this,t)),this._$AV.push(h),l=i[++c]}o!==l?.index&&(s=C.nextNode(),o++)}return C.currentNode=R,e}p(t){let n=0;for(let i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(t,i,n),n+=i.strings.length-2):i._$AI(t[n])),n++}},Z=class r{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,n,i,e){this.type=2,this._$AH=a,this._$AN=void 0,this._$AA=t,this._$AB=n,this._$AM=i,this.options=e,this._$Cv=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode,n=this._$AM;return n!==void 0&&t?.nodeType===11&&(t=n.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,n=this){t=M(this,t,n),W(t)?t===a||t==null||t===""?(this._$AH!==a&&this._$AR(),this._$AH=a):t!==this._$AH&&t!==N&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):se(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==a&&W(this._$AH)?this._$AA.nextSibling.data=t:this.T(R.createTextNode(t)),this._$AH=t}$(t){let{values:n,_$litType$:i}=t,e=typeof i=="number"?this._$AC(t):(i.el===void 0&&(i.el=q.createElement(Lt(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===e)this._$AH.p(n);else{let s=new at(e,this),o=s.u(this.options);s.p(n),this.T(o),this._$AH=s}}_$AC(t){let n=Ot.get(t.strings);return n===void 0&&Ot.set(t.strings,n=new q(t)),n}k(t){pt(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,i,e=0;for(let s of t)e===n.length?n.push(i=new r(this.O(K()),this.O(K()),this,this.options)):i=n[e],i._$AI(s),e++;e<n.length&&(this._$AR(i&&i._$AB.nextSibling,e),n.length=e)}_$AR(t=this._$AA.nextSibling,n){for(this._$AP?.(!1,!0,n);t!==this._$AB;){let i=Ct(t).nextSibling;Ct(t).remove(),t=i}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}},T=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,n,i,e,s){this.type=1,this._$AH=a,this._$AN=void 0,this.element=t,this.name=n,this._$AM=e,this.options=s,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=Line truncated
|
||||
:host {
|
||||
--nf-text: var(--primary-text-color, #e1e1e1);
|
||||
--nf-muted: var(--secondary-text-color, #9b9b9b);
|
||||
@@ -29,7 +29,7 @@ var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&
|
||||
font-family: var(--nf-font);
|
||||
color: var(--nf-text);
|
||||
}
|
||||
`,Ve=y`
|
||||
`,je=y`
|
||||
:host([readable]) {
|
||||
--secondary-text-color: var(--primary-text-color, #e1e1e1);
|
||||
--divider-color: color-mix(in srgb, var(--primary-text-color, #e1e1e1) 40%, transparent);
|
||||
@@ -40,7 +40,7 @@ var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&
|
||||
:host([readable]) .nf-overlay {
|
||||
zoom: 1.2;
|
||||
}
|
||||
`,je=y`
|
||||
`,Be=y`
|
||||
/* a group of switches: one rounded pill, the active one tinted with the accent */
|
||||
.nf-seg {
|
||||
display: inline-flex;
|
||||
@@ -203,32 +203,33 @@ var Y=globalThis,G=Y.ShadowRoot&&(Y.ShadyCSS===void 0||Y.ShadyCSS.nativeShadow)&
|
||||
min-height: 40px;
|
||||
}
|
||||
}
|
||||
`;function gt(r,t){let n=new Set;return t.flatMap(i=>{let e=String(r?.states[i]?.attributes.symcon_source_entity||i),o=r?.states[e]?.attributes,s=Number(o?.symcon_id);return!s||!o?.symcon_archive||n.has(s)?[]:(n.add(s),[e])})}var Vt,bt=class extends v{static properties={hass:{attribute:!1},ids:{attribute:!1},label:{attribute:!1},busy:{state:!0},error:{state:!0}};constructor(){super(),this.ids=[],this.label="",this.busy=!1,this.error=""}async open(t){t.stopPropagation(),this.busy=!0,this.error="";try{let n=new URL("./nextfloor-trend.js?v=84417e0b2573",import.meta.url).href;await(await(Vt??=import(n).catch(e=>{throw Vt=void 0,e}))).openTrend(this.hass,this.ids,this.label)}catch(n){this.error=n instanceof Error?n.message:String(n)}finally{this.busy=!1}}render(){if(!gt(this.hass,this.ids).length)return a;let t=this.label?`Trend anzeigen: ${this.label}`:"Trend anzeigen";return d`<button type="button" title=${t} aria-label=${t} aria-haspopup="dialog" ?disabled=${this.busy} @pointerdown=${n=>n.stopPropagation()} @click=${n=>{this.open(n)}}>
|
||||
`;function bt(r,t){let n=new Set;return t.flatMap(i=>{let e=String(r?.states[i]?.attributes.symcon_source_entity||i),s=r?.states[e]?.attributes,o=Number(s?.symcon_id);return!o||!s?.symcon_archive||n.has(o)?[]:(n.add(o),[e])})}var jt,yt=class extends v{static properties={hass:{attribute:!1},ids:{attribute:!1},label:{attribute:!1},busy:{state:!0},error:{state:!0}};constructor(){super(),this.ids=[],this.label="",this.busy=!1,this.error=""}async open(t){t.stopPropagation(),this.busy=!0,this.error="";try{let n=new URL("./nextfloor-trend.js?v=84417e0b2573",import.meta.url).href;await(await(jt??=import(n).catch(e=>{throw jt=void 0,e}))).openTrend(this.hass,this.ids,this.label)}catch(n){this.error=n instanceof Error?n.message:String(n)}finally{this.busy=!1}}render(){if(!bt(this.hass,this.ids).length)return a;let t=this.label?`Trend anzeigen: ${this.label}`:"Trend anzeigen";return d`<button type="button" title=${t} aria-label=${t} aria-haspopup="dialog" ?disabled=${this.busy} @pointerdown=${n=>n.stopPropagation()} @click=${n=>{this.open(n)}}>
|
||||
<svg width="12" height="12" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M3 2v15h15M5 13l4-5 4 2 4-6"/></svg>
|
||||
</button>${this.error?d`<span role="alert">${this.error}</span>`:a}`}static styles=y`:host{position:relative;display:inline-flex;flex:0 0 18px;width:18px;height:18px;vertical-align:middle;margin-left:3px;font-weight:normal;line-height:0}button{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:18px;height:18px;padding:2px;border:0;border-radius:3px;background:transparent;color:var(--nf-accent,#40c8ff);opacity:.8;cursor:pointer}svg{display:block;flex-shrink:0}button:hover,button:focus-visible{opacity:1;background:#40c8ff18}button:focus-visible{outline:1px solid currentColor;outline-offset:1px}button:disabled{opacity:.4}span{position:absolute;right:0;top:22px;z-index:10;box-sizing:border-box;width:200px;padding:8px;border:1px solid #ff9b9b50;border-radius:6px;background:var(--nf-chrome-solid,#1c1c1c);font:12px/1.4 system-ui;color:#ff9b9b;white-space:normal}`};customElements.get("nf-trend-button")||customElements.define("nf-trend-button",bt);function X(r,t,n=""){let i=gt(r,t);return i.length?d`<nf-trend-button .hass=${r} .ids=${i} .label=${n}></nf-trend-button>`:a}var pe={heating_manifold:"Heiz-/K\xFChlkreisverteiler",buffer_tank:"Pufferspeicher",freshwater_station:"Frischwasserstation"},Bt=r=>r.name||pe[r.type],It=r=>r.name||{heating:"Heizkreis",cooling:"K\xFChlkreis",changeover:"Heizen / K\xFChlen",pump:"Vorschubpumpe"}[r.kind],Kt=(r,t)=>t.kind==="pump"?"Pumpenkreis":t.kind==="cooling"?"K\xFChlen":t.kind==="heating"?"Heizen":g(t.mode_entity)&&b(r.states[t.mode_entity])===null?"Betriebsart \u2013":Number(g(t.mode_entity)?b(r.states[t.mode_entity]):0)===(t.cooling_value??1)?"K\xFChlen":"Heizen",et=(r,t,n)=>[f(r,"Vorlauf",t),f(r,"R\xFCcklauf",n)].filter(i=>i!==null),yt=(r,t,n)=>{let i=E(r,t),e=E(r,n);return i===null||e===null?a:d`<div class="reading delta"><span>ΔT · VL − RL</span><b>${(i-e).toLocaleString(r.language,{maximumFractionDigits:1})} K</b></div>`};function Wt(r,t){let n=F(t),i=t.type==="freshwater_station"?[]:et(r,n.flow,n.return);if(t.type==="buffer_tank"&&i.unshift(...[...n.sensors??[]].sort((e,o)=>o.level-e.level).flatMap(e=>{let o=f(r,e.name||"F\xFChler",e.entity);return o?[o]:[]})),t.type==="freshwater_station"){let e=f(r,"Zirkulation",n.circulation_temperature);e&&i.push(e)}for(let e of t.values??[]){let o=f(r,e.label||String(e.entity&&r.states[e.entity]?.attributes.friendly_name||"Wert"),e.entity);o&&i.push({...o,icon:e.icon})}return i}function qt(r,t){return[...et(r,t.flow,t.return),...[["Kaltwasser",t.cold_water],["Trinkwarmwasser",t.hot_water],["Pumpenleistung",t.power]].flatMap(([n,i])=>{let e=f(r,n,i);return e?[e]:[]})]}var vt=(r,t)=>`K${t+1} \xB7 ${r.name||`Station ${t+1}`}`,H=(r,t)=>d`<div class="reading" data-source=${t.id}><span>${t.icon?.startsWith("mdi:")?d`<ha-icon icon=${t.icon}></ha-icon>`:t.icon||a} ${t.label}</span><b>${t.text}${X(r,[t.id],t.label)}</b></div>`;function L(r,t,n){let i=S(r,n);return i.id?d`<div class="reading" data-source=${i.id}><span>${t}<small>${i.feedback?"Ist":"Soll"}</small></span><b><i class="lamp" style=${`background:${i.running===null?"#888":i.running?"#6fe1a2":"#465361"}`}></i>${U(r.states[i.id])}${X(r,[i.id],t)}</b></div>`:a}var Zt=y`
|
||||
</button>${this.error?d`<span role="alert">${this.error}</span>`:a}`}static styles=y`:host{position:relative;display:inline-flex;flex:0 0 18px;width:18px;height:18px;vertical-align:middle;margin-left:3px;font-weight:normal;line-height:0}button{display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;width:18px;height:18px;padding:2px;border:0;border-radius:3px;background:transparent;color:var(--nf-accent,#40c8ff);opacity:.8;cursor:pointer}svg{display:block;flex-shrink:0}button:hover,button:focus-visible{opacity:1;background:#40c8ff18}button:focus-visible{outline:1px solid currentColor;outline-offset:1px}button:disabled{opacity:.4}span{position:absolute;right:0;top:22px;z-index:10;box-sizing:border-box;width:200px;padding:8px;border:1px solid #ff9b9b50;border-radius:6px;background:var(--nf-chrome-solid,#1c1c1c);font:12px/1.4 system-ui;color:#ff9b9b;white-space:normal}`};customElements.get("nf-trend-button")||customElements.define("nf-trend-button",yt);function D(r,t,n=""){let i=bt(r,t);return i.length?d`<nf-trend-button .hass=${r} .ids=${i} .label=${n}></nf-trend-button>`:a}var fe={heating_manifold:"Heiz-/K\xFChlkreisverteiler",buffer_tank:"Pufferspeicher",freshwater_station:"Frischwasserstation"},It=r=>r.name||fe[r.type],Kt=r=>r.name||{heating:"Heizkreis",cooling:"K\xFChlkreis",changeover:"Heizen / K\xFChlen",pump:"Vorschubpumpe"}[r.kind],Wt=(r,t)=>t.kind==="pump"?"Pumpenkreis":t.kind==="cooling"?"K\xFChlen":t.kind==="heating"?"Heizen":f(t.mode_entity)&&b(r.states[t.mode_entity])===null?"Betriebsart \u2013":Number(f(t.mode_entity)?b(r.states[t.mode_entity]):0)===(t.cooling_value??1)?"K\xFChlen":"Heizen",nt=(r,t,n)=>[m(r,"Vorlauf",t),m(r,"R\xFCcklauf",n)].filter(i=>i!==null),vt=(r,t,n)=>{let i=E(r,t),e=E(r,n);return i===null||e===null?a:d`<div class="reading delta"><span>ΔT · VL − RL</span><b>${(i-e).toLocaleString(r.language,{maximumFractionDigits:1})} K</b></div>`};function qt(r,t){let n=z(t),i=t.type==="freshwater_station"?[]:nt(r,n.flow,n.return);if(t.type==="buffer_tank"&&i.unshift(...[...n.sensors??[]].sort((e,s)=>s.level-e.level).flatMap(e=>{let s=m(r,e.name||"F\xFChler",e.entity);return s?[s]:[]})),t.type==="freshwater_station"){let e=m(r,"Zirkulation",n.circulation_temperature);e&&i.push(e)}for(let e of t.values??[]){let s=m(r,e.label||String(e.entity&&r.states[e.entity]?.attributes.friendly_name||"Wert"),e.entity);s&&i.push({...s,icon:e.icon})}return i}function Zt(r,t){return[...nt(r,t.flow,t.return),...[["Kaltwasser",t.cold_water],["Trinkwarmwasser",t.hot_water],["Pumpenleistung",t.power]].flatMap(([n,i])=>{let e=m(r,n,i);return e?[e]:[]})]}var xt=(r,t)=>`K${t+1} \xB7 ${r.name||`Station ${t+1}`}`,H=(r,t)=>d`<div class="reading" data-source=${t.id}><span>${t.icon?.startsWith("mdi:")?d`<ha-icon icon=${t.icon}></ha-icon>`:t.icon||a} ${t.label}</span><b>${t.text}${D(r,[t.id],t.label)}</b></div>`,P=(r,t,n="Status")=>{let i=m(r,n,t);return i?d`<div class="reading status-reading" data-source=${i.id}><span>${n}</span><b><span class="status-text" title=${i.text}>${i.text}</span>${D(r,[i.id],n)}</b></div>`:a};function V(r,t,n){let i=A(r,n);return i.id?d`<div class="reading" data-source=${i.id}><span>${t}<small>${i.feedback?"Ist":"Soll"}</small></span><b><i class="lamp" style=${`background:${i.running===null?"#888":i.running?"#6fe1a2":"#465361"}`}></i>${L(r.states[i.id])}${D(r,[i.id],t)}</b></div>`:a}var Jt=y`
|
||||
:host{display:block;color:var(--nf-text);font:12px/1.4 system-ui,sans-serif;min-width:170px;max-width:300px}
|
||||
button{font:inherit;color:inherit;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:7px;padding:5px 8px;cursor:pointer}button:disabled,input:disabled{opacity:.45;cursor:default}button:focus-visible,input:focus-visible{outline:2px solid var(--nf-accent);outline-offset:2px}
|
||||
.title{display:block;width:100%;padding:0 0 5px;border:0;background:none;font-weight:600;text-align:left;white-space:normal}.content{max-height:250px;overflow:auto;overscroll-behavior:contain}.circuit{border-top:1px solid var(--nf-line);padding:5px 0}.circuit-name{font-size:11px;font-weight:600;margin-bottom:3px}.reading{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:10px;align-items:center;min-height:22px}.reading>span{color:var(--nf-muted);white-space:normal}.reading b{display:flex;align-items:center;justify-content:flex-end;white-space:nowrap;font-variant-numeric:tabular-nums;font-weight:500}.reading small{font-size:9px;margin-left:5px;opacity:.75}.delta{font-size:10px}.lamp{display:inline-block;flex:none;width:6px;height:6px;border-radius:50%;margin-right:5px}.empty{color:var(--nf-muted);font-size:11px;white-space:normal;margin:5px 0}nf-trend-button{margin-left:3px}
|
||||
.status-reading{grid-template-columns:auto minmax(0,1fr)}.status-reading b{min-width:0}.status-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.circuit-name small,h3 small{font-size:10px;color:var(--nf-muted);font-weight:normal;margin-left:5px}
|
||||
ha-icon{--mdc-icon-size:13px;width:13px;height:13px;vertical-align:middle}
|
||||
dialog{box-sizing:border-box;width:min(620px,calc(100vw - 24px));max-width:none;max-height:calc(100dvh - 24px);padding:0;color:var(--nf-text);background:var(--nf-chrome-solid,#1c1c1c);border:1px solid var(--nf-line);border-radius:14px;box-shadow:0 20px 70px #0008;font:13px/1.4 system-ui,sans-serif}dialog::backdrop{background:#050b16a6;backdrop-filter:blur(3px)}header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 18px;border-bottom:1px solid var(--nf-line)}h2{font-size:17px;margin:0}.body{padding:12px 18px;max-height:calc(100dvh - 120px);overflow:auto;overscroll-behavior:contain}h3{font-size:13px;margin:12px 0 7px}fieldset{min-width:0;margin:8px 0;padding:10px;border:1px solid var(--nf-line);border-radius:9px}legend{font-size:12px;color:var(--nf-muted)}.command{display:flex;align-items:center;gap:12px;margin-top:8px}.command input[type=range]{flex:1;min-width:0;accent-color:var(--nf-accent)}.command input[type=number]{width:90px;box-sizing:border-box;background:var(--nf-fill,#ffffff10);border:1px solid var(--nf-line);border-radius:6px;color:inherit;padding:5px}.command output{font-variant-numeric:tabular-nums;min-width:45px;text-align:right}.error{color:#ff9b9b}.readonly{color:var(--nf-muted);font-size:11px;margin:4px 0}.body .reading{padding:4px 0}.body .circuit{padding-bottom:12px}
|
||||
`,xt=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean}};render(){if(!this.hass||!this.item)return a;let t=F(this.item),n=Wt(this.hass,this.item),i=this.item.type==="freshwater_station"?O(this.item):[];return d`<button class="title" @click=${()=>jt(this.hass,this.item,this.readOnly)} aria-haspopup="dialog">${Bt(this.item)} ⚙</button><div class="content">
|
||||
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit"><div class="circuit-name">${It(e)} <small>${Kt(this.hass,e)}</small></div>${q(e)?L(this.hass,"Pumpe",e.pump):a}${Z(e)?L(this.hass,"Ventil",e.valve):a}${et(this.hass,e.flow,e.return).map(o=>H(this.hass,o))}${f(this.hass,"Leistung",e.power)?H(this.hass,f(this.hass,"Leistung",e.power)):a}</section>`):a}
|
||||
${i.length>1?d`<small class="cascade-count">Kaskade · ${i.length} Stationen</small>${i.map((e,o)=>{let s=S(this.hass,e.pump),c=f(this.hass,"Trinkwarmwasser",e.hot_water)||f(this.hass,"Vorlauf",e.flow);return d`<div class="station-summary" data-station=${e.id}><button class="station-name" @click=${()=>jt(this.hass,this.item,this.readOnly,e.id)}><i class="lamp" title=${`Pumpe: ${s.id?U(this.hass.states[s.id]):"\u2013"}`} style=${`background:${s.running===null?"#888":s.running?"#6fe1a2":"#a82638"}`}></i>${vt(e,o)}</button><b>${c?.text||"\u2013"}</b>${c?X(this.hass,[c.id],`${vt(e,o)} \xB7 ${c.label}`):a}</div>`})}`:i.map(e=>d`<section class="circuit">${qt(this.hass,e).map(o=>H(this.hass,o))}${L(this.hass,"Ladepumpe",e.pump)}${T(e)?L(this.hass,"Kaskadenventil",e.valve):a}</section>`)}
|
||||
${n.map(e=>H(this.hass,e))}${this.item.type==="freshwater_station"?L(this.hass,"Zirkulationspumpe",t.circulation):a}
|
||||
${this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"&&!n.length?d`<p class="empty">Noch keine Fühler verknüpft</p>`:a}
|
||||
</div>`}static styles=[mt,Zt,y`.cascade-count{color:var(--nf-muted)}.station-summary{display:grid;grid-template-columns:minmax(0,1fr) auto 18px;align-items:center;gap:6px;width:100%;padding:5px 0;font-size:11px}.station-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0;background:none;border:0;text-align:left}.station-summary b{white-space:nowrap;font-variant-numeric:tabular-nums}`]},$t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean},focusStation:{attribute:!1},pending:{state:!0},error:{state:!0}};constructor(){super(),this.pending=new Set,this.error="",this.readOnly=!1}async show(){await this.updateComplete,this.shadowRoot.querySelector("dialog").showModal(),this.focusStation&&this.shadowRoot.querySelector(`[data-station="${CSS.escape(this.focusStation)}"]`)?.scrollIntoView({block:"start"})}async send(t,n){let i=this.hass.states[t];if(!(this.readOnly||!i?.attributes.symcon_has_action||b(i)===null||this.pending.has(t))){this.pending=new Set([...this.pending,t]),this.error="";try{await this.hass.callService("symcon","set_value",{entity_id:t,value:n})}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.pending=new Set([...this.pending].filter(e=>e!==t))}}}control(t,n){if(!g(n?.command)&&!g(n?.feedback))return a;let i=g(n?.command)?n.command:null,e=i?this.hass.states[i]:void 0,o=e?.attributes,s=b(e),c=!!i&&!!o?.symcon_has_action&&s!==null&&!this.readOnly&&!this.pending.has(i),l=Number(o?.symcon_min??0),h=Number(o?.symcon_max??100),p=Number(o?.symcon_step||(o?.symcon_variable_type===1?1:.1)),u=z(e),m=$=>{let _=$.target;i&&_.value.trim()&&_.checkValidity()&&Number.isFinite(_.valueAsNumber)&&this.send(i,_.valueAsNumber)};return d`<fieldset data-control=${t}><legend>${t}</legend>${L(this.hass,t,n)}
|
||||
${i?d`<div class="reading"><span>Befehl / Sollwert</span><b>${U(e)}${X(this.hass,[i],`${t} \xB7 Sollwert`)}</b></div>
|
||||
${o?.symcon_variable_type===0?d`<div class="command"><button data-command=${i} ?disabled=${!c} @click=${()=>{this.send(i,!J(e))}}>${J(e)?"Ausschalten / Schlie\xDFen":"Einschalten / \xD6ffnen"}</button></div>`:[1,2].includes(Number(o?.symcon_variable_type))?d`<div class="command"><input type="range" aria-label=${`${t} Sollwert`} data-command=${i} min=${l} max=${h} step=${p} .value=${String(u??l)} ?disabled=${!c} @change=${m}/><input type="number" aria-label=${`${t} nativer Sollwert`} min=${l} max=${h} step=${p} .value=${u===null?"":String(u)} ?disabled=${!c} @change=${m}/></div>`:a}
|
||||
${this.readOnly?d`<p class="readonly">Historische Ansicht · nur Anzeige</p>`:o?.symcon_has_action?a:d`<p class="readonly">Nur Anzeige · keine Symcon-Schaltaktion hinterlegt</p>`}`:a}
|
||||
</fieldset>`}render(){if(!this.hass||!this.item)return a;let t=F(this.item),n=Wt(this.hass,this.item),i=this.item.type==="freshwater_station"?O(this.item):[];return d`<dialog @close=${()=>{this.remove(),x===this&&(x=null)}} @keydown=${e=>e.stopPropagation()}><header><h2>${Bt(this.item)}</h2><button aria-label="Schließen" @click=${()=>this.shadowRoot.querySelector("dialog").close()}>×</button></header><div class="body">
|
||||
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit" data-circuit=${e.id}><h3>${It(e)} <small>${Kt(this.hass,e)}</small></h3>${q(e)?this.control("Pumpe",e.pump):a}${Z(e)?this.control("Ventil",e.valve):a}${et(this.hass,e.flow,e.return).map(o=>H(this.hass,o))}${yt(this.hass,e.flow,e.return)}${f(this.hass,"Pumpenleistung",e.power)?H(this.hass,f(this.hass,"Pumpenleistung",e.power)):a}</section>`):a}
|
||||
${i.map((e,o)=>d`<details class="freshwater-unit" data-station=${e.id} ?open=${o===0||this.focusStation===e.id}><summary>${vt(e,o)}</summary>${qt(this.hass,e).map(s=>H(this.hass,s))}${yt(this.hass,e.flow,e.return)}${this.control("Ladepumpe",e.pump)}${T(e)?this.control("Kaskadenventil",e.valve):a}</details>`)}
|
||||
${n.map(e=>H(this.hass,e))}${this.item.type==="buffer_tank"?yt(this.hass,t.flow,t.return):a}
|
||||
`,$t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean}};render(){if(!this.hass||!this.item)return a;let t=z(this.item),n=qt(this.hass,this.item),i=this.item.type==="freshwater_station"?F(this.item):[];return d`<button class="title" @click=${()=>Bt(this.hass,this.item,this.readOnly)} aria-haspopup="dialog">${It(this.item)} ⚙</button><div class="content">${P(this.hass,t.status,"Anlagenstatus")}
|
||||
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit"><div class="circuit-name">${Kt(e)} <small>${Wt(this.hass,e)}</small></div>${P(this.hass,e.status)}${J(e)?V(this.hass,"Pumpe",e.pump):a}${X(e)?V(this.hass,"Ventil",e.valve):a}${nt(this.hass,e.flow,e.return).map(s=>H(this.hass,s))}${m(this.hass,"Leistung",e.power)?H(this.hass,m(this.hass,"Leistung",e.power)):a}</section>`):a}
|
||||
${i.length>1?d`<small class="cascade-count">Kaskade · ${i.length} Stationen</small>${i.map((e,s)=>{let o=A(this.hass,e.pump),c=m(this.hass,"Trinkwarmwasser",e.hot_water)||m(this.hass,"Vorlauf",e.flow);return d`<div class="station-summary" data-station=${e.id}><button class="station-name" @click=${()=>Bt(this.hass,this.item,this.readOnly,e.id)}><i class="lamp" title=${`Pumpe: ${o.id?L(this.hass.states[o.id]):"\u2013"}`} style=${`background:${o.running===null?"#888":o.running?"#6fe1a2":"#a82638"}`}></i>${xt(e,s)}</button><b>${c?.text||"\u2013"}</b>${c?D(this.hass,[c.id],`${xt(e,s)} \xB7 ${c.label}`):a}${P(this.hass,e.status)}</div>`})}`:i.map(e=>d`<section class="circuit">${P(this.hass,e.status)}${Zt(this.hass,e).map(s=>H(this.hass,s))}${V(this.hass,"Ladepumpe",e.pump)}${O(e)?V(this.hass,"Kaskadenventil",e.valve):a}</section>`)}
|
||||
${n.map(e=>H(this.hass,e))}${this.item.type==="freshwater_station"?V(this.hass,"Zirkulationspumpe",t.circulation):a}
|
||||
${this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"&&!n.length&&!f(t.status)?d`<p class="empty">Noch keine Fühler verknüpft</p>`:a}
|
||||
</div>`}static styles=[gt,Jt,y`.cascade-count{color:var(--nf-muted)}.station-summary{display:grid;grid-template-columns:minmax(0,1fr) auto 18px;align-items:center;gap:6px;width:100%;padding:5px 0;font-size:11px}.station-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:0;background:none;border:0;text-align:left}.station-summary>.status-reading{grid-column:1/-1}.station-summary b{white-space:nowrap;font-variant-numeric:tabular-nums}`]},_t=class extends v{static properties={hass:{attribute:!1},item:{attribute:!1},readOnly:{type:Boolean},focusStation:{attribute:!1},pending:{state:!0},error:{state:!0}};constructor(){super(),this.pending=new Set,this.error="",this.readOnly=!1}async show(){await this.updateComplete,this.shadowRoot.querySelector("dialog").showModal(),this.focusStation&&this.shadowRoot.querySelector(`[data-station="${CSS.escape(this.focusStation)}"]`)?.scrollIntoView({block:"start"})}async send(t,n){let i=this.hass.states[t];if(!(this.readOnly||!i?.attributes.symcon_has_action||b(i)===null||this.pending.has(t))){this.pending=new Set([...this.pending,t]),this.error="";try{await this.hass.callService("symcon","set_value",{entity_id:t,value:n})}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.pending=new Set([...this.pending].filter(e=>e!==t))}}}control(t,n){if(!f(n?.command)&&!f(n?.feedback))return a;let i=f(n?.command)?n.command:null,e=i?this.hass.states[i]:void 0,s=e?.attributes,o=b(e),c=!!i&&!!s?.symcon_has_action&&o!==null&&!this.readOnly&&!this.pending.has(i),l=Number(s?.symcon_min??0),h=Number(s?.symcon_max??100),p=Number(s?.symcon_step||(s?.symcon_variable_type===1?1:.1)),u=U(e),g=$=>{let _=$.target;i&&_.value.trim()&&_.checkValidity()&&Number.isFinite(_.valueAsNumber)&&this.send(i,_.valueAsNumber)};return d`<fieldset data-control=${t}><legend>${t}</legend>${V(this.hass,t,n)}
|
||||
${i?d`<div class="reading"><span>Befehl / Sollwert</span><b>${L(e)}${D(this.hass,[i],`${t} \xB7 Sollwert`)}</b></div>
|
||||
${s?.symcon_variable_type===0?d`<div class="command"><button data-command=${i} ?disabled=${!c} @click=${()=>{this.send(i,!Y(e))}}>${Y(e)?"Ausschalten / Schlie\xDFen":"Einschalten / \xD6ffnen"}</button></div>`:[1,2].includes(Number(s?.symcon_variable_type))?d`<div class="command"><input type="range" aria-label=${`${t} Sollwert`} data-command=${i} min=${l} max=${h} step=${p} .value=${String(u??l)} ?disabled=${!c} @change=${g}/><input type="number" aria-label=${`${t} nativer Sollwert`} min=${l} max=${h} step=${p} .value=${u===null?"":String(u)} ?disabled=${!c} @change=${g}/></div>`:a}
|
||||
${this.readOnly?d`<p class="readonly">Historische Ansicht · nur Anzeige</p>`:s?.symcon_has_action?a:d`<p class="readonly">Nur Anzeige · keine Symcon-Schaltaktion hinterlegt</p>`}`:a}
|
||||
</fieldset>`}render(){if(!this.hass||!this.item)return a;let t=z(this.item),n=qt(this.hass,this.item),i=this.item.type==="freshwater_station"?F(this.item):[];return d`<dialog @close=${()=>{this.remove(),x===this&&(x=null)}} @keydown=${e=>e.stopPropagation()}><header><h2>${It(this.item)}</h2><button aria-label="Schließen" @click=${()=>this.shadowRoot.querySelector("dialog").close()}>×</button></header><div class="body">${P(this.hass,t.status,"Anlagenstatus")}
|
||||
${this.item.type==="heating_manifold"?(t.circuits??[]).map(e=>d`<section class="circuit" data-circuit=${e.id}><h3>${Kt(e)} <small>${Wt(this.hass,e)}</small></h3>${P(this.hass,e.status)}${J(e)?this.control("Pumpe",e.pump):a}${X(e)?this.control("Ventil",e.valve):a}${nt(this.hass,e.flow,e.return).map(s=>H(this.hass,s))}${vt(this.hass,e.flow,e.return)}${m(this.hass,"Pumpenleistung",e.power)?H(this.hass,m(this.hass,"Pumpenleistung",e.power)):a}</section>`):a}
|
||||
${i.map((e,s)=>d`<details class="freshwater-unit" data-station=${e.id} ?open=${s===0||this.focusStation===e.id}><summary>${xt(e,s)}</summary>${P(this.hass,e.status)}${Zt(this.hass,e).map(o=>H(this.hass,o))}${vt(this.hass,e.flow,e.return)}${this.control("Ladepumpe",e.pump)}${O(e)?this.control("Kaskadenventil",e.valve):a}</details>`)}
|
||||
${n.map(e=>H(this.hass,e))}${this.item.type==="buffer_tank"?vt(this.hass,t.flow,t.return):a}
|
||||
${this.item.type==="freshwater_station"?this.control("Zirkulationspumpe",t.circulation):a}
|
||||
${!n.length&&this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"?d`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>`:a}
|
||||
${!n.length&&!f(t.status)&&this.item.type!=="heating_manifold"&&this.item.type!=="freshwater_station"?d`<p class="empty">Die Fühler lassen sich im Editor über den Objektbaum zuweisen.</p>`:a}
|
||||
${this.error?d`<p class="error" role="alert">${this.error}</p>`:a}
|
||||
</div></dialog>`}static styles=[mt,Zt,y`:host{max-width:none;min-width:0}.freshwater-unit{border-bottom:1px solid var(--nf-line);padding:8px 0}.freshwater-unit>summary{cursor:pointer;font-weight:600;padding:4px 0}`]},x=null;function en(){x?.remove(),x=null}async function jt(r,t,n=!1,i){x?.remove();let e=document.createElement("nf-hydronic-dialog");x=e,Object.assign(e,{hass:r,item:t,readOnly:n,focusStation:i}),document.body.append(e),await e.show()}function nn(r,t,n=!1){if(!x)return;let i=t.floors.flatMap(e=>e.furniture).find(e=>e.id===x.item.id);if(!i||!Dt(i.type)){x.remove(),x=null;return}Object.assign(x,{hass:r,item:i,readOnly:n})}customElements.get("nf-hydronic-card")||customElements.define("nf-hydronic-card",xt);customElements.get("nf-hydronic-dialog")||customElements.define("nf-hydronic-dialog",$t);export{en as closeHydronic,he as hydronicVisual,jt as openHydronic,nn as refreshHydronic};
|
||||
</div></dialog>`}static styles=[gt,Jt,y`:host{max-width:none;min-width:0}.freshwater-unit{border-bottom:1px solid var(--nf-line);padding:8px 0}.freshwater-unit>summary{cursor:pointer;font-weight:600;padding:4px 0}`]},x=null;function nn(){x?.remove(),x=null}async function Bt(r,t,n=!1,i){x?.remove();let e=document.createElement("nf-hydronic-dialog");x=e,Object.assign(e,{hass:r,item:t,readOnly:n,focusStation:i}),document.body.append(e),await e.show()}function rn(r,t,n=!1){if(!x)return;let i=t.floors.flatMap(e=>e.furniture).find(e=>e.id===x.item.id);if(!i||!Vt(i.type)){x.remove(),x=null;return}Object.assign(x,{hass:r,item:i,readOnly:n})}customElements.get("nf-hydronic-card")||customElements.define("nf-hydronic-card",$t);customElements.get("nf-hydronic-dialog")||customElements.define("nf-hydronic-dialog",_t);export{nn as closeHydronic,pe as hydronicVisual,Bt as openHydronic,rn as refreshHydronic};
|
||||
/*! Bundled license information:
|
||||
|
||||
@lit/reactive-element/css-tag.js:
|
||||
|
||||
@@ -16,16 +16,16 @@
|
||||
},
|
||||
{
|
||||
"type": "Button",
|
||||
"caption": "Designer in der Konsole öffnen",
|
||||
"caption": "Designer im Browser öffnen",
|
||||
"onClick": "echo NFSC_OpenDesigner($id);",
|
||||
"link": true
|
||||
},
|
||||
{
|
||||
"type": "Button",
|
||||
"caption": "Neuen Designer-Zugang erzeugen",
|
||||
"caption": "Alle Anmeldungen beenden und Designer öffnen",
|
||||
"onClick": "echo NFSC_RotateAccessToken($id);",
|
||||
"link": true,
|
||||
"confirm": "Alle aktuell offenen Designer- und Kachelansichten dieser Instanz müssen danach neu geladen werden. Fortfahren?"
|
||||
"confirm": "Alle Benutzer dieser Instanz werden abgemeldet. Der Designer wird anschließend im Browser neu geöffnet. Fortfahren?"
|
||||
}
|
||||
],
|
||||
"status": [
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Instance-local accounts and revocable HttpOnly sessions. Console actions are never exposed through the WebHook API. */
|
||||
trait NextFloorAccess
|
||||
{
|
||||
private ?array $requestUser = null;
|
||||
private ?array $requestScope = null;
|
||||
private const SESSION_TTL = 43200;
|
||||
private const SESSION_IDLE = 7200;
|
||||
|
||||
private function accessLock(callable $operation): mixed
|
||||
{
|
||||
$name = 'NextFloorAccess_' . $this->InstanceID;
|
||||
$native = function_exists('IPS_SemaphoreEnter');
|
||||
if ($native && !IPS_SemaphoreEnter($name, 3000)) throw new RuntimeException('access_busy');
|
||||
try { return $operation(); }
|
||||
finally { if ($native) IPS_SemaphoreLeave($name); }
|
||||
}
|
||||
|
||||
private function accounts(): array { return $this->jsonAttribute('Accounts', []); }
|
||||
|
||||
/** A short-lived, single-use console ticket; no reusable admin credential in browser URLs. */
|
||||
private function consoleUrl(): string
|
||||
{
|
||||
$ticket = $this->newToken();
|
||||
$this->accessLock(function () use ($ticket): void {
|
||||
$tickets = array_filter($this->jsonAttribute('ConsoleTickets', []), static fn(array $t): bool => $t['expires'] > time());
|
||||
$tickets = array_slice($tickets, -19, null, true);
|
||||
$tickets[hash('sha256', $ticket)] = ['expires' => time() + 90, 'epoch' => $this->ensureAccessToken()];
|
||||
$this->writeJsonAttribute('ConsoleTickets', $tickets);
|
||||
});
|
||||
return '/hook/' . $this->hookPath() . '/designer?mode=designer&ticket=' . rawurlencode($ticket);
|
||||
}
|
||||
|
||||
private function sessionCookie(): string { return 'NFSC_Session_' . $this->InstanceID; }
|
||||
private function loginCookie(): string { return 'NFSC_Login_' . $this->InstanceID; }
|
||||
|
||||
private function accessCookie(string $name, string $value, int $expires = 0): void
|
||||
{
|
||||
setcookie($name, $value, ['expires' => $expires, 'path' => '/hook/' . $this->hookPath() . '/',
|
||||
'secure' => $this->secureRequest(), 'httponly' => true, 'samesite' => 'Strict']);
|
||||
}
|
||||
|
||||
private function secureRequest(): bool
|
||||
{
|
||||
// A proxy header can only strengthen cookie protection, never turn native HTTPS off.
|
||||
return (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off') || ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https';
|
||||
}
|
||||
|
||||
private function createSession(string $accountID, array $account, bool $remember = false): array
|
||||
{
|
||||
$token = $this->newToken();
|
||||
$id = hash('sha256', $token);
|
||||
$session = ['account' => $accountID, 'epoch' => $account['epoch'], 'csrf' => $this->newToken(),
|
||||
'expires' => time() + ($remember ? 2592000 : self::SESSION_TTL), 'idle' => $remember ? 604800 : self::SESSION_IDLE, 'seen' => time()];
|
||||
// Called inside accessLock, including ticket exchange and password login.
|
||||
$sessions = array_filter($this->jsonAttribute('Sessions', []), static fn(array $s): bool => $s['expires'] > time() && $s['seen'] > time() - ($s['idle'] ?? self::SESSION_IDLE));
|
||||
if (count($sessions) >= 128) throw new RuntimeException('session_limit');
|
||||
$sessions[$id] = $session;
|
||||
$this->writeJsonAttribute('Sessions', $sessions);
|
||||
$this->accessCookie($this->sessionCookie(), $token, $remember ? $session['expires'] : 0);
|
||||
return [...$account, 'id' => $accountID, 'session_id' => $id, 'csrf' => $session['csrf']];
|
||||
}
|
||||
|
||||
private function resolveSession(): ?array
|
||||
{
|
||||
$token = $_COOKIE[$this->sessionCookie()] ?? '';
|
||||
if (!is_string($token) || preg_match('/^[a-f0-9]{64}$/D', $token) !== 1) return null;
|
||||
return $this->accessLock(function () use ($token): ?array {
|
||||
$id = hash('sha256', $token);
|
||||
$sessions = $this->jsonAttribute('Sessions', []);
|
||||
$s = $sessions[$id] ?? null;
|
||||
if (!$s || $s['expires'] <= time() || $s['seen'] <= time() - ($s['idle'] ?? self::SESSION_IDLE)) return null;
|
||||
$account = $s['account'] === '__console__' ? ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $this->ensureAccessToken()]
|
||||
: ($this->accounts()[$s['account']] ?? null);
|
||||
if (!$account || !$account['enabled'] || !hash_equals((string) $account['epoch'], (string) $s['epoch'])) return null;
|
||||
if ($s['seen'] < time() - 60) {
|
||||
$sessions[$id]['seen'] = time();
|
||||
$this->writeJsonAttribute('Sessions', $sessions);
|
||||
}
|
||||
return [...$account, 'id' => $s['account'], 'session_id' => $id, 'csrf' => $s['csrf']];
|
||||
});
|
||||
}
|
||||
|
||||
private function exchangeConsoleTicket(string $ticket): bool
|
||||
{
|
||||
if (preg_match('/^[a-f0-9]{64}$/D', $ticket) !== 1) return false;
|
||||
return $this->accessLock(function () use ($ticket): bool {
|
||||
$tickets = $this->jsonAttribute('ConsoleTickets', []);
|
||||
$key = hash('sha256', $ticket);
|
||||
$grant = $tickets[$key] ?? null;
|
||||
unset($tickets[$key]);
|
||||
$this->writeJsonAttribute('ConsoleTickets', $tickets);
|
||||
if (!$grant || $grant['expires'] <= time() || !hash_equals($this->ensureAccessToken(), $grant['epoch'])) return false;
|
||||
$this->requestUser = $this->createSession('__console__', ['name' => 'Symcon-Konsole', 'role' => 'admin', 'enabled' => true, 'epoch' => $grant['epoch']]);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
private function safeMode(): string { return ($_GET['mode'] ?? '') === 'tile' ? 'tile' : 'designer'; }
|
||||
private function entryUrl(string $tail = 'designer'): string { return '/hook/' . $this->hookPath() . '/' . $tail . '?mode=' . $this->safeMode(); }
|
||||
private function accessRedirect(string $url): void { header('Location: ' . $url, true, 303); header('Cache-Control: no-store'); }
|
||||
|
||||
private function validOrigin(): bool
|
||||
{
|
||||
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
|
||||
if ($origin === '') return true; // non-browser clients still require the CSRF value and session cookie
|
||||
$parts = parse_url($origin);
|
||||
if (!is_array($parts) || ($parts['scheme'] ?? '') !== ($this->secureRequest() ? 'https' : 'http')) return false;
|
||||
$authority = strtolower((string) ($parts['host'] ?? '') . (isset($parts['port']) ? ':' . $parts['port'] : ''));
|
||||
return $authority !== '' && hash_equals(strtolower((string) ($_SERVER['HTTP_HOST'] ?? '')), $authority);
|
||||
}
|
||||
|
||||
private function validCsrf(): bool
|
||||
{
|
||||
$value = $_SERVER['HTTP_X_NEXTFLOOR_CSRF'] ?? $_POST['csrf'] ?? '';
|
||||
return $this->requestUser !== null && is_string($value) && $value !== '' && $this->validOrigin()
|
||||
&& hash_equals($this->requestUser['csrf'], $value);
|
||||
}
|
||||
|
||||
/** Login stays a regular HTML form, including with JavaScript disabled and on small touch screens. */
|
||||
private function loginPage(string $error = '', int $status = 200): void
|
||||
{
|
||||
$csrf = $this->newToken();
|
||||
$this->accessCookie($this->loginCookie(), $csrf);
|
||||
$escape = static fn(string $s): string => htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
http_response_code($status);
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
header('Cache-Control: no-store');
|
||||
$configured = count(array_filter($this->accounts(), static fn(array $a): bool => $a['enabled'])) > 0;
|
||||
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
||||
. '<title>Anmelden · ' . $escape($this->viewTitle()) . '</title><style>html{color-scheme:dark}body{margin:0;min-height:100dvh;display:grid;place-items:center;background:#0c1320;color:#e6edf5;font:16px/1.5 system-ui}main{box-sizing:border-box;width:min(420px,calc(100% - 32px));padding:32px;background:#1b2432;border:1px solid #344255;border-radius:18px;box-shadow:0 16px 60px #0005}h1{margin:0 0 4px;font-size:25px}p{color:#aebdce}label{display:block;margin:18px 0 6px}input,button{box-sizing:border-box;width:100%;padding:12px 14px;border-radius:9px;border:1px solid #465872;font:inherit}input{background:#101a28;color:inherit}button{margin-top:24px;background:#1bb8e8;color:#061624;font-weight:700;cursor:pointer}input:focus,button:focus{outline:2px solid #45d0ff;outline-offset:3px}[role=alert]{padding:10px;background:#82353555;border-radius:8px;color:#ffc4c4}.note{font-size:13px}</style></head><body><main><h1>'
|
||||
. $escape($this->viewTitle()) . '</h1><p>Mit deinem NextFloor-Konto anmelden.</p>'
|
||||
. ($error !== '' ? '<p role="alert">' . $escape($error) . '</p>' : '')
|
||||
. ($configured ? '<form method="post" action="' . $escape($this->entryUrl('login')) . '"><input type="hidden" name="csrf" value="' . $csrf . '">'
|
||||
. '<label for="username">Benutzername</label><input id="username" name="username" autocomplete="username" required maxlength="64" autofocus>'
|
||||
. '<label for="password">Passwort</label><input id="password" name="password" type="password" autocomplete="current-password" required maxlength="72">'
|
||||
. '<label style="display:flex;gap:9px;align-items:center;font-size:14px"><input style="width:auto" type="checkbox" name="remember" value="1">Angemeldet bleiben (30 Tage)</label><button type="submit">Anmelden</button></form><p class="note">Passwort vergessen? Der Symcon-Administrator kann es in der NextFloor-Instanz zurücksetzen.</p>'
|
||||
: '<p role="status">Noch kein Benutzer eingerichtet. Lege in der Symcon-Konfiguration der NextFloor-Instanz zuerst einen Benutzer mit Passwort an.</p>')
|
||||
. '</main></body></html>';
|
||||
}
|
||||
|
||||
private function passwordLogin(): void
|
||||
{
|
||||
$csrf = $_POST['csrf'] ?? '';
|
||||
$nonce = $_COOKIE[$this->loginCookie()] ?? '';
|
||||
if (!$this->validOrigin() || !is_string($csrf) || !is_string($nonce) || strlen($nonce) !== 64 || !hash_equals($nonce, $csrf)) {
|
||||
$this->loginPage('Die Anmeldung ist abgelaufen. Bitte erneut versuchen.', 403);
|
||||
return;
|
||||
}
|
||||
$name = is_string($_POST['username'] ?? null) ? mb_strtolower(trim($_POST['username'])) : '';
|
||||
$password = is_string($_POST['password'] ?? null) ? $_POST['password'] : '';
|
||||
$result = $this->accessLock(function () use ($name, $password): string {
|
||||
$now = time();
|
||||
$limits = array_filter($this->jsonAttribute('LoginThrottle', []), static fn(array $v): bool => $v['until'] > time());
|
||||
$ipKey = 'ip:' . hash('sha256', (string) ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
|
||||
$nameKey = 'name:' . hash('sha256', $name);
|
||||
if (($limits[$ipKey]['count'] ?? 0) >= 40 || ($limits[$nameKey]['count'] ?? 0) >= 8) return 'limited';
|
||||
$found = null;
|
||||
foreach ($this->accounts() as $id => $a) if (mb_strtolower($a['name']) === $name) { $found = [$id, $a]; break; }
|
||||
// Use the same platform algorithm/cost for an unknown username as for real accounts.
|
||||
$hash = $found[1]['password'] ?? $this->ReadAttributeString('LoginDummyHash');
|
||||
$valid = strlen($password) <= 72 && !str_contains($password, "\0") && password_verify($password, $hash);
|
||||
if (!$valid || !$found || !$found[1]['enabled']) {
|
||||
foreach ([$ipKey, $nameKey] as $key) $limits[$key] = ['count' => ($limits[$key]['count'] ?? 0) + 1, 'until' => $limits[$key]['until'] ?? $now + 900];
|
||||
$this->writeJsonAttribute('LoginThrottle', array_slice($limits, -1024, null, true));
|
||||
return 'invalid';
|
||||
}
|
||||
unset($limits[$nameKey]);
|
||||
$this->writeJsonAttribute('LoginThrottle', $limits);
|
||||
$this->requestUser = $this->createSession($found[0], $found[1], ($_POST['remember'] ?? '') === '1');
|
||||
return 'ok';
|
||||
});
|
||||
if ($result !== 'ok') { $this->loginPage($result === 'limited' ? 'Zu viele Anmeldeversuche. Bitte in 15 Minuten erneut versuchen.' : 'Benutzername oder Passwort ist ungültig.', $result === 'limited' ? 429 : 401); return; }
|
||||
$this->accessCookie($this->loginCookie(), '', time() - 3600);
|
||||
$this->accessRedirect($this->entryUrl());
|
||||
}
|
||||
|
||||
private function logoutSession(): void
|
||||
{
|
||||
$id = $this->requestUser['session_id'] ?? '';
|
||||
$this->accessLock(function () use ($id): void {
|
||||
$sessions = $this->jsonAttribute('Sessions', []); unset($sessions[$id]); $this->writeJsonAttribute('Sessions', $sessions);
|
||||
});
|
||||
$this->accessCookie($this->sessionCookie(), '', time() - 3600);
|
||||
$this->requestUser = null;
|
||||
$this->accessRedirect($this->entryUrl('login'));
|
||||
}
|
||||
|
||||
private function publicAccess(): array
|
||||
{
|
||||
$admin = $this->requestUser['role'] === 'admin';
|
||||
$canControl = $admin || ($this->requestUser['control_all'] ?? false);
|
||||
foreach (['rooms', 'devices', 'objects'] as $group) foreach ($this->requestUser[$group] ?? [] as $g) if (($g['access'] ?? '') === 'control') $canControl = true;
|
||||
return ['id' => $this->requestUser['id'], 'name' => $this->requestUser['name'], 'is_admin' => $admin,
|
||||
'view_all' => $admin || ($this->requestUser['view_all'] ?? false), 'control_all' => $admin || ($this->requestUser['control_all'] ?? false), 'can_control' => $canControl];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
class NextFloorDenied extends RuntimeException {}
|
||||
|
||||
/** Deny by default; project geometry and live data are separate capabilities. */
|
||||
trait NextFloorPermissions
|
||||
{
|
||||
private const REF_FIELDS = ['entity', 'entity_id', 'device', 'tracker', 'power', 'energy', 'temperature', 'humidity', 'co2', 'illuminance',
|
||||
'supply_vsr', 'extract_vsr', 'supply_temperature', 'extract_temperature', 'reheat', 'status', 'schedules',
|
||||
'floor_heating', 'clean_entity', 'panel', 'hidden', 'no_state', 'cover', 'cover2', 'cover_tilt', 'cover2_tilt',
|
||||
'contact', 'contact2', 'tilt', 'tilt2', 'position', 'tilt_angle', 'lock', 'door_left', 'door_right', 'soc', 'charge', 'export',
|
||||
'gang_entities', 'flow', 'return', 'command', 'feedback', 'circulation_temperature', 'hot_water', 'cold_water',
|
||||
'start', 'end', 'duration', 'start_time', 'end_time', 'charging_time', 'charged_energy', 'lock_status', 'range', 'charging', 'plugged', 'departure',
|
||||
'grid', 'solar', 'battery', 'battery_soc', 'consumption', 'tariff', 'meter', 'favorites', 'condition', 'pressure', 'wind_speed', 'wind_gust_speed', 'wind_bearing',
|
||||
'cloud_coverage', 'precipitation', 'precipitation_total', 'uv_index', 'visibility', 'snow', 'fog', 'lightning'];
|
||||
private const REF_GROUPS = ['climate', 'hvac', 'utility_meters', 'electricity', 'water', 'gas', 'heating', 'cooling',
|
||||
'values', 'charging', 'hydronic', 'circuits', 'sensors', 'stations', 'pump', 'valve', 'circulation', 'show_when', 'car', 'gates', 'settings', 'presence', 'weather_variables'];
|
||||
|
||||
private function refKey(string $key): bool { return in_array($key, self::REF_FIELDS, true) || preg_match('/_(?:entit(?:y\d*|ies)|sensor\d*)$/D', $key) === 1; }
|
||||
private function entityRefs(array $node): array
|
||||
{
|
||||
$ids = [];
|
||||
foreach ($node as $key => $value) {
|
||||
if (!is_int($key) && !$this->refKey($key) && !in_array($key, self::REF_GROUPS, true)) continue;
|
||||
if (is_string($value) && $this->variableIdForEntity($value) !== null) $ids[] = $this->variableIdForEntity($value);
|
||||
if (is_array($value)) $ids = [...$ids, ...$this->entityRefs($value)];
|
||||
}
|
||||
return array_values(array_unique($ids));
|
||||
}
|
||||
|
||||
private function planKey(string $kind, array $floor, string $id): string { return $kind . ':' . rawurlencode((string) $floor['id']) . ':' . rawurlencode($id); }
|
||||
|
||||
/** Keep existing grants on uniquely identified rooms/devices when an admin moves them to another floor. */
|
||||
private function migrateMovedPlanGrants(array $before, array $after): void
|
||||
{
|
||||
$index = function (array $plan): array {
|
||||
$result = [];
|
||||
foreach ($plan['floors'] ?? [] as $floor) foreach (['rooms', 'furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
|
||||
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
|
||||
if ($id === '') continue;
|
||||
$kind = $group === 'rooms' ? 'room' : $group;
|
||||
$result[$kind . ':' . $id][] = $this->planKey($kind, $floor, $id);
|
||||
}
|
||||
return $result;
|
||||
};
|
||||
$old = $index($before); $new = $index($after); $moves = [];
|
||||
foreach ($old as $id => $keys) if (count($keys) === 1 && count($new[$id] ?? []) === 1 && $keys[0] !== $new[$id][0]) $moves[$keys[0]] = $new[$id][0];
|
||||
if ($moves === []) return;
|
||||
$accounts = $this->accounts(); $changed = false;
|
||||
foreach ($accounts as &$account) foreach (['rooms', 'devices'] as $group) {
|
||||
$rows = [];
|
||||
foreach ($account[$group] ?? [] as $row) {
|
||||
$target = (string) $row['target'];
|
||||
if (isset($moves[$target])) { $target = $moves[$target]; $changed = true; }
|
||||
$level = $row['access'] === 'control' || ($rows[$target]['access'] ?? '') === 'control' ? 'control' : 'view';
|
||||
$rows[$target] = ['target' => $target, 'access' => $level];
|
||||
}
|
||||
$account[$group] = array_values($rows);
|
||||
}
|
||||
unset($account);
|
||||
if ($changed) { $this->writeJsonAttribute('Accounts', $accounts); $this->requestScope = null; }
|
||||
}
|
||||
|
||||
private function accessCatalog(): array
|
||||
{
|
||||
$rooms = []; $devices = [];
|
||||
$building = $this->building();
|
||||
$topology = $building['topology'] ?? [];
|
||||
$find = static function (string $group, ?string $id) use ($topology): array {
|
||||
foreach ($topology[$group] ?? [] as $row) if ($row['id'] === $id) return $row;
|
||||
return [];
|
||||
};
|
||||
foreach ($building['floors'] ?? [] as $floor) {
|
||||
$group = $find('buildings', $floor['outdoor_building_id'] ?? $floor['building_id'] ?? null);
|
||||
$branch = $find('branches', $floor['outdoor_branch_id'] ?? $group['branch_id'] ?? null);
|
||||
$location = $find('locations', $floor['outdoor_location_id'] ?? $branch['location_id'] ?? null);
|
||||
$parts = [$location['name'] ?? '', $branch['name'] ?? '', $group['name'] ?? '', $floor['name'] ?? 'Etage'];
|
||||
$prefix = implode(' / ', array_filter($parts, static fn(string $v): bool => $v !== '')) . ' / ';
|
||||
foreach ($floor['rooms'] ?? [] as $room) $rooms[] = ['caption' => $prefix . ($room['name'] ?? $room['id']), 'value' => $this->planKey('room', $floor, (string) $room['id'])];
|
||||
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
|
||||
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
|
||||
if ($id === '') continue;
|
||||
$room = $this->itemRoom($floor, $item);
|
||||
$label = trim((string) ($item['name'] ?? ''));
|
||||
if ($label === '' && ($native = $this->variableIdForEntity($id)) !== null && IPS_ObjectExists($native)) {
|
||||
$parts = []; $at = $native; $seen = [];
|
||||
while ($at > 0 && IPS_ObjectExists($at) && count($parts) < 3 && !isset($seen[$at])) {
|
||||
$seen[$at] = true; array_unshift($parts, IPS_GetName($at)); $at = (int) IPS_GetObject($at)['ParentID'];
|
||||
}
|
||||
$label = implode(' / ', $parts);
|
||||
}
|
||||
if ($label === '') $label = str_replace('_', ' ', (string) ($item['type'] ?? 'Gerät'));
|
||||
$devices[] = ['caption' => $prefix . ($room ? ($room['name'] ?? '') . ' / ' : '') . $label, 'value' => $this->planKey($group, $floor, $id)];
|
||||
}
|
||||
}
|
||||
return ['rooms' => $rooms, 'devices' => $devices];
|
||||
}
|
||||
|
||||
private function insideRoom(float $x, float $z, array $points): bool
|
||||
{
|
||||
$inside = false; $count = count($points);
|
||||
for ($i = 0, $j = $count - 1; $i < $count; $j = $i++) {
|
||||
[$xi, $zi] = $points[$i]; [$xj, $zj] = $points[$j];
|
||||
if (($zi > $z) !== ($zj > $z) && $x < ($xj - $xi) * ($z - $zi) / ($zj - $zi) + $xi) $inside = !$inside;
|
||||
}
|
||||
return $inside;
|
||||
}
|
||||
|
||||
private function itemRoom(array $floor, array $item): ?array
|
||||
{
|
||||
foreach ($floor['rooms'] ?? [] as $room) {
|
||||
if (isset($item['room_id']) ? $item['room_id'] === $room['id'] : (isset($item['x'], $item['z']) && $this->insideRoom((float) $item['x'], (float) $item['z'], $room['points'] ?? []))) return $room;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private function grantMap(array $grants): array
|
||||
{
|
||||
$map = [];
|
||||
foreach ($grants as $g) if (in_array($g['access'] ?? '', ['view', 'control'], true)) $map[(string) $g['target']] = $g['access'];
|
||||
return $map;
|
||||
}
|
||||
|
||||
private function isAdministrator(): bool { return ($this->requestUser['role'] ?? '') === 'admin'; }
|
||||
|
||||
private function scope(?array $tree = null): array
|
||||
{
|
||||
if ($this->requestScope !== null) return $this->requestScope;
|
||||
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
|
||||
$user = $this->requestUser;
|
||||
$all = $this->isAdministrator();
|
||||
$scope = ['view_all' => $all || ($user['view_all'] ?? false) || ($user['control_all'] ?? false), 'control_all' => $all || ($user['control_all'] ?? false),
|
||||
'read' => [], 'write' => [], 'native_read' => [], 'entities' => [], 'rooms' => $this->grantMap($user['rooms'] ?? []), 'devices' => $this->grantMap($user['devices'] ?? [])];
|
||||
if ($all) return $this->requestScope = $scope;
|
||||
$tree ??= $this->objectTree();
|
||||
$parents = []; $native = [];
|
||||
foreach ($tree['objects'] as $o) $parents[(int) $o['object_id']] = (int) $o['parent_id'];
|
||||
foreach ($tree['variables'] as $v) {
|
||||
$native[(int) $v['attributes']['symcon_id']] = true;
|
||||
$scope['entities'][(int) $v['attributes']['symcon_id']] = $v['entity_id'];
|
||||
}
|
||||
$descendantCache = [];
|
||||
$descendants = static function (int $root) use ($native, $parents, &$descendantCache): array {
|
||||
if (isset($descendantCache[$root])) return $descendantCache[$root];
|
||||
$ids = [];
|
||||
foreach ($native as $id => $_) {
|
||||
$at = $id; $seen = [];
|
||||
while ($at > 0 && !isset($seen[$at])) {
|
||||
if ($at === $root) { $ids[] = $id; break; }
|
||||
$seen[$at] = true; $at = $parents[$at] ?? 0;
|
||||
}
|
||||
}
|
||||
return $descendantCache[$root] = $ids;
|
||||
};
|
||||
$allow = static function (array $ids, string $level, bool $explicit = false) use (&$scope, $native): void {
|
||||
foreach ($ids as $id) if (isset($native[$id])) {
|
||||
$scope['read'][$id] = true;
|
||||
if ($level === 'control') $scope['write'][$id] = true;
|
||||
if ($explicit) $scope['native_read'][$id] = true;
|
||||
}
|
||||
};
|
||||
foreach ($user['objects'] ?? [] as $g) {
|
||||
$target = (int) $g['target']; $seen = [];
|
||||
while (IPS_ObjectExists($target) && (int) IPS_GetObject($target)['ObjectType'] === 6 && !isset($seen[$target])) {
|
||||
$seen[$target] = true; $target = (int) IPS_GetLink($target)['TargetID'];
|
||||
}
|
||||
$allow($descendants($target), $g['access'], true);
|
||||
}
|
||||
foreach ($this->building()['floors'] ?? [] as $floor) {
|
||||
foreach ($floor['rooms'] ?? [] as $room) {
|
||||
$key = $this->planKey('room', $floor, (string) $room['id']);
|
||||
$own = $scope['rooms'][$key] ?? null;
|
||||
$level = $scope['control_all'] || $own === 'control' ? 'control' : ($scope['view_all'] ? 'view' : $own);
|
||||
if ($level === null) continue;
|
||||
$scope['rooms'][$key] = $level;
|
||||
$allow($this->entityRefs($room), $level);
|
||||
foreach ([$room['area_id'] ?? '', ...($room['sub_areas'] ?? [])] as $area) if (preg_match('/^symcon-category-(\d+)$/D', (string) $area, $m) === 1) $allow($descendants((int) $m[1]), $level);
|
||||
}
|
||||
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $item) {
|
||||
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
|
||||
$own = $scope['devices'][$this->planKey($group, $floor, $id)] ?? null;
|
||||
$room = $this->itemRoom($floor, $item);
|
||||
$inherited = $room ? ($scope['rooms'][$this->planKey('room', $floor, (string) $room['id'])] ?? null) : null;
|
||||
$level = $scope['control_all'] || $own === 'control' || $inherited === 'control' ? 'control' : ($own ?? $inherited ?? ($scope['view_all'] ? 'view' : null));
|
||||
if ($level !== null) { $scope['devices'][$this->planKey($group, $floor, $id)] = $level; $allow($this->entityRefs($item), $level); }
|
||||
}
|
||||
if ($scope['view_all']) {
|
||||
$allow($this->entityRefs($floor), $scope['control_all'] ? 'control' : 'view');
|
||||
foreach ($floor['outdoor'] ?? [] as $area) $allow($this->entityRefs($area), $scope['control_all'] ? 'control' : 'view');
|
||||
}
|
||||
}
|
||||
if ($scope['view_all']) $allow($this->entityRefs($this->building()), $scope['control_all'] ? 'control' : 'view');
|
||||
return $this->requestScope = $scope;
|
||||
}
|
||||
|
||||
private function allowedEntity(string $entity, bool $write): bool
|
||||
{
|
||||
$id = $this->variableIdForEntity($entity);
|
||||
if ($id === null) return false;
|
||||
$s = $this->scope();
|
||||
return $this->isAdministrator() || ($write ? isset($s['write'][$id]) : isset($s['read'][$id]));
|
||||
}
|
||||
|
||||
/** Authorize every target before the first write: mixed bulk commands cannot partially execute. */
|
||||
private function authorizeApi(string $action, array $request): void
|
||||
{
|
||||
if ($this->requestUser === null) throw new NextFloorDenied('authentication_required');
|
||||
$read = ['bootstrap', 'variables/snapshot', 'archive/trend', 'building/get', 'image/get', 'packs/list', 'transport/read', 'transport/release'];
|
||||
if (!$this->isAdministrator() && !in_array($action, [...$read, 'variables/action'], true)) throw new NextFloorDenied('admin_required');
|
||||
if ($action === 'archive/trend' && (!is_string($request['entity_id'] ?? null) || !$this->allowedEntity($request['entity_id'], false))) throw new NextFloorDenied('read_forbidden');
|
||||
if ($action === 'variables/action') {
|
||||
$targets = $request['data']['entity_id'] ?? [];
|
||||
$targets = is_array($targets) ? $targets : [$targets];
|
||||
if (!$targets || count($targets) > 256) throw new NextFloorDenied('invalid_targets');
|
||||
foreach ($targets as $target) {
|
||||
if (!is_string($target) || !$this->allowedEntity($target, true)) throw new NextFloorDenied('control_forbidden');
|
||||
$id = $this->variableIdForEntity($target);
|
||||
if (!$this->isAdministrator() && IPS_VariableExists($id)) {
|
||||
$v = IPS_GetVariable($id); $actionID = (int) ($v['VariableCustomAction'] ?: $v['VariableAction']);
|
||||
if ($actionID <= 0) throw new NextFloorDenied('variable_readonly');
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($action === 'image/get' && !$this->isAdministrator()) {
|
||||
$id = is_string($request['image_id'] ?? null) ? $request['image_id'] : '';
|
||||
$images = [];
|
||||
$visible = $this->visibleBuilding();
|
||||
array_walk_recursive($visible, static function (mixed $value, mixed $key) use (&$images): void {
|
||||
if (!is_string($value)) return;
|
||||
if ($key === 'image_id') $images[] = $value;
|
||||
elseif (is_string($key) && preg_match('/^(?:picture|image|url|.*_image)$/D', $key) && str_starts_with($value, 'image:')) $images[] = substr($value, 6);
|
||||
});
|
||||
if ($id === '' || !in_array($id, $images, true)) throw new NextFloorDenied('image_forbidden');
|
||||
}
|
||||
}
|
||||
|
||||
private function visibleTree(array $tree): array
|
||||
{
|
||||
if ($this->isAdministrator()) return $tree;
|
||||
$scope = $this->scope($tree);
|
||||
$variables = [];
|
||||
foreach ($tree['variables'] as $v) {
|
||||
$id = (int) $v['attributes']['symcon_id'];
|
||||
if (!isset($scope['read'][$id])) continue;
|
||||
$can = isset($scope['write'][$id]) && (($v['attributes']['symcon_schedule'] ?? false) || ($v['attributes']['symcon_has_action'] ?? false));
|
||||
$v['attributes']['symcon_can_control'] = $can;
|
||||
if (!$can) $v['attributes']['symcon_has_action'] = false;
|
||||
$variables[] = $v;
|
||||
}
|
||||
$areaIDs = array_fill_keys(array_filter(array_column($variables, 'area_id'), 'is_string'), true);
|
||||
$areas = array_filter($tree['areas'], static fn(array $a): bool => isset($areaIDs[$a['area_id']]));
|
||||
// Utility discovery also needs topology (e.g. Büro / Strom / Leistung). Keep only permitted
|
||||
// variable nodes and their ancestors; never expose unrelated branches or variable values.
|
||||
$nodes = [];
|
||||
foreach ($tree['objects'] as $node) $nodes[(int) $node['object_id']] = $node;
|
||||
$keep = [];
|
||||
foreach ($variables as $v) {
|
||||
$at = (int) $v['attributes']['symcon_id'];
|
||||
while ($at > 0 && isset($nodes[$at]) && !isset($keep[$at])) {
|
||||
$keep[$at] = true; $at = (int) $nodes[$at]['parent_id'];
|
||||
}
|
||||
}
|
||||
$objects = array_values(array_filter($tree['objects'], static fn(array $node): bool => isset($keep[(int) $node['object_id']])));
|
||||
return ['variables' => $variables, 'areas' => array_values($areas), 'objects' => $objects];
|
||||
}
|
||||
|
||||
private function maskRefs(array $node, array $allow): array
|
||||
{
|
||||
foreach ($node as $key => $v) {
|
||||
// Strip unknown/legacy binding fields too. Geometry identifiers and captions are not live bindings.
|
||||
if (in_array($key, ['id', 'name', 'type', 'label', 'icon', 'room_id', 'area_id', 'parent_meter', 'buffer_id'], true)) continue;
|
||||
if (is_string($v) && ($id = $this->variableIdForEntity($v)) !== null && !isset($allow[$id])) $node[$key] = 'none';
|
||||
elseif (is_array($v)) $node[$key] = $this->maskRefs($v, $allow);
|
||||
}
|
||||
return $node;
|
||||
}
|
||||
|
||||
private function visibleBuilding(): array
|
||||
{
|
||||
$building = $this->building();
|
||||
if ($this->isAdministrator()) return $building;
|
||||
$s = $this->scope();
|
||||
// Admin-owned executable UI configuration is never part of a user view.
|
||||
$building['settings']['plugins'] = []; $building['settings']['buttons'] = [];
|
||||
foreach (['custom_buttons', 'media_presets', 'announce_phrases'] as $key) unset($building['settings'][$key]);
|
||||
foreach ($building['floors'] as &$floor) {
|
||||
$panels = [];
|
||||
foreach (['furniture', 'openings', 'placements'] as $group) foreach ($floor[$group] ?? [] as $i => $item) {
|
||||
$id = (string) ($item['id'] ?? $item['entity_id'] ?? '');
|
||||
$granted = $s['view_all'] || isset($s['devices'][$this->planKey($group, $floor, $id)]);
|
||||
$filtered = $granted ? $item : $this->maskRefs($item, $s['native_read']);
|
||||
unset($filtered['tap']);
|
||||
if (!$granted) {
|
||||
unset($filtered['show_when'], $filtered['pictures'], $filtered['screen_pictures'], $filtered['picture']);
|
||||
if (empty($item['entity'])) $filtered['entity'] = 'none';
|
||||
if (!$this->entityRefs($filtered)) { $filtered['power_card'] = false; $filtered['hydronic']['card'] = false; }
|
||||
}
|
||||
$floor[$group][$i] = $filtered;
|
||||
$room = $this->itemRoom($floor, $item);
|
||||
if ($room) foreach ($this->entityRefs($filtered) as $native) $panels[$room['id']][$native] = true;
|
||||
}
|
||||
foreach ($floor['rooms'] as &$room) {
|
||||
$key = $this->planKey('room', $floor, (string) $room['id']);
|
||||
if ($s['view_all'] || isset($s['rooms'][$key])) continue;
|
||||
$room = $this->maskRefs($room, []);
|
||||
$room['area_id'] = null; $room['sub_areas'] = []; $room['climate_card'] = false;
|
||||
$room['symcon_read_room'] = false;
|
||||
$room['climate'] = ['temperature' => 'none', 'humidity' => 'none', 'co2' => 'none', 'illuminance' => 'none'];
|
||||
$room['hvac'] = null; $room['utility_meters'] = null; $room['moods'] = []; $room['floor_heating'] = 'none';
|
||||
$room['panel'] = array_values(array_filter(array_map(static fn(int $id): ?string => $s['entities'][$id] ?? null, array_keys($panels[$room['id']] ?? []))));
|
||||
}
|
||||
unset($room);
|
||||
if (!$s['view_all']) { $floor['power_entity'] = 'none'; $floor['utility_meters'] = null; }
|
||||
foreach ($floor['outdoor'] ?? [] as $i => $area) if (!$s['view_all']) {
|
||||
$floor['outdoor'][$i] = $this->maskRefs($area, $s['native_read']); $floor['outdoor'][$i]['area_id'] = null;
|
||||
}
|
||||
}
|
||||
unset($floor);
|
||||
if (!$s['view_all']) {
|
||||
$building['presence'] = []; $building['energy'] = []; $building['settings']['weather_variables'] = [];
|
||||
foreach ($building['settings'] as $key => $value) if (is_string($value) && $this->variableIdForEntity($value) !== null) $building['settings'][$key] = 'none';
|
||||
}
|
||||
return $building;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/** Native Symcon 9.0 configuration. Password fields are actions, never persistent module properties. */
|
||||
trait NextFloorUsers
|
||||
{
|
||||
public function GetConfigurationForm(): string
|
||||
{
|
||||
$form = json_decode((string) file_get_contents(__DIR__ . '/../form.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$id = $this->ReadAttributeString('SelectedAccount');
|
||||
$account = $this->accounts()[$id] ?? [];
|
||||
$catalog = $this->accessCatalog();
|
||||
$level = ['type' => 'Select', 'options' => [['caption' => 'Nur ansehen', 'value' => 'view'], ['caption' => 'Ansehen und bedienen', 'value' => 'control']]];
|
||||
$grants = function (string $name, string $caption, array $options, array $values): array {
|
||||
return ['type' => 'List', 'name' => $name, 'caption' => $caption, 'rowCount' => 5, 'add' => true, 'delete' => true, 'values' => $values,
|
||||
'columns' => $this->planGrantColumns($options, $values)];
|
||||
};
|
||||
$userForm = ['type' => 'ExpansionPanel', 'caption' => 'Benutzer und Zugriffsrechte', 'expanded' => true, 'items' => [
|
||||
['type' => 'ValidationTextBox', 'caption' => 'Direkter Zugang (an die Symcon-Adresse anhängen)', 'value' => '/hook/' . $this->hookPath() . '/', 'enabled' => false],
|
||||
['type' => 'Button', 'caption' => 'Anmeldeseite öffnen', 'link' => true, 'onClick' => 'echo NFSC_OpenLogin($id);'],
|
||||
['type' => 'Select', 'name' => 'AccountSelect', 'caption' => 'Benutzer auswählen', 'value' => $id, 'options' => $this->accountOptions(), 'onChange' => 'NFSC_SelectAccessUser($id, $AccountSelect);'],
|
||||
['type' => 'ValidationTextBox', 'name' => 'AccountName', 'caption' => 'Benutzername', 'value' => $account['name'] ?? ''],
|
||||
['type' => 'PasswordTextBox', 'name' => 'AccountPassword', 'caption' => 'Neues Passwort (leer = bestehendes behalten)', 'value' => ''],
|
||||
['type' => 'Button', 'name' => 'AccountReset', 'caption' => 'Passwort zurücksetzen', 'enabled' => $id !== '', 'onClick' => 'echo NFSC_ResetUserPassword($id, $AccountSelect, $AccountPassword);'],
|
||||
['type' => 'CheckBox', 'name' => 'AccountEnabled', 'caption' => 'Zugang aktiv', 'value' => $account['enabled'] ?? true],
|
||||
['type' => 'Select', 'name' => 'AccountRole', 'caption' => 'Rolle', 'value' => $account['role'] ?? 'user', 'options' => [['caption' => 'Benutzer · Ansicht und freigegebene Bedienung', 'value' => 'user'], ['caption' => 'Admin · vollständiger Zugriff und Editor', 'value' => 'admin']]],
|
||||
['type' => 'CheckBox', 'name' => 'AccountViewAll', 'caption' => 'Alle Zustände ansehen', 'value' => $account['view_all'] ?? false],
|
||||
['type' => 'CheckBox', 'name' => 'AccountControlAll', 'caption' => 'Alles ansehen und bedienen', 'value' => $account['control_all'] ?? false],
|
||||
$grants('AccountRooms', 'Einzelne Räume', $catalog['rooms'], $account['rooms'] ?? []),
|
||||
$grants('AccountDevices', 'Einzelne Geräte im Plan', $catalog['devices'], $account['devices'] ?? []),
|
||||
['type' => 'List', 'name' => 'AccountObjects', 'caption' => 'Weitere Symcon-Geräte / Datenpunkte (optional)', 'rowCount' => 4, 'add' => true, 'delete' => true, 'values' => $account['objects'] ?? [],
|
||||
'columns' => [['name' => 'target', 'caption' => 'Objekt aus dem Objektbaum', 'width' => 'auto', 'add' => 0, 'edit' => ['type' => 'SelectObject']],
|
||||
['name' => 'access', 'caption' => 'Recht', 'width' => '190px', 'add' => 'view', 'edit' => $level]]],
|
||||
['type' => 'Button', 'caption' => 'Benutzer speichern', 'onClick' => [
|
||||
// Native List variables implement iteration/ArrayAccess; direct JSON encoding does not serialize their rows.
|
||||
'$rooms = []; foreach ($AccountRooms as $row) { $rooms[] = ["target" => $row["target"], "access" => $row["access"]]; }',
|
||||
'$devices = []; foreach ($AccountDevices as $row) { $devices[] = ["target" => $row["target"], "access" => $row["access"]]; }',
|
||||
'$objects = []; foreach ($AccountObjects as $row) { $objects[] = ["target" => $row["target"], "access" => $row["access"]]; }',
|
||||
'echo NFSC_SaveAccessUser($id, $AccountSelect, $AccountName, $AccountRole, $AccountEnabled, $AccountViewAll, $AccountControlAll, json_encode($rooms), json_encode($devices), json_encode($objects), $AccountPassword);',
|
||||
]],
|
||||
['type' => 'Button', 'name' => 'AccountRevoke', 'caption' => 'Benutzer abmelden', 'enabled' => $id !== '', 'onClick' => 'echo NFSC_RevokeUserSessions($id, $AccountSelect);'],
|
||||
['type' => 'Button', 'name' => 'AccountDelete', 'caption' => 'Benutzer löschen', 'enabled' => $id !== '', 'confirm' => 'Diesen NextFloor-Benutzer einschließlich seiner Zugänge löschen?', 'onClick' => 'echo NFSC_DeleteAccessUser($id, $AccountSelect);'],
|
||||
['type' => 'PopupButton', 'caption' => 'ⓘ Rechte und Passwörter', 'popup' => ['caption' => 'Zugriffsrechte', 'items' => [
|
||||
['type' => 'Label', 'caption' => 'Die Auswahl eines Benutzers lädt dessen Einstellungen und alle drei Freigabetabellen. Änderungen werden erst durch Benutzer speichern übernommen; beim Wechsel werden nicht gespeicherte Eingaben verworfen. Das Passwortfeld wird bei jedem Wechsel geleert.'],
|
||||
['type' => 'Label', 'caption' => 'Admins dürfen den Editor und alle Geräte verwenden. Die Benutzerverwaltung bleibt ausschließlich in der Symcon-Konfiguration.'],
|
||||
['type' => 'Label', 'caption' => 'Alle Zustände ansehen ohne weitere Bedienfreigabe ist ein Zugang nur zum Lesen. Einzelne Raum- und Gerätefreigaben ergänzen diese Grundrechte. Ohne Freigabe bleibt das Gebäude sichtbar, seine Zustände werden nicht übertragen.'],
|
||||
['type' => 'Label', 'caption' => 'Eine Raumfreigabe umfasst seine verknüpften Werte, Geräte im Raum und die zugeordneten Bereichskategorien. Gerätefreigaben gelten für deren verknüpfte Datenpunkte. Bei automatischen Gerätezuordnungen die benötigten Symcon-Objekte zusätzlich auswählen oder feste Verknüpfungen im Editor setzen.'],
|
||||
['type' => 'Label', 'caption' => 'Passwörter: 8–72 Bytes. Leer beim Speichern erhält das bisherige Passwort. Änderungen an Konto oder Rechten beenden bestehende Anmeldungen dieses Benutzers. Die Konsole kann jederzeit Passwörter zurücksetzen.'],
|
||||
]]],
|
||||
]];
|
||||
$form['actions'][] = $userForm;
|
||||
return json_encode($form, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
public function OpenLogin(): string { $this->requireWebHook(); return 'link:/hook/' . $this->hookPath() . '/login'; }
|
||||
|
||||
private function accountOptions(): array
|
||||
{
|
||||
$options = [['caption' => '+ Neuen Benutzer anlegen', 'value' => '']];
|
||||
foreach ($this->accounts() as $id => $a) $options[] = ['caption' => $a['name'] . ($a['enabled'] ? '' : ' (gesperrt)'), 'value' => $id];
|
||||
return $options;
|
||||
}
|
||||
|
||||
private function planGrantColumns(array $options, array $values): array
|
||||
{
|
||||
foreach ($values as $v) if (!in_array($v['target'], array_column($options, 'value'), true)) $options[] = ['caption' => '(Nicht mehr im Plan) ' . $v['target'], 'value' => $v['target']];
|
||||
return [['name' => 'target', 'caption' => 'Freigabe', 'width' => 'auto', 'add' => '', 'edit' => ['type' => 'Select', 'options' => [['caption' => 'Bitte auswählen', 'value' => ''], ...$options]]],
|
||||
['name' => 'access', 'caption' => 'Recht', 'width' => '190px', 'add' => 'view', 'edit' => ['type' => 'Select', 'options' => [['caption' => 'Nur ansehen', 'value' => 'view'], ['caption' => 'Ansehen und bedienen', 'value' => 'control']]]]];
|
||||
}
|
||||
|
||||
public function SelectAccessUser(string $UserID): void
|
||||
{
|
||||
$a = $this->accounts()[$UserID] ?? [];
|
||||
if (!$a) $UserID = '';
|
||||
$this->WriteAttributeString('SelectedAccount', $UserID);
|
||||
$catalog = $this->accessCatalog();
|
||||
$this->UpdateFormField('AccountSelect', 'options', json_encode($this->accountOptions()));
|
||||
foreach (['AccountSelect' => $UserID, 'AccountName' => $a['name'] ?? '', 'AccountEnabled' => $a['enabled'] ?? true,
|
||||
'AccountRole' => $a['role'] ?? 'user', 'AccountViewAll' => $a['view_all'] ?? false, 'AccountControlAll' => $a['control_all'] ?? false, 'AccountPassword' => ''] as $name => $value) $this->UpdateFormField($name, 'value', $value);
|
||||
foreach (['AccountRooms' => 'rooms', 'AccountDevices' => 'devices', 'AccountObjects' => 'objects'] as $name => $key) {
|
||||
if ($key !== 'objects') $this->UpdateFormField($name, 'columns', json_encode($this->planGrantColumns($catalog[$key], $a[$key] ?? [])));
|
||||
$this->UpdateFormField($name, 'values', json_encode($a[$key] ?? []));
|
||||
}
|
||||
foreach (['AccountReset', 'AccountRevoke', 'AccountDelete'] as $name) $this->UpdateFormField($name, 'enabled', $UserID !== '');
|
||||
}
|
||||
|
||||
private function passwordHash(string $password): string
|
||||
{
|
||||
if (strlen($password) < 8 || strlen($password) > 72 || str_contains($password, "\0")) throw new InvalidArgumentException('Das Passwort muss 8–72 Bytes lang sein.');
|
||||
return password_hash($password, defined('PASSWORD_ARGON2ID') ? PASSWORD_ARGON2ID : PASSWORD_DEFAULT);
|
||||
}
|
||||
|
||||
private function parseGrants(string $json, bool $objects = false): array
|
||||
{
|
||||
$rows = json_decode($json, true);
|
||||
if (!is_array($rows) || !array_is_list($rows) || count($rows) > 256) throw new InvalidArgumentException('Ungültige Freigabeliste.');
|
||||
$result = [];
|
||||
foreach ($rows as $row) {
|
||||
if (!is_array($row)) throw new InvalidArgumentException('Ungültige Freigabe.');
|
||||
$target = $objects ? (int) ($row['target'] ?? 0) : (string) ($row['target'] ?? '');
|
||||
if ($target === '' || $target === 0) continue;
|
||||
if (!in_array($row['access'] ?? '', ['view', 'control'], true)) throw new InvalidArgumentException('Bitte für jede Freigabe ein Recht auswählen.');
|
||||
if ($objects && (!IPS_ObjectExists($target) || !in_array((int) IPS_GetObject($target)['ObjectType'], [0, 1, 2, 4, 6], true))) throw new InvalidArgumentException('Das freigegebene Objekt existiert nicht oder ist kein Gerät, Datenpunkt, Ereignis oder Bereich.');
|
||||
$key = (string) $target;
|
||||
$level = $row['access'] === 'control' || ($result[$key]['access'] ?? '') === 'control' ? 'control' : 'view';
|
||||
$result[$key] = ['target' => $target, 'access' => $level];
|
||||
}
|
||||
return array_values($result);
|
||||
}
|
||||
|
||||
public function SaveAccessUser(string $UserID, string $Name, string $Role, bool $Enabled, bool $ViewAll, bool $ControlAll, string $Rooms, string $Devices, string $Objects, string $Password): string
|
||||
{
|
||||
try {
|
||||
$Name = trim($Name);
|
||||
if (preg_match('/^[\p{L}\p{N}][\p{L}\p{N}_.@ -]{1,63}$/uD', $Name) !== 1) throw new InvalidArgumentException('Benutzername: 2–64 Buchstaben, Zahlen, Leerzeichen oder . _ @ -');
|
||||
if (!in_array($Role, ['admin', 'user'], true)) throw new InvalidArgumentException('Ungültige Rolle.');
|
||||
$rooms = $this->parseGrants($Rooms); $devices = $this->parseGrants($Devices); $objects = $this->parseGrants($Objects, true);
|
||||
$hash = $Password === '' ? null : $this->passwordHash($Password);
|
||||
$id = $this->accessLock(function () use ($UserID, $Name, $Role, $Enabled, $ViewAll, $ControlAll, $rooms, $devices, $objects, $hash): string {
|
||||
$accounts = $this->accounts();
|
||||
if ($UserID !== '' && !isset($accounts[$UserID])) throw new InvalidArgumentException('Benutzer nicht gefunden.');
|
||||
foreach ($accounts as $id => $a) if ($id !== $UserID && mb_strtolower($a['name']) === mb_strtolower($Name)) throw new InvalidArgumentException('Dieser Benutzername ist bereits vergeben.');
|
||||
if ($UserID === '' && count($accounts) >= 128) throw new InvalidArgumentException('Maximal 128 Benutzer pro Instanz.');
|
||||
if ($UserID === '' && $hash === null) throw new InvalidArgumentException('Für neue Benutzer bitte ein Passwort setzen.');
|
||||
$id = $UserID ?: bin2hex(random_bytes(16));
|
||||
$accounts[$id] = ['name' => $Name, 'role' => $Role, 'enabled' => $Enabled, 'view_all' => $ViewAll || $ControlAll,
|
||||
'control_all' => $ControlAll, 'rooms' => $rooms, 'devices' => $devices, 'objects' => $objects,
|
||||
'password' => $hash ?? $accounts[$id]['password'], 'epoch' => $this->newToken()];
|
||||
$this->writeJsonAttribute('Accounts', $accounts);
|
||||
$this->clearUserSessions($id);
|
||||
return $id;
|
||||
});
|
||||
$this->SelectAccessUser($id);
|
||||
return 'Benutzer gespeichert. Vorherige Anmeldungen dieses Benutzers wurden beendet.';
|
||||
} catch (InvalidArgumentException $e) { return $e->getMessage(); }
|
||||
}
|
||||
|
||||
private function clearUserSessions(string $id): void
|
||||
{
|
||||
$this->writeJsonAttribute('Sessions', array_filter($this->jsonAttribute('Sessions', []), static fn(array $s): bool => $s['account'] !== $id));
|
||||
}
|
||||
|
||||
public function ResetUserPassword(string $UserID, string $Password): string
|
||||
{
|
||||
try {
|
||||
$hash = $this->passwordHash($Password);
|
||||
$this->accessLock(function () use ($UserID, $hash): void {
|
||||
$accounts = $this->accounts();
|
||||
if (!isset($accounts[$UserID])) throw new InvalidArgumentException('Bitte einen bestehenden Benutzer auswählen.');
|
||||
$accounts[$UserID]['password'] = $hash; $accounts[$UserID]['epoch'] = $this->newToken();
|
||||
$this->writeJsonAttribute('Accounts', $accounts); $this->clearUserSessions($UserID);
|
||||
$limits = $this->jsonAttribute('LoginThrottle', []); unset($limits['name:' . hash('sha256', mb_strtolower($accounts[$UserID]['name']))]);
|
||||
$this->writeJsonAttribute('LoginThrottle', $limits);
|
||||
});
|
||||
$this->UpdateFormField('AccountPassword', 'value', '');
|
||||
return 'Passwort zurückgesetzt. Bestehende Anmeldungen dieses Benutzers sind beendet.';
|
||||
} catch (InvalidArgumentException $e) { return $e->getMessage(); }
|
||||
}
|
||||
|
||||
public function RevokeUserSessions(string $UserID): string
|
||||
{
|
||||
$this->accessLock(fn() => $this->clearUserSessions($UserID));
|
||||
return 'Bestehende Anmeldungen dieses Benutzers wurden beendet.';
|
||||
}
|
||||
|
||||
public function DeleteAccessUser(string $UserID): string
|
||||
{
|
||||
$this->accessLock(function () use ($UserID): void {
|
||||
$accounts = $this->accounts(); unset($accounts[$UserID]); $this->writeJsonAttribute('Accounts', $accounts); $this->clearUserSessions($UserID);
|
||||
});
|
||||
$this->SelectAccessUser('');
|
||||
return 'Benutzer gelöscht.';
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
"aliases": [
|
||||
"NextFloor Designer und 3D-Kachel"
|
||||
],
|
||||
"url": "https://git.portal.se-cloud.de/Hannes/NextFloor/src/branch/main/symcon/README.md",
|
||||
"url": "https://git.portal.se-cloud.de/Hannes/NextFloor/src/branch/symcon/README.md",
|
||||
"parentRequirements": [],
|
||||
"childRequirements": [],
|
||||
"implemented": [],
|
||||
|
||||
+97
-47
@@ -2,15 +2,20 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once __DIR__ . '/libs/Access.php';
|
||||
require_once __DIR__ . '/libs/Users.php';
|
||||
require_once __DIR__ . '/libs/Permissions.php';
|
||||
|
||||
/**
|
||||
* NextFloor for IP-Symcon.
|
||||
*
|
||||
* One visualization instance owns a floor-plan project. Its protected WebHook serves the designer as
|
||||
* a console tab and the same viewer in an HTML-SDK tile iframe. The frontend receives every variable
|
||||
* in the object tree with a friendly path; it never asks an end user to type an object id.
|
||||
* a browser tab and the same viewer in an HTML-SDK tile iframe. Admins receive the native object tree;
|
||||
* user sessions receive only authorized live bindings. Object selections always use named choices.
|
||||
*/
|
||||
class NextFloor extends IPSModuleStrict
|
||||
{
|
||||
use NextFloorAccess, NextFloorUsers, NextFloorPermissions;
|
||||
private const MAX_BUILDING_BYTES = 8_000_000;
|
||||
private const MAX_IMAGE_BYTES = 8_000_000;
|
||||
private const MAX_HISTORY = 20;
|
||||
@@ -31,6 +36,12 @@ class NextFloor extends IPSModuleStrict
|
||||
$this->RegisterAttributeString('Packs', '[]');
|
||||
$this->RegisterAttributeString('History', '[]');
|
||||
$this->RegisterAttributeString('AccessToken', '');
|
||||
$this->RegisterAttributeString('Accounts', '{}');
|
||||
$this->RegisterAttributeString('Sessions', '{}');
|
||||
$this->RegisterAttributeString('ConsoleTickets', '{}');
|
||||
$this->RegisterAttributeString('LoginThrottle', '{}');
|
||||
$this->RegisterAttributeString('LoginDummyHash', '');
|
||||
$this->RegisterAttributeString('SelectedAccount', '');
|
||||
$this->RegisterAttributeString('StateHash', '');
|
||||
$this->RegisterAttributeString('HookError', '');
|
||||
$this->RegisterAttributeInteger('BuildingRevision', 0);
|
||||
@@ -40,6 +51,7 @@ class NextFloor extends IPSModuleStrict
|
||||
$this->RegisterTimer('WebHookRetry', 0, 'NFSC_RetryWebHook($_IPS[\'TARGET\']);');
|
||||
|
||||
$this->ensureAccessToken();
|
||||
if ($this->ReadAttributeString('LoginDummyHash') === '') $this->WriteAttributeString('LoginDummyHash', $this->passwordHash($this->newToken()));
|
||||
$this->SetVisualizationType(1);
|
||||
$this->ensureWebHook(true);
|
||||
}
|
||||
@@ -76,7 +88,7 @@ class NextFloor extends IPSModuleStrict
|
||||
return 'WebHook registriert: /hook/' . $this->hookPath() . '. Jetzt den Designer öffnen.';
|
||||
}
|
||||
|
||||
/** URL returned to the console form. It opens in a console tab, as IPSView does. */
|
||||
/** Browser link returned to the console form; link: does not create a native Pro Console tab. */
|
||||
public function OpenDesigner(): string
|
||||
{
|
||||
$this->requireWebHook();
|
||||
@@ -84,11 +96,13 @@ class NextFloor extends IPSModuleStrict
|
||||
return 'link:' . $this->designerUrl('designer');
|
||||
}
|
||||
|
||||
/** Invalidates links from copied browser history and returns a fresh designer URL. */
|
||||
/** Revoke all logins and outstanding console tickets, then issue a fresh one-use designer link. */
|
||||
public function RotateAccessToken(): string
|
||||
{
|
||||
$this->requireWebHook();
|
||||
$this->WriteAttributeString('AccessToken', $this->newToken());
|
||||
$this->WriteAttributeString('Sessions', '{}');
|
||||
$this->WriteAttributeString('ConsoleTickets', '{}');
|
||||
return 'link:' . $this->designerUrl('designer');
|
||||
}
|
||||
|
||||
@@ -108,24 +122,52 @@ class NextFloor extends IPSModuleStrict
|
||||
/** IP-Symcon calls this for /hook/nextfloor/<instance id>/... */
|
||||
protected function ProcessHookData(): void
|
||||
{
|
||||
$this->requestUser = null;
|
||||
$this->requestScope = null;
|
||||
// Keep a same-origin Origin on native form POSTs; no-referrer can turn it into "null".
|
||||
header('Referrer-Policy: same-origin');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('X-Frame-Options: SAMEORIGIN');
|
||||
header("Content-Security-Policy: frame-ancestors 'self'; object-src 'none'; base-uri 'none'");
|
||||
$requestPath = (string) ($_SERVER['REQUEST_URI'] ?? '');
|
||||
if ($requestPath === '') {
|
||||
$requestPath = (string) ($_SERVER['SCRIPT_NAME'] ?? '');
|
||||
}
|
||||
$path = (string) (parse_url($requestPath, PHP_URL_PATH) ?? '');
|
||||
$prefix = '/hook/' . $this->hookPath();
|
||||
if (!str_starts_with($path, $prefix)) {
|
||||
if ($path !== $prefix && !str_starts_with($path, $prefix . '/')) {
|
||||
$this->sendError(404, 'not_found');
|
||||
return;
|
||||
}
|
||||
if (!$this->hasValidToken()) {
|
||||
$this->sendError(403, 'forbidden');
|
||||
return;
|
||||
}
|
||||
|
||||
$tail = trim(substr($path, strlen($prefix)), '/');
|
||||
try {
|
||||
$method = (string) ($_SERVER['REQUEST_METHOD'] ?? 'GET');
|
||||
$this->requestUser = $this->resolveSession();
|
||||
if ($tail === 'login') {
|
||||
if ($method === 'POST') $this->passwordLogin();
|
||||
elseif ($method !== 'GET') $this->sendError(405, 'method_not_allowed');
|
||||
elseif ($this->requestUser !== null) $this->accessRedirect($this->entryUrl());
|
||||
else $this->loginPage();
|
||||
return;
|
||||
}
|
||||
if (($tail === 'designer' || $tail === '') && $method === 'GET' && isset($_GET['ticket'])) {
|
||||
// Always exchange and remove a ticket, even if another user was already logged in.
|
||||
if (is_string($_GET['ticket']) && $this->exchangeConsoleTicket($_GET['ticket'])) $this->accessRedirect($this->entryUrl());
|
||||
else $this->loginPage('Der Konsolen-Link ist abgelaufen oder wurde schon verwendet. Bitte erneut in der Konsole öffnen.', 401);
|
||||
return;
|
||||
}
|
||||
if ($this->requestUser === null) {
|
||||
if ($tail === '' || $tail === 'designer') $this->accessRedirect($this->entryUrl('login'));
|
||||
else $this->sendError(401, 'authentication_required');
|
||||
return;
|
||||
}
|
||||
if ($tail === 'logout') {
|
||||
if ($method !== 'POST' || !$this->validCsrf()) $this->sendError(403, 'csrf_invalid');
|
||||
else $this->logoutSession();
|
||||
return;
|
||||
}
|
||||
if ($tail === '' || $tail === 'designer') {
|
||||
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
|
||||
$this->sendDesignerPage();
|
||||
return;
|
||||
}
|
||||
@@ -134,6 +176,8 @@ class NextFloor extends IPSModuleStrict
|
||||
return;
|
||||
}
|
||||
if (str_starts_with($tail, 'assets/')) {
|
||||
if ($method !== 'GET') { $this->sendError(405, 'method_not_allowed'); return; }
|
||||
if (!$this->isAdministrator() && preg_match('#^assets/nextfloor-(?:editor|card-editor)\.js$#D', $tail)) { $this->sendError(403, 'admin_required'); return; }
|
||||
$this->sendAsset(substr($tail, strlen('assets/')));
|
||||
return;
|
||||
}
|
||||
@@ -216,7 +260,7 @@ class NextFloor extends IPSModuleStrict
|
||||
|
||||
private function designerUrl(string $mode): string
|
||||
{
|
||||
return '/hook/' . $this->hookPath() . '/designer?mode=' . rawurlencode($mode) . '&token=' . rawurlencode($this->ensureAccessToken());
|
||||
return $mode === 'tile' ? '/hook/' . $this->hookPath() . '/designer?mode=tile' : $this->consoleUrl();
|
||||
}
|
||||
|
||||
private function ensureAccessToken(): string
|
||||
@@ -234,46 +278,21 @@ class NextFloor extends IPSModuleStrict
|
||||
return bin2hex(random_bytes(32));
|
||||
}
|
||||
|
||||
private function hasValidToken(): bool
|
||||
{
|
||||
// The first HTML request carries the random URL token. It also sets an HttpOnly cookie
|
||||
// below, so lazy ES-module imports (which cannot inherit a query string) stay protected.
|
||||
$provided = (string) ($_GET['token'] ?? $_COOKIE[$this->cookieName()] ?? '');
|
||||
return $provided !== '' && hash_equals($this->ensureAccessToken(), $provided);
|
||||
}
|
||||
|
||||
private function cookieName(): string
|
||||
{
|
||||
return 'NFSC_' . $this->InstanceID;
|
||||
}
|
||||
|
||||
private function setAccessCookie(): void
|
||||
{
|
||||
setcookie($this->cookieName(), $this->ensureAccessToken(), [
|
||||
'expires' => 0,
|
||||
'path' => '/hook/' . $this->hookPath() . '/',
|
||||
'secure' => (($_SERVER['HTTPS'] ?? '') !== '' && ($_SERVER['HTTPS'] ?? '') !== 'off'),
|
||||
'httponly' => true,
|
||||
'samesite' => 'Strict'
|
||||
]);
|
||||
}
|
||||
|
||||
private function sendDesignerPage(): void
|
||||
{
|
||||
$this->setAccessCookie();
|
||||
$config = [
|
||||
'endpoint' => '/hook/' . $this->hookPath(),
|
||||
'token' => $this->ensureAccessToken(),
|
||||
'csrf' => $this->requestUser['csrf'],
|
||||
'user' => $this->publicAccess(),
|
||||
'language' => 'de',
|
||||
'title' => $this->viewTitle()
|
||||
];
|
||||
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion())
|
||||
. '&token=' . rawurlencode($this->ensureAccessToken());
|
||||
$asset = '/hook/' . $this->hookPath() . '/assets/nextfloor-designer.js?v=' . rawurlencode($this->moduleVersion());
|
||||
header('Content-Type: text/html; charset=utf-8');
|
||||
header('Cache-Control: no-store');
|
||||
echo '<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
||||
. '<title>' . htmlspecialchars($config['title'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</title>'
|
||||
. '<style>html,body{width:100%;height:100%;margin:0;background:#111;color:#e1e1e1}body>nextfloor-panel,body>nextfloor-card{display:block;width:100%;height:100%}</style>'
|
||||
. '<style>html,body{width:100%;height:100%;margin:0;background:#111;color:#e1e1e1}body{display:flex;flex-direction:column}body>nextfloor-panel,body>nextfloor-card{display:block;flex:1;min-height:0;width:100%}.nf-session-bar{display:flex;align-items:center;gap:10px;padding:5px 12px;font:12px/1.4 system-ui;background:#20252d;border-bottom:1px solid #ffffff15}.nf-session-bar span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.nf-session-bar form{margin:0 0 0 auto;flex-shrink:0}.nf-session-bar button{font:inherit;padding:5px 12px;border:1px solid #ffffff25;border-radius:7px;background:#ffffff0a;color:inherit;cursor:pointer}</style>'
|
||||
. '</head><body><p style="padding:1rem;font-family:system-ui">NextFloor wird geladen …</p>'
|
||||
. '<script>window.__NEXTFLOOR_SYMCON__=' . json_encode($config, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';</script>'
|
||||
. '<script type="module" src="' . htmlspecialchars($asset, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"></script></body></html>';
|
||||
@@ -304,18 +323,23 @@ class NextFloor extends IPSModuleStrict
|
||||
$this->sendError(405, 'method_not_allowed');
|
||||
return;
|
||||
}
|
||||
$request = json_decode((string) file_get_contents('php://input'), true);
|
||||
if (!$this->validCsrf()) { $this->sendError(403, 'csrf_invalid'); return; }
|
||||
$limit = $this->isAdministrator() ? self::MAX_TRANSFER_BYTES : 65536;
|
||||
$raw = (string) file_get_contents('php://input', false, null, 0, $limit + 1);
|
||||
if (strlen($raw) > $limit) { $this->sendError(413, 'request_too_large'); return; }
|
||||
$request = json_decode($raw, true);
|
||||
if (!is_array($request) || !is_string($request['action'] ?? null)) {
|
||||
$this->sendError(400, 'invalid_request');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->authorizeApi($request['action'], $request);
|
||||
$result = match ($request['action']) {
|
||||
'bootstrap' => $this->bootstrap(),
|
||||
'variables/snapshot' => $this->variablesSnapshot((int) ($request['revision'] ?? -1)),
|
||||
'archive/trend' => $this->archiveTrend($request),
|
||||
'building/get' => ['building' => $this->building(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()],
|
||||
'building/get' => ['building' => $this->visibleBuilding(), 'revision' => $this->ReadAttributeInteger('BuildingRevision'), 'version' => $this->moduleVersion()],
|
||||
'building/save' => ['revision' => $this->saveBuilding($this->arrayValue($request, 'building'))],
|
||||
'image/get' => $this->imageGet((string) ($request['image_id'] ?? '')),
|
||||
'image/set' => $this->imageSet((string) ($request['image_id'] ?? ''), (string) ($request['data'] ?? '')),
|
||||
@@ -336,6 +360,8 @@ class NextFloor extends IPSModuleStrict
|
||||
default => throw new RuntimeException('unknown_action')
|
||||
};
|
||||
$this->sendApiResult($result, ($request['transport'] ?? '') === 'nextfloor-chunks-v1');
|
||||
} catch (NextFloorDenied $error) {
|
||||
$this->sendError(403, $error->getMessage());
|
||||
} catch (InvalidArgumentException $error) {
|
||||
$this->sendError(400, $error->getMessage());
|
||||
} catch (RuntimeException $error) {
|
||||
@@ -345,9 +371,10 @@ class NextFloor extends IPSModuleStrict
|
||||
|
||||
private function bootstrap(): array
|
||||
{
|
||||
$objects = $this->objectTree();
|
||||
$objects = $this->visibleTree($this->objectTree());
|
||||
$stateRevision = $this->stateRevision($objects);
|
||||
return [
|
||||
'access' => $this->publicAccess(),
|
||||
'state_revision' => $stateRevision,
|
||||
'building_revision' => $this->ReadAttributeInteger('BuildingRevision'),
|
||||
'variables' => $objects['variables'],
|
||||
@@ -358,7 +385,7 @@ class NextFloor extends IPSModuleStrict
|
||||
|
||||
private function variablesSnapshot(int $knownRevision): array
|
||||
{
|
||||
$objects = $this->objectTree();
|
||||
$objects = $this->visibleTree($this->objectTree());
|
||||
$stateRevision = $this->stateRevision($objects);
|
||||
$result = [
|
||||
'state_revision' => $stateRevision,
|
||||
@@ -487,7 +514,7 @@ class NextFloor extends IPSModuleStrict
|
||||
'symcon_path' => $path,
|
||||
'symcon_profile' => $profile,
|
||||
'symcon_variable_type' => (int) $variable['VariableType'],
|
||||
'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) !== 0,
|
||||
'symcon_has_action' => ((int) ($variable['VariableCustomAction'] ?: $variable['VariableAction'])) > 0,
|
||||
'symcon_formatted' => GetValueFormatted($variableID),
|
||||
'symcon_value' => $value,
|
||||
'device_class' => $this->deviceClassFor($profile, $name, $unit)
|
||||
@@ -648,6 +675,8 @@ class NextFloor extends IPSModuleStrict
|
||||
private function stateRevision(array $objects): int
|
||||
{
|
||||
$hash = hash('sha256', $this->encodeResponse($objects));
|
||||
// Distinct user scopes must not invalidate one global revision on every alternating poll.
|
||||
if ($this->requestUser !== null && !$this->isAdministrator()) return (int) hexdec(substr($hash, 0, 12));
|
||||
if (!hash_equals($this->ReadAttributeString('StateHash'), $hash)) {
|
||||
$this->WriteAttributeString('StateHash', $hash);
|
||||
$this->WriteAttributeInteger('StateRevision', $this->ReadAttributeInteger('StateRevision') + 1);
|
||||
@@ -683,11 +712,14 @@ class NextFloor extends IPSModuleStrict
|
||||
if (strlen($encoded) > self::MAX_BUILDING_BYTES) {
|
||||
throw new InvalidArgumentException('building_too_large');
|
||||
}
|
||||
return $this->accessLock(function () use ($building, $encoded): int {
|
||||
$this->migrateMovedPlanGrants($this->building(), $building);
|
||||
$this->WriteAttributeString('Building', $encoded);
|
||||
$revision = $this->ReadAttributeInteger('BuildingRevision') + 1;
|
||||
$this->WriteAttributeInteger('BuildingRevision', $revision);
|
||||
$this->UpdateVisualizationValue(json_encode(['building_revision' => $revision]));
|
||||
return $revision;
|
||||
});
|
||||
}
|
||||
|
||||
private function imageGet(string $imageID): array
|
||||
@@ -1129,6 +1161,7 @@ class NextFloor extends IPSModuleStrict
|
||||
if (preg_match('/^[a-f0-9]{32}\.json$/D', basename($file)) !== 1 || is_link($file)) continue;
|
||||
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
|
||||
unlink($file);
|
||||
if (is_file($file . '.owner') && !is_link($file . '.owner')) unlink($file . '.owner');
|
||||
} else {
|
||||
$active++;
|
||||
}
|
||||
@@ -1152,15 +1185,32 @@ class NextFloor extends IPSModuleStrict
|
||||
throw $error;
|
||||
}
|
||||
fclose($handle);
|
||||
if (file_put_contents($file . '.owner', $this->transferOwner(), LOCK_EX) === false) {
|
||||
unlink($file);
|
||||
throw new RuntimeException('transfer_storage_unavailable');
|
||||
}
|
||||
chmod($file . '.owner', 0600);
|
||||
return ['id' => $id, 'bytes' => $bytes, 'chunk_bytes' => self::TRANSFER_CHUNK_BYTES, 'chunks' => (int) ceil($bytes / self::TRANSFER_CHUNK_BYTES)];
|
||||
}
|
||||
|
||||
private function transferOwner(): string
|
||||
{
|
||||
return hash('sha256', (string) ($this->requestUser['session_id'] ?? 'internal') . ':' . (string) ($this->requestUser['epoch'] ?? ''));
|
||||
}
|
||||
|
||||
private function ownsTransfer(string $file): bool
|
||||
{
|
||||
$owner = $file . '.owner';
|
||||
return is_file($owner) && !is_link($owner) && hash_equals($this->transferOwner(), (string) file_get_contents($owner));
|
||||
}
|
||||
|
||||
private function readTransfer(string $id, int $index): array
|
||||
{
|
||||
$file = $this->transferFile($id);
|
||||
if (!is_file($file) || is_link($file)) throw new RuntimeException('transfer_not_found');
|
||||
if (!is_file($file) || is_link($file) || !$this->ownsTransfer($file)) throw new RuntimeException('transfer_not_found');
|
||||
if ((int) filemtime($file) < time() - self::TRANSFER_TTL) {
|
||||
unlink($file);
|
||||
unlink($file . '.owner');
|
||||
throw new RuntimeException('transfer_expired: Bitte erneut laden.');
|
||||
}
|
||||
$bytes = (int) filesize($file);
|
||||
@@ -1183,7 +1233,7 @@ class NextFloor extends IPSModuleStrict
|
||||
private function releaseTransfer(string $id): array
|
||||
{
|
||||
$file = $this->transferFile($id);
|
||||
if (is_file($file) && !is_link($file)) unlink($file);
|
||||
if (is_file($file) && !is_link($file) && $this->ownsTransfer($file)) { unlink($file); unlink($file . '.owner'); }
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
+169
-6
@@ -1,10 +1,12 @@
|
||||
# NextFloor für IP-Symcon 9.0
|
||||
|
||||
Dieses Verzeichnis ist eine vollständige IP-Symcon-Bibliothek. Der gleiche NextFloor-Designer
|
||||
läuft damit in zwei Symcon-Oberflächen:
|
||||
Dieses Verzeichnis ist eine vollständige IP-Symcon-Bibliothek. NextFloor lässt sich
|
||||
über den Designer und die Kachel-Visualisierung verwenden:
|
||||
|
||||
- **Designer:** Die Instanzkonfiguration öffnet den Designer per geschütztem WebHook in einem
|
||||
eigenen Konsolen-/Browser-Tab – derselbe Ansatz, den auch IPSView für seinen Designer nutzt.
|
||||
Browser-Tab. Auch die installierte Pro-Konsole öffnet diesen Link im Standardbrowser.
|
||||
IPSViews interner Designer-Tab ist speziell in Symcons Konsole integriert; die öffentliche
|
||||
Modulschnittstelle von Symcon 9.0 bietet diesen Tab nicht für eigene Web-Oberflächen an.
|
||||
- **Kachel-Visualisierung:** Die NextFloor-Instanz kann direkt in der Tile-Visualisierung als
|
||||
HTML-SDK-Kachel abgelegt werden. Sie zeigt die 3D-Ansicht samt Bedienung.
|
||||
|
||||
@@ -16,9 +18,70 @@ In **Kerninstanzen → Modules** wird dieses Repository verwendet:
|
||||
|
||||
Im Zahnrad des Eintrags den Branch **`symcon`** wählen und auf Aktualisierungen prüfen.
|
||||
`main` enthält die Quellen für die Entwicklung, `symcon` die installierbare Bibliothek.
|
||||
Nach der Aktualisierung auf **0.2.29 / Build 32** die Konsole neu laden. Unter
|
||||
Nach der Aktualisierung auf **0.4.3 / Build 41** die Konsole neu laden. Unter
|
||||
**Instanz hinzufügen → Hersteller NextFloor** erscheint **„NextFloor Designer und 3D-Kachel“**.
|
||||
|
||||
## Hierarchie und Etagen
|
||||
|
||||
Im Editor oben **Hierarchie** öffnen. Bei einem bisherigen Plan dort auf
|
||||
**Hierarchie einrichten** klicken.
|
||||
Bestehende Stockwerke werden einem ersten Ort, einer Niederlassung und einem Gebäude
|
||||
zugeordnet; ihre IDs, Geometrie, Datenpunkte und Benutzerfreigaben bleiben erhalten.
|
||||
Im separaten Dialog Orte, Niederlassungen und Gebäude benennen und weitere anlegen.
|
||||
Die drei Listen zeigen jeweils die Einträge der ausgewählten übergeordneten Ebene.
|
||||
Beispiel: **Urbach / Zentrale / RAS19 / EG / IT**.
|
||||
|
||||
- Oben im Editor unter **Ansicht** einen **Ort**, eine **Niederlassung** oder ein
|
||||
**Gebäude** auswählen. Ort und Niederlassung zeigen eine Gesamtübersicht ihrer
|
||||
untergeordneten Pläne, auch in der 3D-Hälfte. Die Knöpfe darunter öffnen die nächste
|
||||
Ebene. Eine Gesamtübersicht wählt keine Etage automatisch zur Bearbeitung aus.
|
||||
Bei Auswahl eines Gebäudes erscheinen darunter nur seine Etagen und sein Außenplan.
|
||||
**+ Etage** legt ein Stockwerk in genau diesem Gebäude an, mit eigener Höhenfolge.
|
||||
Ein Gebäudewechsel ändert keine Zuordnung und erzeugt keine Etage. Ein leeres
|
||||
Gebäude bleibt auch nach einem Neuladen der Daten ausgewählt und leer.
|
||||
- Die rechte Leiste bleibt für Etagen-, Raum- und Geräteeigenschaften verfügbar.
|
||||
Im ausgewählten Raum über **Bereich (Symcon)** die vorhandene Bereichskategorie
|
||||
verknüpfen; Räume derselben Kategorie werden in der Raumliste zusammengefasst.
|
||||
Der Raum gehört über seine Etage zum Gebäude. Die Auswahl verändert weder den
|
||||
Symcon-Objektbaum noch den Raumnamen; dafür gibt es **Bereichsnamen übernehmen**.
|
||||
- Zum Verschieben zuerst die betreffende Etage öffnen und oben
|
||||
**Ausgewählte Etage verschieben…** wählen. Der Dialog nennt ihren vollständigen
|
||||
Pfad. Erst die Schaltfläche **Etage „…“ verschieben** übernimmt das Zielgebäude;
|
||||
eine bloße Zielauswahl oder das Schließen des Dialogs ändert nichts.
|
||||
- Für einen einzelnen Raum rechts **Raum verschieben…** öffnen. Zielgebäude und
|
||||
Zieletage auswählen, bei Bedarf die vorgeschlagene Position X/Z anpassen und erst
|
||||
dann **Raum „…“ verschieben** drücken. Raumdaten, Datenpunktverknüpfungen,
|
||||
Türen/Fenster, enthaltene Möbel, platzierte Geräte und Notizen ziehen mit um.
|
||||
Der Dialog meldet Konflikte mit bereits vorhandenen Gerätekennungen. Vorhandene
|
||||
Benutzerfreigaben folgen eindeutig identifizierbaren Räumen und Geräten, auch
|
||||
beim Rückgängigmachen; Ansicht bleibt Ansicht und Bedienung bleibt Bedienung.
|
||||
- Pro **Ort**, **Niederlassung** und **Gebäude** im Hierarchiedialog über
|
||||
**Außenplan anlegen** einen eigenen Außenplan erstellen und im Editor wie
|
||||
gewohnt Außenflächen, Geräte und Möbel platzieren.
|
||||
Jeder Außenplan gehört direkt zur jeweiligen Ebene und erscheint dort auch in
|
||||
der linken Navigation mit einer passenden Vorschau. Das Außen-Popup berücksichtigt
|
||||
auch bisher auf untergeordneten Gebäudestockwerken platzierte Außen-Datenpunkte,
|
||||
ohne Werte benachbarter Niederlassungen oder Gebäude einzumischen.
|
||||
- Die linke Navigation in Designer und Kachel folgt der Topologie. Die kleinen
|
||||
Pfadknöpfe führen zu den übergeordneten Ebenen zurück. Die Vorschaubilder zeigen
|
||||
nur die Stockwerke des Eintrags; Raumvorschauen werden auf den Raum zugeschnitten.
|
||||
- Die obere Raumleiste erscheint erst bei Auswahl eines Stockwerks. In Orts-,
|
||||
Niederlassungs-, Gebäude- und Außenansichten bleibt sie ausgeblendet.
|
||||
- Die rechte Verbrauchsübersicht folgt derselben Auswahl: **Ort → Niederlassungen**,
|
||||
**Niederlassung → Gebäude**, **Gebäude → Stockwerke**, **Stockwerk → Bereiche**.
|
||||
Oben stehen jeweils die Leistungen und Verbräuche der ausgewählten Gruppe.
|
||||
Einträge öffnen die entsprechende Ebene. Eigene Außenpläne mit Zählern erscheinen
|
||||
separat unter ihrem jeweiligen Besitzer. Alle fünf Medien, eigene Stockwerkszähler,
|
||||
getrennte Verbrauchszeiträume, Trendknöpfe und „Err:“-Teilsummen bleiben erhalten.
|
||||
- Stockwerksstapel und automatische Dächer werden pro Gebäude dargestellt.
|
||||
Planpositionen bleiben unverändert. Bei Bedarf ein Gebäude über **Verschieben**
|
||||
mit **Alle Stockwerke dieses Gebäudes mitnehmen** im gemeinsamen Grundriss anordnen.
|
||||
|
||||
Auch die Freigabe-Auswahl in der Symcon-Benutzerverwaltung zeigt die vollständigen
|
||||
Pfade. Die Rechte bleiben an die bisherigen Stockwerks-, Raum- und Geräte-IDs gebunden.
|
||||
Leere Gruppen können entfernt werden; Gruppen mit untergeordneten Einträgen sind geschützt.
|
||||
Pläne ohne eingerichtete Topologie behalten ihre bisherige Navigation.
|
||||
|
||||
### Für die Entwicklung
|
||||
|
||||
IP-Symcon erwartet `library.json` im Wurzelverzeichnis eines Repositories. Das eigentliche
|
||||
@@ -41,11 +104,111 @@ Danach in IP-Symcon unter **Kerninstanzen → Modules** den Git-Link des Forks h
|
||||
im Zahnrad des Eintrags den Branch `symcon` wählen. Anschließend steht **NextFloor** bei
|
||||
„Instanz hinzufügen“ zur Verfügung.
|
||||
|
||||
### Status von Heizkreisen und Frischwasserstationen
|
||||
|
||||
Im Editor lässt sich je Heizkreis und je FriWa-Station unter **Status (optional)** eine
|
||||
Variable aus dem Symcon-Objektbaum auswählen. **Anlagenstatus (optional)** ergänzt einen
|
||||
gemeinsamen Status für das gesamte Gerät. Integer-Variablen zeigen den in Symcon
|
||||
hinterlegten Aliastext; Namen und Pfade begrenzen die Auswahl nicht. Die Statuswerte
|
||||
erscheinen in der schwebenden 3D-Kachel und im Detailfenster, bei Kaskaden je Station.
|
||||
Nicht verknüpfte Statuszeilen bleiben ausgeblendet. Die Anzeige ist schreibgeschützt.
|
||||
|
||||
Die Dateien unter `NextFloor/assets/` und `NextFloor/packs/` werden durch
|
||||
`frontend` mit `npm run build` erzeugt beziehungsweise kopiert und gehören daher in den Branch.
|
||||
Der Build prüft anschließend die Modulmetadaten und die installierbare Verzeichnisstruktur.
|
||||
Dieselbe Prüfung lässt sich separat mit `node symcon/tests/validate-package.mjs` ausführen.
|
||||
|
||||
## Anmeldung und Benutzerrechte ab 0.3.0
|
||||
|
||||
1. In der NextFloor-Instanz **Benutzer und Zugriffsrechte** öffnen.
|
||||
2. Unter **Benutzer auswählen → Neuen Benutzer anlegen** Namen und Passwort setzen.
|
||||
3. Rolle und Freigaben auswählen, dann **Benutzer speichern**. Diese Aktionen
|
||||
werden sofort gespeichert; das Passwortfeld wird danach geleert.
|
||||
4. **Anmeldeseite öffnen** aufrufen und die Adresse als Lesezeichen verwenden.
|
||||
Sie ist dauerhaft und enthält kein Zugangs-Token. Die Adresse steht außerdem
|
||||
im Formular: `/hook/nextfloor/<Instanz-ID>/` an der Symcon-Serveradresse.
|
||||
|
||||
Das Passwortfeld steht direkt unter dem Benutzernamen. Beim Benutzerwechsel werden
|
||||
Rolle, Schalter und alle drei Freigabetabellen mit den gespeicherten Werten dieses
|
||||
Benutzers neu befüllt; das Passwortfeld wird geleert. Die Auswahl **Neuen Benutzer
|
||||
anlegen** leert die Tabellen. Änderungen werden erst mit **Benutzer speichern**
|
||||
übernommen; ein Wechsel verwirft noch nicht gespeicherte Eingaben. Seit 0.3.2 werden
|
||||
die nativen Formularlisten zeilenweise übertragen, auch wenn sie leer sind oder
|
||||
gerade keine Zeile ausgewählt ist.
|
||||
|
||||
Die Konten gehören zur jeweiligen NextFloor-Instanz. Die Benutzerverwaltung
|
||||
bleibt ausschließlich in der Symcon-Konfiguration. **Designer im Browser
|
||||
öffnen** ermöglicht dem Symcon-Administrator weiterhin den vollständigen Zugang,
|
||||
auch wenn kein NextFloor-Admin mehr angemeldet ist oder alle Konten gesperrt sind.
|
||||
Der dabei erzeugte Konsolen-Link gilt 90 Sekunden und kann einmal verwendet werden.
|
||||
Als Lesezeichen wird stattdessen die dauerhafte Anmeldeseite verwendet.
|
||||
|
||||
| Einstellung | Zugriff |
|
||||
| --- | --- |
|
||||
| Admin | Komplette Visualisierung, Bedienung und Editor |
|
||||
| Benutzer ohne Freigaben | Komplettes Gebäude als Geometrie, keine Zustände oder Bedienung |
|
||||
| Alle Zustände ansehen | Alle Daten dieser Visualisierung, ohne Bedienung |
|
||||
| Alles ansehen und bedienen | Daten und Bedienung dieser Visualisierung, ohne Editor |
|
||||
| Raumfreigabe „Nur ansehen“ | Zustände des ausgewählten Raums und seiner Geräte |
|
||||
| Raumfreigabe „Ansehen und bedienen“ | Zusätzlich Bedienung dieser Geräte |
|
||||
| Gerätefreigabe | Nur das gewählte Gerät und seine verknüpften Werte, ohne den ganzen Raum freizugeben |
|
||||
|
||||
Einzelfreigaben ergänzen die Grundrechte. So kann ein Benutzer alles ansehen,
|
||||
aber ausschließlich Büro 2 bedienen. „Alle“ bezieht sich auf die Visualisierung;
|
||||
unverknüpfte Symcon-Variablen werden Benutzern nicht pauschal übertragen.
|
||||
Ein Raum umfasst seine verknüpften Werte, die Geräte im Raum und die zugeordneten
|
||||
Bereichskategorien einschließlich Unterkategorien. Freigaben für Geräte im Plan
|
||||
verwenden deren feste Datenpunkt-Verknüpfungen. Automatisch zugeordnete Geräte
|
||||
können über **Weitere Symcon-Geräte / Datenpunkte** ergänzt oder im Editor fest
|
||||
verknüpft werden. Die Auswahl erfolgt aus dem Objektbaum; es müssen keine IDs
|
||||
eingetippt werden. Eine hier ausgewählte Instanz oder Kategorie umfasst ihre
|
||||
untergeordneten Datenpunkte. Ein ausgewählter Link gilt für sein Ziel.
|
||||
|
||||
Außerhalb freigegebener Räume bleiben die Gebäudegeometrie und Möbel sichtbar;
|
||||
ihre Live-Verknüpfungen werden entfernt. Einzeln freigegebene Geräte bleiben
|
||||
im jeweiligen Raum erreichbar, ohne dessen Raumklima freizugeben. Die Prüfung
|
||||
gilt auch für direkte API-Aufrufe, native Rollen-Aliase, Trends und Datenübertragungen.
|
||||
Benutzer erhalten weder den kompletten Objektbaum noch Projekt-Historie,
|
||||
Backups, Uploads oder Editor-Funktionen. Schaltbefehle mit nicht freigegebenen
|
||||
Zielen werden vor der ersten Aktion abgewiesen. Passive Variablen ohne native
|
||||
Schaltaktion bleiben für Benutzer schreibgeschützt.
|
||||
|
||||
**Passwort zurücksetzen**, Sperren, Löschen und **Benutzer abmelden** funktionieren
|
||||
in der Konsole. Änderungen an Konto oder Rechten beenden dessen bisherige
|
||||
Anmeldungen sofort. Passwörter werden gehasht gespeichert. Anmeldungen verwenden
|
||||
HttpOnly-Cookies und CSRF-Schutz; es gibt keine wiederverwendbaren Admin-Token
|
||||
im Viewer-Link oder in der Kachel. Der normale Zugang gilt bis zu zwölf Stunden
|
||||
mit maximal zwei Stunden Inaktivität. **Angemeldet bleiben** gilt bis zu 30 Tage
|
||||
mit maximal sieben Tagen Inaktivität. Ein Passwort-Reset oder eine Sperre hebt
|
||||
auch diese Anmeldungen auf. Für den Zugriff über das Internet die HTTPS-Adresse
|
||||
des Symcon-Servers bzw. des eigenen HTTPS-Proxys verwenden.
|
||||
|
||||
Nach dem Update erfordert die Kachel-Visualisierung eine Anmeldung. Vorherige
|
||||
Links mit `token=...` gelten nicht mehr als Admin-Zugang; der aktualisierte
|
||||
Konsolen-Knopf und die neue Anmeldeseite bleiben verfügbar. Unsichere lokale
|
||||
Browser-Entwürfe werden im Symcon-Zugang nicht zwischen Konten gespeichert.
|
||||
|
||||
## Änderungen in 0.3.0
|
||||
|
||||
- Passwort-Anmeldung und vollständige Benutzerverwaltung mit Raum- und
|
||||
Gerätefreigaben in der Symcon-Konfiguration (siehe oben).
|
||||
- **Pflastersteine**, **Trittplatten** und **Natursteinweg** als weitere
|
||||
Außenflächenarten: strukturierte Pflastersteine, einzelne Gartenplatten mit
|
||||
grünen Zwischenräumen und unregelmäßige Natursteinplatten. Texturmaßstab und
|
||||
Drehung sind wie bei den vorhandenen Arten pro Fläche einstellbar.
|
||||
|
||||
## Änderungen in 0.2.30
|
||||
|
||||
- Jede Außenfläche erhält **Texturmaßstab (%)** und **Texturdrehung (°)** direkt
|
||||
unter der Auswahl der Flächenart. 100 % ist die bisherige Größe, 200 % macht
|
||||
das Muster doppelt so groß und 50 % halb so groß. Der Bereich ist 5–2000 %;
|
||||
Drehungen werden auf eine volle Umdrehung normalisiert (auch negative Eingaben
|
||||
sind möglich).
|
||||
- Die Einstellungen betreffen ausschließlich das Muster der ausgewählten Fläche,
|
||||
gelten auch bei Gefälle und Transparenz und bleiben beim Speichern, Laden und
|
||||
Duplizieren erhalten. Bestehende Flächen behalten 100 % / 0°.
|
||||
- Eine Erklärung zu Maßstab und Drehung steht hinter dem Infosymbol.
|
||||
|
||||
## Änderungen in 0.2.29
|
||||
|
||||
- **Außenflächen einrasten:** Beim Zeichnen, Verschieben und Bearbeiten der Ecken
|
||||
@@ -479,7 +642,7 @@ Nach dem Update den Designer neu laden, damit die neue Übertragung auf beiden S
|
||||
### Update bei „Hook not found“
|
||||
|
||||
Das vollständige Modul auf 0.2.1 aktualisieren und die NextFloor-Instanzkonfiguration
|
||||
neu öffnen. Einmal **„WebHook reparieren“**, anschließend **„Designer in der Konsole öffnen“**
|
||||
neu öffnen. Einmal **„WebHook reparieren“**, anschließend **„Designer im Browser öffnen“**
|
||||
anklicken. Der Eintrag gehört unter **WebHook Control → Hooks (Intern)**; ein eigener
|
||||
PHP-Skript-Hook unter „Benutzerdefiniert“ ist nicht erforderlich. Die bestehende Instanz
|
||||
nicht neu anlegen, da ihr Plan in ihren Attributen gespeichert ist.
|
||||
@@ -508,7 +671,7 @@ nicht neu anlegen, da ihr Plan in ihren Attributen gespeichert ist.
|
||||
## Einrichtung
|
||||
|
||||
1. Eine **NextFloor**-Instanz anlegen.
|
||||
2. In ihrer Konfiguration auf **„Designer in der Konsole öffnen“** klicken und den Grundriss
|
||||
2. In ihrer Konfiguration auf **„Designer im Browser öffnen“** klicken und den Grundriss
|
||||
anlegen.
|
||||
3. Für die Anzeige in der Tile-Visualisierung die Instanz wie jede andere Visualisierungs-
|
||||
Instanz als Kachel hinzufügen.
|
||||
|
||||
+3
-3
@@ -6,7 +6,7 @@
|
||||
"compatibility": {
|
||||
"version": "9.0"
|
||||
},
|
||||
"version": "0.2.29",
|
||||
"build": 32,
|
||||
"date": 1794787200
|
||||
"version": "0.4.3",
|
||||
"build": 41,
|
||||
"date": 1795046400
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
require __DIR__ . '/support/access-runtime.php';
|
||||
$module = new AccessFixtureModule(); initializeAccessFixture($module);
|
||||
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
|
||||
$accounts = $method('accounts');
|
||||
$as = static function (string $name) use ($module, $accounts): void {
|
||||
foreach ($accounts as $id => $a) if ($a['name'] === $name) {
|
||||
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
|
||||
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
|
||||
}
|
||||
throw new RuntimeException('Unknown fixture account');
|
||||
};
|
||||
$denied = static function (callable $call, string $reason): void {
|
||||
try { $call(); throw new LogicException('Unexpected permission grant: ' . $reason); }
|
||||
catch (NextFloorDenied $e) { check($e->getMessage() === $reason, 'Expected ' . $reason . ', got ' . $e->getMessage()); }
|
||||
};
|
||||
foreach ($accounts as $a) check($a['password'] !== $a['name'] . '-test-password' && password_verify($a['name'] . '-test-password', $a['password']), 'Passwords are hashed');
|
||||
$form = $module->GetConfigurationForm();
|
||||
check(!str_contains($form, 'password_hash') && !str_contains($form, '$2y$') && !str_contains($form, '$argon2'), 'Configuration never exposes password hashes');
|
||||
check(str_contains($form, 'SelectObject') && str_contains($form, 'Büro 2'), 'Rights use actual plan and native object choices');
|
||||
|
||||
$as('empty');
|
||||
check($method('visibleTree', $method('objectTree'))['variables'] === [], 'An empty user sees no values');
|
||||
$building = $method('visibleBuilding');
|
||||
check(count($building['floors'][0]['rooms']) === 2 && count($building['floors'][0]['furniture']) === 1, 'All building geometry remains');
|
||||
check($building['floors'][0]['rooms'][0]['climate_card'] === false && $building['floors'][0]['rooms'][1]['area_id'] === null, 'No live room binding leaks');
|
||||
$denied(fn() => $method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]), 'admin_required');
|
||||
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
|
||||
|
||||
$as('reader');
|
||||
$tree = $method('visibleTree', $method('objectTree'));
|
||||
check(count($tree['variables']) === 9, 'Global readers see every variable and the schedule');
|
||||
check(!in_array(888, array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'), true), 'All means the visualization, never unrelated Symcon variables');
|
||||
check(!in_array(888, array_column($tree['objects'], 'object_id'), true), 'Users never receive unrelated native object branches');
|
||||
foreach ($tree['variables'] as $v) check($v['attributes']['symcon_can_control'] === false, 'Every reader value is marked readonly');
|
||||
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
|
||||
|
||||
$as('office');
|
||||
$tree = $method('visibleTree', $method('objectTree'));
|
||||
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
|
||||
check($ids === [101, 102, 103, 104, 105], 'Room control exposes its own native category and schedule only; links do not pull in private targets');
|
||||
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'cover.101']]); // alias uses the same native capability
|
||||
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => ['light.101', 'light.201']]]), 'control_forbidden');
|
||||
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.103']]), 'variable_readonly');
|
||||
$method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.104']);
|
||||
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.204']), 'read_forbidden');
|
||||
$building = $method('visibleBuilding');
|
||||
check($building['floors'][0]['rooms'][1]['climate']['temperature'] === 'none', 'Foreign room climate is removed');
|
||||
check($building['floors'][0]['placements'][1]['entity_id'] === 'none', 'Foreign placement link is removed even while its geometry stays');
|
||||
$topology = $method('objectTree');
|
||||
foreach ($topology['objects'] as &$node) if ($node['object_id'] === 103) $node['parent_id'] = 11;
|
||||
unset($node);
|
||||
$topology['objects'][] = ['object_id' => 11, 'parent_id' => 10, 'name' => 'Strom', 'path' => 'Gebäude / Büro 2 / Strom', 'object_type' => 0];
|
||||
$as('office');
|
||||
$withTopology = $method('visibleTree', $topology);
|
||||
check(in_array(11, array_column($withTopology['objects'], 'object_id'), true), 'Utility discovery retains an authorized meter category');
|
||||
check(!in_array(900, array_column($withTopology['objects'], 'object_id'), true), 'Unrelated instance branches remain private');
|
||||
|
||||
$as('device');
|
||||
$tree = $method('visibleTree', $method('objectTree'));
|
||||
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
|
||||
check($ids === [102, 103], 'Single-device grant does not grant its whole room or native area');
|
||||
$building = $method('visibleBuilding');
|
||||
check($building['floors'][0]['rooms'][0]['climate_card'] === false, 'Device grant does not reveal room climate');
|
||||
check(in_array('switch.102', $building['floors'][0]['rooms'][0]['panel'], true), 'Approved device is still reachable in its room under its actual native entity');
|
||||
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.101']]), 'control_forbidden');
|
||||
|
||||
// Shared variables and legacy bindings on a different item must not reappear outside the granted room.
|
||||
$extended = fixtureBuilding();
|
||||
$extended['floors'][0]['furniture'][] = ['id' => 'private', 'type' => 'wallbox', 'x' => 7, 'z' => 2, 'temp_entity2' => 'sensor.104', 'legacy_binding' => 'sensor.104', 'picture' => 'https://camera.invalid/live'];
|
||||
$fixture['attributes']['Building'] = json_encode($extended);
|
||||
$as('office'); $projected = $method('visibleBuilding')['floors'][0]['furniture'][1];
|
||||
check($projected['temp_entity2'] === 'none' && $projected['legacy_binding'] === 'none' && !isset($projected['picture']), 'Unauthorized items never reuse otherwise approved values or live pictures');
|
||||
$extended['floors'][0]['furniture'][0]['temp_entity2'] = 'sensor.104';
|
||||
$fixture['attributes']['Building'] = json_encode($extended);
|
||||
$as('device');
|
||||
check($method('allowedEntity', 'sensor.104', false), 'Additional temperature bindings belong to an explicitly granted device');
|
||||
$extended['floors'][0]['furniture'][0]['hydronic'] = ['status' => 'cover.104', 'circuits' => [['id' => 'c1', 'status' => 'cover.105']], 'stations' => [['id' => 's1', 'status' => 'cover.204']]];
|
||||
$fixture['attributes']['Building'] = json_encode($extended);
|
||||
$as('device');
|
||||
foreach ([104, 105, 204] as $id) check($method('allowedEntity', 'sensor.' . $id, false), 'A granted device includes its plant, circuit and station status');
|
||||
$as('empty');
|
||||
$hiddenHydronic = $method('visibleBuilding')['floors'][0]['furniture'][0]['hydronic'];
|
||||
check($hiddenHydronic['status'] === 'none' && $hiddenHydronic['circuits'][0]['status'] === 'none' && $hiddenHydronic['stations'][0]['status'] === 'none', 'Unauthorized hydronic statuses remain private');
|
||||
$fixture['attributes']['Building'] = json_encode(fixtureBuilding());
|
||||
|
||||
$as('operator');
|
||||
$method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.201']]);
|
||||
$denied(fn() => $method('authorizeApi', 'archive/trend', ['entity_id' => 'sensor.888']), 'read_forbidden');
|
||||
$denied(fn() => $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'sensor.888']]), 'control_forbidden');
|
||||
$as('native');
|
||||
$tree = $method('visibleTree', $method('objectTree'));
|
||||
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
|
||||
check($ids === [201, 203], 'An explicit native instance grant follows its descendants, not its whole area');
|
||||
|
||||
$as('admin');
|
||||
$method('authorizeApi', 'building/save', ['building' => fixtureBuilding()]);
|
||||
check(count($method('visibleTree', $method('objectTree'))['objects']) > 0, 'Admin retains the native editor tree');
|
||||
check($method('visibleBuilding') === fixtureBuilding(), 'Admin project is unmodified');
|
||||
ob_start(); $method('sendApiResult', ['payload' => str_repeat('x', 300000)], true); $manifest = json_decode((string) ob_get_clean(), true)['_nextfloor_transfer'];
|
||||
$as('reader');
|
||||
try { $method('readTransfer', $manifest['id'], 0); throw new LogicException('Cross-session transport read was accepted'); }
|
||||
catch (RuntimeException $e) { check($e->getMessage() === 'transfer_not_found', 'Transfer ownership is enforced'); }
|
||||
$method('releaseTransfer', $manifest['id']);
|
||||
$as('admin');
|
||||
check(strlen($method('readTransfer', $manifest['id'], 0)['data']) > 0, 'Another session cannot remove this snapshot');
|
||||
$method('releaseTransfer', $manifest['id']);
|
||||
$url = $module->OpenDesigner(); parse_str((string) parse_url(substr($url, 5), PHP_URL_QUERY), $query);
|
||||
check(isset($query['ticket']) && !isset($query['token']), 'Console links use tickets, never a reusable admin token');
|
||||
check($method('exchangeConsoleTicket', $query['ticket']), 'Console recovers admin access without an account');
|
||||
check(!$method('exchangeConsoleTicket', $query['ticket']), 'Console tickets cannot be replayed');
|
||||
check(!str_contains($module->GetVisualizationTile(), 'ticket=') && !str_contains($module->GetVisualizationTile(), 'token='), 'Tiles never embed admin capabilities');
|
||||
|
||||
// A saved rights/enable change and a native delete revoke a previously valid cookie.
|
||||
$accountID = array_key_first(array_filter($accounts, static fn(array $a): bool => $a['name'] === 'officeview'));
|
||||
$browserToken = str_repeat('b', 64);
|
||||
$fixture['attributes']['Sessions'] = json_encode([hash('sha256', $browserToken) => ['account' => $accountID, 'epoch' => $accounts[$accountID]['epoch'], 'csrf' => 'test', 'seen' => time(), 'expires' => time() + 3600]]);
|
||||
$_COOKIE['NFSC_Session_12345'] = $browserToken;
|
||||
check($method('resolveSession') !== null, 'Cookie starts valid');
|
||||
$module->SaveAccessUser($accountID, 'officeview', 'user', false, false, false, '[]', '[]', '[]', '');
|
||||
check($method('resolveSession') === null, 'Disabling or editing rights revokes the old cookie');
|
||||
$module->DeleteAccessUser($accountID);
|
||||
check(!isset($method('accounts')[$accountID]) && $method('resolveSession') === null, 'Deletion removes the account and its access');
|
||||
echo "OK: hashed accounts, console recovery, one-use tickets, admin/reader/room/device scopes, alias-resistant access, private state and geometry separation, bulk preauthorization, archive guards and native readonly variables\n";
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
if (!getenv('NEXTFLOOR_TEST_STATE')) { echo "Local authentication browser-test fixture; NEXTFLOOR_TEST_STATE required.\n"; exit; }
|
||||
require __DIR__ . '/support/access-runtime.php';
|
||||
$module = new AccessFixtureModule(); initializeAccessFixture($module);
|
||||
$path = parse_url((string) $_SERVER['REQUEST_URI'], PHP_URL_PATH);
|
||||
if ($path === '/__test/console') { header('Content-Type: application/json'); echo json_encode(['url' => substr($module->OpenDesigner(), 5)]); return; }
|
||||
if ($path === '/__test/state') {
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode(['writes' => $fixture['writes'], 'accounts' => array_map(static fn(array $a): array => ['name' => $a['name'], 'enabled' => $a['enabled']], json_decode($fixture['attributes']['Accounts'], true))]); return;
|
||||
}
|
||||
if ($path === '/__test/reset' && $_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$data = json_decode((string) file_get_contents('php://input'), true);
|
||||
$accounts = json_decode($fixture['attributes']['Accounts'], true);
|
||||
foreach ($accounts as $id => $a) if ($a['name'] === ($data['name'] ?? '')) { echo $module->ResetUserPassword($id, (string) ($data['password'] ?? '')); return; }
|
||||
}
|
||||
$module->hook();
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
require __DIR__ . '/support/access-runtime.php';
|
||||
$module = new AccessFixtureModule(); initializeAccessFixture($module);
|
||||
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
|
||||
$as = static function (string $name) use ($module, $method): void {
|
||||
foreach ($method('accounts') as $id => $a) if ($a['name'] === $name) {
|
||||
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
|
||||
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
|
||||
}
|
||||
};
|
||||
$before = $method('building'); $after = $before;
|
||||
$source = &$after['floors'][0];
|
||||
$target = [...$source, 'id' => 'og', 'name' => 'Obergeschoss', 'elevation' => 3, 'rooms' => [], 'furniture' => [], 'placements' => []];
|
||||
$target['rooms'][] = array_shift($source['rooms']);
|
||||
$target['furniture'][] = array_shift($source['furniture']);
|
||||
$target['placements'][] = array_shift($source['placements']);
|
||||
unset($source); $after['floors'][] = $target;
|
||||
$as('admin'); $method('saveBuilding', $after);
|
||||
$accounts = array_column($method('accounts'), null, 'name');
|
||||
check($accounts['office']['rooms'] === [['target' => 'room:og:office2', 'access' => 'control']], 'Room control rights follow the moved room');
|
||||
check($accounts['officeview']['rooms'] === [['target' => 'room:og:office2', 'access' => 'view']], 'Readonly room rights stay readonly');
|
||||
check($accounts['device']['devices'] === [['target' => 'furniture:og:wallbox', 'access' => 'control']], 'Explicit device rights follow its unique identity');
|
||||
check($accounts['empty']['rooms'] === [] && $accounts['empty']['devices'] === [], 'Moving cannot create a new grant');
|
||||
$as('office'); $tree = $method('visibleTree', $method('objectTree'));
|
||||
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
|
||||
check($ids === [101, 102, 103, 104, 105], 'The moved room still exposes exactly its original native variables');
|
||||
$as('device'); $method('authorizeApi', 'variables/action', ['data' => ['entity_id' => 'light.102']]);
|
||||
$as('admin'); $method('saveBuilding', $before);
|
||||
$accounts = array_column($method('accounts'), null, 'name');
|
||||
check($accounts['office']['rooms'][0]['target'] === 'room:eg:office2', 'Undo restores the original grant key');
|
||||
check($accounts['device']['devices'][0]['target'] === 'furniture:eg:wallbox', 'Undo also restores the explicit device key');
|
||||
|
||||
// An ambiguous ID may be a duplicate rather than a move; never guess and widen its grant.
|
||||
$ambiguous = $after; $ambiguous['floors'][0]['furniture'][] = $target['furniture'][0];
|
||||
$method('saveBuilding', $ambiguous);
|
||||
$accounts = array_column($method('accounts'), null, 'name');
|
||||
check($accounts['device']['devices'][0]['target'] === 'furniture:eg:wallbox', 'Duplicate identities never trigger automatic grant migration');
|
||||
echo "OK: room/device grants follow unique floor moves and undo, preserve view/control levels and native visibility, reject ambiguous identities and create no grants\n";
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
// Deliberately small local Symcon fixture. No connection to a user's actual kernel or variables.
|
||||
const KR_READY = 10103;
|
||||
const IPS_KERNELSTARTED = 10001;
|
||||
const KL_ERROR = 10205;
|
||||
$fixtureFile = getenv('NEXTFLOOR_TEST_STATE') ?: '';
|
||||
$fixture = $fixtureFile !== '' && is_file($fixtureFile) ? json_decode((string) file_get_contents($fixtureFile), true) : [];
|
||||
$fixture += ['attributes' => [], 'properties' => [], 'writes' => [], 'initialized' => false];
|
||||
function persistFixture(): void { global $fixture, $fixtureFile; if ($fixtureFile !== '') file_put_contents($fixtureFile, json_encode($fixture, JSON_THROW_ON_ERROR), LOCK_EX); }
|
||||
function check(bool $condition, string $message): void { if (!$condition) throw new RuntimeException($message); }
|
||||
class IPSModuleStrict
|
||||
{
|
||||
protected int $InstanceID;
|
||||
public array $fields = [];
|
||||
public function __construct(int $id = 12345) { $this->InstanceID = $id; }
|
||||
public function Create(): void {}
|
||||
public function ApplyChanges(): void {}
|
||||
public function MessageSink(int $t, int $s, int $m, array $d): void {}
|
||||
protected function RegisterPropertyString(string $name, string $value): void { global $fixture; $fixture['properties'][$name] ??= $value; persistFixture(); }
|
||||
protected function RegisterAttributeString(string $name, string $value): void { global $fixture; $fixture['attributes'][$name] ??= $value; persistFixture(); }
|
||||
protected function RegisterAttributeInteger(string $name, int $value): void { global $fixture; $fixture['attributes'][$name] ??= $value; persistFixture(); }
|
||||
protected function ReadAttributeString(string $name): string { global $fixture; return (string) ($fixture['attributes'][$name] ?? ''); }
|
||||
protected function ReadAttributeInteger(string $name): int { global $fixture; return (int) ($fixture['attributes'][$name] ?? 0); }
|
||||
protected function WriteAttributeString(string $name, string $value): void { global $fixture; $fixture['attributes'][$name] = $value; persistFixture(); }
|
||||
protected function WriteAttributeInteger(string $name, int $value): void { global $fixture; $fixture['attributes'][$name] = $value; persistFixture(); }
|
||||
protected function ReadPropertyString(string $name): string { global $fixture; return (string) ($fixture['properties'][$name] ?? ''); }
|
||||
protected function RegisterMessage(int $sender, int $message): void {}
|
||||
protected function RegisterTimer(string $name, int $interval, string $script): void {}
|
||||
protected function SetTimerInterval(string $name, int $interval): void {}
|
||||
protected function SetVisualizationType(int $type): void {}
|
||||
protected function SetStatus(int $status): void {}
|
||||
protected function LogMessage(string $message, int $type): void { throw new RuntimeException('Unexpected module log: ' . $message); }
|
||||
protected function RegisterHook(string $path): bool { return true; }
|
||||
protected function UpdateFormField(string $name, string $key, mixed $value): void { $this->fields[$name][$key] = $value; }
|
||||
protected function UpdateVisualizationValue(string $value): void {}
|
||||
}
|
||||
function IPS_GetKernelRunlevel(): int { return KR_READY; }
|
||||
function IPS_GetInstanceListByModuleID(string $module): array { return $module === '{43192F0B-135B-4CE7-A0A7-1475603F3060}' ? [700] : []; }
|
||||
function fixtureObjects(): array
|
||||
{
|
||||
return [1 => [0, 0, 'Gebäude'], 10 => [1, 0, 'Büro 2'], 20 => [1, 0, 'Büro 3'], 900 => [20, 1, 'Privates Gerät'],
|
||||
101 => [10, 2, 'Licht'], 102 => [10, 2, 'Wallbox schalten'], 103 => [10, 2, 'Wallbox Leistung'], 104 => [10, 2, 'Raumtemperatur'],
|
||||
105 => [10, 4, 'Schaltuhr'], 201 => [900, 2, 'Licht privat'], 203 => [900, 2, 'Leistung privat'], 204 => [20, 2, 'Temperatur privat'],
|
||||
999 => [1, 2, 'Gesamtleistung'], 888 => [1, 2, 'Nicht mit NextFloor verknüpftes Geheimnis'], 109 => [10, 6, 'Link auf privaten Datenpunkt']];
|
||||
}
|
||||
function IPS_ObjectExists(int $id): bool { return isset(fixtureObjects()[$id]); }
|
||||
function IPS_VariableExists(int $id): bool { return (fixtureObjects()[$id][1] ?? -1) === 2; }
|
||||
function IPS_EventExists(int $id): bool { return $id === 105; }
|
||||
function IPS_GetName(int $id): string { return fixtureObjects()[$id][2]; }
|
||||
function IPS_GetObject(int $id): array { $o = fixtureObjects()[$id]; return ['ParentID' => $o[0], 'ObjectType' => $o[1], 'ObjectPosition' => $id, 'ObjectIsHidden' => false, 'ObjectIcon' => '']; }
|
||||
function IPS_GetChildrenIDs(int $id): array { return array_keys(array_filter(fixtureObjects(), static fn(array $o): bool => $o[0] === $id)); }
|
||||
function IPS_GetLink(int $id): array { return ['TargetID' => 201]; }
|
||||
function IPS_GetInstance(int $id): array { return ['ModuleInfo' => ['ModuleType' => 3, 'ModuleID' => '{00000000-0000-0000-0000-000000000001}']]; }
|
||||
function IPS_GetVariable(int $id): array { return ['VariableType' => in_array($id, [101, 102, 201], true) ? 0 : 2, 'VariableCustomAction' => 0, 'VariableAction' => in_array($id, [101, 102, 201], true) ? 1 : 0, 'VariableCustomProfile' => '', 'VariableProfile' => '']; }
|
||||
function IPS_GetVariablePresentation(int $id): array { return ['SUFFIX' => in_array($id, [104, 204], true) ? '°C' : (in_array($id, [103, 203, 999], true) ? 'W' : ''), 'MIN' => 0, 'MAX' => 100]; }
|
||||
function IPS_VariableProfileExists(string $name): bool { return false; }
|
||||
function GetValue(int $id): mixed { global $fixture; return $fixture['values'][$id] ?? match ($id) { 101, 102 => true, 201 => false, 104 => 22.3, 204 => 26.7, 103 => 7400.0, 203 => 531.0, default => 7931.0 }; }
|
||||
function GetValueFormatted(int $id): string { $v = GetValue($id); return is_bool($v) ? ($v ? 'An' : 'Aus') : (string) $v; }
|
||||
function RequestAction(int $id, mixed $value): void { global $fixture; $fixture['writes'][] = [$id, $value]; $fixture['values'][$id] = $value; persistFixture(); }
|
||||
function SetValue(int $id, mixed $value): void { RequestAction($id, $value); }
|
||||
function IPS_GetEvent(int $id): array { global $fixture; return ['EventType' => 2, 'EventActive' => $fixture['values'][105] ?? true, 'ScheduleActions' => [], 'ScheduleGroups' => []]; }
|
||||
function IPS_SetEventActive(int $id, bool $active): bool { RequestAction($id, $active); return true; }
|
||||
function AC_GetAggregationVariables(int $id, bool $all): array { return array_map(static fn(int $v): array => ['VariableID' => $v, 'AggregationActive' => true, 'AggregationType' => 0], [104, 204]); }
|
||||
function AC_GetLoggedValues(int $a, int $id, int $start, int $end, int $limit): array { return $start === 0 ? [] : [['TimeStamp' => $start, 'Value' => GetValue($id), 'Duration' => 60], ['TimeStamp' => $end, 'Value' => GetValue($id), 'Duration' => 0]]; }
|
||||
function AC_GetAggregatedValues(int $a, int $id, int $level, int $start, int $end, int $limit): array { return []; }
|
||||
|
||||
require_once __DIR__ . '/../../NextFloor/module.php';
|
||||
class AccessFixtureModule extends NextFloor { public function hook(): void { $this->ProcessHookData(); } }
|
||||
|
||||
function fixtureBuilding(): array
|
||||
{
|
||||
$room = static fn(string $id, string $name, int $x, int $category, string $temperature): array => ['id' => $id, 'name' => $name, 'area_id' => 'symcon-category-' . $category, 'points' => [[$x, 0], [$x + 4, 0], [$x + 4, 3], [$x, 3]], 'floor_material' => 'wood', 'climate_card' => true, 'climate' => ['temperature' => $temperature]];
|
||||
return ['version' => 1, 'settings' => ['grid' => 0.1, 'north' => 0, 'wall_exterior' => 0.24, 'wall_interior' => 0.12, 'roof' => ['type' => 'none'], 'plugins' => []],
|
||||
'energy' => ['consumption' => 'sensor.999'], 'presence' => [], 'floors' => [['id' => 'eg', 'name' => 'Erdgeschoss', 'elevation' => 0, 'height' => 2.7, 'cut_height' => 1.2,
|
||||
'rooms' => [$room('office2', 'Büro 2', 0, 10, 'sensor.104'), $room('office3', 'Büro 3', 5, 20, 'sensor.204')],
|
||||
'openings' => [], 'walls' => [], 'outdoor' => [], 'background' => null,
|
||||
'placements' => [['entity_id' => 'light.101', 'x' => 2, 'z' => 1, 'y' => null], ['entity_id' => 'light.201', 'x' => 7, 'z' => 1, 'y' => null]],
|
||||
'furniture' => [['id' => 'wallbox', 'type' => 'wallbox', 'name' => 'Wallbox Büro 2', 'x' => 3, 'z' => 2, 'w' => 0.3, 'd' => 0.3, 'h' => 0.4, 'rotation' => 0, 'entity' => 'light.102', 'power' => 'sensor.103', 'power_card' => true]]]]];
|
||||
}
|
||||
|
||||
function initializeAccessFixture(AccessFixtureModule $module): void
|
||||
{
|
||||
global $fixture;
|
||||
$module->Create();
|
||||
if ($fixture['initialized']) return;
|
||||
$fixture['properties']['Title'] = 'Bürogebäude';
|
||||
$fixture['attributes']['Building'] = json_encode(fixtureBuilding(), JSON_THROW_ON_ERROR);
|
||||
$fixture['attributes']['BuildingRevision'] = 1;
|
||||
$make = static function (string $name, string $role, bool $viewAll, bool $controlAll, array $rooms = [], array $devices = [], array $objects = []) use ($module): void {
|
||||
$result = $module->SaveAccessUser('', $name, $role, true, $viewAll, $controlAll, json_encode($rooms), json_encode($devices), json_encode($objects), $name . '-test-password');
|
||||
check(str_starts_with($result, 'Benutzer gespeichert'), $result);
|
||||
};
|
||||
$make('admin', 'admin', true, true);
|
||||
$make('reader', 'user', true, false);
|
||||
$make('office', 'user', false, false, [['target' => 'room:eg:office2', 'access' => 'control']]);
|
||||
$make('officeview', 'user', false, false, [['target' => 'room:eg:office2', 'access' => 'view']]);
|
||||
$make('device', 'user', false, false, [], [['target' => 'furniture:eg:wallbox', 'access' => 'control']]);
|
||||
$make('empty', 'user', false, false);
|
||||
$make('operator', 'user', true, true);
|
||||
$make('native', 'user', false, false, [], [], [['target' => 900, 'access' => 'view']]);
|
||||
$fixture['initialized'] = true; persistFixture();
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
require __DIR__ . '/support/access-runtime.php';
|
||||
$module = new AccessFixtureModule(); initializeAccessFixture($module);
|
||||
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
|
||||
$accounts = $method('accounts');
|
||||
$as = static function (string $name) use ($module, $accounts): void {
|
||||
foreach ($accounts as $id => $a) if ($a['name'] === $name) {
|
||||
(new ReflectionProperty(NextFloor::class, 'requestUser'))->setValue($module, [...$a, 'id' => $id, 'session_id' => 'fixture-' . $name, 'csrf' => 'fixture']);
|
||||
(new ReflectionProperty(NextFloor::class, 'requestScope'))->setValue($module, null); return;
|
||||
}
|
||||
};
|
||||
$b = fixtureBuilding();
|
||||
$b['topology'] = ['locations' => [['id' => 'urbach', 'name' => 'Urbach'], ['id' => 'ulm', 'name' => 'Ulm']],
|
||||
'branches' => [['id' => 'hq', 'name' => 'Zentrale', 'location_id' => 'urbach'], ['id' => 'south', 'name' => 'Süd', 'location_id' => 'ulm']],
|
||||
'buildings' => [['id' => 'ras19', 'name' => 'RAS19', 'branch_id' => 'hq'], ['id' => 'ulm1', 'name' => 'RAS19', 'branch_id' => 'south']]];
|
||||
$b['floors'][0]['building_id'] = 'ras19';
|
||||
$outside = ['id' => 'garden', 'name' => 'Außen', 'building_id' => null, 'outdoor_location_id' => 'urbach', 'elevation' => 0, 'height' => 2.5,
|
||||
'rooms' => [], 'openings' => [], 'placements' => [], 'outdoor' => [], 'furniture' => [['id' => 'garden-meter', 'type' => 'wallbox', 'name' => 'Gartengerät', 'entity' => 'sensor.203', 'x' => 1, 'z' => 2]]];
|
||||
$b['floors'][] = $outside;
|
||||
$b['floors'][] = [...$outside, 'id' => 'branch-garden', 'outdoor_location_id' => null, 'outdoor_branch_id' => 'hq', 'furniture' => [[...$outside['furniture'][0], 'id' => 'branch-meter', 'name' => 'Hofgerät']]];
|
||||
$b['floors'][] = [...$outside, 'id' => 'building-garden', 'outdoor_location_id' => null, 'outdoor_building_id' => 'ras19', 'furniture' => [[...$outside['furniture'][0], 'id' => 'building-meter', 'name' => 'Terrassengerät']]];
|
||||
$as('admin'); $method('authorizeApi', 'building/save', ['building' => $b]); $method('saveBuilding', $b);
|
||||
check($method('building')['topology'] === $b['topology'], 'The complete hierarchy persists without changing native links');
|
||||
$form = $module->GetConfigurationForm();
|
||||
check(str_contains($form, 'Urbach / Zentrale / RAS19 / Erdgeschoss / Büro 2'), 'Room choices include their complete topology path');
|
||||
check(str_contains($form, 'Urbach / Außen / Gartengerät'), 'Outdoor device grants belong to the location path');
|
||||
check(str_contains($form, 'Urbach / Zentrale / Außen / Hofgerät'), 'Branch outdoor device grants use their own full path');
|
||||
check(str_contains($form, 'Urbach / Zentrale / RAS19 / Außen / Terrassengerät'), 'Building outdoor device grants use their own full path');
|
||||
|
||||
$as('office');
|
||||
$tree = $method('visibleTree', $method('objectTree'));
|
||||
$ids = array_column(array_column($tree['variables'], 'attributes'), 'symcon_id'); sort($ids);
|
||||
check($ids === [101, 102, 103, 104, 105], 'Existing room rights keep their stable key and do not grant outdoor/other-location values');
|
||||
$visible = $method('visibleBuilding');
|
||||
check($visible['topology'] === $b['topology'], 'Users retain the complete logical topology, like the building geometry');
|
||||
check($visible['floors'][1]['furniture'][0]['entity'] === 'none', 'Unapproved outdoor status is still filtered server-side');
|
||||
$as('empty');
|
||||
check($method('visibleTree', $method('objectTree'))['variables'] === [], 'Adding topology cannot grant access to an empty account');
|
||||
echo "OK: persisted five-level topology with location/branch/building outdoors; complete grant choice paths; unchanged room keys; scoped state and native permissions\n";
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
require __DIR__ . '/support/access-runtime.php';
|
||||
$module = new AccessFixtureModule(); initializeAccessFixture($module);
|
||||
$method = static fn(string $name, mixed ...$args): mixed => (new ReflectionMethod($module, $name))->invoke($module, ...$args);
|
||||
|
||||
// Like a native List variable, this object is iterable/array-accessible but does not JSON-encode its rows.
|
||||
final class NativeFormList implements IteratorAggregate, ArrayAccess
|
||||
{
|
||||
public function __construct(private array $rows) {}
|
||||
public function getIterator(): Traversable { foreach ($this->rows as $row) yield new ArrayObject($row); }
|
||||
public function offsetExists(mixed $offset): bool { return isset($this->rows[$offset]); }
|
||||
public function offsetGet(mixed $offset): mixed { return $this->rows[$offset] ?? null; }
|
||||
public function offsetSet(mixed $offset, mixed $value): void { throw new LogicException('Readonly fixture'); }
|
||||
public function offsetUnset(mixed $offset): void { throw new LogicException('Readonly fixture'); }
|
||||
}
|
||||
function NFSC_SaveAccessUser(int $id, string $user, string $name, string $role, bool $enabled, bool $view, bool $control, string $rooms, string $devices, string $objects, string $password): string
|
||||
{
|
||||
global $module;
|
||||
return $module->SaveAccessUser($user, $name, $role, $enabled, $view, $control, $rooms, $devices, $objects, $password);
|
||||
}
|
||||
function NFSC_SelectAccessUser(int $id, string $user): void { global $module; $module->SelectAccessUser($user); }
|
||||
function formItems(): array
|
||||
{
|
||||
global $module;
|
||||
$form = json_decode($module->GetConfigurationForm(), true, 512, JSON_THROW_ON_ERROR);
|
||||
return array_values(array_filter($form['actions'], static fn(array $a): bool => ($a['type'] ?? '') === 'ExpansionPanel'))[0]['items'];
|
||||
}
|
||||
function clickSave(string $script, array $fields): string
|
||||
{
|
||||
extract($fields);
|
||||
$id = 12345;
|
||||
ob_start();
|
||||
try { eval($script); return (string) ob_get_contents(); }
|
||||
finally { ob_end_clean(); }
|
||||
}
|
||||
$items = formItems();
|
||||
$names = array_column($items, 'name');
|
||||
check(array_search('AccountPassword', $names, true) === array_search('AccountName', $names, true) + 1, 'Password belongs directly below the user name');
|
||||
$save = array_values(array_filter($items, static fn(array $item): bool => ($item['caption'] ?? '') === 'Benutzer speichern'))[0]['onClick'];
|
||||
$script = is_array($save) ? implode("\n", $save) : $save;
|
||||
$fields = ['AccountSelect' => '', 'AccountName' => 'form-empty', 'AccountRole' => 'user', 'AccountEnabled' => true,
|
||||
'AccountViewAll' => true, 'AccountControlAll' => false, 'AccountPassword' => 'form-test-password',
|
||||
'AccountRooms' => new NativeFormList([]), 'AccountDevices' => new NativeFormList([]), 'AccountObjects' => new NativeFormList([])];
|
||||
check(json_encode($fields['AccountRooms']) === '{}', 'Fixture reproduces the unsupported direct List serialization');
|
||||
check(str_starts_with(clickSave($script, $fields), 'Benutzer gespeichert.'), 'The actual save button accepts empty native form lists');
|
||||
$emptyID = $module->fields['AccountSelect']['value'];
|
||||
$empty = $method('accounts')[$emptyID];
|
||||
check($empty['rooms'] === [] && $empty['devices'] === [] && $empty['objects'] === [], 'Empty tables remain empty');
|
||||
|
||||
$rooms = [['target' => 'room:eg:office2', 'access' => 'view'], ['target' => 'room:old:removed', 'access' => 'control']];
|
||||
$devices = [['target' => 'furniture:eg:wallbox', 'access' => 'control']];
|
||||
$objects = [['target' => 900, 'access' => 'view'], ['target' => 104, 'access' => 'view']];
|
||||
$fields = [...$fields, 'AccountName' => 'form-scoped', 'AccountViewAll' => false,
|
||||
'AccountRooms' => new NativeFormList($rooms), 'AccountDevices' => new NativeFormList($devices), 'AccountObjects' => new NativeFormList($objects)];
|
||||
check(str_starts_with(clickSave($script, $fields), 'Benutzer gespeichert.'), 'The actual save button serializes every row, including rows that are not selected');
|
||||
$scopedID = $module->fields['AccountSelect']['value'];
|
||||
$scoped = $method('accounts')[$scopedID];
|
||||
check($scoped['rooms'] === $rooms && $scoped['devices'] === $devices && $scoped['objects'] === $objects, 'All three grant tables retain exact per-user rights');
|
||||
|
||||
$change = array_values(array_filter($items, static fn(array $item): bool => ($item['name'] ?? '') === 'AccountSelect'))[0]['onChange'];
|
||||
$select = static function (string $selected) use ($change): void { $id = 12345; $AccountSelect = $selected; eval($change); };
|
||||
$select($emptyID);
|
||||
foreach (['AccountRooms', 'AccountDevices', 'AccountObjects'] as $name) check(json_decode($module->fields[$name]['values'], true) === [], 'Switching to an unrestricted reader clears the previous grants');
|
||||
check($module->fields['AccountName']['value'] === 'form-empty' && $module->fields['AccountPassword']['value'] === '', 'User changes load the right name and clear the password field');
|
||||
check(!in_array('room:old:removed', array_column(json_decode($module->fields['AccountRooms']['columns'], true)[0]['edit']['options'], 'value'), true), 'Stale target choices do not leak into another user');
|
||||
$select($scopedID);
|
||||
foreach (['AccountRooms' => $rooms, 'AccountDevices' => $devices, 'AccountObjects' => $objects] as $name => $expected) check(json_decode($module->fields[$name]['values'], true) === $expected, 'Each table restores the selected user');
|
||||
check(in_array('room:old:removed', array_column(json_decode($module->fields['AccountRooms']['columns'], true)[0]['edit']['options'], 'value'), true), 'Previously linked missing plan targets remain visible when switching users');
|
||||
$fields = [...$fields, 'AccountSelect' => $scopedID, 'AccountPassword' => ''];
|
||||
check(str_starts_with(clickSave($script, $fields), 'Benutzer gespeichert.'), 'Saving an existing user permits an empty password');
|
||||
check(password_verify('form-test-password', $method('accounts')[$scopedID]['password']), 'Empty password preserves the previous hash');
|
||||
check(str_starts_with(clickSave($script, [...$fields, 'AccountSelect' => '', 'AccountName' => 'no-password']), 'Für neue Benutzer'), 'New accounts still require a password');
|
||||
$select('');
|
||||
foreach (['AccountRooms', 'AccountDevices', 'AccountObjects'] as $name) check(json_decode($module->fields[$name]['values'], true) === [], 'New user selection resets every grant table');
|
||||
check(!$module->fields['AccountReset']['enabled'] && !$module->fields['AccountDelete']['enabled'], 'New user selection disables existing-account operations');
|
||||
check($module->SaveAccessUser($emptyID, 'form-empty', 'user', true, true, false, '{"target":"room:eg:office2","access":"control"}', '[]', '[]', '') === 'Ungültige Freigabeliste.', 'A selected row cannot be mistaken for the complete grants list');
|
||||
|
||||
$form = json_decode($module->GetConfigurationForm(), true);
|
||||
check($form['actions'][1]['caption'] === 'Designer im Browser öffnen' && $form['actions'][1]['link'] === true, 'The browser link does not promise a native Pro Console tab');
|
||||
echo "OK: real form save with opaque iterable Lists; empty/multiple grants; user-switch reload/reset and missing-target choices; password position and preservation; honest browser action\n";
|
||||
@@ -56,6 +56,9 @@ export function validateSymconPackage(root = fileURLToPath(new URL("../", import
|
||||
ids.add(module.id);
|
||||
assert.equal(entry.name, module.name.replaceAll(" ", ""), "Module directory must match its PHP class name");
|
||||
const php = readFileSync(join(directory, "module.php"), "utf8");
|
||||
for (const helper of ["Access.php", "Users.php", "Permissions.php"]) {
|
||||
assert.ok(readFileSync(join(directory, "libs", helper)).length > 0, `Missing server access helper: ${helper}`);
|
||||
}
|
||||
assert.match(php, new RegExp(`class\\s+${entry.name}\\s+extends\\s+IPSModuleStrict\\b`), "Module PHP class is missing or mismatched");
|
||||
const form = readJson(join(directory, "form.json"));
|
||||
assert.ok(Array.isArray(form.elements) && Array.isArray(form.actions), "Module form must contain elements and actions");
|
||||
|
||||
@@ -144,7 +144,10 @@ $earlyFailure->RetryWebHook();
|
||||
check(isset($nativeHooks['/hook/nextfloor/34567']) && $earlyFailure->status === 102, 'Unavailable early WebHook Control must recover automatically');
|
||||
|
||||
// Verify that returned URLs reach the real dispatcher, including Symcon's SCRIPT_NAME fallback.
|
||||
parse_str((string) parse_url(substr($link, 5), PHP_URL_QUERY), $_GET);
|
||||
$_GET = [];
|
||||
$browserToken = str_repeat('a', 64);
|
||||
$_COOKIE = ['NFSC_Session_12345' => $browserToken];
|
||||
$module->attributes['Sessions'] = json_encode([hash('sha256', $browserToken) => ['account' => '__console__', 'epoch' => $token, 'csrf' => 'fixture', 'expires' => time() + 3600, 'seen' => time()]]);
|
||||
$_SERVER['REQUEST_URI'] = $hook . '/designer';
|
||||
$process = new ReflectionMethod($module, 'ProcessHookData');
|
||||
ob_start();
|
||||
@@ -163,9 +166,11 @@ $process->invoke($module);
|
||||
$fallback = ob_get_clean();
|
||||
check(str_contains($fallback, 'window.__NEXTFLOOR_SYMCON__='), 'Dispatcher must accept SCRIPT_NAME when REQUEST_URI is absent');
|
||||
$_GET['token'] = 'wrong-token';
|
||||
$_COOKIE = [];
|
||||
$_SERVER['SCRIPT_NAME'] = $hook . '/api';
|
||||
ob_start();
|
||||
$process->invoke($module);
|
||||
$unauthorized = ob_get_clean();
|
||||
check(http_response_code() === 403 && str_contains($unauthorized, 'forbidden'), 'Recovery must not bypass hook authentication');
|
||||
check(http_response_code() === 401 && str_contains($unauthorized, 'authentication_required'), 'Recovery and legacy URL tokens must not bypass session authentication');
|
||||
|
||||
echo "OK: early registration, startup/update and delayed reset recovery, ongoing maintenance, titles, data preservation, routing and authentication\n";
|
||||
+82
-1
@@ -19,6 +19,59 @@ from custom_components.nextfloor.schema import (
|
||||
ROOM = {"id": "r1", "name": "Bad", "area_id": None, "points": [[0, 0], [2, 0], [2, 2]], "floor_material": "tiles"}
|
||||
|
||||
|
||||
def test_topology_and_per_location_outdoor_membership_survive_validation() -> None:
|
||||
from custom_components.nextfloor.schema import BUILDING_SCHEMA, empty_building
|
||||
|
||||
topology = {
|
||||
"locations": [{"id": "urbach", "name": "Urbach"}, {"id": "ulm", "name": "Ulm"}],
|
||||
"branches": [{"id": "hq", "name": "Zentrale", "location_id": "urbach"}],
|
||||
"buildings": [{"id": "ras19", "name": "RAS19", "branch_id": "hq"}],
|
||||
}
|
||||
floor = {
|
||||
"id": "eg",
|
||||
"name": "EG",
|
||||
"elevation": 0,
|
||||
"height": 2.5,
|
||||
"cut_height": 1.15,
|
||||
"rooms": [ROOM],
|
||||
"openings": [],
|
||||
"placements": [],
|
||||
"furniture": [],
|
||||
"background": None,
|
||||
"outdoor": [],
|
||||
"building_id": "ras19",
|
||||
"outdoor_location_id": None,
|
||||
}
|
||||
outdoor = {
|
||||
**floor,
|
||||
"id": "garden",
|
||||
"name": "Außen",
|
||||
"building_id": None,
|
||||
"outdoor_location_id": "urbach",
|
||||
"rooms": [],
|
||||
}
|
||||
b = {**empty_building(), "topology": topology, "floors": [floor, outdoor]}
|
||||
result = BUILDING_SCHEMA(b)
|
||||
assert result["topology"] == topology
|
||||
assert result["floors"][0]["building_id"] == "ras19"
|
||||
assert result["floors"][1]["outdoor_location_id"] == "urbach"
|
||||
for field, owner in (("outdoor_branch_id", "hq"), ("outdoor_building_id", "ras19")):
|
||||
item = {**outdoor, "outdoor_location_id": None, field: owner}
|
||||
assert BUILDING_SCHEMA({**b, "floors": [floor, item]})["floors"][1][field] == owner
|
||||
with pytest.raises(vol.Invalid):
|
||||
BUILDING_SCHEMA({**b, "floors": [{**item, field: 123}]})
|
||||
assert "topology" not in BUILDING_SCHEMA(empty_building())
|
||||
for bad in (
|
||||
{**b, "topology": {**topology, "branches": [{"id": "hq", "name": "Zentrale", "location_id": 12}]}},
|
||||
{**b, "topology": {**topology, "buildings": [{"id": "ras19", "name": "RAS19", "branch_id": "invalid/id"}]}},
|
||||
{**b, "floors": [{**floor, "building_id": 123}]},
|
||||
{**b, "floors": [{**outdoor, "outdoor_location_id": 123}]},
|
||||
{**b, "floors": [floor] * 129},
|
||||
):
|
||||
with pytest.raises(vol.Invalid):
|
||||
BUILDING_SCHEMA(bad)
|
||||
|
||||
|
||||
def test_charging_station_links_formats_and_clearing_survive_validation() -> None:
|
||||
charging = {
|
||||
"soc": "cover.1",
|
||||
@@ -47,11 +100,13 @@ def test_freshwater_cascade_station_links_buffer_reference_and_limits() -> None:
|
||||
"hot_water": "climate.3",
|
||||
"cold_water": "cover.4",
|
||||
"power": "sensor.5",
|
||||
"status": "cover.10",
|
||||
"pump": {"command": "light.6", "feedback": "cover.7"},
|
||||
"valve": {"feedback": "climate.8"},
|
||||
"has_valve": True,
|
||||
}
|
||||
hydraulic = {
|
||||
"status": "lock.11",
|
||||
"stations": [{**station, "id": f"s{i}"} for i in range(4)],
|
||||
"buffer_id": "buffer",
|
||||
"circulation": {"feedback": "cover.9"},
|
||||
@@ -63,6 +118,8 @@ def test_freshwater_cascade_station_links_buffer_reference_and_limits() -> None:
|
||||
{"stations": []},
|
||||
{"stations": [station] * 17},
|
||||
{"stations": [{**station, "power": 123}]},
|
||||
{"stations": [{**station, "status": 123}]},
|
||||
{"status": 123},
|
||||
{"buffer_id": 123},
|
||||
):
|
||||
with pytest.raises(vol.Invalid):
|
||||
@@ -266,9 +323,11 @@ def test_hydronic_circuits_buffer_probes_and_fresh_water_bindings() -> None:
|
||||
"has_valve": False,
|
||||
"pump": control,
|
||||
"valve_type": "mixing",
|
||||
"status": "cover.7",
|
||||
}
|
||||
hydronic = {
|
||||
"card": True,
|
||||
"status": "lock.8",
|
||||
"circuits": [circuit],
|
||||
"sensors": [{"id": f"s{i}", "name": f"Fühler {i}", "entity": None, "level": i / 6} for i in range(7)],
|
||||
"flow": "light.3",
|
||||
@@ -281,6 +340,7 @@ def test_hydronic_circuits_buffer_probes_and_fresh_water_bindings() -> None:
|
||||
for bad in (
|
||||
{"circuits": [{**circuit, "kind": "guess_from_name"}]},
|
||||
{"circuits": [{**circuit, "valve_type": "unknown"}]},
|
||||
{"circuits": [{**circuit, "status": 123}]},
|
||||
{"circuits": [circuit] * 33},
|
||||
{"sensors": [{"id": "s", "name": "Fühler", "entity": None, "level": 1.01}]},
|
||||
{"pump": {"command": 12345}},
|
||||
@@ -401,10 +461,31 @@ def test_outdoor_area_opacity() -> None:
|
||||
OUTDOOR_SCHEMA({**base, "opacity": bad})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["street", "sidewalk", "gravel", "river", "stream"])
|
||||
@pytest.mark.parametrize(
|
||||
"kind", ["street", "sidewalk", "gravel", "river", "stream", "pavers", "stepping_stones", "natural_stone"]
|
||||
)
|
||||
def test_new_outdoor_surfaces(kind: str) -> None:
|
||||
from custom_components.nextfloor.schema import OUTDOOR_SCHEMA
|
||||
|
||||
data = {"id": "outside", "type": kind, "points": [[0, 0], [4.03, 0], [4, 3]], "slope": 0.2, "opacity": 0.4}
|
||||
result = OUTDOOR_SCHEMA(data)
|
||||
assert all(result[key] == value for key, value in data.items())
|
||||
|
||||
|
||||
def test_outdoor_texture_settings() -> None:
|
||||
from custom_components.nextfloor.schema import OUTDOOR_SCHEMA
|
||||
|
||||
base = {"id": "outside", "type": "terrace", "points": [[0, 0], [4, 0], [4, 3]]}
|
||||
old = OUTDOOR_SCHEMA(base)
|
||||
assert old["texture_scale"] is None and old["texture_rotation"] is None
|
||||
for scale, rotation in [(0.05, -360), (1, 0), (2.5, 45), (20, 360)]:
|
||||
result = OUTDOOR_SCHEMA({**base, "texture_scale": scale, "texture_rotation": rotation})
|
||||
assert result["texture_scale"] == scale and result["texture_rotation"] == rotation
|
||||
for key, invalid in [
|
||||
("texture_scale", 0),
|
||||
("texture_scale", 21),
|
||||
("texture_rotation", -361),
|
||||
("texture_rotation", 361),
|
||||
]:
|
||||
with pytest.raises(vol.Invalid):
|
||||
OUTDOOR_SCHEMA({**base, key: invalid})
|
||||
Reference in new issue
Block a user