@camstack/addon-admin-ui 1.2.476 → 1.2.477
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AddonAssetIcon-NsStjqDv.js → AddonAssetIcon-B_-30Ezl.js} +1 -1
- package/dist/assets/Addons-CbHidHOJ.js +5 -0
- package/dist/assets/{AdminPage-BBb_f0ke.js → AdminPage-3JxWocN3.js} +1 -1
- package/dist/assets/{AdminSectionedPage-B77fFYLu.js → AdminSectionedPage-DtiHBXGC.js} +1 -1
- package/dist/assets/AiProfiles-7FToWDqj.js +3 -0
- package/dist/assets/{BrokerForm-Dql4j_7g.js → BrokerForm-D5-q8F_8.js} +1 -1
- package/dist/assets/{Build-0VXUZTUO.js → Build-DwW5kYsa.js} +4 -4
- package/dist/assets/{Calendars-DDdCqGq7.js → Calendars-BhMRY6EV.js} +1 -1
- package/dist/assets/{Cluster-B8y8FoQV.js → Cluster-z11q6anB.js} +1 -1
- package/dist/assets/{CompositionBlockEditor-RHV08gl_.js → CompositionBlockEditor-CElNVsCR.js} +1 -1
- package/dist/assets/{CompositionEditorPage-zqBIwPtu.js → CompositionEditorPage-NzgZB76B.js} +1 -1
- package/dist/assets/Data-D_U-HkwO.js +2 -0
- package/dist/assets/{DeviceDetail-BhhXtfQ_.js → DeviceDetail-D89wXQHP.js} +2 -2
- package/dist/assets/{DeviceDoActionFields-CM877gWa.js → DeviceDoActionFields-Bj4gX0r-.js} +1 -1
- package/dist/assets/{Devices-D_p1jnJs.js → Devices-BnhDZU3y.js} +1 -1
- package/dist/assets/{EmbedPlayerPage-n_ZfqSgX.js → EmbedPlayerPage-Ccf5hGui.js} +1 -1
- package/dist/assets/{HelperWizard-WGprHYSO.js → HelperWizard-CrXHYd19.js} +2 -2
- package/dist/assets/History-BsJBR2zt.js +1 -0
- package/dist/assets/Identity-B_6I_sCY.js +1 -0
- package/dist/assets/IntegrationDetail-B9L7AfYy.js +1 -0
- package/dist/assets/IntegrationHub-CSaA690G.js +1 -0
- package/dist/assets/Integrations-B-KtSB_m.js +1 -0
- package/dist/assets/Integrations-CMW4LOX-.js +1 -0
- package/dist/assets/{Library-B6p5cMT3.js → Library-3dGkOQB5.js} +1 -1
- package/dist/assets/Locations-Bh5GRDCv.js +3 -0
- package/dist/assets/{Logs-DbUcQh4T.js → Logs-diqSxXEc.js} +1 -1
- package/dist/assets/{MyAccess-BjgGZZmK.js → MyAccess-BqulMSGv.js} +1 -1
- package/dist/assets/{Network-DJAN2ffw.js → Network-C8Gpb2Vn.js} +1 -1
- package/dist/assets/{NodeAddonsSettingsPanel-P5f0HKwt.js → NodeAddonsSettingsPanel-Dq6sGWkR.js} +1 -1
- package/dist/assets/Notifications-C5w5t75z.js +1 -0
- package/dist/assets/Pipeline-CjumfHMc.js +1 -0
- package/dist/assets/Recordings-DE76fgEt.js +1 -0
- package/dist/assets/{ScanNetworkModal-D0nIF1xL.js → ScanNetworkModal-DXzDOpxk.js} +1 -1
- package/dist/assets/SessionsList-Ca-zN1Fi.js +2 -0
- package/dist/assets/{Showroom-OGwDnxr_.js → Showroom-B9HZ38O5.js} +1 -1
- package/dist/assets/{System-CkfHfeMd.js → System-CHEbMPI_.js} +1 -1
- package/dist/assets/{Terminal-puPiVrKC.js → Terminal-CWFZuQLg.js} +3 -3
- package/dist/assets/{Viewer-QizHE8-x.js → Viewer-DwNVIy-u.js} +1 -1
- package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BIhn7NhC.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-QiJARN9B.js} +1 -1
- package/dist/assets/{addon-icons-context-DxUCqyaH.js → addon-icons-context-lrP_33gc.js} +1 -1
- package/dist/assets/{assignment-candidates-D58mtpje.js → assignment-candidates-BcnFMc1B.js} +1 -1
- package/dist/assets/{authed-media-B_8ON2MT.js → authed-media-CnaIhiH3.js} +1 -1
- package/dist/assets/{board-model-4EY3kgfH.js → board-model-gmvqxkjB.js} +1 -1
- package/dist/assets/{device-integration-icon-C28x8nbP.js → device-integration-icon-0oWIIjcP.js} +1 -1
- package/dist/assets/device-picker-model-CUPf26ML.js +1 -0
- package/dist/assets/{format-Bq6kzos8.js → format-CIO4xeN9.js} +1 -1
- package/dist/assets/{hostInit-EKt3RqKv.js → hostInit-DB6u6qxU.js} +1 -1
- package/dist/assets/i18n-xhwARoF0.js +1 -0
- package/dist/assets/icons-apbWMCU4.js +1 -0
- package/dist/assets/index-C3uCLHv0.js +4 -0
- package/dist/assets/{index-CU-5JpMo.css → index-D4ZlWCxy.css} +1 -1
- package/dist/assets/{linked-devices-model-Cgse8lhb.js → linked-devices-model-BoOq02QT.js} +1 -1
- package/dist/assets/{location-owned-usage-uS8d4cQL.js → location-owned-usage-IF2k-L3A.js} +1 -1
- package/dist/assets/{mf-entry-bootstrap-0-99fca1f4.js → mf-entry-bootstrap-0-f45a46c2.js} +2 -2
- package/dist/assets/mount-CUPf26ML.js +1 -0
- package/dist/assets/remoteEntry-CVuKB7K_.js +1 -0
- package/dist/assets/src-DntJrWmU.js +67 -0
- package/dist/assets/{step-inspector-model-C-7jLQzL.js → step-inspector-model-CyqFN-LU.js} +1 -1
- package/dist/assets/table-2-CTZnEliG.js +1 -0
- package/dist/assets/{use-scenes-feed-wrd7r_Sr.js → use-scenes-feed-D80maECB.js} +1 -1
- package/dist/assets/{use-stationary-objects-U-Gv-CIi.js → use-stationary-objects-DBEa50KS.js} +1 -1
- package/dist/assets/useEventInvalidation-CUPf26ML.js +1 -0
- package/dist/assets/{useNodeUrlSelection-DZ8j6nae.js → useNodeUrlSelection-DGV2ltbG.js} +1 -1
- package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BaETqb6x.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CglCXJMd.js} +2 -2
- package/dist/index.html +7 -7
- package/dist/server/addon.js +1 -1
- package/package.json +1 -1
- package/dist/assets/Addons-CC-7wyzX.js +0 -5
- package/dist/assets/AiProfiles-DQ7eLKoM.js +0 -3
- package/dist/assets/Data-C8MsiGcu.js +0 -2
- package/dist/assets/History-DP_G-ECr.js +0 -1
- package/dist/assets/Identity-D_ESOlFi.js +0 -1
- package/dist/assets/IntegrationDetail-DAaPI_ET.js +0 -1
- package/dist/assets/IntegrationHub-Ch94ozNN.js +0 -1
- package/dist/assets/Integrations-BBm9vAbT.js +0 -1
- package/dist/assets/Integrations-CcDZmbwS.js +0 -1
- package/dist/assets/Locations-C_Mo8QAj.js +0 -3
- package/dist/assets/Notifications-BahnGVKD.js +0 -1
- package/dist/assets/Pipeline-gniN2j7S.js +0 -1
- package/dist/assets/Recordings-BK-wAC4w.js +0 -1
- package/dist/assets/SessionsList-eAK6hNQb.js +0 -2
- package/dist/assets/device-picker-model-BkHlLdb8.js +0 -1
- package/dist/assets/i18n-l_m6iBJW.js +0 -1
- package/dist/assets/icons-BivKI4y9.js +0 -1
- package/dist/assets/index-BFjKpxae.js +0 -4
- package/dist/assets/mount-BkHlLdb8.js +0 -1
- package/dist/assets/remoteEntry-awBSqPjf.js +0 -1
- package/dist/assets/src-ByunGuTZ.js +0 -67
- package/dist/assets/useEventInvalidation-BkHlLdb8.js +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{An as p,Fn as m,It as h,Nt as g,Zi as _,kn as v,or as y,ot as b,pi as x,pn as S,pt as C,qi as w,sa as T,vn as E,wr as D,xi as O,yi as k}from"./player-overlays-Dbv95cvz.js";import{Di as A,Ei as j,Ii as M,Li as N,Na as P,Oi as F,Ti as I,bi as L,dn as R,ei as z,gi as B,ni as V,pi as H,ri as ee,va as te,wi as ne,xi as re}from"./client-DvJxGh2F.js";import{t as ie}from"./boxes-0ut2NdHU.js";import{n as ae,r as oe,t as se}from"./ungroup-3fOR8xo7.js";import{s as ce}from"./video-D7jv0spx.js";import{
|
|
1
|
+
import{C as e,E as t,J as n,K as r,P as i,R as a,S as o,V as s,Y as c,a as l,et as u,t as d,x as f}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{An as p,Fn as m,It as h,Nt as g,Zi as _,kn as v,or as y,ot as b,pi as x,pn as S,pt as C,qi as w,sa as T,vn as E,wr as D,xi as O,yi as k}from"./player-overlays-Dbv95cvz.js";import{Di as A,Ei as j,Ii as M,Li as N,Na as P,Oi as F,Ti as I,bi as L,dn as R,ei as z,gi as B,ni as V,pi as H,ri as ee,va as te,wi as ne,xi as re}from"./client-DvJxGh2F.js";import{t as ie}from"./boxes-0ut2NdHU.js";import{n as ae,r as oe,t as se}from"./ungroup-3fOR8xo7.js";import{s as ce}from"./video-D7jv0spx.js";import{$r as U,$t as le,$u as W,Aa as ue,Ca as de,Dr as fe,Gn as G,Jt as pe,Ju as K,Kr as q,No as me,Oa as he,Qu as ge,Sr as _e,Tn as ve,Wr as ye,Xu as be,Zu as xe,_o as Se,an as Ce,bt as we,co as Te,dd as Ee,fo as De,gt as Oe,ja as ke,ka as Ae,ko as je,mt as Me,nn as Ne,pd as Pe,vn as Fe,wa as Ie,wn as Le,xa as Re}from"./src-DntJrWmU.js";import{t as J}from"./i18n-xhwARoF0.js";import{t as Y}from"./useTranslation-BJr-n0es.js";import{P as ze,ar as Be,fr as Ve,lr as X,m as He,mr as Ue,ur as We,x as Ge}from"./index-C3uCLHv0.js";import{t as Ke}from"./AdminSectionedPage-DtiHBXGC.js";import{t as qe}from"./DeviceDoActionFields-Bj4gX0r-.js";import{R as Je,f as Ye,t as Xe}from"./HelperWizard-CrXHYd19.js";import{t as Ze}from"./CompositionBlockEditor-CElNVsCR.js";var Qe=`const AUTOMATION_RECIPE =`,$e=`// EJECTED from the visual automation editor — this file is now hand-owned.
|
|
2
2
|
// The recipe that produced it was removed with it, on purpose: while it was
|
|
3
|
-
// here the editor could re-open this block and overwrite everything below.`;function et(e){return e.includes(Qe)}function tt(e){let t=e.indexOf(Qe);if(t<0)return null;let n=e.indexOf(`{`,t+25);if(n<0)return null;let r=0,i=!1,a=!1;for(let o=n;o<e.length;o+=1){let s=e.charAt(o);if(i){a?a=!1:s===`\\`?a=!0:s===`"`&&(i=!1);continue}if(s===`"`){i=!0;continue}if(s===`{`)r+=1;else if(s===`}`&&(--r,r===0))return{declStart:t,literalEnd:o+1,json:e.slice(n,o+1)}}return null}function nt(e){let t=tt(e);if(t===null)return{ok:!1,reason:J.t(`helpers.recipeFromCode.noLiteral`)};let n;try{n=JSON.parse(t.json)}catch(e){let t=e instanceof Error?e.message:String(e);return{ok:!1,reason:J.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=I.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?J.t(`helpers.recipeFromCode.schemaMismatch`):J.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function rt(e){let t=tt(e);if(t===null)return e;let n=e.slice(t.literalEnd),r=/^\s*as\s+const/.exec(n),i=t.literalEnd+(r===null?0:r[0].length);return`${e.slice(0,t.declStart)}${$e}${e.slice(i)}`}u();var it=6e4;function at(){let e=
|
|
4
|
-
`};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function yt(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function bt(){return{kind:`expression`,expr:``,bindings:{}}}function xt(e,t,n){return e.map((e,r)=>r===t?n:e)}function St(e,t){return e.filter((e,n)=>n!==t)}function Ct(e,t,n){let r=e[t];if(r===void 0)return e;let i=Math.min(Math.max(n,0),e.length-1);if(i===t)return e;let a=St(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function wt(e,t){return{...e,triggers:[...t]}}function Tt(e,t){return{...e,actions:[...t]}}var Et=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function Dt({actions:t,devices:n,devicesState:r=`answered`,onChange:i}){let{t:a}=Y();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:a(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((s,c)=>e(`div`,{className:`rounded border border-border p-3 space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(G,{variant:`default`,children:c+1}),e(`label`,{className:`w-40`,children:[o(Z,{children:a(`automation.actionList.step`,`Step`)}),o(q,{value:s.kind,onChange:e=>i(xt(t,c,vt(Ot(e.target.value)))),options:Et.map(e=>({value:e.value,label:a(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(W,{variant:`ghost`,disabled:c===0,onClick:()=>i(Ct(t,c,c-1)),title:a(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:o(w,{className:`h-3.5 w-3.5`})}),o(W,{variant:`ghost`,disabled:c===t.length-1,onClick:()=>i(Ct(t,c,c+1)),title:a(`automation.actionList.runThisStepLater`,`Run this step later`),children:o(_,{className:`h-3.5 w-3.5`})}),o(W,{variant:`ghost`,onClick:()=>i(St(t,c)),title:a(`automation.actionList.removeThisStep`,`Remove this step`),children:o(h,{className:`h-3.5 w-3.5`})})]})]}),s.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Z,{children:a(`automation.actionList.seconds`,`Seconds`)}),o(K,{type:`number`,min:0,max:300,value:String(s.seconds),onChange:e=>i(xt(t,c,{kind:`wait`,seconds:Number(e.target.value)}))})]}),s.kind===`code`&&e(`label`,{className:`block`,children:[o(Z,{children:a(`automation.actionList.code`,`Code`)}),o(`textarea`,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:s.code,spellCheck:!1,onChange:e=>i(xt(t,c,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),s.kind===`cap`&&o(At,{action:s,devices:n,devicesState:r,onChange:e=>i(xt(t,c,e))})]},`${s.kind}-${String(c)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(W,{variant:`outline`,onClick:()=>i([...t,vt(`cap`)]),children:[o(v,{className:`h-4 w-4`}),` `,a(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function Ot(e){return Et.find(t=>t.value===e)?.value??`cap`}function kt(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function At({action:e,devices:t,devicesState:n,onChange:r}){return o(qe,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:kt(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function jt({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=Y(),c=Lt(n,r,i);if(n?.kind===`boolean`)return o(q,{value:t===!0?`true`:`false`,onChange:e=>a(e.target.value===`true`),options:[{value:`true`,label:s(`common.true`)},{value:`false`,label:s(`common.false`)}]});if(n?.kind===`enum`&&n.enumValues!==void 0&&n.enumValues.length>0)return o(q,{value:String(t),onChange:e=>a(e.target.value),options:n.enumValues.map(e=>({value:e,label:e}))});if(n?.kind===`number`){let n=typeof t==`number`&&c?c.toDisplayValue(t):t;return e(`span`,{className:`inline-flex items-center gap-1`,children:[o(K,{type:`number`,value:typeof n==`number`?String(n):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&a(c?c.fromDisplayValue(t):t)}}),c!==void 0&&c.unit.length>0?o(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return o(K,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function Mt({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Y(),s=Lt(t,n,r);return o(K,{value:(s?e.map(e=>typeof e==`number`?s.toDisplayValue(e):e):e).join(`, `),placeholder:a(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let n=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);i(t?.kind===`number`?n.map(e=>Number(e)).filter(e=>!Number.isNaN(e)).map(e=>s?s.fromDisplayValue(e):e):n)}})}function Nt(e){return typeof e==`object`}function Pt(e){return Nt(e)?e[0]??``:e}function Ft(e){return Nt(e)?e:typeof e==`boolean`?[]:[e]}function It(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Lt(e,t,n){let r=t??0,i=e?.kind===`number`&&e.quantity!==void 0,{data:a}=Ne({deviceId:r},{enabled:i&&r>0}),o=a?.sourceInfo?.quantity,s=te(o)?o:void 0,c=It(e?.quantity,s);if(c===void 0)return;let l=a?.display;return ge({quantity:c,display:l,capName:n})}function Rt({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=ct(a),c=mt(s?.kind),l=t.operator===`in`,u=e=>{r({...t,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},d=e=>{let n=zt(e,c);r({...t,operator:n,value:n===`in`?Ft(t.value):Pt(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(lt,{value:a,devices:n,onChange:u}),e(`label`,{className:`min-w-[8rem]`,children:[o(Z,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(q,{value:t.operator,onChange:e=>d(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(Mt,{value:Ft(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})}):o(jt,{value:Pt(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]})]})}function zt(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Bt={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function Vt({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a=Object.entries(t.bindings),s=e=>{r({kind:`expression`,expr:t.expr,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`label`,{className:`block`,children:[o(Z,{children:i(`automation.expressionLeafRow.expression`,`Expression`)}),o(K,{value:t.expr,placeholder:i(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),onChange:e=>r({kind:`expression`,expr:e.target.value,bindings:t.bindings})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.mustEvaluateToTrueOr`,`Must evaluate to true or false. Every name in it has to be bound below — an unbound name is refused when the automation is saved, not when it runs.`)})]}),e(`div`,{className:`space-y-1.5`,children:[a.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),a.map(([e,r])=>o(Ht,{alias:e,source:r,devices:n,onRename:n=>s(Jt(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(Yt(t.bindings,e))},e)),e(W,{variant:`ghost`,onClick:()=>s({...t.bindings,[qt(t.bindings)]:Bt}),children:[o(v,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]})]})}function Ht({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=Y(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Gt(r,Wt(n)),cap:n.cap,fieldPath:n.fieldPath};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[e(`label`,{className:`w-32`,children:[o(Z,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(K,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Z,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(q,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:Bt),options:[{value:`global`,label:c(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:c(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),l?e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(K,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Ut(e.target.value)})})]}):o(lt,{value:u,devices:r,onChange:e=>a({kind:`global`,sourceStableId:Kt(r,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),o(W,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(h,{className:`h-3.5 w-3.5`})})]})}function Ut(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Wt(e){return e.kind===`global`?e.sourceStableId:``}function Gt(e,t){return e.find(e=>e.stableId===t)?.id??0}function Kt(e,t){return e.find(e=>e.id===t)?.stableId??``}function qt(e){for(let t=0;t<26;t+=1){let n=String.fromCharCode(97+t);if(!(n in e))return n}return`n${String(Object.keys(e).length)}`}function Jt(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Yt(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Xt(e){return e.kind===`all`||e.kind===`any`}function Q(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:Xt(t)?t:{kind:`all`,children:[t]}}function Zt(e,t){return t===null||Xt(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function Qt(e){return Zt(e,Q(e))}function $t(e,t){if(t.length===0)return e;let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?$t(e.child,r):null;if(!Xt(e))return null;let i=e.children[n];return i===void 0?null:$t(i,r)}function en(e,t,n){if(t.length===0)return n(e);let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=en(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!Xt(e))return e;let a=e.children[r];if(a===void 0)return e;let o=en(a,i,n),s=o===null?[...e.children.slice(0,r),...e.children.slice(r+1)]:[...e.children.slice(0,r),o,...e.children.slice(r+1)];return s.length===0?null:{kind:e.kind,children:s}}function tn(e){return e===null?null:F({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function nn(e){let t=Q(e);return{depth:t.children.length===0?0:j(t),leaves:t.children.length===0?0:A(t),depthLimit:3,leafLimit:32}}function rn(e,t){let n=tn(t);return n===null?{ok:!0,recipe:Zt(e,t)}:{ok:!1,reason:n}}function an(e,t){let n=Q(e);return rn(e,{kind:n.kind,children:[...n.children,t]})}function on(e,t,n){return Zt(e,en(Q(e),t,()=>n))}function sn(e,t){return Zt(e,en(Q(e),t,()=>null))}function cn(e,t,n){return Zt(e,en(Q(e),t,e=>Xt(e)?{kind:n,children:e.children}:e))}function ln(e,t){return $t(Q(e),t)===null?{ok:!1,reason:J.t(`helpers.recipeOps.rowGone`)}:rn(e,en(Q(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function un(e){if(e.length===0)return null;let t=e[e.length-1];return t===void 0?null:{path:e.slice(0,-1),index:t}}function dn(e,t,n){if(t.length<2)return{ok:!1,reason:J.t(`helpers.recipeOps.selectTwo`)};if(new Set(t.map(e=>e.slice(0,-1).join(`/`))).size!==1)return{ok:!1,reason:J.t(`helpers.recipeOps.differentGroups`)};let r=un(t[0]??[]);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.rootGroup`)};let i=Q(e),a=$t(i,r.path);if(a===null||!Xt(a))return{ok:!1,reason:J.t(`helpers.recipeOps.insideNot`)};let o=[...t.map(e=>e[e.length-1]??-1)].sort((e,t)=>e-t),s=o.map(e=>a.children[e]).filter(e=>e!==void 0);if(s.length!==o.length)return{ok:!1,reason:J.t(`helpers.recipeOps.selectedGone`)};let c=a.children.filter((e,t)=>!o.includes(t)),l=o[0]??0,u={kind:n,children:s},d={kind:a.kind,children:[...c.slice(0,l),u,...c.slice(l)]};return rn(e,en(i,r.path,()=>d))}function fn(e,t){if(t.length===0)return{ok:!1,reason:J.t(`helpers.recipeOps.outerNotGroup`)};let n=Q(e),r=$t(n,t);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return rn(e,en(n,t,()=>r.child));if(!Xt(r))return{ok:!1,reason:J.t(`helpers.recipeOps.rowIsCondition`)};let i=un(t);if(i===null)return{ok:!1,reason:J.t(`helpers.recipeOps.noParent`)};let a=$t(n,i.path);if(a===null||!Xt(a))return{ok:!1,reason:J.t(`helpers.recipeOps.groupInNot`)};let o={kind:a.kind,children:[...a.children.slice(0,i.index),...r.children,...a.children.slice(i.index+1)]};return rn(e,en(n,i.path,()=>o))}u();var pn=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function mn(e){return e.join(`/`)}function hn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function gn({recipe:t,devices:n,onChange:i}){let{t:a}=Y(),[s,l]=c([]),[u,d]=c(null),f=Q(t),p=nn(t),m=r(()=>s.map(hn),[s]),h=e=>{if(!e.ok){d(e.reason);return}d(null),l([]),i(e.recipe)},g=dn(t,m,`all`),_=dn(t,m,`any`),y=m.length===1?ln(t,m[0]??[]):{ok:!1,reason:a(`automation.conditionTree.selectOneNegate`)},b={devices:n,selected:new Set(s),onToggleSelect:e=>l(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(e,n)=>i(on(t,e,n)),onRemove:e=>{l([]),i(sn(t,e))},onSetKind:(e,n)=>i(cn(t,e,n)),onUngroup:e=>h(fn(t,e))};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(G,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),o(`div`,{className:`w-32`,children:o(q,{value:f.kind,onChange:e=>i(cn(t,[],_n(e.target.value))),options:pn.map(e=>({value:e.value,label:a(e.labelKey)}))})}),o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.budget`,{depth:p.depth,depthLimit:p.depthLimit,leaves:p.leaves,leafLimit:p.leafLimit})})]}),f.children.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.noConditionsTheActionsRun`,`No conditions. The actions run every time a trigger fires.`)}):o(vn,{container:f,path:[],handlers:b}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(W,{variant:`outline`,onClick:()=>h(an(t,yt())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[o(v,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),e(W,{variant:`outline`,onClick:()=>h(an(t,bt())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[o(oe,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),o(`span`,{className:`mx-1 h-5 w-px bg-border`}),o(W,{variant:`ghost`,disabled:!g.ok,onClick:()=>h(g),title:g.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):g.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),o(W,{variant:`ghost`,disabled:!_.ok,onClick:()=>h(_),title:_.ok?a(`automation.conditionTree.anyOneOfTheSelected`,`Any one of the selected rows is enough`):_.reason,children:a(`automation.conditionTree.groupAsAny`,`Group as ANY`)}),o(W,{variant:`ghost`,disabled:!y.ok,onClick:()=>h(y),title:y.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):y.reason,children:`NOT`}),s.length>0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.selectedCount`,{count:s.length})})]}),u!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:u})]})}function _n(e){return e===`any`?`any`:`all`}function vn({container:e,path:t,handlers:n}){return o(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>o(yn,{node:e,path:[...t,r],handlers:n},mn([...t,r])))})}function yn({node:t,path:n,handlers:r}){let{t:i}=Y(),a=mn(n),s=o(ye,{checked:r.selected.has(a),onChange:()=>r.onToggleSelect(a),"aria-label":i(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return Xt(t)?e(`div`,{className:`rounded border border-border bg-surface-subtle/40 p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(`div`,{className:`w-32`,children:o(q,{value:t.kind,onChange:e=>r.onSetKind(n,_n(e.target.value)),options:pn.map(e=>({value:e.value,label:i(e.labelKey)}))})}),e(W,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[o(se,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.ungroup`)]}),o(W,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:o(h,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`pl-4`,children:o(vn,{container:t,path:n,handlers:r})})]}):t.kind===`not`?e(`div`,{className:`rounded border border-border p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(G,{variant:`warning`,children:`NOT`}),e(W,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[o(se,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.removeNot`)]})]}),o(`div`,{className:`pl-4`,children:o(yn,{node:t.child,path:[...n,0],handlers:r})})]}):e(`div`,{className:`flex items-start gap-2 rounded border border-border p-2`,children:[o(`div`,{className:`pt-6`,children:s}),o(`div`,{className:`min-w-0 flex-1`,children:t.kind===`condition`?o(Rt,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)}):o(Vt,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)})}),o(W,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:o(h,{className:`h-3.5 w-3.5`})})]})}u();function bn({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Y(),[l,u]=c(!1),d=ve(),f=async()=>{await d({title:s(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:s(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`),confirmLabel:s(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:s(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return e(`div`,{className:`rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[e(W,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?O:k,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(W,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?s(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):s(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[o(ce,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),l&&o(`div`,{className:`border-t border-border p-3`,children:t===null?o(`p`,{className:`text-xs text-warning`,children:n??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):o(Ce,{maxHeight:420,children:t})})]})}var xn=[`device-state`,`device-event`,`schedule`,`manual`],Sn=Object.values(P).sort((e,t)=>e.localeCompare(t));function Cn({triggers:t,devices:n,onChange:r}){let{t:i}=Y();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:i(`automation.triggerEditor.noTriggersYetWithoutOne`,`No triggers yet. Without one nothing can ever start this automation — not even "Run actions", which needs a manual trigger to have somewhere to arrive.`)}),t.map((e,i)=>o(wn,{trigger:e,devices:n,position:i,onChange:e=>r(xt(t,i,e)),onRemove:()=>r(St(t,i))},`${e.kind}-${String(i)}`)),e(W,{variant:`outline`,onClick:()=>r([...t,_t(`device-state`)]),title:i(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[o(v,{className:`h-4 w-4`}),` `,i(`automation.triggerEditor.trigger`)]})]})}function wn({trigger:t,devices:n,position:r,onChange:i,onRemove:a}){let{t:s}=Y();return e(`div`,{className:`rounded border border-border p-3`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(G,{variant:`default`,children:r===0?s(`automation.triggerEditor.when`,`When`):s(`automation.triggerEditor.orWhen`,`or when`)}),e(`label`,{className:`min-w-[13rem] flex-1`,children:[o(Z,{children:s(`automation.triggerEditor.trigger`,`Trigger`)}),o(q,{value:t.kind,onChange:e=>i(_t(Tn(e.target.value))),options:xn.map(e=>({value:e,label:ht(e)}))})]}),o(W,{variant:`ghost`,onClick:a,title:s(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:o(h,{className:`h-4 w-4`})})]}),e(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[t.kind===`device-state`&&o(Dn,{trigger:t,devices:n,onChange:i}),t.kind===`device-event`&&o(kn,{trigger:t,devices:n,onChange:i}),t.kind===`schedule`&&e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Z,{children:s(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(K,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>i({kind:`schedule`,cron:e.target.value})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]}),t.kind===`manual`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})]})]})}function Tn(e){return xn.find(t=>t===e)??`manual`}function En(e,t){return{kind:`device-state`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function Dn({trigger:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=ct(a),c={...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}};return e(f,{children:[o(lt,{value:a,devices:n,onChange:e=>r(En(e,c))}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),e(`div`,{className:`flex items-center gap-2`,children:[e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(ye,{checked:t.becomes===void 0,onChange:e=>r(En(a,{...c,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),i(`automation.triggerEditor.anyChange`,`any change`)]}),t.becomes!==void 0&&o(jt,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(En(a,{...c,becomes:e}))})]})]}),e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(ye,{checked:t.edge===!0,onChange:e=>r(En(a,{...c,...e.target.checked?{edge:!0}:{edge:void 0}}))}),i(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),e(`label`,{className:`w-28`,children:[o(Z,{children:i(`automation.triggerEditor.heldForS`,`Held for (s)`)}),o(K,{type:`number`,min:0,value:t.forMs===void 0?``:String(t.forMs/1e3),placeholder:`0`,onChange:e=>r(En(a,{...c,forMs:On(e.target.value)}))})]}),e(`label`,{className:`w-28`,children:[o(Z,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(K,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(En(a,{...c,debounceMs:On(e.target.value)}))})]})]})}function On(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function kn({trigger:t,devices:n,onChange:r}){let{t:i}=Y();return e(f,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.eventCategory`,`Event category`)}),o(q,{value:t.category,onChange:e=>r({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:i(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...Sn.map(e=>({value:e,label:e}))]})]}),e(`label`,{className:`min-w-[11rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.fromDevice`,`From device`)}),o(q,{value:t.deviceId===void 0?``:String(t.deviceId),onChange:e=>r({kind:`device-event`,category:t.category,...e.target.value===``?{}:{deviceId:Number(e.target.value)}}),options:[{value:``,label:i(`automation.triggerEditor.anyDevice`,`Any device`)},...n.map(e=>({value:String(e.id),label:e.name}))]})]})]})}u();var An=`hub`;function jn({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=Y(),[p,m]=c(t?.name??``),[h,g]=c(()=>Qt(n)),[_,v]=c(!1),b=at(),x=F(h),C=r(()=>Nn(h),[h]),w=r(()=>Pn(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),T=p.trim()===``,E=T||x!==null||C!==null||w.code===null;return e(`div`,{className:`space-y-4`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(G,{variant:`info`,children:f(`automation.automationEditor.runsOnTheHub`,`runs on the hub`)})}),e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(K,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(Mn,{step:`1`,title:f(`automation.automationEditor.when`,`When`),subtitle:f(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:o(Cn,{triggers:h.triggers,devices:b,onChange:e=>g(wt(h,e))})}),o(Mn,{step:`2`,title:f(`automation.automationEditor.andOnlyIf`,`And only if`),subtitle:f(`automation.automationEditor.checkedAfterATriggerFires`,`Checked after a trigger fires. Nothing runs unless this is true.`),children:o(gn,{recipe:h,devices:b,onChange:g})}),o(Mn,{step:`3`,title:f(`automation.automationEditor.then`,`Then`),subtitle:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(Dt,{actions:h.actions,devices:b,onChange:e=>g(Tt(h,e))})}),o(bn,{code:w.code,error:w.error,canEject:t!==null,ejecting:s,onEject:u}),x!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:x}),x===null&&C!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:C}),a!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(W,{onClick:()=>{w.code!==null&&l({name:p.trim(),code:w.code,enabled:t?.enabled??!0,placement:An})},disabled:i||E,children:[i&&o(y,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(W,{variant:`ghost`,onClick:()=>v(!_),disabled:t===null,title:t===null?f(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):f(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,children:[o(S,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,_?`▾`:`▸`]}),o(W,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),T&&o(G,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Pe,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Mn({step:t,title:n,subtitle:r,children:i}){return e(`section`,{className:`border-l-2 border-border pl-4`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[o(`span`,{className:`text-xs font-mono text-foreground-subtle`,children:t}),o(`h4`,{className:`text-sm font-medium uppercase tracking-wide`,children:n}),o(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i]})}function Nn(e){let t=I.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?J.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Pn(e,t){try{return{code:ne({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Fn(e){if(!e.enabled)return{tone:`idle`,label:J.t(`helpers.coreBlockStatus.disabled`),detail:J.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:J.t(`helpers.coreBlockStatus.running`),detail:J.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??J.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??J.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??J.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function In(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Ln(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Rn(e){let t=e=>{let t=Fn(e).tone;return t===`error`?0:t===`pending`?1:t===`ok`?2:3};return[...e].sort((e,n)=>t(e)-t(n)||e.name.localeCompare(n.name))}function zn(e){if(e.length===0)return J.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Fn(e).tone===`error`).length,n=e.filter(e=>Fn(e).tone===`ok`).length,r=[J.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(J.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(J.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}function Bn({block:t,busy:n,confirming:r,logsOpen:i,unreadable:a,onEdit:s,onToggle:c,onToggleLogs:l,onAskDelete:u,onCancelDelete:d,onConfirmDelete:f}){let g=T(),{t:_}=Y(),v=Fn(t),y=Me(t.updatedAt,g);return e(`li`,{className:`flex flex-col gap-2 p-3`,children:[e(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(G,{variant:In(v.tone),children:v.label}),y!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:_(`common.edited`,{when:y})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:v.detail}),a!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:_(`automation.editor.listUnreadable`,{reason:a})})]}),r?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:_(`automation.automationList.deleteThisAutomation`,`Delete this automation?`)}),o(W,{variant:`danger`,onClick:e=>{e.stopPropagation(),f()},disabled:n,children:_(`common.delete`,`Delete`)}),o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),d()},children:_(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),s()},disabled:a!==null,title:a===null?_(`common.edit`,`Edit`):_(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:o(m,{className:`h-4 w-4`})}),e(xe,{children:[o(Se,{children:o(W,{variant:`ghost`,disabled:!0,title:_(`automation.automationList.runActions`,`Run actions`),children:o(p,{className:`h-4 w-4`})})}),o(be,{children:_(`automation.automationList.runningAnAutomationByHand`,`Running an automation by hand needs the automation-control authority, which is not wired up yet. There is deliberately no second way to execute one.`)})]}),o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:_(`automation.automationList.logs`,`Logs`),children:o(S,{className:`h-4 w-4`})}),o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c(!t.enabled)},disabled:n,title:t.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`),children:t.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`)}),o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},title:_(`common.delete`,`Delete`),children:o(h,{className:`h-4 w-4`})})]})]}),i&&e(`div`,{className:`rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Pe,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Vn({onCreate:t}){let{t:n}=Y();return o(Le,{children:e(`div`,{className:`space-y-2 p-4`,children:[o(`p`,{className:`text-sm text-foreground`,children:n(`automation.automationList.noAutomationsYet`,`No automations yet.`)}),o(`p`,{className:`max-w-2xl text-xs text-foreground-subtle`,children:n(`automation.automationList.anAutomationIsATrigger`,`An automation is a trigger, a set of conditions and a list of actions. It compiles to an ordinary block and runs in its own supervised process — there is no separate engine, so anything that goes wrong shows up here with a reason.`)}),o(W,{onClick:t,children:n(`automation.automationList.newAutomation`,`New automation`)})]})})}u();var Hn=[`coreBlocks`,`list`],Un=5e3;function Wn(e){return e instanceof Error?e.message:String(e)}function Gn({onOpenScripts:t,initialBlockId:i,onBlockIdChange:a,createRequested:u=!1,onCreateConsumed:f}){let{t:p}=Y(),m=b(),{state:h,openNew:g,openEdit:_,close:v}=je({editKey:`block`,newKey:`new`}),[y,x]=c(null),[S,w]=c(null),[T,E]=c(null),D=n(null),O=h.mode!==`closed`;s(()=>{u&&(x(null),g(),a?.(null),f?.())},[u,f,a,g]);let k=l({queryKey:Hn,refetchInterval:Un,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=()=>{k.refetch()},j=k.data;s(()=>{i===void 0||D.current===i||j?.find(e=>e.id===i&&et(e.code))!==void 0&&(D.current=i,_(i),a?.(i))},[i,j,_,a]);let M=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{x(e.block),_(e.block.id),a?.(e.block.id),A()}}),N=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),_(e.block.id),a?.(e.block.id),A()}}),P=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{w(null),A()}}),F=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:A}),I=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:rt(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{v(),x(null),A(),t(e.block.id)}}),L=k.data,R=Rn((L??[]).filter(e=>et(e.code))),z=L!==void 0&&R.length===0,B=h.mode===`edit`?R.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,V=h.mode===`new`||B===null?null:Ln(R,B),H=V===null?null:nt(V.code),ee=M.error===null?N.error===null?I.error===null?null:Wn(I.error):Wn(N.error):Wn(M.error),te=r(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=nt(e.code);return o(`ul`,{className:`list-none`,children:o(Bn,{block:e,busy:F.isPending||P.isPending,confirming:S===e.id,logsOpen:T===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{x(e),_(e.id),a?.(e.id)},onToggle:t=>F.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>E(T===e.id?null:e.id),onAskDelete:()=>w(e.id),onCancelDelete:()=>w(null),onConfirmDelete:()=>P.mutate(e.id)})})},sortValue:e=>e.name}],[S,T,a,_,P,F,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:zn(R)}),k.error!=null&&o(U,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Wn(k.error),onRetry:A}),z?o(Vn,{onCreate:()=>{x(null),g(),a?.(null)}}):o(de,{columns:te,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ie,emptyMessage:L===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{x(e),_(e.id),a?.(e.id)}}),o(Oe,{open:O,onClose:()=>{M.reset(),N.reset(),I.reset(),x(null),v(),a?.(null)},title:V===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:V.name}),icon:C,width:`xl`,testId:`automation-editor-panel`,children:o(jn,{existing:V,initialRecipe:H!==null&&H.ok?H.recipe:gt,saving:M.isPending||N.isPending,saveError:ee,ejecting:I.isPending,onSave:e=>{V===null?M.mutate(e):N.mutate({blockId:V.id,block:e})},onEject:()=>{V!==null&&I.mutate(V)},onCancel:()=>{M.reset(),N.reset(),I.reset(),x(null),v(),a?.(null)}},V?.id??`new`)}),P.error!=null&&o(U,{message:Wn(P.error)}),F.error!=null&&o(U,{message:Wn(F.error)})]})}u();var Kn=`px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`;function qn(){let{t}=Y(),n=T(),r=Ve(),i=we(),a=pe(),s=he(),l=De({addonId:`composer`}),[u,d]=c(N.Sensor),[f,p]=c(M.TemperatureSensor),[m,h]=c(``),[g,_]=c(``),[v,y]=c(null),[b,x]=c(`choose`),S=Je({type:u,role:f});return b===`choose`?e(`section`,{className:`flex flex-col gap-3 rounded-lg border border-border bg-surface p-3 sm:p-4`,children:[o(`h2`,{className:`text-sm font-semibold`,children:t(`build.customDeviceTab.newComposedDevice`)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[o(W,{variant:`outline`,"data-testid":`blank-composition`,onClick:()=>x(`blank`),children:t(`helper.blank`)}),o(W,{"data-testid":`new-helper`,onClick:()=>x(`helper`),children:t(`helper.newHelper`)})]})]}):b===`helper`?e(`section`,{className:`flex flex-col gap-3 rounded-lg border border-border bg-surface p-3 sm:p-4`,children:[o(W,{variant:`ghost`,size:`sm`,onClick:()=>x(`choose`),children:t(`helper.back`)}),o(`h2`,{className:`text-sm font-semibold`,children:t(`helper.newHelper`)}),o(Xe,{initial:null,start:`template`,saving:i.isPending,onSave:e=>Ye(e,async(t,n)=>{let{block:o}=await i.mutateAsync({block:{...n===``?{}:{name:n},enabled:!0,composition:t}}),c=`${H}${o.id}`,u=((await l.refetch()).data??l.data)?.find(e=>e.stableId===c);if(u!==void 0){n!==``&&await a.mutateAsync({deviceId:u.id,name:n}),e.room.trim()!==``&&await s.mutateAsync({deviceId:u.id,location:e.room.trim()}),r(He(u.id),{replace:!0});return}r(`/build/compositions/${encodeURIComponent(o.id)}`,{replace:!0})})})]}):e(`section`,{className:`flex flex-col gap-3 rounded-lg border border-border bg-surface p-3 sm:p-4`,children:[o(W,{variant:`ghost`,size:`sm`,onClick:()=>x(`choose`),children:t(`helper.back`)}),o(`h2`,{className:`text-sm font-semibold`,children:t(`build.customDeviceTab.newComposedDevice`)}),e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`compositionEditor.targetType`),o(q,{value:u,onChange:e=>{let t=Object.values(N).find(t=>t===e.target.value);t!==void 0&&d(t)},options:Object.values(N).map(e=>({value:e,label:Ee(e,n).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`customize.identity.role`),o(q,{value:f??``,onChange:e=>p(Object.values(M).find(t=>t===e.target.value)??null),options:[{value:``,label:t(`customize.identity.noRole`)},...Object.values(M).map(e=>({value:e,label:Fe(e,n).label}))]})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`compositionEditor.name`),o(`input`,{className:Kn,value:m,onChange:e=>h(e.target.value)})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`customize.identity.room`),o(`input`,{className:Kn,value:g,onChange:e=>_(e.target.value)})]})]}),v!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:v}),o(W,{disabled:S===null||i.isPending,onClick:()=>{S!==null&&(async()=>{y(null);try{let e=m.trim(),{block:t}=await i.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:S}}),n=`${H}${t.id}`,o=((await l.refetch()).data??l.data)?.find(e=>e.stableId===n);if(o!==void 0){e!==``&&await a.mutateAsync({deviceId:o.id,name:e}),g.trim()!==``&&await s.mutateAsync({deviceId:o.id,location:g.trim()}),r(He(o.id),{replace:!0});return}r(`/build/compositions/${encodeURIComponent(t.id)}`,{replace:!0})}catch(e){y(e instanceof Error?e.message:String(e))}})()},children:t(`compositionEditor.save`)})]})}function Jn(e){return{state:`answered`,byRef:new Map(e.map(e=>[L(e),e]))}}function Yn(e,t){if(e.state!==`unanswered`)return e.byRef.get(L(t))??null}function Xn(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Zn(e){return re(e).map(e=>e.source)}function Qn(e){let t=e.block.source?.kind===`composition`?e.block.source.composition:null;if(t===null)return[];let n=[];for(let e of t.features){if(e.kind===`passthrough`){n.push(e.source);continue}for(let t of Object.values(e.fields))n.push(...Zn(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Zn(e))}let r=new Set;return n.filter(e=>{let t=L(e);return r.has(t)?!1:(r.add(t),!0)})}function $n(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label:J.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[J.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[J.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??J.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function er(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return $n(e);case`degraded`:return{tone:`pending`,label:J.t(`helpers.compositionRows.degraded`),reason:n??J.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:J.t(`helpers.compositionRows.failed`),reason:n??J.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:J.t(`helpers.compositionRows.notRunning`),reason:n??J.t(`helpers.compositionRows.notRunningReason`)}}}function tr(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:J.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:J.t(`helpers.compositionRows.unknown`),reason:J.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return er(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.notReported`),reason:J.t(`helpers.compositionRows.noRecord`,{stored:r})}}function nr(e){return L(e)}function rr(e,t){let n=Yn(t,e);return{key:L(e),label:n?n.name:nr(e),presence:Xn(n),deviceId:n?n.id:null}}function ir(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function ar(e,t){let n=e.block.source?.kind===`composition`?e.block.source.composition:null;if(n===null)return null;let r=n.target,i=r.kind===`existing`?r.device:B(e.block.id),a=L(i),o=Qn(e).filter(e=>L(e)!==a).map(e=>rr(e,t)),s=n.features.map(e=>e.enabled===!1?J.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=Yn(t,i),l=ir(e),u=tr(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,features:s,state:u,sources:o,reportedDeviceId:l};let d=Xn(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:nr(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function or(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function sr(e,t){return or(e)-or(t)||e.name.localeCompare(t.name)}function cr(e,t){let n=e.flatMap(e=>{let n=ar(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(sr),customizations:n.filter(e=>e.kind===`customization`).toSorted(sr)}}var lr=1e4;function ur(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function dr(){let e=Be();return e.data===void 0?{state:`unanswered`,reason:e.error==null?J.t(`build.customDeviceTab.deviceListPending`):J.t(`build.customDeviceTab.deviceListUnreadable`,{error:ur(e.error)})}:Jn(e.data)}function fr({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Y(),i=fe({},{refetchInterval:lr}),a=dr(),s=je({editKey:`block`,newKey:`new`}),c=s.state.mode===`edit`?s.state.id:null,l=c===null&&(t||s.state.mode===`new`),u=()=>{s.close(),n?.()},d=i.data;return e(f,{children:[mr(d,i.error,()=>void i.refetch(),a,{onEditComposed:e=>s.openEdit(e)}),o(Oe,{open:l||c!==null,onClose:u,title:l?r(`build.customDeviceTab.newComposedDevice`,`New composed device`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:ie,width:`xl`,testId:`composed-device-editor`,children:l?o(qn,{}):c===null?null:o(Ze,{blockId:c})})]})}function pr(t){return o(Le,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:J.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[J.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function mr(e,t,n,r,i){if(t!=null&&e===void 0)return o(U,{title:J.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:ur(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:J.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return pr(e.reason);let a=t==null?null:ur(t);return o(hr,{lists:cr(e.views,r),fleet:r,refreshError:a,onEditComposed:i.onEditComposed})}function hr({lists:t,fleet:n,refreshError:r,onEditComposed:i}){let{t:a}=Y();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),o(gr,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,onEditComposed:i}),o(gr,{title:a(`build.customDeviceTab.customizations`,`Customizations`),hint:a(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:t.customizations,nameHeader:`Device`,emptyMessage:a(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,onEditComposed:i})]})}function gr({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,onEditComposed:c}){return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[o(`h3`,{className:`font-medium`,children:t}),o(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),o(Le,{variant:`flat`,className:`p-0`,children:o(de,{columns:_r(i,s,c),rows:r,rowKey:e=>e.blockId,minWidthPx:760,bordered:!1,maxBodyHeight:Ie,emptyMessage:a,onRowClick:s===`composed`?e=>c(e.blockId):void 0})})]})}function _r(t,n,r){let i=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(vr,{row:e})},{key:`type`,header:J.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??J.t(`common.unknownWord`)})},{key:`state`,header:J.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[o(G,{variant:In(t.state.tone),children:t.state.label}),t.state.reason!==null&&o(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:J.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(br,{sources:e.sources})}];return n===`composed`&&i.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>o(`div`,{className:`flex justify-end gap-1`,children:o(W,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),r(e.blockId)},children:J.t(`common.edit`,`Edit`)})})}),i}function vr({row:t}){let{t:n}=Y();return e(`div`,{className:`space-y-0.5`,children:[o(yr,{row:t}),t.namePresence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),o(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function yr({row:e}){let{t}=Y();return e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):e.reportedDeviceId===null?o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:e.name})}):o(We,{to:He(e.reportedDeviceId),className:`text-xs text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:e.name})}function br({sources:t}){let{t:n}=Y();return t.length===0?o(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):o(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?o(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):o(We,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function xr(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Sr(e){if(Array.isArray(e))return e}function Cr(e,t,n){return(t=Mr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function wr(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Tr(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
3
|
+
// here the editor could re-open this block and overwrite everything below.`;function et(e){return e.includes(Qe)}function tt(e){let t=e.indexOf(Qe);if(t<0)return null;let n=e.indexOf(`{`,t+25);if(n<0)return null;let r=0,i=!1,a=!1;for(let o=n;o<e.length;o+=1){let s=e.charAt(o);if(i){a?a=!1:s===`\\`?a=!0:s===`"`&&(i=!1);continue}if(s===`"`){i=!0;continue}if(s===`{`)r+=1;else if(s===`}`&&(--r,r===0))return{declStart:t,literalEnd:o+1,json:e.slice(n,o+1)}}return null}function nt(e){let t=tt(e);if(t===null)return{ok:!1,reason:J.t(`helpers.recipeFromCode.noLiteral`)};let n;try{n=JSON.parse(t.json)}catch(e){let t=e instanceof Error?e.message:String(e);return{ok:!1,reason:J.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=I.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?J.t(`helpers.recipeFromCode.schemaMismatch`):J.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function rt(e){let t=tt(e);if(t===null)return e;let n=e.slice(t.literalEnd),r=/^\s*as\s+const/.exec(n),i=t.literalEnd+(r===null?0:r[0].length);return`${e.slice(0,t.declStart)}${$e}${e.slice(i)}`}u();var it=6e4;function at(){let e=De({projection:`slim`});return r(()=>(e.data??[]).filter(e=>R(String(e.type))).map(e=>({id:e.id,name:e.name,stableId:e.stableId,type:String(e.type),location:e.location??null})).toSorted((e,t)=>e.name.localeCompare(t.name)),[e.data])}function ot(e){let t=b();return l({queryKey:[`automation`,`wireable-fields`,e],enabled:e>0,staleTime:it,queryFn:async()=>(await t.trpcClient.deviceManager.getWireableFields.query({deviceId:e})).caps})}function st(e,t){return e.find(e=>e.cap===t)?.fields??[]}function Z({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function ct(e){let t=ot(e.deviceId);if(t.data!==void 0)return st(t.data,e.cap).find(t=>t.path===e.fieldPath)}function lt({value:t,devices:n,onChange:r}){let{t:i}=Y(),a=ot(t.deviceId),s=a.data??[],c=st(s,t.cap);return e(f,{children:[e(`label`,{className:`min-w-[10rem] flex-1`,children:[o(Z,{children:i(`automation.fieldPicker.device`,`Device`)}),o(K,{value:String(t.deviceId),onChange:e=>r({deviceId:Number(e.target.value),cap:``,fieldPath:``}),options:[{value:`0`,label:i(`automation.fieldPicker.selectADevice`,`Select a device…`)},...n.map(e=>({value:String(e.id),label:e.name}))]})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:i(`automation.fieldPicker.capability`,`Capability`)}),o(K,{value:t.cap,disabled:t.deviceId===0,onChange:e=>r({...t,cap:e.target.value,fieldPath:``}),options:[{value:``,label:ut(t.deviceId,s.length,a.isLoading)},...s.map(e=>({value:e.cap,label:e.cap}))]})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:i(`automation.fieldPicker.field`,`Field`)}),o(K,{value:t.fieldPath,disabled:t.cap===``,onChange:e=>r({...t,fieldPath:e.target.value}),options:[{value:``,label:c.length===0?i(`automation.fieldPicker.noReadableFields`,`No readable fields`):i(`automation.fieldPicker.selectAField`,`Select a field…`)},...c.map(e=>({value:e.path,label:`${e.path} (${e.kind})`}))]})]})]})}function ut(e,t,n){return e===0?J.t(`automation.fieldPicker.pickDeviceFirst`):n?J.t(`automation.fieldPicker.readingDevice`):t===0?J.t(`automation.fieldPicker.noReadableCaps`):J.t(`automation.fieldPicker.selectCap`)}var dt=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function ft(e){switch(e){case`boolean`:return[`eq`,`ne`];case`number`:return[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`];case`string`:case`enum`:return[`eq`,`ne`,`contains`,`in`];default:return dt}}function pt(e){switch(e){case`eq`:return J.t(`helpers.recipeParts.op_eq`);case`ne`:return J.t(`helpers.recipeParts.op_ne`);case`gt`:return J.t(`helpers.recipeParts.op_gt`);case`gte`:return J.t(`helpers.recipeParts.op_gte`);case`lt`:return J.t(`helpers.recipeParts.op_lt`);case`lte`:return J.t(`helpers.recipeParts.op_lte`);case`contains`:return J.t(`helpers.recipeParts.op_contains`);default:return J.t(`helpers.recipeParts.op_in`)}}function mt(e){return ft(e).map(e=>({value:e,label:pt(e)}))}function ht(e){switch(e){case`device-state`:return J.t(`helpers.recipeParts.trigger_device_state`);case`device-event`:return J.t(`helpers.recipeParts.trigger_device_event`);case`schedule`:return J.t(`helpers.recipeParts.trigger_schedule`);default:return J.t(`helpers.recipeParts.trigger_manual`)}}var gt={triggers:[],actions:[]};function _t(e){switch(e){case`device-state`:return{kind:e,deviceId:0,cap:``,fieldPath:``};case`device-event`:return{kind:e,category:``};case`schedule`:return{kind:e,cron:`0 30 23 * * *`};default:return{kind:`manual`}}}function vt(e){switch(e){case`wait`:return{kind:e,seconds:5};case`code`:return{kind:e,code:`// runs inside this automation, with ctx in scope
|
|
4
|
+
`};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function yt(){return{kind:`condition`,deviceId:0,cap:``,fieldPath:``,operator:`eq`,value:``}}function bt(){return{kind:`expression`,expr:``,bindings:{}}}function xt(e,t,n){return e.map((e,r)=>r===t?n:e)}function St(e,t){return e.filter((e,n)=>n!==t)}function Ct(e,t,n){let r=e[t];if(r===void 0)return e;let i=Math.min(Math.max(n,0),e.length-1);if(i===t)return e;let a=St(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function wt(e,t){return{...e,triggers:[...t]}}function Tt(e,t){return{...e,actions:[...t]}}var Et=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`code`,labelKey:`automation.actionList.kindCode`}];function Dt({actions:t,devices:n,devicesState:r=`answered`,onChange:i}){let{t:a}=Y();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:a(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((s,c)=>e(`div`,{className:`rounded border border-border p-3 space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(U,{variant:`default`,children:c+1}),e(`label`,{className:`w-40`,children:[o(Z,{children:a(`automation.actionList.step`,`Step`)}),o(K,{value:s.kind,onChange:e=>i(xt(t,c,vt(Ot(e.target.value)))),options:Et.map(e=>({value:e.value,label:a(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(q,{variant:`ghost`,disabled:c===0,onClick:()=>i(Ct(t,c,c-1)),title:a(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),children:o(w,{className:`h-3.5 w-3.5`})}),o(q,{variant:`ghost`,disabled:c===t.length-1,onClick:()=>i(Ct(t,c,c+1)),title:a(`automation.actionList.runThisStepLater`,`Run this step later`),children:o(_,{className:`h-3.5 w-3.5`})}),o(q,{variant:`ghost`,onClick:()=>i(St(t,c)),title:a(`automation.actionList.removeThisStep`,`Remove this step`),children:o(h,{className:`h-3.5 w-3.5`})})]})]}),s.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Z,{children:a(`automation.actionList.seconds`,`Seconds`)}),o(W,{type:`number`,min:0,max:300,value:String(s.seconds),onChange:e=>i(xt(t,c,{kind:`wait`,seconds:Number(e.target.value)}))})]}),s.kind===`code`&&e(`label`,{className:`block`,children:[o(Z,{children:a(`automation.actionList.code`,`Code`)}),o(`textarea`,{className:`h-32 w-full rounded-md border border-border bg-surface p-2 font-mono text-xs text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,value:s.code,spellCheck:!1,onChange:e=>i(xt(t,c,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),s.kind===`cap`&&o(At,{action:s,devices:n,devicesState:r,onChange:e=>i(xt(t,c,e))})]},`${s.kind}-${String(c)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(q,{variant:`outline`,onClick:()=>i([...t,vt(`cap`)]),children:[o(v,{className:`h-4 w-4`}),` `,a(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function Ot(e){return Et.find(t=>t.value===e)?.value??`cap`}function kt(e){return typeof e==`number`?e:typeof e==`object`&&e&&`$var`in e?{$var:e.$var}:[...e]}function At({action:e,devices:t,devicesState:n,onChange:r}){return o(qe,{value:e,allowTriggerDevice:!0,allowMultiSameFamily:!0,devices:t,listState:n,onChange:e=>r({kind:`cap`,deviceId:kt(e.deviceId),cap:e.cap,method:e.method,...e.args===void 0?{}:{args:{...e.args}}})})}function jt({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=Y(),c=Lt(n,r,i);if(n?.kind===`boolean`)return o(K,{value:t===!0?`true`:`false`,onChange:e=>a(e.target.value===`true`),options:[{value:`true`,label:s(`common.true`)},{value:`false`,label:s(`common.false`)}]});if(n?.kind===`enum`&&n.enumValues!==void 0&&n.enumValues.length>0)return o(K,{value:String(t),onChange:e=>a(e.target.value),options:n.enumValues.map(e=>({value:e,label:e}))});if(n?.kind===`number`){let n=typeof t==`number`&&c?c.toDisplayValue(t):t;return e(`span`,{className:`inline-flex items-center gap-1`,children:[o(W,{type:`number`,value:typeof n==`number`?String(n):``,placeholder:`0`,onChange:e=>{let t=Number(e.target.value);e.target.value!==``&&!Number.isNaN(t)&&a(c?c.fromDisplayValue(t):t)}}),c!==void 0&&c.unit.length>0?o(`span`,{className:`text-xs text-foreground-subtle`,children:c.unit}):null]})}return o(W,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function Mt({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=Y(),s=Lt(t,n,r);return o(W,{value:(s?e.map(e=>typeof e==`number`?s.toDisplayValue(e):e):e).join(`, `),placeholder:a(`automation.valueInput.oneTwoThree`,`one, two, three`),onChange:e=>{let n=e.target.value.split(`,`).map(e=>e.trim()).filter(e=>e!==``);i(t?.kind===`number`?n.map(e=>Number(e)).filter(e=>!Number.isNaN(e)).map(e=>s?s.fromDisplayValue(e):e):n)}})}function Nt(e){return typeof e==`object`}function Pt(e){return Nt(e)?e[0]??``:e}function Ft(e){return Nt(e)?e:typeof e==`boolean`?[]:[e]}function It(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Lt(e,t,n){let r=t??0,i=e?.kind===`number`&&e.quantity!==void 0,{data:a}=Te({deviceId:r},{enabled:i&&r>0}),o=a?.sourceInfo?.quantity,s=te(o)?o:void 0,c=It(e?.quantity,s);if(c===void 0)return;let l=a?.display;return le({quantity:c,display:l,capName:n})}function Rt({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=ct(a),c=mt(s?.kind),l=t.operator===`in`,u=e=>{r({...t,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},d=e=>{let n=zt(e,c);r({...t,operator:n,value:n===`in`?Ft(t.value):Pt(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(lt,{value:a,devices:n,onChange:u}),e(`label`,{className:`min-w-[8rem]`,children:[o(Z,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(K,{value:t.operator,onChange:e=>d(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(Mt,{value:Ft(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})}):o(jt,{value:Pt(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]})]})}function zt(e,t){return t.find(t=>t.value===e)?.value??`eq`}var Bt={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function Vt({leaf:t,devices:n,onChange:r}){let{t:i}=Y(),a=Object.entries(t.bindings),s=e=>{r({kind:`expression`,expr:t.expr,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`label`,{className:`block`,children:[o(Z,{children:i(`automation.expressionLeafRow.expression`,`Expression`)}),o(W,{value:t.expr,placeholder:i(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),onChange:e=>r({kind:`expression`,expr:e.target.value,bindings:t.bindings})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.mustEvaluateToTrueOr`,`Must evaluate to true or false. Every name in it has to be bound below — an unbound name is refused when the automation is saved, not when it runs.`)})]}),e(`div`,{className:`space-y-1.5`,children:[a.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`automation.expressionLeafRow.noNamesBoundYetAn`,`No names bound yet. An expression reads devices only through these.`)}),a.map(([e,r])=>o(Ht,{alias:e,source:r,devices:n,onRename:n=>s(Jt(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(Yt(t.bindings,e))},e)),e(q,{variant:`ghost`,onClick:()=>s({...t.bindings,[qt(t.bindings)]:Bt}),children:[o(v,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]})]})}function Ht({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=Y(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:Gt(r,Wt(n)),cap:n.cap,fieldPath:n.fieldPath};return e(`div`,{className:`flex flex-wrap items-end gap-2 rounded border border-border p-2`,children:[e(`label`,{className:`w-32`,children:[o(Z,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(W,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Z,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(K,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:Bt),options:[{value:`global`,label:c(`automation.expressionLeafRow.aDeviceField`,`A device field`)},{value:`literal`,label:c(`automation.expressionLeafRow.aConstant`,`A constant`)}]})]}),l?e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Z,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(W,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Ut(e.target.value)})})]}):o(lt,{value:u,devices:r,onChange:e=>a({kind:`global`,sourceStableId:Kt(r,e.deviceId),cap:e.cap,fieldPath:e.fieldPath})}),o(q,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(h,{className:`h-3.5 w-3.5`})})]})}function Ut(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function Wt(e){return e.kind===`global`?e.sourceStableId:``}function Gt(e,t){return e.find(e=>e.stableId===t)?.id??0}function Kt(e,t){return e.find(e=>e.id===t)?.stableId??``}function qt(e){for(let t=0;t<26;t+=1){let n=String.fromCharCode(97+t);if(!(n in e))return n}return`n${String(Object.keys(e).length)}`}function Jt(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Yt(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Xt(e){return e.kind===`all`||e.kind===`any`}function Q(e){let t=e.conditions;return t===void 0?{kind:`all`,children:[]}:Xt(t)?t:{kind:`all`,children:[t]}}function Zt(e,t){return t===null||Xt(t)&&t.children.length===0?{triggers:e.triggers,actions:e.actions}:{triggers:e.triggers,actions:e.actions,conditions:t}}function Qt(e){return Zt(e,Q(e))}function $t(e,t){if(t.length===0)return e;let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?$t(e.child,r):null;if(!Xt(e))return null;let i=e.children[n];return i===void 0?null:$t(i,r)}function en(e,t,n){if(t.length===0)return n(e);let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=en(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(!Xt(e))return e;let a=e.children[r];if(a===void 0)return e;let o=en(a,i,n),s=o===null?[...e.children.slice(0,r),...e.children.slice(r+1)]:[...e.children.slice(0,r),o,...e.children.slice(r+1)];return s.length===0?null:{kind:e.kind,children:s}}function tn(e){return e===null?null:F({triggers:[{kind:`manual`}],actions:[{kind:`wait`,seconds:0}],conditions:e})}function nn(e){let t=Q(e);return{depth:t.children.length===0?0:j(t),leaves:t.children.length===0?0:A(t),depthLimit:3,leafLimit:32}}function rn(e,t){let n=tn(t);return n===null?{ok:!0,recipe:Zt(e,t)}:{ok:!1,reason:n}}function an(e,t){let n=Q(e);return rn(e,{kind:n.kind,children:[...n.children,t]})}function on(e,t,n){return Zt(e,en(Q(e),t,()=>n))}function sn(e,t){return Zt(e,en(Q(e),t,()=>null))}function cn(e,t,n){return Zt(e,en(Q(e),t,e=>Xt(e)?{kind:n,children:e.children}:e))}function ln(e,t){return $t(Q(e),t)===null?{ok:!1,reason:J.t(`helpers.recipeOps.rowGone`)}:rn(e,en(Q(e),t,e=>e.kind===`not`?e.child:{kind:`not`,child:e}))}function un(e){if(e.length===0)return null;let t=e[e.length-1];return t===void 0?null:{path:e.slice(0,-1),index:t}}function dn(e,t,n){if(t.length<2)return{ok:!1,reason:J.t(`helpers.recipeOps.selectTwo`)};if(new Set(t.map(e=>e.slice(0,-1).join(`/`))).size!==1)return{ok:!1,reason:J.t(`helpers.recipeOps.differentGroups`)};let r=un(t[0]??[]);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.rootGroup`)};let i=Q(e),a=$t(i,r.path);if(a===null||!Xt(a))return{ok:!1,reason:J.t(`helpers.recipeOps.insideNot`)};let o=[...t.map(e=>e[e.length-1]??-1)].sort((e,t)=>e-t),s=o.map(e=>a.children[e]).filter(e=>e!==void 0);if(s.length!==o.length)return{ok:!1,reason:J.t(`helpers.recipeOps.selectedGone`)};let c=a.children.filter((e,t)=>!o.includes(t)),l=o[0]??0,u={kind:n,children:s},d={kind:a.kind,children:[...c.slice(0,l),u,...c.slice(l)]};return rn(e,en(i,r.path,()=>d))}function fn(e,t){if(t.length===0)return{ok:!1,reason:J.t(`helpers.recipeOps.outerNotGroup`)};let n=Q(e),r=$t(n,t);if(r===null)return{ok:!1,reason:J.t(`helpers.recipeOps.groupGone`)};if(r.kind===`not`)return rn(e,en(n,t,()=>r.child));if(!Xt(r))return{ok:!1,reason:J.t(`helpers.recipeOps.rowIsCondition`)};let i=un(t);if(i===null)return{ok:!1,reason:J.t(`helpers.recipeOps.noParent`)};let a=$t(n,i.path);if(a===null||!Xt(a))return{ok:!1,reason:J.t(`helpers.recipeOps.groupInNot`)};let o={kind:a.kind,children:[...a.children.slice(0,i.index),...r.children,...a.children.slice(i.index+1)]};return rn(e,en(n,i.path,()=>o))}u();var pn=[{value:`all`,labelKey:`automation.conditionTree.allOf`},{value:`any`,labelKey:`automation.conditionTree.anyOf`}];function mn(e){return e.join(`/`)}function hn(e){return e===``?[]:e.split(`/`).map(e=>Number(e))}function gn({recipe:t,devices:n,onChange:i}){let{t:a}=Y(),[s,l]=c([]),[u,d]=c(null),f=Q(t),p=nn(t),m=r(()=>s.map(hn),[s]),h=e=>{if(!e.ok){d(e.reason);return}d(null),l([]),i(e.recipe)},g=dn(t,m,`all`),_=dn(t,m,`any`),y=m.length===1?ln(t,m[0]??[]):{ok:!1,reason:a(`automation.conditionTree.selectOneNegate`)},b={devices:n,selected:new Set(s),onToggleSelect:e=>l(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),onUpdate:(e,n)=>i(on(t,e,n)),onRemove:e=>{l([]),i(sn(t,e))},onSetKind:(e,n)=>i(cn(t,e,n)),onUngroup:e=>h(fn(t,e))};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(U,{variant:`default`,children:a(`automation.conditionTree.andOnlyIf`,`And only if`)}),o(`div`,{className:`w-32`,children:o(K,{value:f.kind,onChange:e=>i(cn(t,[],_n(e.target.value))),options:pn.map(e=>({value:e.value,label:a(e.labelKey)}))})}),o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.budget`,{depth:p.depth,depthLimit:p.depthLimit,leaves:p.leaves,leafLimit:p.leafLimit})})]}),f.children.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.conditionTree.noConditionsTheActionsRun`,`No conditions. The actions run every time a trigger fires.`)}):o(vn,{container:f,path:[],handlers:b}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{variant:`outline`,onClick:()=>h(an(t,yt())),title:a(`automation.conditionTree.compareOneDeviceFieldTo`,`Compare one device field to a value`),children:[o(v,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addCondition`)]}),e(q,{variant:`outline`,onClick:()=>h(an(t,bt())),title:a(`automation.conditionTree.arithmeticAcrossDeviceFieldsThe`,`Arithmetic across device fields — the bounded expression engine`),children:[o(oe,{className:`h-4 w-4`}),` `,a(`automation.conditionTree.addExpression`)]}),o(`span`,{className:`mx-1 h-5 w-px bg-border`}),o(q,{variant:`ghost`,disabled:!g.ok,onClick:()=>h(g),title:g.ok?a(`automation.conditionTree.allSelectedRowsMustBe`,`All selected rows must be true`):g.reason,children:a(`automation.conditionTree.groupAsAll`,`Group as ALL`)}),o(q,{variant:`ghost`,disabled:!_.ok,onClick:()=>h(_),title:_.ok?a(`automation.conditionTree.anyOneOfTheSelected`,`Any one of the selected rows is enough`):_.reason,children:a(`automation.conditionTree.groupAsAny`,`Group as ANY`)}),o(q,{variant:`ghost`,disabled:!y.ok,onClick:()=>h(y),title:y.ok?a(`automation.conditionTree.invertTheSelectedRow`,`Invert the selected row`):y.reason,children:`NOT`}),s.length>0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.selectedCount`,{count:s.length})})]}),u!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning`,children:u})]})}function _n(e){return e===`any`?`any`:`all`}function vn({container:e,path:t,handlers:n}){return o(`div`,{className:`space-y-1.5`,children:e.children.map((e,r)=>o(yn,{node:e,path:[...t,r],handlers:n},mn([...t,r])))})}function yn({node:t,path:n,handlers:r}){let{t:i}=Y(),a=mn(n),s=o(G,{checked:r.selected.has(a),onChange:()=>r.onToggleSelect(a),"aria-label":i(`automation.conditionTree.selectThisRowForGrouping`,`Select this row for grouping`)});return Xt(t)?e(`div`,{className:`rounded border border-border bg-surface-subtle/40 p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(`div`,{className:`w-32`,children:o(K,{value:t.kind,onChange:e=>r.onSetKind(n,_n(e.target.value)),options:pn.map(e=>({value:e.value,label:i(e.labelKey)}))})}),e(q,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.dissolveThisGroupKeepingIts`,`Dissolve this group, keeping its rows`),children:[o(se,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.ungroup`)]}),o(q,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.deleteThisGroupAndEverything`,`Delete this group and everything in it`),children:o(h,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`pl-4`,children:o(vn,{container:t,path:n,handlers:r})})]}):t.kind===`not`?e(`div`,{className:`rounded border border-border p-2`,children:[e(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[s,o(U,{variant:`warning`,children:`NOT`}),e(q,{variant:`ghost`,onClick:()=>r.onUngroup(n),title:i(`automation.conditionTree.removeTheNotKeepingThe`,`Remove the NOT, keeping the row`),children:[o(se,{className:`h-3.5 w-3.5`}),` `,i(`automation.conditionTree.removeNot`)]})]}),o(`div`,{className:`pl-4`,children:o(yn,{node:t.child,path:[...n,0],handlers:r})})]}):e(`div`,{className:`flex items-start gap-2 rounded border border-border p-2`,children:[o(`div`,{className:`pt-6`,children:s}),o(`div`,{className:`min-w-0 flex-1`,children:t.kind===`condition`?o(Rt,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)}):o(Vt,{leaf:t,devices:r.devices,onChange:e=>r.onUpdate(n,e)})}),o(q,{variant:`ghost`,onClick:()=>r.onRemove(n),title:i(`automation.conditionTree.removeThisCondition`,`Remove this condition`),children:o(h,{className:`h-3.5 w-3.5`})})]})}u();function bn({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=Y(),[l,u]=c(!1),d=ye(),f=async()=>{await d({title:s(`automation.generatedCodePanel.ejectToCodeThisCannot`,`Eject to code — this cannot be undone`),message:s(`automation.generatedCodePanel.theRecipeIsRemovedFrom`,`The recipe is removed from the block and it becomes an ordinary script. The visual editor will no longer open it, and there is no way back to it except authoring a new automation from scratch. The code itself is kept exactly as it is now.`),confirmLabel:s(`automation.generatedCodePanel.ejectToCode`,`Eject to code`),cancelLabel:s(`automation.generatedCodePanel.keepItVisual`,`Keep it visual`),variant:`warning`})&&a()};return e(`div`,{className:`rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2 px-3 py-2`,children:[e(q,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?O:k,{className:`h-4 w-4`}),s(`automation.generatedCodePanel.generatedCode`,`Generated code`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.generatedCodePanel.derivedFromTheRecipeAbove`,`Derived from the recipe above — regenerated on every save, never edited here.`)}),e(q,{className:`ml-auto`,variant:`ghost`,disabled:!r||t===null||i,onClick:()=>void f(),title:r?s(`automation.generatedCodePanel.takePermanentOwnershipOfThis`,`Take permanent ownership of this code as a script`):s(`automation.generatedCodePanel.saveTheAutomationFirstThere`,`Save the automation first — there is no stored block to eject yet`),children:[o(ce,{className:`h-4 w-4`}),` `,s(`automation.generatedCodePanel.eject`)]})]}),l&&o(`div`,{className:`border-t border-border p-3`,children:t===null?o(`p`,{className:`text-xs text-warning`,children:n??s(`automation.generatedCodePanel.theRecipeIsNotComplete`,`The recipe is not complete enough to generate a block yet.`)}):o(Fe,{maxHeight:420,children:t})})]})}var xn=[`device-state`,`device-event`,`schedule`,`manual`],Sn=Object.values(P).sort((e,t)=>e.localeCompare(t));function Cn({triggers:t,devices:n,onChange:r}){let{t:i}=Y();return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:i(`automation.triggerEditor.noTriggersYetWithoutOne`,`No triggers yet. Without one nothing can ever start this automation — not even "Run actions", which needs a manual trigger to have somewhere to arrive.`)}),t.map((e,i)=>o(wn,{trigger:e,devices:n,position:i,onChange:e=>r(xt(t,i,e)),onRemove:()=>r(St(t,i))},`${e.kind}-${String(i)}`)),e(q,{variant:`outline`,onClick:()=>r([...t,_t(`device-state`)]),title:i(`automation.triggerEditor.addAnotherWayThisAutomation`,`Add another way this automation can start`),children:[o(v,{className:`h-4 w-4`}),` `,i(`automation.triggerEditor.trigger`)]})]})}function wn({trigger:t,devices:n,position:r,onChange:i,onRemove:a}){let{t:s}=Y();return e(`div`,{className:`rounded border border-border p-3`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(U,{variant:`default`,children:r===0?s(`automation.triggerEditor.when`,`When`):s(`automation.triggerEditor.orWhen`,`or when`)}),e(`label`,{className:`min-w-[13rem] flex-1`,children:[o(Z,{children:s(`automation.triggerEditor.trigger`,`Trigger`)}),o(K,{value:t.kind,onChange:e=>i(_t(Tn(e.target.value))),options:xn.map(e=>({value:e,label:ht(e)}))})]}),o(q,{variant:`ghost`,onClick:a,title:s(`automation.triggerEditor.removeThisTrigger`,`Remove this trigger`),children:o(h,{className:`h-4 w-4`})})]}),e(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:[t.kind===`device-state`&&o(Dn,{trigger:t,devices:n,onChange:i}),t.kind===`device-event`&&o(kn,{trigger:t,devices:n,onChange:i}),t.kind===`schedule`&&e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Z,{children:s(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(W,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>i({kind:`schedule`,cron:e.target.value})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]}),t.kind===`manual`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})]})]})}function Tn(e){return xn.find(t=>t===e)??`manual`}function En(e,t){return{kind:`device-state`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function Dn({trigger:t,devices:n,onChange:r}){let{t:i}=Y(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=ct(a),c={...t.becomes===void 0?{}:{becomes:t.becomes},...t.edge===void 0?{}:{edge:t.edge},...t.forMs===void 0?{}:{forMs:t.forMs},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}};return e(f,{children:[o(lt,{value:a,devices:n,onChange:e=>r(En(e,c))}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),e(`div`,{className:`flex items-center gap-2`,children:[e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(G,{checked:t.becomes===void 0,onChange:e=>r(En(a,{...c,...e.target.checked?{becomes:void 0}:{becomes:``}}))}),i(`automation.triggerEditor.anyChange`,`any change`)]}),t.becomes!==void 0&&o(jt,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(En(a,{...c,becomes:e}))})]})]}),e(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[o(G,{checked:t.edge===!0,onChange:e=>r(En(a,{...c,...e.target.checked?{edge:!0}:{edge:void 0}}))}),i(`automation.triggerEditor.onlyOnAChange`,`only on a change`)]}),e(`label`,{className:`w-28`,children:[o(Z,{children:i(`automation.triggerEditor.heldForS`,`Held for (s)`)}),o(W,{type:`number`,min:0,value:t.forMs===void 0?``:String(t.forMs/1e3),placeholder:`0`,onChange:e=>r(En(a,{...c,forMs:On(e.target.value)}))})]}),e(`label`,{className:`w-28`,children:[o(Z,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(W,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(En(a,{...c,debounceMs:On(e.target.value)}))})]})]})}function On(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function kn({trigger:t,devices:n,onChange:r}){let{t:i}=Y();return e(f,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.eventCategory`,`Event category`)}),o(K,{value:t.category,onChange:e=>r({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:i(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...Sn.map(e=>({value:e,label:e}))]})]}),e(`label`,{className:`min-w-[11rem] flex-1`,children:[o(Z,{children:i(`automation.triggerEditor.fromDevice`,`From device`)}),o(K,{value:t.deviceId===void 0?``:String(t.deviceId),onChange:e=>r({kind:`device-event`,category:t.category,...e.target.value===``?{}:{deviceId:Number(e.target.value)}}),options:[{value:``,label:i(`automation.triggerEditor.anyDevice`,`Any device`)},...n.map(e=>({value:String(e.id),label:e.name}))]})]})]})}u();var An=`hub`;function jn({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=Y(),[p,m]=c(t?.name??``),[h,g]=c(()=>Qt(n)),[_,v]=c(!1),b=at(),x=F(h),C=r(()=>Nn(h),[h]),w=r(()=>Pn(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),T=p.trim()===``,E=T||x!==null||C!==null||w.code===null;return e(`div`,{className:`space-y-4`,children:[o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(U,{variant:`info`,children:f(`automation.automationEditor.runsOnTheHub`,`runs on the hub`)})}),e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(W,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(Mn,{step:`1`,title:f(`automation.automationEditor.when`,`When`),subtitle:f(`automation.automationEditor.anyOneOfTheseStarts`,`Any one of these starts a run.`),children:o(Cn,{triggers:h.triggers,devices:b,onChange:e=>g(wt(h,e))})}),o(Mn,{step:`2`,title:f(`automation.automationEditor.andOnlyIf`,`And only if`),subtitle:f(`automation.automationEditor.checkedAfterATriggerFires`,`Checked after a trigger fires. Nothing runs unless this is true.`),children:o(gn,{recipe:h,devices:b,onChange:g})}),o(Mn,{step:`3`,title:f(`automation.automationEditor.then`,`Then`),subtitle:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(Dt,{actions:h.actions,devices:b,onChange:e=>g(Tt(h,e))})}),o(bn,{code:w.code,error:w.error,canEject:t!==null,ejecting:s,onEject:u}),x!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:x}),x===null&&C!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:C}),a!==null&&o(`p`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:a}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{onClick:()=>{w.code!==null&&l({name:p.trim(),code:w.code,enabled:t?.enabled??!0,placement:An})},disabled:i||E,children:[i&&o(y,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(q,{variant:`ghost`,onClick:()=>v(!_),disabled:t===null,title:t===null?f(`automation.automationEditor.logsAppearOnceTheAutomation`,`Logs appear once the automation has been saved and started`):f(`automation.automationEditor.showThisAutomationSProcess`,`Show this automation's process logs`),"data-testid":`automation-logs-toggle`,children:[o(S,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,_?`▾`:`▸`]}),o(q,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),T&&o(U,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),_&&t!==null&&e(`div`,{className:`rounded border border-border`,"data-testid":`automation-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ne,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Mn({step:t,title:n,subtitle:r,children:i}){return e(`section`,{className:`border-l-2 border-border pl-4`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[o(`span`,{className:`text-xs font-mono text-foreground-subtle`,children:t}),o(`h4`,{className:`text-sm font-medium uppercase tracking-wide`,children:n}),o(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i]})}function Nn(e){let t=I.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?J.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Pn(e,t){try{return{code:ne({name:e,recipe:t}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Fn(e){if(!e.enabled)return{tone:`idle`,label:J.t(`helpers.coreBlockStatus.disabled`),detail:J.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:J.t(`helpers.coreBlockStatus.running`),detail:J.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??J.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??J.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:J.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??J.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function In(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function Ln(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function Rn(e){let t=e=>{let t=Fn(e).tone;return t===`error`?0:t===`pending`?1:t===`ok`?2:3};return[...e].sort((e,n)=>t(e)-t(n)||e.name.localeCompare(n.name))}function zn(e){if(e.length===0)return J.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Fn(e).tone===`error`).length,n=e.filter(e=>Fn(e).tone===`ok`).length,r=[J.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(J.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(J.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}function Bn({block:t,busy:n,confirming:r,logsOpen:i,unreadable:a,onEdit:s,onToggle:c,onToggleLogs:l,onAskDelete:u,onCancelDelete:d,onConfirmDelete:f}){let g=T(),{t:_}=Y(),v=Fn(t),y=pe(t.updatedAt,g);return e(`li`,{className:`flex flex-col gap-2 p-3`,children:[e(`div`,{className:`flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3`,children:[e(`div`,{className:`min-w-0 flex-1`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(U,{variant:In(v.tone),children:v.label}),y!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:_(`common.edited`,{when:y})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:v.detail}),a!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:_(`automation.editor.listUnreadable`,{reason:a})})]}),r?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:_(`automation.automationList.deleteThisAutomation`,`Delete this automation?`)}),o(q,{variant:`danger`,onClick:e=>{e.stopPropagation(),f()},disabled:n,children:_(`common.delete`,`Delete`)}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),d()},children:_(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),s()},disabled:a!==null,title:a===null?_(`common.edit`,`Edit`):_(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),children:o(m,{className:`h-4 w-4`})}),e(be,{children:[o(ge,{children:o(q,{variant:`ghost`,disabled:!0,title:_(`automation.automationList.runActions`,`Run actions`),children:o(p,{className:`h-4 w-4`})})}),o(xe,{children:_(`automation.automationList.runningAnAutomationByHand`,`Running an automation by hand needs the automation-control authority, which is not wired up yet. There is deliberately no second way to execute one.`)})]}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),l()},title:_(`automation.automationList.logs`,`Logs`),children:o(S,{className:`h-4 w-4`})}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),c(!t.enabled)},disabled:n,title:t.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`),children:t.enabled?_(`common.disable`,`Disable`):_(`common.enable`,`Enable`)}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),u()},title:_(`common.delete`,`Delete`),children:o(h,{className:`h-4 w-4`})})]})]}),i&&e(`div`,{className:`rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ne,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}function Vn({onCreate:t}){let{t:n}=Y();return o(_e,{children:e(`div`,{className:`space-y-2 p-4`,children:[o(`p`,{className:`text-sm text-foreground`,children:n(`automation.automationList.noAutomationsYet`,`No automations yet.`)}),o(`p`,{className:`max-w-2xl text-xs text-foreground-subtle`,children:n(`automation.automationList.anAutomationIsATrigger`,`An automation is a trigger, a set of conditions and a list of actions. It compiles to an ordinary block and runs in its own supervised process — there is no separate engine, so anything that goes wrong shows up here with a reason.`)}),o(q,{onClick:t,children:n(`automation.automationList.newAutomation`,`New automation`)})]})})}u();var Hn=[`coreBlocks`,`list`],Un=5e3;function Wn(e){return e instanceof Error?e.message:String(e)}function Gn({onOpenScripts:t,initialBlockId:i,onBlockIdChange:a,createRequested:u=!1,onCreateConsumed:f}){let{t:p}=Y(),m=b(),{state:h,openNew:g,openEdit:_,close:v}=Me({editKey:`block`,newKey:`new`}),[y,x]=c(null),[S,w]=c(null),[T,E]=c(null),D=n(null),O=h.mode!==`closed`;s(()=>{u&&(x(null),g(),a?.(null),f?.())},[u,f,a,g]);let k=l({queryKey:Hn,refetchInterval:Un,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),A=()=>{k.refetch()},j=k.data;s(()=>{i===void 0||D.current===i||j?.find(e=>e.id===i&&et(e.code))!==void 0&&(D.current=i,_(i),a?.(i))},[i,j,_,a]);let M=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{x(e.block),_(e.block.id),a?.(e.block.id),A()}}),N=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{x(e.block),_(e.block.id),a?.(e.block.id),A()}}),P=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{w(null),A()}}),F=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:A}),I=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:rt(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{v(),x(null),A(),t(e.block.id)}}),L=k.data,R=Rn((L??[]).filter(e=>et(e.code))),z=L!==void 0&&R.length===0,B=h.mode===`edit`?R.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,V=h.mode===`new`||B===null?null:Ln(R,B),H=V===null?null:nt(V.code),ee=M.error===null?N.error===null?I.error===null?null:Wn(I.error):Wn(N.error):Wn(M.error),te=r(()=>[{key:`row`,header:p(`build.automationsTab.automation`,`Automation`),nowrap:!1,notSortableReason:`Composite status row`,render:e=>{let t=nt(e.code);return o(`ul`,{className:`list-none`,children:o(Bn,{block:e,busy:F.isPending||P.isPending,confirming:S===e.id,logsOpen:T===e.id,unreadable:t.ok?null:t.reason,onEdit:()=>{x(e),_(e.id),a?.(e.id)},onToggle:t=>F.mutate({blockId:e.id,enabled:t}),onToggleLogs:()=>E(T===e.id?null:e.id),onAskDelete:()=>w(e.id),onCancelDelete:()=>w(null),onConfirmDelete:()=>P.mutate(e.id)})})},sortValue:e=>e.name}],[S,T,a,_,P,F,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:L===void 0?``:zn(R)}),k.error!=null&&o(fe,{title:p(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:Wn(k.error),onRetry:A}),z?o(Vn,{onCreate:()=>{x(null),g(),a?.(null)}}):o(Le,{columns:te,rows:R,rowKey:e=>e.id,pageSize:25,maxBodyHeight:ve,emptyMessage:L===void 0?p(`build.automationsTab.loadingAutomations`,`Loading automations…`):p(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>{x(e),_(e.id),a?.(e.id)}}),o(Oe,{open:O,onClose:()=>{M.reset(),N.reset(),I.reset(),x(null),v(),a?.(null)},title:V===null?p(`build.automationsTab.newAutomation`,`New automation`):p(`build.automationsTab.edit`,`Edit {{name}}`,{name:V.name}),icon:C,width:`xl`,testId:`automation-editor-panel`,children:o(jn,{existing:V,initialRecipe:H!==null&&H.ok?H.recipe:gt,saving:M.isPending||N.isPending,saveError:ee,ejecting:I.isPending,onSave:e=>{V===null?M.mutate(e):N.mutate({blockId:V.id,block:e})},onEject:()=>{V!==null&&I.mutate(V)},onCancel:()=>{M.reset(),N.reset(),I.reset(),x(null),v(),a?.(null)}},V?.id??`new`)}),P.error!=null&&o(fe,{message:Wn(P.error)}),F.error!=null&&o(fe,{message:Wn(F.error)})]})}u();var Kn=`px-1.5 py-0.5 text-[11px] bg-background border border-border rounded`;function qn(){let{t}=Y(),n=T(),r=Ve(),i=Re(),a=me(),s=je(),l=Se({addonId:`composer`}),[u,d]=c(N.Sensor),[f,p]=c(M.TemperatureSensor),[m,h]=c(``),[g,_]=c(``),[v,y]=c(null),[b,x]=c(`choose`),S=Je({type:u,role:f});return b===`choose`?e(`section`,{className:`flex flex-col gap-3 rounded-lg border border-border bg-surface p-3 sm:p-4`,children:[o(`h2`,{className:`text-sm font-semibold`,children:t(`build.customDeviceTab.newComposedDevice`)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[o(q,{variant:`outline`,"data-testid":`blank-composition`,onClick:()=>x(`blank`),children:t(`helper.blank`)}),o(q,{"data-testid":`new-helper`,onClick:()=>x(`helper`),children:t(`helper.newHelper`)})]})]}):b===`helper`?e(`section`,{className:`flex flex-col gap-3 rounded-lg border border-border bg-surface p-3 sm:p-4`,children:[o(q,{variant:`ghost`,size:`sm`,onClick:()=>x(`choose`),children:t(`helper.back`)}),o(`h2`,{className:`text-sm font-semibold`,children:t(`helper.newHelper`)}),o(Xe,{initial:null,start:`template`,saving:i.isPending,onSave:e=>Ye(e,async(t,n)=>{let{block:o}=await i.mutateAsync({block:{...n===``?{}:{name:n},enabled:!0,composition:t}}),c=`${H}${o.id}`,u=((await l.refetch()).data??l.data)?.find(e=>e.stableId===c);if(u!==void 0){n!==``&&await a.mutateAsync({deviceId:u.id,name:n}),e.room.trim()!==``&&await s.mutateAsync({deviceId:u.id,location:e.room.trim()}),r(He(u.id),{replace:!0});return}r(`/build/compositions/${encodeURIComponent(o.id)}`,{replace:!0})})})]}):e(`section`,{className:`flex flex-col gap-3 rounded-lg border border-border bg-surface p-3 sm:p-4`,children:[o(q,{variant:`ghost`,size:`sm`,onClick:()=>x(`choose`),children:t(`helper.back`)}),o(`h2`,{className:`text-sm font-semibold`,children:t(`build.customDeviceTab.newComposedDevice`)}),e(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-2`,children:[e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`compositionEditor.targetType`),o(K,{value:u,onChange:e=>{let t=Object.values(N).find(t=>t===e.target.value);t!==void 0&&d(t)},options:Object.values(N).map(e=>({value:e,label:Pe(e,n).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`customize.identity.role`),o(K,{value:f??``,onChange:e=>p(Object.values(M).find(t=>t===e.target.value)??null),options:[{value:``,label:t(`customize.identity.noRole`)},...Object.values(M).map(e=>({value:e,label:Ee(e,n).label}))]})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`compositionEditor.name`),o(`input`,{className:Kn,value:m,onChange:e=>h(e.target.value)})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[t(`customize.identity.room`),o(`input`,{className:Kn,value:g,onChange:e=>_(e.target.value)})]})]}),v!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:v}),o(q,{disabled:S===null||i.isPending,onClick:()=>{S!==null&&(async()=>{y(null);try{let e=m.trim(),{block:t}=await i.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:S}}),n=`${H}${t.id}`,o=((await l.refetch()).data??l.data)?.find(e=>e.stableId===n);if(o!==void 0){e!==``&&await a.mutateAsync({deviceId:o.id,name:e}),g.trim()!==``&&await s.mutateAsync({deviceId:o.id,location:g.trim()}),r(He(o.id),{replace:!0});return}r(`/build/compositions/${encodeURIComponent(t.id)}`,{replace:!0})}catch(e){y(e instanceof Error?e.message:String(e))}})()},children:t(`compositionEditor.save`)})]})}function Jn(e){return{state:`answered`,byRef:new Map(e.map(e=>[L(e),e]))}}function Yn(e,t){if(e.state!==`unanswered`)return e.byRef.get(L(t))??null}function Xn(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function Zn(e){return re(e).map(e=>e.source)}function Qn(e){let t=e.block.source?.kind===`composition`?e.block.source.composition:null;if(t===null)return[];let n=[];for(let e of t.features){if(e.kind===`passthrough`){n.push(e.source);continue}for(let t of Object.values(e.fields))n.push(...Zn(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...Zn(e))}let r=new Set;return n.filter(e=>{let t=L(e);return r.has(t)?!1:(r.add(t),!0)})}function $n(e){let t=e.fields.filter(e=>e.state===`unavailable`),n=e.fields.filter(e=>e.state===`stale`);if(t.length===0&&n.length===0)return{tone:`ok`,label:J.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[J.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[J.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??J.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function er(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return $n(e);case`degraded`:return{tone:`pending`,label:J.t(`helpers.compositionRows.degraded`),reason:n??J.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:J.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:J.t(`helpers.compositionRows.failed`),reason:n??J.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:J.t(`helpers.compositionRows.notRunning`),reason:n??J.t(`helpers.compositionRows.notRunningReason`)}}}function tr(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:J.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:J.t(`helpers.compositionRows.unknown`),reason:J.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return er(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:J.t(`helpers.compositionRows.notReported`),reason:J.t(`helpers.compositionRows.noRecord`,{stored:r})}}function nr(e){return L(e)}function rr(e,t){let n=Yn(t,e);return{key:L(e),label:n?n.name:nr(e),presence:Xn(n),deviceId:n?n.id:null}}function ir(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function ar(e,t){let n=e.block.source?.kind===`composition`?e.block.source.composition:null;if(n===null)return null;let r=n.target,i=r.kind===`existing`?r.device:B(e.block.id),a=L(i),o=Qn(e).filter(e=>L(e)!==a).map(e=>rr(e,t)),s=n.features.map(e=>e.enabled===!1?J.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=Yn(t,i),l=ir(e),u=tr(e);if(r.kind===`new`)return{blockId:e.block.id,kind:`composed`,name:e.block.name,namePresence:`present`,type:r.role===void 0?r.type:`${r.type} · ${r.role}`,features:s,state:u,sources:o,reportedDeviceId:l};let d=Xn(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:nr(r.device),namePresence:d,type:c?c.type:null,features:s,state:u,sources:o,reportedDeviceId:l}}function or(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function sr(e,t){return or(e)-or(t)||e.name.localeCompare(t.name)}function cr(e,t){let n=e.flatMap(e=>{let n=ar(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(sr),customizations:n.filter(e=>e.kind===`customization`).toSorted(sr)}}var lr=1e4;function ur(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function dr(){let e=Be();return e.data===void 0?{state:`unanswered`,reason:e.error==null?J.t(`build.customDeviceTab.deviceListPending`):J.t(`build.customDeviceTab.deviceListUnreadable`,{error:ur(e.error)})}:Jn(e.data)}function fr({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=Y(),i=he({},{refetchInterval:lr}),a=dr(),s=Me({editKey:`block`,newKey:`new`}),c=s.state.mode===`edit`?s.state.id:null,l=c===null&&(t||s.state.mode===`new`),u=()=>{s.close(),n?.()},d=i.data;return e(f,{children:[mr(d,i.error,()=>void i.refetch(),a,{onEditComposed:e=>s.openEdit(e)}),o(Oe,{open:l||c!==null,onClose:u,title:l?r(`build.customDeviceTab.newComposedDevice`,`New composed device`):r(`build.customDeviceTab.editComposedDevice`,`Edit composed device`),icon:ie,width:`xl`,testId:`composed-device-editor`,children:l?o(qn,{}):c===null?null:o(Ze,{blockId:c})})]})}function pr(t){return o(_e,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:J.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[J.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function mr(e,t,n,r,i){if(t!=null&&e===void 0)return o(fe,{title:J.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:ur(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:J.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return pr(e.reason);let a=t==null?null:ur(t);return o(hr,{lists:cr(e.views,r),fleet:r,refreshError:a,onEditComposed:i.onEditComposed})}function hr({lists:t,fleet:n,refreshError:r,onEditComposed:i}){let{t:a}=Y();return e(`div`,{className:`space-y-4`,children:[r!==null&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.showingTheLastAnswerThe`,`Showing the last answer — the latest refresh failed:`),` `,r]}),n.state===`unanswered`&&e(`p`,{className:`text-xs text-warning`,children:[a(`build.customDeviceTab.deviceNamesAreShownAs`,`Device names are shown as references:`),` `,n.reason,`. No source is marked missing until it has.`]}),o(gr,{title:a(`build.customDeviceTab.composedDevices`,`Composed devices`),hint:a(`build.customDeviceTab.aNewDeviceWhoseState`,`A new device whose state is derived from other devices.`),rows:t.composed,nameHeader:`Name`,emptyMessage:a(`build.customDeviceTab.noComposedDevices`,`No composed devices.`),kind:`composed`,onEditComposed:i}),o(gr,{title:a(`build.customDeviceTab.customizations`,`Customizations`),hint:a(`build.customDeviceTab.fieldsAddedToOrReplaced`,`Fields added to or replaced on an existing device — one per device, edited from the device.`),rows:t.customizations,nameHeader:`Device`,emptyMessage:a(`build.customDeviceTab.noCustomizations`,`No customizations.`),kind:`customization`,onEditComposed:i})]})}function gr({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,onEditComposed:c}){return e(`section`,{className:`space-y-2`,"aria-label":t,children:[e(`div`,{children:[o(`h3`,{className:`font-medium`,children:t}),o(`p`,{className:`text-xs text-foreground-subtle`,children:n})]}),o(_e,{variant:`flat`,className:`p-0`,children:o(Le,{columns:_r(i,s,c),rows:r,rowKey:e=>e.blockId,minWidthPx:760,bordered:!1,maxBodyHeight:ve,emptyMessage:a,onRowClick:s===`composed`?e=>c(e.blockId):void 0})})]})}function _r(t,n,r){let i=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(vr,{row:e})},{key:`type`,header:J.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??J.t(`common.unknownWord`)})},{key:`state`,header:J.t(`build.customDeviceTab.state`,`State`),nowrap:!1,notSortableReason:`A state and its reason are read together, not ordered.`,render:t=>e(`div`,{className:`space-y-0.5`,children:[o(U,{variant:In(t.state.tone),children:t.state.label}),t.state.reason!==null&&o(`p`,{className:`max-w-md whitespace-normal text-xs text-foreground-subtle`,children:t.state.reason})]})},{key:`sources`,header:J.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(br,{sources:e.sources})}];return n===`composed`&&i.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:e=>o(`div`,{className:`flex justify-end gap-1`,children:o(q,{type:`button`,size:`sm`,variant:`secondary`,onClick:t=>{t.stopPropagation(),r(e.blockId)},children:J.t(`common.edit`,`Edit`)})})}),i}function vr({row:t}){let{t:n}=Y();return e(`div`,{className:`space-y-0.5`,children:[o(yr,{row:t}),t.namePresence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`build.customDeviceTab.deviceMissing`,`device missing`)}),o(`p`,{className:`text-[11px] text-foreground-subtle`,children:t.features.join(`, `)})]})}function yr({row:e}){let{t}=Y();return e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):e.reportedDeviceId===null?o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:e.name})}):o(We,{to:He(e.reportedDeviceId),className:`text-xs text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:e.name})}function br({sources:t}){let{t:n}=Y();return t.length===0?o(`span`,{className:`text-xs text-foreground-subtle`,children:`—`}):o(`ul`,{className:`space-y-0.5`,children:t.map(t=>e(`li`,{className:`text-xs`,children:[t.deviceId===null?o(`span`,{className:t.presence===`missing`?`text-danger`:`text-foreground`,children:t.label}):o(We,{to:`/devices/${String(t.deviceId)}`,className:`hover:underline`,children:t.label}),t.presence===`missing`&&o(`span`,{className:`ml-1.5 text-[10px] text-danger`,children:n(`common.missing`)})]},t.key))})}function xr(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Sr(e){if(Array.isArray(e))return e}function Cr(e,t,n){return(t=Mr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function wr(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t!==0)for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Tr(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
5
5
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Er(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Dr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Er(Object(n),!0).forEach(function(t){Cr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Er(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Or(e,t){if(e==null)return{};var n,r,i=kr(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function kr(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Ar(e,t){return Sr(e)||wr(e,t)||Nr(e,t)||Tr()}function jr(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Mr(e){var t=jr(e,`string`);return typeof t==`symbol`?t:t+``}function Nr(e,t){if(e){if(typeof e==`string`)return xr(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?xr(e,t):void 0}}function Pr(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Fr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ir(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Fr(Object(n),!0).forEach(function(t){Pr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Fr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Lr(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Rr(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function zr(e){return{}.toString.call(e).includes(`Object`)}function Br(e){return!Object.keys(e).length}function Vr(e){return typeof e==`function`}function Hr(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ur(e,t){return zr(t)||Jr(`changeType`),Object.keys(t).some(function(t){return!Hr(e,t)})&&Jr(`changeField`),t}function Wr(e){Vr(e)||Jr(`selectorType`)}function Gr(e){Vr(e)||zr(e)||Jr(`handlerType`),zr(e)&&Object.values(e).some(function(e){return!Vr(e)})&&Jr(`handlersType`)}function Kr(e){e||Jr(`initialIsRequired`),zr(e)||Jr(`initialType`),Br(e)&&Jr(`initialContent`)}function qr(e,t){throw Error(e[t]||e.default)}var Jr=Rr(qr)({initialIsRequired:`initial state is required`,initialType:`initial state should be an object`,initialContent:`initial state shouldn't be an empty object`,handlerType:`handler should be an object or a function`,handlersType:`all handlers should be a functions`,selectorType:`selector should be a function`,changeType:`provided value of changes should be an object`,changeField:`it seams you want to change a field in the state which is not specified in the "initial" state`,default:"an unknown error accured in `state-local` package"}),Yr={changes:Ur,selector:Wr,handler:Gr,initial:Kr};function Xr(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Yr.initial(e),Yr.handler(t);var n={current:e},r=Rr($r)(n,t),i=Rr(Qr)(n),a=Rr(Yr.changes)(e),o=Rr(Zr)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return Yr.selector(e),e(n.current)}function c(e){Lr(r,i,a,o)(e)}return[s,c]}function Zr(e,t){return Vr(t)?t(e.current):t}function Qr(e,t){return e.current=Ir(Ir({},e.current),t),t}function $r(e,t,n){return Vr(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var ei={create:Xr},ti={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function ni(e){return function t(){var n=this,r=[...arguments];return r.length>=e.length?e.apply(this,r):function(){var e=[...arguments];return t.apply(n,[].concat(r,e))}}}function ri(e){return{}.toString.call(e).includes(`Object`)}function ii(e){return e||ci(`configIsRequired`),ri(e)||ci(`configType`),e.urls?(ai(),{paths:{vs:e.urls.monacoBase}}):e}function ai(){console.warn(si.deprecation)}function oi(e,t){throw Error(e[t]||e.default)}var si={configIsRequired:`the configuration object is required`,configType:`the configuration object should be an object`,default:"an unknown error accured in `@monaco-editor/loader` package",deprecation:`Deprecation warning!
|
|
6
6
|
You are using deprecated way of configuration.
|
|
7
7
|
|
|
@@ -37,4 +37,4 @@ export default function block(ctx: AddonContext) {
|
|
|
37
37
|
ctx.logger.info('hello from a core block')
|
|
38
38
|
return () => undefined
|
|
39
39
|
}
|
|
40
|
-
`;function na({existing:e,dirty:t,saving:n,restarting:r}){return e===null?J.t(`helpers.restartGate.saveFirstNoProcess`):n?J.t(`helpers.restartGate.saving`):r?J.t(`helpers.restartGate.restarting`):t?J.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:J.t(`helpers.restartGate.disabled`)}u();var ra=5e3;function ia(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=Reflect.get(n,`id`),r=Reflect.get(n,`name`),i=Reflect.get(n,`type`),a=Reflect.get(n,`stableId`);typeof e!=`number`||typeof r!=`string`||typeof i!=`string`||t.push({id:e,name:r,type:i,...typeof a==`string`?{stableId:a}:{}})}return t}function aa({blockId:t}){let{t:n}=Y(),i=z(t),a=Te({addonId:i,projection:`slim`},{refetchInterval:ra}),s=r(()=>ia(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(y,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptDevicesPanel.loading`)]}):a.isError?e(`p`,{className:`text-xs text-danger`,children:[n(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,a.error instanceof Error?a.error.message:String(a.error)]}):e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(G,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:o(`code`,{})}})}):o(`ul`,{className:`space-y-3`,children:s.map(t=>o(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${t.id}`,children:e(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[o(We,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:t.name}),o(G,{variant:`info`,style:`outline`,children:t.type}),t.stableId!==void 0&&e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,o(`code`,{children:t.stableId})]}),e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,t.id]})]})},t.id))})]})}u();function oa(e){return e===`refresh-channel-catalog`||e===`send-tv-schedule-now`||e===`refresh-nordvpn-catalog`||e===`probe-nordvpn-italy`||e===`test-nordvpn-endpoint`||e===`refresh-unifi-catalog`}function sa(e){let t=Date.now();switch(e){case`refresh-channel-catalog`:return{channelCatalogRefreshAt:t};case`send-tv-schedule-now`:return{sendNowAt:t};case`refresh-nordvpn-catalog`:return{nordVpnCatalogRefreshAt:t};case`probe-nordvpn-italy`:return{nordVpnProbeAt:t};case`test-nordvpn-endpoint`:return{nordVpnTestAt:t};case`refresh-unifi-catalog`:return{unifiCatalogRefreshAt:t}}}function ca(e){switch(e){case`refresh-channel-catalog`:return J.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return J.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return J.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return J.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return J.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return J.t(`build.scriptSettingsPanel.enableUnifi`)}}function la(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function ua(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function da(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=la(e);n!==null&&(t[n]=ua(e))}return t}function fa(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function pa({blockId:t}){let{t:n}=Y(),i=b(),s=_e({blockId:t},{retry:!1}),l=ue({blockId:t},{refetchInterval:1e4,retry:!1}),u=le({onSuccess:()=>{l.refetch()}}),d=me(),f=Ae(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[x,S]=c(!1),C=fa(l.data)?l.data:null,w=r(()=>C===null?{}:da(C),[C]),T=p??w,E=a(e=>{m(e)},[]),D=p!==null,O=a(()=>{p!==null&&(g(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[t,p,u]),k=a(async(e,n)=>{if(oa(e)){S(!0),g(null),v(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:sa(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(ca(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{S(!1)}}},[t,s.data?.block?.enabled,p,d,f,l,i.trpcClient.coreBlocks]);return l.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(y,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):l.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,l.error instanceof Error?l.error.message:String(l.error)]}):C===null?null:e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(W,{size:`sm`,variant:`primary`,onClick:O,disabled:!D||u.isPending||x,children:[u.isPending&&o(y,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(ze,{schema:C,values:T,onChange:E,onAction:k}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}u();var ma=`hub`;function ha({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:p,onSave:m,onCancel:h}){let{t:_}=Y(),v=b(),C=ve(),{resolvedMode:w}=ke(),T=ee({code:t?.code??ta,files:t?.files,entry:t?.entry}),[D,O]=c(t?.name??``),[k,A]=c(T.files),[j,M]=c(T.entry),[N,P]=c(T.entry),[F,I]=c(t?.placement??ma),[L,R]=c(t?.integrationId??``),[B,V]=c([]),[H,te]=c(!1),[ne,re]=c(`blank`),[ie,ae]=c(null),[oe,se]=c(``),ce=k[N]??``,le=e=>{A(t=>({...t,[N]:e}))},ue=Object.keys(k).toSorted(),de=$i.length>1,fe=r(()=>[...n?.libs??[],...Ji(k,N)],[n?.libs,k,N]),U=d({mutationFn:()=>v.trpcClient.coreBlocks.compile.mutate({files:k,entry:j})}),pe=r(()=>B.filter(e=>e.severity>=8),[B]),me=Qi(B),he=D.trim()===``,ge=t===null?null:ee(t),_e=t===null||ge===null||JSON.stringify(k)!==JSON.stringify(ge.files)||j!==ge.entry||D.trim()!==t.name||F!==t.placement||(L.trim()===``?void 0:L.trim())!==t.integrationId,ye=()=>{U.reset(),m({name:D.trim(),files:k,entry:j,enabled:t?.enabled??!0,placement:F,...L.trim()===``?{}:{integrationId:L.trim()}})},be=()=>{let e=ea(Object.keys(k));A(t=>({...t,[e]:``})),P(e),ae(e),se(e)},xe=e=>{ae(e),se(e)},Se=()=>{if(ie===null)return;let e=ie,t=oe.trim();if(ae(null),!(t===``||t===e)){if(k[t]!==void 0){P(t);return}A(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),j===e&&M(t),P(t)}},Ce=async e=>{let t=$i.find(t=>t.id===e);if(t===void 0)return;let n=$i.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(k)===JSON.stringify(n.files)&&j===n.entry)&&!await C({title:_(`build.blockEditor.loadExample`,`Load example`),message:_(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:_(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(re(e),A({...t.files}),M(t.entry),P(t.entry),(D.trim()===``||ne===`blank`)&&O(t.id===`blank`?``:t.name))},we=t===null?null:Fn(t),Te=na({existing:t,dirty:_e,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[we!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(G,{variant:In(we.tone),children:we.label})}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.name`,`Name`)}),o(K,{className:`mt-1`,value:D,onChange:e=>O(e.target.value),placeholder:_(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(K,{className:`mt-1`,value:L,onChange:e=>R(e.target.value),placeholder:_(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&de&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.startFrom`,`Start from`)}),o(`select`,{className:`mt-1 w-full rounded border border-border bg-surface px-2 py-1.5 text-sm`,value:ne,onChange:e=>void Ce(e.target.value),"data-testid":`script-example-select`,children:$i.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(Re,{selectedNodeId:F,onSelect:I,label:_(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),F!==ma&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(g,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(X,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[ue.map(t=>ie===t?o(K,{value:oe,onChange:e=>se(e.target.value),onBlur:()=>Se(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),Se()),e.key===`Escape`&&(e.preventDefault(),ae(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":_(`build.blockEditor.renameFile`,`Rename file`)},t):e(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs ${t===N?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>P(t),onDoubleClick:()=>xe(t),title:_(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===j?` · ${_(`build.blockEditor.entry`)}`:``]},t)),o(`button`,{type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:be,"data-testid":`script-file-add`,children:_(`build.blockEditor.file`,`+ file`)}),N!==j&&o(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>M(N),title:_(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:_(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:_(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):o(Zi,{value:ce,onChange:le,path:`file:///${N}`,extraLibs:fe,onDiagnostics:V,dark:w===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:_(`build.blockEditor.theNodeReturnedNoType`,`The node returned no type definitions, so this code is NOT being checked against the system's types. The server-side compile still applies on save.`)}),pe.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[o(`p`,{className:`font-medium text-danger`,children:_(`build.blockEditor.errorsCannotSave`,{count:pe.length})}),pe.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:_(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),pe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.moreErrors`,{count:pe.length-5})})]}),U.data!==void 0&&(U.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(x,{className:`h-3.5 w-3.5`}),` `,_(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[U.data.line!==void 0&&o(`span`,{className:`mr-1`,children:_(`build.blockEditor.errorLine`,{line:String(U.data.line)})}),U.data.error??_(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),U.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[_(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,ga(U.error)]}),s!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),t!==null&&e(`div`,{className:`space-y-3`,children:[o(pa,{blockId:t.id}),o(aa,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(W,{variant:`outline`,onClick:()=>U.mutate(),disabled:U.isPending||a,title:_(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[U.isPending&&o(y,{className:`h-4 w-4 animate-spin`}),` `,_(`common.compile`)]}),e(W,{onClick:ye,disabled:a||me||he,children:[a&&o(y,{className:`h-4 w-4 animate-spin`}),` `,_(`common.save`)]}),e(W,{variant:`outline`,onClick:()=>p?.(),disabled:Te!==null||p===void 0,title:Te??_(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(E,{className:`h-4 w-4 animate-spin`}):o(E,{className:`h-4 w-4`}),` `,_(`build.blockEditor.restart`,`Restart`)]}),e(W,{variant:`ghost`,onClick:()=>te(!H),title:_(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,children:[o(S,{className:`h-4 w-4`}),` `,_(`common.logs`),` `,H?`▾`:`▸`]}),o(W,{variant:`ghost`,onClick:h,disabled:a,children:_(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[_(`build.blockEditor.errorsCount`,{count:pe.length}),_e&&t!==null?` · ${_(`build.blockEditor.unsavedChanges`)}`:``]}),he&&o(G,{variant:`warning`,children:_(`build.blockEditor.nameRequired`,`Name required`)})]}),H&&e(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:t===null?_(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):o(f,{children:o(X,{i18nKey:`build.blockEditor.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(Pe,{addonId:z(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function ga(e){return e instanceof Error?e.message:String(e)}u();var _a=[`coreBlocks`,`list`],va=[`coreBlocks`,`getTypeDefs`],ya=5e3;function ba(e){return e instanceof Error?e.message:String(e)}function xa({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let f=T(),{t:p}=Y(),m=b(),{state:g,openNew:_,openEdit:v,close:y}=je({editKey:`block`,newKey:`new`}),[x,C]=c(null),[w,D]=c(null),[O,k]=c(null),A=l({queryKey:_a,refetchInterval:ya,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),j=g.mode!==`closed`,M=l({queryKey:va,enabled:j,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),N=()=>{A.refetch()},P=n(null),F=A.data;s(()=>{t===void 0||P.current===t||F?.find(e=>e.id===t&&V(e)===`code`)!==void 0&&(P.current=t,v(t),i?.(t))},[t,F,v,i]),s(()=>{a&&(C(null),_(),i?.(null),u?.())},[a,u,i,_]);let I=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{C(e.block),v(e.block.id),i?.(e.block.id),N()}}),L=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{C(e.block),v(e.block.id),i?.(e.block.id),N()}}),R=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{D(null),N()}}),B=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:N}),H=d({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:N}),ee=Rn((A.data??[]).filter(e=>V(e)===`code`)),te=A.data!==void 0&&ee.length===0,ne=I.isPending||L.isPending,re=I.error===null?L.error===null?null:ba(L.error):ba(I.error),ie=g.mode===`edit`?ee.find(e=>e.id===g.id)??(x!==null&&x.id===g.id?x:null):null,oe=g.mode===`new`||ie===null?null:Ln(ee,ie),se=r(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:t=>{let n=Fn(t),r=Me(t.updatedAt,f);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(G,{variant:In(n.tone),children:n.label}),o(G,{variant:`info`,children:t.placement}),r!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`common.edited`,{when:r})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:n.detail}),O===t.id&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Pe,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:t=>{let n=B.isPending||R.isPending,r=H.isPending&&H.variables===t.id;return w===t.id?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`build.scriptsTab.deleteThisScript`,`Delete this script?`)}),o(W,{variant:`danger`,onClick:()=>R.mutate(t.id),disabled:n,children:p(`common.delete`,`Delete`)}),o(W,{variant:`ghost`,onClick:()=>D(null),children:p(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),C(t),v(t.id),i?.(t.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),H.mutate(t.id)},disabled:n||r||!t.enabled,title:t.enabled?p(`build.scriptsTab.restart`,`Restart`):p(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:o(E,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),k(O===t.id?null:t.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:o(S,{className:`h-4 w-4`})}),o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),B.mutate({blockId:t.id,enabled:!t.enabled})},disabled:n,title:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`),children:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`)}),o(W,{variant:`ghost`,onClick:e=>{e.stopPropagation(),D(t.id)},title:p(`common.delete`,`Delete`),children:o(h,{className:`h-4 w-4`})})]})}}],[w,O,i,v,R,H.isPending,H.variables,B,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:A.data===void 0?``:zn(ee)}),A.error!=null&&o(U,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:ba(A.error),onRetry:N}),o(de,{columns:se,rows:ee,rowKey:e=>e.id,pageSize:25,maxBodyHeight:Ie,emptyMessage:te?p(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):A.data===void 0?p(`build.scriptsTab.loadingScripts`,`Loading scripts…`):p(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{C(e),v(e.id),i?.(e.id)}}),o(Oe,{open:j,onClose:()=>{I.reset(),L.reset(),H.reset(),C(null),y(),i?.(null)},title:oe===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:oe.name}),icon:ae,width:`xl`,testId:`script-editor-panel`,children:o(ha,{existing:oe,typeDefs:M.data,typeDefsLoading:M.isLoading,saving:ne,saveError:re,restarting:H.isPending,restartError:H.error===null?null:ba(H.error),onRestart:oe===null?void 0:()=>H.mutate(oe.id),onSave:e=>{let t=oe;t===null?I.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),L.reset(),H.reset(),C(null),y(),i?.(null)}})}),R.error!=null&&o(U,{message:ba(R.error)}),B.error!=null&&o(U,{message:ba(B.error)}),H.error!=null&&o(U,{message:ba(H.error)})]})}var Sa=[`automations`,`scripts`,`custom-device`];function Ca(e){return e!==null&&Sa.some(t=>t===e)}var wa=[`coreBlocks`,`list`,`build-counts`],Ta=[`block`,`create`,`new`];function Ea(e){return e.filter(e=>V(e)===`code`).length}function Da(e){return e.filter(e=>et(e.code)).length}function Oa(e,t){return t===null?e:`${e} (${String(t)})`}function ka(){let{t}=Y(),n=b(),[r,i]=Ue(),a=r.get(`tab`),s=Ca(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:wa,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:Ea(u),f=u===void 0?null:Da(u),p=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),m=p.data?.state===`loaded`?p.data.views.length:null,h=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},g=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`automations`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},_=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},y=()=>{i(e=>{if(s===`custom-device`){let e=new URLSearchParams(window.location.search);return e.set(`tab`,`custom-device`),e.delete(`block`),e.delete(`create`),e.set(`new`,`1`),e}let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},x=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},S=s===`automations`?`New automation`:s===`scripts`?`New script`:`New composition`,C=Ge(`/build`,{t,isAdmin:!0})??{icon:D,title:t(`nav.build`,`Build-your-self`)};return o(Ke,{icon:C.icon,title:C.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${C.title} sections`,fill:!0,actions:e(W,{type:`button`,onClick:y,"data-testid":`build-new`,children:[o(v,{className:`h-4 w-4`}),` `,S]}),sections:[{id:`automations`,label:Oa(`Automations`,f),ownedParams:Ta,content:o(Gn,{onOpenScripts:h,initialBlockId:s===`automations`?r.get(`block`)??void 0:void 0,onBlockIdChange:g,createRequested:s===`automations`&&c,onCreateConsumed:x})},{id:`scripts`,label:Oa(`Scripts`,d),ownedParams:Ta,content:o(xa,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:_,createRequested:s===`scripts`&&c,onCreateConsumed:x})},{id:`custom-device`,label:Oa(`Custom Device`,m),ownedParams:Ta,content:o(fr,{createRequested:s===`custom-device`&&c,onCreateConsumed:x})}]})}export{ka as BuildPage};
|
|
40
|
+
`;function na({existing:e,dirty:t,saving:n,restarting:r}){return e===null?J.t(`helpers.restartGate.saveFirstNoProcess`):n?J.t(`helpers.restartGate.saving`):r?J.t(`helpers.restartGate.restarting`):t?J.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:J.t(`helpers.restartGate.disabled`)}u();var ra=5e3;function ia(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let e=Reflect.get(n,`id`),r=Reflect.get(n,`name`),i=Reflect.get(n,`type`),a=Reflect.get(n,`stableId`);typeof e!=`number`||typeof r!=`string`||typeof i!=`string`||t.push({id:e,name:r,type:i,...typeof a==`string`?{stableId:a}:{}})}return t}function aa({blockId:t}){let{t:n}=Y(),i=z(t),a=De({addonId:i,projection:`slim`},{refetchInterval:ra}),s=r(()=>ia(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(y,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptDevicesPanel.loading`)]}):a.isError?e(`p`,{className:`text-xs text-danger`,children:[n(`build.scriptDevicesPanel.couldNotListDevices`,`Could not list devices:`),` `,a.error instanceof Error?a.error.message:String(a.error)]}):e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-devices-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptDevicesPanel.devices`,`Devices`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(U,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`build.scriptDevicesPanel.noDevices`,components:{code:o(`code`,{})}})}):o(`ul`,{className:`space-y-3`,children:s.map(t=>o(`li`,{className:`rounded border border-border/80 px-3 py-2`,"data-testid":`script-device-${t.id}`,children:e(`div`,{className:`flex flex-wrap items-baseline gap-2`,children:[o(We,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:t.name}),o(U,{variant:`info`,style:`outline`,children:t.type}),t.stableId!==void 0&&e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`stableId `,o(`code`,{children:t.stableId})]}),e(`span`,{className:`text-[11px] text-foreground-subtle`,children:[`#`,t.id]})]})},t.id))})]})}u();function oa(e){return e===`refresh-channel-catalog`||e===`send-tv-schedule-now`||e===`refresh-nordvpn-catalog`||e===`probe-nordvpn-italy`||e===`test-nordvpn-endpoint`||e===`refresh-unifi-catalog`}function sa(e){let t=Date.now();switch(e){case`refresh-channel-catalog`:return{channelCatalogRefreshAt:t};case`send-tv-schedule-now`:return{sendNowAt:t};case`refresh-nordvpn-catalog`:return{nordVpnCatalogRefreshAt:t};case`probe-nordvpn-italy`:return{nordVpnProbeAt:t};case`test-nordvpn-endpoint`:return{nordVpnTestAt:t};case`refresh-unifi-catalog`:return{unifiCatalogRefreshAt:t}}}function ca(e){switch(e){case`refresh-channel-catalog`:return J.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return J.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return J.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return J.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return J.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return J.t(`build.scriptSettingsPanel.enableUnifi`)}}function la(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function ua(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function da(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=la(e);n!==null&&(t[n]=ua(e))}return t}function fa(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function pa({blockId:t}){let{t:n}=Y(),i=b(),s=de({blockId:t},{retry:!1}),l=Ie({blockId:t},{refetchInterval:1e4,retry:!1}),u=ke({onSuccess:()=>{l.refetch()}}),d=Ae(),f=ue(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[x,S]=c(!1),C=fa(l.data)?l.data:null,w=r(()=>C===null?{}:da(C),[C]),T=p??w,E=a(e=>{m(e)},[]),D=p!==null,O=a(()=>{p!==null&&(g(null),u.mutate({blockId:t,patch:p},{onSuccess:()=>m(null),onError:e=>g(e instanceof Error?e.message:String(e))}))},[t,p,u]),k=a(async(e,n)=>{if(oa(e)){S(!0),g(null),v(null);try{p!==null&&(await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:p}),m(null)),await i.trpcClient.coreBlocks.updateBlockSettings.mutate({blockId:t,patch:sa(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(ca(e))),await d.mutateAsync({blockId:t}),await l.refetch(),e===`send-tv-schedule-now`?v(`Sending tonight’s schedule now…`):e===`probe-nordvpn-italy`?v(`Probing NordVPN Italy stations (no UniFi change)…`):e===`test-nordvpn-endpoint`?v(`Testing VPN endpoint on UniFi…`):e===`refresh-nordvpn-catalog`?v(`Refreshing NordVPN Italy catalog…`):e===`refresh-unifi-catalog`&&v(`Refreshing UniFi ID catalogs…`)}catch(e){g(e instanceof Error?e.message:String(e))}finally{S(!1)}}},[t,s.data?.block?.enabled,p,d,f,l,i.trpcClient.coreBlocks]);return l.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(y,{className:`h-3.5 w-3.5 animate-spin`}),` `,n(`build.scriptSettingsPanel.loading`)]}):l.isError?e(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-error`,children:[n(`build.scriptSettingsPanel.couldNotLoadSettings`,`Could not load settings:`),` `,l.error instanceof Error?l.error.message:String(l.error)]}):C===null?null:e(`section`,{className:`space-y-3 rounded border border-border p-3`,"data-testid":`script-settings-panel`,children:[e(`div`,{className:`flex items-center justify-between gap-2`,children:[e(`div`,{children:[o(`h4`,{className:`text-sm font-medium`,children:n(`build.scriptSettingsPanel.settings`,`Settings`)}),o(`p`,{className:`text-xs text-foreground-subtle`,children:o(X,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(q,{size:`sm`,variant:`primary`,onClick:O,disabled:!D||u.isPending||x,children:[u.isPending&&o(y,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(ze,{schema:C,values:T,onChange:E,onAction:k}),h===null?null:o(`p`,{className:`text-xs text-danger`,"data-testid":`script-settings-save-error`,children:h}),_===null?null:o(`p`,{className:`text-xs text-foreground-subtle`,"data-testid":`script-settings-info`,children:_})]})}u();var ma=`hub`;function ha({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:p,onSave:m,onCancel:h}){let{t:_}=Y(),v=b(),C=ye(),{resolvedMode:w}=Ce(),T=ee({code:t?.code??ta,files:t?.files,entry:t?.entry}),[D,O]=c(t?.name??``),[k,A]=c(T.files),[j,M]=c(T.entry),[N,P]=c(T.entry),[F,I]=c(t?.placement??ma),[L,R]=c(t?.integrationId??``),[B,V]=c([]),[H,te]=c(!1),[ne,re]=c(`blank`),[ie,ae]=c(null),[oe,se]=c(``),ce=k[N]??``,le=e=>{A(t=>({...t,[N]:e}))},ue=Object.keys(k).toSorted(),de=$i.length>1,fe=r(()=>[...n?.libs??[],...Ji(k,N)],[n?.libs,k,N]),G=d({mutationFn:()=>v.trpcClient.coreBlocks.compile.mutate({files:k,entry:j})}),pe=r(()=>B.filter(e=>e.severity>=8),[B]),K=Qi(B),me=D.trim()===``,he=t===null?null:ee(t),ge=t===null||he===null||JSON.stringify(k)!==JSON.stringify(he.files)||j!==he.entry||D.trim()!==t.name||F!==t.placement||(L.trim()===``?void 0:L.trim())!==t.integrationId,_e=()=>{G.reset(),m({name:D.trim(),files:k,entry:j,enabled:t?.enabled??!0,placement:F,...L.trim()===``?{}:{integrationId:L.trim()}})},ve=()=>{let e=ea(Object.keys(k));A(t=>({...t,[e]:``})),P(e),ae(e),se(e)},be=e=>{ae(e),se(e)},xe=()=>{if(ie===null)return;let e=ie,t=oe.trim();if(ae(null),!(t===``||t===e)){if(k[t]!==void 0){P(t);return}A(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),j===e&&M(t),P(t)}},Se=async e=>{let t=$i.find(t=>t.id===e);if(t===void 0)return;let n=$i.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(k)===JSON.stringify(n.files)&&j===n.entry)&&!await C({title:_(`build.blockEditor.loadExample`,`Load example`),message:_(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:_(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(re(e),A({...t.files}),M(t.entry),P(t.entry),(D.trim()===``||ne===`blank`)&&O(t.id===`blank`?``:t.name))},Te=t===null?null:Fn(t),Ee=na({existing:t,dirty:ge,saving:a,restarting:l});return e(`div`,{className:`space-y-4`,children:[Te!==null&&o(`div`,{className:`flex flex-wrap items-center gap-2`,children:o(U,{variant:In(Te.tone),children:Te.label})}),e(`div`,{className:`grid gap-3 sm:grid-cols-2`,children:[e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.name`,`Name`)}),o(W,{className:`mt-1`,value:D,onChange:e=>O(e.target.value),placeholder:_(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(W,{className:`mt-1`,value:L,onChange:e=>R(e.target.value),placeholder:_(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&de&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.startFrom`,`Start from`)}),o(`select`,{className:`mt-1 w-full rounded border border-border bg-surface px-2 py-1.5 text-sm`,value:ne,onChange:e=>void Se(e.target.value),"data-testid":`script-example-select`,children:$i.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(we,{selectedNodeId:F,onSelect:I,label:_(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),F!==ma&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(g,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(X,{i18nKey:`build.blockEditor.hubOnlyWarning`,components:{strong:o(`strong`,{})}})})]})]}),e(`div`,{className:`flex min-h-[56vh] flex-col rounded border border-border`,children:[e(`div`,{className:`flex flex-wrap items-center gap-1 border-b border-border px-2 py-1.5`,children:[ue.map(t=>ie===t?o(W,{value:oe,onChange:e=>se(e.target.value),onBlur:()=>xe(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),xe()),e.key===`Escape`&&(e.preventDefault(),ae(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":_(`build.blockEditor.renameFile`,`Rename file`)},t):e(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs ${t===N?`bg-muted font-medium text-foreground`:`text-foreground-subtle hover:text-foreground`}`,onClick:()=>P(t),onDoubleClick:()=>be(t),title:_(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===j?` · ${_(`build.blockEditor.entry`)}`:``]},t)),o(`button`,{type:`button`,className:`ml-1 rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:ve,"data-testid":`script-file-add`,children:_(`build.blockEditor.file`,`+ file`)}),N!==j&&o(`button`,{type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>M(N),title:_(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:_(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:_(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):o(Zi,{value:ce,onChange:le,path:`file:///${N}`,extraLibs:fe,onDiagnostics:V,dark:w===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:_(`build.blockEditor.theNodeReturnedNoType`,`The node returned no type definitions, so this code is NOT being checked against the system's types. The server-side compile still applies on save.`)}),pe.length>0&&e(`div`,{className:`space-y-1 rounded border border-danger/40 bg-danger/10 p-3 text-xs`,children:[o(`p`,{className:`font-medium text-danger`,children:_(`build.blockEditor.errorsCannotSave`,{count:pe.length})}),pe.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:_(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),pe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:_(`build.blockEditor.moreErrors`,{count:pe.length-5})})]}),G.data!==void 0&&(G.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(x,{className:`h-3.5 w-3.5`}),` `,_(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[G.data.line!==void 0&&o(`span`,{className:`mr-1`,children:_(`build.blockEditor.errorLine`,{line:String(G.data.line)})}),G.data.error??_(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),G.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[_(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,ga(G.error)]}),s!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:s}),u!==null&&o(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:u}),t!==null&&e(`div`,{className:`space-y-3`,children:[o(pa,{blockId:t.id}),o(aa,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(q,{variant:`outline`,onClick:()=>G.mutate(),disabled:G.isPending||a,title:_(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[G.isPending&&o(y,{className:`h-4 w-4 animate-spin`}),` `,_(`common.compile`)]}),e(q,{onClick:_e,disabled:a||K||me,children:[a&&o(y,{className:`h-4 w-4 animate-spin`}),` `,_(`common.save`)]}),e(q,{variant:`outline`,onClick:()=>p?.(),disabled:Ee!==null||p===void 0,title:Ee??_(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(E,{className:`h-4 w-4 animate-spin`}):o(E,{className:`h-4 w-4`}),` `,_(`build.blockEditor.restart`,`Restart`)]}),e(q,{variant:`ghost`,onClick:()=>te(!H),title:_(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,children:[o(S,{className:`h-4 w-4`}),` `,_(`common.logs`),` `,H?`▾`:`▸`]}),o(q,{variant:`ghost`,onClick:h,disabled:a,children:_(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[_(`build.blockEditor.errorsCount`,{count:pe.length}),ge&&t!==null?` · ${_(`build.blockEditor.unsavedChanges`)}`:``]}),me&&o(U,{variant:`warning`,children:_(`build.blockEditor.nameRequired`,`Name required`)})]}),H&&e(`div`,{className:`rounded border border-border`,"data-testid":`script-logs-panel`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:t===null?_(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):o(f,{children:o(X,{i18nKey:`build.blockEditor.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(Ne,{addonId:z(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function ga(e){return e instanceof Error?e.message:String(e)}u();var _a=[`coreBlocks`,`list`],va=[`coreBlocks`,`getTypeDefs`],ya=5e3;function ba(e){return e instanceof Error?e.message:String(e)}function xa({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let f=T(),{t:p}=Y(),m=b(),{state:g,openNew:_,openEdit:v,close:y}=Me({editKey:`block`,newKey:`new`}),[x,C]=c(null),[w,D]=c(null),[O,k]=c(null),A=l({queryKey:_a,refetchInterval:ya,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),j=g.mode!==`closed`,M=l({queryKey:va,enabled:j,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),N=()=>{A.refetch()},P=n(null),F=A.data;s(()=>{t===void 0||P.current===t||F?.find(e=>e.id===t&&V(e)===`code`)!==void 0&&(P.current=t,v(t),i?.(t))},[t,F,v,i]),s(()=>{a&&(C(null),_(),i?.(null),u?.())},[a,u,i,_]);let I=d({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{C(e.block),v(e.block.id),i?.(e.block.id),N()}}),L=d({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{C(e.block),v(e.block.id),i?.(e.block.id),N()}}),R=d({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:()=>{D(null),N()}}),B=d({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:N}),H=d({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:N}),ee=Rn((A.data??[]).filter(e=>V(e)===`code`)),te=A.data!==void 0&&ee.length===0,ne=I.isPending||L.isPending,re=I.error===null?L.error===null?null:ba(L.error):ba(I.error),ie=g.mode===`edit`?ee.find(e=>e.id===g.id)??(x!==null&&x.id===g.id?x:null):null,oe=g.mode===`new`||ie===null?null:Ln(ee,ie),se=r(()=>[{key:`name`,header:p(`build.scriptsTab.name`,`Name`),render:t=>{let n=Fn(t),r=pe(t.updatedAt,f);return e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:`truncate font-medium`,children:t.name}),o(U,{variant:In(n.tone),children:n.label}),o(U,{variant:`info`,children:t.placement}),r!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`common.edited`,{when:r})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:n.detail}),O===t.id&&e(`div`,{className:`mt-2 rounded border border-border`,children:[o(`div`,{className:`border-b border-border px-3 py-1.5 text-xs text-foreground-subtle`,children:o(X,{i18nKey:`common.logsOf`,values:{id:z(t.id)},components:{code:o(`code`,{})}})}),o(Ne,{addonId:z(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})},sortValue:e=>e.name,nowrap:!1},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:t=>{let n=B.isPending||R.isPending,r=H.isPending&&H.variables===t.id;return w===t.id?e(`div`,{className:`flex justify-end gap-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:p(`build.scriptsTab.deleteThisScript`,`Delete this script?`)}),o(q,{variant:`danger`,onClick:()=>R.mutate(t.id),disabled:n,children:p(`common.delete`,`Delete`)}),o(q,{variant:`ghost`,onClick:()=>D(null),children:p(`common.cancel`,`Cancel`)})]}):e(`div`,{className:`flex justify-end gap-1`,children:[o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),C(t),v(t.id),i?.(t.id)},title:p(`common.edit`,`Edit`),children:p(`common.edit`,`Edit`)}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),H.mutate(t.id)},disabled:n||r||!t.enabled,title:t.enabled?p(`build.scriptsTab.restart`,`Restart`):p(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:o(E,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),k(O===t.id?null:t.id)},title:p(`build.scriptsTab.logs`,`Logs`),children:o(S,{className:`h-4 w-4`})}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),B.mutate({blockId:t.id,enabled:!t.enabled})},disabled:n,title:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`),children:t.enabled?p(`common.disable`,`Disable`):p(`common.enable`,`Enable`)}),o(q,{variant:`ghost`,onClick:e=>{e.stopPropagation(),D(t.id)},title:p(`common.delete`,`Delete`),children:o(h,{className:`h-4 w-4`})})]})}}],[w,O,i,v,R,H.isPending,H.variables,B,p]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:A.data===void 0?``:zn(ee)}),A.error!=null&&o(fe,{title:p(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:ba(A.error),onRetry:N}),o(Le,{columns:se,rows:ee,rowKey:e=>e.id,pageSize:25,maxBodyHeight:ve,emptyMessage:te?p(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):A.data===void 0?p(`build.scriptsTab.loadingScripts`,`Loading scripts…`):p(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{C(e),v(e.id),i?.(e.id)}}),o(Oe,{open:j,onClose:()=>{I.reset(),L.reset(),H.reset(),C(null),y(),i?.(null)},title:oe===null?p(`build.scriptsTab.newScript`,`New script`):p(`build.scriptsTab.edit`,`Edit {{name}}`,{name:oe.name}),icon:ae,width:`xl`,testId:`script-editor-panel`,children:o(ha,{existing:oe,typeDefs:M.data,typeDefsLoading:M.isLoading,saving:ne,saveError:re,restarting:H.isPending,restartError:H.error===null?null:ba(H.error),onRestart:oe===null?void 0:()=>H.mutate(oe.id),onSave:e=>{let t=oe;t===null?I.mutate(e):L.mutate({blockId:t.id,block:e})},onCancel:()=>{I.reset(),L.reset(),H.reset(),C(null),y(),i?.(null)}})}),R.error!=null&&o(fe,{message:ba(R.error)}),B.error!=null&&o(fe,{message:ba(B.error)}),H.error!=null&&o(fe,{message:ba(H.error)})]})}var Sa=[`automations`,`scripts`,`custom-device`];function Ca(e){return e!==null&&Sa.some(t=>t===e)}var wa=[`coreBlocks`,`list`,`build-counts`],Ta=[`block`,`create`,`new`];function Ea(e){return e.filter(e=>V(e)===`code`).length}function Da(e){return e.filter(e=>et(e.code)).length}function Oa(e,t){return t===null?e:`${e} (${String(t)})`}function ka(){let{t}=Y(),n=b(),[r,i]=Ue(),a=r.get(`tab`),s=Ca(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:wa,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:Ea(u),f=u===void 0?null:Da(u),p=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),m=p.data?.state===`loaded`?p.data.views.length:null,h=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===void 0?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},g=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`automations`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},_=e=>{i(t=>{let n=new URLSearchParams(t);return n.set(`tab`,`scripts`),n.delete(`create`),e===null?n.delete(`block`):n.set(`block`,e),n},{replace:!0})},y=()=>{i(e=>{if(s===`custom-device`){let e=new URLSearchParams(window.location.search);return e.set(`tab`,`custom-device`),e.delete(`block`),e.delete(`create`),e.set(`new`,`1`),e}let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},x=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},S=s===`automations`?`New automation`:s===`scripts`?`New script`:`New composition`,C=Ge(`/build`,{t,isAdmin:!0})??{icon:D,title:t(`nav.build`,`Build-your-self`)};return o(Ke,{icon:C.icon,title:C.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${C.title} sections`,fill:!0,actions:e(q,{type:`button`,onClick:y,"data-testid":`build-new`,children:[o(v,{className:`h-4 w-4`}),` `,S]}),sections:[{id:`automations`,label:Oa(`Automations`,f),ownedParams:Ta,content:o(Gn,{onOpenScripts:h,initialBlockId:s===`automations`?r.get(`block`)??void 0:void 0,onBlockIdChange:g,createRequested:s===`automations`&&c,onCreateConsumed:x})},{id:`scripts`,label:Oa(`Scripts`,d),ownedParams:Ta,content:o(xa,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:_,createRequested:s===`scripts`&&c,onCreateConsumed:x})},{id:`custom-device`,label:Oa(`Custom Device`,m),ownedParams:Ta,content:o(fr,{createRequested:s===`custom-device`&&c,onCreateConsumed:x})}]})}export{ka as BuildPage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,K as t,R as n,S as r,Y as i,et as a,x as o}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{bi as s,yi as c}from"./player-overlays-Dbv95cvz.js";import{nr as l,rr as u}from"./client-DvJxGh2F.js";import{h as d}from"./video-D7jv0spx.js";import{Gr as f,_a as p,_r as m,fr as h,ga as g,gr as _,mr as v,pr as y,va as b,vr as x,ya as S}from"./src-ByunGuTZ.js";import{t as C}from"./i18n-l_m6iBJW.js";import{t as w}from"./useTranslation-BJr-n0es.js";import{lr as T,ur as E}from"./index-BFjKpxae.js";import{t as D}from"./AdminPage-BBb_f0ke.js";a();var O=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function k(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function A(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function j(e){let t=e.getDay();return k(A(e,t===0?-6:1-t))}function M(e,t){if(t===`day`){let t=k(e);return{startMs:t.getTime(),endMs:A(t,1).getTime()}}if(t===`week`){let t=j(e);return{startMs:t.getTime(),endMs:A(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=j(n),a=A(j(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function N(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=j(e),n=A(t,6),r={month:`short`,day:`numeric`};return`${t.toLocaleDateString(void 0,r)} – ${n.toLocaleDateString(void 0,{...r,year:`numeric`})}`}return e.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}function P(e,t,n){return t===`day`?A(e,n):t===`week`?A(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function F(e,t){if(t===void 0)return e;let n=t.calendars[e.id];return n===void 0?e:{...e,visible:n.visible??e.visible,color:n.color??e.defaultColor}}function I(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function L(e){if(e.allDay===!0)return C.t(`systemPage.calendars.allDay`);let t=new Date(e.startMs),n=new Date(e.endMs),r={hour:`2-digit`,minute:`2-digit`};return`${t.toLocaleTimeString([],r)} – ${n.toLocaleTimeString([],r)}`}function R(e){let t=l(e),n=new Date(t.startMs),r=new Date(t.endMs),i={weekday:`short`,year:`numeric`,month:`short`,day:`numeric`};if(e.allDay===!0){let e=k(n),t=A(k(r),-1);return H(e,t)?C.t(`systemPage.calendars.dayAllDay`,{date:n.toLocaleDateString(void 0,i)}):C.t(`systemPage.calendars.rangeAllDay`,{from:n.toLocaleDateString(void 0,i),to:t.toLocaleDateString(void 0,i)})}let a={hour:`2-digit`,minute:`2-digit`};return H(n,r)?`${n.toLocaleDateString(void 0,i)} · ${n.toLocaleTimeString([],a)} – ${r.toLocaleTimeString([],a)}`:`${n.toLocaleString(void 0,{...i,...a})} – ${r.toLocaleString(void 0,{...i,...a})}`}function z({label:t,children:n}){return e(`div`,{className:`grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-sm`,children:[r(`dt`,{className:`text-foreground-subtle`,children:t}),r(`dd`,{className:`min-w-0 break-words text-foreground`,children:n})]})}function B({ev:t,calendarName:n,color:i,onClose:a}){let{t:o}=w();return r(h,{open:!0,onOpenChange:e=>!e&&a(),children:e(v,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(m,{children:e(`div`,{className:`flex min-w-0 items-start gap-2.5`,children:[r(`span`,{className:`mt-1.5 h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:i},"aria-hidden":!0}),r(x,{className:`min-w-0 break-words`,children:t.title})]})}),r(y,{children:e(`dl`,{className:`space-y-3`,children:[r(z,{label:o(`systemPage.calendars.when`,`When`),children:R(t)}),r(z,{label:o(`systemPage.calendars.calendar`,`Calendar`),children:n}),t.location!==void 0&&t.location.length>0?r(z,{label:o(`systemPage.calendars.location`,`Location`),children:t.location}):null,t.description!==void 0&&t.description.length>0?r(z,{label:o(`systemPage.calendars.description`,`Description`),children:r(`span`,{className:`whitespace-pre-wrap`,children:t.description})}):null]})}),r(_,{children:r(f,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`common.close`,`Close`)})})]})})}function V(e,t){return e.filter(e=>u(e,t))}function H(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function U({mode:e,onChange:t}){let{t:n}=w(),i=[{id:`month`,label:n(`systemPage.calendars.month`,`Month`)},{id:`week`,label:n(`systemPage.calendars.week`,`Week`)},{id:`day`,label:n(`systemPage.calendars.day`,`Day`)}];return r(`div`,{className:`inline-flex rounded-lg border border-border bg-surface p-0.5`,role:`group`,"aria-label":n(`systemPage.calendars.calendarView`,`Calendar view`),children:i.map(n=>r(`button`,{type:`button`,className:e===n.id?`rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground`:`rounded-md px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground`,"aria-pressed":e===n.id,onClick:()=>t(n.id),"data-testid":`calendars-view-${n.id}`,children:n.label},n.id))})}function W({calendars:t,onToggleVisible:n,onColorChange:i,busy:a}){let{t:o}=w();return e(`aside`,{className:`w-full shrink-0 space-y-2 lg:w-56 xl:w-64`,"data-testid":`calendars-legend`,children:[r(`h2`,{className:`text-xs font-medium text-foreground-subtle`,children:o(`systemPage.calendars.calendars`,`Calendars`)}),r(`ul`,{className:`space-y-1`,children:t.map(t=>e(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface`,children:[r(`input`,{type:`checkbox`,className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:t.visible,disabled:a,onChange:e=>n(t.id,e.target.checked),"aria-label":o(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${t.id}`}),r(`input`,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:t.color,disabled:a,onChange:e=>i(t.id,e.target.value.toUpperCase()),"aria-label":o(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:t.name}),"data-testid":`calendars-color-${t.id}`}),e(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`truncate text-sm font-medium ${t.visible?`text-foreground`:`text-foreground-subtle`}`,children:t.name}),e(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[I(t),t.enabled?``:` · ${o(`systemPage.calendars.unavailableAtSource`)}`]})]})]},t.id))})]})}function G({ev:t,color:n,compact:i,onSelect:a}){return r(`button`,{type:`button`,className:i?`block w-full truncate rounded px-1 py-0.5 text-left text-[10px] leading-tight text-white hover:brightness-110`:`block w-full rounded-md px-2 py-1.5 text-left text-xs text-white hover:brightness-110`,style:{backgroundColor:n},title:t.title,onClick:()=>a(t),"data-testid":`calendars-event-${t.id}`,children:i?t.title:e(o,{children:[r(`div`,{className:`font-medium`,children:t.title}),r(`div`,{className:`opacity-90`,children:L(t)})]})})}function K({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let{t:s}=w(),{startMs:c,endMs:l}=M(t,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=A(e,1))u.push(e);let d=t.getMonth();return e(`div`,{"data-testid":`calendars-month`,children:[r(`div`,{className:`mb-1 grid grid-cols-7 gap-px`,children:O.map(e=>r(`div`,{className:`px-1 py-1 text-center text-[11px] font-medium text-foreground-subtle`,children:e},e))}),r(`div`,{className:`grid grid-cols-7 gap-px overflow-hidden rounded-lg border border-border bg-border`,children:u.map(t=>{let c=k(t).getTime(),l=V(n,c),u=t.getMonth()!==d,f=H(t,a);return e(`div`,{className:`min-h-[5.5rem] bg-background p-1 ${u?`opacity-45`:``}`,children:[r(`div`,{className:f?`mb-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] font-semibold text-primary-foreground`:`mb-1 text-[11px] font-medium text-foreground-subtle`,children:t.getDate()}),e(`div`,{className:`space-y-0.5`,children:[l.slice(0,3).map(e=>r(G,{ev:e,color:i.get(e.calendarId)??`#64748B`,compact:!0,onSelect:o},e.id)),l.length>3?r(`div`,{className:`text-[10px] text-foreground-subtle`,children:s(`common.moreCount`,{count:l.length-3})}):null]})]},c)})})]})}function q({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let s=j(t);return r(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-7 sm:gap-px sm:overflow-hidden sm:rounded-lg sm:border sm:border-border sm:bg-border`,"data-testid":`calendars-week`,children:Array.from({length:7},(e,t)=>A(s,t)).map(t=>{let s=k(t).getTime(),c=V(n,s);return e(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[r(`div`,{className:H(t,a)?`mb-2 text-xs font-semibold text-primary`:`mb-2 text-xs font-medium text-foreground-subtle`,children:t.toLocaleDateString(void 0,{weekday:`short`,day:`numeric`})}),r(`div`,{className:`space-y-1`,children:c.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):c.map(e=>r(G,{ev:e,color:i.get(e.calendarId)??`#64748B`,onSelect:o},e.id))})]},s)})})}function J({anchor:t,events:n,colorById:i,calName:a,onSelectEvent:o}){let{t:s}=w(),c=V(n,k(t).getTime());return c.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-day-empty`,children:s(`systemPage.calendars.noEventsOnThisDay`,`No events on this day.`)}):r(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,"data-testid":`calendars-day`,children:c.map(t=>r(`li`,{children:e(`button`,{type:`button`,className:`flex w-full items-start gap-3 px-3 py-3 text-left hover:bg-surface`,onClick:()=>o(t),"data-testid":`calendars-event-${t.id}`,children:[r(`span`,{className:`mt-1 h-2.5 w-2.5 shrink-0 rounded-full`,style:{backgroundColor:i.get(t.calendarId)??`#64748B`}}),e(`div`,{className:`min-w-0`,children:[r(`div`,{className:`font-medium text-sm text-foreground`,children:t.title}),e(`div`,{className:`text-xs text-foreground-subtle`,children:[L(t),` · `,a.get(t.calendarId)??t.calendarId]}),t.location!==void 0&&t.location.length>0?r(`div`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.location}):null]})]})},t.id))})}function Y(){let{t:a}=w(),o=p(),l=g({}),u=S(),[f,m]=i(`month`),[h,_]=i(()=>k(new Date)),[v,y]=i(null),x=t(()=>k(new Date),[]),C=o.isSuccess,O=l.isSuccess&&l.data!==void 0?l.data:void 0,A=t(()=>!C||o.data===void 0?[]:o.data.map(e=>F(e,O)),[C,o.data,O]),j=t(()=>A.filter(e=>e.visible),[A]),I=t(()=>j.map(e=>e.id),[j]),L=t(()=>M(h,f),[h,f]),R=b({startMs:L.startMs,endMs:L.endMs,calendarIds:[...I]},{enabled:C&&I.length>0}),z=R.data??[],V=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.color);return e},[A]),H=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.name);return e},[A]),G=n((e,t)=>{u.mutateAsync({calendarId:e,visible:t}).then(()=>l.refetch())},[l,u]),Y=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&u.mutateAsync({calendarId:e,color:t}).then(()=>l.refetch())},[l,u]),X=n(()=>_(k(new Date)),[]),Z=n(()=>_(e=>P(e,f,-1)),[f]),ee=n(()=>_(e=>P(e,f,1)),[f]),Q=`inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border bg-surface text-foreground hover:bg-primary/5 disabled:opacity-50`,$;return $=o.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingCalendars`,`Loading calendars…`)}):o.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,o.error.message]}):A.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(T,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(E,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):I.length===0?e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:a(`systemPage.calendars.allCalendarsAreHiddenTurn`,`All calendars are hidden. Turn one on in the legend to see events.`)})]}):e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),e(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(U,{mode:f,onChange:m}),e(`div`,{className:`flex items-center gap-1`,children:[r(`button`,{type:`button`,className:Q,onClick:Z,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(s,{className:`h-4 w-4`})}),r(`button`,{type:`button`,className:`inline-flex items-center rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5`,onClick:X,"data-testid":`calendars-today`,children:a(`systemPage.calendars.today`,`Today`)}),r(`button`,{type:`button`,className:Q,onClick:ee,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(c,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:N(h,f)})]}),R.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingEvents`,`Loading events…`)}):R.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,R.error.message]}):f===`month`?r(K,{anchor:h,events:z,colorById:V,today:x,onSelectEvent:y}):f===`week`?r(q,{anchor:h,events:z,colorById:V,today:x,onSelectEvent:y}):r(J,{anchor:h,events:z,colorById:V,calName:H,onSelectEvent:y})]})]}),e(D,{icon:d,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[$,v===null?null:r(B,{ev:v,calendarName:H.get(v.calendarId)??v.calendarId,color:V.get(v.calendarId)??`#64748B`,onClose:()=>y(null)})]})}export{Y as CalendarsPage,Y as default};
|
|
1
|
+
import{C as e,K as t,R as n,S as r,Y as i,et as a,x as o}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{bi as s,yi as c}from"./player-overlays-Dbv95cvz.js";import{nr as l,rr as u}from"./client-DvJxGh2F.js";import{h as d}from"./video-D7jv0spx.js";import{Kr as f,_a as p,_r as m,ba as h,hr as g,mr as _,pr as v,va as y,vr as b,ya as x,yr as S}from"./src-DntJrWmU.js";import{t as C}from"./i18n-xhwARoF0.js";import{t as w}from"./useTranslation-BJr-n0es.js";import{lr as T,ur as E}from"./index-C3uCLHv0.js";import{t as D}from"./AdminPage-3JxWocN3.js";a();var O=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function k(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function A(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function j(e){let t=e.getDay();return k(A(e,t===0?-6:1-t))}function M(e,t){if(t===`day`){let t=k(e);return{startMs:t.getTime(),endMs:A(t,1).getTime()}}if(t===`week`){let t=j(e);return{startMs:t.getTime(),endMs:A(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=j(n),a=A(j(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function N(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=j(e),n=A(t,6),r={month:`short`,day:`numeric`};return`${t.toLocaleDateString(void 0,r)} – ${n.toLocaleDateString(void 0,{...r,year:`numeric`})}`}return e.toLocaleDateString(void 0,{month:`long`,year:`numeric`})}function P(e,t,n){return t===`day`?A(e,n):t===`week`?A(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function F(e,t){if(t===void 0)return e;let n=t.calendars[e.id];return n===void 0?e:{...e,visible:n.visible??e.visible,color:n.color??e.defaultColor}}function I(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function L(e){if(e.allDay===!0)return C.t(`systemPage.calendars.allDay`);let t=new Date(e.startMs),n=new Date(e.endMs),r={hour:`2-digit`,minute:`2-digit`};return`${t.toLocaleTimeString([],r)} – ${n.toLocaleTimeString([],r)}`}function R(e){let t=l(e),n=new Date(t.startMs),r=new Date(t.endMs),i={weekday:`short`,year:`numeric`,month:`short`,day:`numeric`};if(e.allDay===!0){let e=k(n),t=A(k(r),-1);return H(e,t)?C.t(`systemPage.calendars.dayAllDay`,{date:n.toLocaleDateString(void 0,i)}):C.t(`systemPage.calendars.rangeAllDay`,{from:n.toLocaleDateString(void 0,i),to:t.toLocaleDateString(void 0,i)})}let a={hour:`2-digit`,minute:`2-digit`};return H(n,r)?`${n.toLocaleDateString(void 0,i)} · ${n.toLocaleTimeString([],a)} – ${r.toLocaleTimeString([],a)}`:`${n.toLocaleString(void 0,{...i,...a})} – ${r.toLocaleString(void 0,{...i,...a})}`}function z({label:t,children:n}){return e(`div`,{className:`grid grid-cols-[7rem_minmax(0,1fr)] gap-x-3 gap-y-1 text-sm`,children:[r(`dt`,{className:`text-foreground-subtle`,children:t}),r(`dd`,{className:`min-w-0 break-words text-foreground`,children:n})]})}function B({ev:t,calendarName:n,color:i,onClose:a}){let{t:o}=w();return r(v,{open:!0,onOpenChange:e=>!e&&a(),children:e(g,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(b,{children:e(`div`,{className:`flex min-w-0 items-start gap-2.5`,children:[r(`span`,{className:`mt-1.5 h-3 w-3 shrink-0 rounded-full`,style:{backgroundColor:i},"aria-hidden":!0}),r(S,{className:`min-w-0 break-words`,children:t.title})]})}),r(_,{children:e(`dl`,{className:`space-y-3`,children:[r(z,{label:o(`systemPage.calendars.when`,`When`),children:R(t)}),r(z,{label:o(`systemPage.calendars.calendar`,`Calendar`),children:n}),t.location!==void 0&&t.location.length>0?r(z,{label:o(`systemPage.calendars.location`,`Location`),children:t.location}):null,t.description!==void 0&&t.description.length>0?r(z,{label:o(`systemPage.calendars.description`,`Description`),children:r(`span`,{className:`whitespace-pre-wrap`,children:t.description})}):null]})}),r(m,{children:r(f,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`common.close`,`Close`)})})]})})}function V(e,t){return e.filter(e=>u(e,t))}function H(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function U({mode:e,onChange:t}){let{t:n}=w(),i=[{id:`month`,label:n(`systemPage.calendars.month`,`Month`)},{id:`week`,label:n(`systemPage.calendars.week`,`Week`)},{id:`day`,label:n(`systemPage.calendars.day`,`Day`)}];return r(`div`,{className:`inline-flex rounded-lg border border-border bg-surface p-0.5`,role:`group`,"aria-label":n(`systemPage.calendars.calendarView`,`Calendar view`),children:i.map(n=>r(`button`,{type:`button`,className:e===n.id?`rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground`:`rounded-md px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground`,"aria-pressed":e===n.id,onClick:()=>t(n.id),"data-testid":`calendars-view-${n.id}`,children:n.label},n.id))})}function W({calendars:t,onToggleVisible:n,onColorChange:i,busy:a}){let{t:o}=w();return e(`aside`,{className:`w-full shrink-0 space-y-2 lg:w-56 xl:w-64`,"data-testid":`calendars-legend`,children:[r(`h2`,{className:`text-xs font-medium text-foreground-subtle`,children:o(`systemPage.calendars.calendars`,`Calendars`)}),r(`ul`,{className:`space-y-1`,children:t.map(t=>e(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface`,children:[r(`input`,{type:`checkbox`,className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:t.visible,disabled:a,onChange:e=>n(t.id,e.target.checked),"aria-label":o(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${t.id}`}),r(`input`,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:t.color,disabled:a,onChange:e=>i(t.id,e.target.value.toUpperCase()),"aria-label":o(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:t.name}),"data-testid":`calendars-color-${t.id}`}),e(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`truncate text-sm font-medium ${t.visible?`text-foreground`:`text-foreground-subtle`}`,children:t.name}),e(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[I(t),t.enabled?``:` · ${o(`systemPage.calendars.unavailableAtSource`)}`]})]})]},t.id))})]})}function G({ev:t,color:n,compact:i,onSelect:a}){return r(`button`,{type:`button`,className:i?`block w-full truncate rounded px-1 py-0.5 text-left text-[10px] leading-tight text-white hover:brightness-110`:`block w-full rounded-md px-2 py-1.5 text-left text-xs text-white hover:brightness-110`,style:{backgroundColor:n},title:t.title,onClick:()=>a(t),"data-testid":`calendars-event-${t.id}`,children:i?t.title:e(o,{children:[r(`div`,{className:`font-medium`,children:t.title}),r(`div`,{className:`opacity-90`,children:L(t)})]})})}function K({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let{t:s}=w(),{startMs:c,endMs:l}=M(t,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=A(e,1))u.push(e);let d=t.getMonth();return e(`div`,{"data-testid":`calendars-month`,children:[r(`div`,{className:`mb-1 grid grid-cols-7 gap-px`,children:O.map(e=>r(`div`,{className:`px-1 py-1 text-center text-[11px] font-medium text-foreground-subtle`,children:e},e))}),r(`div`,{className:`grid grid-cols-7 gap-px overflow-hidden rounded-lg border border-border bg-border`,children:u.map(t=>{let c=k(t).getTime(),l=V(n,c),u=t.getMonth()!==d,f=H(t,a);return e(`div`,{className:`min-h-[5.5rem] bg-background p-1 ${u?`opacity-45`:``}`,children:[r(`div`,{className:f?`mb-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[11px] font-semibold text-primary-foreground`:`mb-1 text-[11px] font-medium text-foreground-subtle`,children:t.getDate()}),e(`div`,{className:`space-y-0.5`,children:[l.slice(0,3).map(e=>r(G,{ev:e,color:i.get(e.calendarId)??`#64748B`,compact:!0,onSelect:o},e.id)),l.length>3?r(`div`,{className:`text-[10px] text-foreground-subtle`,children:s(`common.moreCount`,{count:l.length-3})}):null]})]},c)})})]})}function q({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let s=j(t);return r(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-7 sm:gap-px sm:overflow-hidden sm:rounded-lg sm:border sm:border-border sm:bg-border`,"data-testid":`calendars-week`,children:Array.from({length:7},(e,t)=>A(s,t)).map(t=>{let s=k(t).getTime(),c=V(n,s);return e(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[r(`div`,{className:H(t,a)?`mb-2 text-xs font-semibold text-primary`:`mb-2 text-xs font-medium text-foreground-subtle`,children:t.toLocaleDateString(void 0,{weekday:`short`,day:`numeric`})}),r(`div`,{className:`space-y-1`,children:c.length===0?r(`p`,{className:`text-[11px] text-foreground-subtle`,children:`—`}):c.map(e=>r(G,{ev:e,color:i.get(e.calendarId)??`#64748B`,onSelect:o},e.id))})]},s)})})}function J({anchor:t,events:n,colorById:i,calName:a,onSelectEvent:o}){let{t:s}=w(),c=V(n,k(t).getTime());return c.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-day-empty`,children:s(`systemPage.calendars.noEventsOnThisDay`,`No events on this day.`)}):r(`ul`,{className:`divide-y divide-border rounded-lg border border-border`,"data-testid":`calendars-day`,children:c.map(t=>r(`li`,{children:e(`button`,{type:`button`,className:`flex w-full items-start gap-3 px-3 py-3 text-left hover:bg-surface`,onClick:()=>o(t),"data-testid":`calendars-event-${t.id}`,children:[r(`span`,{className:`mt-1 h-2.5 w-2.5 shrink-0 rounded-full`,style:{backgroundColor:i.get(t.calendarId)??`#64748B`}}),e(`div`,{className:`min-w-0`,children:[r(`div`,{className:`font-medium text-sm text-foreground`,children:t.title}),e(`div`,{className:`text-xs text-foreground-subtle`,children:[L(t),` · `,a.get(t.calendarId)??t.calendarId]}),t.location!==void 0&&t.location.length>0?r(`div`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:t.location}):null]})]})},t.id))})}function Y(){let{t:a}=w(),o=y(),l=p({}),u=h(),[f,m]=i(`month`),[g,_]=i(()=>k(new Date)),[v,b]=i(null),S=t(()=>k(new Date),[]),C=o.isSuccess,O=l.isSuccess&&l.data!==void 0?l.data:void 0,A=t(()=>!C||o.data===void 0?[]:o.data.map(e=>F(e,O)),[C,o.data,O]),j=t(()=>A.filter(e=>e.visible),[A]),I=t(()=>j.map(e=>e.id),[j]),L=t(()=>M(g,f),[g,f]),R=x({startMs:L.startMs,endMs:L.endMs,calendarIds:[...I]},{enabled:C&&I.length>0}),z=R.data??[],V=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.color);return e},[A]),H=t(()=>{let e=new Map;for(let t of A)e.set(t.id,t.name);return e},[A]),G=n((e,t)=>{u.mutateAsync({calendarId:e,visible:t}).then(()=>l.refetch())},[l,u]),Y=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&u.mutateAsync({calendarId:e,color:t}).then(()=>l.refetch())},[l,u]),X=n(()=>_(k(new Date)),[]),Z=n(()=>_(e=>P(e,f,-1)),[f]),ee=n(()=>_(e=>P(e,f,1)),[f]),Q=`inline-flex h-8 w-8 items-center justify-center rounded-lg border border-border bg-surface text-foreground hover:bg-primary/5 disabled:opacity-50`,$;return $=o.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingCalendars`,`Loading calendars…`)}):o.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,o.error.message]}):A.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(T,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(E,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):I.length===0?e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:a(`systemPage.calendars.allCalendarsAreHiddenTurn`,`All calendars are hidden. Turn one on in the legend to see events.`)})]}):e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(W,{calendars:A,onToggleVisible:G,onColorChange:Y,busy:u.isPending}),e(`div`,{className:`min-w-0 flex-1 space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[r(U,{mode:f,onChange:m}),e(`div`,{className:`flex items-center gap-1`,children:[r(`button`,{type:`button`,className:Q,onClick:Z,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(s,{className:`h-4 w-4`})}),r(`button`,{type:`button`,className:`inline-flex items-center rounded-lg border border-border bg-surface px-2.5 py-1.5 text-xs font-medium text-foreground hover:bg-primary/5`,onClick:X,"data-testid":`calendars-today`,children:a(`systemPage.calendars.today`,`Today`)}),r(`button`,{type:`button`,className:Q,onClick:ee,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(c,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:N(g,f)})]}),R.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingEvents`,`Loading events…`)}):R.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,R.error.message]}):f===`month`?r(K,{anchor:g,events:z,colorById:V,today:S,onSelectEvent:b}):f===`week`?r(q,{anchor:g,events:z,colorById:V,today:S,onSelectEvent:b}):r(J,{anchor:g,events:z,colorById:V,calName:H,onSelectEvent:b})]})]}),e(D,{icon:d,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[$,v===null?null:r(B,{ev:v,calendarName:H.get(v.calendarId)??v.calendarId,color:V.get(v.calendarId)??`#64748B`,onClose:()=>b(null)})]})}export{Y as CalendarsPage,Y as default};
|