@camstack/addon-admin-ui 1.2.644 → 1.2.646

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.
Files changed (132) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/assets/Addons-XDq92kO2.js +5 -0
  3. package/dist/assets/{AdminPage-DBIlGQcg.js → AdminPage-Bdna98Ou.js} +1 -1
  4. package/dist/assets/AdminSectionedPage-BReYGJXb.js +1 -0
  5. package/dist/assets/AiProfiles-Bw8hGoO0.js +3 -0
  6. package/dist/assets/{BootstrapSettingsForm-B4JdtXuz.js → BootstrapSettingsForm-c18LdxYs.js} +1 -1
  7. package/dist/assets/Build-48zeU1Yw.js +40 -0
  8. package/dist/assets/{Calendars-C7qfbr7A.js → Calendars-B2Wez_3o.js} +1 -1
  9. package/dist/assets/{CameraGrids-mWpZKvQ5.js → CameraGrids-BpGte0K0.js} +1 -1
  10. package/dist/assets/Cluster-CAB19PAX.js +1 -0
  11. package/dist/assets/CompositionBlockEditor-BN5J817G.js +2 -0
  12. package/dist/assets/{CompositionEditorPage-D2-woXyS.js → CompositionEditorPage-7ta40LxI.js} +1 -1
  13. package/dist/assets/Data-C_ebBdlu.js +2 -0
  14. package/dist/assets/DeviceDetail-GEBcTe6R.js +2 -0
  15. package/dist/assets/{Devices-CWvTKpnT.js → Devices-C42wiSOq.js} +1 -1
  16. package/dist/assets/{EmbedDevicePage-CvbzEbvN.js → EmbedDevicePage-SFb5MyT-.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-MuC48n-_.js → EmbedPlayerPage-DUcN1y4L.js} +1 -1
  18. package/dist/assets/History-B1fPhKG2.js +1 -0
  19. package/dist/assets/Identity-Bp3HGCWd.js +1 -0
  20. package/dist/assets/InstancesTable-BGtfLCCP.js +1 -0
  21. package/dist/assets/IntegrationDetail-CMMQieRt.js +1 -0
  22. package/dist/assets/IntegrationWizard-BaM2i4NA.js +1 -0
  23. package/dist/assets/Integrations-Cx2N6swv.js +2 -0
  24. package/dist/assets/Integrations-GPlT8cKN.js +1 -0
  25. package/dist/assets/Library-Bz4-Eas4.js +1 -0
  26. package/dist/assets/Locations-DmfVYXMw.js +3 -0
  27. package/dist/assets/Logs-CIvaD3Yw.js +1 -0
  28. package/dist/assets/{MaskShapeCanvas-j1uA0PkL.js → MaskShapeCanvas-niZe5zHf.js} +1 -1
  29. package/dist/assets/{MotionZonesSettings-0iA5mYRg.js → MotionZonesSettings-Dsi2Uff2.js} +1 -1
  30. package/dist/assets/MyAccess-D7pNURUg.js +2 -0
  31. package/dist/assets/Network-B7ImKtCW.js +1 -0
  32. package/dist/assets/NodeAddonsSettingsPanel-B1FzoINc.js +2 -0
  33. package/dist/assets/Notifications-BHBA5V_j.js +1 -0
  34. package/dist/assets/Pipeline-DIMjhsfr.js +1 -0
  35. package/dist/assets/{PrivacyMaskSettings-BLOdiPL9.js → PrivacyMaskSettings-CwxOqudr.js} +1 -1
  36. package/dist/assets/Recordings-DULk3APi.js +1 -0
  37. package/dist/assets/{RemoteGrid-DdvsdB_y.js → RemoteGrid-B9MFH8gq.js} +1 -1
  38. package/dist/assets/{ScanSubnetEditor-BCfqLZIA.js → ScanSubnetEditor-ChB1ff9j.js} +1 -1
  39. package/dist/assets/{SceneMonitorEditor-Cy11U5pJ.js → SceneMonitorEditor-DjbQscIc.js} +1 -1
  40. package/dist/assets/SessionsList-GQ9o6e6I.js +2 -0
  41. package/dist/assets/{Showroom-CDNZCmQ9.js → Showroom-B4IQCR63.js} +1 -1
  42. package/dist/assets/StorageLocationsTable-51VLoqz4.js +1 -0
  43. package/dist/assets/{System-CKbbRmxa.js → System-DMGCcspI.js} +1 -1
  44. package/dist/assets/{Templates-BQW0A24V.js → Templates-DWije3Aq.js} +1 -1
  45. package/dist/assets/{Terminal-CflJDBLw.js → Terminal-D20GDY9B.js} +5 -5
  46. package/dist/assets/{TrainingProviders--io-U4Mx.js → TrainingProviders-BHjFCr-v.js} +1 -1
  47. package/dist/assets/{Viewer-z_gjByXA.js → Viewer-DBUCXKwT.js} +1 -1
  48. package/dist/assets/{__vite-browser-external-BCAtXlNQ.js → __vite-browser-external-B6QEsNSJ.js} +1 -1
  49. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CMJDSqwo.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CgTKovwO.js} +1 -1
  50. package/dist/assets/{action-draft-Dg61GkLS.js → action-draft-BGdFoh4X.js} +1 -1
  51. package/dist/assets/{ai-page.helpers-QIeUykiQ.js → ai-page.helpers-WItq2Zfb.js} +1 -1
  52. package/dist/assets/{assignment-candidates-CwKJ2Z54.js → assignment-candidates-BP248h74.js} +1 -1
  53. package/dist/assets/{authed-media-BkzUgfxS.js → authed-media-BbpEDtXm.js} +1 -1
  54. package/dist/assets/{board-model-K39WWIgs.js → board-model-v3Qi2ADW.js} +1 -1
  55. package/dist/assets/client-CqZcg6J1.js +1057 -0
  56. package/dist/assets/command-vocab-kJ1oxCcS.js +1 -0
  57. package/dist/assets/create-composition-fA2f0nzR.js +1 -0
  58. package/dist/assets/device-detail-9hSNMll_.js +1 -0
  59. package/dist/assets/{device-integration-icon-TWc3Gi9v.js → device-integration-icon-Cyu0nfTA.js} +1 -1
  60. package/dist/assets/device-picker-model-CtTFN_cS.js +1 -0
  61. package/dist/assets/{dist-B8qwp9-f.js → dist-C25WO9pF.js} +1 -1
  62. package/dist/assets/dist-CYAeZRwB.js +1057 -0
  63. package/dist/assets/{format-hVW7RBVv.js → format-D-8gnxE4.js} +1 -1
  64. package/dist/assets/{hostInit-CWx4j9gp.js → hostInit-Bi8yQqpB.js} +1 -1
  65. package/dist/assets/i18n-jsJQRNVP.js +1 -0
  66. package/dist/assets/icons-DMftZDY6.js +1 -0
  67. package/dist/assets/index-56F3KEmN.js +4 -0
  68. package/dist/assets/index-DcUA-A3F.css +2 -0
  69. package/dist/assets/{linked-devices-model-h00bTRRT.js → linked-devices-model-BHQYp9mv.js} +1 -1
  70. package/dist/assets/{mf-entry-bootstrap-0-58e92d28.js → mf-entry-bootstrap-0-3894ac98.js} +2 -2
  71. package/dist/assets/mount-CtTFN_cS.js +1 -0
  72. package/dist/assets/{notification-rule-status-B-P-wl_0.js → notification-rule-status-OMG9AAuW.js} +1 -1
  73. package/dist/assets/player-overlays-COha2Q7D.js +1 -0
  74. package/dist/assets/remoteEntry-D7QWxsvZ.js +1 -0
  75. package/dist/assets/src-COXDtqhI.js +253 -0
  76. package/dist/assets/step-inspector-model-B2KsfsAh.js +1 -0
  77. package/dist/assets/{use-scenes-feed-CpY0pBjC.js → use-scenes-feed-BUwlMJxG.js} +1 -1
  78. package/dist/assets/{use-stationary-objects-BACQuMo9.js → use-stationary-objects-BadkNxb8.js} +1 -1
  79. package/dist/assets/{useAdminDeviceRemoval-8_UQkuQg.js → useAdminDeviceRemoval-B63tTVbh.js} +1 -1
  80. package/dist/assets/useEventInvalidation-CtTFN_cS.js +1 -0
  81. package/dist/assets/{useNodeUrlSelection-gHQAfZml.js → useNodeUrlSelection-CWhY2Xjn.js} +1 -1
  82. package/dist/assets/useTemplateSave-BHO2U-WX.js +1 -0
  83. package/dist/assets/variable-Cy0obf0C.js +1 -0
  84. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-hv9stH43.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-BMXyrASR.js} +2 -2
  85. package/dist/index.html +9 -9
  86. package/dist/server/addon.js +715 -167
  87. package/package.json +2 -2
  88. package/dist/assets/Addons-ShOLWXd0.js +0 -5
  89. package/dist/assets/AdminSectionedPage-BZZVpePX.js +0 -1
  90. package/dist/assets/AiProfiles-0WnsACbl.js +0 -3
  91. package/dist/assets/Build-9NCzkPDG.js +0 -39
  92. package/dist/assets/Cluster-DZcoj2rP.js +0 -1
  93. package/dist/assets/CompositionBlockEditor-C76eQ7Js.js +0 -2
  94. package/dist/assets/Data-DKNCfvhH.js +0 -2
  95. package/dist/assets/DeviceDetail-DHep5JCp.js +0 -2
  96. package/dist/assets/History-EJImyfJF.js +0 -1
  97. package/dist/assets/Identity-Bp-Zr3O5.js +0 -1
  98. package/dist/assets/InstancesTable-CvfpkEKd.js +0 -1
  99. package/dist/assets/IntegrationDetail-D8rUMymg.js +0 -1
  100. package/dist/assets/IntegrationWizard-CUcCjYQD.js +0 -1
  101. package/dist/assets/Integrations-2NtF5fL7.js +0 -2
  102. package/dist/assets/Integrations-DsjUFK8h.js +0 -1
  103. package/dist/assets/Library-Dxr2Pajp.js +0 -1
  104. package/dist/assets/Locations-rnb6AjY3.js +0 -3
  105. package/dist/assets/Logs-CoJh-c0a.js +0 -1
  106. package/dist/assets/MyAccess-DHgBU4Se.js +0 -2
  107. package/dist/assets/Network-DzqpooQx.js +0 -1
  108. package/dist/assets/NodeAddonsSettingsPanel-CieUBerm.js +0 -2
  109. package/dist/assets/Notifications-DIrApxQt.js +0 -1
  110. package/dist/assets/Pipeline-CXIrhlea.js +0 -1
  111. package/dist/assets/Recordings-D_GHaGDS.js +0 -1
  112. package/dist/assets/SessionsList-CFVXs0eU.js +0 -2
  113. package/dist/assets/StorageLocationsTable-C2jWCBaP.js +0 -1
  114. package/dist/assets/client-B60QT14E.js +0 -951
  115. package/dist/assets/command-vocab-_m2oGZgY.js +0 -1
  116. package/dist/assets/create-composition-B7qf5-qP.js +0 -2
  117. package/dist/assets/device-detail-CJ8-lleI.js +0 -1
  118. package/dist/assets/device-picker-model-CsHVNi49.js +0 -1
  119. package/dist/assets/dist-DXms20e9.js +0 -951
  120. package/dist/assets/i18n-CvWKDmFM.js +0 -1
  121. package/dist/assets/icons-Di72eW9A.js +0 -1
  122. package/dist/assets/index-0ukvsxX5.css +0 -2
  123. package/dist/assets/index-CxPpnulu.js +0 -4
  124. package/dist/assets/mount-CsHVNi49.js +0 -1
  125. package/dist/assets/player-overlays-D-63t-DL.js +0 -1
  126. package/dist/assets/remoteEntry-Bz4Zdkwj.js +0 -1
  127. package/dist/assets/src-g2TJby3U.js +0 -230
  128. package/dist/assets/step-inspector-model-De5uJK-p.js +0 -1
  129. package/dist/assets/ungroup-BlQtUKBm.js +0 -1
  130. package/dist/assets/useEventInvalidation-CsHVNi49.js +0 -1
  131. package/dist/assets/useTemplateSave-DxkUWI5Q.js +0 -1
  132. package/dist/assets/variable-IcIR23WN.js +0 -1
@@ -0,0 +1,40 @@
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,k as d,o as f,t as p,x as m,z as h}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{$n as g,Ar as _,Br as v,Ca as y,Gr as b,Hi as x,Ia as S,Kt as C,Nn as w,Or as T,Pi as E,Qn as D,Xi as O,Yt as k,_a as A,ct as j,gt as M,ir as N,ka as P,ut as F,wt as I,zn as L}from"./player-overlays-COha2Q7D.js";import{$i as R,Ao as z,Bo as ee,Co as B,Do as V,Eo as H,Fo as te,Go as ne,Gt as re,Ha as U,Io as ie,Ka as ae,Lo as oe,Mo as se,No as ce,Oo as le,Po as ue,Pr as de,Ra as W,Ro as fe,So as pe,To as me,Uo as he,Vo as ge,Wa as _e,Xs as ve,Zi as ye,_o as be,bo as xe,do as Se,ea as Ce,fo as we,go as Te,jo as Ee,ko as De,la as Oe,lo as ke,ma as Ae,oo as je,po as Me,ps as Ne,so as Pe,uc as Fe,uo as Ie,vo as Le,wo as Re,xo as ze,yo as Be,zo as Ve}from"./client-CqZcg6J1.js";import{t as He}from"./chevron-down-CBb-F8DT.js";import{t as Ue}from"./boxes-k5PsZ3NR.js";import{c as We}from"./video-BV-3O_ZC.js";import{n as Ge,r as Ke,t as qe}from"./variable-Cy0obf0C.js";import{$d as G,$r as Je,Af as Ye,Ai as Xe,Au as Ze,Bd as Qe,Bt as $e,Cs as et,Fi as tt,Fu as nt,Ga as rt,Gr as it,H as at,Hn as ot,Hr as st,Ii as ct,Io as lt,Jr as ut,Ka as dt,Kr as ft,Ln as pt,Mi as mt,Mo as ht,Mu as gt,Nu as _t,Ou as vt,Pi as yt,Pt as bt,Pu as xt,Q as St,Qa as Ct,Ri as wt,S as Tt,Sn as Et,Ud as K,Un as Dt,Uo as Ot,Vd as q,Vn as kt,Wd as At,Wn as jt,Wr as Mt,Xa as Nt,Xr as Pt,Z as Ft,Zr as It,_ as Lt,_n as Rt,ar as zt,as as Bt,b as Vt,cr as Ht,eo as Ut,fi as Wt,h as Gt,hr as Kt,ii as qt,ji as Jt,ju as Yt,ku as Xt,ld as Zt,li as Qt,mf as $t,nf as en,no as tn,or as nn,pf as rn,pr as an,qa as on,qr as sn,rt as cn,sf as J,sr as ln,to as un,tu as dn,w as fn,wn as pn,zt as mn}from"./src-COXDtqhI.js";import{t as Y}from"./i18n-jsJQRNVP.js";import{t as X}from"./useTranslation-BJr-n0es.js";import{H as hn,Kr as gn,Qr as _n,Xr as vn,ct as yn,dt as bn,m as xn,p as Sn,qr as Cn,x as wn}from"./index-56F3KEmN.js";import{t as Tn}from"./AdminSectionedPage-BReYGJXb.js";import{n as En}from"./format-D-8gnxE4.js";import{C as Dn,Tt as On,a as kn,at as An,b as jn,g as Mn,i as Nn,lt as Pn,n as Fn,nt as In,o as Ln,r as Rn,w as zn,y as Bn}from"./CompositionBlockEditor-BN5J817G.js";import{a as Vn,c as Hn,i as Un,l as Wn,n as Gn,o as Kn,r as qn,s as Jn,t as Yn,u as Xn}from"./create-composition-fA2f0nzR.js";import{a as Zn,i as Qn,n as $n,o as er,r as tr,s as nr}from"./action-draft-BGdFoh4X.js";var rr=`const AUTOMATION_RECIPE =`,ir=`// EJECTED from the visual automation editor — this file is now hand-owned.
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 ar(e){return e.includes(rr)}function or(e){let t=e.indexOf(rr);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 sr(e){let t=or(e);if(t===null)return{ok:!1,reason:Y.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:Y.t(`helpers.recipeFromCode.badJson`,{detail:t})}}let r=pe.safeParse(n);if(!r.success){let e=r.error.issues[0];return{ok:!1,reason:e===void 0?Y.t(`helpers.recipeFromCode.schemaMismatch`):Y.t(`helpers.recipeFromCode.schemaMismatchAt`,{path:e.path.join(`.`),message:e.message})}}return{ok:!0,recipe:r.data}}function cr(e){let t=or(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)}${ir}${e.slice(i)}`}u();var lr=`when`;function ur(e){return e===void 0||e.trim()===``?null:e}function dr(e){let t=e.slice(e.lastIndexOf(`.`)+1),n=Number(t);return Number.isInteger(n)?n:0}function fr(e){return e===`ok`?`pass`:e===`error`||e===`failed-continued`||e===`timed-out`?`fail`:`idle`}function pr(e){return e.steps.map(e=>({index:dr(e.path),tone:fr(e.outcome),message:ur(e.message)}))}function mr(e){let t=e.trigger.outcome===`pass`?`pass`:`fail`,n=ur(e.trigger.reason),r=e.conditions.find(e=>e.path===lr);return t===`fail`||r===void 0?{tone:t,reason:n}:r.outcome===`fail`?{tone:`fail`,reason:ur(r.reason)??n}:{tone:r.outcome===`pass`?`pass`:`idle`,reason:n}}function hr(e,t){return e.outcome===`ran`?{tone:`pass`,reason:null}:e.outcome===`failed`||e.outcome===`aborted`?{tone:`fail`,reason:t.find(e=>e.tone===`fail`)?.message??null}:{tone:`idle`,reason:ur(e.verdict?.reason)}}function gr(e){let t=pr(e);return{when:mr(e),thenBlock:hr(e,t),steps:t}}function _r(e,t){return e===null?null:e.steps.find(e=>e.index===t)?.tone??`idle`}function vr(e){return e===null?{kind:`unknown`}:{kind:`value`,text:Array.isArray(e)?e.join(`, `):String(e)}}function yr(e){return{kind:e.kind,tone:fr(e.outcome),message:ur(e.message)}}function br(e){if(e===void 0)return null;if(e===`else`)return{kind:`else`};let t=Number(e.slice(e.lastIndexOf(`.`)+1));return Number.isInteger(t)?{kind:`branch`,index:t}:null}function xr(e,t){return t===void 0?null:e===void 0?t:`${e}.${t}`}function Sr(e){return{vars:Object.entries(e.trigger.vars).map(([e,t])=>({name:e,value:vr(t)})),conditions:e.conditions.map(e=>({path:e.path,depth:e.path.split(`.`).length-1,kind:e.kind,outcome:e.outcome,reason:ur(e.reason),subject:xr(e.cap,e.fieldPath),operator:e.operator??null,deviceId:e.deviceId??null,expected:e.expected===void 0?null:vr(e.expected),observed:e.observed===void 0?null:vr(e.observed),rawExpected:e.expected,rawObserved:e.observed})),steps:e.steps.map(e=>({index:dr(e.path),kind:e.kind,tone:fr(e.outcome),message:ur(e.message),args:Object.entries(e.args??{}).map(([e,t])=>({name:e,value:vr(t)})),devices:(e.devices??[]).map(e=>({deviceId:e.deviceId,tone:e.outcome===`ok`?`pass`:`fail`,message:ur(e.message)})),chose:br(e.branch),nested:(e.steps??[]).map(e=>({...yr(e),chose:br(e.branch),rounds:e.iterations??null,inner:(e.steps??[]).map(yr)})),rounds:e.iterations??null}))}}function Cr(e){let t=Sr(e);return{nodes:new Map(t.conditions.map(e=>[e.path,e])),triggerPath:e.trigger.path??null,vars:t.vars}}var wr=6;function Tr(e,t,n){if(typeof e!=`number`||t===void 0||n===void 0)return vr(e);let r=ne(e,t,n);return r===void 0?vr(e):{kind:`value`,text:`${String(Number(r.toPrecision(wr)))} ${n}`}}function Er(e){let t=e.steps.find(e=>e.outcome===`error`),n=t===void 0?ur(e.verdict?.reason)??ur(e.trigger.reason):ur(t.message);return{stepsRun:e.steps.filter(e=>e.outcome===`ok`).length,stepsTotal:e.steps.length,reason:n}}var Dr={ran:`success`,failed:`danger`,aborted:`danger`,"skipped-trigger":`neutral`,"skipped-conditions":`warning`,"skipped-cooldown":`neutral`,"skipped-overlap":`neutral`},Or={pass:`border-success/50 bg-success/10`,fail:`border-danger/50 bg-danger/10`,idle:`border-border bg-surface text-foreground-subtle`},kr={pass:`text-success`,fail:`text-danger`,idle:`text-foreground-subtle`};function Ar(){let{t:e}=X();return t=>{switch(t){case`ran`:return e(`flow.runs.outcomeRan`,`Ran`);case`failed`:return e(`flow.runs.outcomeFailed`,`Failed`);case`aborted`:return e(`flow.runs.outcomeAborted`,`Stopped`);case`skipped-trigger`:return e(`flow.runs.outcomeSkippedTrigger`,`Trigger not met`);case`skipped-conditions`:return e(`flow.runs.outcomeSkippedConditions`,`Skipped by conditions`);case`skipped-cooldown`:return e(`flow.runs.outcomeSkippedCooldown`,`Skipped by cooldown`);default:return e(`flow.runs.outcomeSkippedOverlap`,`Skipped by run mode`)}}}var jr={done:`success`,missed:`warning`,inactive:`neutral`,"condition-false":`neutral`,failed:`danger`,held:`success`,"gave-up":`danger`,overridden:`info`,"suspended-manual":`warning`};function Mr(){let{t:e}=X();return t=>{switch(t){case`done`:return e(`flow.runs.schedulerDone`,`Done`);case`missed`:return e(`flow.runs.schedulerMissed`,`Missed`);case`inactive`:return e(`flow.runs.schedulerInactive`,`Not active`);case`condition-false`:return e(`flow.runs.schedulerConditionFalse`,`Condition not met`);case`failed`:return e(`flow.runs.schedulerFailed`,`Failed`);case`held`:return e(`flow.runs.schedulerHeld`,`Held`);case`gave-up`:return e(`flow.runs.schedulerGaveUp`,`Gave up`);case`overridden`:return e(`flow.runs.schedulerOverridden`,`Changed by hand`);default:return e(`flow.runs.schedulerSuspendedManual`,`Paused by hand`)}}}var Nr=`max-h-64`;function Pr(){let e=$t(),t=rn();return e||t}function Fr({expanded:t,onToggle:n}){let{t:r}=X();return e(G,{variant:`unstyled`,type:`button`,"aria-expanded":t,"data-testid":`runs-toggle`,onClick:n,className:`flex w-full items-center gap-2 px-3 py-2 text-left text-xs text-foreground-muted hover:bg-surface-hover`,children:[o(en,{expanded:t}),o(`span`,{children:t?r(`flow.runs.hide`,`Hide runs`):r(`flow.runs.show`,`Show runs`)})]})}function Ir({run:t}){let{t:n}=X(),r=Ar(),i=Er(t);return e(`p`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 border-t border-border-subtle bg-primary/5 px-3 py-2 text-xs`,"data-testid":`run-summary`,children:[o(K,{variant:Dr[t.outcome],children:r(t.outcome)}),i.reason!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:i.reason}),i.stepsTotal>0&&o(`span`,{className:`text-foreground-subtle`,children:n(`flow.runs.stepsRan`,`{{run}} of {{total}} steps ran`,{run:i.stepsRun,total:i.stepsTotal})})]})}function Lr({traces:t,selectedId:n,onSelect:r}){let{t:i}=X(),a=Ar(),s=Mr(),l=Pr(),[u,d]=c(null),f=u??!l,p=t===void 0?[]:t.toReversed(),h=p.find(e=>e.runId===n)??null;return e(kt,{headingId:`runs-heading`,title:i(`flow.runs.title`,`Runs`),icon:v,children:[o(Fr,{expanded:f,onToggle:()=>d(!f)}),f?t===void 0?o(At,{className:`m-3 h-16`}):p.length===0?o(qt,{title:i(`flow.runs.emptyTitle`,`No runs yet`),description:i(`flow.runs.emptyDescription`,`Each run appears here with what it decided.`)}):e(m,{children:[o(`ul`,{className:`${Nr} divide-y divide-border-subtle overflow-y-auto`,"data-testid":`runs-panel`,children:p.map(t=>{let i=t.runId===n;return o(`li`,{children:e(G,{variant:`unstyled`,type:`button`,"aria-pressed":i,onClick:()=>r(i?null:t.runId),className:`flex w-full flex-col gap-1 px-3 py-2 text-left hover:bg-surface-hover ${i?`bg-primary/10`:``}`,children:[e(`span`,{className:`flex flex-wrap items-center gap-2`,children:[t.scheduler===void 0?o(K,{variant:Dr[t.outcome],children:a(t.outcome)}):o(K,{variant:jr[t.scheduler],children:s(t.scheduler)}),t.repeat>1&&o(K,{variant:`neutral`,style:`outline`,children:`x${String(t.repeat)}`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:En(t.lastAt)})]}),o(`span`,{className:`truncate text-sm text-foreground`,children:t.trigger.reason})]})},t.runId)})}),h!==null&&o(Ir,{run:h}),o(`p`,{className:`border-t border-border-subtle px-3 py-2 text-xs text-foreground-subtle`,children:i(`flow.runs.hint`,`Select a run to colour the blocks: green passed, red failed, grey not evaluated.`)})]}):h!==null&&o(Ir,{run:h})]})}function Rr(e){return Or[e]}var zr={pass:`border-success/50`,fail:`border-danger/50`,idle:`border-border`};function Br(e){return zr[e]}function Vr({step:t,title:n,hint:r,trace:i,children:a}){return e(`section`,{className:`rounded-lg border p-3 ${i===null?`border-border bg-surface`:Or[i.tone]}`,"data-testid":`block-${t}`,children:[e(`div`,{className:`mb-2 flex flex-wrap items-baseline gap-2`,children:[o(`h4`,{className:`text-sm font-semibold uppercase tracking-wide`,children:n}),r!==void 0&&o(`span`,{className:`text-xs text-foreground-subtle`,children:r})]}),i!==null&&i.reason!==null&&o(`p`,{className:`mb-2 text-xs font-medium ${kr[i.tone]}`,children:i.reason}),o(`div`,{className:`space-y-2`,children:a})]})}var Hr=[`count`,`while`,`until`,`forEach`],Ur=2,Wr=10,Gr={kind:`all`,children:[]};function Kr(e){return e===`count`||e===`while`||e===`until`||e===`forEach`}function qr(e,t){return Number.isFinite(e)?Math.min(t,Math.max(1,Math.round(e))):1}function Jr(e){return qr(e,20)}function Yr(e){return qr(e,50)}function Xr(e){switch(e){case`count`:return{by:e,count:Ur};case`while`:case`until`:return{by:e,when:Gr,maxIterations:Wr};case`forEach`:return{by:e,target:{kind:`devices`,ids:[]}}}}function Zr(e,t){if(e.by!==`while`&&e.by!==`until`)return e;let{waitS:n,...r}=e;return t===null?r:{...r,waitS:qr(t,Re)}}function Qr(){return{kind:`repeat`,loop:Xr(`count`),steps:[]}}var $r=[`s`,`min`,`h`],ei={s:1,min:60,h:3600};function ti(e){return e===`s`||e===`min`||e===`h`}function ni(e){return e%ei.h===0?{value:e/ei.h,unit:`h`}:e%ei.min===0?{value:e/ei.min,unit:`min`}:{value:e,unit:`s`}}function ri(e,t){let n=Math.round(e*ei[t]);return Number.isFinite(n)?Math.min(Math.max(n,1),me):1}function ii(){return{kind:`wait-until`,when:{kind:`all`,children:[]},timeoutS:600,onTimeout:`continue`}}var ai=[`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`contains`,`in`];function oi(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 ai}}function si(e){switch(e){case`eq`:return Y.t(`helpers.recipeParts.op_eq`);case`ne`:return Y.t(`helpers.recipeParts.op_ne`);case`gt`:return Y.t(`helpers.recipeParts.op_gt`);case`gte`:return Y.t(`helpers.recipeParts.op_gte`);case`lt`:return Y.t(`helpers.recipeParts.op_lt`);case`lte`:return Y.t(`helpers.recipeParts.op_lte`);case`contains`:return Y.t(`helpers.recipeParts.op_contains`);default:return Y.t(`helpers.recipeParts.op_in`)}}function ci(e){return oi(e).map(e=>({value:e,label:si(e)}))}je.filter(e=>Pe(e).role===`event`),je.filter(e=>Pe(e).role===`state`);function li(e){return Y.t(`${Pe(e).i18nKey}.label`)}function ui(e){return Y.t(`${Pe(e).i18nKey}.description`)}function di(e){return Y.t(`${Pe(e).i18nKey}.example`)}var fi={when:{kind:`all`,children:[]},actions:[]};function pi(e){return ke(e)}function mi(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
+ `};case`action`:return{kind:e,actionId:``};case`stop`:return{kind:e,reason:``,outcome:`ok`};case`set`:return{kind:e,vars:{}};case`wait-until`:return ii();case`parallel`:return{kind:e,steps:[]};case`repeat`:return Qr();case`choose`:return{kind:e,branches:[{if:{kind:`all`,children:[]},steps:[]}]};default:return{kind:`cap`,deviceId:0,cap:``,method:``}}}function Z(e,t,n){return e.map((e,r)=>r===t?n:e)}function hi(e,t){return e.filter((e,n)=>n!==t)}function gi(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=hi(e,t);return[...a.slice(0,i),r,...a.slice(i)]}function _i(e,t){return{...e,actions:[...t]}}var vi={pass:`success`,fail:`danger`,"not-evaluated":`neutral`},yi={pass:`success`,fail:`danger`,idle:`neutral`};function bi({value:e}){let{t}=X();return e.kind===`unknown`?o(`span`,{className:`italic text-foreground-subtle`,"data-testid":`trace-value-unknown`,children:t(`flow.runs.unknownValue`,`unknown`)}):o(`span`,{className:`font-mono text-foreground`,children:e.text})}function xi(){let{t:e}=X();return t=>t===`pass`?e(`flow.runs.nodePass`,`Passed`):t===`fail`?e(`flow.runs.nodeFail`,`Failed`):e(`flow.runs.nodeNotEvaluated`,`Not evaluated`)}function Si(e){let t=le.safeParse(e);return t.success?si(t.data):e}function Ci({items:t,testId:n}){return t.length===0?null:o(`dl`,{className:`grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-0.5 text-[11px]`,"data-testid":n,children:t.map(t=>e(`div`,{className:`contents`,children:[o(`dt`,{className:`text-foreground-subtle`,children:t.name}),o(`dd`,{className:`break-words`,children:o(bi,{value:t.value})})]},t.name))})}function wi({node:t,vars:n=[],expected:r,observed:i}){let{t:a}=X(),s=xi(),c=t.subject===null?null:`${t.subject}${t.operator===null?``:` ${Si(t.operator)}`}`;return e(`div`,{className:`space-y-1 border-t border-border-subtle pt-2 text-xs`,"data-testid":`trace-result`,"data-outcome":t.outcome,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(K,{variant:vi[t.outcome],children:s(t.outcome)}),t.reason!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:t.reason})]}),c!==null&&o(`div`,{className:`text-[11px] text-foreground-subtle`,children:c}),(r!==null||i!==null)&&e(`div`,{className:`flex flex-wrap gap-x-3 text-[11px] text-foreground-subtle`,children:[r!==null&&e(`span`,{"data-testid":`trace-expected`,children:[a(`flow.runs.expected`,`Expected`),` `,o(bi,{value:r})]}),i!==null&&e(`span`,{"data-testid":`trace-observed`,children:[a(`flow.runs.observed`,`Observed`),` `,o(bi,{value:i})]})]}),o(Ci,{testId:`trace-vars`,items:n})]})}function Ti({step:t,deviceName:n}){let{t:r}=X(),i=t.tone===`pass`?r(`flow.runs.stepOk`,`OK`):t.tone===`fail`?r(`flow.runs.stepError`,`Error`):r(`flow.runs.stepNotRun`,`Not run`);return e(`div`,{className:`space-y-1 border-t border-border-subtle pt-2 text-xs`,"data-testid":`step-result`,"data-tone":t.tone,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(K,{variant:yi[t.tone],children:i}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground`,children:t.message})]}),t.chose!==null&&o(`div`,{className:`text-foreground-subtle`,"data-testid":`step-chose`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.nested.length>0&&o(`div`,{className:`text-foreground-subtle`,"data-testid":`step-last-round`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})}),t.nested.length>0&&o(`ol`,{className:`space-y-0.5 text-[11px]`,"data-testid":`step-nested`,children:t.nested.map((t,n)=>e(`li`,{className:`space-y-0.5`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{variant:yi[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message}),t.chose!==null&&o(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-chose-${String(n)}`,children:t.chose.kind===`else`?r(`flow.runs.choseElse`,`Ran the "otherwise" list`):r(`flow.runs.choseBranch`,`Ran branch {{n}}`,{n:t.chose.index+1})}),t.rounds!==null&&t.inner.length>0&&o(`span`,{className:`text-foreground-subtle`,"data-testid":`nested-rounds-${String(n)}`,children:r(`flow.runs.lastRound`,`The last of {{n}} rounds:`,{n:t.rounds})})]}),t.inner.length>0&&o(`ol`,{className:`space-y-0.5 border-l border-border-subtle pl-2`,"data-testid":`nested-inner-${String(n)}`,children:t.inner.map((t,n)=>e(`li`,{className:`flex flex-wrap items-center gap-2`,children:[e(K,{variant:yi[t.tone],children:[String(n+1),` · `,t.kind]}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},String(n)))})]},String(n)))}),o(Ci,{testId:`step-args`,items:t.args}),t.devices.length>0&&o(`ul`,{className:`space-y-0.5 text-[11px]`,"data-testid":`step-devices`,children:t.devices.map(t=>e(`li`,{className:`flex flex-wrap items-center gap-2`,children:[o(K,{variant:yi[t.tone],children:n(t.deviceId)}),t.message!==null&&o(`span`,{className:`min-w-0 break-words text-foreground-subtle`,children:t.message})]},t.deviceId))})]})}u();function Q({children:e}){return o(`span`,{className:`mb-1 block text-xs text-foreground-subtle`,children:e})}function Ei(e){let t=Vn(e.deviceId);if(t.data!==void 0)return qn(t.data,e.cap).find(t=>t.path===e.fieldPath)}function Di({value:t,devices:n,onChange:r}){let{t:i}=X(),[a,s]=c(!1),l=n.find(e=>e.id===t.deviceId),u=t.deviceId===0?i(`automation.fieldPicker.pickAValue`,`Pick a device value…`):`${l?.name??`#${String(t.deviceId)}`}${t.cap===``?``:` · ${t.cap}.${t.fieldPath}`}`;return e(`div`,{className:`min-w-[14rem] max-w-full flex-[2]`,children:[o(Q,{children:i(`automation.fieldPicker.value`,`Device value`)}),e(G,{variant:`outline`,className:`w-full min-w-0 justify-between`,"data-testid":`field-picker-open`,onClick:()=>s(!0),children:[o(`span`,{className:`w-0 flex-1 truncate text-left`,children:u}),o(He,{className:`size-3.5 shrink-0`})]}),a&&o(Oi,{value:t,onCancel:()=>s(!1),onConfirm:e=>{s(!1),r(e)}})]})}function Oi({value:t,onCancel:n,onConfirm:r}){let{t:i}=X(),a=lt({projection:`slim`}),[s,l]=c(null),[u,d]=c(!1),[f,p]=c(t.cap===``?null:{cap:t.cap,path:t.fieldPath});!u&&a.status===`success`&&(d(!0),l(On(a.data).find(e=>e.id===t.deviceId)??null));let h=i(`automation.fieldPicker.title`,`Device value`);return o(St,{open:!0,onClose:n,title:h,width:`xl`,fill:!0,testId:`field-picker-dialog`,footer:e(m,{children:[o(G,{variant:`ghost`,onClick:n,children:i(`common.cancel`,`Cancel`)}),o(G,{disabled:s===null||f===null,"data-testid":`field-picker-confirm`,onClick:()=>{s===null||f===null||r({deviceId:s.id,cap:f.cap,fieldPath:f.path})},children:i(`automation.fieldPicker.use`,`Use this value`)})]}),children:o(An,{kind:`formula`,enabled:!0,fillHeight:!0,hostId:-1,destination:{cap:`automation`,targetId:`field`,title:h,pickerTargetKind:null},device:s,field:f,excludeTypes:Wn,onDeviceChange:l,onFieldChange:p})})}var ki=1e4;function Ai(e,t,n){let r=Object.fromEntries(Object.entries(e??{}).filter(([e])=>e!==t)),i=n===null?r:{...r,[t]:n};return Object.keys(i).length===0?void 0:i}function ji(e,t){return{kind:`action`,actionId:e.actionId,...t===void 0?{}:{variables:t}}}function Mi({step:t,onChange:n}){let{t:r}=X(),i=tt({},{refetchInterval:ki});if(i.data===void 0)return o(At,{className:`h-8 w-64`});let a=i.data.find(e=>e.id===t.actionId),s=t.actionId!==``&&a===void 0;return e(`div`,{className:`space-y-2`,"data-testid":`run-action-step`,children:[e(`label`,{className:`block max-w-sm`,children:[o(Q,{children:r(`automation.runAction.action`,`Action`)}),o(F,{value:t.actionId,onChange:e=>n({kind:`action`,actionId:e.target.value}),options:[{value:``,label:r(`automation.runAction.pick`,`Pick an action`)},...s?[{value:t.actionId,label:r(`automation.runAction.missing`,`Missing action ({{id}})`,{id:t.actionId})}]:[],...i.data.map(e=>({value:e.id,label:e.name}))]})]}),s&&o(`p`,{className:`text-xs text-danger`,children:r(`automation.runAction.missingHint`,`This action no longer exists. Pick another, or the step will fail.`)}),(a?.variables??[]).length>0&&o(`div`,{className:`flex flex-wrap items-end gap-3`,children:(a?.variables??[]).map(e=>o(Ni,{variable:e,value:t.variables?.[e.name],onChange:r=>n(ji(t,Ai(t.variables,e.name,r)))},e.name))})]})}function Ni({variable:t,value:n,onChange:r}){let{t:i}=X(),a=t.label??t.name,s=t.default===void 0?i(`automation.runAction.required`,`required`):i(`automation.runAction.defaultIs`,`default {{value}}`,{value:String(t.default)});if(t.type===`boolean`||t.type===`select`){let c=t.type===`boolean`?[{value:`true`,label:i(`common.yes`,`Yes`)},{value:`false`,label:i(`common.no`,`No`)}]:(t.options??[]).map(e=>({value:e,label:e}));return e(`label`,{className:`block`,children:[o(Q,{children:a}),o(Jn,{widthClass:`w-40`,value:n===void 0?``:String(n),onChange:e=>{e.target.value===``?r(null):r(t.type===`boolean`?e.target.value===`true`:e.target.value)},options:[{value:``,label:s},...c]})]})}return t.type===`number`?e(`label`,{className:`block`,children:[o(Q,{children:a}),o(Hn,{className:`w-40`,placeholder:s,value:typeof n==`number`?n:void 0,onValue:r})]}):e(`label`,{className:`block`,children:[o(Q,{children:a}),o(J,{className:`w-40`,placeholder:s,value:n===void 0?``:String(n),onChange:e=>r(e.target.value===``?null:e.target.value)})]})}function Pi({onMove:e,label:t,reason:n,testId:r,children:i}){let a=e===null?n:t;return o(`span`,{className:`inline-flex`,title:a,"data-testid":`${r}-wrap`,children:o(G,{variant:`ghost`,disabled:e===null,onClick:e??void 0,"aria-label":t,title:a,"data-testid":r,children:i})})}function Fi({move:t,texts:n}){let{t:r}=X(),i=n??{up:r(`automation.whenTree.moveUp`,`Move up`),down:r(`automation.whenTree.moveDown`,`Move down`),atFirst:r(`automation.whenTree.alreadyFirst`,`Already first in this block`),atLast:r(`automation.whenTree.alreadyLast`,`Already last in this block`)};return e(m,{children:[o(Pi,{onMove:t.up,label:i.up,reason:i.atFirst,testId:`move-up`,children:o(A,{className:`h-3.5 w-3.5`})}),o(Pi,{onMove:t.down,label:i.down,reason:i.atLast,testId:`move-down`,children:o(y,{className:`h-3.5 w-3.5`})})]})}var Ii=[`cap`,`action`,`wait`,`set`,`stop`],Li=[`cap`,`action`,`wait`];function Ri(e){return Bi(e)&&Li.includes(e.kind)}var zi={kind:`all`,children:[]};function Bi(e){return Ii.includes(e.kind)?!(`if`in e)&&!(`else`in e):!1}function Vi(){return{if:zi,steps:[]}}function Hi(e){return e.branches.length<6}function Ui(e){return Hi(e)?{...e,branches:[...e.branches,Vi()]}:e}function Wi(e){return e.branches.length>1}function Gi(e,t){return Wi(e)?{...e,branches:e.branches.filter((e,n)=>n!==t)}:e}function Ki(e,t,n){return{...e,branches:e.branches.map((e,r)=>r===t?n:e)}}function qi(e,t){let{else:n,...r}=e;return t===void 0?r:{...r,else:[...t]}}var Ji=[...Ii,`wait-until`,`choose`,`parallel`,`repeat`];function Yi(e){return e<2?Ji:Ii}function Xi(e){if(Bi(e))return!0;switch(e.kind){case`wait-until`:case`parallel`:return!0;case`repeat`:return e.steps.every(Bi);case`choose`:return e.branches.every(e=>e.steps.every(Bi))&&(e.else??[]).every(Bi);default:return!1}}var Zi=[`border-chart-series-a`,`border-chart-series-f`,`border-chart-series-b`,`border-chart-series-d`];function Qi(e,t){let n=Zi.length;return(e+1+t%(n-1))%n}function $i(e,t){let n=0;return e.map(e=>ce(e)?null:Qi(t,n++))}function ea(e){return Zi[e%Zi.length]??Zi[0]}function ta(e){let t=[],n=0;return z(e,e=>{se(e)&&(n+=1,e.id!==void 0&&t.push({id:e.id,ordinal:n,leaf:e}))}),t}function na(e){return Ee(e.when)?!0:e.actions.some(e=>H(e).some(e=>Ee(e.when)))}function ra(e){let t=1;for(;e.has(`t${t}`);)t+=1;return`t${t}`}function ia(e,t){if(ce(e)){if(!se(e)||e.id!==void 0)return e;let n=ra(t);return t.add(n),{...e,id:n}}if(e.kind===`not`){let n=ia(e.child,t);return n===e.child?e:{...e,child:n}}let n=e.children.map(e=>ia(e,t));return n.every((t,n)=>t===e.children[n])?e:{...e,children:n}}function aa(e){if(!na(e))return e;let t=new Set(ta(e.when).map(e=>e.id)),n=ia(e.when,t);return n===e.when?e:{...e,when:n}}function oa(e,t,n){let r=e.leafIds.includes(t)?e.leafIds.filter(e=>e!==t):[...e.leafIds,t];return{kind:`triggered-by`,leafIds:n.filter(e=>r.includes(e))}}function sa(e,t){return e.leafIds.filter(e=>!t.includes(e))}u();var ca=[],la=d(null);function ua({when:e,children:t}){let n=r(()=>ta(e),[e]);return o(la.Provider,{value:n,children:t})}function da(){return h(la)??ca}function fa(){return h(la)!==null}var pa=[`triggered-by`];function ma(e){return{label:li(e),description:ui(e),example:di(e)}}function ha({open:e,onOpenChange:t,mode:n,context:r,underNot:i,treeFull:a,onPick:s}){let{t:c}=X(),l=fa();return o(Lt,{open:e,onOpenChange:t,title:n===`add`?c(`automation.leafPicker.title`,`Add a row`):c(`automation.leafPicker.changeTitle`,`Change the row type`),context:r,underNot:i,treeFull:a,...l?{}:{hidden:pa},recentKey:`automation-${r}`,textsOf:ma,categoryLabelOf:e=>c(`automation.leafPicker.category.${e}`),reasonOf:e=>c(`automation.leafPicker.reason.${e}`),onPick:e=>{s(e),t(!1)}})}var ga=`none`;function _a(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<=0))return Math.round(t*1e3)}function va({hold:t,modes:n,onChange:r}){let{t:i}=X(),a={held:i(`automation.hold.held`,`held`),stable:i(`automation.hold.stable`,`stable`)},s=e=>{if(e===ga){r(void 0);return}let i=n.find(t=>t===e);if(i===void 0)return;let a=t?.ms??3e4;r(i===`stable`&&t?.tolerance!==void 0?{ms:a,mode:i,tolerance:t.tolerance}:{ms:a,mode:i})};return e(m,{children:[e(`label`,{className:`w-32`,children:[o(Q,{children:i(`automation.hold.label`,`For`)}),o(F,{value:t?.mode??ga,onChange:e=>s(e.target.value),options:[{value:ga,label:i(`automation.hold.none`,`no hold`)},...n.map(e=>({value:e,label:a[e]}))]})]}),t!==void 0&&e(`label`,{className:`w-24`,children:[o(Q,{children:i(`automation.hold.seconds`,`Seconds`)}),o(J,{type:`number`,min:1,value:String(t.ms/1e3),onChange:e=>{let n=_a(e.target.value);r(n===void 0?void 0:{...t,ms:n})}})]}),t?.mode===`stable`&&e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.hold.tolerance`,`± tolerance`)}),o(J,{type:`number`,min:0,step:`any`,value:t.tolerance===void 0?``:String(t.tolerance),placeholder:`0`,onChange:e=>{let n=e.target.value.trim(),i=n===``?NaN:Number(n),{tolerance:a,...o}=t;r(Number.isNaN(i)||i<0?o:{...o,tolerance:i})}})]})]})}function ya({value:t,field:n,deviceId:r,cap:i,onChange:a}){let{t:s}=X(),c=Ea(n,r,i);if(n?.kind===`boolean`)return o(F,{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(F,{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(J,{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(J,{value:String(t),placeholder:s(`common.valueWord`),onChange:e=>a(e.target.value)})}function ba({value:e,field:t,deviceId:n,cap:r,onChange:i}){let{t:a}=X(),s=Ea(t,n,r);return o(J,{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 xa(e){return typeof e==`object`&&!he(e)}function Sa(e){return he(e)?e.value:xa(e)?e[0]??``:e}function Ca(e){return he(e)?[e.value]:xa(e)?e:typeof e==`boolean`?[]:[e]}function wa(e){let t=e?.quantity;if(!(e?.kind!==`number`||t===void 0)&&!(!ve(t)||t===`none`||t===`device`))return Me(t).length>0?t:void 0}function Ta(e,t){if(!(e===void 0||e===`none`)){if(e!==`device`)return e;if(!(t===void 0||t===`device`||t===`none`))return t}}function Ea(e,t,n){let r=$e(),i=t??0,a=e?.kind===`number`&&e.quantity!==void 0,{data:o}=ht({deviceId:i},{enabled:a&&i>0}),s=o?.sourceInfo?.quantity,c=ve(s)?s:void 0,l=Ta(e?.quantity,c);if(l===void 0)return;let u=o?.display;return mn({quantity:l,display:u,capName:n,unitPreferences:r})}function Da({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Ei(a),c=ci(s?.kind),l=t.operator===`in`,u=wa(s),d=u===void 0?void 0:we(u),f=e=>{let{unit:n,...i}=t;r({...i,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})},p=e=>{let n=Oa(e,c),{unit:i,...a}=t;r({...n===`in`?a:t,operator:n,value:n===`in`?[...Ca(t.value)]:Sa(t.value)})};return e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(Di,{value:a,devices:n,onChange:f}),e(`label`,{className:`min-w-[8rem]`,children:[o(Q,{children:i(`automation.conditionRow.comparison`,`Comparison`)}),o(F,{value:t.operator,onChange:e=>p(e.target.value),options:c.map(e=>({value:e.value,label:e.label}))})]}),e(`label`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),l?o(ba,{value:Ca(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:[...e]})}):u!==void 0&&d!==void 0?o(Tt,{quantity:u,storedUnit:d,value:typeof t.value==`number`?t.value:void 0,unit:t.unit,"aria-label":i(`automation.conditionRow.value`,`Value`),onChange:e=>{let n=fn(e,d);r({...t,value:n.value,unit:n.unit})}}):o(ya,{value:Sa(t.value),field:s,deviceId:t.deviceId,cap:t.cap,onChange:e=>r({...t,value:e})})]}),o(va,{hold:t.for,modes:[`held`,`stable`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})]})}function Oa(e,t){return t.find(t=>t.value===e)?.value??`eq`}var ka=Object.values(Fe).sort((e,t)=>e.localeCompare(t));function Aa({leaf:t,onChange:n}){let{t:r}=X();return e(`label`,{className:`min-w-[14rem] flex-1`,children:[o(Q,{children:r(`automation.triggerEditor.cronExpression`,`Cron expression`)}),o(J,{value:t.cron,placeholder:`0 30 23 * * *`,onChange:e=>n({kind:`schedule`,cron:e.target.value})}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(gn,{i18nKey:`automation.triggerEditor.cronHint`,components:{code:o(`code`,{})}})})]})}function ja(){return o(`p`,{className:`text-xs text-foreground-subtle`,children:o(gn,{i18nKey:`automation.triggerEditor.manualHint`,components:{b:o(`strong`,{})}})})}function Ma(e,t){return{kind:`device-becomes`,deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath,...t.becomes===void 0?{}:{becomes:t.becomes},...t.operator===void 0||t.value===void 0?{}:{operator:t.operator,value:t.value},...t.hold===void 0?{}:{for:t.hold},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}}}function Na(e){return e.operator===void 0?e.becomes===void 0?`any`:`becomes`:e.operator}var Pa=[`any`,`becomes`,`gt`,`gte`,`lt`,`lte`,`between`,`outside`];function Fa(e){return e===`between`||e===`outside`}function Ia(e){if(e.trim()===``)return;let t=Number(e);return Number.isNaN(t)?void 0:t}function La(e){return typeof e==`number`?e:void 0}function Ra({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a={deviceId:t.deviceId,cap:t.cap,fieldPath:t.fieldPath},s=Ei(a),c=oe(t),l=Na(t),u=La(t.value),d=Array.isArray(t.value)?[t.value[0],t.value[1]]:[void 0,void 0],f={...t.becomes===void 0?{}:{becomes:t.becomes},...t.operator===void 0||t.value===void 0?{}:{operator:t.operator,value:t.value},...c===void 0?{}:{hold:c},...t.debounceMs===void 0?{}:{debounceMs:t.debounceMs}},{becomes:p,operator:h,value:g,..._}=f,v=e=>{if(e===`any`){r(Ma(a,_));return}if(e===`becomes`){r(Ma(a,{..._,becomes:``}));return}let t=ie.safeParse(e);t.success&&r(Ma(a,{..._,operator:t.data,value:Fa(t.data)?[0,0]:0}))},y={any:i(`automation.triggerEditor.anyChange`,`any change`),becomes:i(`automation.triggerEditor.becomesValue`,`becomes a value`),gt:i(`automation.triggerEditor.crossesAbove`,`rises above`),gte:i(`automation.triggerEditor.reachesAtLeast`,`reaches at least`),lt:i(`automation.triggerEditor.dropsBelow`,`drops below`),lte:i(`automation.triggerEditor.reachesAtMost`,`reaches at most`),between:i(`automation.triggerEditor.entersRange`,`enters the range`),outside:i(`automation.triggerEditor.leavesRange`,`leaves the range`),eq:i(`automation.triggerEditor.becomesValue`,`becomes a value`),ne:i(`automation.triggerEditor.stopsBeing`,`stops being`)};return e(m,{children:[o(Di,{value:a,devices:n,onChange:e=>r(Ma(e,f))}),e(`label`,{className:`min-w-[10rem]`,children:[o(Q,{children:i(`automation.triggerEditor.becomes`,`Becomes`)}),o(F,{value:l,onChange:e=>v(e.target.value),options:Pa.map(e=>({value:e,label:y[e]}))})]}),l===`becomes`&&t.becomes!==void 0&&e(`div`,{className:`min-w-[9rem] flex-1`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),o(ya,{value:t.becomes,field:s,deviceId:a.deviceId,cap:a.cap,onChange:e=>r(Ma(a,{...f,becomes:e}))})]}),t.operator!==void 0&&!Fa(l)&&e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.conditionRow.value`,`Value`)}),o(J,{type:`number`,step:`any`,value:u===void 0?``:String(u),onChange:e=>{let n=Ia(e.target.value);n!==void 0&&r(Ma(a,{...f,operator:t.operator,value:n}))}})]}),t.operator!==void 0&&Fa(l)&&[0,1].map(n=>e(`label`,{className:`w-24`,children:[o(Q,{children:n===0?i(`automation.triggerEditor.rangeFrom`,`From`):i(`automation.triggerEditor.rangeTo`,`To`)}),o(J,{type:`number`,step:`any`,value:d[n]===void 0?``:String(d[n]),onChange:e=>{let i=Ia(e.target.value);if(i===void 0)return;let o=[d[0]??0,d[1]??0];o[n]=i,r(Ma(a,{...f,operator:t.operator,value:o}))}})]},n)),o(va,{hold:c,modes:[`held`,`stable`],onChange:e=>{let{hold:t,...n}=f;r(Ma(a,e===void 0?n:{...n,hold:e}))}}),e(`label`,{className:`w-28`,children:[o(Q,{children:i(`automation.triggerEditor.debounceS`,`Debounce (s)`)}),o(J,{type:`number`,min:0,value:t.debounceMs===void 0?``:String(t.debounceMs/1e3),placeholder:`0`,onChange:e=>r(Ma(a,{...f,debounceMs:za(e.target.value)}))})]})]})}function za(e){if(e.trim()===``)return;let t=Number(e);if(!(Number.isNaN(t)||t<0))return Math.round(t*1e3)}function Ba({leaf:t,onChange:n}){let{t:r}=X();return e(m,{children:[e(`label`,{className:`min-w-[15rem] flex-1`,children:[o(Q,{children:r(`automation.triggerEditor.eventCategory`,`Event category`)}),o(F,{value:t.category,onChange:e=>n({kind:`device-event`,category:e.target.value,...t.deviceId===void 0?{}:{deviceId:t.deviceId}}),options:[{value:``,label:r(`automation.triggerEditor.selectAnEvent`,`Select an event…`)},...ka.map(e=>({value:e,label:e}))]})]}),e(`div`,{className:`min-w-[11rem] flex-1`,children:[o(Q,{children:r(`automation.triggerEditor.fromDevice`,`From device`)}),o(Xe,{pick:`device`,excludeTypes:Wn,recentKey:`build-targets`,value:t.deviceId===void 0?null:{deviceId:t.deviceId},placeholder:r(`automation.triggerEditor.anyDevice`,`Any device`),testId:`trigger-event-device`,onChange:e=>n({kind:`device-event`,category:t.category,...e===null?{}:{deviceId:e.deviceId}})})]})]})}function Va(e,t){let n=e.find(e=>e.id===t.deviceId);return{kind:`global`,sourceStableId:n?.stableId??``,...n?.addonId===void 0?{}:{addonId:n.addonId},cap:t.cap,fieldPath:t.fieldPath}}function Ha(e,t){if(t.addonId!==void 0)return e.find(e=>e.stableId===t.sourceStableId&&e.addonId===t.addonId)?.id??0;let n=e.filter(e=>e.stableId===t.sourceStableId);return n.length===1?n[0]?.id??0:0}var Ua={kind:`global`,sourceStableId:``,cap:``,fieldPath:``};function Wa({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=Object.entries(t.bindings),s=e=>{r({...t,bindings:e})};return e(`div`,{className:`space-y-2`,children:[e(`div`,{className:`block`,children:[o(Gt,{label:i(`automation.expressionLeafRow.expression`,`Expression`),value:t.expr,placeholder:i(`automation.expressionLeafRow.indoorOutdoor5`,`indoor - outdoor > 5`),bindings:Object.keys(t.bindings),onChange:e=>r({...t,expr:e})}),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(Ga,{alias:e,source:r,devices:n,onRename:n=>s(Ja(t.bindings,e,n)),onChange:n=>s({...t.bindings,[e]:n}),onRemove:()=>s(Ya(t.bindings,e))},e)),e(G,{variant:`ghost`,onClick:()=>s({...t.bindings,[qa(t.bindings)]:Ua}),children:[o(D,{className:`h-3.5 w-3.5`}),` `,i(`common.name`)]})]}),o(`div`,{className:`flex flex-wrap items-end gap-2`,children:o(va,{hold:t.for,modes:[`held`],onChange:e=>{let{for:n,...i}=t;r(e===void 0?i:{...i,for:e})}})})]})}function Ga({alias:t,source:n,devices:r,onRename:i,onChange:a,onRemove:s}){let{t:c}=X(),l=n.kind===`literal`,u=l?{deviceId:0,cap:``,fieldPath:``}:{deviceId:n.kind===`global`?Ha(r,n):0,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(Q,{children:c(`automation.expressionLeafRow.name`,`Name`)}),o(J,{value:t,placeholder:c(`automation.expressionLeafRow.aliasExample`),onChange:e=>i(e.target.value)})]}),e(`label`,{className:`w-36`,children:[o(Q,{children:c(`automation.expressionLeafRow.reads`,`Reads`)}),o(F,{value:l?`literal`:`global`,onChange:e=>a(e.target.value===`literal`?{kind:`literal`,value:``}:Ua),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(Q,{children:c(`automation.expressionLeafRow.constant`,`Constant`)}),o(J,{value:n.value===null?``:String(n.value),placeholder:`5`,onChange:e=>a({kind:`literal`,value:Ka(e.target.value)})})]}):o(Di,{value:u,devices:r,onChange:e=>a(Va(r,e))}),o(G,{variant:`ghost`,onClick:s,title:c(`automation.expressionLeafRow.removeThisName`,`Remove this name`),children:o(k,{className:`h-3.5 w-3.5`})})]})}function Ka(e){let t=e.trim();return t===`true`?!0:t===`false`?!1:t!==``&&!Number.isNaN(Number(t))?Number(t):e}function qa(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 Ja(e,t,n){let r={};for(let[i,a]of Object.entries(e))i===t?r[n]=a:r[i]=a;return r}function Ya(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}var Xa=`text-xs text-foreground-subtle`;function Za({children:e}){return o(`span`,{className:Xa,children:e})}function Qa(e,t){return e.includes(t)?e.filter(e=>e!==t):[...e,t]}function $a({selected:t,onChange:n}){let{t:r}=X();return e(`div`,{className:`space-y-1`,children:[o(Za,{children:r(`flow.scene.cameras`,`Cameras`)}),o(Xe,{multiple:!0,pick:`device`,noun:`camera`,fixedTypes:Xn,recentKey:`build-cameras`,value:It(t),testId:`scene-cameras`,onChange:e=>n(Pt(e))})]})}function eo({device:t,deviceId:n,selected:r,onToggle:i}){let a=Qe({deviceId:n});return a.data===void 0||a.data.length===0?null:e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(`span`,{className:Xa,children:t?.name??`#${String(n)}`}),a.data.map(e=>o(G,{size:`sm`,variant:r.includes(e.id)?`primary`:`outline`,"aria-pressed":r.includes(e.id),onClick:()=>i(e.id),children:e.name},e.id))]})}function to({devices:t,deviceIds:n,selected:r,onChange:i}){let{t:a}=X();if(n.length===0)return null;let s=e=>{let t=Qa(r,e);i(t.length===0?void 0:t)};return e(`div`,{className:`space-y-1`,children:[o(Za,{children:a(`flow.scene.zones`,`Zones`)}),o(`div`,{className:`space-y-2`,children:n.map(e=>o(eo,{device:t.find(t=>t.id===e),deviceId:e,selected:r,onToggle:s},e))}),o(`p`,{className:Xa,children:r.length===0?a(`flow.scene.wholeScene`,`None picked: the whole scene counts.`):a(`flow.scene.zonesPicked`,`Only these zones count.`)})]})}var no=[`animal`,`person`,`vehicle`,`package`,`other`];function ro(e){return no.find(t=>t===e)??`other`}function io(e){switch(e){case`animal`:return{macro:`animal`};case`person`:return{macro:`person`};case`vehicle`:return{macro:`vehicle`};case`package`:return{macro:`package`};default:return{macro:`other`,className:``}}}function ao(){let{t:e}=X();return t=>{switch(t){case`person`:return e(`flow.class.person`,`Person`);case`vehicle`:return e(`flow.class.vehicle`,`Vehicle`);case`animal`:return e(`flow.class.animal`,`Animal`);case`package`:return e(`flow.class.package`,`Package`);default:return e(`automation.whenTree.macroOther`,`Other class`)}}}function oo(e,t){let n={kind:`sub-class`,className:t};switch(e){case`animal`:return{macro:e,label:n};case`package`:return{macro:e,label:n};case`vehicle`:return{macro:e,label:n};default:return{macro:`person`}}}var so=[`automation`,`class-taxonomy`];function co(){let e=M();return re(l({queryKey:so,retry:!1,staleTime:1/0,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}).data?.taxonomy)}function lo(e,t,n){let r=n?.groups.find(t=>t.key===e),i=r===void 0?ge(e).filter(t=>t!==e).map(e=>({value:e,label:e})):r.options.filter(t=>t.value!==e).map(e=>({value:e.value,label:e.label}));return t!==void 0&&!i.some(e=>e.value===t)?[...i,{value:t,label:t}]:i}function uo({subject:e,onChange:t}){let{t:n}=X(),r=e.label?.kind===`sub-class`?e.label.className:void 0,i=co(),a=lo(e.macro,r,i);return a.length===0?null:o(F,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:r??``,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...a],onChange:n=>{let r=n.target.value;t(r===``?io(e.macro):oo(e.macro,r))}})}function fo({onChange:e,subject:t}){let{t:n}=X(),r=et(),i=t.macro===`person`?t.label:void 0,a=r.data??[],s=a.map(e=>({value:e.id,label:e.name}));return i!==void 0&&!a.some(e=>e.id===i.identityId)&&s.push({value:i.identityId,label:i.name}),o(F,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:i?.identityId??``,options:[{value:``,label:n(`automation.whenTree.anyPerson`,`Anyone`)},...s],onChange:t=>{let n=t.target.value,r=s.find(e=>e.value===n);e(n===``||r===void 0?{macro:`person`}:{macro:`person`,label:{kind:`identity`,identityId:n,name:r.label}})}})}var po=`plate:`,mo=`class:`,ho=200;function go({onChange:e,subject:t}){let{t:n}=X(),r=dn({includeCrops:!1,limit:ho}),i=t.macro===`vehicle`?t.label:void 0,a=i?.kind===`plate`?i.text:void 0,s=co(),c=i?.kind===`sub-class`?i.className:void 0,l=[...new Set((r.data??[]).map(e=>e.text))];a!==void 0&&!l.includes(a)&&l.push(a);let u=a===void 0?c===void 0?``:`${mo}${c}`:`${po}${a}`;return o(F,{"aria-label":n(`automation.whenTree.labelAria`,`Narrow to`),"data-testid":`subject-label`,value:u,options:[{value:``,label:n(`automation.whenTree.anyLabel`,`Any`)},...lo(`vehicle`,c,s).map(e=>({value:`${mo}${e.value}`,label:e.label})),...l.map(e=>({value:`${po}${e}`,label:n(`automation.whenTree.plateOption`,`Plate {{text}}`,{text:e})}))],onChange:t=>{let n=t.target.value;n.startsWith(po)?e({macro:`vehicle`,label:{kind:`plate`,text:n.slice(6)}}):n.startsWith(mo)?e({macro:`vehicle`,label:{kind:`sub-class`,className:n.slice(6)}}):e({macro:`vehicle`})}})}function _o({subject:t,classLabelsOnly:n,verb:r,onChange:i,onRemove:a}){let{t:s}=X(),c=ao(),l=t.macro===`other`?[]:ee[t.macro],u=l.some(e=>e.kind===`cap`&&e.label===`identity`),d=l.some(e=>e.kind===`cap`&&e.label===`plate`);return e(`div`,{className:`flex flex-wrap items-center gap-2`,"data-testid":`subject-row`,children:[o(`div`,{className:`w-36`,children:o(F,{"aria-label":s(`automation.whenTree.macroAria`,`Class`),"data-testid":`subject-macro`,value:t.macro,options:no.map(e=>({value:e,label:c(e)})),onChange:e=>{let n=ro(e.target.value);n!==t.macro&&i(io(n))}})}),o(`span`,{className:`text-sm text-foreground-muted`,children:r}),t.macro===`other`?o(J,{className:`w-40`,"aria-label":s(`automation.whenTree.className`,`Class name`),"data-testid":`subject-class-name`,placeholder:s(`automation.whenTree.classNamePlaceholder`,`Class name`),value:t.className,onChange:e=>i({macro:`other`,className:e.target.value})}):u&&!n?o(`div`,{className:`w-44`,children:o(fo,{subject:t,onChange:i})}):d&&!n?o(`div`,{className:`w-44`,children:o(go,{subject:t,onChange:i})}):!u&&o(`div`,{className:`w-44`,children:o(uo,{subject:t,onChange:i})}),a!==null&&o(G,{variant:`ghost`,onClick:a,title:s(`automation.whenTree.removeClass`,`Remove this class`),children:o(k,{className:`h-3.5 w-3.5`})})]})}function vo({subjects:t,optional:n,classLabelsOnly:r,verb:i,onChange:a}){let{t:s}=X(),c=n||t.length>1;return e(`div`,{className:`space-y-2`,"data-testid":`subject-picker`,children:[t.map((e,n)=>o(_o,{subject:e,classLabelsOnly:r,verb:n===0?i:s(`automation.whenTree.orSubject`,`or`),onChange:e=>a(t.map((t,r)=>r===n?e:t)),onRemove:c?()=>a(t.filter((e,t)=>t!==n)):null},`${e.macro}-${String(n)}`)),t.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:s(`flow.scene.anyClass`,`None picked: any class counts.`)}),e(G,{variant:`ghost`,size:`sm`,onClick:()=>a([...t,io(`person`)]),children:[o(D,{className:`h-3.5 w-3.5`}),` `,t.length===0?s(`automation.whenTree.onlySomeClasses`,`Only some classes`):s(`automation.whenTree.addClass`,`Add a class`)]})]})}var yo=100;function bo({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=Math.round((t.minScore??0)*yo),s=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{minScore:n,...i}=t;r(e<=0?i:{...i,minScore:e/yo})};return e(`div`,{className:`w-full space-y-3`,"data-testid":`detection-fields`,children:[o(vo,{subjects:t.subjects,optional:!1,classLabelsOnly:!1,verb:i(`automation.whenTree.detected`,`detected`),onChange:e=>r({...t,subjects:[...e]})}),o($a,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(to,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:s}),e(`div`,{className:`space-y-1`,children:[o(Za,{children:a===0?i(`flow.scene.minScoreAny`,`Minimum score: any`):i(`flow.scene.minScore`,`Minimum score: {{value}}`,{value:(a/yo).toFixed(2)})}),o(P,{min:0,max:yo,value:a,"aria-label":i(`flow.scene.minScoreAria`,`Minimum score`),className:`block w-full max-w-sm accent-primary`,onChange:e=>c(Number(e.target.value))})]})]})}function xo({leaf:t,devices:n,onChange:r}){let{t:i}=X();return e(`div`,{className:`w-full space-y-3`,"data-testid":`stationary-fields`,children:[o(vo,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.parked`,`object`),onChange:e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})}}),o($a,{selected:t.deviceIds,onChange:e=>r({...t,deviceIds:[...e]})}),o(to,{devices:n,deviceIds:t.deviceIds,selected:t.zones??[],onChange:e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})}}),o(at,{label:i(`flow.scene.firesWhen`,`Fires when it`),value:t.phase,onChange:e=>r({...t,phase:e}),options:[{value:`appeared`,label:i(`flow.scene.phaseAppeared`,`Stopped (parked)`)},{value:`departed`,label:i(`flow.scene.phaseDeparted`,`Left`)}]})]})}function So({leaf:t,onChange:n}){let{t:r}=X();return e(`div`,{className:`flex items-center gap-2`,"data-testid":`interval-fields`,children:[o(Za,{children:r(`flow.scene.every`,`Every`)}),o(Hn,{"aria-label":r(`flow.scene.intervalMinutes`,`Minutes`),className:`w-20`,value:t.minutes,onValue:e=>{e!==null&&n({kind:`interval`,minutes:Math.round(e)})}}),o(Za,{children:r(`flow.scene.minutes`,`minutes`)})]})}function Co({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=e=>{let{subjects:n,...i}=t;r(e.length===0?i:{...i,subjects:[...e]})},s=e=>{let{zones:n,...i}=t;r(e===void 0?i:{...i,zones:[...e]})},c=e=>{let{zones:n,...i}=t;r({...i,deviceId:e})};return e(`div`,{className:`space-y-3`,"data-testid":`stationary-present-fields`,children:[e(`div`,{className:`space-y-1`,children:[o(Za,{children:i(`flow.scene.parkedOn`,`An object is parked on`)}),o(Xe,{pick:`device`,noun:`camera`,fixedTypes:Xn,recentKey:`build-cameras`,clearable:!1,value:t.deviceId>0?{deviceId:t.deviceId}:null,testId:`stationary-present-camera`,onChange:e=>{e!==null&&e.deviceId!==t.deviceId&&c(e.deviceId)}})]}),o(vo,{subjects:t.subjects??[],optional:!0,classLabelsOnly:!0,verb:i(`automation.whenTree.isParked`,`is parked`),onChange:a}),e(`div`,{className:`flex items-center gap-2`,children:[o(Za,{children:i(`flow.scene.minCount`,`At least`)}),o(Hn,{"aria-label":i(`flow.scene.minCountAria`,`Minimum parked objects`),"data-testid":`stationary-present-min-count`,className:`w-20`,value:t.minCount??1,onValue:e=>{let{minCount:n,...i}=t;r(e===null||e<=1?i:{...i,minCount:Math.floor(e)})}}),o(Za,{children:i(`flow.scene.minCountUnit`,`parked objects`)})]}),o(to,{devices:n,deviceIds:t.deviceId>0?[t.deviceId]:[],selected:t.zones??[],onChange:s})]})}var wo=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],To=720,Eo=1440;function Do(){return{name:``,enabled:!0,priority:0,maxLateMs:Te,profiles:[Oo(`profile-1`,`Every day`)]}}function Oo(e,t){return{id:e,name:t,enabled:!0,days:[...wo],points:[]}}function ko(e,t,n){return{id:t,at:{kind:`clock`,hh:Math.floor(n/60),mm:n%60},mode:e,steps:[]}}function Ao(e,t){let n=t.length+1;for(;t.includes(`${e}-${String(n)}`);)n+=1;return`${e}-${String(n)}`}function jo(e){return e.location===null?null:{lat:e.location.latitude,lon:e.location.longitude,timeZone:e.timeZone}}function Mo(e,t){let n=new Intl.DateTimeFormat(`en-US`,{timeZone:t,hourCycle:`h23`,hour:`2-digit`,minute:`2-digit`}).formatToParts(new Date(e)),r=e=>Number(n.find(t=>t.type===e)?.value??0);return r(`hour`)*60+r(`minute`)}function No(e,t=Date.now()){return fe(t,e.timeZone)}function Po(e,t,n){let r=jo(t);if(r===null)return e.kind===`clock`?e.hh*60+e.mm:null;let i=Ve(e,n,r);return i===null?null:Mo(i,t.timeZone)}function Fo(e,t,n){return e.kind===`sun`?Po({...e,offsetMin:0},t,n):null}function Io(e,t,n){if(e.kind===`clock`)return{kind:`clock`,hh:Math.floor(t/60),mm:t%60};if(e.kind===`sun`&&n!==null){let r=Math.max(-720,Math.min(To,t-n));return{...e,offsetMin:r}}return e}function Lo(e){let t=/^([01]\d|2[0-3]):([0-5]\d)$/.exec(e);return t===null?null:{kind:`clock`,hh:Number(t[1]),mm:Number(t[2])}}function Ro(e,t){return`${String(e).padStart(2,`0`)}:${String(t).padStart(2,`0`)}`}function zo(e){return Ro(Math.floor(e/60),e%60)}function Bo(e,t,n){let r=e.flatMap(e=>{let r=Po(e.at,t,n);return r===null?[]:[{point:e,minute:r}]}).toSorted((e,t)=>e.minute-t.minute);return r.flatMap((e,t)=>{if(e.point.mode!==`hold`)return[];let n=r[t+1];return[{id:e.point.id,fromMinute:e.minute,toMinute:n===void 0?Eo:n.minute}]})}function Vo(e,t){let n=be.safeParse(e);if(!n.success)return{ok:!1,issues:n.error.issues.map(e=>({path:e.path.join(`.`),message:e.message}))};let r=Le(n.data,t);return r.ok?{ok:!0,input:n.data}:{ok:!1,issues:r.issues}}var Ho=[`mon`,`tue`,`wed`,`thu`,`fri`,`sat`,`sun`],Uo=[`sunrise`,`sunset`,`dawn`,`dusk`],Wo={from:{kind:`clock`,hh:22,mm:0},to:{kind:`clock`,hh:6,mm:0}};function Go(e,t){return{kind:`time-is`,...e===void 0?{}:{between:e},...t===void 0?{}:{days:[...t]}}}function Ko(e){return e.days??Ho}function qo(e,t){let n=Ko(e),r=n.includes(t)?n.filter(e=>e!==t):Ho.filter(e=>e===t||n.includes(e)),i=r.length===Ho.length;return Go(e.between,i&&e.between!==void 0?void 0:r)}function Jo(e,t){if(t){let t=e.days!==void 0&&e.days.length===Ho.length;return Go(e.between??Wo,t?void 0:e.days)}return Go(void 0,Ko(e))}function Yo(e,t,n){return Go({...e.between??Wo,[t]:n},e.days)}function Xo(e){return e===`sun`?{kind:`sun`,event:`sunset`,offsetMin:0}:{kind:`clock`,hh:12,mm:0}}function Zo(e){return e.kind===`date`?Xo(`clock`):e}function Qo(e){let t=e.between;return t===void 0||t.from.kind!==`clock`||t.to.kind!==`clock`?!1:t.to.hh*60+t.to.mm<=t.from.hh*60+t.from.mm}function $o(e,t){if(t===void 0)return null;let n=Be(e,t)[0];return n===void 0?null:`${n.path}: ${n.message}`}function es({label:t,testId:n,end:r,onChange:i}){let{t:a}=X(),s=e=>`${t}: ${e}`;return e(`div`,{role:`group`,"aria-label":t,"data-testid":n,children:[o(Q,{children:t}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(F,{wrapperClassName:`relative w-40`,"aria-label":t,value:r.kind,options:[{value:`clock`,label:a(`schedulers.point.clock`,`At a time`)},{value:`sun`,label:a(`schedulers.point.sun`,`At a sun event`)}],onChange:e=>{let t=e.target.value;(t===`clock`||t===`sun`)&&t!==r.kind&&i(Xo(t))}}),r.kind===`clock`&&o(J,{type:`time`,className:`w-28`,"aria-label":s(a(`schedulers.point.time`,`Time`)),value:Ro(r.hh,r.mm),onChange:e=>{let t=Lo(e.target.value);t!==null&&t.kind===`clock`&&i(t)}}),r.kind===`sun`&&e(m,{children:[o(F,{wrapperClassName:`relative w-40`,"aria-label":s(a(`schedulers.point.sunEvent`,`Sun event`)),value:r.event,options:Uo.map(e=>({value:e,label:a(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=Uo.find(t=>t===e.target.value);t!==void 0&&i({...r,event:t})}}),o(Hn,{"aria-label":s(a(`schedulers.point.offset`,`Offset (minutes, negative = before)`)),title:a(`schedulers.point.offset`,`Offset (minutes, negative = before)`),className:`w-20`,value:r.offsetMin,onValue:e=>{e!==null&&i({...r,offsetMin:Math.round(e)})}})]})]})]})}function ts({leaf:t,onChange:n}){let{t:r}=X(),i=t.between,a=Ko(t);return e(`div`,{className:`flex w-full flex-col gap-2`,"data-testid":`time-is-fields`,children:[e(`div`,{className:`flex flex-wrap items-end gap-x-4 gap-y-2`,children:[e(`label`,{children:[o(Q,{children:r(`automation.timeIs.window`,`Time of day`)}),o(F,{wrapperClassName:`relative w-40`,"aria-label":r(`automation.timeIs.window`,`Time of day`),value:i===void 0?`whole-day`:`between`,options:[{value:`between`,label:r(`automation.timeIs.between`,`Between two times`)},{value:`whole-day`,label:r(`automation.timeIs.wholeDay`,`The whole day`)}],onChange:e=>n(Jo(t,e.target.value===`between`))})]}),i!==void 0&&e(m,{children:[o(es,{label:r(`automation.timeIs.from`,`From`),testId:`time-is-from`,end:Zo(i.from),onChange:e=>n(Yo(t,`from`,e))}),o(es,{label:r(`automation.timeIs.to`,`To`),testId:`time-is-to`,end:Zo(i.to),onChange:e=>n(Yo(t,`to`,e))})]})]}),e(`div`,{children:[o(Q,{children:r(`schedulers.profile.days`,`Days`)}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":r(`schedulers.profile.days`,`Days`),children:Ho.map(e=>{let i=a.includes(e);return o(G,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,onClick:()=>n(qo(t,e)),children:r(`schedulers.day.${e}`,e)},e)})}),a.length===0&&o(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`time-is-no-days`,children:r(`automation.timeIs.noDays`,`Pick at least one day.`)}),Qo(t)&&o(`p`,{className:`mt-1 text-xs text-foreground-subtle`,"data-testid":`time-is-wraps`,children:r(`automation.timeIs.wraps`,`This window ends the next day. The days are the days it starts on.`)})]})]})}function ns(e,t){let n=e.leaf;if(n.kind!==`device-becomes`&&n.kind!==`device-event`)return;let r=t.find(e=>e.id===n.deviceId)?.name;return n.kind===`device-becomes`?r:r===void 0?n.category:`${n.category} · ${r}`}function rs({leaf:t,devices:n,onChange:r}){let{t:i}=X(),a=da(),s=a.map(e=>e.id),c=sa(t,s),l=i(`automation.triggeredBy.triggers`,`Started by`);return e(`div`,{children:[o(Q,{children:l}),a.length===0?o(`p`,{className:`text-xs text-warning`,"data-testid":`triggered-by-no-rows`,children:i(`automation.triggeredBy.noRows`,`This automation has no trigger row to choose. Add one to the rules first.`)}):o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":l,children:a.map(e=>{let i=t.leafIds.includes(e.id),a=ns(e,n);return o(G,{size:`sm`,variant:i?`primary`:`outline`,"aria-pressed":i,className:`h-auto min-h-8 whitespace-normal py-1 text-left`,onClick:()=>r(oa(t,e.id,s)),children:`${e.ordinal}. ${li(e.leaf.kind)}${a===void 0?``:` · ${a}`}`},e.id)})}),a.length>0&&t.leafIds.length===0&&o(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-none-picked`,children:i(`automation.triggeredBy.nonePicked`,`Pick at least one trigger.`)}),c.length>0&&o(`p`,{className:`mt-1 text-xs text-warning`,"data-testid":`triggered-by-missing`,children:i(`automation.triggeredBy.missing`,{count:c.length,defaultValue_one:`{{count}} chosen trigger no longer exists. Press a trigger to drop it.`,defaultValue_other:`{{count}} chosen triggers no longer exist. Press a trigger to drop them.`})})]})}function is(e){return e.kind===`all`||e.kind===`any`}function as(e){return[`when`,...e].join(`.`)}function os(e){let t=e.when;return is(t)?t:{kind:`all`,children:[t]}}function ss(e,t){return{...e,when:t}}function cs(e){return ss(e,os(e))}function ls(e,t){let[n,...r]=t;if(n===void 0)return e;if(e.kind===`not`)return n===0?ls(e.child,r):null;if(ce(e))return null;let i=e.children[n];return i===void 0?null:ls(i,r)}function us(e,t,n){let[r,...i]=t;if(r===void 0)return n(e);if(e.kind===`not`){if(r!==0)return e;let t=us(e.child,i,n);return t===null?null:{kind:`not`,child:t}}if(ce(e))return e;let a=e.children[r];if(a===void 0)return e;let o=us(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 ds(e,t,n){let r=os(e);return ss(e,us(r,t,n)??{kind:r.kind,children:[]})}function fs(e){return{kind:e,children:[pi(`device-is`)]}}function ps(e,t,n){return ds(e,t,e=>is(e)?{kind:e.kind,children:[...e.children,n]}:e)}function ms(e,t,n){return ds(e,t,()=>n)}function hs(e,t){return ds(e,t,()=>null)}function gs(e,t,n){return ds(e,t,e=>is(e)?{kind:n,children:e.children}:e)}function _s(e,t){return t.length===0?e:ds(e,t,e=>({kind:`not`,child:e}))}function vs(e,t){return ds(e,t,e=>e.kind===`not`?e.child:e)}function ys(e,t){if(e.kind===t)return e;if(e.kind===`device-is`&&t===`device-becomes`){let{deviceId:n,cap:r,fieldPath:i,operator:a,value:o}=e,s={kind:t,deviceId:n,cap:r,fieldPath:i};return a===`eq`&&!Array.isArray(o)&&typeof o!=`object`?{...s,becomes:o}:s}if(e.kind===`device-becomes`&&t===`device-is`){let{deviceId:n,cap:r,fieldPath:i,becomes:a}=e;return{kind:t,deviceId:n,cap:r,fieldPath:i,operator:`eq`,value:a??``}}let n=pi(t);return se(e)&&e.id!==void 0&&se(n)?{...n,id:e.id}:n}function bs(e){let t=os(e),n=t.children.length===0;return{depth:n?0:te(t),leaves:n?0:De(t),depthLimit:4,leafLimit:32}}function xs(e,t){let n=os(e),r=1,i=n;for(let e of t){let t=ls(i,[e]);if(t===null)break;r+=1,i=t}return r+2<=4}function Ss(e,t,n){let r=t[t.length-1];if(r===void 0)return e;let i=t.slice(0,-1),a=ls(os(e),i);if(a===null||!is(a))return e;let o=r+n;return o<0||o>=a.children.length?e:ds(e,i,()=>({kind:a.kind,children:gi(a.children,r,o)}))}function Cs(e,t,n){let r=as(t),i=as(n),a=e=>e===r||e.startsWith(`${r}.`)?i+e.slice(r.length):e===i||e.startsWith(`${i}.`)?r+e.slice(i.length):e;return new Set([...e].map(a))}function ws(e,t){return ce(e)?t(e.kind):e.kind===`not`?`NOT ${ws(e.child,t)}`:e.children.map(e=>Ts(e,t)).join(` · `)}function Ts(e,t){return is(e)?`${e.kind.toUpperCase()} (${ws(e,t)})`:ws(e,t)}u();function Es({leaf:t,devices:n,context:r,underNot:i,toneClass:a,result:s,onNegate:l,move:u,onChange:d,onRemove:f}){let{t:p}=X(),[m,h]=c(!1),g=se(t);return e(`div`,{className:`rounded border p-2 ${a}`,"data-testid":`when-row`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`div`,{className:`min-w-[13rem] max-w-xs flex-1`,children:[o(Q,{children:p(`automation.whenTree.rowType`,`Row type`)}),e(G,{variant:`outline`,"data-testid":`when-row-type`,className:`w-full justify-between`,onClick:()=>h(!0),title:p(`automation.leafPicker.changeType`,`Change type`),children:[o(`span`,{className:`truncate`,children:li(t.kind)}),o(`span`,{className:`text-foreground-subtle`,children:p(`automation.leafPicker.changeType`,`Change type`)})]}),o(ha,{open:m,onOpenChange:h,mode:`change`,context:r,underNot:i,treeFull:!1,onPick:e=>{e!==t.kind&&d(ys(t,e))}})]}),o(K,{variant:g?`info`:`neutral`,"data-testid":`when-row-nature`,children:g?p(`automation.whenTree.natureEvent`,`Event`):p(`automation.whenTree.natureState`,`State`)}),o(`span`,{className:`flex-1`}),u!==void 0&&o(Fi,{move:u}),l!==null&&o(G,{variant:`ghost`,onClick:l,title:p(`automation.whenTree.negateRow`,`Invert this row (NOT)`),children:`NOT`}),o(G,{variant:`ghost`,onClick:f,title:p(`automation.whenTree.removeRow`,`Remove this row`),children:o(k,{className:`h-3.5 w-3.5`})})]}),o(`div`,{className:`mt-2 flex flex-wrap items-end gap-2`,children:o(Ds,{leaf:t,devices:n,onChange:d})}),s!==void 0&&o(`div`,{className:`mt-2`,children:s})]})}function Ds({leaf:e,devices:t,onChange:n}){switch(e.kind){case`device-becomes`:return o(Ra,{leaf:e,devices:t,onChange:n});case`device-event`:return o(Ba,{leaf:e,onChange:n});case`schedule`:return o(Aa,{leaf:e,onChange:n});case`interval`:return o(So,{leaf:e,onChange:n});case`manual`:return o(ja,{});case`detection`:return o(bo,{leaf:e,devices:t,onChange:n});case`stationary`:return o(xo,{leaf:e,devices:t,onChange:n});case`device-is`:return o(Da,{leaf:e,devices:t,onChange:n});case`stationary-present`:return o(Co,{leaf:e,devices:t,onChange:n});case`expression`:return o(Wa,{leaf:e,devices:t,onChange:n});case`time-is`:return o(ts,{leaf:e,onChange:n});case`triggered-by`:return o(rs,{leaf:e,devices:t,onChange:n})}}u();function Os(e){return e===`any`?`any`:`all`}function ks(e){return e===`pass`?`pass`:e===`fail`?`fail`:`idle`}function As(e,t,n=!0){return e===void 0?t:n?Rr(ks(e)):Br(ks(e))}function js(e,t){return e.run?.nodes.get(as(t))}function Ms({recipe:t,devices:n,onChange:r,run:i=null,hideRule:a=!1,context:s=`trigger`}){let{t:l}=X(),u=os(t),d=bs(t),[f,p]=c(()=>new Set),m={leafContext:s,recipe:t,devices:n,run:i,onChange:r,reshape:e=>{p(new Set),r(e)},collapsed:f,toggleCollapsed:e=>{let t=as(e);p(e=>e.has(t)?new Set([...e].filter(e=>e!==t)):new Set([...e,t]))},moveControls:(e,n)=>{let i=e[e.length-1]??0,a=n=>()=>{let a=[...e.slice(0,-1),i+n];p(t=>Cs(t,e,a)),r(Ss(t,e,n))};return{up:i>0?a(-1):null,down:i<n-1?a(1):null}}},h=u.children.length===0;return e(`div`,{className:`space-y-2`,"data-testid":`when-tree`,children:[!a&&o(`p`,{className:`text-xs text-foreground-subtle`,children:l(`automation.whenTree.rule`,`An event starts a run when it happens and everything here is true at that moment. With only states, a run starts when they become true.`)}),o(Vs,{block:u,path:[],ctx:m,underNot:!1,rail:0,budgetText:l(`automation.whenTree.budget`,{depth:d.depth,depthLimit:d.depthLimit,leaves:d.leaves,leafLimit:d.leafLimit}),move:null,emptyHint:h&&!a?l(`automation.whenTree.empty`,`Add a row to say when this runs. Without one nothing can ever start this automation.`):null})]})}function Ns({node:e,path:t,ctx:n,underNot:r,move:i,rail:a}){return ce(e)?o(Ps,{leaf:e,path:t,ctx:n,underNot:r,move:i}):e.kind===`not`?o(Bs,{child:e.child,path:t,ctx:n,move:i,rail:a}):o(Vs,{block:e,path:t,ctx:n,underNot:r,move:i,rail:a,budgetText:null,emptyHint:null})}function Ps({leaf:e,path:t,ctx:n,underNot:r,move:i}){let a=js(n,t),s=n.run!==null&&n.run.triggerPath===as(t)?n.run.vars:void 0;return o(Es,{leaf:e,devices:n.devices,context:n.leafContext,underNot:r,toneClass:As(a?.outcome,`border-border`),result:a===void 0?void 0:o(Fs,{leaf:e,node:a,vars:s}),onNegate:r?null:()=>n.reshape(_s(n.recipe,t)),...i===null?{}:{move:i},onChange:e=>n.onChange(ms(n.recipe,t,e)),onRemove:()=>n.reshape(hs(n.recipe,t))})}function Fs({leaf:e,node:t,vars:n}){return e.kind===`device-is`&&e.unit!==void 0?o(Is,{leaf:e,node:t,vars:n}):o(wi,{node:t,vars:n,expected:t.expected,observed:t.observed})}function Is({leaf:e,node:t,vars:n}){let r=wa(Ei({deviceId:e.deviceId,cap:e.cap,fieldPath:e.fieldPath})),i=r===void 0?void 0:we(r),a=t=>t===void 0?null:Tr(t,i,e.unit);return o(wi,{node:t,vars:n,expected:a(t.rawExpected),observed:a(t.rawObserved)})}function Ls({node:e}){return e===void 0?null:o(wi,{node:e,expected:null,observed:null})}function Rs({expanded:e,onToggle:t}){let{t:n}=X(),r=e?n(`automation.whenTree.collapse`,`Collapse this block`):n(`automation.whenTree.expand`,`Expand this block`);return o(G,{variant:`ghost`,"aria-expanded":e,"aria-label":r,title:r,onClick:t,children:o(en,{expanded:e})})}function zs({node:e}){let{t}=X(),n=`${t(`automation.whenTree.rowCount`,{count:De(e)})} · ${ws(e,li)}`;return o(`p`,{"data-testid":`when-block-summary`,title:n,className:`break-words text-xs text-foreground-muted sm:truncate`,children:n})}function Bs({child:t,path:n,ctx:r,move:i,rail:a}){let{t:s}=X(),c=!r.collapsed.has(as(n));return e(`div`,{className:`space-y-1.5 rounded border p-2 ${As(js(r,n)?.outcome,`border-warning/40`,!1)}`,"data-testid":`when-not`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(Rs,{expanded:c,onToggle:()=>r.toggleCollapsed(n)}),o(K,{variant:`warning`,children:`NOT`}),o(`span`,{className:`text-xs text-foreground-subtle`,children:s(`automation.whenTree.notHint`,`True when what is below is not`)}),o(`span`,{className:`flex-1`}),i!==null&&o(Fi,{move:i}),e(G,{variant:`ghost`,onClick:()=>r.reshape(vs(r.recipe,n)),title:s(`automation.whenTree.removeNot`,`Remove the NOT, keeping what is inside`),children:[o(Ge,{className:`h-3.5 w-3.5`}),` `,s(`automation.whenTree.removeNotLabel`,`Remove NOT`)]})]}),o(Ls,{node:js(r,n)}),c?o(`div`,{className:`pl-3`,children:o(Ns,{node:t,path:[...n,0],ctx:r,underNot:!0,move:null,rail:a})}):o(zs,{node:t})]})}function Vs({block:t,path:n,ctx:r,underNot:i,move:a,rail:s,budgetText:l,emptyHint:u}){let{t:d}=X(),f=n.length===0,p=f||!r.collapsed.has(as(n)),m=xs(r.recipe,n),[h,g]=c(!1),_=$i(t.children,s),v=[{value:`all`,label:d(`automation.whenTree.allOf`,`All of (AND)`)},{value:`any`,label:d(`automation.whenTree.anyOf`,`Any of (OR)`)}];return e(`div`,{className:`space-y-2 rounded border p-2 ${As(js(r,n)?.outcome,`border-border`,!1)}`,"data-testid":`when-block`,"data-kind":t.kind,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[!f&&o(Rs,{expanded:p,onToggle:()=>r.toggleCollapsed(n)}),o(`div`,{className:`w-40`,children:o(F,{"aria-label":d(`automation.whenTree.blockKind`,`How the rows below combine`),"data-testid":`when-block-kind`,value:t.kind,options:v,onChange:e=>r.onChange(gs(r.recipe,n,Os(e.target.value)))})}),l!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:l}),o(`span`,{className:`flex-1`}),a!==null&&o(Fi,{move:a}),!f&&!i&&o(G,{variant:`ghost`,onClick:()=>r.reshape(_s(r.recipe,n)),title:d(`automation.whenTree.negateBlock`,`Invert this block (NOT)`),children:`NOT`}),!f&&o(G,{variant:`ghost`,onClick:()=>r.reshape(hs(r.recipe,n)),title:d(`automation.whenTree.removeBlock`,`Delete this block and everything in it`),children:o(k,{className:`h-3.5 w-3.5`})})]}),o(Ls,{node:js(r,n)}),u!==null&&o(`p`,{className:`text-xs text-foreground-subtle`,children:u}),!p&&o(zs,{node:t}),p&&t.children.length>0&&o(`div`,{className:`space-y-1.5 border-l-2 pl-3 ${ea(s)}`,"data-testid":`when-block-rail`,"data-rail":s,children:t.children.map((e,i)=>o(Ns,{node:e,path:[...n,i],ctx:r,underNot:!1,move:r.moveControls([...n,i],t.children.length),rail:_[i]??s},as([...n,i])))}),p&&e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{variant:`outline`,onClick:()=>g(!0),title:d(`automation.whenTree.addRowTitle`,`Add one row: an event or a state`),children:[o(D,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addRow`,`Add row`)]}),o(ha,{open:h,onOpenChange:g,mode:`add`,context:r.leafContext,underNot:i,treeFull:De(os(r.recipe))>=32,onPick:e=>r.onChange(ps(r.recipe,n,pi(e)))}),e(G,{variant:`outline`,disabled:!m,onClick:()=>r.onChange(ps(r.recipe,n,fs(t.kind===`all`?`any`:`all`))),title:m?d(`automation.whenTree.addBlockTitle`,`Add a nested block of rows`):d(`automation.whenTree.tooDeep`,`The rules nest at most {{max}} levels deep`,{max:bs(r.recipe).depthLimit}),children:[o(D,{className:`h-4 w-4`}),` `,d(`automation.whenTree.addBlock`,`Add block`)]})]})]})}var Hs={kind:`all`,children:[]};function Us(e){return e.kind===`wait`||e.kind===`cap`}function Ws(e){return!ce(e)&&e.kind!==`not`&&e.children.length===0?null:ue(e)}function Gs(e){let{if:t,else:n,...r}=e;return r}function Ks({when:t,devices:n,hint:r,onChange:i,children:a}){let{t:s}=X(),c=t===void 0?null:{when:t,actions:[]},l=t===void 0?null:Ws(t);return e(`div`,{className:`space-y-2 border-t border-border-subtle pt-2`,children:[o(an,{checked:t!==void 0,label:s(`automation.stepGuard.if`,`Only if…`),"aria-label":s(`automation.stepGuard.if`,`Only if…`),onCheckedChange:e=>i(e?Hs:void 0)}),c!==null&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:r}),o(Ms,{hideRule:!0,context:`guard`,recipe:c,devices:n,onChange:e=>i(e.when)}),l!==null&&o(q,{variant:`warning`,message:l}),a]})]})}function qs({step:t,devices:n,devicesState:r,variables:i,onChange:a}){let{t:s}=X();return e(Ks,{when:t.if,devices:n,hint:s(`automation.stepGuard.hint`,`Checked when this step is reached. If a state cannot be read, the step and its else are both skipped.`),onChange:e=>a(e===void 0?Gs(t):{...t,if:e}),children:[o(an,{checked:t.else!==void 0,label:s(`automation.stepGuard.else`,`Otherwise, run…`),"aria-label":s(`automation.stepGuard.else`,`Otherwise, run…`),onCheckedChange:e=>{if(e)a({...t,else:[]});else{let{else:e,...n}=t;a(n)}}}),t.else!==void 0&&o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(cc,{nested:!0,actions:t.else,devices:n,...r===void 0?{}:{devicesState:r},...i===void 0?{}:{variables:i},allowedKinds:[`cap`,`wait`],onChange:e=>a({...t,else:e.filter(Us)})})})]})}function Js({index:t,step:n,devices:r,devicesState:i,variables:a,depth:s=0,roundDevices:c,onChange:l}){let{t:u}=X(),d={nested:!0,flowControl:!0,devices:r,depth:s+1,allowedKinds:Yi(s+1),...c===void 0?{}:{roundDevices:c},...i===void 0?{}:{devicesState:i},...a===void 0?{}:{variables:a}};return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.choose.hint`,`Read top to bottom: the first branch whose condition is true runs, and only that one. If a condition cannot be read, nothing runs.`)}),n.branches.map((i,a)=>{let s={when:i.if,actions:[]},c=Ws(i.if);return e(`div`,{className:`space-y-2 border-l-2 border-border-subtle pl-3`,"data-testid":`choose-branch-${String(t)}-${String(a)}`,children:[e(`div`,{className:`flex items-center gap-2`,children:[o(Q,{children:a===0?u(`automation.choose.if`,`If`):u(`automation.choose.elseIf`,`Otherwise, if`)}),o(G,{variant:`ghost`,className:`ml-auto`,disabled:!Wi(n),"data-testid":`choose-remove-${String(t)}-${String(a)}`,onClick:()=>l(Gi(n,a)),title:Wi(n)?u(`automation.choose.removeBranch`,`Remove this branch`):u(`automation.choose.lastBranch`,`A choose keeps at least one branch`),children:o(k,{className:`h-3.5 w-3.5`})})]}),o(Ms,{hideRule:!0,context:`guard`,recipe:s,devices:r,onChange:e=>l(Ki(n,a,{...i,if:e.when}))}),c!==null&&o(q,{variant:`warning`,message:c}),o(Q,{children:u(`automation.choose.then`,`Then run`)}),o(cc,{...d,actions:i.steps,onChange:e=>l(Ki(n,a,{...i,steps:e.filter(Xi)}))})]},String(a))}),e(G,{variant:`outline`,"data-testid":`choose-add-${String(t)}`,disabled:!Hi(n),onClick:()=>l(Ui(n)),title:Hi(n)?void 0:u(`automation.choose.maxBranches`,`A choose takes at most 6 branches`),children:[o(D,{className:`h-4 w-4`}),` `,u(`automation.choose.addBranch`,`Add a branch`)]}),o(an,{"data-testid":`choose-else-${String(t)}`,checked:n.else!==void 0,label:u(`automation.choose.else`,`Otherwise, run…`),"aria-label":u(`automation.choose.else`,`Otherwise, run…`),onCheckedChange:e=>l(qi(n,e?[]:void 0))}),n.else!==void 0&&o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(cc,{...d,actions:n.else,onChange:e=>l(qi(n,e.filter(Xi)))})})]})}function Ys(e){return Object.entries(e).map(([e,t])=>({name:e,value:t}))}function Xs(e){return Object.fromEntries(e.map(e=>[e.name,e.value]))}function Zs(e,t,n){let r=Ys(e);return r.some((e,r)=>r!==t&&e.name===n)?e:Xs(r.map((e,r)=>r===t?{...e,name:n}:e))}function Qs(e,t,n){return Xs(Ys(e).map((e,r)=>r===t?{...e,value:n}:e))}function $s(e){return!Object.keys(e).includes(``)}function ec(e){return $s(e)?{...e,"":``}:e}function tc(e,t){return Xs(Ys(e).filter((e,n)=>n!==t))}var nc=`{{vars.name}}`;function rc({index:t,vars:n,onChange:r}){let{t:i}=X();return e(`div`,{className:`space-y-2`,children:[Ys(n).map((a,s)=>e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-40`,children:[o(Q,{children:i(`automation.actionList.setName`,`Variable`)}),o(J,{"data-testid":`set-name-${String(t)}-${String(s)}`,value:a.name,spellCheck:!1,onChange:e=>r(Zs(n,s,e.target.value))})]}),e(`label`,{className:`min-w-40 flex-1`,children:[o(Q,{children:i(`automation.actionList.setValue`,`Value`)}),o(J,{"data-testid":`set-value-${String(t)}-${String(s)}`,value:String(a.value),onChange:e=>r(Qs(n,s,e.target.value))})]}),o(G,{variant:`ghost`,onClick:()=>r(tc(n,s)),title:i(`automation.actionList.setRemove`,`Remove this variable`),children:o(k,{className:`h-3.5 w-3.5`})})]},String(s))),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{variant:`outline`,"data-testid":`set-add-${String(t)}`,disabled:!$s(n),onClick:()=>r(ec(n)),children:[o(D,{className:`h-4 w-4`}),` `,i(`automation.actionList.setAdd`,`Add a variable`)]}),o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`automation.actionList.setHint`,`The steps after this one can use it as {{slot}}.`,{slot:nc,interpolation:{escapeValue:!1}})})]})]})}function ic({index:t,step:n,devices:r,devicesState:i,variables:a,depth:s=0,roundDevices:c,onChange:l}){let{t:u}=X(),{loop:d}=n,f={count:u(`automation.repeat.byCount`,`A number of times`),while:u(`automation.repeat.byWhile`,`While a condition is true`),until:u(`automation.repeat.byUntil`,`Until a condition is true`),forEach:u(`automation.repeat.byForEach`,`Once for each device`)},p=d.by===`while`||d.by===`until`,h=p?Ws(d.when):null,g={name:B,hint:u(`automation.repeat.itemHint`,`the device of this round`)},_=d.by===`forEach`?[...a??[],g]:a,v=d.by===`forEach`?d.target.ids:c;return e(`div`,{className:`space-y-2`,children:[o(`div`,{className:`w-64`,children:o(F,{"data-testid":`repeat-by-${String(t)}`,"aria-label":u(`automation.repeat.by`,`Repeat`),value:d.by,onChange:e=>{let t=e.target.value;Kr(t)&&t!==d.by&&l({...n,loop:Xr(t)})},options:Hr.map(e=>({value:e,label:f[e]}))})}),d.by===`count`&&e(`label`,{className:`block w-24`,children:[o(Q,{children:u(`automation.repeat.count`,`Times`)}),o(J,{type:`number`,min:1,max:20,"data-testid":`repeat-count-${String(t)}`,value:String(d.count),onChange:e=>l({...n,loop:{...d,count:Jr(Number(e.target.value))}})})]}),p&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:d.by===`while`?u(`automation.repeat.whileHint`,`Read before each round: if it is not true at the start, nothing runs. A condition that cannot be read ends the loop.`):u(`automation.repeat.untilHint`,`Read after each round, so the steps run at least once. A condition that cannot be read ends the loop.`)}),o(Ms,{hideRule:!0,context:`guard`,recipe:{when:d.when,actions:[]},devices:r,onChange:e=>l({...n,loop:{...d,when:e.when}})}),h!==null&&o(q,{variant:`warning`,message:h}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-28`,children:[o(Q,{children:u(`automation.repeat.max`,`At most (rounds)`)}),o(J,{type:`number`,min:1,max:50,"data-testid":`repeat-max-${String(t)}`,value:String(d.maxIterations),onChange:e=>l({...n,loop:{...d,maxIterations:Yr(Number(e.target.value))}})})]}),e(`label`,{className:`w-40`,children:[o(Q,{children:u(`automation.repeat.wait`,`Pause between rounds (s)`)}),o(J,{type:`number`,min:1,max:3600,"data-testid":`repeat-wait-${String(t)}`,value:d.waitS===void 0?``:String(d.waitS),placeholder:u(`automation.repeat.noWait`,`none`),onChange:e=>l({...n,loop:Zr(d,e.target.value===``?null:Number(e.target.value))})})]})]}),o(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.maxHint`,`A loop that reaches its maximum stops there, is marked in the run, and the run goes on.`)})]}),d.by===`forEach`&&e(`div`,{className:`space-y-1`,children:[o(Xe,{multiple:!0,pick:`device`,maxItems:50,value:d.target.ids.map(e=>({deviceId:e})),onChange:e=>l({...n,loop:{...d,target:{kind:`devices`,ids:e.map(e=>e.deviceId)}}})}),o(`p`,{className:`text-xs text-foreground-subtle`,children:u(`automation.repeat.forEachHint`,`One round per device, in this order. In a round the steps read the device as the variable "item".`)})]}),o(Q,{children:u(`automation.repeat.steps`,`Each time, run`)}),o(`div`,{className:`border-l-2 border-border-subtle pl-3`,"data-testid":`repeat-steps-${String(t)}`,children:o(cc,{nested:!0,flowControl:!0,actions:n.steps,devices:r,depth:s+1,allowedKinds:Yi(s+1),maxSteps:10,...i===void 0?{}:{devicesState:i},..._===void 0?{}:{variables:_},...v===void 0?{}:{roundDevices:v},onChange:e=>l({...n,steps:e.filter(Xi)})})})]})}function ac({index:t,step:n,devices:r,onChange:i}){let{t:a}=X(),s={when:n.when,actions:[]},c=Ws(n.when),l=ni(n.timeoutS),u={s:a(`automation.waitUntil.unitSeconds`,`seconds`),min:a(`automation.waitUntil.unitMinutes`,`minutes`),h:a(`automation.waitUntil.unitHours`,`hours`)};return e(`div`,{className:`space-y-2`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`automation.waitUntil.hint`,`The run pauses here until this is true. A value that cannot be read is not "true": the run keeps waiting.`)}),o(Ms,{hideRule:!0,context:`guard`,recipe:s,devices:r,onChange:e=>i({...n,when:e.when})}),c!==null&&o(q,{variant:`warning`,message:c}),e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`w-24`,children:[o(Q,{children:a(`automation.waitUntil.timeout`,`At most`)}),o(J,{type:`number`,min:1,"data-testid":`wait-until-timeout-${String(t)}`,value:String(l.value),onChange:e=>i({...n,timeoutS:ri(Number(e.target.value),l.unit)})})]}),o(`div`,{className:`w-32`,children:o(F,{"data-testid":`wait-until-unit-${String(t)}`,"aria-label":a(`automation.waitUntil.unit`,`Unit`),value:l.unit,onChange:e=>i({...n,timeoutS:ri(l.value,ti(e.target.value)?e.target.value:l.unit)}),options:$r.map(e=>({value:e,label:u[e]}))})}),e(`label`,{className:`min-w-56 flex-1`,children:[o(Q,{children:a(`automation.waitUntil.onTimeout`,`If it does not happen in time`)}),o(F,{"data-testid":`wait-until-on-timeout-${String(t)}`,value:n.onTimeout,onChange:e=>i({...n,onTimeout:e.target.value===`stop`?`stop`:`continue`}),options:[{value:`continue`,label:a(`automation.waitUntil.continue`,`Go on with the next step`)},{value:`stop`,label:a(`automation.waitUntil.stop`,`Stop the run as a failure`)}]})]})]})]})}var oc=[{value:`cap`,labelKey:`automation.actionList.kindCap`},{value:`action`,labelKey:`automation.actionList.kindAction`},{value:`wait`,labelKey:`automation.actionList.kindWait`},{value:`wait-until`,labelKey:`automation.actionList.kindWaitUntil`},{value:`set`,labelKey:`automation.actionList.kindSet`},{value:`stop`,labelKey:`automation.actionList.kindStop`},{value:`choose`,labelKey:`automation.actionList.kindChoose`},{value:`parallel`,labelKey:`automation.actionList.kindParallel`},{value:`repeat`,labelKey:`automation.actionList.kindRepeat`},{value:`code`,labelKey:`automation.actionList.kindCode`}],sc=[`set`,`stop`,`choose`,`wait-until`,`parallel`,`repeat`];function cc({actions:t,devices:n,devicesState:r=`answered`,allowedKinds:i,variables:a=[],stepTones:s,stepResults:c,nested:l=!1,flowControl:u=!1,maxSteps:d,roundDevices:f,depth:p=0,onChange:m}){let{t:h}=X(),g=oc.filter(e=>(i===void 0||i.includes(e.value))&&(u||!sc.includes(e.value))),_=h(`automation.actionList.flowGuardHint`,`Checked when this step is reached. If it is false, or a state cannot be read, the step does nothing.`),v={up:h(`automation.actionList.runThisStepEarlier`,`Run this step earlier`),down:h(`automation.actionList.runThisStepLater`,`Run this step later`),atFirst:h(`automation.actionList.alreadyFirstStep`,`This step already runs first`),atLast:h(`automation.actionList.alreadyLastStep`,`This step already runs last`)};return e(`div`,{className:`space-y-2`,children:[t.length===0&&o(`p`,{className:`text-xs text-warning`,children:h(`automation.actionList.noActionsYetAnAutomation`,`No actions yet. An automation that does nothing is not an automation.`)}),t.map((i,d)=>e(`div`,{className:`space-y-2 rounded border p-3 ${s===void 0?`border-border`:Rr(s[d]??`idle`)}`,children:[e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[o(K,{variant:`default`,children:d+1}),e(`label`,{className:`w-40`,children:[o(Q,{children:h(`automation.actionList.step`,`Step`)}),o(F,{"data-testid":`step-kind-${String(d)}`,value:i.kind,onChange:e=>m(Z(t,d,mi(lc(e.target.value)))),options:g.map(e=>({value:e.value,label:h(e.labelKey)}))})]}),e(`div`,{className:`ml-auto flex items-center gap-1`,children:[o(Fi,{move:{up:d===0?null:()=>m(gi(t,d,d-1)),down:d===t.length-1?null:()=>m(gi(t,d,d+1))},texts:v}),o(G,{variant:`ghost`,onClick:()=>m(hi(t,d)),title:h(`automation.actionList.removeThisStep`,`Remove this step`),children:o(k,{className:`h-3.5 w-3.5`})})]})]}),i.kind===`wait`&&e(`label`,{className:`block w-32`,children:[o(Q,{children:h(`automation.actionList.seconds`,`Seconds`)}),o(J,{type:`number`,min:0,max:3600,value:String(i.seconds),onChange:e=>m(Z(t,d,{...i,seconds:Number(e.target.value)}))})]}),i.kind===`stop`&&e(`div`,{className:`flex flex-wrap items-end gap-2`,children:[e(`label`,{className:`min-w-48 flex-1`,children:[o(Q,{children:h(`automation.actionList.stopReason`,`Reason`)}),o(J,{"data-testid":`stop-reason-${String(d)}`,value:i.reason,maxLength:200,onChange:e=>m(Z(t,d,{...i,reason:e.target.value}))})]}),e(`label`,{className:`w-48`,children:[o(Q,{children:h(`automation.actionList.stopOutcome`,`The run ends as`)}),o(F,{"data-testid":`stop-outcome-${String(d)}`,value:i.outcome,onChange:e=>m(Z(t,d,{...i,outcome:e.target.value===`failed`?`failed`:`ok`})),options:[{value:`ok`,label:h(`automation.actionList.stopOk`,`A success`)},{value:`failed`,label:h(`automation.actionList.stopFailed`,`A failure`)}]})]})]}),i.kind===`set`&&o(rc,{index:d,vars:i.vars,onChange:e=>m(Z(t,d,{...i,vars:e}))}),i.kind===`wait-until`&&o(ac,{index:d,step:i,devices:n,onChange:e=>m(Z(t,d,e))}),i.kind===`repeat`&&o(ic,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Z(t,d,e))}),i.kind===`parallel`&&e(`div`,{className:`space-y-2`,"data-testid":`parallel-steps-${String(d)}`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:h(`automation.parallel.hint`,`These start together and the run goes on when all are done. If one fails, the run fails once the others finished.`)}),o(`div`,{className:`border-l-2 border-border-subtle pl-3`,children:o(cc,{nested:!0,flowControl:!0,actions:i.steps,devices:n,devicesState:r,variables:a,allowedKinds:Li,depth:p+1,...f===void 0?{}:{roundDevices:f},maxSteps:5,onChange:e=>m(Z(t,d,{...i,steps:e.filter(Ri)}))})})]}),i.kind===`choose`&&o(Js,{index:d,step:i,devices:n,devicesState:r,variables:a,depth:p,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Z(t,d,e))}),!l&&(i.kind===`stop`||i.kind===`set`)&&o(Ks,{when:i.if,devices:n,hint:_,onChange:e=>{let{if:n,...r}=i;m(Z(t,d,e===void 0?r:{...r,if:e}))}}),i.kind===`code`&&e(`label`,{className:`block`,children:[o(Q,{children:h(`automation.actionList.code`,`Code`)}),o(Kt,{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:i.code,spellCheck:!1,onChange:e=>m(Z(t,d,{kind:`code`,code:e.target.value}))}),o(`span`,{className:`mt-1 block text-xs text-foreground-subtle`,children:o(gn,{i18nKey:`automation.actionList.codeHint`,components:{code:o(`code`,{})}})})]}),i.kind===`cap`&&o(Kn,{step:i,devices:n,devicesState:r,variables:a,...f===void 0?{}:{roundDevices:f},onChange:e=>m(Z(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{},...i.if===void 0?{}:{if:i.if},...i.else===void 0?{}:{else:i.else}}))}),i.kind===`action`&&o(Mi,{step:i,onChange:e=>m(Z(t,d,{...e,...i.continueOnError===!0?{continueOnError:!0}:{}}))}),u&&(i.kind===`cap`||i.kind===`action`)&&o(an,{"data-testid":`continue-on-error-${String(d)}`,checked:i.continueOnError===!0,label:h(`automation.actionList.continueOnError`,`Continue if this step fails`),"aria-label":h(`automation.actionList.continueOnError`,`Continue if this step fails`),onCheckedChange:e=>{let{continueOnError:n,...r}=i;m(Z(t,d,e?{...r,continueOnError:!0}:r))}}),!l&&(i.kind===`wait`||i.kind===`cap`)&&o(qs,{step:i,devices:n,devicesState:r,variables:a,onChange:e=>m(Z(t,d,e))}),c?.[d]!==void 0&&o(Ti,{step:c[d],deviceName:e=>n.find(t=>t.id===e)?.name??`#${String(e)}`})]},`${i.kind}-${String(d)}`)),e(`div`,{className:`flex items-center gap-2`,children:[e(G,{variant:`outline`,disabled:d!==void 0&&t.length>=d,onClick:()=>m([...t,mi(g[0]?.value??`cap`)]),children:[o(D,{className:`h-4 w-4`}),` `,h(`automation.actionList.addStep`)]}),t.length>1&&o(`span`,{className:`text-xs text-foreground-subtle`,children:h(`automation.actionList.stepsRunInOrderAnd`,`Steps run in order and stop at the first failure.`)})]})]})}function lc(e){return oc.find(t=>t.value===e)?.value??`cap`}function uc(e,t){return e.map(e=>({name:e.name,hint:e.label??t(`flow.scope.type_${e.type}`,e.type)}))}function dc(e,t){return ze(e).map(e=>({name:e.name,hint:t(`flow.scope.${e.hintKey??e.name}`,e.description)}))}function fc(e){return e.some(e=>e.required===!0&&e.default===void 0)}function pc(e){return Object.fromEntries(e.map(e=>[e.name,e.default??(e.type===`boolean`?!1:void 0)]))}function mc(e){return e===void 0?!1:typeof e==`string`?e.trim()!==``:typeof e==`number`?Number.isFinite(e):!0}function hc(e,t){return e.filter(e=>e.required===!0&&!mc(t[e.name])).map(e=>e.name)}function gc(e,t){let n={};for(let r of e){let e=t[r.name];mc(e)&&(n[r.name]=e)}return n}u();function _c({variable:e,value:t,onChange:n}){let{t:r}=X(),i=e.label??e.name;return e.type===`number`?o(Hn,{"aria-label":i,value:typeof t==`number`?t:void 0,onValue:e=>n(e??void 0)}):e.type===`boolean`?o(Jn,{widthClass:`w-28`,"aria-label":i,value:t===!0?`yes`:`no`,onChange:e=>n(e.target.value===`yes`),options:[{value:`yes`,label:r(`common.yes`,`Yes`)},{value:`no`,label:r(`common.no`,`No`)}]}):e.type===`select`?o(Jn,{widthClass:`w-48`,"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value===``?void 0:e.target.value),options:[{value:``,label:r(`actions.editor.runDialog.choose`,`Choose…`)},...(e.options??[]).map(e=>({value:e,label:e}))]}):o(J,{"aria-label":i,value:typeof t==`string`?t:``,onChange:e=>n(e.target.value)})}function vc({actionName:t,variables:n,running:r,onRun:i,onCancel:a}){let{t:s}=X(),[l,u]=c(()=>pc(n)),d=hc(n,l);return o(st,{open:!0,onOpenChange:e=>!e&&a(),children:e(Mt,{"aria-label":s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t}),children:[e(sn,{children:[o(ut,{children:s(`actions.editor.runDialog.title`,`Run {{name}}`,{name:t})}),o(it,{children:s(`actions.editor.runDialog.description`,`Give the variables this run should use.`)})]}),o(`div`,{className:`space-y-3`,"data-testid":`run-variables-form`,children:n.map(t=>e(`label`,{className:`block space-y-1`,children:[e(`span`,{className:`text-xs text-foreground-subtle`,children:[t.label??t.name,t.required===!0?` *`:``]}),o(_c,{variable:t,value:l[t.name],onChange:e=>u({...l,[t.name]:e})})]},t.name))}),e(ft,{className:`flex flex-wrap gap-2`,children:[o(G,{variant:`ghost`,onClick:a,children:s(`common.cancel`,`Cancel`)}),e(G,{disabled:r||d.length>0,onClick:()=>i(gc(n,l)),children:[r?o(T,{className:`h-4 w-4 animate-spin`}):o(g,{className:`h-4 w-4`}),` `,s(`actions.editor.runNow`,`Run now`)]})]})]})})}var yc=[`number`,`string`,`boolean`,`select`];function bc(e,t){return{name:e.name,...e.label===void 0?{}:{label:e.label},type:t,...t===`select`?{options:e.options??[`option`]}:{}}}function xc(e,t){let n=t.split(`,`).map(e=>e.trim()).filter(e=>e!==``),r=e.default!==void 0&&typeof e.default==`string`&&n.includes(e.default),{default:i,...a}=e;return{...r?e:a,options:n.length===0?[`option`]:n}}function Sc(e,t){let{default:n,...r}=e;return t===null?r:{...r,default:t}}function Cc(e,t){let{label:n,...r}=e;return t.trim()===``?r:{...r,label:t}}function wc({variables:t,onChange:n,onRename:r}){let{t:i}=X(),a=e=>{switch(e){case`number`:return i(`actions.variables.typeNumber`,`number`);case`string`:return i(`actions.variables.typeText`,`text`);case`boolean`:return i(`actions.variables.typeBoolean`,`yes / no`);default:return i(`actions.variables.typeSelect`,`select`)}},s=(e,r)=>n(t.map((t,n)=>n===e?r:t));return o(kt,{headingId:`vars-heading`,title:i(`actions.variables.title`,`Variables`),icon:qe,actions:e(G,{variant:`outline`,size:`sm`,onClick:()=>n([...t,Zn(t)]),children:[o(D,{className:`h-4 w-4`}),` `,i(`actions.variables.add`,`Variable`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[t.map((c,l)=>e(`div`,{className:`grid gap-2 sm:grid-cols-[1fr_1fr_8rem_1fr_1.2fr_auto] sm:items-end`,"data-testid":`variable-row`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.name`,`Name`)}),o(J,{"aria-label":i(`actions.variables.nameAria`,`Variable name`),value:c.name,"aria-invalid":!Qn(c.name),onChange:e=>r(l,e.target.value)})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.label`,`Label`)}),o(J,{"aria-label":i(`actions.variables.label`,`Label`),value:c.label??``,onChange:e=>s(l,Cc(c,e.target.value))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.type`,`Type`)}),o(Jn,{widthClass:`w-full`,"aria-label":i(`actions.variables.type`,`Type`),value:c.type,options:yc.map(e=>({value:e,label:a(e)})),onChange:e=>{let t=yc.find(t=>t===e.target.value);t!==void 0&&s(l,bc(c,t))}})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.default`,`Default`)}),o(Tc,{variable:c,onChange:e=>s(l,Sc(c,e))})]}),e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.options`,`Options`)}),o(J,{"aria-label":i(`actions.variables.options`,`Options`),value:(c.options??[]).join(`, `),disabled:c.type!==`select`,placeholder:i(`actions.variables.optionsHint`,`Only for a select`),onChange:e=>s(l,xc(c,e.target.value))})]}),o(G,{variant:`ghost`,"aria-label":i(`actions.variables.remove`,`Remove variable`),onClick:()=>n(t.filter((e,t)=>t!==l)),children:o(k,{className:`h-4 w-4`})})]},`${String(l)}`)),o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.variables.hint`,`Callers can override a variable. In a step, the {x} button puts one in an argument.`)})]})})}function Tc({variable:e,onChange:t}){let{t:n}=X(),r=n(`actions.variables.default`,`Default`);if(e.type===`number`)return o(Hn,{"aria-label":r,value:typeof e.default==`number`?e.default:void 0,onValue:t});if(e.type===`boolean`||e.type===`select`){let i=e.type===`boolean`?[{value:`true`,label:n(`common.yes`,`Yes`)},{value:`false`,label:n(`common.no`,`No`)}]:(e.options??[]).map(e=>({value:e,label:e}));return o(Jn,{widthClass:`w-full`,"aria-label":r,value:e.default===void 0?``:String(e.default),options:[{value:``,label:n(`actions.variables.noDefault`,`None`)},...i],onChange:n=>{n.target.value===``?t(null):t(e.type===`boolean`?n.target.value===`true`:n.target.value)}})}return o(J,{"aria-label":r,value:typeof e.default==`string`?e.default:``,onChange:e=>t(e.target.value===``?null:e.target.value)})}u();var Ec=5e3;function Dc(e){return e.kind===`cap`||e.kind===`wait`}function Oc(e){return e instanceof Error?e.message:String(e)}function kc(){let{t:e}=X();return t=>{switch(t.kind){case`name`:return e(`actions.editor.problemName`,`Give the action a name.`);case`no-steps`:return e(`actions.editor.problemNoSteps`,`Add at least one step.`);case`undeclared`:return e(`actions.editor.problemUndeclared`,`A step uses {{name}}, which is not declared under Variables.`,{name:t.name});case`duplicate`:return e(`actions.editor.problemDuplicate`,`The variable {{name}} is declared twice.`,{name:t.name});case`bad-name`:return e(`actions.editor.problemBadName`,`The variable name "{{name}}" must start with a letter and use letters, digits or _.`,{name:t.name});default:return t.message}}}function Ac({entry:t,onClose:i,onSaved:a,preset:l=null}){let{t:u}=X(),d=f(),p=j(),h=Un(),v=kc(),[y,b]=c(()=>tr(t)),x=n(!1);s(()=>{if(t!==null||l!==`trigger-alarm`||x.current)return;let e=h.find(e=>e.type===Ne.AlarmPanel);e!==void 0&&(x.current=!0,b(nr(e.id,u(`actions.editor.triggerAlarmName`,`Trigger the alarm`))))},[h,t,l,u]);let[S,C]=c(null),[w,E]=c(!1),D=t!==null&&t.readOnly,O=()=>{d.invalidateQueries({queryKey:[[`actions`]]})},A=Jt({onSuccess:e=>{O(),a(e.action.id)}}),M=wt({onSuccess:O}),N=mt({onSuccess:()=>{O(),i()}}),P=ct({onSuccess:O}),F=yt({actionId:t?.id??`none`},{enabled:t!==null,refetchInterval:Ec}),I=F.data?.traces.find(e=>e.runId===S)??null,L=r(()=>I===null?null:gr(I),[I]),R=r(()=>I===null?null:Sr(I).steps,[I]),z=$n(y),ee=r(()=>uc(y.variables,u),[y.variables,u]),B=A.isPending||M.isPending,V=A.error??M.error??N.error??P.error,H=fc(t?.variables??[]);return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`action-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(_,{className:`h-4 w-4 text-foreground-muted`}),o(J,{"aria-label":u(`actions.editor.name`,`Name`),className:`max-w-xs flex-1`,value:y.name,disabled:D,placeholder:u(`actions.editor.namePlaceholder`,`What this action does`),onChange:e=>b({...y,name:e.target.value})}),o(K,{variant:D?`info`:`primary`,children:D?t?.addonId??``:u(`actions.source.internal`,`Internal`)})]}),D?o(`p`,{className:`rounded-md border border-border bg-surface p-3 text-sm text-foreground-muted`,children:u(`actions.editor.readOnly`,`This action is declared by {{addon}}. Edit it there; you can run it from here.`,{addon:t?.addonId??``})}):e(m,{children:[o(wc,{variables:y.variables,onChange:e=>b({...y,variables:e}),onRename:(e,t)=>b(er(y,e,t))}),o(Vr,{step:`steps`,title:u(`actions.editor.steps`,`Steps`),trace:L===null?null:L.thenBlock,children:o(cc,{actions:y.steps,devices:h,allowedKinds:[`cap`,`wait`],stepTones:L===null?void 0:y.steps.map((e,t)=>_r(L,t)??`idle`),stepResults:R===null?void 0:y.steps.map((e,t)=>R.find(e=>e.index===t)),variables:ee,onChange:e=>b({...y,steps:e.filter(Dc)})})})]}),!z.ok&&!D&&y.name!==``&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:v(z.reason)}),V!==null&&o(q,{message:Oc(V)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[!D&&e(G,{onClick:()=>{z.ok&&(t===null?A.mutate({action:z.input}):M.mutate({actionId:t.id,action:z.input}))},disabled:B||!z.ok,children:[B&&o(T,{className:`h-4 w-4 animate-spin`}),` `,u(`common.save`,`Save`)]}),t!==null&&e(G,{variant:`outline`,disabled:P.isPending,onClick:()=>H?E(!0):P.mutate({actionId:t.id}),children:[o(g,{className:`h-4 w-4`}),` `,u(`actions.editor.runNow`,`Run now`)]}),t!==null&&!D&&e(G,{variant:`ghost`,disabled:N.isPending,onClick:()=>{p({title:u(`actions.editor.deleteTitle`,`Delete this action?`),message:u(`actions.editor.deleteMessage`,`{{name}} will be deleted, and removed from every camera that links it.`,{name:t.name}),confirmLabel:u(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&N.mutate({actionId:t.id})})},children:[o(k,{className:`h-4 w-4`}),` `,u(`common.delete`,`Delete`)]}),o(G,{variant:`ghost`,onClick:i,children:u(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Lr,{traces:t===null?[]:F.data?.traces,selectedId:S,onSelect:C})}),w&&t!==null&&o(vc,{actionName:t.name,variables:t.variables??[],running:P.isPending,onCancel:()=>E(!1),onRun:e=>{P.mutate({actionId:t.id,variables:e}),E(!1)}})]})}u();var jc=5e3;function Mc(e){return e instanceof Error?e.message:String(e)}function Nc(){let{t:e}=X();return t=>t.status.isRunning?{variant:`info`,label:e(`actions.status.running`,`Running`)}:t.status.lastError===null?t.status.lastRunAt===null?{variant:`neutral`,label:e(`actions.status.neverRan`,`Never ran`)}:{variant:`success`,label:e(`actions.status.ok`,`OK`)}:{variant:`danger`,label:e(`actions.status.failed`,`Failed`)}}function Pc({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=X(),[a]=_n(),c=f(),l=Nc(),{state:u,openNew:d,openEdit:p,close:h}=Ft({editKey:`action`,newKey:`new`}),v=tt({},{refetchInterval:jc}),y=ct({onSuccess:()=>void c.invalidateQueries({queryKey:[[`actions`]]})});s(()=>{t&&(d(),n?.())},[t,n,d]);let b=v.data??[],x=u.mode===`edit`?b.find(e=>e.id===u.id)??null:null,S=r(()=>[{key:`name`,header:i(`actions.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`source`,header:i(`actions.list.source`,`Source`),render:e=>e.readOnly?o(K,{variant:`info`,children:e.addonId}):o(K,{variant:`primary`,children:i(`actions.source.internal`,`Internal`)}),sortValue:e=>e.addonId},{key:`lastRun`,header:i(`actions.list.lastRun`,`Last run`),render:e=>e.status.lastRunAt===null?o(`span`,{className:`text-foreground-subtle`,children:`-`}):En(e.status.lastRunAt),sortValue:e=>e.status.lastRunAt},{key:`status`,header:i(`actions.list.status`,`Status`),render:e=>{let t=l(e);return o(`span`,{title:e.status.lastError??void 0,children:o(K,{variant:t.variant,children:t.label})})},notSortableReason:i(`actions.list.statusNotSortable`,`Derived from the latest run`)},{key:`run`,align:`right`,render:t=>e(G,{variant:`outline`,size:`sm`,disabled:y.isPending||t.status.isRunning,"aria-label":i(`actions.list.runAria`,`Run {{name}}`,{name:t.name}),onClick:e=>{e.stopPropagation(),y.mutate({actionId:t.id})},children:[o(g,{className:`h-4 w-4`}),` `,i(`actions.list.run`,`Run`)]}),notSortableReason:i(`actions.list.runNotSortable`,`A control`)}],[y,l,i]);return u.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`actions.list.hint`,`Actions are things this installation can do. Run one here, link it to a camera, or use it in an automation.`)}),y.error!=null&&o(q,{message:Mc(y.error)}),v.data===void 0?v.error==null?o(At,{className:`h-24 w-full`}):o(q,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:Mc(v.error),onRetry:()=>void v.refetch()}):b.length===0?o(qt,{icon:_,title:i(`actions.list.emptyTitle`,`No actions yet`),description:i(`actions.list.emptyDescription`,`An action is a short list of commands, such as feeding the dog, that you can reuse.`),action:e(G,{onClick:d,children:[o(D,{className:`h-4 w-4`}),` `,i(`actions.list.new`,`New action`)]})}):e(m,{children:[v.error!=null&&o(q,{title:i(`actions.list.couldNotRead`,`Could not read the actions`),message:Mc(v.error),onRetry:()=>void v.refetch()}),o(Dt,{columns:S,rows:b,rowKey:e=>e.id,pageSize:25,maxBodyHeight:jt,emptyMessage:i(`actions.list.emptyTitle`,`No actions yet`),onRowClick:e=>p(e.id)})]})]}):o(Ac,{entry:x,onClose:h,onSaved:p,preset:u.mode===`new`?a.get(`preset`):null},x?.id??`new`)}u();function Fc({code:t,error:n,canEject:r,ejecting:i,onEject:a}){let{t:s}=X(),[l,u]=c(!1),d=j(),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(G,{variant:`ghost`,onClick:()=>u(!l),children:[o(l?He:x,{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(G,{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(We,{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(pt,{maxHeight:420,children:t})})]})}var Ic=[`single`,`restart`,`queued`,`parallel`,`cooldown`],Lc=2,Rc=30;function zc(e){return e.runMode??{mode:`single`}}function Bc(e,t){let{runMode:n,...r}=e;return t.mode===`single`?r:{...r,runMode:t}}function Vc(e){switch(e){case`queued`:return{mode:`queued`,max:Lc};case`parallel`:return{mode:`parallel`,max:Lc};case`cooldown`:return{mode:`cooldown`,minutes:Rc};case`restart`:return{mode:`restart`};default:return{mode:`single`}}}function Hc(e){return Ic.find(t=>t===e)??`single`}function Uc({value:t,onChange:n}){let{t:r}=X(),i={single:r(`flow.runMode.single`,`Skip it`),restart:r(`flow.runMode.restart`,`Restart the run`),queued:r(`flow.runMode.queued`,`Queue it`),parallel:r(`flow.runMode.parallel`,`Run at the same time`),cooldown:r(`flow.runMode.cooldown`,`Wait after a run`)},a={single:r(`flow.runMode.singleHint`,`A trigger that arrives during a run is dropped.`),restart:r(`flow.runMode.restartHint`,`The run in progress stops and a new one starts.`),queued:r(`flow.runMode.queuedHint`,`Triggers wait their turn, up to the limit.`),parallel:r(`flow.runMode.parallelHint`,`Runs overlap, up to the limit.`),cooldown:r(`flow.runMode.cooldownHint`,`No new run until this long after the last one began.`)};return e(`div`,{className:`flex flex-wrap items-end gap-3`,"data-testid":`run-mode`,children:[e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.label`,`When it is already running`)}),o(Jn,{widthClass:`w-56`,value:t.mode,options:Ic.map(e=>({value:e,label:i[e]})),onChange:e=>n(Vc(Hc(e.target.value)))})]}),(t.mode===`queued`||t.mode===`parallel`)&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.max`,`Up to`)}),o(Hn,{className:`w-20`,"aria-label":r(`flow.runMode.max`,`Up to`),value:t.max,onValue:e=>{e!==null&&n({mode:t.mode,max:Math.round(e)})}})]}),t.mode===`cooldown`&&e(`label`,{className:`space-y-1`,children:[o(`span`,{className:`block text-xs text-foreground-subtle`,children:r(`flow.runMode.minutes`,`Minutes`)}),o(Hn,{className:`w-20`,"aria-label":r(`flow.runMode.minutes`,`Minutes`),value:t.minutes,onValue:e=>{e!==null&&n({mode:`cooldown`,minutes:Math.round(e)})}})]}),o(`p`,{className:`basis-full text-xs text-foreground-subtle`,children:a[t.mode]})]})}var Wc;function Gc(){return Wc??=Se(de),Wc}function Kc(e,t=Gc()){return Ie(e,t)}u();var qc=`hub`,Jc=5e3;function Yc({existing:t,initialRecipe:n,saving:i,saveError:a,ejecting:s,onSave:l,onEject:u,onCancel:d}){let{t:f}=X(),[p,m]=c(t?.name??``),[h,g]=c(()=>cs(n)),_=e=>g(aa(e)),[v,y]=c(!1),[b,x]=c(null),S=Nt({blockId:t?.id??`none`},{enabled:t!==null,refetchInterval:Jc}),C=S.data?.traces.find(e=>e.runId===b)??null,E=r(()=>C===null?null:gr(C),[C]),D=r(()=>dc(h.when,f),[h.when,f]),O=r(()=>C===null?null:Cr(C),[C]),k=r(()=>C===null?null:Sr(C).steps,[C]),A=Un(),j=V(h),M=r(()=>Xc(h),[h]),N=r(()=>Zc(p.trim()===``?`Untitled automation`:p.trim(),h),[p,h]),P=Zt().data,F=r(()=>M===null?$o(h,P):null,[h,P,M]),I=p.trim()===``,L=I||j!==null||M!==null||F!==null||N.code===null;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`automation-editor`,children:[o(ua,{when:h.when,children:e(`div`,{className:`space-y-4`,children:[e(`label`,{className:`block max-w-md text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:f(`automation.automationEditor.name`,`Name`)}),o(J,{className:`mt-1`,value:p,onChange:e=>m(e.target.value),placeholder:f(`automation.automationEditor.whatThisAutomationDoes`,`What this automation does`)})]}),o(Vr,{step:`when`,title:f(`automation.automationEditor.when`,`When`),trace:E===null?null:E.when,children:o(Ms,{recipe:h,devices:A,run:O,onChange:_})}),o(Vr,{step:`then`,title:f(`automation.automationEditor.then`,`Then`),trace:E===null?null:E.thenBlock,hint:f(`automation.automationEditor.inThisOrderStoppingAt`,`In this order, stopping at the first failure.`),children:o(cc,{flowControl:!0,actions:h.actions,devices:A,variables:D,stepTones:E===null?void 0:h.actions.map((e,t)=>_r(E,t)??`idle`),stepResults:k===null?void 0:h.actions.map((e,t)=>k.find(e=>e.index===t)),onChange:e=>_(_i(h,e))})}),o(Vr,{step:`mode`,title:f(`flow.runMode.title`,`Overlap`),trace:null,hint:f(`flow.runMode.hint`,`What happens when a trigger arrives mid-run.`),children:o(Uc,{value:zc(h),onChange:e=>_(Bc(h,e))})}),o(Fc,{code:N.code,error:N.error,canEject:t!==null,ejecting:s,onEject:u}),j!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:j}),j===null&&M!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:M}),j===null&&F!==null&&o(`p`,{className:`rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,"data-testid":`automation-site-error`,children:F}),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(G,{onClick:()=>{N.code!==null&&l({name:p.trim(),code:N.code,enabled:t?.enabled??!0,placement:qc})},disabled:i||L,children:[i&&o(T,{className:`h-4 w-4 animate-spin`}),` `,f(`common.save`)]}),e(G,{variant:`ghost`,onClick:()=>y(!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`,"aria-expanded":v,children:[o(w,{className:`h-4 w-4`}),` `,f(`common.logs`),` `,o(en,{expanded:v})]}),o(G,{variant:`ghost`,onClick:d,disabled:i,children:f(`common.close`,`Close`)}),I&&o(K,{variant:`warning`,children:f(`automation.automationEditor.nameRequired`,`Name required`)})]}),v&&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(gn,{i18nKey:`common.logsOf`,values:{id:ye(t.id)},components:{code:o(`code`,{})}})}),o(Et,{addonId:ye(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}),o(`div`,{className:`order-first lg:order-last`,children:o(Lr,{traces:t===null?[]:S.data?.traces,selectedId:b,onSelect:x})})]})}function Xc(e){let t=pe.safeParse(e);if(t.success)return null;let n=t.error.issues[0];return n===void 0?Y.t(`helpers.automationEditor.incomplete`):`${n.path.length===0?``:`${n.path.join(`.`)}: `}${n.message}`}function Zc(e,t){let n=Kc(t);if(!n.ok)return{code:null,error:n.error};try{return{code:xe({name:e,recipe:n.recipe}),error:null}}catch(e){return{code:null,error:e instanceof Error?e.message:String(e)}}}function Qc(e){if(!e.enabled)return{tone:`idle`,label:Y.t(`helpers.coreBlockStatus.disabled`),detail:Y.t(`helpers.coreBlockStatus.disabledDetail`)};switch(e.status){case`running`:return{tone:`ok`,label:Y.t(`helpers.coreBlockStatus.running`),detail:Y.t(`helpers.coreBlockStatus.runningDetail`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.coreBlockStatus.starting`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.startingDetail`)};case`failed`:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.failed`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.failedDetail`)};default:return{tone:`error`,label:Y.t(`helpers.coreBlockStatus.notRunning`),detail:e.lastError??Y.t(`helpers.coreBlockStatus.notRunningDetail`)}}}function $c(e){switch(e){case`ok`:return`success`;case`pending`:return`warning`;case`error`:return`danger`;default:return`default`}}function el(e,t){let n=e.find(e=>e.id===t.id);return n===void 0?t:n.updatedAt>=t.updatedAt?n:t}function tl(e){let t=e=>{let t=Qc(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 nl(e){if(e.length===0)return Y.t(`helpers.coreBlockStatus.noBlocks`);let t=e.filter(e=>Qc(e).tone===`error`).length,n=e.filter(e=>Qc(e).tone===`ok`).length,r=[Y.t(`helpers.coreBlockStatus.blocks`,{count:e.length})];return n>0&&r.push(Y.t(`helpers.coreBlockStatus.runningCount`,{count:n})),t>0&&r.push(Y.t(`helpers.coreBlockStatus.notRunningCount`,{count:t})),r.join(` · `)}var rl=3e4;function il({block:t,logsOpen:n,unreadable:r}){let i=S(),{t:a}=X(),s=Qc(t),c=bt(t.updatedAt,i);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(K,{variant:$c(s.tone),children:s.label}),c!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:a(`common.edited`,{when:c})})]}),(s.tone===`error`||s.tone===`pending`)&&o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:s.detail}),r!==null&&o(`p`,{className:`mt-0.5 text-xs text-warning`,children:a(`automation.editor.listUnreadable`,{reason:r})}),n&&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(gn,{i18nKey:`common.logsOf`,values:{id:ye(t.id)},components:{code:o(`code`,{})}})}),o(Et,{addonId:ye(t.id),maxHeight:`max-h-64`,showFilters:!1})]})]})}var al=2;function ol(e){let t=[];if(z(e.when,e=>{se(e)&&t.push(li(e.kind))}),t.length===0)return De(e.when)===0?``:Y.t(`automation.whenTree.stateOnly`);let n=[...new Set(t)],r=n.slice(0,al).join(`, `),i=n.length-al;return i>0?`${r} +${i}`:r}function sl({recipe:e}){let{t}=X();if(e===null)return o(`span`,{className:`text-foreground-subtle`,children:`-`});let n=ol(e);return n===``?o(`span`,{className:`text-foreground-subtle`,children:t(`automation.automationList.noTrigger`,`No trigger`)}):o(`span`,{children:n})}function cl({blockId:t}){let{t:n}=X(),r=Nt({blockId:t},{refetchInterval:rl});if(r.data===void 0)return r.error===null||r.error===void 0?o(At,{className:`h-4 w-16`}):o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.lastRunUnknown`,`Unknown`)});let i=r.data.traces.findLast(e=>!e.outcome.startsWith(`skipped-`));if(i===void 0)return o(`span`,{className:`text-foreground-subtle`,children:n(`automation.automationList.neverRan`,`Never ran`)});let a=i.outcome===`failed`||i.outcome===`aborted`;return e(`span`,{className:`inline-flex items-center gap-2`,children:[En(i.lastAt),a&&o(K,{variant:`danger`,children:n(`automation.automationList.lastRunFailed`,`Failed`)})]})}function ll({block:e,disabled:t,onToggle:n}){let{t:r}=X();return o(`span`,{className:`inline-flex`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(an,{checked:e.enabled,disabled:t,onCheckedChange:n,"aria-label":e.enabled?r(`automation.automationList.disableNamed`,`Disable {{name}}`,{name:e.name}):r(`automation.automationList.enableNamed`,`Enable {{name}}`,{name:e.name})})})}function ul({unreadable:e,onEdit:t,onToggleLogs:n,onDelete:r}){let{t:i}=X();return o(`span`,{className:`inline-flex justify-end`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:o(Rt,{items:[{id:`edit`,label:i(`common.edit`,`Edit`),icon:N,disabled:e!==null,description:e===null?void 0:i(`automation.automationList.thisBlockCannotBeOpened`,`This block cannot be opened visually`),onClick:t},{id:`run`,label:i(`automation.automationList.runActions`,`Run actions`),icon:g,disabled:!0,description:i(`automation.automationList.runNotAvailable`,`Not available yet`),onClick:()=>void 0},{id:`logs`,label:i(`automation.automationList.logs`,`Logs`),icon:w,onClick:n},{id:`delete`,label:i(`common.delete`,`Delete`),icon:k,danger:!0,separatorBefore:!0,onClick:r}]})})}function dl({onCreate:t}){let{t:n}=X();return o(qt,{icon:I,title:n(`automation.automationList.noAutomationsYet`,`No automations yet.`),action:e(G,{onClick:t,"data-testid":`automation-empty-new`,children:[o(D,{className:`h-4 w-4`}),` `,n(`automation.automationList.newAutomation`,`New automation`)]})})}u();var fl=[`coreBlocks`,`list`],pl=5e3;function ml(e){return e instanceof Error?e.message:String(e)}function hl({onOpenScripts:t,createRequested:n=!1,onCreateConsumed:i}){let{t:a}=X(),u=M(),{state:d,openNew:f,openEdit:m,close:h}=Ft({editKey:`block`,newKey:`new`}),g=j(),[_,v]=c(null),y=d.mode!==`closed`;s(()=>{n&&(f(),i?.())},[n,i,f]);let b=l({queryKey:fl,refetchInterval:pl,queryFn:async()=>(await u.trpcClient.coreBlocks.list.query({})).blocks}),x=()=>{b.refetch()},S=e=>{h(),x(),yn({title:a(`build.automationsTab.saved`,`Automation saved`),message:e.name,severity:`info`})},C=p({mutationFn:e=>u.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>S(e.block)}),w=p({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>S(e.block)}),T=p({mutationFn:e=>u.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:x}),E=p({mutationFn:e=>u.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:x}),D=p({mutationFn:e=>u.trpcClient.coreBlocks.update.mutate({blockId:e.id,block:{name:e.name,code:cr(e.code),enabled:e.enabled,placement:e.placement,...e.integrationId===void 0?{}:{integrationId:e.integrationId}}}),onSuccess:e=>{h(),x(),t(e.block.id)}}),O=b.data,k=tl((O??[]).filter(e=>ar(e.code))),A=O!==void 0&&k.length===0,N=d.mode===`edit`?k.find(e=>e.id===d.id)??null:null,P=d.mode===`edit`&&O!==void 0&&N===null;s(()=>{P&&h()},[P,h]);let F=N===null?null:sr(N.code),L=C.error===null?w.error===null?D.error===null?null:ml(D.error):ml(w.error):ml(C.error),R=r(()=>[{key:`name`,header:a(`build.automationsTab.automation`,`Automation`),nowrap:!1,render:e=>{let t=sr(e.code);return o(il,{block:e,logsOpen:_===e.id,unreadable:t.ok?null:t.reason})},sortValue:e=>e.name},{key:`trigger`,header:a(`build.automationsTab.trigger`,`Trigger`),render:e=>{let t=sr(e.code);return o(sl,{recipe:t.ok?t.recipe:null})},notSortableReason:a(`build.automationsTab.triggerNotSortable`,`Read from the recipe`)},{key:`lastRun`,header:a(`build.automationsTab.lastRun`,`Last run`),render:e=>o(cl,{blockId:e.id}),notSortableReason:a(`build.automationsTab.lastRunNotSortable`,`Read per automation`)},{key:`enabled`,header:a(`build.automationsTab.enabled`,`Enabled`),render:e=>o(ll,{block:e,disabled:E.isPending,onToggle:t=>E.mutate({blockId:e.id,enabled:t})}),sortValue:e=>+!!e.enabled},{key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,render:e=>{let t=sr(e.code);return o(ul,{unreadable:t.ok?null:t.reason,onEdit:()=>m(e.id),onToggleLogs:()=>v(_===e.id?null:e.id),onDelete:()=>{g({title:a(`automation.automationList.deleteThisAutomation`,`Delete this automation?`),message:a(`automation.automationList.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&T.mutate(e.id)})}})}}],[g,_,m,T,E,a]);return y?d.mode===`edit`&&N===null?o(At,{className:`h-24 w-full`}):e(`div`,{className:`space-y-3`,"data-testid":`automation-editor-panel`,children:[e(`h3`,{className:`flex items-center gap-2 text-sm font-semibold`,children:[o(I,{className:`h-4 w-4 text-foreground-muted`}),N===null?a(`build.automationsTab.newAutomation`,`New automation`):a(`build.automationsTab.edit`,`Edit {{name}}`,{name:N.name})]}),o(Yc,{existing:N,initialRecipe:F!==null&&F.ok?F.recipe:fi,saving:C.isPending||w.isPending,saveError:L,ejecting:D.isPending,onSave:e=>{N===null?C.mutate(e):w.mutate({blockId:N.id,block:e})},onEject:()=>{N!==null&&D.mutate(N)},onCancel:()=>{C.reset(),w.reset(),D.reset(),h()}},N?.id??`new`),T.error!=null&&o(q,{message:ml(T.error)})]}):e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:O===void 0?``:nl(k)}),b.error!=null&&o(q,{title:a(`build.automationsTab.couldNotReadTheAutomations`,`Could not read the automations`),message:ml(b.error),onRetry:x}),A?o(dl,{onCreate:f}):o(Dt,{columns:R,rows:k,rowKey:e=>e.id,pageSize:25,maxBodyHeight:jt,emptyMessage:O===void 0?a(`build.automationsTab.loadingAutomations`,`Loading automations…`):a(`build.automationsTab.noAutomationsYet`,`No automations yet.`),onRowClick:e=>m(e.id)}),T.error!=null&&o(q,{message:ml(T.error)}),E.error!=null&&o(q,{message:ml(E.error)})]})}var gl={kind:`all`,children:[]};function _l({value:t,devices:n,label:r,onChange:i}){let{t:a}=X(),s=t===void 0?null:{when:t,actions:[]};return e(`div`,{className:`space-y-2`,children:[o(an,{checked:t!==void 0,label:r,"aria-label":r,onCheckedChange:e=>i(e?gl:void 0)}),s!==null&&e(m,{children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.activeWhen.hint`,`Only states count here, such as "someone is home". While they are false, nothing runs and holds pause.`)}),o(Ms,{recipe:s,devices:n,onChange:e=>i(e.when)})]})]})}var vl=[`sunrise`,`sunset`,`dawn`,`dusk`],yl=6e4;function bl(e){return e.kind===`cap`||e.kind===`wait`}function xl(e,t){let n={id:e.id,at:e.at,mode:t,steps:t===`release`?[]:e.steps,...e.conditions===void 0?{}:{conditions:e.conditions}};return t===`hold`?{...n,...e.override===void 0?{}:{override:e.override},...e.maxHoldAttempts===void 0?{}:{maxHoldAttempts:e.maxHoldAttempts}}:n}function Sl({point:t,devices:n,site:r,localDate:i,issues:a,onChange:s,onRemove:c}){let{t:l}=X(),u=t.at,d=u.kind===`sun`?Po(u,r,i):null,f=Fo(u,r,i),p=t.override??{mode:`respect`},h=e=>s({...t,at:e});return e(`div`,{className:`space-y-3`,"data-testid":`point-editor`,children:[e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.kind`,`Point type`)}),o(F,{"aria-label":l(`schedulers.point.kind`,`Point type`),value:t.mode,options:[{value:`edge`,label:l(`schedulers.point.edge`,`Edge: run once`)},{value:`hold`,label:l(`schedulers.point.hold`,`Hold: keep true`)},{value:`release`,label:l(`schedulers.point.release`,`Release: end the hold`)}],onChange:e=>{let n=e.target.value;(n===`edge`||n===`hold`||n===`release`)&&s(xl(t,n))}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.when`,`When`)}),o(F,{"aria-label":l(`schedulers.point.when`,`When`),value:u.kind===`sun`?`sun`:`clock`,options:[{value:`clock`,label:l(`schedulers.point.clock`,`At a time`)},{value:`sun`,label:l(`schedulers.point.sun`,`At a sun event`)}],onChange:e=>{e.target.value===`sun`?h({kind:`sun`,event:`sunset`,offsetMin:0}):h({kind:`clock`,hh:12,mm:0})}})]}),u.kind===`clock`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.time`,`Time`)}),o(J,{type:`time`,"aria-label":l(`schedulers.point.time`,`Time`),value:Ro(u.hh,u.mm),onChange:e=>{let t=Lo(e.target.value);t!==null&&h(t)}})]}),u.kind===`sun`&&e(m,{children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.sunEvent`,`Sun event`)}),o(F,{"aria-label":l(`schedulers.point.sunEvent`,`Sun event`),value:u.event,options:vl.map(e=>({value:e,label:l(`schedulers.sun.${e}`,e)})),onChange:e=>{let t=vl.find(t=>t===e.target.value);t!==void 0&&h({...u,event:t})}})]}),e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.offset`,`Offset (minutes, negative = before)`)}),o(Hn,{"aria-label":l(`schedulers.point.offset`,`Offset (minutes, negative = before)`),className:`w-28`,value:u.offsetMin,onValue:e=>{e!==null&&h({...u,offsetMin:Math.round(e)})}})]}),o(`p`,{className:`pb-2 text-xs text-foreground-muted`,"data-testid":`sun-computed`,children:d===null||f===null?l(`schedulers.point.sunUnknown`,`No time today: the site location is not set.`):l(`schedulers.point.sunComputed`,`Today at {{time}} ({{zone}})`,{time:zo(d),zone:r.timeZone})})]}),e(G,{variant:`ghost`,className:`ml-auto`,onClick:c,"aria-label":l(`schedulers.point.remove`,`Remove point`),children:[o(k,{className:`h-4 w-4`}),` `,l(`schedulers.point.remove`,`Remove point`)]})]}),t.mode!==`release`&&o(cc,{actions:t.steps,devices:n,allowedKinds:[`cap`,`wait`],onChange:e=>s({...t,steps:e.filter(bl)})}),t.mode===`release`&&o(`p`,{className:`text-xs text-foreground-subtle`,children:l(`schedulers.point.releaseHint`,`A release ends the running hold without doing anything to the devices.`)}),t.mode===`hold`&&e(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.override`,`If someone changes it by hand`)}),o(F,{"aria-label":l(`schedulers.point.override`,`If someone changes it by hand`),value:p.mode,options:[{value:`respect`,label:l(`schedulers.point.respect`,`Leave it alone`)},{value:`reassert`,label:l(`schedulers.point.reassert`,`Put the hold back after a while`)}],onChange:e=>s({...t,override:e.target.value===`reassert`?{mode:`reassert`,graceMs:10*yl}:{mode:`respect`}})})]}),p.mode===`reassert`&&e(`label`,{className:`space-y-1 text-xs text-foreground-muted`,children:[o(`span`,{children:l(`schedulers.point.grace`,`Wait (minutes)`)}),o(Hn,{"aria-label":l(`schedulers.point.grace`,`Wait (minutes)`),className:`w-24`,value:p.graceMs/yl,onValue:e=>{e!==null&&s({...t,override:{mode:`reassert`,graceMs:Math.max(0,Math.round(e*yl))}})}})]})]}),a.length>0&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:a.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))})]})}u();var Cl=5e3,wl=600,Tl=6e4,El={timeZone:`UTC`,location:null};function Dl(e){return e instanceof Error?e.message:String(e)}function Ol(e){if(e===null)return Do();let{id:t,createdAt:n,updatedAt:r,...i}=e;return i}function kl(e,t){let[n,r]=c(e);return s(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}function Al(e,t){return t(`schedulers.day.${e}`,e)}function jl({entry:t,onClose:n,onSaved:i}){let{t:a}=X(),s=f(),l=j(),u=Un(),d=Zt(),p=d.data??El,[m,h]=c(()=>Ol(t)),[g,_]=c(()=>m.profiles[0]?.id??``),[v,y]=c(null),[b,x]=c(null),S=()=>{s.invalidateQueries({queryKey:[[`schedulers`]]})},C=Xt({onSuccess:e=>{S(),i(e.scheduler.id)}}),w=nt({onSuccess:S}),E=Ze({onSuccess:()=>{S(),n()}}),A=gt({schedulerId:t?.id??`none`},{enabled:t!==null,refetchInterval:Cl}),M=r(()=>Vo(m,p),[m,p]),N=m.profiles.some(e=>e.points.some(e=>e.mode===`hold`)),P=kl(M.ok?M.input:null,wl),F=vt(P===null?{scheduler:m}:t===null?{scheduler:P}:{scheduler:P,schedulerId:t.id},{enabled:P!==null&&N&&d.data!==void 0}),I=m.profiles.find(e=>e.id===g)??m.profiles[0],L=I===void 0?-1:m.profiles.indexOf(I),R=No(p),z=I?.points.find(e=>e.id===v)??null,ee=I===void 0||z===null?-1:I.points.indexOf(z),B=M.ok?[]:M.issues,V=e=>B.filter(t=>t.path===e||t.path.startsWith(`${e}.`)),H=e=>h({...m,profiles:m.profiles.map((t,n)=>n===L?e:t)}),te=e=>{I!==void 0&&H({...I,points:I.points.map(t=>t.id===e.id?e:t)})},ne=r(()=>I===void 0?[]:I.points.flatMap(e=>{let t=Po(e.at,p,R);if(t===null)return[];let n=e.at.kind===`sun`?`${a(`schedulers.sun.${e.at.event}`,e.at.event)} ${e.at.offsetMin>=0?`+`:``}${String(e.at.offsetMin)} (${zo(t)})`:Ro(e.at.hh,e.at.mm);return[{id:e.id,minute:t,label:n,tone:e.mode===`hold`?`success`:e.mode===`release`?`neutral`:`primary`,draggable:e.at.kind===`clock`||e.at.kind===`sun`&&Fo(e.at,p,R)!==null}]}),[I,p,R,a]),re=r(()=>I===void 0?[]:Bo(I.points,p,R),[I,p,R]),U=(e,t)=>{let n=I?.points.find(t=>t.id===e);n!==void 0&&te({...n,at:Io(n.at,t,Fo(n.at,p,R))})},ie=e=>{if(I===void 0)return;let t=Ao(`point`,m.profiles.flatMap(e=>e.points.map(e=>e.id)));H({...I,points:[...I.points,ko(e,t,720)]}),y(t)},ae=()=>{let e=Ao(`profile`,m.profiles.map(e=>e.id));h({...m,profiles:[...m.profiles,Oo(e,a(`schedulers.profile.newName`,`New profile`))]}),_(e),y(null)},oe=C.isPending||w.isPending,se=C.error??w.error??E.error;return e(`div`,{className:`grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]`,"data-testid":`scheduler-editor`,children:[e(`div`,{className:`space-y-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(O,{className:`h-4 w-4 text-foreground-muted`}),o(J,{"aria-label":a(`schedulers.editor.name`,`Name`),className:`max-w-xs flex-1`,value:m.name,placeholder:a(`schedulers.editor.namePlaceholder`,`What this scheduler does`),onChange:e=>h({...m,name:e.target.value})})]}),e(kt,{headingId:`scheduler-settings`,title:a(`schedulers.editor.settings`,`Settings`),children:[e(`div`,{className:`divide-y divide-border px-3`,children:[o(ot,{label:a(`schedulers.editor.enabled`,`Enabled`),children:o(an,{checked:m.enabled,"aria-label":a(`schedulers.editor.enabled`,`Enabled`),onCheckedChange:e=>h({...m,enabled:e})})}),o(ot,{label:a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),children:o(Hn,{"aria-label":a(`schedulers.editor.priority`,`Priority (higher wins a conflict)`),className:`w-24`,value:m.priority,onValue:e=>{e!==null&&h({...m,priority:Math.round(e)})}})}),o(ot,{label:a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),children:o(Hn,{"aria-label":a(`schedulers.editor.maxLate`,`Run a missed point up to (minutes late)`),className:`w-24`,value:m.maxLateMs/Tl,onValue:e=>{e!==null&&h({...m,maxLateMs:Math.round(e*Tl)})}})})]}),e(`div`,{className:`p-3`,children:[o(_l,{value:m.activeWhen,devices:u,label:a(`schedulers.editor.activeWhen`,`Only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=m;h(e===void 0?n:{...n,activeWhen:e})}}),V(`activeWhen`).map(e=>o(`p`,{className:`mt-1 text-xs text-warning`,children:e.message},e.message))]})]}),o(kt,{headingId:`scheduler-profiles`,title:a(`schedulers.editor.profiles`,`Profiles`),actions:e(G,{variant:`outline`,size:`sm`,onClick:ae,children:[o(D,{className:`h-4 w-4`}),` `,a(`schedulers.profile.add`,`Add profile`)]}),children:e(`div`,{className:`space-y-3 p-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.profile.hint`,`Each day, the first profile in this order whose days and condition hold is the one that runs.`)}),I!==void 0&&e(zt,{value:I.id,onValueChange:e=>{_(e),y(null)},appearance:`pills`,children:[o(ln,{children:m.profiles.map(e=>o(Ht,{value:e.id,children:e.name},e.id))}),e(nn,{value:I.id,className:`space-y-3 pt-3`,children:[e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[o(J,{"aria-label":a(`schedulers.profile.name`,`Profile name`),className:`max-w-xs`,value:I.name,onChange:e=>H({...I,name:e.target.value})}),o(an,{checked:I.enabled,label:a(`schedulers.profile.enabled`,`Enabled`),onCheckedChange:e=>H({...I,enabled:e})}),m.profiles.length>1&&e(G,{variant:`ghost`,size:`sm`,onClick:()=>{h({...m,profiles:m.profiles.filter(e=>e.id!==I.id)}),_(``),y(null)},children:[o(k,{className:`h-4 w-4`}),` `,a(`schedulers.profile.remove`,`Remove profile`)]})]}),o(`div`,{className:`flex flex-wrap gap-1`,role:`group`,"aria-label":a(`schedulers.profile.days`,`Days`),children:wo.map(e=>{let t=I.days.includes(e);return o(G,{size:`sm`,variant:t?`primary`:`outline`,"aria-pressed":t,onClick:()=>H({...I,days:t?I.days.filter(t=>t!==e):wo.filter(t=>t===e||I.days.includes(t))}),children:Al(e,a)},e)})}),V(`profiles.${String(L)}.days`).map(e=>o(`p`,{className:`text-xs text-warning`,children:a(`schedulers.profile.daysNeeded`,`Pick at least one day.`)},e.message)),o(_l,{value:I.activeWhen,devices:u,label:a(`schedulers.profile.activeWhen`,`This profile only when a condition holds`),onChange:e=>{let{activeWhen:t,...n}=I;H(e===void 0?n:{...n,activeWhen:e})}}),o(Vt,{ariaLabel:a(`schedulers.timeline.label`,`Day timeline`),markers:ne,bands:re,selectedId:v,onSelect:y,onMove:U}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{variant:`outline`,size:`sm`,onClick:()=>ie(`edge`),children:[o(D,{className:`h-4 w-4`}),` `,a(`schedulers.point.addEdge`,`Edge`)]}),e(G,{variant:`outline`,size:`sm`,onClick:()=>ie(`hold`),children:[o(D,{className:`h-4 w-4`}),` `,a(`schedulers.point.addHold`,`Hold`)]}),e(G,{variant:`outline`,size:`sm`,onClick:()=>ie(`release`),children:[o(D,{className:`h-4 w-4`}),` `,a(`schedulers.point.addRelease`,`Release`)]}),o(K,{variant:`neutral`,children:p.timeZone})]}),I.points.length===0&&o(`p`,{className:`text-xs text-foreground-subtle`,children:a(`schedulers.timeline.empty`,`Add a point to place something on the day.`)}),z!==null&&o(Sl,{point:z,devices:u,site:p,localDate:R,issues:V(`profiles.${String(L)}.points.${String(ee)}`),onChange:te,onRemove:()=>{H({...I,points:I.points.filter(e=>e.id!==z.id)}),y(null)}},z.id)]})]})]})}),F.data!==void 0&&F.data.conflicts.length>0&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:F.data.conflicts.map(e=>o(`li`,{children:a(`schedulers.conflict.message`,`{{other}} wants device {{device}} in another state from {{from}} to {{to}} ({{winner}}).`,{other:e.other.schedulerName,device:e.deviceId,from:zo(e.fromMinute),to:zo(e.toMinute),winner:e.winner===`mine`?a(`schedulers.conflict.mine`,`this one wins`):e.winner===`other`?a(`schedulers.conflict.other`,`the other one wins`):a(`schedulers.conflict.tie`,`the one that started first wins`)})},`${e.other.schedulerId}:${e.other.pointId}:${e.mine.pointId}:${String(e.deviceId)}`))}),!M.ok&&m.name!==``&&B.length>0&&z===null&&o(`ul`,{className:`space-y-1 rounded border border-warning/40 bg-warning/10 p-3 text-xs text-warning`,children:B.map(e=>o(`li`,{children:e.message},`${e.path}:${e.message}`))}),se!==null&&o(q,{message:Dl(se)}),e(`div`,{className:`flex flex-wrap gap-2`,children:[e(G,{onClick:()=>{M.ok&&(t===null?C.mutate({scheduler:M.input}):w.mutate({schedulerId:t.id,scheduler:M.input}))},disabled:oe||!M.ok||d.data===void 0,children:[oe&&o(T,{className:`h-4 w-4 animate-spin`}),` `,a(`common.save`,`Save`)]}),t!==null&&e(G,{variant:`ghost`,disabled:E.isPending,onClick:()=>{l({title:a(`schedulers.editor.deleteTitle`,`Delete this scheduler?`),message:a(`schedulers.editor.deleteMessage`,`{{name}} will be deleted and any hold it keeps will stop.`,{name:t.name}),confirmLabel:a(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&E.mutate({schedulerId:t.id})})},children:[o(k,{className:`h-4 w-4`}),` `,a(`common.delete`,`Delete`)]}),o(G,{variant:`ghost`,onClick:n,children:a(`common.close`,`Close`)})]})]}),o(`div`,{className:`order-first lg:order-last`,children:o(Lr,{traces:t===null?[]:A.data?.traces,selectedId:b,onSelect:x})})]})}u();var Ml=5e3;function Nl(e){return e instanceof Error?e.message:String(e)}function Pl({createRequested:t=!1,onCreateConsumed:n}){let{t:i}=X(),a=f(),{state:c,openNew:l,openEdit:u,close:d}=Ft({editKey:`scheduler`,newKey:`new`}),p=_t({},{refetchInterval:Ml}),m=Yt({},{refetchInterval:Ml}),h=xt({onSuccess:()=>void a.invalidateQueries({queryKey:[[`schedulers`]]})});s(()=>{t&&(l(),n?.())},[t,n,l]);let g=p.data??[],_=c.mode===`edit`?g.find(e=>e.id===c.id)??null:null,v=e=>{if(!e.enabled)return{variant:`neutral`,label:i(`schedulers.status.off`,`Off`)};let t=m.data?.find(t=>t.schedulerId===e.id);return t===void 0?{variant:`neutral`,label:`-`}:t.hold===null?{variant:`neutral`,label:i(`schedulers.status.idle`,`Idle`)}:t.hold.suspendedInactive?{variant:`warning`,label:i(`schedulers.status.paused`,`Paused`)}:t.hold.targets.some(e=>e.status===`gave-up`)?{variant:`danger`,label:i(`schedulers.status.gaveUp`,`Gave up`)}:{variant:`success`,label:i(`schedulers.status.holding`,`Holding`)}},y=r(()=>[{key:`name`,header:i(`schedulers.list.name`,`Name`),render:e=>o(`span`,{className:`font-medium`,children:e.name}),sortValue:e=>e.name},{key:`enabled`,header:i(`schedulers.list.enabled`,`Enabled`),render:e=>o(`span`,{onClick:e=>e.stopPropagation(),children:o(an,{checked:e.enabled,disabled:h.isPending,"aria-label":i(`schedulers.list.enabledAria`,`Enable {{name}}`,{name:e.name}),onCheckedChange:t=>h.mutate({schedulerId:e.id,enabled:t})})}),sortValue:e=>Number(e.enabled)},{key:`profiles`,header:i(`schedulers.list.profiles`,`Profiles`),render:e=>String(e.profiles.length),sortValue:e=>e.profiles.length},{key:`priority`,header:i(`schedulers.list.priority`,`Priority`),render:e=>String(e.priority),sortValue:e=>e.priority},{key:`status`,header:i(`schedulers.list.status`,`Now`),render:e=>{let t=v(e);return o(K,{variant:t.variant,children:t.label})},notSortableReason:i(`schedulers.list.statusNotSortable`,`Derived from the live hold`)},{key:`updated`,header:i(`schedulers.list.updated`,`Updated`),render:e=>En(e.updatedAt),sortValue:e=>e.updatedAt}],[h,m.data,i]);return c.mode===`closed`?e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:i(`schedulers.list.hint`,`A scheduler does things over the day: run something at a time or at sunset, or keep a device in a state for a stretch of time.`)}),h.error!=null&&o(q,{message:Nl(h.error)}),p.data===void 0?p.error==null?o(At,{className:`h-24 w-full`}):o(q,{title:i(`schedulers.list.couldNotRead`,`Could not read the schedulers`),message:Nl(p.error),onRetry:()=>void p.refetch()}):g.length===0?o(qt,{icon:O,title:i(`schedulers.list.emptyTitle`,`No schedulers yet`),description:i(`schedulers.list.emptyDescription`,`A scheduler turns the garden lights on at sunset and off at 23:00, every day or only on some days.`),action:e(G,{onClick:l,children:[o(D,{className:`h-4 w-4`}),` `,i(`schedulers.list.new`,`New scheduler`)]})}):o(Dt,{columns:y,rows:g,rowKey:e=>e.id,pageSize:25,maxBodyHeight:jt,emptyMessage:i(`schedulers.list.emptyTitle`,`No schedulers yet`),onRowClick:e=>u(e.id)})]}):o(jl,{entry:_,onClose:d,onSaved:u},_?.id??`new`)}async function Fl(e,t){let n=`${ae}${e}`;return(await t())?.find(e=>e.stableId===n)?.id??null}var Il=10,Ll=400;async function Rl(e,t,n=Ll){for(let r=0;r<Il;r+=1){let r=await Fl(e,t);if(r!==null)return r;await new Promise(e=>setTimeout(e,n))}return null}var zl=`media-player`;function Bl(e){return e===Ne.MediaPlayer?`media-source`:`none`}function Vl(e){return e===Ne.MediaPlayer?{fieldChoice:`operator`,purpose:`member`,multiple:!1,max:1,deviceTypes:[Ne.MediaPlayer],accept:[{cap:zl,fieldPath:`state`,valueKind:`state`}],history:{required:!1,minRetentionMs:null},mustBindCaps:[zl],exclude:[]}:null}function Hl(e){return e===null||e.cap!==`media-player`?[]:[{kind:`fields`,cap:zl,fields:{},commands:Object.fromEntries(Object.keys(Ae()).map(t=>[t,{kind:`forward`,source:e.source,cap:zl,method:t}]))}]}function Ul(e,t){let n=e===Ne.MediaPlayer?Hl(t):[];return{target:{kind:`new`,type:e},features:n}}u();function Wl({onTitle:t}){let{t:n}=X(),r=S(),i=vn(),a=Yn(),l=Bt(),u=Ot({addonId:`composer`}),[d,f]=c(Ne.Sensor),[p,m]=c(``),[h,g]=c([]),[_,v]=c(null),y=h[0]??null,b=Vl(d),x=Ul(d,y);s(()=>{t(n(`helper.newDevice`))},[t,n]);let C=async()=>{v(null);try{let e=p.trim(),{block:t}=await a.mutateAsync({block:{...e===``?{}:{name:e},enabled:!0,composition:x}}),r=await Rl(t.id,async()=>(await u.refetch()).data??u.data);if(r===null){v(n(`helper.devicePending`));return}e!==``&&await l.mutateAsync({deviceId:r,name:e}),i(Sn(r),{replace:!0})}catch(e){v(e instanceof Error?e.message:String(e))}};return e(`div`,{className:`flex flex-col gap-3`,"data-testid":`device-create-form`,children:[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:[n(`compositionEditor.targetType`),o(F,{value:d,onChange:e=>{let t=Object.values(Ne).find(t=>t===e.target.value);t!==void 0&&(f(t),g([]))},options:Object.values(Ne).map(e=>({value:e,label:Ye(e,r).label}))})]}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[n(`compositionEditor.name`),o(J,{"aria-label":n(`compositionEditor.name`),value:p,onChange:e=>m(e.target.value)})]})]}),b!==null&&e(`div`,{className:`flex flex-col gap-1`,"data-testid":`device-create-source`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:n(`helper.deviceSource.${Bl(d)}`)}),o(An,{kind:`members`,request:b,enabled:!0,members:h,onMembersChange:g,onRefuse:()=>void 0})]}),_!==null&&o(`p`,{role:`alert`,className:`text-xs text-danger`,children:_}),o(G,{disabled:a.isPending,onClick:()=>void C(),children:n(`compositionEditor.save`)})]})}u();function Gl({preset:t,saving:n,onSave:i,onBack:a}){let{t:s,i18n:l}=X(),u=In(!0),[d,f]=c({}),[p,m]=c(s(t.nameKey)),[h,g]=c(null),[_,v]=c([]),[y,b]=c(!1),x=r(()=>u.kind===`known`?new Map(u.value.map(e=>[U({addonId:e.addonId,stableId:e.stableId}),e.name])):new Map,[u]),S=r(()=>new Set(Object.values(d).flatMap(e=>e===void 0?[]:[U(e)])),[d]),C=r(()=>u.kind===`known`?{kind:`known`,value:Dn(u.value,S)}:u,[u,S]),w=Rn(t,d),T=u.kind===`known`?zn(u.value,w,!1):null,E=t.build(d),D=Nn(t,d),O=(e,t)=>{v([]),f(n=>({...n,[e]:t}))},k=e=>x.get(U(e))??e.stableId;return e(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`preset-wizard`,children:[o(`p`,{className:`text-[11px] text-foreground-muted`,children:s(t.descriptionKey)}),e(`label`,{className:`flex flex-col gap-1 text-[11px]`,children:[s(`preset.name`),o(J,{"aria-label":s(`preset.name`),value:p,onChange:e=>m(e.target.value)})]}),o(`ul`,{className:`flex flex-col gap-2`,"aria-label":s(`preset.slots`),children:t.slots.map(t=>{let n=d[t.key];return e(`li`,{className:`grid grid-cols-1 gap-1 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-center`,"data-testid":`preset-slot-${t.key}`,children:[e(`div`,{className:`min-w-0`,children:[e(`div`,{className:`text-xs text-foreground`,children:[s(t.labelKey),t.optionalGroup===void 0?` *`:``]}),e(`div`,{className:`text-[11px] text-foreground-muted break-words`,children:[Pn(t.expectedCap,l.language),t.optionalGroup===void 0?``:` · ${s(`preset.optional`)}`]})]}),e(`div`,{className:`flex flex-wrap gap-1`,children:[o(G,{variant:`outline`,size:`sm`,onClick:()=>g(t),children:n===void 0?s(`preset.choose`):k(n)}),n!==void 0&&t.optionalGroup!==void 0&&o(G,{variant:`ghost`,size:`sm`,onClick:()=>O(t.key,void 0),children:s(`preset.clear`)})]})]},t.key)})}),E===null&&D.length>0&&o(`p`,{className:`text-[11px] text-foreground-muted`,"data-testid":`preset-missing`,children:s(`preset.missing`,{slots:D.map(e=>s(e.labelKey)).join(`, `)})}),E!==null&&e(`section`,{className:`flex flex-col gap-1`,"data-testid":`preset-preview`,children:[o(`h3`,{className:`text-xs font-medium text-foreground`,children:s(`preset.preview`)}),o(`ul`,{className:`flex flex-col gap-1 text-[11px] text-foreground-muted`,children:E.features.map(e=>e.kind===`fields`?o(`li`,{children:s(`preset.previewFeature`,{cap:Pn(e.cap,l.language),fields:Object.keys(e.fields).length,commands:Object.keys(e.commands??{}).length+Object.values(e.items??{}).filter(e=>e.reset!==void 0).length})},e.cap):null)})]}),o(Ln,{lines:_,testId:`preset-refusals`}),e(`div`,{className:`mt-auto flex flex-wrap gap-2`,children:[o(G,{disabled:E===null||n||y,onClick:()=>{E===null||y||(b(!0),i(E,p.trim()).then(e=>{e.kind===`refused`&&v(e.lines)}).finally(()=>b(!1)))},"data-testid":`preset-create`,children:s(`preset.create`)}),o(G,{variant:`ghost`,onClick:a,children:s(`preset.back`)})]}),o(jn,{open:h!==null,title:h===null?``:s(`preset.pickTitle`,{slot:s(h.labelKey)}),selection:`single`,candidates:C,room:T,confirmLabel:()=>s(`preset.pickConfirm`),onConfirm:e=>{let t=e[0],n=h;g(null),t!==void 0&&n!==null&&O(n.key,t.ref)},onClose:()=>g(null)})]})}u();var Kl=`preset`;function ql({mode:e,onTitle:t}){return o(e===`helper`?Jl:Wl,{onTitle:t})}function Jl({onTitle:e}){let{t}=X(),r=vn(),i=Yn(),a=Bt(),l=Ot({addonId:`composer`}),[u,d]=c(null),[f,p]=c(!1),[m,h]=_n(),g=kn(m.get(Kl)),_=g===null?Yl(u,t):t(g.labelKey);s(()=>{f||e(_)},[e,_,f]);let v=e=>h(t=>{let n=new URLSearchParams(t);return e===null?n.delete(Kl):n.set(Kl,e),n},{replace:!0}),y=async(e,n)=>{try{let{block:o}=await i.mutateAsync({block:{...n===``?{}:{name:n},enabled:!0,composition:e}}),s=await Rl(o.id,async()=>(await l.refetch()).data??l.data);return s===null?{kind:`refused`,lines:Mn(t(`helper.devicePending`))}:(n!==``&&await a.mutateAsync({deviceId:s,name:n}),r(Sn(s),{replace:!0}),{kind:`saved`,deviceId:s})}catch(e){return{kind:`refused`,lines:Mn(e instanceof Error?e.message:String(e))}}},b=n(null);return f?o(Wl,{onTitle:e}):g===null?o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Fn,{fillHeight:!0,onDevice:()=>p(!0),onPreset:v,purpose:`create`,initial:null,start:`template`,saving:i.isPending,onDraftChange:d,onSave:async(e,n)=>{let o=null,s=await Bn(e,async(s,c)=>{let u=b.current,d;if(u!==null&&u.draft===e)d=u.blockId;else{let{block:t}=await i.mutateAsync({block:{...c===``?{}:{name:c},enabled:!0,composition:s}});d=t.id,b.current={draft:e,blockId:d}}let f=await Rl(d,async()=>(await l.refetch()).data??l.data);if(f===null)throw Error(t(`helper.devicePending`));o=f,b.current=null,c!==``&&await a.mutateAsync({deviceId:f,name:c}),n===`open`&&r(xn(f),{replace:!0})}),c=o;return s.length>0||c===null?{kind:`refused`,lines:Xl(s,t)}:{kind:`saved`,deviceId:c}}})}):o(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3`,"data-testid":`composition-create-form`,children:o(Gl,{preset:g,saving:i.isPending,onSave:y,onBack:()=>v(null)})})}function Yl(e,t){if(e===null)return t(`helper.newComposed`);if(e.kind===`statistic`)return t(`helper.newTitle.statistic`);if(e.kind===`integral`)return t(`helper.newTitle.integral`);if(e.kind===`arithmetic`)return t(`helper.newTitle.${e.op}`);if(e.kind===`threshold`||e.kind===`expression`||e.kind===`derivative`)return t(`helper.newTitle.${e.kind}`);let n=Oe(e.templateId);return t(n===null?`helper.newComposed`:`helper.newTitle.${n.id}`)}function Xl(e,t){return e.length>0?e:Mn(t(`helper.devicePending`))}function Zl(e){let t=e.helper;if(t===void 0)return{section:`advanced`,kind:null};switch(t.kind){case`group`:return{section:`group`,kind:t.templateId};case`arithmetic`:return{section:`calculation`,kind:t.op};case`expression`:return{section:`advanced`,kind:`expression`};default:return{section:`calculation`,kind:t.kind}}}function Ql(e){return{state:`answered`,byRef:new Map(e.map(e=>[U(e),e]))}}function $l(e,t){if(e.state!==`unanswered`)return e.byRef.get(U(t))??null}function eu(e){return e===void 0?`unknown`:e===null?`missing`:`present`}function tu(e){return _e(e).map(e=>e.source)}function nu(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(...tu(t));for(let t of Object.values(e.items??{}))for(let e of Object.values(t.fields))n.push(...tu(e))}let r=new Set;return n.filter(e=>{let t=U(e);return r.has(t)?!1:(r.add(t),!0)})}function ru(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:Y.t(`helpers.compositionRows.running`),reason:null};let r=[...t.length>0?[Y.t(`helpers.compositionRows.fieldsUnavailable`,{count:t.length})]:[],...n.length>0?[Y.t(`helpers.compositionRows.fieldsStale`,{count:n.length})]:[]].join(`, `),i=t[0]??n[0],a=i===void 0?``:` — ${i.cap}.${i.path}: ${i.reason??Y.t(`helpers.compositionRows.noReason`)}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.running`),reason:`${r}${a}`}}function iu(e,t){let n=e.reason??t??null;switch(e.status){case`running`:return ru(e);case`degraded`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.degraded`),reason:n??Y.t(`helpers.compositionRows.degradedReason`)};case`starting`:return{tone:`pending`,label:Y.t(`helpers.compositionRows.starting`),reason:n};case`failed`:return{tone:`error`,label:Y.t(`helpers.compositionRows.failed`),reason:n??Y.t(`helpers.compositionRows.failedReason`)};default:return{tone:`error`,label:Y.t(`helpers.compositionRows.notRunning`),reason:n??Y.t(`helpers.compositionRows.notRunningReason`)}}}function au(e){let{block:t,state:n}=e;if(!t.enabled)return{tone:`idle`,label:Y.t(`helpers.compositionRows.off`),reason:null};if(n.kind===`unreachable`)return{tone:`pending`,label:Y.t(`helpers.compositionRows.unknown`),reason:Y.t(`helpers.compositionRows.unreachable`,{error:n.error})};if(n.state!==null)return iu(n.state,t.lastError);let r=t.lastError===void 0?t.status:`${t.status}: ${t.lastError}`;return{tone:`pending`,label:Y.t(`helpers.compositionRows.notReported`),reason:Y.t(`helpers.compositionRows.noRecord`,{stored:r})}}function ou(e){return U(e)}function su(e,t){let n=$l(t,e);return{key:U(e),label:n?n.name:ou(e),presence:eu(n),deviceId:n?n.id:null}}function cu(e){return e.state.kind===`answered`&&e.state.state!==null?e.state.state.deviceId:null}function lu(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:W(e.block.id),a=U(i),o=nu(e).filter(e=>U(e)!==a).map(e=>su(e,t)),s=n.features.map(e=>e.enabled===!1?Y.t(`helpers.compositionRows.featureOff`,{cap:e.cap}):e.cap),c=$l(t,i),l=cu(e),u=au(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}`,origin:Zl(n),features:s,state:u,sources:o,reportedDeviceId:l};let d=eu(c);return{blockId:e.block.id,kind:`customization`,name:c?c.name:ou(r.device),namePresence:d,type:c?c.type:null,origin:Zl(n),features:s,state:u,sources:o,reportedDeviceId:l}}function uu(e){return e.state.tone===`error`?0:e.state.tone===`pending`?1:e.state.tone===`ok`?2:3}function du(e,t){return uu(e)-uu(t)||e.name.localeCompare(t.name)}function fu(e,t){let n=e.flatMap(e=>{let n=lu(e,t);return n===null?[]:[n]});return{composed:n.filter(e=>e.kind===`composed`).toSorted(du),customizations:n.filter(e=>e.kind===`customization`).toSorted(du)}}u();var pu=1e4;function mu(e){return e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):String(e)}function hu(){let e=hn();return e.data===void 0?{state:`unanswered`,reason:e.error==null?Y.t(`build.customDeviceTab.deviceListPending`):Y.t(`build.customDeviceTab.deviceListUnreadable`,{error:mu(e.error)})}:Ql(e.data)}function gu(e,t){return e===`blank`?`blank`:e===`helper`||e===`1`||t?`helper`:null}function _u({createRequested:t=!1,onCreateConsumed:n}={}){let{t:r}=X(),[i,a]=_n(),s=Ct({},{refetchInterval:pu}),l=hu(),u=Ft({editKey:`block`,newKey:`new`}),d=u.state.mode===`edit`?u.state.id:null,f=d===null?gu(i.get(`new`),t):null,p=f!==null,[h,g]=c(``),_=j(),v=rt(),y=()=>{u.close(),a(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`new`),e.delete(`block`),e},{replace:!0}),n?.()},b=s.data;return e(m,{children:[yu(b,s.error,()=>void s.refetch(),l,{onEditComposed:e=>u.openEdit(e),deleting:v.isPending,onDelete:e=>{_({title:r(`build.customDeviceTab.deleteThisComposedDevice`,`Delete this composed device?`),message:r(`build.customDeviceTab.deleteMessage`,`{{name}} will be deleted. This cannot be undone.`,{name:e.name}),confirmLabel:r(`common.delete`,`Delete`),variant:`danger`}).then(t=>{t&&v.mutate({blockId:e.blockId},{onSuccess:()=>void s.refetch()})})}}),o(St,{open:p,onClose:y,title:h||r(f===`blank`?`helper.newComposition`:`helper.newComposed`),icon:Ue,width:`xl`,testId:`composed-device-editor`,fill:!0,children:f!==null&&o(ql,{mode:f,onTitle:g},f)}),o(Gn,{blockId:d,onClose:y}),v.error!=null&&o(q,{message:mu(v.error)})]})}function vu(t){return o(Je,{children:e(`div`,{className:`space-y-1 p-4`,children:[o(`p`,{className:`text-sm text-warning`,children:Y.t(`build.customDeviceTab.theCompositionStoreHasNot`,`The composition store has not been read yet.`)}),e(`p`,{className:`text-xs text-foreground-subtle`,children:[Y.t(`build.customDeviceTab.thisIsNotTheSame`,`This is not the same as having none — the list appears once the hub has read it (`),t,`).`]})]})})}function yu(e,t,n,r,i){if(t!=null&&e===void 0)return o(q,{title:Y.t(`build.customDeviceTab.couldNotReadTheCompositions`,`Could not read the compositions`),message:mu(t),onRetry:n});if(e===void 0)return o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:Y.t(`build.customDeviceTab.loadingCompositions`,`Loading compositions…`)});if(e.state===`not-loaded`)return vu(e.reason);let a=t==null?null:mu(t);return o(bu,{lists:fu(e.views,r),fleet:r,refreshError:a,handlers:i})}function bu({lists:t,fleet:n,refreshError:r,handlers:i}){let{t:a}=X();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(xu,{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`,handlers:i}),o(xu,{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`,handlers:i})]})}function xu({title:t,hint:n,rows:r,nameHeader:i,emptyMessage:a,kind:s,handlers:c}){let{t:l}=X();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(Dt,{columns:Su(i,s,c,l),rows:r,rowKey:e=>e.blockId,pageSize:25,maxBodyHeight:jt,emptyMessage:a,onRowClick:s===`composed`?e=>c.onEditComposed(e.blockId):void 0})]})}function Su(t,n,r,i){let a=[{key:`name`,header:t,sortValue:e=>e.name.toLowerCase(),render:e=>o(wu,{row:e})},{key:`type`,header:Y.t(`build.customDeviceTab.type`,`Type`),sortValue:e=>e.type,render:e=>o(`span`,{className:`text-xs text-foreground-subtle`,children:e.type??Y.t(`common.unknownWord`)})},...n===`composed`?[{key:`origin`,header:Y.t(`build.customDeviceTab.builtAs`,`Built as`),sortValue:e=>Cu(e.origin,i),render:e=>o(K,{variant:`default`,"data-testid":`composed-origin-badge`,children:Cu(e.origin,i)})}]:[],{key:`state`,header:Y.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(K,{variant:$c(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:Y.t(`build.customDeviceTab.sources`,`Sources`),nowrap:!1,notSortableReason:`A list of devices has no single order.`,render:e=>o(Eu,{sources:e.sources})}];return n===`composed`&&a.push({key:`actions`,header:``,align:`right`,notSortableReason:`Row actions`,nowrap:!0,render:t=>e(`div`,{className:`flex justify-end gap-1`,children:[o(G,{variant:`ghost`,title:i(`common.edit`,`Edit`),onClick:e=>{e.stopPropagation(),r.onEditComposed(t.blockId)},children:i(`common.edit`,`Edit`)}),o(G,{variant:`ghost`,title:i(`common.delete`,`Delete`),disabled:r.deleting,"aria-label":i(`common.delete`,`Delete`),onClick:e=>{e.stopPropagation(),r.onDelete(t)},children:o(k,{className:`h-4 w-4`})})]})}),a}function Cu(e,t){let n=e.kind===null?null:t(`helper.template.${e.kind}`);return e.section===`group`?t(`helper.badge.group`,{kind:n}):e.section===`calculation`?t(`helper.badge.calculation`,{kind:n}):n===null?t(`helper.badge.advanced`):t(`helper.badge.advancedKind`,{kind:n})}function wu({row:t}){let{t:n}=X();return e(`div`,{className:`space-y-0.5`,children:[o(Tu,{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 Tu({row:e}){let{t}=X(),n=Wt(e.reportedDeviceId??0,`compact`,e.name),r=e.reportedDeviceId===null?e.name:n;return e.reportedDeviceId===null?e.kind===`composed`?o(`span`,{className:`text-xs font-medium text-foreground`,children:e.name}):o(`span`,{className:`text-xs text-foreground-subtle`,children:t(`build.customDeviceTab.notReported`,{name:r})}):o(Cn,{to:e.kind===`composed`?xn(e.reportedDeviceId):Sn(e.reportedDeviceId),className:`text-xs font-medium text-foreground hover:underline`,onClick:e=>e.stopPropagation(),children:r})}function Eu({sources:t}){let{t:n}=X();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(Cn,{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 Du(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 Ou(e){if(Array.isArray(e))return e}function ku(e,t,n){return(t=Ru(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Au(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 ju(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
5
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Mu(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 Nu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Mu(Object(n),!0).forEach(function(t){ku(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Mu(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Pu(e,t){if(e==null)return{};var n,r,i=Fu(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 Fu(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 Iu(e,t){return Ou(e)||Au(e,t)||zu(e,t)||ju()}function Lu(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 Ru(e){var t=Lu(e,`string`);return typeof t==`symbol`?t:t+``}function zu(e,t){if(e){if(typeof e==`string`)return Du(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)?Du(e,t):void 0}}function Bu(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Vu(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 Hu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Vu(Object(n),!0).forEach(function(t){Bu(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Vu(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Uu(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}}function Wu(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 Gu(e){return{}.toString.call(e).includes(`Object`)}function Ku(e){return!Object.keys(e).length}function qu(e){return typeof e==`function`}function Ju(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Yu(e,t){return Gu(t)||ed(`changeType`),Object.keys(t).some(function(t){return!Ju(e,t)})&&ed(`changeField`),t}function Xu(e){qu(e)||ed(`selectorType`)}function Zu(e){qu(e)||Gu(e)||ed(`handlerType`),Gu(e)&&Object.values(e).some(function(e){return!qu(e)})&&ed(`handlersType`)}function Qu(e){e||ed(`initialIsRequired`),Gu(e)||ed(`initialType`),Ku(e)&&ed(`initialContent`)}function $u(e,t){throw Error(e[t]||e.default)}var ed=Wu($u)({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"}),td={changes:Yu,selector:Xu,handler:Zu,initial:Qu};function nd(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};td.initial(e),td.handler(t);var n={current:e},r=Wu(ad)(n,t),i=Wu(id)(n),a=Wu(td.changes)(e),o=Wu(rd)(n);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:function(e){return e};return td.selector(e),e(n.current)}function c(e){Uu(r,i,a,o)(e)}return[s,c]}function rd(e,t){return qu(t)?t(e.current):t}function id(e,t){return e.current=Hu(Hu({},e.current),t),t}function ad(e,t,n){return qu(t)?t(e.current):Object.keys(n).forEach(function(n){return t[n]?.call(t,e.current[n])}),n}var od={create:nd},sd={paths:{vs:`https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs`}};function cd(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 ld(e){return{}.toString.call(e).includes(`Object`)}function ud(e){return e||md(`configIsRequired`),ld(e)||md(`configType`),e.urls?(dd(),{paths:{vs:e.urls.monacoBase}}):e}function dd(){console.warn(pd.deprecation)}function fd(e,t){throw Error(e[t]||e.default)}var pd={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
+ You are using deprecated way of configuration.
7
+
8
+ Instead of using
9
+ monaco.config({ urls: { monacoBase: '...' } })
10
+ use
11
+ monaco.config({ paths: { vs: '...' } })
12
+
13
+ For more please check the link https://github.com/suren-atoyan/monaco-loader#config
14
+ `},md=cd(fd)(pd),hd={config:ud},gd=function(){var e=[...arguments];return function(t){return e.reduceRight(function(e,t){return t(e)},t)}};function _d(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],_d(e[n],t[n]))}),Nu(Nu({},e),t)}var vd={type:`cancelation`,msg:`operation is manually canceled`};function yd(e){var t=!1,n=new Promise(function(n,r){e.then(function(e){return t?r(vd):n(e)}),e.catch(r)});return n.cancel=function(){return t=!0},n}var bd=[`monaco`],xd=Iu(od.create({config:sd,isInitialized:!1,resolve:null,reject:null,monaco:null}),2),Sd=xd[0],Cd=xd[1];function wd(e){var t=hd.config(e),n=t.monaco,r=Pu(t,bd);Cd(function(e){return{config:_d(e.config,r),monaco:n}})}function Td(){var e=Sd(function(e){return{monaco:e.monaco,isInitialized:e.isInitialized,resolve:e.resolve}});if(!e.isInitialized){if(Cd({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),yd(Md);if(window.monaco&&window.monaco.editor)return Ad(window.monaco),e.resolve(window.monaco),yd(Md);gd(Ed,Od)(kd)}return yd(Md)}function Ed(e){return document.body.appendChild(e)}function Dd(e){var t=document.createElement(`script`);return e&&(t.src=e),t}function Od(e){var t=Sd(function(e){return{config:e.config,reject:e.reject}}),n=Dd(`${t.config.paths.vs}/loader.js`);return n.onload=function(){return e()},n.onerror=t.reject,n}function kd(){var e=Sd(function(e){return{config:e.config,resolve:e.resolve,reject:e.reject}}),t=window.require;t.config(e.config),t([`vs/editor/editor.main`],function(t){var n=t.m||t;Ad(n),e.resolve(n)},function(t){e.reject(t)})}function Ad(e){Sd().monaco||Cd({monaco:e})}function jd(){return Sd(function(e){return e.monaco})}var Md=new Promise(function(e,t){return Cd({resolve:e,reject:t})}),Nd={config:wd,init:Td,__getMonacoInstance:jd};u();var Pd={wrapper:{display:`flex`,position:`relative`,textAlign:`initial`},fullWidth:{width:`100%`},hide:{display:`none`}},Fd={container:{display:`flex`,height:`100%`,width:`100%`,justifyContent:`center`,alignItems:`center`}};function Id({children:e}){return t.createElement(`div`,{style:Fd.container},e)}var Ld=Id;function Rd({width:e,height:n,isEditorReady:r,loading:i,_ref:a,className:o,wrapperProps:s}){return t.createElement(`section`,{style:{...Pd.wrapper,width:e,height:n},...s},!r&&t.createElement(Ld,null,i),t.createElement(`div`,{ref:a,style:{...Pd.fullWidth,...!r&&Pd.hide},className:o}))}var zd=i(Rd);function Bd(e){s(e,[])}var Vd=Bd;function Hd(e,t,r=!0){let i=n(!0);s(i.current||!r?()=>{i.current=!1}:e,t)}var $=Hd;function Ud(){}function Wd(e,t,n,r){return Gd(e,r)||Kd(e,t,n,r)}function Gd(e,t){return e.editor.getModel(qd(e,t))}function Kd(e,t,n,r){return e.editor.createModel(t,n,r?qd(e,r):void 0)}function qd(e,t){return e.Uri.parse(t)}function Jd({original:e,modified:r,language:i,originalLanguage:o,modifiedLanguage:l,originalModelPath:u,modifiedModelPath:d,keepCurrentOriginalModel:f=!1,keepCurrentModifiedModel:p=!1,theme:m=`light`,loading:h=`Loading...`,options:g={},height:_=`100%`,width:v=`100%`,className:y,wrapperProps:b={},beforeMount:x=Ud,onMount:S=Ud}){let[C,w]=c(!1),[T,E]=c(!0),D=n(null),O=n(null),k=n(null),A=n(S),j=n(x),M=n(!1);Vd(()=>{let e=Nd.init();return e.then(e=>(O.current=e)&&E(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>D.current?F():e.cancel()}),$(()=>{if(D.current&&O.current){let t=D.current.getOriginalEditor(),n=Wd(O.current,e||``,o||i||`text`,u||``);n!==t.getModel()&&t.setModel(n)}},[u],C),$(()=>{if(D.current&&O.current){let e=D.current.getModifiedEditor(),t=Wd(O.current,r||``,l||i||`text`,d||``);t!==e.getModel()&&e.setModel(t)}},[d],C),$(()=>{let e=D.current.getModifiedEditor();e.getOption(O.current.editor.EditorOption.readOnly)?e.setValue(r||``):r!==e.getValue()&&(e.executeEdits(``,[{range:e.getModel().getFullModelRange(),text:r||``,forceMoveMarkers:!0}]),e.pushUndoStop())},[r],C),$(()=>{D.current?.getModel()?.original.setValue(e||``)},[e],C),$(()=>{let{original:e,modified:t}=D.current.getModel();O.current.editor.setModelLanguage(e,o||i||`text`),O.current.editor.setModelLanguage(t,l||i||`text`)},[i,o,l],C),$(()=>{O.current?.editor.setTheme(m)},[m],C),$(()=>{D.current?.updateOptions(g)},[g],C);let N=a(()=>{if(!O.current)return;j.current(O.current);let t=Wd(O.current,e||``,o||i||`text`,u||``),n=Wd(O.current,r||``,l||i||`text`,d||``);D.current?.setModel({original:t,modified:n})},[i,r,l,e,o,u,d]),P=a(()=>{!M.current&&k.current&&(D.current=O.current.editor.createDiffEditor(k.current,{automaticLayout:!0,...g}),N(),O.current?.editor.setTheme(m),w(!0),M.current=!0)},[g,m,N]);s(()=>{C&&A.current(D.current,O.current)},[C]),s(()=>{!T&&!C&&P()},[T,C,P]);function F(){let e=D.current?.getModel();f||e?.original?.dispose(),p||e?.modified?.dispose(),D.current?.dispose()}return t.createElement(zd,{width:v,height:_,isEditorReady:C,loading:h,_ref:k,className:y,wrapperProps:b})}i(Jd);function Yd(e){let t=n();return s(()=>{t.current=e},[e]),t.current}var Xd=Yd,Zd=new Map;function Qd({defaultValue:e,defaultLanguage:r,defaultPath:i,value:o,language:l,path:u,theme:d=`light`,line:f,loading:p=`Loading...`,options:m={},overrideServices:h={},saveViewState:g=!0,keepCurrentModel:_=!1,width:v=`100%`,height:y=`100%`,className:b,wrapperProps:x={},beforeMount:S=Ud,onMount:C=Ud,onChange:w,onValidate:T=Ud}){let[E,D]=c(!1),[O,k]=c(!0),A=n(null),j=n(null),M=n(null),N=n(C),P=n(S),F=n(),I=n(o),L=Xd(u),R=n(!1),z=n(!1);Vd(()=>{let e=Nd.init();return e.then(e=>(A.current=e)&&k(!1)).catch(e=>e?.type!==`cancelation`&&console.error(`Monaco initialization: error:`,e)),()=>j.current?B():e.cancel()}),$(()=>{let t=Wd(A.current,e||o||``,r||l||``,u||i||``);t!==j.current?.getModel()&&(g&&Zd.set(L,j.current?.saveViewState()),j.current?.setModel(t),g&&j.current?.restoreViewState(Zd.get(u)))},[u],E),$(()=>{j.current?.updateOptions(m)},[m],E),$(()=>{!j.current||o===void 0||(j.current.getOption(A.current.editor.EditorOption.readOnly)?j.current.setValue(o):o!==j.current.getValue()&&(z.current=!0,j.current.executeEdits(``,[{range:j.current.getModel().getFullModelRange(),text:o,forceMoveMarkers:!0}]),j.current.pushUndoStop(),z.current=!1))},[o],E),$(()=>{let e=j.current?.getModel();e&&l&&A.current?.editor.setModelLanguage(e,l)},[l],E),$(()=>{f!==void 0&&j.current?.revealLine(f)},[f],E),$(()=>{A.current?.editor.setTheme(d)},[d],E);let ee=a(()=>{if(!(!M.current||!A.current)&&!R.current){P.current(A.current);let t=u||i,n=Wd(A.current,o||e||``,r||l||``,t||``);j.current=A.current?.editor.create(M.current,{model:n,automaticLayout:!0,...m},h),g&&j.current.restoreViewState(Zd.get(t)),A.current.editor.setTheme(d),f!==void 0&&j.current.revealLine(f),D(!0),R.current=!0}},[e,r,i,o,l,u,m,h,g,d,f]);s(()=>{E&&N.current(j.current,A.current)},[E]),s(()=>{!O&&!E&&ee()},[O,E,ee]),I.current=o,s(()=>{E&&w&&(F.current?.dispose(),F.current=j.current?.onDidChangeModelContent(e=>{z.current||w(j.current.getValue(),e)}))},[E,w]),s(()=>{if(E){let e=A.current.editor.onDidChangeMarkers(e=>{let t=j.current.getModel()?.uri;if(t&&e.find(e=>e.path===t.path)){let e=A.current.editor.getModelMarkers({resource:t});T?.(e)}});return()=>{e?.dispose()}}return()=>{}},[E,T]);function B(){F.current?.dispose(),_?g&&Zd.set(u,j.current.saveViewState()):j.current.getModel()?.dispose(),j.current.dispose()}return t.createElement(zd,{width:v,height:y,isEditorReady:E,loading:p,_ref:M,className:b,wrapperProps:x})}var $d=i(Qd);u();function ef(e,t){let n=[];for(let[r,i]of Object.entries(e))r!==t&&(n.push({filePath:`file:///${r}`,content:i}),r.endsWith(`.ts`)&&n.push({filePath:`file:///${r.slice(0,-3)}.js`,content:i}));return n}var tf={target:99,module:99,moduleResolution:2,strict:!0,noImplicitAny:!0,strictNullChecks:!0,allowNonTsExtensions:!0,isolatedModules:!0};function nf(e,t){let n=e.languages.typescript.typescriptDefaults;n.setCompilerOptions({...n.getCompilerOptions(),...tf}),n.setExtraLibs(t.map(e=>({filePath:e.filePath,content:e.content})))}function rf({value:e,onChange:t,extraLibs:r=[],path:i=`file:///block.ts`,onDiagnostics:c,readOnly:l=!1,heightPx:u=420,dark:d=!0}){let f=n(null),p=a((e,t)=>{if(f.current=t,nf(t,r),c===void 0)return;let n=e.getModel();if(n===null)return;let i=()=>{c(t.editor.getModelMarkers({resource:n.uri}).map(e=>({line:e.startLineNumber,column:e.startColumn,message:e.message,severity:e.severity})))};t.editor.onDidChangeMarkers(i),i()},[r,c]);return s(()=>{let e=f.current;e!==null&&nf(e,r)},[r]),o($d,{height:u,defaultLanguage:`typescript`,path:i,theme:d?`vs-dark`:`vs`,value:e,onChange:e=>t(e??``),onMount:p,options:{readOnly:l,minimap:{enabled:!1},fontSize:12,lineNumbers:`on`,scrollBeyondLastLine:!1,automaticLayout:!0,tabSize:2,renderWhitespace:`selection`}})}function af(e){return e.some(e=>e.severity>=8)}var of=[{id:`blank`,name:`Blank script`,get description(){return Y.t(`helpers.buildExamples.blankDescription`)},entry:`main.ts`,files:{"main.ts":`import type { AddonContext } from '@camstack/types'
15
+
16
+ /**
17
+ * A core block. Runs in its own process, with the same \`ctx\` an addon gets.
18
+ * Return a function to release whatever you took (timers, sockets, listeners).
19
+ *
20
+ * Declaring devices: import { reconcileBlockDevices, exposeBlockDevices } from
21
+ * '@camstack/types' and hang them off the shared Blocks integration.
22
+ */
23
+ export default function block(ctx: AddonContext) {
24
+ ctx.logger.info('hello from a core block')
25
+
26
+ const timer = setInterval(() => {
27
+ ctx.logger.info('tick')
28
+ }, 60_000)
29
+
30
+ return () => {
31
+ clearInterval(timer)
32
+ }
33
+ }
34
+ `}}];function sf(e){let t=e instanceof Set?e:new Set(e);if(!t.has(`file.ts`))return`file.ts`;let n=2;for(;t.has(`file-${String(n)}.ts`);)n+=1;return`file-${String(n)}.ts`}var cf=of.find(e=>e.id===`blank`)?.files[`main.ts`]??`import type { AddonContext } from '@camstack/types'
35
+
36
+ export default function block(ctx: AddonContext) {
37
+ ctx.logger.info('hello from a core block')
38
+ return () => undefined
39
+ }
40
+ `;function lf({existing:e,dirty:t,saving:n,restarting:r}){return e===null?Y.t(`helpers.restartGate.saveFirstNoProcess`):n?Y.t(`helpers.restartGate.saving`):r?Y.t(`helpers.restartGate.restarting`):t?Y.t(`helpers.restartGate.saveFirstDirty`):e.enabled?null:Y.t(`helpers.restartGate.disabled`)}u();var uf=5e3;function df(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 ff({blockId:t}){let{t:n}=X(),i=ye(t),a=lt({addonId:i,projection:`slim`},{refetchInterval:uf}),s=r(()=>df(a.data),[a.data]);return a.isLoading?e(`p`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[o(T,{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(gn,{i18nKey:`build.scriptDevicesPanel.declaredBy`,values:{addonId:i},components:{code:o(`code`,{className:`text-[11px]`})}})})]}),o(K,{variant:`default`,children:s.length})]}),s.length===0?o(`p`,{className:`text-xs text-foreground-subtle`,children:o(gn,{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(Cn,{to:`/devices/${String(t.id)}`,className:`text-sm font-medium hover:underline`,title:n(`build.scriptDevicesPanel.openDeviceDetail`,`Open device detail`),children:o(Qt,{device:{id:t.id,name:t.name,type:t.type,stableId:t.stableId??``,parentDeviceId:null},form:`compact`})}),o(K,{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 pf(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 mf(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 hf(e){switch(e){case`refresh-channel-catalog`:return Y.t(`build.scriptSettingsPanel.enableChannel`);case`send-tv-schedule-now`:return Y.t(`build.scriptSettingsPanel.enableTv`);case`refresh-nordvpn-catalog`:return Y.t(`build.scriptSettingsPanel.enableNord`);case`probe-nordvpn-italy`:return Y.t(`build.scriptSettingsPanel.enableItaly`);case`test-nordvpn-endpoint`:return Y.t(`build.scriptSettingsPanel.enableVpn`);case`refresh-unifi-catalog`:return Y.t(`build.scriptSettingsPanel.enableUnifi`)}}function gf(e){if(typeof e!=`object`||!e||!(`key`in e))return null;let t=Reflect.get(e,`key`);return typeof t==`string`?t:null}function _f(e){if(!(typeof e!=`object`||!e||!(`value`in e)))return Reflect.get(e,`value`)}function vf(e){let t={};for(let n of e.sections)for(let e of n.fields){let n=gf(e);n!==null&&(t[n]=_f(e))}return t}function yf(e){return typeof e!=`object`||!e?!1:Array.isArray(Reflect.get(e,`sections`))}function bf({blockId:t}){let{t:n}=X(),i=M(),s=dt({blockId:t},{retry:!1}),l=on({blockId:t},{refetchInterval:1e4,retry:!1}),u=tn({onSuccess:()=>{l.refetch()}}),d=Ut(),f=un(),[p,m]=c(null),[h,g]=c(null),[_,v]=c(null),[y,b]=c(!1),x=yf(l.data)?l.data:null,S=r(()=>x===null?{}:vf(x),[x]),C=p??S,w=a(e=>{m(e)},[]),E=p!==null,D=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]),O=a(async(e,n)=>{if(pf(e)){b(!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:mf(e)}),s.data?.block?.enabled!==!0&&(await f.mutateAsync({blockId:t,enabled:!0}),v(hf(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{b(!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(T,{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)]}):x===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(gn,{i18nKey:`build.scriptSettingsPanel.declaredBy`,components:{code:o(`code`,{})}})})]}),e(G,{size:`sm`,variant:`primary`,onClick:D,disabled:!E||u.isPending||y,children:[u.isPending&&o(T,{className:`h-3.5 w-3.5 animate-spin`}),n(`build.scriptSettingsPanel.saveSettings`,`Save settings`)]})]}),o(bn,{schema:x,values:C,onChange:w,onAction:O}),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 xf=`hub`;function Sf({existing:t,typeDefs:n,typeDefsLoading:i,saving:a,saveError:s,restarting:l,restartError:u,onRestart:d,onSave:f,onCancel:h}){let{t:g}=X(),_=M(),v=j(),{resolvedMode:y}=pn(),b=Ce({code:t?.code??cf,files:t?.files,entry:t?.entry}),[x,S]=c(t?.name??``),[D,O]=c(b.files),[k,A]=c(b.entry),[N,P]=c(b.entry),[I,R]=c(t?.placement??xf),[z,ee]=c(t?.integrationId??``),[B,V]=c([]),[H,te]=c(!1),[ne,re]=c(`blank`),[U,ie]=c(null),[ae,oe]=c(``),se=D[N]??``,ce=e=>{O(t=>({...t,[N]:e}))},le=Object.keys(D).toSorted(),ue=of.length>1,de=r(()=>[...n?.libs??[],...ef(D,N)],[n?.libs,D,N]),W=p({mutationFn:()=>_.trpcClient.coreBlocks.compile.mutate({files:D,entry:k})}),fe=r(()=>B.filter(e=>e.severity>=8),[B]),pe=af(B),me=x.trim()===``,he=t===null?null:Ce(t),ge=t===null||he===null||JSON.stringify(D)!==JSON.stringify(he.files)||k!==he.entry||x.trim()!==t.name||I!==t.placement||(z.trim()===``?void 0:z.trim())!==t.integrationId,_e=()=>{W.reset(),f({name:x.trim(),files:D,entry:k,enabled:t?.enabled??!0,placement:I,...z.trim()===``?{}:{integrationId:z.trim()}})},ve=()=>{let e=sf(Object.keys(D));O(t=>({...t,[e]:``})),P(e),ie(e),oe(e)},be=e=>{ie(e),oe(e)},xe=()=>{if(U===null)return;let e=U,t=ae.trim();if(ie(null),!(t===``||t===e)){if(D[t]!==void 0){P(t);return}O(n=>{let r={};for(let[i,a]of Object.entries(n))r[i===e?t:i]=a;return r}),k===e&&A(t),P(t)}},Se=async e=>{let t=of.find(t=>t.id===e);if(t===void 0)return;let n=of.find(e=>e.id===`blank`);!(n!==void 0&&JSON.stringify(D)===JSON.stringify(n.files)&&k===n.entry)&&!await v({title:g(`build.blockEditor.loadExample`,`Load example`),message:g(`build.blockEditor.replaceTheCurrentEditorContents`,`Replace the current editor contents with this example?`),confirmLabel:g(`build.blockEditor.replace`,`Replace`),variant:`warning`})||(re(e),O({...t.files}),A(t.entry),P(t.entry),(x.trim()===``||ne===`blank`)&&S(t.id===`blank`?``:t.name))},we=t===null?null:Qc(t),Te=lf({existing:t,dirty:ge,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(K,{variant:$c(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:g(`build.blockEditor.name`,`Name`)}),o(J,{className:`mt-1`,value:x,onChange:e=>S(e.target.value),placeholder:g(`build.blockEditor.whatThisScriptDoes`,`What this script does`)})]}),e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.integrationOptional`,`Integration (optional)`)}),o(J,{className:`mt-1`,value:z,onChange:e=>ee(e.target.value),placeholder:g(`build.blockEditor.leaveEmptyForTheShared`,`Leave empty for the shared system integration`)})]})]}),t===null&&ue&&e(`label`,{className:`block text-sm`,children:[o(`span`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.startFrom`,`Start from`)}),o(F,{className:`mt-1 w-full`,value:ne,onChange:e=>void Se(e.target.value),"data-testid":`script-example-select`,children:of.map(t=>e(`option`,{value:t.id,children:[t.name,` — `,t.description]},t.id))})]}),e(`div`,{children:[o(cn,{selectedNodeId:I,onSelect:R,label:g(`build.blockEditor.runsOn`,`Runs on`),alwaysShow:!0}),I!==xf&&e(`p`,{className:`mt-2 flex items-start gap-2 text-xs text-warning`,children:[o(C,{className:`mt-0.5 h-3.5 w-3.5 shrink-0`}),o(`span`,{children:o(gn,{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:[le.map(t=>U===t?o(J,{value:ae,onChange:e=>oe(e.target.value),onBlur:()=>xe(),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),xe()),e.key===`Escape`&&(e.preventDefault(),ie(null))},className:`h-7 w-36 px-2 py-0 text-xs`,autoFocus:!0,"data-testid":`script-file-rename`,"aria-label":g(`build.blockEditor.renameFile`,`Rename file`)},t):e(G,{variant:`unstyled`,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:g(`build.blockEditor.doubleClickToRename`,`Double-click to rename`),"data-testid":`script-file-tab-${t}`,children:[t,t===k?` · ${g(`build.blockEditor.entry`)}`:``]},t)),o(G,{variant:`unstyled`,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:g(`build.blockEditor.file`,`+ file`)}),N!==k&&o(G,{variant:`unstyled`,type:`button`,className:`rounded px-2 py-1 text-xs text-foreground-subtle hover:text-foreground`,onClick:()=>A(N),title:g(`build.blockEditor.useThisFileAsThe`,`Use this file as the compile entry`),children:g(`build.blockEditor.setAsEntry`,`Set as entry`)})]}),i?o(`p`,{className:`p-4 text-sm text-foreground-subtle`,children:g(`build.blockEditor.loadingTheNodeSType`,`Loading the node's type definitions…`)}):o(rf,{value:se,onChange:ce,path:`file:///${N}`,extraLibs:de,onDiagnostics:V,dark:y===`dark`,heightPx:560})]}),n!==void 0&&n.libs.length===0&&o(`p`,{className:`text-xs text-warning`,children:g(`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.`)}),fe.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:g(`build.blockEditor.errorsCannotSave`,{count:fe.length})}),fe.slice(0,5).map(e=>o(`p`,{className:`text-danger`,children:g(`build.blockEditor.diagnosticLine`,{line:e.line,message:e.message})},`${String(e.line)}:${String(e.column)}:${e.message}`)),fe.length>5&&o(`p`,{className:`text-foreground-subtle`,children:g(`build.blockEditor.moreErrors`,{count:fe.length-5})})]}),W.data!==void 0&&(W.data.ok?e(`p`,{className:`flex items-center gap-2 text-xs text-success`,children:[o(E,{className:`h-3.5 w-3.5`}),` `,g(`build.blockEditor.compiledOk`)]}):e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[W.data.line!==void 0&&o(`span`,{className:`mr-1`,children:g(`build.blockEditor.errorLine`,{line:String(W.data.line)})}),W.data.error??g(`build.blockEditor.theCodeDoesNotCompile`,`the code does not compile`)]})),W.error!==null&&e(`div`,{className:`rounded border border-danger/40 bg-danger/10 p-3 text-xs text-danger`,children:[g(`build.blockEditor.couldNotReachTheCompiler`,`Could not reach the compiler:`),` `,Cf(W.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(bf,{blockId:t.id}),o(ff,{blockId:t.id})]}),e(`div`,{className:`flex flex-wrap items-center gap-2`,children:[e(G,{variant:`outline`,onClick:()=>W.mutate(),disabled:W.isPending||a,title:g(`build.blockEditor.typeCheckOnTheNode`,`Type-check on the node without saving`),children:[W.isPending&&o(T,{className:`h-4 w-4 animate-spin`}),` `,g(`common.compile`)]}),e(G,{onClick:_e,disabled:a||pe||me,children:[a&&o(T,{className:`h-4 w-4 animate-spin`}),` `,g(`common.save`)]}),e(G,{variant:`outline`,onClick:()=>d?.(),disabled:Te!==null||d===void 0,title:Te??g(`build.blockEditor.stopTheProcessAndLet`,`Stop the process and let the supervisor bring it back`),children:[l?o(L,{className:`h-4 w-4 animate-spin`}):o(L,{className:`h-4 w-4`}),` `,g(`build.blockEditor.restart`,`Restart`)]}),e(G,{variant:`ghost`,onClick:()=>te(!H),title:g(`build.blockEditor.showThisScriptSProcess`,`Show this script's process logs`),"data-testid":`script-logs-toggle`,"aria-expanded":H,children:[o(w,{className:`h-4 w-4`}),` `,g(`common.logs`),` `,o(en,{expanded:H})]}),o(G,{variant:`ghost`,onClick:h,disabled:a,children:g(`common.close`,`Close`)}),e(`span`,{className:`ml-auto text-xs text-foreground-subtle`,children:[g(`build.blockEditor.errorsCount`,{count:fe.length}),ge&&t!==null?` · ${g(`build.blockEditor.unsavedChanges`)}`:``]}),me&&o(K,{variant:`warning`,children:g(`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?g(`build.blockEditor.logsAppearOnceTheScript`,`Logs appear once the script has been saved and started.`):o(m,{children:o(gn,{i18nKey:`build.blockEditor.logsOf`,values:{id:ye(t.id)},components:{code:o(`code`,{})}})})}),t!==null&&o(Et,{addonId:ye(t.id),maxHeight:`max-h-[560px]`,showFilters:!1})]})]})}function Cf(e){return e instanceof Error?e.message:String(e)}u();var wf=[`coreBlocks`,`list`],Tf=[`coreBlocks`,`getTypeDefs`],Ef=5e3;function Df(e){return e instanceof Error?e.message:String(e)}function Of({initialBlockId:t,onBlockIdChange:i,createRequested:a=!1,onCreateConsumed:u}={}){let d=S(),{t:f}=X(),m=M(),{state:h,openNew:g,openEdit:_,close:v}=Ft({editKey:`block`,newKey:`new`}),[y,b]=c(null),x=j(),[C,T]=c(null),E=l({queryKey:wf,refetchInterval:Ef,queryFn:async()=>(await m.trpcClient.coreBlocks.list.query({})).blocks}),D=h.mode!==`closed`,O=l({queryKey:Tf,enabled:D,staleTime:1/0,gcTime:1/0,queryFn:()=>m.trpcClient.coreBlocks.getTypeDefs.query({})}),A=()=>{E.refetch()},N=n(null),P=E.data;s(()=>{t===void 0||N.current===t||P?.find(e=>e.id===t&&R(e)===`code`)!==void 0&&(N.current=t,_(t),i?.(t))},[t,P,_,i]),s(()=>{a&&(b(null),g(),i?.(null),u?.())},[a,u,i,g]);let F=p({mutationFn:e=>m.trpcClient.coreBlocks.create.mutate({block:e}),onSuccess:e=>{b(e.block),_(e.block.id),i?.(e.block.id),A()}}),I=p({mutationFn:e=>m.trpcClient.coreBlocks.update.mutate(e),onSuccess:e=>{b(e.block),_(e.block.id),i?.(e.block.id),A()}}),z=p({mutationFn:e=>m.trpcClient.coreBlocks.delete.mutate({blockId:e}),onSuccess:A}),ee=p({mutationFn:e=>m.trpcClient.coreBlocks.setEnabled.mutate(e),onSuccess:A}),B=p({mutationFn:e=>m.trpcClient.coreBlocks.restart.mutate({blockId:e}),onSuccess:A}),V=tl((E.data??[]).filter(e=>R(e)===`code`)),H=E.data!==void 0&&V.length===0,te=F.isPending||I.isPending,ne=F.error===null?I.error===null?null:Df(I.error):Df(F.error),re=h.mode===`edit`?V.find(e=>e.id===h.id)??(y!==null&&y.id===h.id?y:null):null,U=h.mode===`new`||re===null?null:el(V,re),ie=r(()=>[{key:`name`,header:f(`build.scriptsTab.name`,`Name`),render:t=>{let n=Qc(t),r=bt(t.updatedAt,d);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(K,{variant:$c(n.tone),children:n.label}),o(K,{variant:`info`,children:t.placement}),r!==null&&o(`span`,{className:`text-xs text-foreground-subtle`,children:f(`common.edited`,{when:r})})]}),o(`p`,{className:`mt-0.5 text-xs text-foreground-subtle`,children:n.detail}),C===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(gn,{i18nKey:`common.logsOf`,values:{id:ye(t.id)},components:{code:o(`code`,{})}})}),o(Et,{addonId:ye(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=ee.isPending||z.isPending,r=B.isPending&&B.variables===t.id;return e(`div`,{className:`flex justify-end gap-1`,children:[o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),b(t),_(t.id),i?.(t.id)},title:f(`common.edit`,`Edit`),children:f(`common.edit`,`Edit`)}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),B.mutate(t.id)},disabled:n||r||!t.enabled,title:t.enabled?f(`build.scriptsTab.restart`,`Restart`):f(`build.scriptsTab.enableItInsteadADisabled`,`Enable it instead — a disabled script has no process`),children:o(L,{className:`h-4 w-4${r?` animate-spin`:``}`})}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),T(C===t.id?null:t.id)},title:f(`build.scriptsTab.logs`,`Logs`),children:o(w,{className:`h-4 w-4`})}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),ee.mutate({blockId:t.id,enabled:!t.enabled})},disabled:n,title:t.enabled?f(`common.disable`,`Disable`):f(`common.enable`,`Enable`),children:t.enabled?f(`common.disable`,`Disable`):f(`common.enable`,`Enable`)}),o(G,{variant:`ghost`,onClick:e=>{e.stopPropagation(),x({title:f(`build.scriptsTab.deleteThisScript`,`Delete this script?`),message:f(`build.scriptsTab.deleteMessage`,`{{name}} and its source will be deleted. This cannot be undone.`,{name:t.name}),confirmLabel:f(`common.delete`,`Delete`),variant:`danger`}).then(e=>{e&&z.mutate(t.id)})},title:f(`common.delete`,`Delete`),children:o(k,{className:`h-4 w-4`})})]})}}],[x,C,i,_,z,B.isPending,B.variables,ee,f]);return e(`div`,{className:`space-y-3`,children:[o(`p`,{className:`text-xs text-foreground-subtle`,children:E.data===void 0?``:nl(V)}),E.error!=null&&o(q,{title:f(`build.scriptsTab.couldNotReadTheScripts`,`Could not read the scripts`),message:Df(E.error),onRetry:A}),o(Dt,{columns:ie,rows:V,rowKey:e=>e.id,pageSize:25,maxBodyHeight:jt,emptyMessage:H?f(`build.scriptsTab.noScriptsYetAScript`,`No scripts yet. A script is TypeScript the hub runs in its own process.`):E.data===void 0?f(`build.scriptsTab.loadingScripts`,`Loading scripts…`):f(`build.scriptsTab.noScriptsYet`,`No scripts yet.`),onRowClick:e=>{b(e),_(e.id),i?.(e.id)}}),o(St,{open:D,onClose:()=>{F.reset(),I.reset(),B.reset(),b(null),v(),i?.(null)},title:U===null?f(`build.scriptsTab.newScript`,`New script`):f(`build.scriptsTab.edit`,`Edit {{name}}`,{name:U.name}),icon:Ke,width:`xl`,testId:`script-editor-panel`,children:o(Sf,{existing:U,typeDefs:O.data,typeDefsLoading:O.isLoading,saving:te,saveError:ne,restarting:B.isPending,restartError:B.error===null?null:Df(B.error),onRestart:U===null?void 0:()=>B.mutate(U.id),onSave:e=>{let t=U;t===null?F.mutate(e):I.mutate({blockId:t.id,block:e})},onCancel:()=>{F.reset(),I.reset(),B.reset(),b(null),v(),i?.(null)}})}),z.error!=null&&o(q,{message:Df(z.error)}),ee.error!=null&&o(q,{message:Df(ee.error)}),B.error!=null&&o(q,{message:Df(B.error)})]})}var kf=[`automations`,`actions`,`schedulers`,`scripts`,`custom-device`];function Af(e){return e!==null&&kf.some(t=>t===e)}var jf=[`coreBlocks`,`list`,`build-counts`],Mf=[`schedulers`,`list`,`build-counts`],Nf=[`actions`,`list`,`build-counts`],Pf=[`block`,`action`,`scheduler`,`create`,`new`];function Ff(e){return e.filter(e=>R(e)===`code`).length}function If(e){return e.filter(e=>ar(e.code)).length}function Lf(e,t){return t===null?e:`${e} (${String(t)})`}function Rf(){let{t}=X(),n=M(),[r,i]=_n(),a=r.get(`tab`),s=Af(a)?a:`automations`,c=r.get(`create`)===`1`,u=l({queryKey:jf,refetchInterval:5e3,queryFn:async()=>(await n.trpcClient.coreBlocks.list.query({})).blocks}).data,d=u===void 0?null:Ff(u),f=u===void 0?null:If(u),p=l({queryKey:Nf,refetchInterval:1e4,queryFn:async()=>n.trpcClient.actions.list.query({})}),m=p.data===void 0?null:p.data.length,h=l({queryKey:Mf,refetchInterval:1e4,queryFn:async()=>n.trpcClient.schedulers.list.query({})}),g=h.data===void 0?null:h.data.length,_=l({queryKey:[`coreBlocks`,`listCompositions`,`build-counts`],refetchInterval:1e4,queryFn:async()=>n.trpcClient.coreBlocks.listCompositions.query({})}),v=_.data?.state===`loaded`?_.data.views.length:null,y=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})},x=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})},S=()=>{i(e=>{let t=new URLSearchParams(e);return t.set(`create`,`1`),t.delete(`block`),t},{replace:!0})},C=e=>{i(()=>{let t=new URLSearchParams(window.location.search);return t.set(`tab`,`custom-device`),t.delete(`block`),t.delete(`create`),t.set(`new`,e),t},{replace:!0})},w=()=>{i(()=>{let e=new URLSearchParams(window.location.search);return e.delete(`create`),e},{replace:!0})},T=s===`automations`?t(`build.newAutomation`,`New automation`):s===`actions`?t(`build.newAction`,`New action`):s===`schedulers`?t(`build.newScheduler`,`New scheduler`):t(`build.newScript`,`New script`),E=wn(`/build`,{t,isAdmin:!0})??{icon:b,title:t(`nav.build`,`Build-your-self`)};return o(Tn,{icon:E.icon,title:E.title,subtitle:t(`build.automationsScriptsAndComposedDevices`,`Automations, scripts and composed devices — what this installation does on its own.`),defaultSection:`automations`,sectionsLabel:`${E.title} sections`,fill:!0,actions:s===`custom-device`?e(G,{type:`button`,onClick:()=>C(`helper`),"data-testid":`build-new-composed`,children:[o(D,{className:`h-4 w-4`}),` `,t(`helper.newComposed`)]}):e(G,{type:`button`,onClick:S,"data-testid":`build-new`,children:[o(D,{className:`h-4 w-4`}),` `,T]}),sections:[{id:`automations`,label:Lf(t(`build.tabAutomations`,`Automations`),f),ownedParams:Pf,content:o(hl,{onOpenScripts:y,createRequested:s===`automations`&&c,onCreateConsumed:w})},{id:`actions`,label:Lf(t(`build.tabActions`,`Actions`),m),ownedParams:Pf,content:o(Pc,{createRequested:s===`actions`&&c,onCreateConsumed:w})},{id:`schedulers`,label:Lf(t(`build.tabSchedulers`,`Schedulers`),g),ownedParams:Pf,content:o(Pl,{createRequested:s===`schedulers`&&c,onCreateConsumed:w})},{id:`scripts`,label:Lf(t(`build.tabCode`,`Code`),d),ownedParams:Pf,content:o(Of,{initialBlockId:s===`scripts`?r.get(`block`)??void 0:void 0,onBlockIdChange:x,createRequested:s===`scripts`&&c,onCreateConsumed:w})},{id:`custom-device`,label:Lf(t(`build.tabCustomDevice`,`Custom Device`),v),ownedParams:Pf,content:o(_u,{createRequested:s===`custom-device`&&c,onCreateConsumed:w})}]})}export{Rf 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{Ri as s,wa as c,zi as l}from"./player-overlays-D-63t-DL.js";import{Qa as u,Za as d}from"./client-B60QT14E.js";import{y as f}from"./video-BV-3O_ZC.js";import{$a as p,Br as m,Gr as h,Hr as g,Kr as _,Pi as v,Qa as y,Vr as b,Wr as x,Za as S,af as C,eo as w}from"./src-g2TJby3U.js";import{t as T}from"./i18n-CvWKDmFM.js";import{t as E}from"./useTranslation-BJr-n0es.js";import{Kr as D,Z as O,qr as k}from"./index-CxPpnulu.js";import{t as A}from"./AdminPage-DBIlGQcg.js";a();function ee(e,t){return e.flatMap(e=>e.instances.map(n=>({addonId:e.addonId,id:n.id,name:n.name,enabled:n.enabled!==!1,providerName:t.get(e.addonId)??e.addonId})))}function te(e,t,n){let r=new Set,i=(e,t)=>`${e}\u0000${t}`,a=e.map(e=>{let a=e.instanceId===void 0?null:t.find(t=>t.addonId===e.providerAddonId&&t.id===e.instanceId)??null;return a!==null&&r.add(i(a.addonId,a.id)),{key:a===null?e.id:`instance:${a.addonId}:${a.id}`,name:e.name,providerName:a?.providerName??n(e),calendar:e,instance:a}});for(let e of t)r.has(i(e.addonId,e.id))||a.push({key:`instance:${e.addonId}:${e.id}`,name:e.name,providerName:e.providerName,calendar:null,instance:e});return a}var j=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function M(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function N(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function P(e){let t=e.getDay();return M(N(e,t===0?-6:1-t))}function F(e,t){if(t===`day`){let t=M(e);return{startMs:t.getTime(),endMs:N(t,1).getTime()}}if(t===`week`){let t=P(e);return{startMs:t.getTime(),endMs:N(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=P(n),a=N(P(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function I(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=P(e),n=N(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 L(e,t,n){return t===`day`?N(e,n):t===`week`?N(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function R(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 z(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function B(e){if(e.allDay===!0)return T.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 V(e){let t=d(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=M(n),t=N(M(r),-1);return G(e,t)?T.t(`systemPage.calendars.dayAllDay`,{date:n.toLocaleDateString(void 0,i)}):T.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 G(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 H({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 U({ev:t,calendarName:n,color:i,onClose:a}){let{t:o}=E();return r(m,{open:!0,onOpenChange:e=>!e&&a(),children:e(g,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(h,{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(_,{className:`min-w-0 break-words`,children:t.title})]})}),r(b,{children:e(`dl`,{className:`space-y-3`,children:[r(H,{label:o(`systemPage.calendars.when`,`When`),children:V(t)}),r(H,{label:o(`systemPage.calendars.calendar`,`Calendar`),children:n}),t.location!==void 0&&t.location.length>0?r(H,{label:o(`systemPage.calendars.location`,`Location`),children:t.location}):null,t.description!==void 0&&t.description.length>0?r(H,{label:o(`systemPage.calendars.description`,`Description`),children:r(`span`,{className:`whitespace-pre-wrap`,children:t.description})}):null]})}),r(x,{children:r(v,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`common.close`,`Close`)})})]})})}function W(e,t){return e.filter(e=>u(e,t))}function G(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function K({mode:e,onChange:t}){let{t:n}=E(),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(v,{variant:`unstyled`,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 q({rows:t,onToggleVisible:n,onColorChange:i,busy:a}){let{t:s}=E();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:s(`systemPage.calendars.calendars`,`Calendars`)}),r(`ul`,{className:`space-y-1`,children:t.map(t=>{let l=t.calendar,u=t.instance!==null&&!t.instance.enabled;return e(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface ${u?`opacity-60`:``}`,"data-testid":`calendars-row-${t.key}`,children:[l!==null&&!u?e(o,{children:[r(c,{className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:l.visible,disabled:a,onChange:e=>n(l.id,e.target.checked),"aria-label":s(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${l.id}`}),r(C,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:l.color,disabled:a,onChange:e=>i(l.id,e.target.value.toUpperCase()),"aria-label":s(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:t.name}),"data-testid":`calendars-color-${l.id}`})]}):null,e(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`truncate text-sm font-medium ${l?.visible===!0&&!u?`text-foreground`:`text-foreground-subtle`}`,children:t.name}),e(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[t.providerName,u?` · ${s(`systemPage.calendars.switchedOff`)}`:``,l!==null&&!l.enabled?` · ${s(`systemPage.calendars.unavailableAtSource`)}`:``]})]})]},t.key)})}),r(k,{to:`/system/integrations?tab=calendars`,className:`block text-[11px] text-primary underline-offset-2 hover:underline`,"data-testid":`calendars-manage-sources`,children:s(`systemPage.calendars.manageSources`,`Manage sources`)})]})}function J({ev:t,color:n,compact:i,onSelect:a}){return r(v,{variant:`unstyled`,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:B(t)})]})})}function ne({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let{t:s}=E(),{startMs:c,endMs:l}=F(t,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=N(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:j.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=M(t).getTime(),l=W(n,c),u=t.getMonth()!==d,f=G(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(J,{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 re({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let s=P(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)=>N(s,t)).map(t=>{let s=M(t).getTime(),c=W(n,s);return e(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[r(`div`,{className:G(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(J,{ev:e,color:i.get(e.calendarId)??`#64748B`,onSelect:o},e.id))})]},s)})})}function ie({anchor:t,events:n,colorById:i,calName:a,onSelectEvent:o}){let{t:s}=E(),c=W(n,M(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(v,{variant:`unstyled`,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:[B(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}=E(),o=y(),c=S({}),u=w(),d=O(`calendar-source`),[m,h]=i(`month`),[g,_]=i(()=>M(new Date)),[b,x]=i(null),C=t(()=>M(new Date),[]),T=o.isSuccess,j=c.isSuccess&&c.data!==void 0?c.data:void 0,N=t(()=>!T||o.data===void 0?[]:o.data.map(e=>R(e,j)),[T,o.data,j]),P=t(()=>N.filter(e=>e.visible),[N]),B=t(()=>P.map(e=>e.id),[P]),V=t(()=>F(g,m),[g,m]),H=p({startMs:V.startMs,endMs:V.endMs,calendarIds:[...B]},{enabled:T&&B.length>0}),W=H.data??[],G=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.color);return e},[N]),J=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.name);return e},[N]),Y=t(()=>te(N,ee(d.holders,d.displayNames),z),[N,d.holders,d.displayNames]),X=n((e,t)=>{u.mutateAsync({calendarId:e,visible:t}).then(()=>c.refetch())},[c,u]),Z=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&u.mutateAsync({calendarId:e,color:t}).then(()=>c.refetch())},[c,u]),ae=n(()=>_(M(new Date)),[]),oe=n(()=>_(e=>L(e,m,-1)),[m]),se=n(()=>_(e=>L(e,m,1)),[m]),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||d.state===`pending`?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]}):d.state===`error`&&Y.length===0?e(`p`,{className:`text-sm text-danger`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,d.error]}):Y.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(D,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(k,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):B.length===0?e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(q,{rows:Y,onToggleVisible:X,onColorChange:Z,busy:u.isPending}),r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:N.length===0?a(`systemPage.calendars.allSwitchedOff`):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(q,{rows:Y,onToggleVisible:X,onColorChange:Z,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(K,{mode:m,onChange:h}),e(`div`,{className:`flex items-center gap-1`,children:[r(v,{variant:`unstyled`,type:`button`,className:Q,onClick:oe,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(l,{className:`h-4 w-4`})}),r(v,{variant:`unstyled`,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:ae,"data-testid":`calendars-today`,children:a(`systemPage.calendars.today`,`Today`)}),r(v,{variant:`unstyled`,type:`button`,className:Q,onClick:se,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(s,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:I(g,m)})]}),H.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingEvents`,`Loading events…`)}):H.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,H.error.message]}):m===`month`?r(ne,{anchor:g,events:W,colorById:G,today:C,onSelectEvent:x}):m===`week`?r(re,{anchor:g,events:W,colorById:G,today:C,onSelectEvent:x}):r(ie,{anchor:g,events:W,colorById:G,calName:J,onSelectEvent:x})]})]}),e(A,{icon:f,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[d.state===`error`&&Y.length>0?e(`p`,{className:`mb-3 text-sm text-warning`,role:`status`,"data-testid":`calendars-switches-unavailable`,children:[a(`systemPage.calendars.switchesUnavailable`,`The calendar switches could not be loaded, so they are hidden. Calendars switched off are not listed until they load.`),` `,d.error]}):null,$,b===null?null:r(U,{ev:b,calendarName:J.get(b.calendarId)??b.calendarId,color:G.get(b.calendarId)??`#64748B`,onClose:()=>x(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{Hi as s,Oa as c,Ui as l}from"./player-overlays-COha2Q7D.js";import{no as u,ro as d}from"./client-CqZcg6J1.js";import{y as f}from"./video-BV-3O_ZC.js";import{$d as p,Ba as m,Ha as h,Hr as g,Jr as _,Kr as v,Ua as y,Ur as b,Va as x,Wr as S,qr as C,sf as w}from"./src-COXDtqhI.js";import{t as T}from"./i18n-jsJQRNVP.js";import{t as E}from"./useTranslation-BJr-n0es.js";import{Kr as D,Z as O,qr as k}from"./index-56F3KEmN.js";import{t as A}from"./AdminPage-Bdna98Ou.js";a();function ee(e,t){return e.flatMap(e=>e.instances.map(n=>({addonId:e.addonId,id:n.id,name:n.name,enabled:n.enabled!==!1,providerName:t.get(e.addonId)??e.addonId})))}function te(e,t,n){let r=new Set,i=(e,t)=>`${e}\u0000${t}`,a=e.map(e=>{let a=e.instanceId===void 0?null:t.find(t=>t.addonId===e.providerAddonId&&t.id===e.instanceId)??null;return a!==null&&r.add(i(a.addonId,a.id)),{key:a===null?e.id:`instance:${a.addonId}:${a.id}`,name:e.name,providerName:a?.providerName??n(e),calendar:e,instance:a}});for(let e of t)r.has(i(e.addonId,e.id))||a.push({key:`instance:${e.addonId}:${e.id}`,name:e.name,providerName:e.providerName,calendar:null,instance:e});return a}var j=[`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`,`Sun`];function M(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())}function N(e,t){let n=new Date(e);return n.setDate(n.getDate()+t),n}function P(e){let t=e.getDay();return M(N(e,t===0?-6:1-t))}function F(e,t){if(t===`day`){let t=M(e);return{startMs:t.getTime(),endMs:N(t,1).getTime()}}if(t===`week`){let t=P(e);return{startMs:t.getTime(),endMs:N(t,7).getTime()}}let n=new Date(e.getFullYear(),e.getMonth(),1),r=new Date(e.getFullYear(),e.getMonth()+1,0),i=P(n),a=N(P(r),7);return{startMs:i.getTime(),endMs:a.getTime()}}function I(e,t){if(t===`day`)return e.toLocaleDateString(void 0,{weekday:`long`,year:`numeric`,month:`long`,day:`numeric`});if(t===`week`){let t=P(e),n=N(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 L(e,t,n){return t===`day`?N(e,n):t===`week`?N(e,n*7):new Date(e.getFullYear(),e.getMonth()+n,1)}function R(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 z(e){return e.providerAddonId!==void 0&&e.providerAddonId.length>0?e.providerAddonId:e.source===`ha`?`Home Assistant`:e.source}function B(e){if(e.allDay===!0)return T.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 V(e){let t=u(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=M(n),t=N(M(r),-1);return G(e,t)?T.t(`systemPage.calendars.dayAllDay`,{date:n.toLocaleDateString(void 0,i)}):T.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 G(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 H({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 U({ev:t,calendarName:n,color:i,onClose:a}){let{t:o}=E();return r(g,{open:!0,onOpenChange:e=>!e&&a(),children:e(S,{width:`md`,placement:`sheet-on-mobile`,scroll:`body`,"data-testid":`calendars-event-detail`,children:[r(C,{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(_,{className:`min-w-0 break-words`,children:t.title})]})}),r(b,{children:e(`dl`,{className:`space-y-3`,children:[r(H,{label:o(`systemPage.calendars.when`,`When`),children:V(t)}),r(H,{label:o(`systemPage.calendars.calendar`,`Calendar`),children:n}),t.location!==void 0&&t.location.length>0?r(H,{label:o(`systemPage.calendars.location`,`Location`),children:t.location}):null,t.description!==void 0&&t.description.length>0?r(H,{label:o(`systemPage.calendars.description`,`Description`),children:r(`span`,{className:`whitespace-pre-wrap`,children:t.description})}):null]})}),r(v,{children:r(p,{type:`button`,size:`sm`,variant:`secondary`,onClick:a,children:o(`common.close`,`Close`)})})]})})}function W(e,t){return e.filter(e=>d(e,t))}function G(e,t){return e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function K({mode:e,onChange:t}){let{t:n}=E(),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(p,{variant:`unstyled`,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 q({rows:t,onToggleVisible:n,onColorChange:i,busy:a}){let{t:s}=E();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:s(`systemPage.calendars.calendars`,`Calendars`)}),r(`ul`,{className:`space-y-1`,children:t.map(t=>{let l=t.calendar,u=t.instance!==null&&!t.instance.enabled;return e(`li`,{className:`flex items-start gap-2 rounded-md px-1.5 py-1.5 hover:bg-surface ${u?`opacity-60`:``}`,"data-testid":`calendars-row-${t.key}`,children:[l!==null&&!u?e(o,{children:[r(c,{className:`mt-1 h-3.5 w-3.5 shrink-0 accent-primary`,checked:l.visible,disabled:a,onChange:e=>n(l.id,e.target.checked),"aria-label":s(`systemPage.calendars.show`,`Show {{name}}`,{name:t.name}),"data-testid":`calendars-visible-${l.id}`}),r(w,{type:`color`,className:`mt-0.5 h-6 w-6 shrink-0 cursor-pointer rounded border border-border bg-transparent p-0`,value:l.color,disabled:a,onChange:e=>i(l.id,e.target.value.toUpperCase()),"aria-label":s(`systemPage.calendars.colourFor`,`Colour for {{name}}`,{name:t.name}),"data-testid":`calendars-color-${l.id}`})]}):null,e(`div`,{className:`min-w-0 flex-1`,children:[r(`div`,{className:`truncate text-sm font-medium ${l?.visible===!0&&!u?`text-foreground`:`text-foreground-subtle`}`,children:t.name}),e(`div`,{className:`truncate text-[11px] text-foreground-subtle`,children:[t.providerName,u?` · ${s(`systemPage.calendars.switchedOff`)}`:``,l!==null&&!l.enabled?` · ${s(`systemPage.calendars.unavailableAtSource`)}`:``]})]})]},t.key)})}),r(k,{to:`/system/integrations?tab=calendars`,className:`block text-[11px] text-primary underline-offset-2 hover:underline`,"data-testid":`calendars-manage-sources`,children:s(`systemPage.calendars.manageSources`,`Manage sources`)})]})}function J({ev:t,color:n,compact:i,onSelect:a}){return r(p,{variant:`unstyled`,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:B(t)})]})})}function ne({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let{t:s}=E(),{startMs:c,endMs:l}=F(t,`month`),u=[];for(let e=new Date(c);e.getTime()<l;e=N(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:j.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=M(t).getTime(),l=W(n,c),u=t.getMonth()!==d,f=G(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(J,{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 re({anchor:t,events:n,colorById:i,today:a,onSelectEvent:o}){let s=P(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)=>N(s,t)).map(t=>{let s=M(t).getTime(),c=W(n,s);return e(`div`,{className:`min-h-[8rem] bg-background p-2 sm:min-h-[12rem]`,children:[r(`div`,{className:G(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(J,{ev:e,color:i.get(e.calendarId)??`#64748B`,onSelect:o},e.id))})]},s)})})}function ie({anchor:t,events:n,colorById:i,calName:a,onSelectEvent:o}){let{t:s}=E(),c=W(n,M(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(p,{variant:`unstyled`,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:[B(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}=E(),o=x(),c=m({}),u=y(),d=O(`calendar-source`),[g,_]=i(`month`),[v,b]=i(()=>M(new Date)),[S,C]=i(null),w=t(()=>M(new Date),[]),T=o.isSuccess,j=c.isSuccess&&c.data!==void 0?c.data:void 0,N=t(()=>!T||o.data===void 0?[]:o.data.map(e=>R(e,j)),[T,o.data,j]),P=t(()=>N.filter(e=>e.visible),[N]),B=t(()=>P.map(e=>e.id),[P]),V=t(()=>F(v,g),[v,g]),H=h({startMs:V.startMs,endMs:V.endMs,calendarIds:[...B]},{enabled:T&&B.length>0}),W=H.data??[],G=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.color);return e},[N]),J=t(()=>{let e=new Map;for(let t of N)e.set(t.id,t.name);return e},[N]),Y=t(()=>te(N,ee(d.holders,d.displayNames),z),[N,d.holders,d.displayNames]),X=n((e,t)=>{u.mutateAsync({calendarId:e,visible:t}).then(()=>c.refetch())},[c,u]),Z=n((e,t)=>{/^#[0-9A-Fa-f]{6}$/.test(t)&&u.mutateAsync({calendarId:e,color:t}).then(()=>c.refetch())},[c,u]),ae=n(()=>b(M(new Date)),[]),oe=n(()=>b(e=>L(e,g,-1)),[g]),se=n(()=>b(e=>L(e,g,1)),[g]),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||d.state===`pending`?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]}):d.state===`error`&&Y.length===0?e(`p`,{className:`text-sm text-danger`,children:[a(`systemPage.calendars.couldNotListCalendars`,`Could not list calendars:`),` `,d.error]}):Y.length===0?r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-sources`,children:r(D,{i18nKey:`systemPage.calendars.emptySources`,components:{link:r(k,{to:`/system/integrations?tab=calendars`,className:`text-accent underline-offset-2 hover:underline`})}})}):B.length===0?e(`div`,{className:`flex flex-col gap-4 lg:flex-row lg:items-start`,children:[r(q,{rows:Y,onToggleVisible:X,onColorChange:Z,busy:u.isPending}),r(`p`,{className:`text-sm text-foreground-subtle`,"data-testid":`calendars-empty-hidden`,children:N.length===0?a(`systemPage.calendars.allSwitchedOff`):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(q,{rows:Y,onToggleVisible:X,onColorChange:Z,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(K,{mode:g,onChange:_}),e(`div`,{className:`flex items-center gap-1`,children:[r(p,{variant:`unstyled`,type:`button`,className:Q,onClick:oe,"aria-label":a(`systemPage.calendars.previous`,`Previous`),"data-testid":`calendars-prev`,children:r(l,{className:`h-4 w-4`})}),r(p,{variant:`unstyled`,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:ae,"data-testid":`calendars-today`,children:a(`systemPage.calendars.today`,`Today`)}),r(p,{variant:`unstyled`,type:`button`,className:Q,onClick:se,"aria-label":a(`common.next`,`Next`),"data-testid":`calendars-next`,children:r(s,{className:`h-4 w-4`})})]}),r(`span`,{className:`text-sm font-medium text-foreground`,"data-testid":`calendars-period`,children:I(v,g)})]}),H.isPending?r(`p`,{className:`text-sm text-foreground-subtle`,children:a(`systemPage.calendars.loadingEvents`,`Loading events…`)}):H.isError?e(`p`,{className:`text-sm text-destructive`,children:[a(`systemPage.calendars.couldNotListEvents`,`Could not list events:`),` `,H.error.message]}):g===`month`?r(ne,{anchor:v,events:W,colorById:G,today:w,onSelectEvent:C}):g===`week`?r(re,{anchor:v,events:W,colorById:G,today:w,onSelectEvent:C}):r(ie,{anchor:v,events:W,colorById:G,calName:J,onSelectEvent:C})]})]}),e(A,{icon:f,title:a(`systemPage.calendars.calendars`,`Calendars`),subtitle:a(`systemPage.calendars.calendarsFromConnectedSourcesUsed`,`Calendars from connected sources. Used by Calendar events notification rules.`),children:[d.state===`error`&&Y.length>0?e(`p`,{className:`mb-3 text-sm text-warning`,role:`status`,"data-testid":`calendars-switches-unavailable`,children:[a(`systemPage.calendars.switchesUnavailable`,`The calendar switches could not be loaded, so they are hidden. Calendars switched off are not listed until they load.`),` `,d.error]}):null,$,S===null?null:r(U,{ev:S,calendarName:J.get(S.calendarId)??S.calendarId,color:G.get(S.calendarId)??`#64748B`,onClose:()=>C(null)})]})}export{Y as CalendarsPage,Y as default};
@@ -1 +1 @@
1
- import{S as e}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Mr as t}from"./player-overlays-D-63t-DL.js";import{t as n}from"./useTranslation-BJr-n0es.js";import{t as r}from"./InstancesTable-CvfpkEKd.js";function i(){let{t:i}=n();return e(r,{functionCap:`camera-grid-layout`,icon:t,title:i(`cameraGrids.title`,`Camera grids`),subtitle:i(`cameraGrids.subtitle`,`A grid is a composite camera: several cameras composed into one picture, recorded and played back like any other. Create one with a name, then open its camera to lay it out.`),emptyTitle:i(`cameraGrids.empty`,`No camera grids yet`),emptyDescription:i(`cameraGrids.emptyHint`,`Add a grid to compose several cameras into one.`),addLabel:i(`cameraGrids.add`,`Add grid`)})}export{i as CameraGridsPage};
1
+ import{S as e}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CEyXHAdg.js";import{Nr as t}from"./player-overlays-COha2Q7D.js";import{t as n}from"./useTranslation-BJr-n0es.js";import{t as r}from"./InstancesTable-BGtfLCCP.js";function i(){let{t:i}=n();return e(r,{functionCap:`camera-grid-layout`,icon:t,title:i(`cameraGrids.title`,`Camera grids`),subtitle:i(`cameraGrids.subtitle`,`A grid is a composite camera: several cameras composed into one picture, recorded and played back like any other. Create one with a name, then open its camera to lay it out.`),emptyTitle:i(`cameraGrids.empty`,`No camera grids yet`),emptyDescription:i(`cameraGrids.emptyHint`,`Add a grid to compose several cameras into one.`),addLabel:i(`cameraGrids.add`,`Add grid`)})}export{i as CameraGridsPage};