@mohsinonxrm/pptb-commandbar-studio 0.8.0 → 0.9.0-beta.1

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 (60) hide show
  1. package/CHANGELOG.md +472 -0
  2. package/README.md +71 -48
  3. package/dist/assets/BulkPublishModal-DzDZJg0U.js +36 -0
  4. package/dist/assets/CommandEditorPanel-DsCP9yG4.js +1 -0
  5. package/dist/assets/CommandPalette-ID3kRJ9l.js +1 -0
  6. package/dist/assets/CompareView-DGsrcdoN.js +7 -0
  7. package/dist/assets/CrmParameterEditor-C22QGWff.js +1 -0
  8. package/dist/assets/EditorDrawer-CvCe9WeO.js +2 -0
  9. package/dist/assets/HideInsteadOfDeleteModal-3j9g-E9l.js +1 -0
  10. package/dist/assets/IconPickerModal-BLoDLbLR.js +1 -0
  11. package/dist/assets/ImportXmlModal-BD-L1QzJ.js +1 -0
  12. package/dist/assets/{MonacoEditor-uzfuRCpJ.js → MonacoEditor-BMKRZv-g.js} +1 -1
  13. package/dist/assets/NewButtonModal-COYXwEyk.js +1 -0
  14. package/dist/assets/NewGroupModal-boP_t1fI.js +1 -0
  15. package/dist/assets/NewTabModal-BI4afbC5.js +1 -0
  16. package/dist/assets/RuleEditorPanel-l8QnRFj6.js +1 -0
  17. package/dist/assets/ScriptView-BVyCmRvD.js +1 -0
  18. package/dist/assets/TabDisplayRulesPanel-gORq6MO7.js +1 -0
  19. package/dist/assets/TranslationsView-DubBATog.js +1 -0
  20. package/dist/assets/WebResourceBrowser-BATScmTw.js +1 -0
  21. package/dist/assets/XmlView-Bn4KlTw3.js +2 -0
  22. package/dist/assets/dnd-C1w9VFfC.js +5 -0
  23. package/dist/assets/fluent-icons-CQEhzzaC.js +1 -0
  24. package/dist/assets/fluent-ui-BEjALNLO.js +59 -0
  25. package/dist/assets/index-6so8O90C.js +136 -0
  26. package/dist/assets/index-D5GCH8nj.css +1 -0
  27. package/dist/assets/ruleKinds-BKTUiZ1-.js +1 -0
  28. package/dist/assets/useReplaceWebResourceConfirm-DND-V0vw.js +1 -0
  29. package/dist/assets/useStableKeys-BkDn7til.js +1 -0
  30. package/dist/assets/{xmlValidator-BkeotXuB.js → xmlValidator-PbODaIQV.js} +1 -1
  31. package/dist/icons/icon.svg +7 -4
  32. package/dist/index.html +15 -9
  33. package/index.html +10 -4
  34. package/package.json +1 -1
  35. package/dist/assets/BulkPublishModal-mJ41AWew.js +0 -36
  36. package/dist/assets/CommandEditorPanel-BiP1kPHY.js +0 -1
  37. package/dist/assets/CommandPalette-q51_0qRZ.js +0 -1
  38. package/dist/assets/ConflictDrawer-CdWv_PbN.js +0 -1
  39. package/dist/assets/DiffViewer-BQP5f73U.js +0 -7
  40. package/dist/assets/HideInsteadOfDeleteModal-C9r6ah5p.js +0 -1
  41. package/dist/assets/IconPickerModal-B81Tnf5i.js +0 -1
  42. package/dist/assets/ImportXmlModal-C0cMaS59.js +0 -1
  43. package/dist/assets/LocalizationEditor-DniDtrZV.js +0 -1
  44. package/dist/assets/NewButtonModal-BXpX1Ld5.js +0 -1
  45. package/dist/assets/NewGroupModal-Bh7lXq52.js +0 -1
  46. package/dist/assets/NewTabModal-Pntdk3in.js +0 -1
  47. package/dist/assets/RuleEditorPanel-BUGKgc0N.js +0 -1
  48. package/dist/assets/ScalingEditorPanel-p3-Yw3CO.js +0 -1
  49. package/dist/assets/TabDisplayRulesPanel-CSNshwaw.js +0 -1
  50. package/dist/assets/UrlComposerModal-WKSTwUcW.js +0 -1
  51. package/dist/assets/WebResourceBrowser-BK-gVU2g.js +0 -1
  52. package/dist/assets/XmlDrawer-CQJElnD1.js +0 -2
  53. package/dist/assets/dnd-Cq8OftAq.js +0 -5
  54. package/dist/assets/fluent-icons-BqJj6rDi.js +0 -1
  55. package/dist/assets/fluent-ui-QADO660t.js +0 -43
  56. package/dist/assets/index-D9lerlVA.css +0 -1
  57. package/dist/assets/index-Di2_5czx.js +0 -136
  58. package/dist/assets/ruleKinds-B9hACGaq.js +0 -1
  59. package/dist/assets/useReplaceWebResourceConfirm-BUWBVNSC.js +0 -1
  60. package/dist/assets/useStableKeys-p2OkzZWO.js +0 -1
@@ -0,0 +1,136 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./EditorDrawer-CvCe9WeO.js","./monaco-BIO15LCS.js","./monaco-DdLsZAcA.css","./fluent-icons-CQEhzzaC.js","./fluent-ui-BEjALNLO.js","./dnd-C1w9VFfC.js","./BulkPublishModal-DzDZJg0U.js","./MonacoEditor-BMKRZv-g.js","./xmlValidator-PbODaIQV.js","./ruleKinds-BKTUiZ1-.js","./crmParameters-rgfZhhzN.js","./NewButtonModal-COYXwEyk.js","./NewGroupModal-boP_t1fI.js","./NewTabModal-BI4afbC5.js","./ImportXmlModal-BD-L1QzJ.js","./CommandPalette-ID3kRJ9l.js","./IconPickerModal-BLoDLbLR.js","./useReplaceWebResourceConfirm-DND-V0vw.js","./WebResourceBrowser-BATScmTw.js","./HideInsteadOfDeleteModal-3j9g-E9l.js","./server.browser-xEJRzS2D.js"])))=>i.map(i=>d[i]);
2
+ import{K as me,L as a,m as Ie,M as dn,i as ln,N as vm,J as Pl,O as Fl,j as it,P as _l,Q as aa,U as ra,V as On,X as la,Y as ql,Z as ca,$ as ds,a0 as wm,a1 as Wl,a2 as Hl,a3 as Cm,a4 as Gl,a5 as bi,a6 as Im,a7 as Mn,a8 as Et,a9 as ao,aa as yo,ab as ar,ac as Dn,ad as ke,ae as rr,af as jm,ag as Rm,ah as $m,ai as Ul,aj as Nm,ak as Tm,al as km,am as Am,an as Om,ao as Mm,ap as Dm,aq as Em,ar as Bm,as as yi,at as Lm,au as zm,av as Pm,aw as Vl,ax as Fm,ay as _m,az as qm,aA as Wm,aB as Hm,aC as Gm,aD as Um,aE as Xl,aF as Vm,aG as Xm,aH as Km,aI as Ym,aJ as Jm,aK as Zm,aL as Qm,aM as Kl,aN as ep,aO as tp,aP as np,aQ as op,aR as sp,aS as ip,aT as ap,aU as rp,aV as lp,aW as cp,aX as Yl,aY as dp,aZ as da,a_ as up,a$ as mp,b0 as pp,b1 as Jl,b2 as fp,b3 as hp,b4 as gp,b5 as bp,b6 as yp,b7 as xp,b8 as Sp,b9 as vp,ba as wp,bb as Cp,bc as Ip,bd as jp,be as Rp,bf as $p,bg as Np,bh as Tp,bi as kp,bj as Bo,bk as Ap,bl as Op,bm as Mp,bn as Dp,bo as Ep,bp as Bp,bq as Lp,br as zp,bs as Zl,bt as Pp,bu as Ql,bv as Fp,bw as _p,bx as qp,by as Wp,bz as Hp,bA as Gp,bB as Up,bC as Vp,bD as Xp,bE as ec,bF as Kp,bG as Yp,bH as Jp,bI as us,bJ as Zp,bK as Qp,bL as ef,bM as tf,bN as nf,bO as of,bP as sf,bQ as xi,bR as af,bS as tc,bT as rf,bU as lf,bV as cf,bW as df,bX as uf,bY as nc,bZ as mf,b_ as oc,b$ as pf,c0 as ff,c1 as hf,c2 as gf,c3 as bf,c4 as yf,c5 as xf,h as Sf,c6 as sc,x as vf,y as wf,c7 as Si,c8 as Cf,c9 as If,ca as jf,cb as Rf,cc as $f,cd as Nf,ce as Tf,cf as ic,cg as kf,ch as Af,A as Of,ci as Mf,s as Df,cj as Ef,ck as Bf,cl as Lf,cm as zf,cn as Pf,co as ac,cp as Ff,cq as _f,cr as qf,cs as Wf,ct as Hf,cu as Gf,cv as vi,cw as Uf,cx as Vf,cy as Xf,cz as Kf,cA as Yf,cB as Jf,cC as Zf,cD as Qf,cE as rc,cF as eh,cG as th,cH as nh,cI as oh,cJ as sh,cK as ih,cL as ah,cM as rh,cN as lh,cO as ch,cP as dh,cQ as uh,cR as mh,cS as ph,cT as lr,cU as fh,cV as cr,cW as hh,cX as gh,cY as bh,cZ as dr,c_ as yh,c$ as xh,d0 as ur,d1 as Sh,d2 as vh,d3 as wh,d4 as Es,d5 as Ch,d6 as mr,d7 as Io,d8 as Ih,d9 as jo,da as jh,db as pr,dc as Rh,dd as fr,de as lc,df as cc,dg as dc,C as $h,dh as Nh,di as Th,dj as kh,dk as Ah,dl as Oh,dm as Mh,dn as Dh}from"./fluent-icons-CQEhzzaC.js";import{l as Eh,m as Bh,R as et,_ as ft,a as E}from"./monaco-BIO15LCS.js";import{a as Lh,T as pe,b as V,B as xe,t as h,C as ua,O as hr,c as wi,D as zh,d as Ph,e as Fh,f as _h,g as qh,h as K,i as Wh,j as gr,u as uc,P as ma,k as pa,l as fa,F as _e,I as Dt,m as ha,n as Hh,o as Pt,p as nn,q as Gh,M as Xe,s as Ke,v as Ye,w as Je,x as fe,y as Uh,z as ro,A as Sn,E as Mt,G as mc,H as ga,J as ba,K as Vh,L as Rt,N as $t,Q as pc,R as ms,S as $n,U as br,V as Ci,W as on,X as Ft,Y as ya,Z as Xh,_ as Kh,$ as Yh,a0 as yr,a1 as Fn,a2 as Jh,a3 as _n,a4 as lo,a5 as fc,a6 as qe,a7 as xa,a8 as sn,a9 as Zh,aa as Qh,ab as xr,ac as hc,ad as eg,ae as gc,af as Ze,ag as tg,ah as Sa,ai as _t,aj as ng,ak as og,al as Sr,am as bc,an as yc,ao as xc,ap as Sc,aq as sg,ar as ig,as as vc,at as va,au as wa,av as ag,aw as Lo,ax as Bs,ay as rg,az as lg,aA as yn,aB as cg,aC as dg,aD as ug,aE as mg,aF as wc,aG as pg,aH as fg,aI as hg,aJ as gg,aK as bg,aL as yg,aM as xg,aN as Sg,aO as vg,aP as wg,aQ as Cg,aR as Ig,aS as Zn,aT as qt,aU as Wt,aV as jg,aW as Rg,aX as $g}from"./fluent-ui-BEjALNLO.js";import{u as Ng,a as Cc,b as Go,D as Ic,c as jc,d as Rc,K as $c,P as Nc,e as Ca,p as vr,s as Tg,S as kg,v as Ag,f as Og,C as Mg,g as Dg}from"./dnd-C1w9VFfC.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&o(l)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function Eg(e){return new Worker(""+new URL("editor.worker-D1TDBLlL.js",import.meta.url).href,{name:e?.name})}function Bg(e){return new Worker(""+new URL("json.worker-BggoxaER.js",import.meta.url).href,{name:e?.name})}function Lg(e){return new Worker(""+new URL("ts.worker-BrLZGe_E.js",import.meta.url).href,{name:e?.name})}function zg(e){return new Worker(""+new URL("css.worker-C_6RgliQ.js",import.meta.url).href,{name:e?.name})}function Pg(e){return new Worker(""+new URL("html.worker-CLyYFd_g.js",import.meta.url).href,{name:e?.name})}Eh.config({monaco:Bh});self.MonacoEnvironment={getWorker(e,t){return t==="json"?new Bg:t==="typescript"||t==="javascript"?new Lg:t==="css"||t==="scss"||t==="less"?new zg:t==="html"||t==="handlebars"||t==="razor"?new Pg:new Eg}};var Ro={},wr;function Fg(){if(wr)return Ro;wr=1;var e=Lh();return Ro.createRoot=e.createRoot,Ro.hydrateRoot=e.hydrateRoot,Ro}var _g=Fg();const Cr=e=>{let t;const n=new Set,o=(d,u)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const m=t;t=u??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(g=>g(t,m))}},s=()=>t,r={setState:o,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(o,s,r);return r},qg=(e=>e?Cr(e):Cr),Wg=e=>e;function Hg(e,t=Wg){const n=et.useSyncExternalStore(e.subscribe,et.useCallback(()=>t(e.getState()),[e,t]),et.useCallback(()=>t(e.getInitialState()),[e,t]));return et.useDebugValue(n),n}const Gg=e=>{const t=qg(e),n=o=>Hg(t,o);return Object.assign(n,t),n},Xt=(e=>Gg);function Uo(e){if(!e||!e.id&&!e.url)return"";const t=(e.url??"").trim().replace(/\/+$/,"").toLowerCase();return`${e.id??""}|${t}`}function Tc(){return window.toolboxAPI?.connections}async function Ia(){const e=Tc();if(!e)return null;if(typeof e.getConnection=="function"){const t=await e.getConnection(0).catch(()=>null);if(t)return t}return typeof e.getActiveConnection=="function"?await e.getActiveConnection()??null:null}class Ii extends Error{constructor(t){super(`${t} was stopped: the tool's connection changed in Power Platform ToolBox. Nothing was written to the newly selected environment; anything already written by this operation went to the environment it started on.`),this.name="ConnectionChangedError"}}let Qn,ji=0;function Ir(e){const t=Uo(e);Qn!==void 0&&t!==Qn&&ji++,Qn=t}async function ps(e){const t=Tc();if(Qn===void 0||!t?.getConnection&&!t?.getActiveConnection)return;let n;try{n=Uo(await Ia())}catch{throw new Ii(e)}if(n!==Qn)throw new Ii(e)}function Ug(e){const t=window.toolboxAPI?.events;if(typeof t?.on!="function")return()=>{};let n=0;const o=(s,i)=>{const l=i?.event;if(l!=="connection:updated"&&l!=="connection:created"&&l!=="connection:deleted")return;const r=++n;Ia().then(c=>{r===n&&e(c)}).catch(()=>{})};return t.on(o),()=>t.off?.(o)}function kc(){const e=ji;return async t=>{if(ji!==e)throw new Ii(t);await ps(t)}}const Ri=new Set;function Vg(e){return Ri.add(e),()=>Ri.delete(e)}const ae=Xt()((e,t)=>({connectionId:"",connectionUrl:"",connectionName:"",environment:"Dev",publisherPrefix:"new",solutions:[],activeSolution:null,entities:[],activeEntity:null,solutionEntityIds:null,solutionRibbonComponentIds:null,currentUserId:"",currentUserName:"",connectionVersion:0,connectionNotice:null,setConnection:(n,o,s,i=t().connectionId)=>{Ir({id:i,url:n}),e({connectionId:i,connectionUrl:n,connectionName:o,environment:s})},switchConnection:(n,o)=>{const s=t();Ir(n),e({connectionId:n.id,connectionUrl:n.url,connectionName:n.name,environment:n.environment,publisherPrefix:"new",solutions:[],activeSolution:null,entities:[],activeEntity:null,solutionEntityIds:null,solutionRibbonComponentIds:null,currentUserId:"",currentUserName:"",connectionVersion:s.connectionVersion+1,connectionNotice:{...o,from:{name:s.connectionName,url:s.connectionUrl,environment:s.environment},to:{name:n.name,url:n.url,environment:n.environment}}})},dismissConnectionNotice:()=>e({connectionNotice:null}),setSolutions:n=>e({solutions:n}),setActiveSolution:n=>{ft(async()=>{const{useRuntimeLogStore:s}=await Promise.resolve().then(()=>eb);return{useRuntimeLogStore:s}},void 0,import.meta.url).then(({useRuntimeLogStore:s})=>{s.getState().logInfo("dataverse",`Active solution: "${n.friendlyName||n.uniqueName}" — publisher="${n.publisherUniqueName||"(empty)"}", prefix="${n.publisherPrefix||"(empty)"}"`),(!n.publisherPrefix||n.publisherPrefix==="new"||/^defaultpublisher/i.test(n.publisherUniqueName??""))&&s.getState().logWarn("dataverse",`Solution "${n.friendlyName||n.uniqueName}" uses the org's default publisher (prefix="${n.publisherPrefix||"new"}"). All IDs and imports from CBS will land under that publisher. To use your own (e.g. "mxrm"), create a new solution in maker.powerapps.com bound to your custom publisher and pick that one here.`)});const o=t().activeSolution?.id!==n.id;if(e({activeSolution:n,publisherPrefix:n.publisherPrefix||"new",...o?{activeEntity:null,entities:[],solutionEntityIds:null,solutionRibbonComponentIds:null}:{}}),o)for(const s of Ri)s()},setEntities:n=>e({entities:n}),setActiveEntity:n=>e({activeEntity:n}),setSolutionEntityIds:n=>e({solutionEntityIds:n}),setSolutionRibbonComponentIds:n=>e({solutionRibbonComponentIds:n}),setCurrentUser:(n,o)=>e({currentUserId:n,currentUserName:o}),setPublisherPrefix:n=>e({publisherPrefix:n})})),Xg=e=>(t,n,o)=>{const s=o.subscribe;return o.subscribe=((l,r,c)=>{let d=l;if(r){const u=c?.equalityFn||Object.is;let p=l(o.getState());d=m=>{const g=l(m);if(!u(p,g)){const b=p;r(p=g,b)}},c?.fireImmediately&&r(p,p)}return s(d)}),e(t,n,o)},Kg=Xg;function Yg(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const l=c=>c===null?null:JSON.parse(c,void 0),r=(i=n.getItem(s))!=null?i:null;return r instanceof Promise?r.then(l):l(r)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const $i=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(o){return $i(o)(n)},catch(o){return this}}}catch(n){return{then(o){return this},catch(o){return $i(o)(n)}}}},Jg=(e,t)=>(n,o,s)=>{let i={storage:Yg(()=>window.localStorage),partialize:y=>y,version:0,merge:(y,x)=>({...x,...y}),...t},l=!1,r=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return e((...y)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...y)},o,s);const p=()=>{const y=i.partialize({...o()});return u.setItem(i.name,{state:y,version:i.version})},m=s.setState;s.setState=(y,x)=>(m(y,x),p());const g=e((...y)=>(n(...y),p()),o,s);s.getInitialState=()=>g;let b;const f=()=>{var y,x;if(!u)return;const S=++r;l=!1,c.forEach(N=>{var O;return N((O=o())!=null?O:g)});const C=((x=i.onRehydrateStorage)==null?void 0:x.call(i,(y=o())!=null?y:g))||void 0;return $i(u.getItem.bind(u))(i.name).then(N=>{if(N)if(typeof N.version=="number"&&N.version!==i.version){if(i.migrate){const O=i.migrate(N.state,N.version);return O instanceof Promise?O.then(I=>[!0,I]):[!0,O]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,N.state];return[!1,void 0]}).then(N=>{var O;if(S!==r)return;const[I,j]=N;if(b=i.merge(j,(O=o())!=null?O:g),n(b,!0),I)return p()}).then(()=>{S===r&&(C?.(o(),void 0),b=o(),l=!0,d.forEach(N=>N(b)))}).catch(N=>{S===r&&C?.(void 0,N)})};return s.persist={setOptions:y=>{i={...i,...y},y.storage&&(u=y.storage)},clearStorage:()=>{++r,u?.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>f(),hasHydrated:()=>l,onHydrate:y=>(c.add(y),()=>{c.delete(y)}),onFinishHydration:y=>(d.add(y),()=>{d.delete(y)})},i.skipHydration||f(),b||g},Zg=Jg;function ot(e){const t=e.find(l=>l.kind==="command"),n=e[e.length-1],o=n?.kind==="rule"?n:null,s=e.find(l=>l.kind==="translations"),i=[...e].reverse().find(l=>l.kind==="diff");return{editorStack:e,commandEditorOpen:!!t,commandEditorId:t?.id??null,ruleEditorOpen:!!o,ruleEditorId:o?.id??null,ruleEditorKind:o?.ruleKind??null,tabDisplayRulesOpen:e.some(l=>l.kind==="tabRules"),xmlDrawerOpen:e.some(l=>l.kind==="xml"),diffViewerOpen:!!i,diffViewerMode:i?.id??"compare",localizationEditorOpen:!!s,localizationEditorButtonId:s?.id??null}}function Zt(e,t){return e[e.length-1]?.kind===t.kind?[...e.slice(0,-1),t]:[...e,t]}const Qg=e=>({leftPaneWidth:260,leftPaneTab:"structure",rightPaneWidth:340,bottomPanelHeight:220,bottomCollapsed:!0,rightPaneMode:"docked",themeMode:"light",ribbonViewStyle:"groups",activeBottomTab:"commands",editorStack:[],commandEditorOpen:!1,commandEditorId:null,ruleEditorOpen:!1,ruleEditorId:null,ruleEditorKind:null,commandEditorTab:"actions",xmlDrawerOpen:!1,bulkPublishOpen:!1,iconPickerOpen:!1,localizationEditorOpen:!1,localizationEditorButtonId:null,newGroupOpen:!1,newButtonGroupId:null,importXmlOpen:!1,importXmlSeed:"",importXmlNote:"",webResourceBrowserOpen:!1,diffViewerOpen:!1,diffViewerMode:"compare",tabDisplayRulesOpen:!1,commandPaletteOpen:!1,solutionPickerOpen:!1,tablePickerOpen:!1,propertiesRequested:!1,newTabOpen:!1,hideInsteadOfDelete:null,announcement:"",setLeftPaneWidth:t=>e({leftPaneWidth:t}),setRightPaneWidth:t=>e({rightPaneWidth:t}),setBottomPanelHeight:t=>e({bottomPanelHeight:t}),setBottomCollapsed:t=>e({bottomCollapsed:t}),setRightPaneMode:t=>e({rightPaneMode:t}),setThemeMode:t=>e({themeMode:t}),setRibbonViewStyle:t=>e({ribbonViewStyle:t}),setActiveBottomTab:t=>e({activeBottomTab:t}),openCommandEditor:t=>e(n=>({...ot(t?Zt(n.editorStack,{kind:"command",id:t}):[]),commandEditorTab:t&&t===n.commandEditorId?n.commandEditorTab:"actions"})),closeCommandEditor:()=>e(ot([])),openRuleEditor:(t,n)=>e(o=>ot(t?Zt(o.editorStack,{kind:"rule",id:t,ruleKind:n}):o.editorStack)),closeRuleEditor:()=>e(t=>ot(t.editorStack[t.editorStack.length-1]?.kind==="rule"?t.editorStack.slice(0,-1):t.editorStack)),setCommandEditorTab:t=>e({commandEditorTab:t}),openScriptView:(t,n)=>e(o=>ot(Zt(o.editorStack,{kind:"script",id:t,editable:n}))),editorBack:()=>e(t=>ot(t.editorStack.slice(0,-1))),closeEditor:()=>e(ot([])),openXmlDrawer:t=>e(n=>ot(Zt(n.editorStack,{kind:"xml",id:t}))),closeXmlDrawer:()=>e(t=>ot(t.editorStack.filter(n=>n.kind!=="xml"))),openBulkPublish:()=>e({bulkPublishOpen:!0}),closeBulkPublish:()=>e({bulkPublishOpen:!1}),openIconPicker:()=>e({iconPickerOpen:!0}),closeIconPicker:()=>e({iconPickerOpen:!1}),openLocalizationEditor:t=>e(n=>ot(Zt(n.editorStack,{kind:"translations",id:t}))),closeLocalizationEditor:()=>e(t=>ot(t.editorStack.filter(n=>n.kind!=="translations"))),openNewGroup:()=>e({newGroupOpen:!0}),closeNewGroup:()=>e({newGroupOpen:!1}),openNewButton:t=>e({newButtonGroupId:t}),closeNewButton:()=>e({newButtonGroupId:null}),openImportXml:(t,n)=>e({importXmlOpen:!0,importXmlSeed:typeof t=="string"?t:"",importXmlNote:typeof n=="string"?n:""}),closeImportXml:()=>e({importXmlOpen:!1}),openWebResourceBrowser:()=>e({webResourceBrowserOpen:!0}),closeWebResourceBrowser:()=>e({webResourceBrowserOpen:!1}),openDiffViewer:(t,n)=>e(o=>ot(Zt(o.editorStack,{kind:"diff",id:t,historyIndex:n}))),closeDiffViewer:()=>e(t=>ot(t.editorStack.filter(n=>n.kind!=="diff"))),openTabDisplayRules:(t,n)=>e(o=>ot(Zt(o.editorStack,{kind:"tabRules",id:n,location:t}))),setCommandPaletteOpen:t=>e({commandPaletteOpen:t}),setSolutionPickerOpen:t=>e({solutionPickerOpen:t}),setTablePickerOpen:t=>e({tablePickerOpen:t}),setLeftPaneTab:t=>e({leftPaneTab:t}),structureChoice:0,noteStructureChoice:()=>e(t=>({structureChoice:t.structureChoice+1})),setPropertiesRequested:t=>e({propertiesRequested:t}),openNewTab:()=>e({newTabOpen:!0}),closeNewTab:()=>e({newTabOpen:!1}),openHideInsteadOfDelete:t=>e({hideInsteadOfDelete:t}),closeHideInsteadOfDelete:()=>e({hideInsteadOfDelete:null}),announce:t=>e({announcement:t})}),Z=Xt()(Zg(Qg,{name:"cbs:ui",partialize:e=>({leftPaneWidth:e.leftPaneWidth,leftPaneTab:e.leftPaneTab,rightPaneWidth:e.rightPaneWidth,bottomPanelHeight:e.bottomPanelHeight,bottomCollapsed:e.bottomCollapsed,rightPaneMode:e.rightPaneMode,themeMode:e.themeMode,ribbonViewStyle:e.ribbonViewStyle})})),ce=Xt()((e,t)=>({entries:[],append:n=>{const s={id:`${Date.now()}-${t().entries.length+1}`,ts:new Date().toISOString(),...n};e({entries:[...t().entries,s].slice(-400)})},logInfo:(n,o)=>t().append({scope:n,level:"info",message:o}),logWarn:(n,o)=>t().append({scope:n,level:"warn",message:o}),logError:(n,o)=>t().append({scope:n,level:"error",message:o}),clear:()=>e({entries:[]})})),eb=Object.freeze(Object.defineProperty({__proto__:null,useRuntimeLogStore:ce},Symbol.toStringTag,{value:"Module"})),tb=new Set(["Default","InvertResult","PropertyValue","ExpectedValue","TrackedInCrm","PassParams","AllowCustomRelationship","AllowSystemRelationship"]),jr=["EnableRules","DisplayRules","Actions"];function nb(e,t){return tb.has(t)||e.tagName==="BoolParameter"&&t==="Value"}function ob(e){const t=e.trim();return t==="1"?"true":t==="0"?"false":t}function sb(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;")}function zo(e,t,n){const o=Array.from(e.attributes).map(l=>[l.name,nb(e,l.name)?ob(l.value):l.value]).sort(([l],[r])=>l<r?-1:l>r?1:0).map(([l,r])=>` ${l}="${sb(r)}"`).join(""),s=[];let i=[];for(const l of Array.from(e.childNodes))if(l.nodeType===1)i.push(l);else if(l.nodeType===3||l.nodeType===4){const r=(l.textContent??"").trim();r&&s.push(`${n} #text ${r}`)}if(t.normalizeCommands&&e.tagName==="CommandDefinition"){const l=new Map(i.map(d=>[d.tagName,d])),r=i.filter(d=>!jr.includes(d.tagName)),c=jr.map(d=>{const u=l.get(d);return u?zo(u,t,`${n} `):`${n} <${d}/>`});i=[],s.push(...c,...r.map(d=>zo(d,t,`${n} `)))}for(const l of i)s.push(zo(l,t,`${n} `));return s.length===0?`${n}<${e.tagName}${o}/>`:`${n}<${e.tagName}${o}>
3
+ ${s.join(`
4
+ `)}
5
+ ${n}</${e.tagName}>`}function Ac(e){const t=new DOMParser().parseFromString(e,"application/xml"),n=t.querySelector("parsererror");if(n)throw new Error(`XML parse error: ${n.textContent??"unknown"}`);return t.documentElement}function Nn(e,t={}){const n=typeof e=="string"?Ac(e):e;return zo(n,t,"")}function ib(e,t,n={}){try{return Nn(e,n)===Nn(t,n)}catch{return!1}}const vn={button:"Button",flyout:"FlyoutAnchor",splitButton:"SplitButton",textBox:"TextBox",comboBox:"ComboBox",checkBox:"CheckBox",toggleButton:"ToggleButton",label:"Label",dropDown:"DropDown",mruSplitButton:"MRUSplitButton",spinner:"Spinner",galleryButton:"GalleryButton"},Oc=Object.fromEntries(Object.entries(vn).map(([e,t])=>[t,e])),ab=new Set(["toggleButton","label","dropDown","mruSplitButton","spinner","galleryButton"]);function dt(e){return!!e&&ab.has(e)}const Mc=["Command","QueryCommand","MenuCommand","PopulateQueryCommand","CommandMenuOpen","CommandMenuClose","CommandPreview","CommandPreviewRevert","CommandRevert"],Dc=new RegExp(`\\s(?:${Mc.join("|")})="([^"]+)"`,"g");function Ec(e){const t=new Set(e.commandId?[e.commandId]:[]),n=e.source?.attributes.PopulateQueryCommand;if(n&&(e.kind==="flyout"||e.kind==="splitButton")&&t.add(n),dt(e.kind))for(const o of e.source?.xml?.matchAll(Dc)??[])t.add(o[1]);return[...t]}function rb(e,t,n){const o=s=>s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;");return e.replace(Dc,(s,i)=>i===t||i===o(t)?s.replace(`"${i}"`,`"${o(n)}"`):s)}const yt={button:"Button",flyout:"Flyout",splitButton:"Split button",textBox:"Text box",comboBox:"Combo box",checkBox:"Check box",toggleButton:"Toggle button",label:"Label",dropDown:"Drop-down",mruSplitButton:"MRU split button",spinner:"Spinner",galleryButton:"Gallery button"};function Bc(e,t){const n=t.length>0?Math.min(...t):1/0,o=e.filter(s=>s<n);return{after:o.length>0?Math.max(...o):0,before:n}}function Lc(e,t){let n=e.after>0?e.after+1:e.before>10?10:1;for(;t.has(n);)n++;return n<e.before?n:void 0}function zc(e,t,n){const o=[],s=[],i=new Set([...t.maxSizes,...t.scales]),l=(m,g)=>{o.push({tabId:e,id:m.id,kind:m.kind,groupId:m.groupId,from:m.sequence,to:g}),i.add(g)},r=n.filter(m=>m.kind==="Scale"),c=[];for(const m of r)i.has(m.sequence)?c.push(m):i.add(m.sequence);for(const m of c)l(m,Math.max(0,...i)+1);const d=[...t.scales,...r.map(m=>o.find(g=>g.id===m.id&&g.kind==="Scale")?.to??m.sequence)],u=Bc(t.maxSizes,d),p=[];for(const m of n.filter(g=>g.kind==="MaxSize"))m.sequence<u.before&&!i.has(m.sequence)?i.add(m.sequence):p.push(m);for(const m of p){const g=Lc(u,i);g===void 0?s.push(`The scaling of tab ${e} has no free position for MaxSize ${m.id} (Sequence ${m.sequence}): it must come before the first Scale (${u.before}) and use a Sequence no other step uses`):l(m,g)}return{changes:o,problems:s}}function lb(e){return`Repaired the scaling of tab ${e.tabId}: ${e.kind} ${e.id} (group ${e.groupId}) moves from Sequence ${e.from} to ${e.to}, so no two scaling steps share a Sequence`}function En(){return{customActions:new Map,templates:new Map,commandDefinitions:new Map,tabDisplayRules:new Map,displayRules:new Map,enableRules:new Map,locLabels:new Map}}const Tn=()=>new XMLSerializer;function Pc(e){const t=new DOMParser().parseFromString(e,"application/xml"),n=t.querySelector("parsererror");if(n)throw new Error(`Invalid RibbonDiffXml: ${n.textContent??"parse error"}`);return t}function kt(e,t){return e?Array.from(e.children).filter(n=>n.tagName===t):[]}function Se(e,t){return kt(e,t)[0]}function Fc(e){if(e.tagName==="HideCustomAction"){const n=e.getAttribute("HideActionId");return n?`hide:${n}`:null}const t=e.getAttribute("Id");return t?`ca:${t}`:null}function Z0(e){const t=En(),o=Pc(e).documentElement;if(o.tagName!=="RibbonDiffXml")throw new Error(`Expected <RibbonDiffXml> root, got <${o.tagName}>`);const s=Tn();for(const r of Array.from(Se(o,"CustomActions")?.children??[])){const c=Fc(r);c&&t.customActions.set(c,s.serializeToString(r))}const i=Se(Se(o,"Templates"),"RibbonTemplates");for(const r of Array.from(i?.children??[])){const c=r.getAttribute("Id");c&&t.templates.set(c,s.serializeToString(r))}for(const r of kt(Se(o,"CommandDefinitions"),"CommandDefinition")){const c=r.getAttribute("Id");c&&t.commandDefinitions.set(c,s.serializeToString(r))}const l=Se(o,"RuleDefinitions");for(const r of kt(Se(l,"TabDisplayRules"),"TabDisplayRule")){const c=r.getAttribute("TabCommand");c&&t.tabDisplayRules.set(c,s.serializeToString(r))}for(const r of kt(Se(l,"DisplayRules"),"DisplayRule")){const c=r.getAttribute("Id");c&&t.displayRules.set(c,s.serializeToString(r))}for(const r of kt(Se(l,"EnableRules"),"EnableRule")){const c=r.getAttribute("Id");c&&t.enableRules.set(c,s.serializeToString(r))}for(const r of kt(Se(o,"LocLabels"),"LocLabel")){const c=r.getAttribute("Id");c&&t.locLabels.set(c,s.serializeToString(r))}return t}function ve(e){return Pc(e).documentElement}function cb(e){const t=En();for(const n of e.diffs){const o=n.rdx?.trim();if(!o)continue;const s=ve(o);switch(n.difftype){case 3:{const i=s.getAttribute("Id")??n.diffid;i&&t.locLabels.set(i,o);break}case 2:{const i=s.getAttribute("Id")??n.diffid;i&&t.templates.set(i,o);break}default:{const i=Fc(s);i&&t.customActions.set(i,o)}}}for(const n of e.commands){const o=n.commanddefinition?.trim(),s=n.command??(o?ve(o).getAttribute("Id"):null);o&&s&&t.commandDefinitions.set(s,o)}for(const n of e.rules){const o=n.ruledefinition?.trim();if(!o)continue;const s=ve(o);if(n.ruletype===3||s.tagName==="TabDisplayRule"){const i=s.getAttribute("TabCommand")??n.ruleid;i&&t.tabDisplayRules.set(i,o)}else if(n.ruletype===1||s.tagName==="EnableRule"){const i=s.getAttribute("Id")??n.ruleid;i&&t.enableRules.set(i,o)}else{const i=s.getAttribute("Id")??n.ruleid;i&&t.displayRules.set(i,o)}}return t}function ja(e,t){const n=En();for(const o of Object.keys(n)){for(const[s,i]of e[o])n[o].set(s,i);for(const[s,i]of t[o])n[o].set(s,i)}return n}function Q0(e){const t=(n,o)=>Array.from(n.values()).map(s=>`${o}${s}`).join(`
6
+ `);return`<RibbonDiffXml>
7
+ <CustomActions>
8
+ ${t(e.customActions," ")}
9
+ </CustomActions>
10
+ <Templates>
11
+ <RibbonTemplates Id="Mscrm.Templates">
12
+ ${t(e.templates," ")}
13
+ </RibbonTemplates>
14
+ </Templates>
15
+ <CommandDefinitions>
16
+ ${t(e.commandDefinitions," ")}
17
+ </CommandDefinitions>
18
+ <RuleDefinitions>
19
+ <TabDisplayRules>
20
+ ${t(e.tabDisplayRules," ")}
21
+ </TabDisplayRules>
22
+ <DisplayRules>
23
+ ${t(e.displayRules," ")}
24
+ </DisplayRules>
25
+ <EnableRules>
26
+ ${t(e.enableRules," ")}
27
+ </EnableRules>
28
+ </RuleDefinitions>
29
+ <LocLabels>
30
+ ${t(e.locLabels," ")}
31
+ </LocLabels>
32
+ </RibbonDiffXml>`}function db(e){if(e.tagName!=="JavaScriptFunction")return!1;const t=(e.getAttribute("Library")??"").trim(),n=e.getAttribute("FunctionName")??"";return t.startsWith("/_")||/^\$webresource:Main_system_library\.js$/i.test(t)||/^(XrmCore|Mscrm)\./.test(n)}function Rr(e,t){const n=ve(t);if(e==="commandDefinitions")for(const o of Array.from(n.getElementsByTagName("JavaScriptFunction")))db(o)&&o.parentNode?.replaceChild(n.ownerDocument.createElement("PlatformJavaScriptFunction"),o);if(e==="locLabels")for(const o of Array.from(n.getElementsByTagName("Titles"))){const s=Array.from(o.children).sort((i,l)=>Number(i.getAttribute("languagecode"))-Number(l.getAttribute("languagecode")));for(const i of s)o.appendChild(i)}return Nn(n,{normalizeCommands:e==="commandDefinitions"})}const _c=(e,t,n)=>{try{return Rr(e,t)===Rr(e,n)}catch{return t===n}},$r=e=>Array.from(ve(e).getElementsByTagName("Title")).map(t=>`${t.getAttribute("languagecode")}=${t.getAttribute("description")??""}`);function ub(e,t,n){if(e!=="locLabels")return _c(e,t,n);try{const o=new Set($r(t)),s=$r(n);return s.length>0&&s.every(i=>o.has(i))}catch{return t===n}}function eI(e,t){const n=[];for(const o of Object.keys(t))for(const[s,i]of t[o]){const l=e[o].get(s);(l===void 0||!_c(o,l,i))&&n.push(`${o}:${s}`)}return n}function tI(e,t,n={}){const o=[],s=[],i=[],l=new Set(n.contentKeys??[]);for(const r of Object.keys(e)){for(const[c,d]of e[r]){const u=t[r].get(c);u===void 0?o.push(`${r}:${c}`):l.has(`${r}:${c}`)&&!ub(r,d,u)&&i.push(`${r}:${c}`)}for(const c of t[r].keys())e[r].has(c)||s.push(`${r}:${c}`)}return{missing:o,unexpected:s,differing:i}}function nI(e){return Object.values(e).reduce((t,n)=>t+n.size,0)}function Ls(e){const t=ve(e);return t.tagName!=="CustomAction"?null:Se(t,"CommandUIDefinition")?.firstElementChild??null}function bt(e){return!!e&&e.endsWith("._children")}const mb=new Set(["Menu","MenuSection","Controls"]);function Ni(e){return e.tagName==="Tab"||e.tagName==="Group"?[]:Array.from(e.getElementsByTagName("*")).filter(t=>!mb.has(t.tagName)&&!!t.getAttribute("Id")&&t.parentElement?.tagName==="Controls")}const co=e=>e?.tagName==="Tab"||e?.tagName==="Group",Nr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function qc(e){return Array.from(e.getElementsByTagName("Controls")).flatMap(t=>Array.from(t.children))}function Wc(e,t){if(e.getAttribute("Id")===t)return e;for(const n of Array.from(e.getElementsByTagName("*")))if(n.getAttribute("Id")===t)return n;return null}function Vo(e){return co(e)?qc(e):Ni(e)}function Xo(e){const t=new Set;for(const n of e.customActions.values()){const o=ve(n);if(o.tagName!=="CustomAction"||!bt(o.getAttribute("Location")))continue;const s=Se(o,"CommandUIDefinition")?.firstElementChild,i=s?.getAttribute("Id");if(i&&t.add(i),s)for(const l of Vo(s)){const r=l.getAttribute("Id");r&&t.add(r)}}return t}function Hc(e,t){const n=new Map(e),o=Tn(),s=t?new Set(t):void 0;for(let i=!0;i;){i=!1;const l=new Map;for(const[r,c]of n){const d=ve(c);if(d.tagName!=="CustomAction"||!bt(d.getAttribute("Location")))continue;const u=Se(d,"CommandUIDefinition")?.firstElementChild;if(co(u))for(const p of[u,...Array.from(u.getElementsByTagName("Group"))]){const m=p.getAttribute("Id");m&&!l.has(m)&&l.set(m,r)}}for(const[r,c]of n){const d=ve(c);if(d.tagName!=="CustomAction")continue;const u=/^(.+)\.(Controls|Groups|Scaling)\._children$/.exec(d.getAttribute("Location")??""),p=Se(d,"CommandUIDefinition")?.firstElementChild,m=u?l.get(u[1]):void 0;if(!u||!p||!m||m===r||s&&!s.has(r)&&!s.has(m))continue;const[,g,b]=u,f=ve(n.get(m)),y=Wc(f,g);if(!y||y.tagName!==(b==="Controls"?"Group":"Tab"))continue;const x=f.ownerDocument;let S=Se(y,b);if(!S){S=x.createElement(b),S.setAttribute("Id",`${g}.${b}`);const I=b==="Scaling"?Se(y,"Groups"):void 0;y.insertBefore(S,I??null)}const C=x.importNode(p,!0),N=d.getAttribute("Sequence");!C.getAttribute("Sequence")&&N&&C.setAttribute("Sequence",N);const O=C.tagName==="MaxSize"?Se(S,"Scale"):void 0;S.insertBefore(C,O??null),n.set(m,o.serializeToString(f)),s?.add(m),n.delete(r),i=!0;break}}return n}function pb(e,t){const n=Se(e,"CommandUIDefinition")?.firstElementChild??null;return n?n.getAttribute("Id")===t?n:Vo(n).find(o=>o.getAttribute("Id")===t)??null:null}function Gc(e){const t=new Set;for(const n of e.customActions.values()){const o=ve(n);if(o.tagName!=="CustomAction"||!bt(o.getAttribute("Location")))continue;const s=Se(o,"CommandUIDefinition")?.firstElementChild;if(!s||s.tagName!=="Tab"&&s.tagName!=="Group")continue;const i=s.getAttribute("Id");i&&t.add(i);for(const l of Array.from(s.getElementsByTagName("Group"))){const r=l.getAttribute("Id");r&&t.add(r)}}return t}function fs(e){const t=[];for(const n of e.customActions.values()){const o=ve(n);if(o.tagName!=="HideCustomAction")continue;const s=o.getAttribute("Location");s&&t.push({hideActionId:o.getAttribute("HideActionId")??"",location:s})}return t}function fb(e){const t=[],n=e.getAttribute("Id");n&&t.push(n);for(const o of Array.from(e.getElementsByTagName("*"))){const s=o.getAttribute("Id");s&&t.push(s)}return t}function eo(e){const t=[];for(const n of[e,...Array.from(e.getElementsByTagName("*"))])for(const o of Mc){const s=n.getAttribute(o);s&&t.push(s)}return t}function Uc(e){const t=new Set;for(const n of e.customActions.values()){const o=ve(n);if(o.tagName==="CustomAction")for(const s of eo(o))t.add(s)}return t}function hb(e){return/^(Mscrm|Microsoft)\./.test(e)}function Ra(e,t){if(hb(e))return!0;for(const n of t)if(n===e)return!1;return!0}function gb(e){const t=e?.match(/^(.+)\.(?:Controls|Groups)\._children$/);return t?t[1]:null}function Po(e,t){if(!t||e.children.length>0||t.children.length===0)return e;for(const n of Array.from(t.children))e.appendChild(e.ownerDocument.importNode(n,!0));return e}function Tr(e,t){for(const n of Array.from(t.attributes))t.removeAttribute(n.name);for(const n of Array.from(e.attributes))t.setAttribute(n.name,n.value)}function bb(e,t,n){const o=kt(e,"Menu")[0],s=kt(t,"Menu")[0];if(!o){for(const r of Ni(t))n(r.getAttribute("Id")??"")&&r.parentNode?.removeChild(r);return Po(t,e)}const i=o.cloneNode(!0),l=(r,c)=>[i,...Array.from(i.getElementsByTagName("*"))].find(d=>d.getAttribute("Id")===c&&(r?d.tagName===r:d.parentElement?.tagName==="Controls"));if(s){for(const r of Array.from(s.getElementsByTagName("MenuSection"))){const c=l("MenuSection",r.getAttribute("Id")??"");if(c){Tr(r,c);continue}const d=l("Menu",r.parentElement?.getAttribute("Id")??"");if(!d)continue;const u=r.cloneNode(!0);for(const p of Array.from(u.getElementsByTagName("*")))p.parentElement?.tagName==="Controls"&&n(p.getAttribute("Id")??"")&&p.parentNode?.removeChild(p);d.appendChild(u)}for(const r of Ni(t)){const c=r.getAttribute("Id")??"";if(n(c))continue;const d=l(null,c);if(d){Tr(r,d);continue}const u=l("Controls",r.parentElement?.getAttribute("Id")??"");u&&u.appendChild(r.cloneNode(!0))}}for(const r of kt(t,"Menu"))t.removeChild(r);return t.appendChild(i),t}const zs=/\$LocLabels:([^"'\s]+)/g;function kr(e){const t=new Set;for(const n of e)for(const o of eo(ve(n)))t.add(o);return t}function yb(e){const t=new Set;for(const n of e){const o=ve(n);for(const s of[o,...Array.from(o.getElementsByTagName("*"))])for(const i of Array.from(s.attributes))i.value.startsWith("$LocLabels:")&&t.add(i.value.slice(11))}return t}function $o(e){const t={EnableRule:new Set,DisplayRule:new Set};for(const n of e){const o=ve(n);for(const s of["EnableRule","DisplayRule"])for(const i of Array.from(o.getElementsByTagName(s))){const l=i.getAttribute("Id");l&&t[s].add(l)}}return t}function oI(e,t,n={}){const o=new Set(n.editedCommandIds??[]),s=new Set(n.editedEnableRuleIds??[]),i=new Set(n.editedDisplayRuleIds??[]),l=new Set(n.deletedControlIds??[]),r=new Set(n.unhiddenControlIds??[]),c=new Set(n.retainedCommandIds??[]),d=Tn(),u=ja(e,En()),p=new Map,m=new Map,g=[];for(const[k,v]of e.customActions){const T=Ls(v),R=ve(v);if(R.tagName!=="CustomAction")continue;const D=R.getAttribute("Location");if(T?.getAttribute("Id")&&bt(D)){p.set(T.getAttribute("Id"),k);for(const q of Vo(T)){const X=q.getAttribute("Id");X&&g.push([X,k])}}else D&&m.set(D,k)}for(const[k,v]of g)p.has(k)||p.set(k,v);const b=(k,v)=>{const T=u.customActions.get(k);if(!T)return{ca:null,el:null,nested:!1};const R=ve(T),D=pb(R,v);return{ca:R,el:D,nested:!!D&&D.parentElement?.tagName!=="CommandUIDefinition"}},f=new Set;for(const[k,v]of t.customActions){const T=ve(v),R=Ls(v),D=R?.getAttribute("Id")??null,q=D?p.get(D):void 0,X=T.tagName==="CustomAction"&&bt(T.getAttribute("Location"));X&&D&&f.add(D);const ne=R?.tagName==="Tab"||R?.tagName==="Group";if(X&&ne)for(const G of qc(R)){const U=G.getAttribute("Id");if(!U)continue;f.add(U);const te=p.get(U),P=te?b(te,U):null;!te||!P?.ca||!P.el||(P.nested?(P.el.parentNode.removeChild(P.el),u.customActions.set(te,d.serializeToString(P.ca))):u.customActions.delete(te))}const re=T.tagName==="CustomAction"&&R&&D&&q&&!(X&&ne),le=re?b(q,D):null;if(re&&le?.ca&&le.el&&le.nested){const{ca:G,el:U}=le;if(X)U.parentNode.removeChild(U),u.customActions.set(k,v);else{const te=Po(G.ownerDocument.importNode(R,!0),U);U.parentNode.replaceChild(te,U)}u.customActions.set(q,d.serializeToString(G));continue}if(re&&le?.ca&&le.el){const{ca:G,el:U,nested:te}=le;if(X&&te){U.parentNode.removeChild(U),u.customActions.set(q,d.serializeToString(G)),u.customActions.set(k,v);continue}let P=G.ownerDocument.importNode(R,!0);if(X?P=bb(U,P,Q=>{const be=p.get(Q);return!!be&&be!==q}):P=Po(P,U),U.parentNode.replaceChild(P,U),!te){X&&G.setAttribute("Location",T.getAttribute("Location"));const Q=R.getAttribute("Sequence")??(X?T.getAttribute("Sequence"):null);Q&&G.setAttribute("Sequence",Q)}u.customActions.set(q,d.serializeToString(G));continue}const F=T.getAttribute("Location"),L=T.tagName==="CustomAction"&&F?m.get(F):void 0;if(L&&R){const G=Ls(e.customActions.get(L)),U=ve(v),te=Se(U,"CommandUIDefinition");te?.firstElementChild&&Po(te.firstElementChild,G),u.customActions.delete(L),u.customActions.set(k,d.serializeToString(U));continue}u.customActions.set(k,v)}for(const{id:k,sequence:v}of n.resequencedContainers??[])for(const[T,R]of u.customActions){const D=ve(R),q=Se(D,"CommandUIDefinition");if(D.tagName!=="CustomAction"||!q)continue;const X=q.firstElementChild,ne=X?.getAttribute("Id")===k?X:Array.from(q.getElementsByTagName("*")).find(re=>(re.tagName==="Group"||re.tagName==="Tab")&&re.getAttribute("Id")===k);ne&&(ne.setAttribute("Sequence",String(v)),ne===X&&D.setAttribute("Sequence",String(v)),u.customActions.set(T,Tn().serializeToString(D)))}for(const k of n.movedControls??[]){const v=p.get(k.id),T=v?b(v,k.id):null;if(!v||!T?.ca||!T.el){if(f.has(k.id))continue;throw new Error(`Can't move ${k.id}: it isn't in this table's unmanaged customizations.`)}const{ca:R,el:D}=T,q=k.controlsId??`${k.groupId}.Controls`;if(D.setAttribute("Sequence",String(k.sequence)),!T.nested)R.setAttribute("Location",`${q}._children`),R.setAttribute("Sequence",String(k.sequence));else if(D.parentElement?.getAttribute("Id")!==q){const X=Array.from(R.getElementsByTagName("Controls")).find(ne=>ne.getAttribute("Id")===q);if(D.parentNode.removeChild(D),X)X.appendChild(D);else{let ne=`${k.id}.CustomAction`;for(;u.customActions.has(`ca:${ne}`);)ne+="_";u.customActions.set(`ca:${ne}`,`<CustomAction Id="${Nr(ne)}" Location="${Nr(`${q}._children`)}" Sequence="${k.sequence}"><CommandUIDefinition>${d.serializeToString(D)}</CommandUIDefinition></CustomAction>`)}}u.customActions.set(v,d.serializeToString(R))}const y=new Set,x=new Set;for(const[k,v]of Array.from(u.customActions)){const T=ve(v);if(T.tagName==="HideCustomAction"){r.has(T.getAttribute("Location")??"")&&u.customActions.delete(k);continue}const R=Se(T,"CommandUIDefinition")?.firstElementChild??null,D=R?.getAttribute("Id");if(!R||!bt(T.getAttribute("Location")))continue;if(D&&l.has(D)&&!f.has(D)){u.customActions.delete(k);for(const X of v.matchAll(zs))x.add(X[1]);for(const X of eo(R))y.add(X);continue}const q=Vo(R).filter(X=>{const ne=X.getAttribute("Id")??"";return l.has(ne)&&!f.has(ne)});if(q.length!==0){for(const X of q){const ne=d.serializeToString(X);for(const re of ne.matchAll(zs))x.add(re[1]);for(const re of eo(X))y.add(re);X.parentNode?.removeChild(X)}u.customActions.set(k,d.serializeToString(T))}}const S=new Set,C=new Set(n.deletedContainerIds??[]),N=(k,v)=>{for(const T of fb(k))C.add(T);for(const T of eo(k))y.add(T);for(const T of[k,...Array.from(k.getElementsByTagName("Tab"))]){const R=T.tagName==="Tab"?T.getAttribute("Command"):null;R&&S.add(R)}for(const T of v.matchAll(zs))x.add(T[1])};for(let k=C.size>0;k;){k=!1;for(const[v,T]of Array.from(u.customActions)){const R=ve(T),D=R.getAttribute("Location");if(R.tagName==="HideCustomAction"){D&&C.has(D)&&(u.customActions.delete(v),k=!0);continue}const q=Se(R,"CommandUIDefinition")?.firstElementChild??null,X=q?.getAttribute("Id")??null,ne=gb(D);if(!!X&&C.has(X)&&bt(D)||!!ne&&C.has(ne)||!bt(D)&&!!D&&C.has(D)||!!q?.getAttribute("GroupId")&&C.has(q.getAttribute("GroupId"))){u.customActions.delete(v),q&&N(q,T),k=!0;continue}if(q?.tagName!=="Tab")continue;const le=Array.from(q.getElementsByTagName("*")).filter(F=>F.tagName==="Group"?C.has(F.getAttribute("Id")??""):(F.tagName==="MaxSize"||F.tagName==="Scale")&&C.has(F.getAttribute("GroupId")??""));if(le.length!==0){for(const F of le)N(F,d.serializeToString(F)),F.parentNode?.removeChild(F);u.customActions.set(v,d.serializeToString(R)),k=!0}}}const O=new Set;for(const[k,v]of u.customActions)e.customActions.get(k)!==v&&O.add(k);u.customActions=Hc(u.customActions,O);const I=(k,v)=>{for(const[T,R]of t[k])e[k].has(T)&&!v.has(T)||u[k].set(T,R)};I("commandDefinitions",o),I("enableRules",s),I("displayRules",i);const j=kr(u.customActions.values());for(const k of y){if(c.has(k)||!u.commandDefinitions.has(k)||j.has(k))continue;const v=u.commandDefinitions.get(k);u.commandDefinitions.delete(k);const T=$o([v]),R=$o(u.commandDefinitions.values());for(const D of T.EnableRule)R.EnableRule.has(D)||u.enableRules.delete(D);for(const D of T.DisplayRule)R.DisplayRule.has(D)||u.displayRules.delete(D)}const $={EnableRule:new Set(n.retainedEnableRuleIds??[]),DisplayRule:new Set(n.retainedDisplayRuleIds??[])},w=Uc(u);for(const k of n.uncustomisedCommandIds??[]){const v=u.commandDefinitions.get(k);if(v===void 0||t.commandDefinitions.has(k)||!Ra(k,w))continue;u.commandDefinitions.delete(k);const T=$o(u.commandDefinitions.values()),R=$o([v]);for(const D of["EnableRule","DisplayRule"])for(const q of R[D]){const X=D==="EnableRule"?u.enableRules:u.displayRules;(D==="EnableRule"?t.enableRules:t.displayRules).has(q)||$[D].has(q)||T[D].has(q)||X.delete(q)}}for(const[k,v]of t.tabDisplayRules)u.tabDisplayRules.set(k,v);for(const[k,v]of t.templates)u.templates.set(k,v);const A=yb(u.customActions.values());for(const k of x)!t.locLabels.has(k)&&!A.has(k)&&u.locLabels.delete(k);const B=kr(u.customActions.values());for(const k of S)!t.tabDisplayRules.has(k)&&!B.has(k)&&u.tabDisplayRules.delete(k);for(const k of n.removedTabCommands??[])t.tabDisplayRules.has(k)||u.tabDisplayRules.delete(k);for(const[k,v]of t.locLabels){if(e.locLabels.get(k)){const R=Array.from(ve(v).querySelectorAll("Title")).map(D=>D.getAttribute("description"));if(R.length>0&&R.every(D=>D===k))continue}u.locLabels.set(k,v)}return u}function sI(e,t,n){const o=ja(e,En());for(const[s,i]of o.customActions){const l=ve(i);if(l.tagName!=="CustomAction"||!bt(l.getAttribute("Location")))continue;const r=Se(l,"CommandUIDefinition")?.firstElementChild;if(!co(r))continue;const c=Wc(r,t);if(!(!c||!co(c))){c.setAttribute("Title",n),o.customActions.set(s,Tn().serializeToString(l));break}}return o}function $a(e){const t=[],n=(o,s,i)=>({id:o.getAttribute("Id")??"",kind:o.tagName,groupId:o.getAttribute("GroupId")??"",sequence:Number(o.getAttribute("Sequence")??"0"),size:o.getAttribute("Size")??"",tabId:s,key:i});for(const[o,s]of e.customActions){const i=ve(s);if(i.tagName!=="CustomAction")continue;const l=Se(i,"CommandUIDefinition")?.firstElementChild;if(!l)continue;const r=/^(.+)\.Scaling\._children$/.exec(i.getAttribute("Location")??"");if(r&&(l.tagName==="MaxSize"||l.tagName==="Scale")&&t.push(n(l,r[1],o)),l.tagName==="Tab"&&bt(i.getAttribute("Location"))){const c=l.getAttribute("Id")??"";for(const d of Array.from(Se(l,"Scaling")?.children??[]))(d.tagName==="MaxSize"||d.tagName==="Scale")&&t.push(n(d,c,o))}}return t}function iI(e,t){const n=$a(e),o=new Map;for(const c of n)o.set(c.tabId,[...o.get(c.tabId)??[],c]);const s=[],i=[];for(const[c,d]of o){const u=zc(c,t[c]??{maxSizes:[],scales:[]},d);s.push(...u.changes),i.push(...u.problems)}if(s.length===0)return{parts:e,changes:s,problems:i};const l=ja(e,En()),r=Tn();for(const c of s){const d=n.find(g=>g.id===c.id&&g.kind===c.kind&&g.tabId===c.tabId),u=ve(l.customActions.get(d.key)),p=Se(u,"CommandUIDefinition").firstElementChild;(p.tagName==="Tab"?Array.from(Se(p,"Scaling")?.children??[]).find(g=>g.tagName===c.kind&&g.getAttribute("Id")===c.id):p)?.setAttribute("Sequence",String(c.to)),p.tagName!=="Tab"&&u.setAttribute("Sequence",String(c.to)),l.customActions.set(d.key,r.serializeToString(u))}return{parts:l,changes:s,problems:i}}function xb(e,t){const n=new Map;for(const s of t.customActions.values()){const i=ve(s);if(i.tagName!=="CustomAction"||!bt(i.getAttribute("Location")))continue;const l=Se(i,"CommandUIDefinition")?.firstElementChild;if(co(l))for(const r of[l,...Array.from(l.getElementsByTagName("Group"))]){const c=r.getAttribute("Id"),d=r.getAttribute("Title");c&&d?.startsWith("$LocLabels:")&&n.set(c,d)}}for(const s of e.tabs){const i=n.get(s.id);i&&(s.label=i);for(const l of s.groups){const r=n.get(l.id);r&&(l.label=r)}}const o=new Set(e.tabs.map(s=>s.id));for(const s of $a(t)){if(!o.has(s.tabId))continue;e.scalingByTab=e.scalingByTab??{};const i=e.scalingByTab[s.tabId]=e.scalingByTab[s.tabId]??{tabId:s.tabId,maxSizes:[],scales:[]},l=s.kind==="MaxSize"?i.maxSizes:i.scales,r={id:s.id,groupId:s.groupId,size:s.size,sequence:s.sequence},c=l.findIndex(d=>d.id===s.id);c>=0?l[c]=r:l.push(r)}}function He(e,t,n=1033){if(!e)return"";const o=e.match(/^\$LocLabels:(.+)$/);if(o){const i=o[1],l=t.find(r=>r.id===i);if(l){const r=l.titles.find(u=>u.languageCode===n),c=l.titles.find(u=>u.languageCode===1033),d=l.titles[0];return r?.description??c?.description??d?.description??i}return i}const s=e.match(/^\$Resources(?:\([^)]*\))?:(.+)$/);return s?s[1]:e}function to(e){return!!e&&/^\$Resources(\([^)]*\))?:/.test(e)}function Vc(e){return`$LocLabels:${e}`}function Xc(e){const t=e.match(/^\$LocLabels:(.+)$/);return t?t[1]:null}const Ar=128;function hs(e,t){const n=`${e}.${t}`;if(n.length<=Ar)return n;const o=Sb(e),s=Ar-t.length-o.length-2;return`${e.slice(0,s)}_${o}.${t}`}function Sb(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function gs(e){return hs(e,"LabelText")}function bs(e){return hs(e,"ToolTipTitle")}function ys(e){return hs(e,"ToolTipDescription")}function vb(e){return hs(e,"Title")}function wb(e,t){const n=(o,s)=>(o?Xc(o):null)??s;return{label:n(t?.labelToken,gs(e)),tooltipTitle:n(t?.tooltipTitleToken,bs(e)),tooltipBody:n(t?.tooltipBodyToken,ys(e))}}function aI(e,t,n,o,s=1033){const i=e?Xc(e):null;return i?o.some(l=>l.id===i)?i:(n??"")===He(e,[...o],s)?null:t:t}function Cb(e,t,n=1033){const o=new Set(Object.values(wb(e.id,e.source))),s=new Set;for(const i of t)o.has(i.id)&&i.titles.forEach(l=>s.add(l.languageCode));return[...s].sort((i,l)=>i===n?-1:l===n?1:i-l)}const Ut={HomepageGrid:{label:"Main grid",title:"Main grid",body:"The command bar above the table's full-page list of records. Unified Interface shows this ribbon as one flat bar: tabs, group layout and scaling are ignored, and commands that don't fit move under More commands (⋮).",ribbonId:"Mscrm.HomepageGrid.{table}"},Form:{label:"Main form",title:"Main form",body:"The command bar at the top of the table's main form. Unified Interface shows it as one flat bar: tab layout and scaling are ignored, but button visibility and command actions work as configured, as in Ribbon Workbench. Microsoft doesn't support the tabbed ribbon on Unified Interface.",ribbonId:"Mscrm.Form.{table}"},SubGrid:{label:"Sub-grid",title:"Sub-grid",body:"The command bar on this table's sub-grids on other tables' forms, and on the Related tab's associated view. A sub-grid has room for only a few commands before More commands. Of the built-in controls, only Add, Show List and Delete are supported, and their icons can't be changed.",ribbonId:"Mscrm.SubGrid.{table}"},Application:{label:"Application",title:"Application ribbon",body:"Changes here apply to every table. Buttons on GlobalTab appear in the global command bar at the top of every page. Built-in GlobalTab buttons are read-only.",ribbonId:"Application ribbon"}};function Ib(e,t){return Ut[e].ribbonId.replace("{table}",t||"<table>")}function jb(e){if(!e?.modernImage)return;const t={ModernImage:e.modernImage};for(const n of["Image16by16","Image32by32"]){const o=e.attributes[n];o&&(t[n]=o)}return{modernImage:e.modernImage,attributes:t}}const wn=e=>e==="flyout"||e==="splitButton",Na=["button","flyout"],Kc=e=>["true","1"].includes(e?.trim().toLowerCase()??"");function cn(e){const t=[];for(const n of e.menu?.sections??[])for(const o of n.controls)t.push(o),t.push(...cn(o));return t}function Yc(e){return e.flatMap(t=>[t,...cn(t)])}function Ne(e){return Yc(e.buttons)}function Rb(e,t){const n=[];for(const o of Object.keys(e))for(const s of e[o].tabs)for(const i of s.groups)for(const l of Ne(i))l.commandId===t&&n.push({location:o,tab:s,group:i,button:l});return n}function Jc(e,t,n,o,s){const i=[];for(const{location:l,button:r}of Rb(e,t))if(r.id!==n){const c=s&&l!==s?` (${Ut[l].label.toLowerCase()})`:"",d=(o(r)||r.id)+c;i.includes(d)||i.push(d)}return i}function xs(e,t){for(const n of e)for(const o of n.menu?.sections??[]){const s=o.controls.findIndex(l=>l.id===t);if(s>=0)return{parent:n,section:o,index:s};const i=xs(o.controls,t);if(i)return i}}function Ko(e,t){if(!e.buttons.some(n=>n.id===t))return xs(e.buttons,t)}function Ss(e,t){if(!e||!t)return;const n=e.buttons.find(s=>s.id===t);if(n)return n;const o=xs(e.buttons,t);return o?.section.controls[o.index]}function $b(e,t){if(!(!e||!t))return e.buttons.find(n=>n.id===t||cn(n).some(o=>o.id===t))}function Zc(e,t){const n=xs(e.buttons,t);return n?(n.section.controls.splice(n.index,1),!0):!1}function Ps(e){return{id:`${e}.Menu`,sections:[Ti(e,[])]}}function Ti(e,t,n){let o=t.length+1;const s=new Set(t.map(l=>l.id));for(;s.has(`${e}.MenuSection${o}`);)o++;const i=`${e}.MenuSection${o}`;return{id:i,title:n,sequence:o*10,displayMode:"Menu16",controlsId:`${i}.Controls`,controls:[]}}function Nb(e,t,n,o){if(!e)return;const s=new Set,i=new Map,l=c=>{const d=i.get(c);if(d)return d;let u=c.startsWith(t)?`${n}${c.slice(t.length)}`:`${n}.${c.split(".").pop()||"Item"}`;for(let p=2;s.has(u);p++)u=`${u.replace(/_\d+$/,"")}_${p}`;return s.add(u),i.set(c,u),u},r=c=>c.replace(/(\sId=")([^"]*)(")/g,(d,u,p,m)=>`${u}${l(p)}${m}`);return{...e,id:l(e.id),sections:e.sections.map(c=>({...c,id:l(c.id),controlsId:l(c.controlsId),controls:c.controls.map(d=>Yo(d,l(d.id),o)),...c.rawControls?{rawControls:c.rawControls.map(d=>({...d,xml:r(d.xml)}))}:{},...c.rawContent!==void 0?{rawContent:r(c.rawContent)}:{}}))}}function Tb(e,t,n){return e.replace(/(\s(?:Id|InitialItem)=")([^"]*)(")/g,(o,s,i,l)=>`${s}${i.startsWith(t)?`${n}${i.slice(t.length)}`:`${n}.${i}`}${l}`)}const kb=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand"];function no(e,t){return!!t&&!!e?.startsWith("$LocLabels:")&&!t.has(e.slice(11))}function Yo(e,t,n){const o=kb.filter(u=>e.source?.attributes[u]!==void 0),s=jb(e.source),i={...s?.attributes??{},...Object.fromEntries(o.map(u=>[u,e.source.attributes[u]]))},l=u=>to(u)||no(u,n)?u:void 0,r={labelToken:l(e.source?.labelToken),tooltipTitleToken:l(e.source?.tooltipTitleToken),tooltipBodyToken:l(e.source?.tooltipBodyToken)},c=Object.fromEntries(Object.entries(r).filter(([,u])=>u!==void 0)),d=e.source?.xml?Tb(e.source.xml,e.id,t):void 0;return{...e,id:t,source:Object.keys(i).length+Object.keys(c).length>0||d?{...s?.modernImage?{modernImage:s.modernImage}:{},...c,attributes:i,...d?{xml:d}:{}}:void 0,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0,menu:Nb(e.menu,e.id,t,n)}}const Ab=["label","icon","image16","image32","tooltipTitle","tooltipBody","commandId","templateAlias"];function ki(e,t){for(const n of Ab)if((e[n]??"")!==(t[n]??""))return!0;return!1}function Ct(e){const t=new Map,n=new Map,o=(s,i,l,r)=>{const c=n.get(s.id)??0;n.set(s.id,c+1);const d=`${s.id}#${c}`;t.set(d,r?{button:s,groupId:i,tabId:l,menu:r}:{button:s,groupId:i,tabId:l});for(const u of s.menu?.sections??[])for(const p of u.controls)o(p,i,l,{parentKey:d,parentId:s.id,sectionId:u.id,controlsId:u.controlsId})};for(const s of e.tabs)for(const i of s.groups)for(const l of i.buttons)o(l,i.id,s.id);return t}function Ta(e,t){const n=Ct(t),o=Ct(e),s=l=>{for(let r=l.menu?.parentKey;r;r=o.get(r)?.menu?.parentKey)if(!n.has(r))return!0;return!1},i=[];for(const[l,r]of o){const c=n.get(l)?.button,d=r.button;if(s(r)){d.hidden&&i.push({entry:r,change:"hide"});continue}c?d.hidden&&!c.hidden?i.push({entry:r,change:"hide"}):ki(c,d)&&i.push({entry:r,change:"override"}):(d.hidden&&(d.oob||d.managed)||i.push({entry:r,change:"new"}),d.hidden&&i.push({entry:r,change:"hide"}))}return i}function Qc(e){return e.commandId||`${e.id}.Command`}function Ob(e,t){return e==="SubGrid"?`Mscrm.SubGrid.${t}.ContextualTabs._children`:"Mscrm.Tabs._children"}function ed(e,t,n){switch(e){case"HomepageGrid":return[{tabCommand:n,rules:[{kind:"EntityRule",entityName:t,context:"HomePageGrid",appliesTo:"PrimaryEntity"}]}];case"Form":return[{tabCommand:n,rules:[{kind:"EntityRule",entityName:t,context:"Form",appliesTo:"PrimaryEntity"}]}];case"SubGrid":return[{tabCommand:n,rules:[{kind:"EntityRule",entityName:t,context:"SubGridStandard",appliesTo:"SelectedEntity"},{kind:"EntityRule",entityName:t,context:"SubGridAssociated",appliesTo:"SelectedEntity"}]}];default:return[]}}function Mb(e,t,n){const o=Qc(e),s=(e.tabDisplayRules??[]).map(i=>({...i,tabCommand:i.tabCommand||o}));return{...e,commandId:o,tabDisplayRules:s.length>0?s:ed(t,n,o)}}function rI(e){const{current:t,baseline:n,commands:o,enableRules:s,displayRules:i,locLabels:l}=e,r=e.languageCode??1033,c=e.location==="Application",d=new Set,u=new Set;for(const L of n.tabs){d.add(L.id);for(const G of L.groups)u.add(G.id)}const p=Ct(n),m=new Map;for(const[L,G]of Ct(t))m.set(G.button,p.get(L)?.button);const g=t.tabs.filter(L=>!d.has(L.id)).map(L=>Mb(L,e.location,e.entityLogicalName)),b=[],f=[],y=[],x=[],S=[],C=L=>S.push(L),N=[],O=L=>{const G=[];for(const U of L.buttons)U.hidden||m.get(U)||(G.push(vs(U,l,C,r,!0)),N.push(U,...cn(U)));return G},I=new Set,j=nd(t,n).steps;for(const L of g){const G=new Map(L.groups.map(U=>[U.id,O(U)]));for(const U of L.groups)for(const te of U.buttons)!te.hidden&&!m.get(te)&&I.add(te);b.push(qb(L,t.scalingByTab?.[L.id],Ob(e.location,e.entityLogicalName),G,j,C,r,l))}const $=[];for(const L of t.tabs)if(d.has(L.id)){for(const G of L.groups)if(!u.has(G.id)){for(const te of G.buttons)!te.hidden&&!m.get(te)&&I.add(te);f.push(_b(G,L.id,O(G),C,r,l));const U=j.get(G.id);U&&$.push(Oi(L.id,"MaxSize",U))}}f.push(...$);for(const{entry:L,change:G}of Ta(t,n)){const{button:U,groupId:te,menu:P}=L;if(!I.has(U))if(G==="hide")x.push(Fb(U));else if(G==="new"){const Q=P?`${P.controlsId}._children`:`${te}.Controls._children`;y.push(zb(U,Q,l,C,r)),N.push(U,...cn(U))}else y.push(Pb(U,l,C,r)),N.push(U)}const w=new Set;for(const L of N)for(const G of Ec(L))w.add(G);for(const L of t.tabs)for(const G of L.groups){const U=G.source?.attributes.Command;U&&!u.has(G.id)&&w.add(U)}const A=[];for(const L of g){const G=L.commandId;w.add(G),o.some(U=>U.id===G)||A.push({id:G,enableRules:[],displayRules:[],actions:[]})}const B=[...o.filter(L=>w.has(L.id)&&(!qs(L.id)||L.actions.length>0)),...A],k=new Set,v=new Set;for(const L of B)L.enableRules.forEach(G=>k.add(G)),L.displayRules.forEach(G=>v.add(G));const T=s.filter(L=>k.has(L.id)&&!qs(L.id)),R=i.filter(L=>v.has(L.id)&&!qs(L.id)),D=Yb(S),q=B.map(Qb).join(`
33
+ `),X=T.map(ey).join(`
34
+ `),ne=R.map(ty).join(`
35
+ `),re=D.map(ny).join(`
36
+ `),le=[...b,...f,...Eb(t,n,d),...y,...x],F=g.filter(L=>L.tabDisplayRules.length>0).map(L=>oy(L,c)).filter(Boolean).join(`
37
+ `);return`<RibbonDiffXml>
38
+ <CustomActions>
39
+ ${le.join(`
40
+ `)}
41
+ </CustomActions>
42
+ <Templates><RibbonTemplates Id="Mscrm.Templates"/></Templates>
43
+ <CommandDefinitions>
44
+ ${q}
45
+ </CommandDefinitions>
46
+ <RuleDefinitions>
47
+ <TabDisplayRules>
48
+ ${F}
49
+ </TabDisplayRules>
50
+ <DisplayRules>
51
+ ${ne}
52
+ </DisplayRules>
53
+ <EnableRules>
54
+ ${X}
55
+ </EnableRules>
56
+ </RuleDefinitions>
57
+ <LocLabels>
58
+ ${re}
59
+ </LocLabels>
60
+ </RibbonDiffXml>`}function Db(e,t){const n=new Set,o=new Set;for(const b of t.tabs){n.add(b.id);for(const f of b.groups)o.add(f.id)}let s=0,i=0,l=0,r=0,c=0,d=0;for(const b of e.tabs){n.has(b.id)||r++,b.tabDisplayRules&&b.tabDisplayRules.length>0&&(d+=b.tabDisplayRules.length);for(const f of b.groups)!o.has(f.id)&&n.has(b.id)&&c++}for(const{change:b}of Ta(e,t))b==="hide"?l++:b==="new"?s++:i++;const u=e.scalingByTab??{},p=t.scalingByTab??{};let m=0;for(const[b,f]of Object.entries(u))JSON.stringify(f)!==JSON.stringify(p[b])&&m++;const g=s+i+l+r+c+m>0;return{newButtons:s,overriddenButtons:i,hiddenButtons:l,newTabs:r,newGroups:c,scalingChanges:m,tabDisplayRules:d,hasAnyChange:g}}function Eb(e,t,n){const o=[],s=[];for(const[i,l]of Object.entries(e.scalingByTab??{})){if(!n.has(i))continue;const r=t.scalingByTab?.[i],c=(d,u)=>u?.some(p=>JSON.stringify(p)===JSON.stringify(d))??!1;for(const d of l.maxSizes)c(d,r?.maxSizes)||o.push(Oi(i,"MaxSize",d));for(const d of l.scales)c(d,r?.scales)||s.push(Oi(i,"Scale",d))}return[...o,...s]}function Ai(e,t){const n=e==="Scale"&&t.popupSize?` PopupSize="${he(t.popupSize)}"`:"";return`<${e} Id="${he(t.id)}" GroupId="${he(t.groupId)}" Sequence="${t.sequence}" Size="${he(t.size)}"${n}/>`}function Oi(e,t,n){return`<CustomAction Id="${he(n.id)}.CustomAction"
61
+ Location="${he(e)}.Scaling._children"
62
+ Sequence="${n.sequence}">
63
+ <CommandUIDefinition>
64
+ ${Ai(t,n)}
65
+ </CommandUIDefinition>
66
+ </CustomAction>`}const td={"Mscrm.Templates.Flexible":"Large","Mscrm.Templates.Flexible2":"LargeLarge","Mscrm.Templates.Flexible3":"LargeLargeMedium","Mscrm.Templates.Flexible4":"LargeMediumLargeLarge","Mscrm.Templates.3":"Large","Mscrm.Templates.3.3":"LargeLarge","Mscrm.Templates.3.3.3":"LargeLargeMedium","Mscrm.Templates.4.3.3":"LargeMediumLarge","Mscrm.Templates.FourOverflow":"LargeMediumLargeLarge","Mscrm.Templates.FourLargeButtons":"Large","Mscrm.Templates.OneLargeTwoMedium":"Large","Mscrm.Templates.OneLargeThreeMedium":"Large","Mscrm.Templates.TwoLargeTwoMedium":"Large","Mscrm.Templates.TwoLargeThreeMedium":"Large","Mscrm.Templates.ThreeLargeThreeMedium":"Large"},Bb=Object.keys(td);function Lb(e){return td[ka(e.template)]}function nd(e,t){const n=new Map,o=[],s=new Set(t.tabs.map(l=>l.id)),i=new Set(t.tabs.flatMap(l=>l.groups.map(r=>r.id)));for(const l of e.tabs){const r=!s.has(l.id),c=e.scalingByTab?.[l.id],d=(c?.maxSizes??[]).map(g=>g.sequence),u=(c?.scales??[]).map(g=>g.sequence),p=new Set([...d,...u]);if(r&&p.size<d.length+u.length&&o.push(`The scaling of new tab ${l.id} uses a Sequence more than once — give every MaxSize and Scale its own`),r&&d.length>0)continue;const m=Bc(d,u);for(const g of l.groups){if(!r&&i.has(g.id)||c?.maxSizes.some(y=>y.groupId===g.id))continue;const b=Lb(g);if(!b)continue;const f=Lc(m,p);if(f===void 0){o.push(`No free scaling position for the new group "${g.label}" (${g.id}) on tab ${l.id}: its MaxSize must come after the tab's last MaxSize (${m.after}) and before its first Scale (${m.before}), and no Sequence is free there`);continue}p.add(f),n.set(g.id,{id:`${g.id}.MaxSize`,groupId:g.id,size:b,sequence:f})}}return{steps:n,problems:o}}function zb(e,t,n,o,s=1033){return`<CustomAction Id="${he(e.id)}.CustomAction"
67
+ Location="${he(t)}"
68
+ Sequence="${e.sequence}">
69
+ <CommandUIDefinition>
70
+ ${vs(e,n,o,s,!0)}
71
+ </CommandUIDefinition>
72
+ </CustomAction>`}function Pb(e,t,n,o=1033){return`<CustomAction Id="${he(e.id)}.Override.CustomAction"
73
+ Location="${he(e.id)}"
74
+ Sequence="${e.sequence}">
75
+ <CommandUIDefinition>
76
+ ${vs(e,t,n,o)}
77
+ </CommandUIDefinition>
78
+ </CustomAction>`}function Fb(e,t){return`<HideCustomAction HideActionId="${he(e.id)}.HideAction"
79
+ Location="${he(e.id)}"/>`}function _b(e,t,n,o,s=1033,i=[]){return`<CustomAction Id="${he(e.id)}.CustomAction"
80
+ Location="${he(t)}.Groups._children"
81
+ Sequence="${e.sequence}">
82
+ <CommandUIDefinition>
83
+ ${od(e,o,n,s,i)}
84
+ </CommandUIDefinition>
85
+ </CustomAction>`}function qb(e,t,n,o,s,i,l=1033,r=[]){const c=sd(e,i,l,r),d=e.commandId?` Command="${he(e.commandId)}"`:"",u=e.groups.map(b=>od(b,i,o.get(b.id)??[],l,r)).join(`
86
+ `),m=[...(t?.maxSizes.length?t.maxSizes:e.groups.map(b=>s.get(b.id)).filter(b=>!!b)).map(b=>Ai("MaxSize",b)),...(t?.scales??[]).map(b=>Ai("Scale",b))],g=m.length===0?`<Scaling Id="${he(e.id)}.Scaling"/>`:`<Scaling Id="${he(e.id)}.Scaling">
87
+ ${m.join(`
88
+ `)}
89
+ </Scaling>`;return`<CustomAction Id="${he(e.id)}.CustomAction"
90
+ Location="${he(n)}"
91
+ Sequence="${e.sequence}">
92
+ <CommandUIDefinition>
93
+ <Tab Id="${he(e.id)}"${d} Title="${he(c)}"${id(e,r,i)} Sequence="${e.sequence}"${ad(e)}>
94
+ ${g}
95
+ <Groups Id="${he(e.id)}.Groups">
96
+ ${u}
97
+ </Groups>
98
+ </Tab>
99
+ </CommandUIDefinition>
100
+ </CustomAction>`}function od(e,t,n=[],o=1033,s=[]){const i=sd(e,t,o,s),l=ka(e.template),r=n.length===0?`<Controls Id="${he(e.id)}.Controls"/>`:`<Controls Id="${he(e.id)}.Controls">
101
+ ${n.join(`
102
+ `)}
103
+ </Controls>`;return`<Group Id="${he(e.id)}" Title="${he(i)}"${id(e,s,t)} Sequence="${e.sequence}" Template="${he(l)}"${ad(e)}>
104
+ ${r}
105
+ </Group>`}function sd(e,t,n,o){const s=`${e.id}.Title`;if(e.source&&e.label){const i=oo(e.label,e.source.titleToken,s,o,t,n);if(i)return i}return t({id:s,titles:[{languageCode:n,description:e.label}]}),Vc(s)}function id(e,t,n){const o=e.description,s=o?.startsWith("$LocLabels:")?t.find(i=>i.id===o.slice(11)):void 0;return s&&n(s),ee("Description",o)}const Wb=new Set(["Id","Command","Title","Description","Sequence","Template"]);function ad(e){const t="buttons"in e;return Object.entries(e.source?.attributes??{}).filter(([n])=>t&&n==="Command"||!Wb.has(n)).filter(([n])=>!Aa.has(n)).map(([n,o])=>` ${n}="${he(o)}"`).join("")}function ka(e){const t=e?.trim();return t?t.includes(".")?t:`Mscrm.Templates.${t}`:"Mscrm.Templates.Flexible2"}function Hb(e,t,n,o,s=1033){const i=e??"";if(i.startsWith("$LocLabels:")){const c=i.slice(11),d=n.find(u=>u.id===c);return d&&o(d),i}if(to(i))return i;const l=[{languageCode:s,description:i}],r=n.find(c=>c.id===t);if(r)for(const c of r.titles)c.languageCode!==s&&l.push(c);return o({id:t,titles:l}),Vc(t)}const Gb=["ToolTipTitle","ToolTipDescription","ToolTipHelpKeyWord","ToolTipShortcutKey","ToolTipImage32by32","ToolTipImage32by32Class","ToolTipImage32by32Left","ToolTipImage32by32Top"],Fs=["Image16by16","Image16by16Class","Image16by16Left","Image16by16Top","Image32by32","Image32by32Class","Image32by32Left","Image32by32Top","ModernImage"],pn=["Id","Command","Sequence","TemplateAlias",...Gb],_s=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand","CacheMenuVersions"],Ub={Button:new Set([...pn,...Fs,"Alt","CommandType","CommandValueId","Description","LabelCss","LabelText","MenuItemId","ModernCommandType","Priority"]),FlyoutAnchor:new Set([...pn,...Fs,..._s,"Alt","CommandMenuClose","CommandType","LabelText","ModernCommandType","ToolTipSelectedItemTitle"]),SplitButton:new Set([...pn,...Fs,..._s,"Alt","CommandMenuClose","CommandMenuOpen","CommandType","LabelText","MenuAlt","MenuCommand","ToolTipSelectedItemTitle"]),CheckBox:new Set([...pn,"Alt","LabelText","MenuItemId","QueryCommand"]),TextBox:new Set([...pn,"ImeEnabled","MaxLength","QueryCommand","ShowAsLabel","Width"]),ComboBox:new Set([...pn,..._s,"AllowFreeForm","Alt","AltArrow","AutoComplete","AutoCompleteDelay","CommandMenuClose","CommandMenuOpen","CommandPreview","CommandPreviewRevert","ImeEnabled","InitialItem","QueryCommand","ToolTipSelectedItemTitle","Width"])},Aa=new Set(["SolutionUniqueName"]);function Vb(e){if(e)return e.includes("_")?e.toLowerCase():e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function oo(e,t,n,o,s,i=1033){if(t!==void 0&&(e??"")===He(t,o,i)){if(t.startsWith("$LocLabels:")){const c=o.find(d=>d.id===t.slice(11));c&&s(c)}return t}if(!e)return;const l=t?.startsWith("$LocLabels:")?t.slice(11):void 0,r=l&&o.some(c=>c.id===l)?l:n;return Hb(e,r,o,s,i)}function Oa(e){const t=e.source,n=r=>!!r?.startsWith("$webresource:"),o=r=>r&&!r.startsWith("/")&&/[/.]/.test(r)?Ma(r):r,s=o(e.image32),i=o(e.image16),l=[[e.image32,s,"Image32by32"],[e.image16,i,"Image16by16"]].filter(([r,c,d])=>n(c)&&r!==t?.attributes[d]).map(([,r])=>r);return t&&Vb(t.modernImage)===e.icon&&l.length===0?t.modernImage:l[0]??[s,i,e.icon].find(n)}function vs(e,t,n,o=1033,s=!1){const i=Jb(e.kind),l=e.source;if(l?.xml&&dt(e.kind))return Zb(e,l.xml,t,n);const r=new Map;for(const[b,f]of Object.entries(l?.attributes??{}))Aa.has(b)||r.set(b,f);const c=(b,f)=>f===void 0||f===""?r.delete(b):r.set(b,f);c("Id",e.id),c("Command",e.commandId||void 0),c("LabelText",oo(e.label,l?.labelToken,gs(e.id),t,n,o)??""),r.has("LabelText")||r.set("LabelText",""),c("ToolTipTitle",oo(e.tooltipTitle,l?.tooltipTitleToken,bs(e.id),t,n,o)),c("ToolTipDescription",oo(e.tooltipBody,l?.tooltipBodyToken,ys(e.id),t,n,o)),c("TemplateAlias",e.templateAlias),c("Sequence",l&&!("Sequence"in l.attributes)&&e.sequence===0?void 0:String(e.sequence));const d=b=>!!b&&(b.startsWith("$webresource:")||b.includes("/")||b.includes(".")),u=b=>d(b)?Ma(b):void 0;c("ModernImage",Oa(e)),c("Image16by16",u(e.image16)),c("Image32by32",u(e.image32));const p=Ub[i];if(p)for(const b of[...r.keys()])p.has(b)||r.delete(b);const m=Array.from(r.entries()).map(([b,f])=>`${b}="${he(f)}"`).join(" "),g=s&&e.menu&&Xb.has(i)?Kb(e.menu,t,n,o):"";return g?`<${i} ${m}>${g}</${i}>`:`<${i} ${m}/>`}const Xb=new Set(["FlyoutAnchor","SplitButton","ComboBox"]);function Kb(e,t,n,o){const s=e.sections.map(r=>{const c=new Map(Object.entries(r.attributes??{})),d=(g,b)=>b===void 0||b===""?c.delete(g):c.set(g,b);d("Id",r.id),d("Title",oo(r.title,r.attributes?.Title,vb(r.id),t,n,o));const u=!!r.attributes&&!("Sequence"in r.attributes)&&r.sequence===0;d("Sequence",u?void 0:String(r.sequence)),d("DisplayMode",r.displayMode);const p=Array.from(c.entries()).map(([g,b])=>` ${g}="${he(b)}"`).join("");if(r.rawContent!==void 0)return`<MenuSection${p}>${r.rawContent}</MenuSection>`;const m=r.controls.map(g=>vs(g,t,n,o,!0));for(const g of[...r.rawControls??[]].sort((b,f)=>b.index-f.index))m.splice(Math.min(g.index,m.length),0,g.xml);return`<MenuSection${p}><Controls Id="${he(r.controlsId)}">${m.join("")}</Controls></MenuSection>`}),i=new Map(Object.entries(e.attributes??{}));return i.set("Id",e.id),`<Menu${Array.from(i.entries()).map(([r,c])=>` ${r}="${he(c)}"`).join("")}>${s.join("")}</Menu>`}function qs(e){return/^(Mscrm|Microsoft)\./.test(e)}function Yb(e){const t=new Map;for(const n of e){const o=t.get(n.id);(!o||n.titles.length>o.titles.length)&&t.set(n.id,n)}return Array.from(t.values())}function Jb(e){return vn[e]??"Button"}function Zb(e,t,n,o){const s=new DOMParser().parseFromString(t,"application/xml").documentElement;for(const l of[s,...Array.from(s.getElementsByTagName("*"))])for(const r of Aa)l.removeAttribute(r);s.setAttribute("Id",e.id),(s.hasAttribute("Sequence")||e.sequence!==0)&&s.setAttribute("Sequence",String(e.sequence));const i=new XMLSerializer().serializeToString(s);for(const l of i.matchAll(/\$LocLabels:([^"'\s<]+)/g)){const r=n.find(c=>c.id===l[1]);r&&o(r)}return i}function Ma(e){const t=(e??"").trim();if(!t||/^\$webresource:/i.test(t)||/^https?:\/\//i.test(t))return t;const n=t.match(/^\/?WebResources\/(.+)$/i);return n?`$webresource:${n[1]}`:t.startsWith("/")||t.startsWith(".")?t:`$webresource:${t}`}function rd(e){const t=(e??"").trim();return t.startsWith("/")?t:Ma(t)}function ee(e,t){return t===void 0?"":` ${e}="${he(String(t))}"`}function It(e,t,n,o){return n.length===0?`<${e}${t}/>`:`<${e}${t}>
106
+ ${n.map(s=>`${o} ${s}`).join(`
107
+ `)}
108
+ ${o}</${e}>`}function ld(e,t=" "){switch(e.kind){case"javascript":return It("JavaScriptFunction",`${ee("FunctionName",e.functionName)}${ee("Library",rd(e.library))}`,e.params.map(n=>Mi(n,!1)),t);case"url":return It("Url",`${ee("Address",e.address)}${ee("PassParams",e.passParams)}${ee("WinMode",e.winMode)}${ee("WinParams",e.winParams)}`,e.params.map(n=>Mi(n,!0)),t);case"outlookCommand":return`<OutlookCommand${ee("ActionType",e.actionType)}${ee("Data",e.data)}/>`;case"raw":return e.xml;default:return""}}function Qb(e){const t=" ",n=(l,r)=>{const c=[...r];for(const d of e.rawRuleRefs??[])d.container===l&&c.splice(Math.min(d.index,c.length),0,d.xml);return c},o=n("EnableRules",e.enableRules.map(l=>`<EnableRule Id="${he(l)}"/>`)),s=n("DisplayRules",e.displayRules.map(l=>`<DisplayRule Id="${he(l)}"/>`)),i=e.actions.map(l=>ld(l,`${t} `)).filter(Boolean);return`<CommandDefinition Id="${he(e.id)}">
109
+ ${t} ${It("EnableRules","",o,`${t} `)}
110
+ ${t} ${It("DisplayRules","",s,`${t} `)}
111
+ ${t} ${It("Actions","",i,`${t} `)}
112
+ ${t}</CommandDefinition>`}function Mi(e,t){const n=t?ee("Name",e.name??""):"";switch(e.kind){case"CrmParameter":return`<CrmParameter${n}${ee("Value",e.value)}/>`;case"BoolParameter":return`<BoolParameter${n}${ee("Value",e.value)}/>`;case"IntParameter":return`<IntParameter${n}${ee("Value",e.value)}/>`;case"DecimalParameter":return`<DecimalParameter${n}${ee("Value",e.value)}/>`;case"StringParameter":return`<StringParameter${n}${ee("Value",e.value)}/>`}}function ey(e){return It("EnableRule",ee("Id",e.id),e.steps.map(t=>ws(t," "))," ")}function ty(e){return It("DisplayRule",ee("Id",e.id),e.steps.map(t=>ws(t," "))," ")}function ws(e,t=""){if(e.kind==="RawRule")return e.xml;if(e.kind==="OrRule"){const s=e.groups.map(i=>It("Or","",i.map(l=>ws(l,`${t} `)),`${t} `));return It("OrRule","",s,t)}const n=`${ee("Default",e.default)}${ee("InvertResult",e.invertResult)}`,o=(s,i)=>`<${s}${i}${n}/>`;switch(e.kind){case"SelectionCountRule":return o("SelectionCountRule",`${ee("AppliesTo",e.appliesTo)}${ee("Minimum",e.minimum)}${ee("Maximum",e.maximum)}`);case"EntityRule":return o("EntityRule",`${ee("EntityName",e.entityName)}${ee("AppliesTo",e.appliesTo)}${ee("Context",e.context)}`);case"FormStateRule":return o("FormStateRule",ee("State",e.state));case"CommandClientTypeRule":return o("CommandClientTypeRule",ee("Type",e.type));case"CrmClientTypeRule":return o("CrmClientTypeRule",ee("Type",e.type));case"CustomRule":return It("CustomRule",`${ee("FunctionName",e.functionName)}${ee("Library",e.library===void 0?void 0:rd(e.library))}${n}`,(e.params??[]).map(s=>Mi(s,!1)),t);case"FeatureControlRule":return o("FeatureControlRule",`${ee("FeatureControlBit",e.featureControlBit)}${ee("ExpectedValue",e.expectedValue)}`);case"MiscellaneousPrivilegeRule":return o("MiscellaneousPrivilegeRule",`${ee("PrivilegeName",e.privilegeName)}${ee("PrivilegeDepth",e.privilegeDepth)}`);case"FormTypeRule":return o("FormTypeRule",ee("Type",e.type));case"ValueRule":return o("ValueRule",`${ee("Field",e.field)}${ee("Value",e.value)}`);case"SkuRule":return o("SkuRule",ee("Sku",e.sku));case"HideForTabletExperienceRule":return o("HideForTabletExperienceRule","");case"OrganizationSettingRule":return o("OrganizationSettingRule",ee("Setting",e.setting));case"EntityPrivilegeRule":return o("EntityPrivilegeRule",`${ee("PrivilegeType",e.privilegeType)}${ee("PrivilegeDepth",e.privilegeDepth)}${ee("AppliesTo",e.appliesTo)}${ee("EntityName",e.entityName)}`);case"EntityPropertyRule":return o("EntityPropertyRule",`${ee("EntityName",e.entityName)}${ee("AppliesTo",e.appliesTo)}${ee("PropertyName",e.propertyName)}${ee("PropertyValue",e.propertyValue)}`);case"DeviceTypeRule":return o("DeviceTypeRule",ee("Type",e.type));case"RelationshipTypeRule":return o("RelationshipTypeRule",`${ee("AppliesTo",e.appliesTo)}${ee("RelationshipType",e.relationshipType)}${ee("AllowCustomRelationship",e.allowCustomRelationship)}${ee("AllowSystemRelationship",e.allowSystemRelationship)}`);case"RecordPrivilegeRule":return o("RecordPrivilegeRule",`${ee("PrivilegeType",e.privilegeType)}${ee("AppliesTo",e.appliesTo)}`);case"FormEntityContextRule":return o("FormEntityContextRule",ee("EntityName",e.entityName));case"PageRule":return o("PageRule",ee("Address",e.address));case"ReferencingAttributeRequiredRule":return o("ReferencingAttributeRequiredRule","");case"OutlookItemTrackingRule":return o("OutlookItemTrackingRule",`${ee("TrackedInCrm",e.trackedInCrm)}${ee("AppliesTo",e.appliesTo)}`);case"OutlookRenderTypeRule":return o("OutlookRenderTypeRule",ee("Type",e.type));case"OutlookVersionRule":return o("OutlookVersionRule",ee("Version",e.version));case"CrmOfflineAccessStateRule":return o("CrmOfflineAccessStateRule",ee("State",e.state));case"CrmOutlookClientTypeRule":return o("CrmOutlookClientTypeRule",ee("Type",e.type));case"CrmOutlookClientVersionRule":return o("CrmOutlookClientVersionRule",`${ee("Major",e.major)}${ee("Minor",e.minor)}${ee("Build",e.build)}${ee("Revision",e.revision)}`);case"OptionSetRule":return o("OptionSetRule",`${ee("OptionSet",e.optionSet)}${ee("StateCode",e.stateCode)}${ee("ObjectTypeCode",e.objectTypeCode)}`);default:{const s=e;throw new Error(`Unknown rule kind: ${s.kind}`)}}}function ny(e){const t=e.titles.map(n=>`<Title languagecode="${n.languageCode}" description="${he(n.description)}"/>`).join(`
113
+ `);return`<LocLabel Id="${he(e.id)}">
114
+ <Titles>
115
+ ${t}
116
+ </Titles>
117
+ </LocLabel>`}function oy(e,t){const n=new Map;for(const o of e.tabDisplayRules){const s=o.rules.map(i=>i.kind==="EntityRule"?`<EntityRule${ee("EntityName",i.entityName)}${ee("AppliesTo",i.appliesTo)}${ee("Context",i.context)}/>`:i.kind==="PageRule"&&t?`<PageRule${ee("Address",i.address)}/>`:"").filter(Boolean);n.set(o.tabCommand,[...n.get(o.tabCommand)??[],...s])}return[...n].filter(([,o])=>o.length>0).map(([o,s])=>`<TabDisplayRule TabCommand="${he(o)}">
118
+ ${s.join(`
119
+ `)}
120
+ </TabDisplayRule>`).join(`
121
+ `)}function he(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function lI(e){const t=e.entities??[];return`<?xml version="1.0" encoding="utf-8"?>
122
+ <ImportExportXml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">${t.length===0?"":`
123
+ <Entities>
124
+ ${t.map(o=>` <Entity>
125
+ <Name LocalizedName="${he(o.localizedName)}" OriginalName="${he(o.localizedName)}">${he(o.schemaName)}</Name>
126
+ ${o.ribbonDiffXml}
127
+ </Entity>`).join(`
128
+ `)}
129
+ </Entities>`}
130
+ ${e.applicationRibbonDiffXml??""}
131
+ </ImportExportXml>`}function Di(e){return/^(Mscrm|Microsoft)\./.test(e)}function Jo(e,t){e.origin=t.origin,e.solutionName=t.solutionName,e.publisherName=t.publisherName,e.oob=t.origin==="oob",e.custom=t.origin==="unmanaged",e.managed=t.origin==="managed"}function sy(e,t){return t?"unmanaged":Di(e)?"oob":"unmanaged"}function Or(e,t){for(const n of e.tabs)for(const o of n.groups)for(const s of Ne(o))t.has(s.id)?Jo(s,{origin:"unmanaged"}):s.origin==="unmanaged"&&Jo(s,{origin:"managed"})}function an(e){return e.origin==="unmanaged"}function Da(e,t,n){return e==="Application"&&t==="Mscrm.GlobalTab"&&n.oob&&!n.custom}function Cs(e,t){return dd(cd(t),[e])}function cd(e){const t=new Map;for(const n of e.tabs)for(const o of n.groups)for(const s of Ne(o))t.set(s.id,(t.get(s.id)??!0)&&an(s));return t}function dd(e,t){return Yc(t).every(n=>e.get(n.id)??an(n))}function Zo(e,t,n){return t?n?"has"in n?n.has(e):n.includes(e):!1:!0}function Ea(e,t,n){const o=t.tabs.some(s=>s.groups.some(i=>i.id===e.id));return Zo(e.id,o,n)&&dd(cd(t),e.buttons)}const Fo="Only tabs and groups your unmanaged customizations add (with a translatable title), or new ones, can be renamed";function Ei(e,t,n,o){const s=e==="tab"?n.tabs.find(l=>l.id===t):new Map(n.tabs.flatMap(l=>l.groups.map(r=>[r.id,r]))).get(t);if(!s)return!0;if(!Zo(t,!0,o?.containerIds))return!1;const i=/^\$LocLabels:(.+)$/.exec(s.label??"")?.[1];return!!i&&Zo(i,!0,o?.locLabelIds)}function ud(e,t,n){const o=t.tabs.some(s=>s.id===e.id);return Zo(e.id,o,n)&&e.groups.every(s=>Ea(s,t,n))}function cI(e,t){const n=t.tabs.flatMap(l=>l.groups.flatMap(r=>Ne(r))).filter(l=>l.id===e.id),o=n.find(l=>!an(l)),s=o??n[0]??e,i=s.origin==="oob"?"the out-of-the-box ribbon":s.origin==="managed"?s.solutionName?`the managed solution "${s.solutionName}"`:"a managed solution":void 0;return o&&n.some(an)?`The ribbon also places a button with this id from ${i??"another solution"}, and that one can't be deleted.`:i&&an(e)?`It is your override of a button from ${i}: the original stays in the ribbon underneath it.`:i?`It comes from ${i}.`:an(s)?"Its menu holds items from another solution.":"It comes from another solution."}function iy(e,t,n=new Set){if(t.size!==0)for(const o of Object.keys(e))for(const s of e[o].tabs)for(const i of s.groups)for(const l of Ne(i)){const r=t.get(l.id);r&&!n.has(l.id)&&l.origin!=="oob"&&Jo(l,r)}}function Is(e,t,n,o=[]){const i=new DOMParser().parseFromString(e,"application/xml"),l=i.querySelector("parsererror");if(l)throw new Error(`Ribbon XML parse error: ${l.textContent??"Unknown"}`);const r=ay(i),c=ry(i);cy(i,r);const d=new py,u=fy(i,d),p=gy(i,d),m=by(i,d);d.flush();const g=[...Sy(i)];for(const x of o)g.some(S=>S.id===x.id)||g.push(x);const b=new Set,f=new Set;i.querySelectorAll("CustomAction").forEach(x=>{const S=x.querySelector("CommandUIDefinition");if(S?.firstElementChild){const C=S.firstElementChild.getAttribute("Id")??"";C&&b.add(C)}}),i.querySelectorAll("HideCustomAction").forEach(x=>{const S=x.getAttribute("Location")??"";S&&f.add(S)});for(const x of r)for(const S of x.groups)for(const C of Ne(S)){const N=b.has(C.id);Jo(C,{origin:sy(C.id,N)}),C.hidden=f.has(C.id),C.source&&(C.source.labelToken=C.source.attributes.LabelText,C.source.tooltipTitleToken=C.source.attributes.ToolTipTitle,C.source.tooltipBodyToken=C.source.attributes.ToolTipDescription),C.label=He(C.label,g),C.tooltipTitle&&(C.tooltipTitle=He(C.tooltipTitle,g)),C.tooltipBody&&(C.tooltipBody=He(C.tooltipBody,g));for(const O of C.menu?.sections??[])O.title&&(O.title=He(O.title,g))}const y=ly(i,r);return{ribbon:{location:t,entityLogicalName:n,tabs:r,...Object.keys(c).length>0?{scalingByTab:c}:{},...Object.keys(y).length?{templateLayouts:y}:{}},commands:u,displayRules:m,enableRules:p,locLabels:g}}const md="Ribbon > Tabs > Tab, Ribbon > ContextualTabs > ContextualGroup > Tab";function Mr(e){const t=e.getAttribute("Description");return t===null?{}:{description:t}}function ay(e){const t=[];return e.querySelectorAll(md).forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const s=n.getAttribute("Title")??o,i=[];n.querySelectorAll(":scope > Groups > Group").forEach(l=>{const r=l.getAttribute("Id")??"";if(!r)return;const c=l.getAttribute("Title")??l.getAttribute("Label")??r,d=parseInt(l.getAttribute("Sequence")??"0",10),u=l.getAttribute("Template")??"",p=[];l.querySelectorAll(":scope > Controls > *").forEach(m=>{Oc[m.tagName]&&pd(m,p)}),i.push({id:r,label:c,sequence:d,template:u,...Mr(l),buttons:p})}),t.push({id:o,label:s,sequence:parseInt(n.getAttribute("Sequence")??"0",10),commandId:n.getAttribute("Command")??void 0,...Mr(n),tabDisplayRules:[],groups:i})}),t.sort((n,o)=>n.sequence-o.sequence)}function ry(e){const t={};return e.querySelectorAll(md).forEach(n=>{const o=n.getAttribute("Id"),s=Array.from(n.children).find(r=>r.tagName==="Scaling");if(!o||!s||t[o])return;const i=r=>({id:r.getAttribute("Id")??"",groupId:r.getAttribute("GroupId")??"",size:r.getAttribute("Size")??"",sequence:parseInt(r.getAttribute("Sequence")??"0",10),...r.getAttribute("PopupSize")?{popupSize:r.getAttribute("PopupSize")}:{}}),l=Array.from(s.children);t[o]={tabId:o,maxSizes:l.filter(r=>r.tagName==="MaxSize").map(i),scales:l.filter(r=>r.tagName==="Scale").map(i)}}),t}function ly(e,t){const n=new Set(t.flatMap(s=>s.groups.map(i=>i.template)).filter(Boolean)),o={};return e.querySelectorAll("GroupTemplate").forEach(s=>{const i=s.getAttribute("Id");!i||!n.has(i)||(o[i]=Array.from(s.querySelectorAll(":scope > Layout")).map(l=>l.getAttribute("Title")??"").filter(Boolean))}),o}function cy(e,t){const n=new Map;for(const o of t)o.commandId&&n.set(o.commandId,o);e.querySelectorAll("RuleDefinitions > TabDisplayRules > TabDisplayRule").forEach(o=>{const s=o.getAttribute("TabCommand")??"",i=n.get(s);if(!i)return;const l=[];for(const c of Array.from(o.children))c.tagName==="EntityRule"?l.push({kind:"EntityRule",entityName:c.getAttribute("EntityName")??void 0,appliesTo:c.getAttribute("AppliesTo")??void 0,context:c.getAttribute("Context")??void 0}):c.tagName==="PageRule"&&l.push({kind:"PageRule",address:c.getAttribute("Address")??""});if(l.length===0)return;const r=i.tabDisplayRules.find(c=>c.tabCommand===s);r?r.rules.push(...l):i.tabDisplayRules.push({tabCommand:s,rules:l})})}function pd(e,t){const n=e.getAttribute("Id")??"";if(!n)return;const o=Oc[e.tagName]??"button",s=dt(o),i=e.getAttribute("LabelText")??n,l=my(e.getAttribute("ModernImage")??void 0),r=parseInt(e.getAttribute("Sequence")??"0",10),c=e.getAttribute("TemplateAlias")??"",d=e.getAttribute("Command")??"";t.push({id:n,label:i,icon:l,sequence:r,templateAlias:c,commandId:d,kind:o,hidden:!1,oob:!0,custom:!1,managed:!1,tooltipTitle:e.getAttribute("ToolTipTitle")??void 0,tooltipBody:e.getAttribute("ToolTipDescription")??void 0,image16:e.getAttribute("Image16by16")??void 0,image32:e.getAttribute("Image32by32")??void 0,source:{modernImage:e.getAttribute("ModernImage")??void 0,attributes:Bi(e),...s?{xml:kn().serializeToString(e)}:{}},menu:s?void 0:uy(e)})}const dy=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]);function Bi(e){return Object.fromEntries(Array.from(e.attributes).map(t=>[t.name,t.value]))}function uy(e){const t=st(e).find(s=>s.tagName==="Menu");if(!t)return;const n=Bi(t),o=[];for(const s of st(t)){if(s.tagName!=="MenuSection")continue;const i=s.getAttribute("Id")??"",l=st(s).find(u=>u.tagName==="Controls"),r=[],c=[];st(l).forEach((u,p)=>{dy.has(u.tagName)&&u.getAttribute("Id")?pd(u,r):c.push({index:p,xml:kn().serializeToString(u)})});const d=Bi(s);o.push({id:i,title:s.getAttribute("Title")??void 0,sequence:parseInt(s.getAttribute("Sequence")??"0",10),displayMode:s.getAttribute("DisplayMode")??void 0,controlsId:l?.getAttribute("Id")??`${i}.Controls`,controls:r,attributes:d,...c.length?{rawControls:c}:{},...l?{}:{rawContent:st(s).map(u=>kn().serializeToString(u)).join("")}})}return{id:t.getAttribute("Id")??`${e.getAttribute("Id")}.Menu`,sections:o,attributes:n}}function my(e){if(e)return e.includes("_")?e.toLowerCase():e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}const kn=()=>new XMLSerializer;function st(e){return e?Array.from(e.childNodes).filter(t=>t.nodeType===Node.ELEMENT_NODE):[]}class py{pending=[];add(t){this.pending.push(t)}flush(){for(const t of[0,1]){const n=this.pending.filter(i=>i.phase===t);if(n.length===0)continue;const o=n.map(i=>i.generate());let s=null;try{const i=Ac(`<v>${o.map(l=>`<i>${l}</i>`).join("")}</v>`);s=st(i).map(l=>st(l)[0])}catch{s=null}n.forEach((i,l)=>{(s?s[l]&&Nn(s[l])===Nn(i.source):ib(o[l],i.source))||i.fallback()})}this.pending=[]}}function fy(e,t){const n=[];return e.querySelectorAll("CommandDefinition").forEach(o=>{const s=o.getAttribute("Id")??"";if(!s)return;const i=st(o),l=m=>i.find(g=>g.tagName===m),r=[],c=(m,g)=>{const b=[];return st(l(m)).forEach((f,y)=>{const x=f.getAttribute("Id");f.tagName===g&&x&&f.attributes.length===1&&st(f).length===0?b.push(x):r.push({container:m,index:y,xml:kn().serializeToString(f)})}),b},d=c("EnableRules","EnableRule"),u=c("DisplayRules","DisplayRule"),p=[];st(l("Actions")).forEach((m,g)=>{const b=hy(m);if(!b){p.push(Dr(m));return}p.push(b),t.add({source:m,generate:()=>ld(b),fallback:()=>p[g]=Dr(m),phase:0})}),n.push({id:s,enableRules:d,displayRules:u,actions:p,...r.length>0?{rawRuleRefs:r}:{}})}),n}function Dr(e){return{kind:"raw",tagName:e.tagName,xml:kn().serializeToString(e)}}function hy(e){switch(e.tagName){case"JavaScriptFunction":{const t=Li(e);return t?{kind:"javascript",library:e.getAttribute("Library")??"",functionName:e.getAttribute("FunctionName")??"",params:t}:null}case"Url":{const t=Li(e);if(!t)return null;const n=e.getAttribute("WinMode");return{kind:"url",address:e.getAttribute("Address")??"",passParams:At(e.getAttribute("PassParams")),winMode:n===null?void 0:Number(n),winParams:e.getAttribute("WinParams")??void 0,params:t}}case"OutlookCommand":return{kind:"outlookCommand",actionType:e.getAttribute("ActionType")??"",data:e.getAttribute("Data")??void 0};default:return null}}function At(e){if(e===null)return;const t=e.trim();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}function Li(e){const t=[];for(const n of st(e)){const o=n.getAttribute("Name")??void 0,s=n.getAttribute("Value")??"";switch(n.tagName){case"CrmParameter":t.push({kind:"CrmParameter",name:o,value:s});break;case"BoolParameter":t.push({kind:"BoolParameter",name:o,value:At(s)??!1});break;case"IntParameter":t.push({kind:"IntParameter",name:o,value:parseInt(s,10)});break;case"DecimalParameter":t.push({kind:"DecimalParameter",name:o,value:parseFloat(s)});break;case"StringParameter":t.push({kind:"StringParameter",name:o,value:s});break;default:return null}}return t}function gy(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > EnableRules > EnableRule").forEach(o=>{const s=o.getAttribute("Id")??"";s&&n.push({id:s,steps:Ba(o,t)})}),n}function by(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > DisplayRules > DisplayRule").forEach(o=>{const s=o.getAttribute("Id")??"";s&&n.push({id:s,steps:Ba(o,t)})}),n}function Ba(e,t){const n=[];return st(e).forEach((o,s)=>{const i=xy(o,t);if(!i){n.push(Er(o));return}n.push(i),t.add({source:o,generate:()=>ws(n[s]),fallback:()=>n[s]=Er(o),phase:i.kind==="OrRule"?1:0})}),n}function Er(e){return{kind:"RawRule",tagName:e.tagName,xml:kn().serializeToString(e)}}function yy(e){const t={},n=At(e.getAttribute("Default")),o=At(e.getAttribute("InvertResult"));return n!==void 0&&(t.default=n),o!==void 0&&(t.invertResult=o),t}function qn(e,t){const n=e.getAttribute(t);return n===null?void 0:parseInt(n,10)}function ut(e,t){return e.getAttribute(t)??void 0}function Ce(e,t){return e.getAttribute(t)??""}function xy(e,t){const n=yy(e);switch(e.tagName){case"OrRule":{const o=st(e);return o.some(s=>s.tagName!=="Or")?null:{kind:"OrRule",groups:o.map(s=>Ba(s,t))}}case"SelectionCountRule":return{kind:"SelectionCountRule",minimum:qn(e,"Minimum"),maximum:qn(e,"Maximum"),appliesTo:ut(e,"AppliesTo"),...n};case"EntityRule":return{kind:"EntityRule",entityName:ut(e,"EntityName"),context:ut(e,"Context"),appliesTo:ut(e,"AppliesTo"),...n};case"FormStateRule":return{kind:"FormStateRule",state:Ce(e,"State"),...n};case"CommandClientTypeRule":return{kind:"CommandClientTypeRule",type:Ce(e,"Type"),...n};case"CustomRule":{const o=Li(e);return o?{kind:"CustomRule",library:Ce(e,"Library"),functionName:Ce(e,"FunctionName"),...o.length>0?{params:o}:{},...n}:null}case"FeatureControlRule":{const o=At(e.getAttribute("ExpectedValue"));return o===void 0?null:{kind:"FeatureControlRule",featureControlBit:Ce(e,"FeatureControlBit"),expectedValue:o,...n}}case"MiscellaneousPrivilegeRule":return{kind:"MiscellaneousPrivilegeRule",privilegeName:Ce(e,"PrivilegeName"),privilegeDepth:ut(e,"PrivilegeDepth"),...n};case"CrmClientTypeRule":return{kind:"CrmClientTypeRule",type:Ce(e,"Type"),...n};case"FormTypeRule":return{kind:"FormTypeRule",type:Ce(e,"Type"),...n};case"ValueRule":return{kind:"ValueRule",field:Ce(e,"Field"),value:Ce(e,"Value"),...n};case"SkuRule":return{kind:"SkuRule",sku:Ce(e,"Sku"),...n};case"HideForTabletExperienceRule":return{kind:"HideForTabletExperienceRule",...n};case"OrganizationSettingRule":return{kind:"OrganizationSettingRule",setting:Ce(e,"Setting"),...n};case"EntityPrivilegeRule":return{kind:"EntityPrivilegeRule",entityName:ut(e,"EntityName"),appliesTo:ut(e,"AppliesTo"),privilegeType:Ce(e,"PrivilegeType"),privilegeDepth:Ce(e,"PrivilegeDepth"),...n};case"EntityPropertyRule":{const o=At(e.getAttribute("PropertyValue"));return o===void 0?null:{kind:"EntityPropertyRule",entityName:ut(e,"EntityName"),appliesTo:ut(e,"AppliesTo"),propertyName:Ce(e,"PropertyName"),propertyValue:o,...n}}case"DeviceTypeRule":return{kind:"DeviceTypeRule",type:Ce(e,"Type"),...n};case"OptionSetRule":return{kind:"OptionSetRule",optionSet:Ce(e,"OptionSet"),stateCode:Ce(e,"StateCode"),objectTypeCode:Ce(e,"ObjectTypeCode"),...n};case"RecordPrivilegeRule":return{kind:"RecordPrivilegeRule",privilegeType:Ce(e,"PrivilegeType"),appliesTo:ut(e,"AppliesTo"),...n};case"FormEntityContextRule":return{kind:"FormEntityContextRule",entityName:Ce(e,"EntityName"),...n};case"PageRule":return{kind:"PageRule",address:Ce(e,"Address"),...n};case"RelationshipTypeRule":return{kind:"RelationshipTypeRule",appliesTo:"SelectedEntity",relationshipType:ut(e,"RelationshipType"),allowCustomRelationship:At(e.getAttribute("AllowCustomRelationship")),allowSystemRelationship:At(e.getAttribute("AllowSystemRelationship")),...n};case"ReferencingAttributeRequiredRule":return{kind:"ReferencingAttributeRequiredRule",...n};case"OutlookItemTrackingRule":{const o=At(e.getAttribute("TrackedInCrm"));return o===void 0?null:{kind:"OutlookItemTrackingRule",trackedInCrm:o,appliesTo:ut(e,"AppliesTo"),...n}}case"OutlookRenderTypeRule":return{kind:"OutlookRenderTypeRule",type:Ce(e,"Type"),...n};case"OutlookVersionRule":return{kind:"OutlookVersionRule",version:Ce(e,"Version"),...n};case"CrmOfflineAccessStateRule":return{kind:"CrmOfflineAccessStateRule",state:Ce(e,"State"),...n};case"CrmOutlookClientTypeRule":return{kind:"CrmOutlookClientTypeRule",type:Ce(e,"Type"),...n};case"CrmOutlookClientVersionRule":return{kind:"CrmOutlookClientVersionRule",major:parseInt(Ce(e,"Major"),10),minor:qn(e,"Minor"),build:qn(e,"Build"),revision:qn(e,"Revision"),...n};default:return null}}function Sy(e){const t=[];return e.querySelectorAll("LocLabel").forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const s=[];n.querySelectorAll("Title").forEach(i=>{const l=parseInt(i.getAttribute("languagecode")??"1033",10),r=i.getAttribute("description")??"";s.push({languageCode:l,description:r})}),t.push({id:o,titles:s})}),t}function Qo(e){return{controlIds:[...Xo(e)],containerIds:[...Gc(e)],locLabelIds:[...e.locLabels.keys()],hides:fs(e),scalingStepIds:$a(e).map(t=>t.id),commandIds:[...e.commandDefinitions.keys()],commandRefIds:[...Uc(e)]}}async function dI(e){try{return Qo(await zi(e))}catch{return null}}function vy(e){const t=`<RibbonDiffXml><CommandDefinitions>${[...e.commandDefinitions.values()].join("")}</CommandDefinitions><RuleDefinitions><DisplayRules>${[...e.displayRules.values()].join("")}</DisplayRules><EnableRules>${[...e.enableRules.values()].join("")}</EnableRules></RuleDefinitions></RibbonDiffXml>`,n=Is(t,"HomepageGrid","");return{commands:n.commands,enableRules:n.enableRules,displayRules:n.displayRules}}function wy(){return window.dataverseAPI}async function Cn(e){const t=[];let n=e;for(;n;){const o=await wy().queryData(n);t.push(...o.value??[]);const s=o["@odata.nextLink"];n=s?s.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}async function zi(e){const t=e===null?"entity eq null and ismanaged eq false":`entity eq '${e.replace(/'/g,"''")}' and ismanaged eq false`,[n,o,s]=await Promise.all([Cn(`ribbondiffs?$select=diffid,difftype,rdx,sequence&$filter=${t}&$orderby=sequence asc,diffid asc`),Cn(`ribboncommands?$select=command,commanddefinition&$filter=${t}&$orderby=command asc`),Cn(`ribbonrules?$select=ruleid,ruletype,ruledefinition&$filter=${t}&$orderby=ruleid asc`)]);return cb({diffs:n,commands:o,rules:s})}function Pi(e){const t=[];for(const[n,o]of e.locLabels){const s=new DOMParser().parseFromString(o,"application/xml"),i=Array.from(s.querySelectorAll("Title")).map(l=>({languageCode:Number(l.getAttribute("languagecode")??1033),description:l.getAttribute("description")??""}));t.push({id:n,titles:i})}return t}function Br(e,t,n,o){const i=`${za()}.${In(e)}.${In(t)}.${In(n)}`;return Pa(i,o)}function La(e,t,n){const s=`${za()}.${In(e)}.${In(t)}.Command`;return Pa(s,n)}function uo(e,t,n){const s=`${za()}.${In(e)}.${t}Rule`;return Pa(s,n)}function Lr(e){return e.replace(/\.Command$/,"").split(".").pop()||"Rule"}function za(){try{return ae.getState().publisherPrefix||"new"}catch{return"new"}}function In(e){return e.replace(/[^a-zA-Z0-9._]/g,"").replace(/^[^a-zA-Z]/,"x")}function Pa(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n++;return`${e}${n}`}function fd(e,t,n,o,s){const i=o.replace(/[^a-zA-Z0-9_]/g,"")||"Button",l=`${e}.${t}.${n}.${i}`;let r=l;for(let c=2;s.has(`${r}.Button`)||s.has(`${r}.Command`);c++)r=`${l}${c}`;return{id:`${r}.Button`,commandId:`${r}.Command`}}function uI(e){return/\s/.test(e)?"ID must not contain whitespace":e?/^[a-zA-Z]/.test(e)?null:"ID must start with a letter":"ID must not be empty"}const J=Xt()(e=>({location:"HomepageGrid",tabId:"MainTab",selectedButtonId:null,selectedGroupId:null,setLocation(t){e({location:t,tabId:"MainTab",selectedButtonId:null,selectedGroupId:null})},setTabId(t){e({tabId:t,selectedButtonId:null,selectedGroupId:null})},selectGroup(t){e({selectedGroupId:t,selectedButtonId:null})},selectButton(t,n){e({selectedGroupId:t,selectedButtonId:n})},selectButtonInContext(t,n,o,s){e({location:t,tabId:n,selectedGroupId:o,selectedButtonId:s})},clearSelection(){e({selectedButtonId:null,selectedGroupId:null})}}));function xo(e){return/\.AllEntities\./.test(e)||/\.VisualizationTab$/.test(e)}function mo(e){const t=e.filter(n=>!xo(n.id));return(t.find(n=>/\.MainTab$/.test(n.id))??t[0]??e[0])?.id}const Ve="Mscrm.OpenRecordItem",hd=["HomepageGrid","SubGrid"],Cy=/\.(HomepageGrid|SubGrid)\.OpenRecordItem\d*\.Button$/;function gd(e){return e.commandId===Ve&&Cy.test(e.id)}function Fa(e){const t=[];for(const n of e?.tabs??[])for(const o of n.groups)for(const s of Ne(o))s.commandId===Ve&&t.push({tabId:n.id,groupId:o.id,button:s});return t}function bd(e){return Fa(e).filter(t=>gd(t.button))}function yd(e){const t=e.button.origin;return t==="unmanaged"?"yours":t===void 0?"unknown":"theirs"}function xd(e){const t=e?.tabs??[],n=mo(t.filter(i=>i.groups.length>0)),o=t.find(i=>i.id===n),s=o?.groups.find(i=>/\.Management$/.test(i.id))??o?.groups[0];return o&&s?{tabId:o.id,groupId:s.id}:null}function Iy(){return{id:Ve,enableRules:[],displayRules:[],actions:[{kind:"javascript",library:"$webresource:",functionName:"YourNamespace.openRecord",params:[{kind:"CrmParameter",value:"SelectedControlSelectedItemReferences"}]}]}}function jy(e){for(const t of e.actions){if(t.kind!=="javascript")continue;if(!t.library.trim().replace(/^\$webresource:/i,"").trim()||!t.functionName.trim())return`${Ve} has a JavaScript action without a web resource or function — set them in the Command Editor, or turn the override off`}return null}const Ry=["Mscrm.HideOnModern","Mscrm.ShowOnlyOnModern"];function Wn(e,t){const n=new Set;for(const o of[t,e.baseline])for(const s of Object.values(o??{}))for(const i of s.tabs){n.add(i.id);for(const l of i.groups){n.add(l.id);for(const r of Ne(l))n.add(r.id)}}for(const o of Object.values(e.layers??{})){for(const s of o?.containerIds??[])n.add(s);for(const s of o?.controlIds??[])n.add(s)}return n}function jn(e,t){return po(e,t)?.containerIds}function po(e,t){return e.layers[t==="Application"?"application":"entity"]}function at(e){return JSON.parse(JSON.stringify(e))}function vt(e){return{ribbons:e.ribbons,commands:e.commands,enableRules:e.enableRules,displayRules:e.displayRules,locLabels:e.locLabels,pendingUnhides:e.pendingUnhides,pendingOrphanDeletes:e.pendingOrphanDeletes,customisedCommandIds:e.customisedCommandIds,uncustomisedCommandIds:e.uncustomisedCommandIds}}function Oe(e,t,n,o,s="info"){return{ts:new Date().toISOString(),userId:"",userName:"You",op:e,target:t,detail:n,icon:o,color:s}}let lt=null;const $y=1e3;let es=null,Ny=0;function Sd(e,t,n,o){const s=es??o,i=e.past[e.past.length-1];return s&&i?.coalesceKey===s&&e.future.length===0&&(es!==null||Date.parse(t.ts)-Date.parse(i.ts)<$y)?{past:[...e.past.slice(0,-1),{...i,...t}],future:[],mutationsSincePublish:e.mutationsSincePublish+1}:{past:[...e.past,{...t,coalesceKey:s,snapshot:n()}].slice(-80),future:[],mutationsSincePublish:e.mutationsSincePublish+1}}function Fe(e,t,n,o){return lt?(lt.meta||(lt.meta=n),t):{...t,...Sd(e,n,()=>vt(e),o)}}function Te(e,t,n,o){const s=at(e.ribbons);return t(s),Fe(e,{ribbons:s},n,o)}function so(e){const t=(n,o)=>JSON.stringify(n)===JSON.stringify(o);return e.pendingUnhides.entity.length+e.pendingUnhides.application.length>0||e.pendingOrphanDeletes.entity.length+e.pendingOrphanDeletes.application.length>0||e.customisedCommandIds.length>0||e.uncustomisedCommandIds.entity.length+e.uncustomisedCommandIds.application.length>0||!t(e.ribbons,e.baseline)||!t(e.commands,e.baselineCommands)||!t(e.enableRules,e.baselineEnableRules)||!t(e.displayRules,e.baselineDisplayRules)||!t(e.locLabels,e.baselineLocLabels)}function Hn(e,t){const n=e.findIndex(o=>o.id===t.id);return n<0?[...e,t]:JSON.stringify(e[n])===JSON.stringify(t)?null:e.map((o,s)=>s===n?t:o)}const zr={entity:null,application:null},Ws={entity:[],application:[]},Pr=["HomepageGrid","SubGrid","Form"];function vd(e,t,n){return(t===void 0||e>t)&&(n===void 0||e<n)?e:t!==void 0&&n!==void 0?n-t>1?Math.floor((t+n)/2):void 0:t!==void 0?t+10:n!==void 0?n>1?Math.max(1,n-10):void 0:e}function Fr(e,t){for(let n=1;n<e.length;n++)e[n].sequence>e[n-1].sequence||(t(e[n])?ts(e,n,t):t(e[n-1])&&ts(e,n-1,t));for(const n of e.filter(t)){const o=e.indexOf(n);if((e[o-1]?.sequence??-1/0)<n.sequence&&n.sequence<(e[o+1]?.sequence??1/0))continue;e.splice(o,1);const i=e.findIndex(l=>l.sequence>n.sequence);e.splice(i<0?e.length:i,0,n)}}function pt(e){return[...e].sort((t,n)=>t.sequence-n.sequence)}function wd(e,t){const n=new Set(e.baseline[t]?.tabs.flatMap(s=>s.groups.map(i=>i.id))??[]),o=new Set(jn(e,t)??[]);return s=>!n.has(s.id)||o.has(s.id)}function Cd(e,t,n,o,s){const i=pt(e.ribbons[t].tabs.find(d=>d.id===n)?.groups??[]),l=i.findIndex(d=>d.id===o),r=i[l+s];if(l<0||!r)return!1;const c=wd(e,t);return c(i[l])||c(r)}function ts(e,t,n){let o=t;for(;o>0&&n(e[o-1]);)o--;let s=t;for(;s<e.length-1&&n(e[s+1]);)s++;const i=o>0?e[o-1].sequence:0,l=s<e.length-1?e[s+1].sequence:1/0;if(l-i-1>=s-o+1){let d=i;for(let u=o;u<=s;u++){const p=s-u,m=e[u];m.sequence>d&&m.sequence<=l-1-p||(m.sequence=l===1/0?d+10:d+Math.max(1,Math.min(10,Math.floor((l-d)/(p+2))))),d=m.sequence}return}const r=new Set(e.filter((d,u)=>u!==t).map(d=>d.sequence));let c=(t>0?e[t-1].sequence:0)+1;for(;r.has(c);)c++;e[t].sequence=c}function _r(e,t,n){const o=e[t],s=vd(o.sequence,e[t-1]?.sequence,e[t+1]?.sequence);if(s!==void 0){o.sequence=s;return}if(ts(e,t,n),!((e[t-1]?.sequence??-1/0)<o.sequence&&o.sequence<(e[t+1]?.sequence??1/0))){e.splice(t,1);const l=e.findIndex(r=>r.sequence>o.sequence);e.splice(l<0?e.length:l,0,o)}}function Hs(){const{activeSolution:e,publisherPrefix:t}=ae.getState();return e?.publisherPrefix?.trim()||t?.trim()||"new"}function Gs(e,t){const n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(`${o}.`)||n.startsWith(`${o}_`)?e:`${t}.${e}`}const Us={HomepageGrid:{location:"HomepageGrid",entityLogicalName:"",tabs:[]},SubGrid:{location:"SubGrid",entityLogicalName:"",tabs:[]},Form:{location:"Form",entityLogicalName:"",tabs:[]},Application:{location:"Application",entityLogicalName:"",tabs:[]}};function ht(e,t,n,o,s){const i=e[t].tabs.find(r=>r.id===n)?.groups.find(r=>r.id===o),l=Ss(i,s);return i&&l?{group:i,button:l}:void 0}function Id(e,t,n){return(e.baseline[t]?.tabs??[]).some(o=>o.groups.some(s=>Ne(s).some(i=>i.id===n)))}function rt(e,t,n){return e==="Application"&&t==="Mscrm.GlobalTab"&&n.oob===!0&&n.custom!==!0}function _a(e,t,n){return n.origin!=="unmanaged"&&!n.hidden&&n.kind!=="flyout"&&n.kind!=="splitButton"&&!dt(n.kind)&&!rt(e,t,n)}function Ty(e,t,n){for(const o of e.baseline[t].tabs)for(const s of o.groups){const i=s.buttons.find(l=>l.id===n);if(i)return i}}function ky(e,t,n){if(t.location!==n.location||t.tabId!==n.tabId||t.groupId!==n.groupId)return!1;const o=pt(e.buttons),s=o.findIndex(l=>l.id===t.buttonId),i=o[s+1]?.id;return n.beforeButtonId?n.beforeButtonId===t.buttonId||n.beforeButtonId===i:i===void 0}const ns=/^\$LocLabels:/,io=e=>e.labelsUnknown?void 0:new Set(e.locLabels.map(t=>t.id));function Ay(e,t){if(!e)return;const n=s=>s&&(!ns.test(s)||no(s,t))?s:void 0,o={};for(const[s,i]of Object.entries(e.attributes))s!=="Id"&&!ns.test(i)&&(o[s]=i);return{...e,labelToken:n(e.labelToken),tooltipTitleToken:n(e.tooltipTitleToken),tooltipBodyToken:n(e.tooltipBodyToken),attributes:o}}const Vs=(e,t)=>({entity:e.entity.filter(n=>n!==t),application:e.application.filter(n=>n!==t)});function qr(e,t){const n=e.baselineCommands.find(s=>s.id===t),o=e.commands.find(s=>s.id===t);return!n||!o||JSON.stringify(n)===JSON.stringify(o)?e.commands:e.commands.map(s=>s.id===t?JSON.parse(JSON.stringify(n)):s)}const M=Xt()(Kg((e,t)=>({ribbons:at(Us),baseline:at(Us),baselineCommands:[],baselineEnableRules:[],baselineDisplayRules:[],baselineLocLabels:[],layers:{...zr},pendingUnhides:{entity:[],application:[]},orphans:{entity:[],application:[]},pendingOrphanDeletes:{entity:[],application:[]},baseLanguageCode:1033,baseLanguageUnknown:!1,labelsUnknown:!1,customisedCommandIds:[],uncustomisedCommandIds:{entity:[],application:[]},reloadRequiredCommandIds:[],commands:[],displayRules:[],enableRules:[],locLabels:[],templates:[],conflicts:[],mutationsSincePublish:0,past:[],future:[],loadRibbons(n){e({ribbons:at(n),baseline:at(n),mutationsSincePublish:0,past:[],future:[]}),lt&&(lt={snapshot:vt(t()),meta:null})},setConflicts(n){e({conflicts:n})},applyImport(n,o){e(s=>Fe(s,{ribbons:{...s.ribbons,...at(n.ribbons)},commands:[...n.commands],enableRules:[...n.enableRules],displayRules:[...n.displayRules],locLabels:[...n.locLabels]},Oe("imported","RibbonDiffXml",o,"arrow_upload","success")))},loadWorkspace(n){const o=at(n.ribbons);e({ribbons:o,baseline:at(o),commands:[...n.commands],displayRules:[...n.displayRules],enableRules:[...n.enableRules],baselineCommands:JSON.parse(JSON.stringify(n.commands)),baselineDisplayRules:JSON.parse(JSON.stringify(n.displayRules)),baselineEnableRules:JSON.parse(JSON.stringify(n.enableRules)),locLabels:[...n.locLabels],baselineLocLabels:JSON.parse(JSON.stringify(n.locLabels)),layers:{...zr,...n.layers??{}},pendingUnhides:{...Ws},orphans:{entity:[],application:[],...n.orphans??{}},pendingOrphanDeletes:{...Ws},baseLanguageCode:n.baseLanguageCode??1033,baseLanguageUnknown:n.baseLanguageUnknown??!1,labelsUnknown:n.labelsUnknown??!1,customisedCommandIds:[],uncustomisedCommandIds:{entity:[],application:[]},reloadRequiredCommandIds:[],templates:[...n.templates??[]],conflicts:[...n.conflicts??[]],mutationsSincePublish:0,past:[],future:[]}),lt&&(lt={snapshot:vt(t()),meta:null})},restoreWorkspace(n,o){const s=JSON.parse(JSON.stringify(n));e(i=>{const l=c=>{const d=i.layers[c];return d?s.pendingUnhides[c].filter(u=>d.hides.some(p=>p.location===u)):s.pendingUnhides[c]},r={...s,pendingUnhides:{entity:l("entity"),application:l("application")}};return JSON.stringify(vt({...i,...r}))===JSON.stringify(vt(i))?i:Fe(i,r,Oe("restored","unsaved changes",o,"history"))})},resetWorkspace(){t().loadWorkspace({ribbons:Us,commands:[],displayRules:[],enableRules:[],locLabels:[]})},undo(){t().restore(t().past.length-1)},redo(){const n=t();if(n.future.length===0||lt)return;const[o,...s]=n.future;e({...o.snapshot,past:[...n.past,{...o,snapshot:vt(n)}],future:s,mutationsSincePublish:so({...n,...o.snapshot})?n.mutationsSincePublish+1:0})},restore(n){const o=t(),{past:s}=o;if(n<0||n>=s.length||lt)return;let i=vt(o),l=o.future;for(let c=s.length-1;c>=n;c--)l=[{...s[c],coalesceKey:void 0,snapshot:i},...l],i=s[c].snapshot;const r=s.length-n;e({...i,past:s.slice(0,n),future:l,mutationsSincePublish:so({...o,...i})?Math.max(1,o.mutationsSincePublish-r):0})},batch(n){if(lt){n();return}lt={snapshot:vt(t()),meta:null};try{n()}finally{const{snapshot:o,meta:s}=lt;lt=null,s&&e(i=>Sd(i,s,()=>o))}},beginEditSession(){es=`session:${++Ny}`},endEditSession(){es=null},moveButton(n,o){const s=t(),l=s.ribbons[n.location].tabs.find(p=>p.id===n.tabId)?.groups.find(p=>p.id===n.groupId),r=l?.buttons.find(p=>p.id===n.buttonId),c=s.ribbons[o.location].tabs.find(p=>p.id===o.tabId)?.groups.find(p=>p.id===o.groupId);if(!r||!l||!c)return null;const d=Ty(s,n.location,r.id)?.origin;if(d!==void 0&&d!=="unmanaged"&&!r.menu&&!wn(r.kind)&&!rt(n.location,n.tabId,r)){if(ky(l,n,o))return null;const p=f=>(ce.getState().logWarn("ribbon",`Can't move ${r.id}: ${f}`),null);if(r.hidden)return p("it's hidden — move your copy of it instead.");if(n.location==="Application"!=(o.location==="Application"))return p("it isn't yours, and a copy can't move between the table's ribbon and the application ribbon.");const m=Hs();let g=null,b=!1;return t().batch(()=>{const f=t().customiseButton(n.location,n.tabId,n.groupId,n.buttonId,m);f&&(b=!0,g=t().moveButton({...n,buttonId:f},o),ce.getState().logInfo("ribbon",`${r.id} isn't yours, so it can't be moved: moved your copy ${f} instead and hid the original.`))}),b&&!g&&t().undo(),b?g:p("it isn't yours and can't be copied (e.g. it has an override of its command); undo the override, then move it.")}return rt(n.location,n.tabId,r)?null:(e(p=>Te(p,m=>{const g=m[n.location].tabs.find(I=>I.id===n.tabId);if(!g)return;const b=g.groups.find(I=>I.id===n.groupId);if(!b)return;const f=b.buttons.findIndex(I=>I.id===n.buttonId);if(f===-1||rt(n.location,n.tabId,b.buttons[f]))return;const x=(n.tabId===o.tabId&&n.location===o.location?g:m[o.location].tabs.find(I=>I.id===o.tabId))?.groups.find(I=>I.id===o.groupId);if(!x)return;const[S]=b.buttons.splice(f,1);x.buttons.sort((I,j)=>I.sequence-j.sequence);const C=o.beforeButtonId?x.buttons.findIndex(I=>I.id===o.beforeButtonId):x.buttons.length,N=C<0?x.buttons.length:C;x.buttons.splice(N,0,S);const O=vd(S.sequence,x.buttons[N-1]?.sequence,x.buttons[N+1]?.sequence);if(O!==void 0)S.sequence=O;else{const I=new Set(p.layers[o.location==="Application"?"application":"entity"]?.controlIds??[]),j=new Set(p.baseline[o.location].tabs.flatMap($=>$.groups.flatMap(w=>w.buttons.map(A=>A.id))));ts(x.buttons,N,$=>$===S||I.has($.id)||!j.has($.id))}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"moved",target:n.buttonId,detail:`to ${o.groupId}`,icon:"arrow_move",color:"info"})),n.buttonId)},setButtonProp(n,o,s,i,l){const c=Object.values(l).every(d=>typeof d=="string")?`button:${n}:${i}:${Object.keys(l).sort().join(",")}`:void 0;e(d=>{const u=p=>{const m=ht(p,n,o,s,i);return!m||l.kind===void 0||l.kind===m.button.kind||!Id(d,n,i)&&(m.group.buttons.includes(m.button)||Na.includes(l.kind))};return Object.keys(l).length===1&&!u(d.ribbons)?{}:Te(d,p=>{const m=ht(p,n,o,s,i)?.button;if(!m||rt(n,o,m))return;const g=m.kind,b=u(p);Object.assign(m,l),b||(m.kind=g),wn(m.kind)&&!m.menu&&(m.menu=Ps(m.id))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:l.label??i,detail:Object.keys(l).join(", "),icon:"edit",color:"info"},c)})},deleteButton(n,o,s,i){const l=t(),r=ht(l.ribbons,n,o,s,i)?.button;if(r&&!Cs(r,l.baseline[n])){ce.getState().logWarn("ribbon",`"${r.label}" (${i}) was not deleted: only your own buttons can be deleted — hide it instead.`);return}e(c=>Te(c,d=>{const u=ht(d,n,o,s,i);if(!u)return;const{group:p,button:m}=u;rt(n,o,m)||Zc(p,i)||(p.buttons=p.buttons.filter(g=>g.id!==i))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:i,detail:s,icon:"delete",color:"danger"}))},addMenuItem({location:n,tabId:o,groupId:s,parentId:i,sectionId:l,item:r}){e(c=>Te(c,d=>{const u=ht(d,n,o,s,i)?.button;if(!u||rt(n,o,u))return;u.menu=u.menu??Ps(u.id),u.menu.sections.length===0&&u.menu.sections.push(Ti(u.id,[]));const p=u.menu.sections.find(g=>g.id===l)??u.menu.sections[0],m=p.controls[p.controls.length-1]?.sequence??0;p.controls.push({...r,kind:r.kind??"button",sequence:r.sequence??m+10,templateAlias:r.templateAlias??"",hidden:!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"})},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:r.label,detail:`menu of ${i}`,icon:"add",color:"success"}))},addMenuSection(n,o,s,i,l){e(r=>Te(r,c=>{const d=ht(c,n,o,s,i)?.button;!d||rt(n,o,d)||(d.menu=d.menu??{id:`${d.id}.Menu`,sections:[]},d.menu.sections.push(Ti(d.id,d.menu.sections,l)))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:l??"Menu section",detail:`menu of ${i}`,icon:"add",color:"success"}))},setMenuSectionProp(n,o,s,i,l,r){e(c=>Te(c,d=>{const u=ht(d,n,o,s,i)?.button,p=u?.menu?.sections.find(m=>m.id===l);!u||!p||rt(n,o,u)||Object.assign(p,r)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:l,detail:Object.keys(r).join(", "),icon:"edit",color:"info"}))},deleteMenuSection(n,o,s,i,l){e(r=>Te(r,c=>{const d=ht(c,n,o,s,i)?.button;!d?.menu||rt(n,o,d)||(d.menu.sections=d.menu.sections.filter(u=>u.id!==l))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:l,detail:`menu of ${i}`,icon:"delete",color:"danger"}))},duplicateButton(n,o,s,i){e(l=>Te(l,r=>{const c=ht(r,n,o,s,i);if(c){const{group:d,button:u}=c;if(rt(n,o,u))return;const p=io(l),m=to(u.source?.labelToken)||no(u.source?.labelToken,p),g={...Yo(u,`${Gs(u.id,Hs())}_copy_${Date.now()}`,p),label:dt(u.kind)||m?u.label:`${u.label} (copy)`,sequence:u.sequence},b=Ko(d,i),f=b?b.section.controls:d.buttons,y=f.findIndex(C=>C.id===i);f.splice(y+1,0,g);const x=new Set(po(l,n)?.controlIds??[]),S=new Set((l.baseline[n]?.tabs??[]).flatMap(C=>C.groups.flatMap(Ne)).map(C=>C.id));_r(f,y+1,C=>C===g||x.has(C.id)||!S.has(C.id))}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:i,detail:s,icon:"copy",color:"info"}))},createButton({tabId:n,groupId:o,location:s,button:i}){e(l=>Te(l,r=>{const d=r[s].tabs.find(u=>u.id===n)?.groups.find(u=>u.id===o);if(d){const u=new Set(d.buttons.map(b=>b.sequence)),p=Math.max(0,...d.buttons.map(b=>b.sequence))+10,m=i.sequence!==void 0&&!u.has(i.sequence)?i.sequence:p,g={...i,id:i.id??`new_${Date.now()}`,label:i.label??"New Button",kind:i.kind??"button",sequence:m,templateAlias:i.templateAlias??"o1",commandId:i.commandId??"",hidden:i.hidden??!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"};wn(g.kind)&&!g.menu&&(g.menu=Ps(g.id)),d.buttons.push(g)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:i.label??"New Button",detail:o,icon:"add",color:"success"}))},createGroup({tabId:n,location:o,group:s}){e(i=>Te(i,l=>{const r=l[o].tabs.find(c=>c.id===n);if(r){const c=l[o],d=o==="Application"?"global":c.entityLogicalName,u={id:s.id??Br(d,`${o}.${s.label??"New Group"}`,"Group",Wn(i,l)),label:s.label??"New Group",sequence:s.sequence!==void 0&&!r.groups.some(p=>p.sequence===s.sequence)?s.sequence:Math.max(0,...r.groups.map(p=>p.sequence))+10,template:s.template??"Flexible2",buttons:s.buttons??[]};r.groups.push(u)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:s.label??"New Group",detail:n,icon:"add",color:"success"}))},renameGroup(n,o,s,i){e(l=>Te(l,r=>{const d=r[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===s);d&&(d.label=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:s,detail:i,icon:"edit",color:"info"}))},duplicateGroup(n,o,s){let i=null;if(e(l=>Te(l,r=>{const c=r[n].tabs.find(N=>N.id===o);if(!c)return;const d=c.groups.find(N=>N.id===s);if(!d)return;const u=`_copy_${Date.now()}`,p=Hs(),m=io(l),g=l.baseLanguageCode,b=d.source?.titleToken,f=b!==void 0&&He(b,l.locLabels,g)===d.label?b:d.label,y=to(f)||no(f,m),x={...JSON.parse(JSON.stringify(d)),id:`${Gs(d.id,p)}${u}`,label:y?He(f,l.locLabels,g):`${He(d.label,l.locLabels,g)} (copy)`,source:y?{titleToken:f,attributes:{}}:void 0,description:void 0,sequence:d.sequence,buttons:d.buttons.map(N=>Yo(N,`${Gs(N.id,p)}${u}`,m))},S=c.groups.findIndex(N=>N.id===s);c.groups.splice(S+1,0,x);const C=new Set((l.baseline[n]?.tabs??[]).flatMap(N=>N.groups.map(O=>O.id)));_r(c.groups,S+1,N=>N===x||!C.has(N.id)),y&&(i={copyId:x.id,title:f})},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:s,detail:o,icon:"copy",color:"info"})),i){const{copyId:l,title:r}=i;ce.getState().logInfo("ribbon",`Duplicate group ${s}: the copy ${l} keeps its title ${r}, which comes from ${to(r)?"the platform":"another solution"} and can't take " (copy)". Rename the copy before you publish if it should read differently: once published, only titles of your own can be renamed.`)}},setGroupTemplate(n,o,s,i){e(l=>Te(l,r=>{const d=r[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===s);d&&(d.template=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:s,detail:`template → ${i}`,icon:"edit",color:"info"}))},deleteGroup(n,o,s){const i=t(),l=i.ribbons[n].tabs.find(r=>r.id===o)?.groups.find(r=>r.id===s);if(l&&!Ea(l,i.baseline[n],jn(i,n))){ce.getState().logWarn("ribbon",`Group "${l.label}" (${s}) was not deleted: only your own groups, with only your own buttons in them, can be deleted — hide its buttons instead.`);return}e(r=>Te(r,c=>{const d=c[n].tabs.find(u=>u.id===o);d&&(d.groups=d.groups.filter(u=>u.id!==s))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:s,detail:o,icon:"delete",color:"danger"}))},createTab(n,o){e(s=>o.id&&Wn(s,s.ribbons).has(o.id)?{}:Te(s,i=>{const l=i[n],r=n==="Application"?"global":l.entityLogicalName,c=o.id??Br(r,`${n}.${o.label??"New Tab"}`,"Tab",Wn(s,i)),d=Qc({...o,id:c}),u={id:c,label:o.label??"New Tab",sequence:o.sequence!==void 0&&!l.tabs.some(p=>p.sequence===o.sequence)?o.sequence:Math.max(0,...l.tabs.map(p=>p.sequence))+10,commandId:d,tabDisplayRules:o.tabDisplayRules?.length?o.tabDisplayRules:ed(n,l.entityLogicalName,d),groups:[]};l.tabs.push(u)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:o.label??"New Tab",detail:n,icon:"add",color:"success"}))},renameTab(n,o,s){e(i=>Te(i,l=>{const r=l[n].tabs.find(c=>c.id===o);r&&(r.label=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:o,detail:s,icon:"edit",color:"info"}))},deleteTab(n,o){const s=t(),i=s.ribbons[n].tabs.find(l=>l.id===o);if(i&&!ud(i,s.baseline[n],jn(s,n))){ce.getState().logWarn("ribbon",`Tab "${i.label}" (${o}) was not deleted: only your own tabs, with only your own groups and buttons in them, can be deleted.`);return}e(l=>Te(l,r=>{r[n].tabs=r[n].tabs.filter(c=>c.id!==o)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:o,detail:n,icon:"delete",color:"danger"}))},reorderTabs(n,o){e(s=>Te(s,i=>{const l=i[n].tabs,r=o.map(u=>l.find(p=>p.id===u)).filter(u=>u!==void 0);i[n].tabs=r;const c=new Set(s.baseline[n]?.tabs.map(u=>u.id)??[]),d=new Set(jn(s,n)??[]);Fr(r,u=>!c.has(u.id)||d.has(u.id))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"reordered",target:"Tabs",detail:n,icon:"arrow_sort",color:"info"}))},moveGroup(n,o,s,i){const l=t();if(!Cd(l,n,o,s,i))return;const r=l.ribbons[n].tabs.find(c=>c.id===o)?.groups.find(c=>c.id===s)?.label??s;e(c=>Te(c,d=>{const u=d[n].tabs.find(b=>b.id===o);if(!u)return;u.groups.sort((b,f)=>b.sequence-f.sequence);const p=u.groups.findIndex(b=>b.id===s),[m]=u.groups.splice(p,1);u.groups.splice(p+i,0,m);const g=wd(c,n);Fr(u.groups,g)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"reordered",target:r,detail:i<0?"Moved left":"Moved right",icon:"arrow_sort",color:"info"}))},setTabDisplayRules(n,o,s){e(i=>Te(i,l=>{const r=l[n].tabs.find(c=>c.id===o);r&&(r.tabDisplayRules=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} display rules`,detail:`${s.length} rule(s)`,icon:"eye",color:"info"}))},setScaling(n,o,s){e(i=>Te(i,l=>{const r=l[n];r.scalingByTab=r.scalingByTab??{},r.scalingByTab[o]={tabId:o,maxSizes:[...s.maxSizes],scales:[...s.scales]}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} scaling`,detail:`${s.maxSizes.length} MaxSize, ${s.scales.length} Scale`,icon:"resize",color:"info"}))},hideOobButton(n,o,s,i){e(l=>Te(l,r=>{const c=ht(r,n,o,s,i)?.button;c&&(rt(n,o,c)||(c.hidden=!0))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"hid",target:i,detail:s,icon:"eye_off",color:"warn"}))},customizeOobButton(n,o,s,i){e(l=>Te(l,r=>{const c=ht(r,n,o,s,i)?.button;if(c){if(rt(n,o,c))return;c.oob=!1,c.custom=!0,c.managed=!1,c.origin="unmanaged"}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"customized",target:i,detail:"OOB override",icon:"edit",color:"info"}))},customiseButton(n,o,s,i,l){const r=t(),c=r.ribbons[n].tabs.find(x=>x.id===o)?.groups.find(x=>x.id===s)?.buttons.find(x=>x.id===i);if(!c||!_a(n,o,c))return null;const d=Wn(r,r.ribbons),u=`${(l||"new").trim()}.${c.id}`;let p=u;for(let x=2;d.has(p);x++)p=`${u}.${x}`;const m=[],g=[],b=io(r),f=[[c.source?.labelToken,gs(p)],[c.source?.tooltipTitleToken,bs(p)],[c.source?.tooltipBodyToken,ys(p)]];for(const[x,S]of f){if(!x||!ns.test(x))continue;const C=r.locLabels.find(N=>N.id===x.replace(ns,""));C?m.push({id:S,titles:C.titles.map(N=>({...N}))}):no(x,b)&&g.push(x)}g.length>0&&ce.getState().logInfo("ribbon",`Customise button ${c.id}: ${g.join(", ")} ${g.length===1?"is":"are"} defined by another solution, so the copy ${p} uses ${g.length===1?"it":"them"} too. Edit the copy's text to give it a label of its own.`);const y=new Set(m.map(x=>x.id));return e(x=>{const S=at(x.ribbons),C=S[n].tabs.find($=>$.id===o)?.groups.find($=>$.id===s),N=C?.buttons.findIndex($=>$.id===i)??-1;if(!C||N<0)return{};const O=C.buttons[N],I={...O,id:p,source:Ay(O.source,b),hidden:!1,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0},j=C.buttons[N+1]?.sequence;return(j===void 0||O.sequence+1<j)&&(I.sequence=O.sequence+1),O.hidden=!0,C.buttons.splice(N+1,0,I),Fe(x,{ribbons:S,...m.length>0?{locLabels:[...x.locLabels.filter($=>!y.has($.id)),...m]}:{}},Oe("customised",i,`copied to ${p}, original hidden`+(g.length>0?" (keeps another solution's labels)":""),"copy"))}),p},customiseCommand(n){const o=t();return!o.commands.some(s=>s.id===n)||o.reloadRequiredCommandIds.includes(n)?!1:(e(s=>Fe(s,{customisedCommandIds:[...s.customisedCommandIds.filter(i=>i!==n),n],uncustomisedCommandIds:Vs(s.uncustomisedCommandIds,n)},Oe("customised",n,"command copied to your layer on publish","code"))),!0)},uncustomiseCommand(n,o){e(s=>Fe(s,{commands:qr(s,n),customisedCommandIds:s.customisedCommandIds.filter(i=>i!==n),uncustomisedCommandIds:{...Vs(s.uncustomisedCommandIds,n),[o]:[...s.uncustomisedCommandIds[o].filter(i=>i!==n),n]}},Oe("uncustomised",n,`command removed from the ${o==="entity"?"table's":"application ribbon's"} layer on publish`,"arrow_undo")))},discardCommandChanges(n){const o=t(),s=qr(o,n);(s!==o.commands||o.customisedCommandIds.includes(n)||o.uncustomisedCommandIds.entity.includes(n)||o.uncustomisedCommandIds.application.includes(n))&&e(l=>Fe(l,{commands:s,customisedCommandIds:l.customisedCommandIds.filter(r=>r!==n),uncustomisedCommandIds:Vs(l.uncustomisedCommandIds,n)},Oe("discarded",n,"command changes","arrow_undo")))},setOpenRecordOverride(n,o,s){if(!hd.includes(n))return!1;const i=t(),l=i.ribbons[n],r=bd(l);if(o){if(r.length>0)return!0;const c=xd(l);if(!c)return!1;const d=Wn(i,i.ribbons);for(const p of i.commands)d.add(p.id);const{id:u}=fd(s,l.entityLogicalName,n,"OpenRecordItem",d);return t().batch(()=>{t().createButton({location:n,tabId:c.tabId,groupId:c.groupId,button:{id:u,label:"Open record",tooltipTitle:"Open record",tooltipBody:`Runs the table's ${Ve} action for the selected row, as opening a row does.`,kind:"button",templateAlias:"o1",commandId:Ve,hidden:!1,oob:!1,custom:!0,managed:!1}}),t().commands.some(p=>p.id===Ve)||t().upsertCommand(Iy())}),!0}return r.length===0?!0:r.some(c=>yd(c)!=="yours")?!1:(t().batch(()=>{for(const u of r)t().deleteButton(n,u.tabId,u.groupId,u.button.id);const c=t();!Object.values(c.ribbons).some(u=>Fa(u).length>0)&&!c.baselineCommands.some(u=>u.id===Ve)&&e(u=>Fe(u,{commands:u.commands.filter(p=>p.id!==Ve)},Oe("removed",Ve,"grid open override","delete","danger")))}),!0)},hideWithDisplayRules(n){const o=n?t().commands.find(i=>i.id===n):void 0;if(!o)return!1;const s=[...o.displayRules];for(const i of Ry)s.includes(i)||s.push(i);return e(i=>{const l=Hn(i.commands,{...o,displayRules:s});return l?Fe(i,{commands:l},Oe("hid",o.id,"with display rules","eye_off","warn")):i}),!0},upsertCommand(n){e(o=>{const s=Hn(o.commands,n);if(!s)return o;const i=s.length>o.commands.length;return Fe(o,{commands:s},i?Oe("added",n.id,"command","add","success"):Oe("edited",n.id,"command","edit"),i?void 0:`command:${n.id}`)})},renameCommandId(n,o){const s=t();return!n||!o||n===o?!0:s.commands.some(i=>i.id===o)?!1:(e(i=>{const l=at(i.ribbons);for(const c of Object.keys(l))for(const d of l[c].tabs)for(const u of d.groups)for(const p of Ne(u))p.commandId===n&&(p.commandId=o),p.source?.xml&&(p.source.xml=rb(p.source.xml,n,o));const r=i.commands.map(c=>c.id===n?{...c,id:o}:c);return Fe(i,{ribbons:l,commands:r},Oe("renamed",n,`command -> ${o}`,"edit"))}),!0)},upsertDisplayRule(n){e(o=>{const s=Hn(o.displayRules,n);if(!s)return o;const i=s.length>o.displayRules.length;return Fe(o,{displayRules:s},i?Oe("added",n.id,"display rule","add","success"):Oe("edited",n.id,"display rule","edit"),i?void 0:`displayRule:${n.id}`)})},renameDisplayRuleId(n,o){const s=t();return!n||!o||n===o?!0:s.displayRules.some(i=>i.id===o)?!1:(e(i=>{const l=i.displayRules.map(c=>c.id===n?{...c,id:o}:c),r=i.commands.map(c=>({...c,displayRules:c.displayRules.map(d=>d===n?o:d)}));return Fe(i,{displayRules:l,commands:r},Oe("renamed",n,`display rule -> ${o}`,"edit"))}),!0)},upsertEnableRule(n){e(o=>{const s=Hn(o.enableRules,n);if(!s)return o;const i=s.length>o.enableRules.length;return Fe(o,{enableRules:s},i?Oe("added",n.id,"enable rule","add","success"):Oe("edited",n.id,"enable rule","edit"),i?void 0:`enableRule:${n.id}`)})},renameEnableRuleId(n,o){const s=t();return!n||!o||n===o?!0:s.enableRules.some(i=>i.id===o)?!1:(e(i=>{const l=i.enableRules.map(c=>c.id===n?{...c,id:o}:c),r=i.commands.map(c=>({...c,enableRules:c.enableRules.map(d=>d===n?o:d)}));return Fe(i,{enableRules:l,commands:r},Oe("renamed",n,`enable rule -> ${o}`,"edit"))}),!0)},upsertLocLabel(n){e(o=>{const s=Hn(o.locLabels,n);return s?Fe(o,{locLabels:s},Oe("edited",n.id,"label","translate"),`locLabel:${n.id}`):o})},setLayerHideUnhidden(n,o,s){e(i=>{if(i.pendingUnhides[n].includes(o)===s)return i;const l=i.pendingUnhides[n].filter(r=>r!==o);return s&&l.push(o),Fe(i,{pendingUnhides:{...i.pendingUnhides,[n]:l}},s?Oe("un-hid",o,"on publish","eye"):Oe("kept hidden",o,"by customizations","eye_off"))})},setOrphanDeleted(n,o,s){e(i=>{const l=i.orphans[n].find(c=>c.id===o);if(!l||s&&l.recentPublish?.published||i.pendingOrphanDeletes[n].includes(o)===s)return i;const r=i.pendingOrphanDeletes[n].filter(c=>c!==o);return s&&r.push(o),Fe(i,{pendingOrphanDeletes:{...i.pendingOrphanDeletes,[n]:r}},s?Oe("deleted",o,"not on the canvas — removed on publish","delete","danger"):Oe("kept",o,"not on the canvas","arrow_undo"))})},setLayerSnapshot(n,o){e(s=>({layers:{...s.layers,[n]:o}}))},markPublished(n,o){e(s=>{const i=Object.keys(s.ribbons),l=n??i,r=at(s.baseline),c=at(s.ribbons);let d=s.locLabels,u=s.baselineLocLabels;const p=(v,T)=>[...v.filter(R=>!T.some(D=>D.id===R.id)),...T];for(const[v,T]of Object.entries(o??{})){const R=v==="entity"?Pr:["Application"];for(const q of R)l.includes(q)&&xb(c[q],T);const D=Pi(T);d=p(d,D),u=p(u,JSON.parse(JSON.stringify(D)))}for(const v of l)r[v]=at(c)[v];const m=i.every(v=>l.includes(v)),g={...s.layers},b={...s.pendingUnhides},f={entity:[],application:[]},y=[["entity",Pr.every(v=>l.includes(v))],["application",l.includes("Application")]];for(const[v,T]of y){const R=o?.[v];if(!T||!R)continue;const D=g[v],q=(X,ne)=>[...new Set([...X,...ne])];g[v]=D?{...D,containerIds:q(D.containerIds,Gc(R)),controlIds:q(D.controlIds,Xo(R)),locLabelIds:q(D.locLabelIds,new Set(R.locLabels.keys()))}:Qo(R)}for(const[v,T]of y){if(!T||b[v].length===0)continue;const R=g[v];R&&(g[v]={...R,hides:R.hides.filter(D=>!b[v].includes(D.location))}),f[v]=b[v],b[v]=[]}const x={...s.orphans},S={...s.pendingOrphanDeletes},C={entity:[],application:[]};for(const[v,T]of y)!T||S[v].length===0||(x[v]=x[v].filter(R=>!S[v].includes(R.id)),C[v]=S[v],S[v]=[]);const N={...s.uncustomisedCommandIds},O=[...s.reloadRequiredCommandIds],I={entity:[],application:[]};for(const[v,T]of y)if(T){for(const R of N[v])O.includes(R)||O.push(R);I[v]=N[v],N[v]=[]}const j=(v,T)=>({entity:v.entity.filter(R=>!T.entity.includes(R)),application:v.application.filter(R=>!T.application.includes(R))}),$=v=>({...v,snapshot:{...v.snapshot,pendingUnhides:j(v.snapshot.pendingUnhides,f),pendingOrphanDeletes:j(v.snapshot.pendingOrphanDeletes??Ws,C),uncustomisedCommandIds:j(v.snapshot.uncustomisedCommandIds,I)}}),w=[f,I,C].reduce((v,T)=>v+T.entity.length+T.application.length,0)>0,A=s.past.map((v,T)=>{const R=w?$(v):v;return T===s.past.length-1&&R.coalesceKey?{...R,coalesceKey:void 0}:R}),B={ribbons:c,locLabels:d,baselineLocLabels:u,baseline:r,layers:g,pendingUnhides:b,uncustomisedCommandIds:N,orphans:x,pendingOrphanDeletes:S,...m?{baselineCommands:JSON.parse(JSON.stringify(s.commands)),baselineEnableRules:JSON.parse(JSON.stringify(s.enableRules)),baselineDisplayRules:JSON.parse(JSON.stringify(s.displayRules)),baselineLocLabels:JSON.parse(JSON.stringify(d)),customisedCommandIds:[]}:{}},k=so({...s,...B});return{...B,past:A,future:w?s.future.map($):s.future,reloadRequiredCommandIds:O,mutationsSincePublish:k?Math.max(1,s.mutationsSincePublish):0}})}})));Vg(()=>{M.getState().resetWorkspace(),J.getState().clearSelection()});var Me=Uint8Array,ct=Uint16Array,qa=Int32Array,js=new Me([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Rs=new Me([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Fi=new Me([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),jd=function(e,t){for(var n=new ct(31),o=0;o<31;++o)n[o]=t+=1<<e[o-1];for(var s=new qa(n[30]),o=1;o<30;++o)for(var i=n[o];i<n[o+1];++i)s[i]=i-n[o]<<5|o;return{b:n,r:s}},Rd=jd(js,2),$d=Rd.b,_i=Rd.r;$d[28]=258,_i[258]=28;var Nd=jd(Rs,0),Oy=Nd.b,Wr=Nd.r,qi=new ct(32768);for(var Re=0;Re<32768;++Re){var Bt=(Re&43690)>>1|(Re&21845)<<1;Bt=(Bt&52428)>>2|(Bt&13107)<<2,Bt=(Bt&61680)>>4|(Bt&3855)<<4,qi[Re]=((Bt&65280)>>8|(Bt&255)<<8)>>1}var jt=(function(e,t,n){for(var o=e.length,s=0,i=new ct(t);s<o;++s)e[s]&&++i[e[s]-1];var l=new ct(t);for(s=1;s<t;++s)l[s]=l[s-1]+i[s-1]<<1;var r;if(n){r=new ct(1<<t);var c=15-t;for(s=0;s<o;++s)if(e[s])for(var d=s<<4|e[s],u=t-e[s],p=l[e[s]-1]++<<u,m=p|(1<<u)-1;p<=m;++p)r[qi[p]>>c]=d}else for(r=new ct(o),s=0;s<o;++s)e[s]&&(r[s]=qi[l[e[s]-1]++]>>15-e[s]);return r}),Vt=new Me(288);for(var Re=0;Re<144;++Re)Vt[Re]=8;for(var Re=144;Re<256;++Re)Vt[Re]=9;for(var Re=256;Re<280;++Re)Vt[Re]=7;for(var Re=280;Re<288;++Re)Vt[Re]=8;var fo=new Me(32);for(var Re=0;Re<32;++Re)fo[Re]=5;var My=jt(Vt,9,0),Dy=jt(Vt,9,1),Ey=jt(fo,5,0),By=jt(fo,5,1),Xs=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},gt=function(e,t,n){var o=t/8|0;return(e[o]|e[o+1]<<8)>>(t&7)&n},Ks=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Wa=function(e){return(e+7)/8|0},So=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new Me(e.subarray(t,n))},Ly=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ue=function(e,t,n){var o=new Error(t||Ly[e]);if(o.code=e,Error.captureStackTrace&&Error.captureStackTrace(o,Ue),!n)throw o;return o},zy=function(e,t,n,o){var s=e.length,i=o?o.length:0;if(!s||t.f&&!t.l)return n||new Me(0);var l=!n,r=l||t.i!=2,c=t.i;l&&(n=new Me(s*3));var d=function(tt){var Be=n.length;if(tt>Be){var Le=new Me(Math.max(Be*2,tt));Le.set(n),n=Le}},u=t.f||0,p=t.p||0,m=t.b||0,g=t.l,b=t.d,f=t.m,y=t.n,x=s*8;do{if(!g){u=gt(e,p,1);var S=gt(e,p+1,3);if(p+=3,S)if(S==1)g=Dy,b=By,f=9,y=5;else if(S==2){var I=gt(e,p,31)+257,j=gt(e,p+10,15)+4,$=I+gt(e,p+5,31)+1;p+=14;for(var w=new Me($),A=new Me(19),B=0;B<j;++B)A[Fi[B]]=gt(e,p+B*3,7);p+=j*3;for(var k=Xs(A),v=(1<<k)-1,T=jt(A,k,1),B=0;B<$;){var R=T[gt(e,p,v)];p+=R&15;var C=R>>4;if(C<16)w[B++]=C;else{var D=0,q=0;for(C==16?(q=3+gt(e,p,3),p+=2,D=w[B-1]):C==17?(q=3+gt(e,p,7),p+=3):C==18&&(q=11+gt(e,p,127),p+=7);q--;)w[B++]=D}}var X=w.subarray(0,I),ne=w.subarray(I);f=Xs(X),y=Xs(ne),g=jt(X,f,1),b=jt(ne,y,1)}else Ue(1);else{var C=Wa(p)+4,N=e[C-4]|e[C-3]<<8,O=C+N;if(O>s){c&&Ue(0);break}r&&d(m+N),n.set(e.subarray(C,O),m),t.b=m+=N,t.p=p=O*8,t.f=u;continue}if(p>x){c&&Ue(0);break}}r&&d(m+131072);for(var re=(1<<f)-1,le=(1<<y)-1,F=p;;F=p){var D=g[Ks(e,p)&re],L=D>>4;if(p+=D&15,p>x){c&&Ue(0);break}if(D||Ue(2),L<256)n[m++]=L;else if(L==256){F=p,g=null;break}else{var G=L-254;if(L>264){var B=L-257,U=js[B];G=gt(e,p,(1<<U)-1)+$d[B],p+=U}var te=b[Ks(e,p)&le],P=te>>4;te||Ue(3),p+=te&15;var ne=Oy[P];if(P>3){var U=Rs[P];ne+=Ks(e,p)&(1<<U)-1,p+=U}if(p>x){c&&Ue(0);break}r&&d(m+131072);var Q=m+G;if(m<ne){var be=i-ne,Ae=Math.min(ne,Q);for(be+m<0&&Ue(3);m<Ae;++m)n[m]=o[be+m]}for(;m<Q;++m)n[m]=n[m-ne]}}t.l=g,t.p=F,t.b=m,t.f=u,g&&(u=1,t.m=f,t.d=b,t.n=y)}while(!u);return m!=n.length&&l?So(n,0,m):n.subarray(0,m)},Nt=function(e,t,n){n<<=t&7;var o=t/8|0;e[o]|=n,e[o+1]|=n>>8},Gn=function(e,t,n){n<<=t&7;var o=t/8|0;e[o]|=n,e[o+1]|=n>>8,e[o+2]|=n>>16},Ys=function(e,t){for(var n=[],o=0;o<e.length;++o)e[o]&&n.push({s:o,f:e[o]});var s=n.length,i=n.slice();if(!s)return{t:kd,l:0};if(s==1){var l=new Me(n[0].s+1);return l[n[0].s]=1,{t:l,l:1}}n.sort(function(O,I){return O.f-I.f}),n.push({s:-1,f:25001});var r=n[0],c=n[1],d=0,u=1,p=2;for(n[0]={s:-1,f:r.f+c.f,l:r,r:c};u!=s-1;)r=n[n[d].f<n[p].f?d++:p++],c=n[d!=u&&n[d].f<n[p].f?d++:p++],n[u++]={s:-1,f:r.f+c.f,l:r,r:c};for(var m=i[0].s,o=1;o<s;++o)i[o].s>m&&(m=i[o].s);var g=new ct(m+1),b=Wi(n[u-1],g,0);if(b>t){var o=0,f=0,y=b-t,x=1<<y;for(i.sort(function(I,j){return g[j.s]-g[I.s]||I.f-j.f});o<s;++o){var S=i[o].s;if(g[S]>t)f+=x-(1<<b-g[S]),g[S]=t;else break}for(f>>=y;f>0;){var C=i[o].s;g[C]<t?f-=1<<t-g[C]++-1:++o}for(;o>=0&&f;--o){var N=i[o].s;g[N]==t&&(--g[N],++f)}b=t}return{t:new Me(g),l:b}},Wi=function(e,t,n){return e.s==-1?Math.max(Wi(e.l,t,n+1),Wi(e.r,t,n+1)):t[e.s]=n},Hr=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new ct(++t),o=0,s=e[0],i=1,l=function(c){n[o++]=c},r=1;r<=t;++r)if(e[r]==s&&r!=t)++i;else{if(!s&&i>2){for(;i>138;i-=138)l(32754);i>2&&(l(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(l(s),--i;i>6;i-=6)l(8304);i>2&&(l(i-3<<5|8208),i=0)}for(;i--;)l(s);i=1,s=e[r]}return{c:n.subarray(0,o),n:t}},Un=function(e,t){for(var n=0,o=0;o<t.length;++o)n+=e[o]*t[o];return n},Td=function(e,t,n){var o=n.length,s=Wa(t+2);e[s]=o&255,e[s+1]=o>>8,e[s+2]=e[s]^255,e[s+3]=e[s+1]^255;for(var i=0;i<o;++i)e[s+i+4]=n[i];return(s+4+o)*8},Gr=function(e,t,n,o,s,i,l,r,c,d,u){Nt(t,u++,n),++s[256];for(var p=Ys(s,15),m=p.t,g=p.l,b=Ys(i,15),f=b.t,y=b.l,x=Hr(m),S=x.c,C=x.n,N=Hr(f),O=N.c,I=N.n,j=new ct(19),$=0;$<S.length;++$)++j[S[$]&31];for(var $=0;$<O.length;++$)++j[O[$]&31];for(var w=Ys(j,7),A=w.t,B=w.l,k=19;k>4&&!A[Fi[k-1]];--k);var v=d+5<<3,T=Un(s,Vt)+Un(i,fo)+l,R=Un(s,m)+Un(i,f)+l+14+3*k+Un(j,A)+2*j[16]+3*j[17]+7*j[18];if(c>=0&&v<=T&&v<=R)return Td(t,u,e.subarray(c,c+d));var D,q,X,ne;if(Nt(t,u,1+(R<T)),u+=2,R<T){D=jt(m,g,0),q=m,X=jt(f,y,0),ne=f;var re=jt(A,B,0);Nt(t,u,C-257),Nt(t,u+5,I-1),Nt(t,u+10,k-4),u+=14;for(var $=0;$<k;++$)Nt(t,u+3*$,A[Fi[$]]);u+=3*k;for(var le=[S,O],F=0;F<2;++F)for(var L=le[F],$=0;$<L.length;++$){var G=L[$]&31;Nt(t,u,re[G]),u+=A[G],G>15&&(Nt(t,u,L[$]>>5&127),u+=L[$]>>12)}}else D=My,q=Vt,X=Ey,ne=fo;for(var $=0;$<r;++$){var U=o[$];if(U>255){var G=U>>18&31;Gn(t,u,D[G+257]),u+=q[G+257],G>7&&(Nt(t,u,U>>23&31),u+=js[G]);var te=U&31;Gn(t,u,X[te]),u+=ne[te],te>3&&(Gn(t,u,U>>5&8191),u+=Rs[te])}else Gn(t,u,D[U]),u+=q[U]}return Gn(t,u,D[256]),u+q[256]},Py=new qa([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),kd=new Me(0),Fy=function(e,t,n,o,s,i){var l=i.z||e.length,r=new Me(o+l+5*(1+Math.ceil(l/7e3))+s),c=r.subarray(o,r.length-s),d=i.l,u=(i.r||0)&7;if(t){u&&(c[0]=i.r>>3);for(var p=Py[t-1],m=p>>13,g=p&8191,b=(1<<n)-1,f=i.p||new ct(32768),y=i.h||new ct(b+1),x=Math.ceil(n/3),S=2*x,C=function(Y){return(e[Y]^e[Y+1]<<x^e[Y+2]<<S)&b},N=new qa(25e3),O=new ct(288),I=new ct(32),j=0,$=0,w=i.i||0,A=0,B=i.w||0,k=0;w+2<l;++w){var v=C(w),T=w&32767,R=y[v];if(f[T]=R,y[v]=T,B<=w){var D=l-w;if((j>7e3||A>24576)&&(D>423||!d)){u=Gr(e,c,0,N,O,I,$,A,k,w-k,u),A=j=$=0,k=w;for(var q=0;q<286;++q)O[q]=0;for(var q=0;q<30;++q)I[q]=0}var X=2,ne=0,re=g,le=T-R&32767;if(D>2&&v==C(w-le))for(var F=Math.min(m,D)-1,L=Math.min(32767,w),G=Math.min(258,D);le<=L&&--re&&T!=R;){if(e[w+X]==e[w+X-le]){for(var U=0;U<G&&e[w+U]==e[w+U-le];++U);if(U>X){if(X=U,ne=le,U>F)break;for(var te=Math.min(le,U-2),P=0,q=0;q<te;++q){var Q=w-le+q&32767,be=f[Q],Ae=Q-be&32767;Ae>P&&(P=Ae,R=Q)}}}T=R,R=f[T],le+=T-R&32767}if(ne){N[A++]=268435456|_i[X]<<18|Wr[ne];var tt=_i[X]&31,Be=Wr[ne]&31;$+=js[tt]+Rs[Be],++O[257+tt],++I[Be],B=w+X,++j}else N[A++]=e[w],++O[e[w]]}}for(w=Math.max(w,B);w<l;++w)N[A++]=e[w],++O[e[w]];u=Gr(e,c,d,N,O,I,$,A,k,w-k,u),d||(i.r=u&7|c[u/8|0]<<3,u-=7,i.h=y,i.p=f,i.i=w,i.w=B)}else{for(var w=i.w||0;w<l+d;w+=65535){var Le=w+65535;Le>=l&&(c[u/8|0]=d,Le=l),u=Td(c,u+1,e.subarray(w,Le))}i.i=l}return So(r,0,o+Wa(u)+s)},_y=(function(){for(var e=new Int32Array(256),t=0;t<256;++t){for(var n=t,o=9;--o;)n=(n&1&&-306674912)^n>>>1;e[t]=n}return e})(),qy=function(){var e=-1;return{p:function(t){for(var n=e,o=0;o<t.length;++o)n=_y[n&255^t[o]]^n>>>8;e=n},d:function(){return~e}}},Wy=function(e,t,n,o,s){if(!s&&(s={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new Me(i.length+e.length);l.set(i),l.set(e,i.length),e=l,s.w=i.length}return Fy(e,t.level==null?6:t.level,t.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,o,s)},Ad=function(e,t){var n={};for(var o in e)n[o]=e[o];for(var o in t)n[o]=t[o];return n},wt=function(e,t){return e[t]|e[t+1]<<8},mt=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},Js=function(e,t){return mt(e,t)+mt(e,t+4)*4294967296},We=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function Od(e,t){return Wy(e,t||{},0,0)}function Md(e,t){return zy(e,{i:2},t&&t.out,t&&t.dictionary)}var Dd=function(e,t,n,o){for(var s in e){var i=e[s],l=t+s,r=o;Array.isArray(i)&&(r=Ad(o,i[1]),i=i[0]),ArrayBuffer.isView(i)?n[l]=[i,r]:(n[l+="/"]=[new Me(0),r],Dd(i,l,n,o))}},Ur=typeof TextEncoder<"u"&&new TextEncoder,Hi=typeof TextDecoder<"u"&&new TextDecoder,Hy=0;try{Hi.decode(kd,{stream:!0}),Hy=1}catch{}var Gy=function(e){for(var t="",n=0;;){var o=e[n++],s=(o>127)+(o>223)+(o>239);if(n+s>e.length)return{s:t,r:So(e,n-1)};s?s==3?(o=((o&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|o>>10,56320|o&1023)):s&1?t+=String.fromCharCode((o&31)<<6|e[n++]&63):t+=String.fromCharCode((o&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(o)}};function os(e,t){if(t){for(var n=new Me(e.length),o=0;o<e.length;++o)n[o]=e.charCodeAt(o);return n}if(Ur)return Ur.encode(e);for(var s=e.length,i=new Me(e.length+(e.length>>1)),l=0,r=function(u){i[l++]=u},o=0;o<s;++o){if(l+5>i.length){var c=new Me(l+8+(s-o<<1));c.set(i),i=c}var d=e.charCodeAt(o);d<128||t?r(d):d<2048?(r(192|d>>6),r(128|d&63)):d>55295&&d<57344?(d=65536+(d&1047552)|e.charCodeAt(++o)&1023,r(240|d>>18),r(128|d>>12&63),r(128|d>>6&63),r(128|d&63)):(r(224|d>>12),r(128|d>>6&63),r(128|d&63))}return So(i,0,l)}function $s(e,t){if(t){for(var n="",o=0;o<e.length;o+=16384)n+=String.fromCharCode.apply(null,e.subarray(o,o+16384));return n}else{if(Hi)return Hi.decode(e);var s=Gy(e),i=s.s,n=s.r;return n.length&&Ue(8),i}}var Uy=function(e,t){return t+30+wt(e,t+26)+wt(e,t+28)},Vy=function(e,t,n){var o=wt(e,t+28),s=wt(e,t+30),i=$s(e.subarray(t+46,t+46+o),!(wt(e,t+8)&2048)),l=t+46+o,r=Xy(e,l,s,n,mt(e,t+20),mt(e,t+24),mt(e,t+42)),c=r[0],d=r[1],u=r[2];return[wt(e,t+10),c,d,i,l+s+wt(e,t+32),u]},Xy=function(e,t,n,o,s,i,l){var r=s==4294967295,c=i==4294967295,d=l==4294967295,u=t+n,p=r+c+d;if(o&&p){for(;t+4<u;t+=4+wt(e,t+2))if(wt(e,t)==1)return[r?Js(e,t+4+8*c):s,c?Js(e,t+4):i,d?Js(e,t+4+8*(c+r)):l,1];o<2&&Ue(13)}return[s,i,l,0]},Gi=function(e){var t=0;if(e)for(var n in e){var o=e[n].length;o>65535&&Ue(9),t+=o+4}return t},Vr=function(e,t,n,o,s,i,l,r){var c=o.length,d=n.extra,u=r&&r.length,p=Gi(d);We(e,t,l!=null?33639248:67324752),t+=4,l!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(i<0&&8),e[t++]=s&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var m=new Date(n.mtime==null?Date.now():n.mtime),g=m.getFullYear()-1980;if((g<0||g>119)&&Ue(10),We(e,t,g<<25|m.getMonth()+1<<21|m.getDate()<<16|m.getHours()<<11|m.getMinutes()<<5|m.getSeconds()>>1),t+=4,i!=-1&&(We(e,t,n.crc),We(e,t+4,i<0?-i-2:i),We(e,t+8,n.size)),We(e,t+12,c),We(e,t+14,p),t+=16,l!=null&&(We(e,t,u),We(e,t+6,n.attrs),We(e,t+10,l),t+=14),e.set(o,t),t+=c,p)for(var b in d){var f=d[b],y=f.length;We(e,t,+b),We(e,t+2,y),e.set(f,t+4),t+=4+y}return u&&(e.set(r,t),t+=u),t},Ky=function(e,t,n,o,s){We(e,t,101010256),We(e,t+8,n),We(e,t+10,n),We(e,t+12,o),We(e,t+16,s)};function mI(e,t){t||(t={});var n={},o=[];Dd(e,"",n,t);var s=0,i=0;for(var l in n){var r=n[l],c=r[0],d=r[1],u=d.level==0?0:8,p=os(l),m=p.length,g=d.comment,b=g&&os(g),f=b&&b.length,y=Gi(d.extra);m>65535&&Ue(11);var x=u?Od(c,d):c,S=x.length,C=qy();C.p(c),o.push(Ad(d,{size:c.length,crc:C.d(),c:x,f:p,m:b,u:m!=l.length||b&&g.length!=f,o:s,compression:u})),s+=30+m+y+S,i+=76+2*(m+y)+(f||0)+S}for(var N=new Me(i+22),O=s,I=i-s,j=0;j<o.length;++j){var p=o[j];Vr(N,p.o,p,p.f,p.u,p.c.length);var $=30+p.f.length+Gi(p.extra);N.set(p.c,p.o+$),Vr(N,s,p,p.f,p.u,p.c.length,p.o,p.m),s+=16+$+(p.m?p.m.length:0)}return Ky(N,s,o.length,I,O),N}function Yy(e,t){for(var n={},o=e.length-22;mt(e,o)!=101010256;--o)(!o||e.length-o>65558)&&Ue(13);var s=wt(e,o+8);if(!s)return{};var i=mt(e,o+16),l=mt(e,o-20)==117853008;if(l){var r=mt(e,o-12);l=mt(e,r)==101075792,l&&(s=mt(e,r+32),i=mt(e,r+48))}for(var c=0;c<s;++c){var d=Vy(e,i,l),u=d[0],p=d[1],m=d[2],g=d[3],b=d[4],f=d[5],y=Uy(e,f);i=b,u?u==8?n[g]=Md(e.subarray(y,y+p),{out:new Me(m)}):Ue(14,"unknown compression type "+u):n[g]=So(e,y,y+p)}return n}const Ns=4,Ed=30,Bd=`cbs:draft:v${Ns}:`,Jy=["cbs:ribbon:","cbs:draft:"],Rn={commands:"baselineCommands",enableRules:"baselineEnableRules",displayRules:"baselineDisplayRules",locLabels:"baselineLocLabels"},Ha=["HomepageGrid","SubGrid","Form","Application"];function Ld(e){return{orgUrl:e.orgUrl.trim().replace(/\/+$/,"").toLowerCase(),solutionId:e.solutionId.trim().toLowerCase(),entityLogicalName:e.entityLogicalName.trim().toLowerCase()}}function An(e){const t=Ld(e);return`${Bd}${encodeURIComponent(t.orgUrl)}:${encodeURIComponent(t.solutionId)}:${encodeURIComponent(t.entityLogicalName)}`}function ss(e,t){return!e||!t?!1:An(e)===An(t)}function Zy(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return`${(t>>>0).toString(16)}.${e.length}`}let No=null;function zd(e){const t=[e.baseline,e.baselineCommands,e.baselineEnableRules,e.baselineDisplayRules,e.baselineLocLabels,e.layers,e.baseLanguageCode];if(No&&No.of.every((o,s)=>o===t[s]))return No.value;const n=Zy(JSON.stringify(t));return No={of:t,value:n},n}const Xr=new WeakMap;function To(e){let t=Xr.get(e);return t===void 0&&(t=JSON.stringify(e),Xr.set(e,t)),t}const xn=e=>JSON.parse(JSON.stringify(e)),vo={},Pd={list:"groups",child:{list:"buttons",child:vo}};function Fd(e){const t=new Map;for(const n of e)t.set(n.id,t.has(n.id)?null:n);return t}function Zs(e,t,n){if(!n.list||!Array.isArray(e[n.list]))return e;const o=t?.[n.list]??[];return{...e,[n.list]:Ui(e[n.list],o,n.child??vo)}}function ko(e,t,n){if(!n.list||e[n.list]===void 0)return e;const o=t?.[n.list]??[];return{...e,[n.list]:Vi(e[n.list],o,n.child??vo)}}function Ui(e,t,n){const o=Fd(t),s=new Set(e.map(i=>i.id));if(s.size===e.length&&o.size===t.length){const i=t.filter(r=>s.has(r.id)),l=e.slice(i.length);if(i.every((r,c)=>e[c].id===r.id)&&l.every(r=>!o.has(r.id)))return{set:e.slice(0,i.length).filter(r=>To(o.get(r.id))!==To(r)).map(r=>Zs(r,o.get(r.id),n)),drop:t.filter(r=>!s.has(r.id)).map(r=>r.id),add:l.map(r=>Zs(r,void 0,n))}}return e.map(i=>{const l=o.get(i.id)??void 0;return l&&To(l)===To(i)?i.id:Zs(i,l,n)})}function Vi(e,t,n){const o=Fd(t);if(Array.isArray(e)){const c=[];for(const d of e)if(typeof d!="string")c.push(ko(d,o.get(d.id)??void 0,n));else{const u=o.get(d);u&&c.push(xn(u))}return c}const s=new Set(e.drop),i=new Map(e.set.map(c=>[c.id,c])),l=[];for(const c of e.add)o.has(c.id)?i.set(c.id,c):l.push(c);const r=new Set(t.map(c=>c.id));return[...t.filter(c=>!s.has(c.id)).map(c=>i.has(c.id)?ko(i.get(c.id),c,n):xn(c)),...[...i.values()].filter(c=>!r.has(c.id)).map(c=>ko(c,void 0,n)),...l.map(c=>ko(c,void 0,n))]}const Qy=e=>!Array.isArray(e)&&e.set.length+e.drop.length+e.add.length===0,is=e=>e;function ex(e){const t=vt(e),n={};for(const i of Ha){const l=t.ribbons[i],r=e.baseline[i];if(!l)continue;const c=Ui(l.tabs,r?.tabs??[],Pd),d={};for(const[p,m]of Object.entries(l))p!=="tabs"&&JSON.stringify(m)!==JSON.stringify(r?.[p])&&(d[p]=m);const u=Object.keys(r??{}).filter(p=>p!=="tabs"&&!(p in l));(!Qy(c)||Object.keys(d).length+u.length>0)&&(n[i]={props:d,unset:u,tabs:c})}const o={};for(const i of Object.keys(Rn))o[i]=Ui(is(t[i]),is(e[Rn[i]]),vo);const s={...t};delete s.ribbons;for(const i of Object.keys(Rn))delete s[i];return{ribbons:n,lists:o,other:s}}function tx(e,t){const{delta:n}=e,o={};for(const i of Ha){const l=n.ribbons[i],r=t.baseline[i];if(!l){o[i]=xn(r);continue}const c={...xn(r),...xn(l.props)};for(const d of l.unset)delete c[d];c.tabs=Vi(l.tabs,is(r?.tabs??[]),Pd),o[i]=c}const s={...vt(t),...xn(n.other),ribbons:o};for(const i of Object.keys(Rn))s[i]=Vi(n.lists[i],is(t[Rn[i]]),vo);return s}function nx(e){return btoa($s(Od(os(JSON.stringify(e)),{level:9}),!0))}function ox(e){return JSON.parse($s(Md(os(atob(e),!0))))}const Gt=e=>Array.isArray(e),Qs=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Kr=e=>{if(Gt(e))return!0;const t=e;return!!t&&typeof t=="object"&&Gt(t.set)&&Gt(t.drop)&&Gt(t.add)},sx=e=>!!e&&typeof e=="object"&&Gt(e.entity)&&Gt(e.application);function ix(e){if(!e||typeof e!="object")return!1;const t=e,n=t.ribbons,o=t.other??{};return!!n&&typeof n=="object"&&Object.entries(n).every(([s,i])=>Ha.includes(s)&&Kr(i?.tabs)&&Qs(i?.props)&&Gt(i?.unset))&&Qs(t.lists)&&Object.keys(Rn).every(s=>Kr(t.lists[s]))&&Qs(t.other)&&["pendingUnhides","uncustomisedCommandIds"].every(s=>!(s in o)||sx(o[s]))&&(!("customisedCommandIds"in o)||Gt(o.customisedCommandIds))}function ax(e,t){try{const n={format:Ns,key:Ld(e),savedAt:new Date().toISOString(),baselineFingerprint:zd(t),data:nx(ex(t))};return localStorage.setItem(An(e),JSON.stringify(n)),n.savedAt}catch{return null}}function rx(e){const t=An(e);let n;try{n=localStorage.getItem(t)}catch{return null}if(!n)return null;try{const o=JSON.parse(n);if(o.format===Ns&&ss(o.key,e)&&typeof o.data=="string"){const s=ox(o.data);if(ix(s)){const i=o;return{format:i.format,key:i.key,savedAt:i.savedAt,baselineFingerprint:i.baselineFingerprint,delta:s}}}}catch{}return as(e),null}function lx(e){try{const t=localStorage.getItem(An(e));if(!t)return!1;const n=JSON.parse(t);return n.format===Ns&&ss(n.key,e)&&typeof n.data=="string"}catch{return!1}}function as(e){try{localStorage.removeItem(An(e))}catch{}}function cx(e,t){try{const n=Date.parse(JSON.parse(e??"").savedAt??"");return!(t-n<=Ed*864e5)}catch{return!0}}function dx(e=Date.now()){const t=[];try{for(let n=0;n<localStorage.length;n++){const o=localStorage.key(n);o&&(o.startsWith(Bd)?cx(localStorage.getItem(o),e):Jy.some(s=>o.startsWith(s)))&&t.push(o)}for(const n of t)localStorage.removeItem(n)}catch{return 0}return t.length}function _d(e){return e.mutationsSincePublish>0||so(e)}function _o(){return je.getState().target!==null&&_d(M.getState())}let rn=null;function en(e){const{target:t,pending:n}=je.getState();if(!t||n)return!0;const o=e.ribbons.HomepageGrid.entityLogicalName;if(o&&o.toLowerCase()!==t.entityLogicalName.toLowerCase())return!0;let s=!0;if(!_d(e))rn!==null&&e.future.some(r=>r.op==="restored"&&r.ts===rn)||(as(t),je.setState({lastSavedAt:null}));else{const l=ax(t,e);s=l!==null,l&&je.setState({lastSavedAt:l})}const{saveFailed:i}=je.getState();return!s&&!i&&ce.getState().logWarn("ribbon","Unsaved changes could not be saved as a draft (browser storage is full or unavailable): publish them, or they are lost when Command Bar Studio closes."),s===i&&je.setState({saveFailed:!s}),s}const ux=["mutationsSincePublish","ribbons","commands","enableRules","displayRules","locLabels","pendingUnhides","customisedCommandIds","uncustomisedCommandIds","baseline","baselineCommands","baselineEnableRules","baselineDisplayRules","baselineLocLabels","layers"];function mx(){return M.subscribe((e,t)=>{e.baseline!==t.baseline&&(rn=null),!ux.every(n=>e[n]===t[n])&&en(e)})}function qd(e){const t=ae.getState();return{orgUrl:t.connectionUrl,solutionId:t.activeSolution?.id??"",entityLogicalName:e}}function px(){const e=M.getState();e.loadWorkspace({ribbons:e.baseline,commands:e.baselineCommands,enableRules:e.baselineEnableRules,displayRules:e.baselineDisplayRules,locLabels:e.baselineLocLabels,templates:e.templates,conflicts:e.conflicts,layers:e.layers,baseLanguageCode:e.baseLanguageCode})}function ei(e){je.setState({target:null,pending:null,pendingBaselineChanged:!1});const t=ae.getState();e.kind==="entity"?t.setActiveEntity(e.entity):t.setActiveSolution(e.solution)}const je=Xt()((e,t)=>({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null,beginLoad(){rn=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,saveFailed:!1,lastSavedAt:null})},workspaceLoaded(n){const o=rx(n);rn=null,e({target:n,pending:o,restoreError:null,lastSavedAt:o?.savedAt??null,pendingBaselineChanged:!!o&&o.baselineFingerprint!==zd(M.getState())})},restoreDraft(){const{target:n,pending:o}=t();if(!n||!o||!ss(n,o.key))return!1;const s=M.getState();try{s.restoreWorkspace(tx(o,s),`saved ${new Date(o.savedAt).toLocaleString()}`)}catch(r){const c=r instanceof Error?r.message:String(r);return ce.getState().logError("ribbon",`The unsaved changes saved ${o.savedAt} couldn't be restored: ${c}`),e({restoreError:c}),!1}const i=M.getState(),l=i.past[i.past.length-1];return i.past.length>s.past.length&&l?.op==="restored"&&(rn=l.ts),e({pending:null,pendingBaselineChanged:!1,restoreError:null}),en(i),!0},discardDraft(){const{target:n,pending:o}=t();o&&(as(o.key),e({pending:null,pendingBaselineChanged:!1,restoreError:null,lastSavedAt:null}),n&&ss(n,o.key)&&en(M.getState()))},requestEntitySwitch(n){ae.getState().activeEntity?.logicalName!==n.logicalName&&(_o()?(en(M.getState()),e({pendingSwitch:{kind:"entity",entity:n}})):ei({kind:"entity",entity:n}))},requestSolutionSwitch(n){ae.getState().activeSolution?.id!==n.id&&(_o()?(en(M.getState()),e({pendingSwitch:{kind:"solution",solution:n}})):ei({kind:"solution",solution:n}))},resolveSwitch(n){const{pendingSwitch:o,target:s,pending:i}=t();if(o){if(n==="cancel"){e({pendingSwitch:null});return}n==="keep"&&!en(M.getState())||(n==="discard"&&s&&!i&&as(s),e({pendingSwitch:null,target:null,pending:null,pendingBaselineChanged:!1,saveFailed:!1}),px(),ei(o))}},releaseForConnectionChange(){const n=_o(),o=n?en(M.getState()):!1;return rn=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null}),{hadChanges:n,kept:o}}})),Wd=e=>e?.trim().toLowerCase()==="production",pI=e=>Wd(e),fI=(e,t)=>t.trim()!==""&&e.trim().toLowerCase()===t.trim().toLowerCase(),fx=me({root:{display:"inline-flex",alignItems:"center",gap:h.spacingHorizontalXS,minWidth:0,borderRadius:h.borderRadiusMedium,":focus-visible":{outline:`2px solid ${h.colorStrokeFocus2}`,outlineOffset:"2px"}},prefix:{color:h.colorNeutralForeground3},name:{maxWidth:"180px"},nameBelow1200:{display:"inline-flex",minWidth:0,"@media (max-width: 1200px)":{display:"none"}}});function hx({prefix:e,compactBelow:t}){const n=fx(),o=ae(r=>r.connectionName),s=ae(r=>r.connectionUrl),i=ae(r=>r.environment);if(!o&&!s)return null;const l=Wd(i);return a.jsx(pe,{content:s||o,relationship:"description",children:a.jsxs("span",{"data-testid":"environment-badge",className:n.root,tabIndex:0,children:[e&&a.jsx(V,{size:200,wrap:!1,className:n.prefix,children:e}),a.jsx("span",{className:t?n.nameBelow1200:void 0,children:a.jsx(V,{size:200,weight:"semibold",truncate:!0,wrap:!1,className:n.name,children:o||s})}),i&&a.jsx(xe,{size:"medium",appearance:l?"filled":"tint",color:l?"warning":"informative",children:i})]})})}const Xi=Xt()(e=>({managed:{},setManaged:t=>e({managed:Object.fromEntries(t.map(n=>[n.id,n]))})})),gx=new Set(["label","labeltext","tabname","tabheading","title","tooltip","tooltiptitle","tooltipdescription","alt","button","tab","group","flyout","menu","name","text","caption"]),bx=/^([A-Za-z_$][\w$]*(\.[\w$!{}-]+){2,}|[A-Z][\w$]*\.[\w$!{}-]+)$/,yx=/^(Mscrm|Ribbon)(_[A-Za-z0-9]+){2,}$/,xx=/^[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)+$/;function Sx(e,t=!1){const n=bx.test(e)?".":yx.test(e)||t&&xx.test(e)?"_":void 0;if(!n)return;const s=e.split(n).filter(i=>i&&!gx.has(i.toLowerCase())).at(-1);if(!(!s||/^(Mscrm|Ribbon|\{!EntityLogicalName\})$/i.test(s)))return s.replace(/_/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").trim()}function vx(e,t){return e.titles.find(n=>n.languageCode===t)?.description??e.titles.find(n=>n.languageCode===1033)?.description??e.titles[0]?.description}const Yr=/^\$(Resources(\([^)]*\))?|LocLabels):/,wx=[[/\{!EntityPluralDisplayName\}/g,"‹table name, plural›"],[/\{!EntityDisplayName\}/g,"‹table name›"]];function Cx(e){return wx.reduce((t,[n,o])=>t.replace(n,o),e)}function Ix(e,t,n,o,s){const i=jx(e,t,n,o,s);return i&&Cx(i)}function jx(e,t,n,o,s){const i=He(e,t,n);if(!i)return i;const r=s!==void 0&&He(s,t,n)===(e??"")?s:e??"";if(!Yr.test(r))return i;const c=o[i];if(c)return vx(c,n)??i;const d=i===r.replace(Yr,"");return Sx(i,d)??i}function Ee(){const e=Xi(n=>n.managed),t=M(n=>n.baseLanguageCode);return E.useCallback((n,o,s,i)=>Ix(n,o,s??t??1033,e,i),[e,t])}const Hd="Unified Interface has no visible tabs: this tab's buttons appear in the table's command bar (or its overflow menu) wherever the tab's display rule applies.",Vn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Rx=e=>[e.icon,e.image16,e.image32].some(t=>!!t&&t.startsWith("$webresource:")),$x=e=>!!e.source&&Oa(e)===e.source.modernImage&&(e.source.modernImage!==void 0||!e.icon),Nx=/^\$LocLabels:(.+)$/,zt=e=>e?Nx.exec(e)?.[1]??null:null,Tx=/^\s*<(EnableRule|DisplayRule)\b[^>]*?\sId="([^"]+)"/,Xn=e=>new Set(e??[]);function kx(e){const t=[];for(const n of Object.values(e.source?.attributes??{})){const o=zt(n);o&&t.push(o)}for(const n of e.source?.xml?.matchAll(/\$LocLabels:([^"'\s<]+)/g)??[])t.includes(n[1])||t.push(n[1]);return t}function Jr(e){return(e.menu?.sections??[]).map(t=>({id:t.id,title:t.title??"",sequence:t.sequence,displayMode:t.displayMode??"",controlsId:t.controlsId}))}function Ax(e){const t=[],n=[],o=[],s=[],i=[],l=[],r=[],c=[],d=[],u=[],p=new Map,m=(F,L)=>{const G=zt(F);G&&p.set(G,new Set([...p.get(G)??[],L]))};for(const{baseline:F}of e.locations)for(const L of F.tabs){m(L.label,L.id);for(const G of L.groups){m(G.label,G.id);for(const U of Ne(G))for(const te of Object.values(U.source?.attributes??{}))m(te,U.id)}}const g=new Set([...(e.locLabels??[]).map(F=>F.id),...Xn(e.layer?.locLabelIds)]);let b=!1;const f=new Set,y=Xn(e.layer?.containerIds),x=Xn(e.layer?.locLabelIds),S=new Set,C=new Set,N=new Map,O=new Map,I=[],j=new Set(e.locations.flatMap(({current:F})=>Array.from(Ct(F).values(),L=>L.button.id))),$=(F,L,G,U)=>{const te=zt(G);if(y.has(L)&&te&&x.has(te)&&!zt(U)&&U.trim())if([...p.get(te)??[]].some(P=>P!==L)){let P=`${L}.Title`;for(let Q=2;P===te||g.has(P);Q++)P=`${L}.Title${Q}`;g.add(P),u.push({id:P,text:U,containerId:L,newLabel:!0})}else u.push({id:te,text:U,containerId:L});else t.push(`Renaming ${F} ${L} — only tabs and groups your unmanaged customizations add (with a translatable title) can be renamed`)};for(const{current:F,baseline:L}of e.locations){const G=Db(F,L);G.newButtons+G.overriddenButtons+G.hiddenButtons+G.newTabs+G.newGroups>0&&(b=!0),G.scalingChanges>0&&t.push(`Scaling changes on ${F.location} (not supported yet)`);const U=nd(F,L);t.push(...U.problems);const te=Xn(e.layer?.scalingStepIds);for(const[H,W]of Object.entries(L.scalingByTab??{})){const oe=F.tabs.find(ue=>ue.id===H),se=[...W.maxSizes.filter(ue=>te.has(ue.id)).map(ue=>({...ue,kind:"MaxSize"})),...W.scales.filter(ue=>te.has(ue.id)).map(ue=>({...ue,kind:"Scale"})),...(oe?.groups??[]).map(ue=>U.steps.get(ue.id)).filter(ue=>!!ue).map(ue=>({...ue,kind:"MaxSize"}))];if(se.length===0)continue;const $e=zc(H,{maxSizes:W.maxSizes.filter(ue=>!te.has(ue.id)).map(ue=>ue.sequence),scales:W.scales.filter(ue=>!te.has(ue.id)).map(ue=>ue.sequence)},se);n.push(...$e.changes.map(lb)),t.push(...$e.problems)}const P=Ct(F),Q=Ct(L);for(const{button:H}of P.values())for(const W of Ec(H))f.add(W);for(const[H,{button:W,menu:oe}]of P){const se=kx(W);se.forEach(Pe=>S.add(Pe));const $e=Q.get(H)?.button,ue=!$e||ki($e,W);ue&&oe&&!Na.includes(W.kind??"button")&&t.push(`Menu item "${W.label}" (${W.id}) is a ${vn[W.kind]??W.kind} — a menu can hold buttons and flyouts only; change its Kind`);for(const Pe of[gs(W.id),bs(W.id),ys(W.id)])ue?C.add(Pe):se.includes(Pe)||N.set(Pe,W);ue&&se.forEach(Pe=>C.add(Pe))}for(const[H,W]of Q){const oe=W.button.id,se=P.get(H);if(!se){if(W.menu&&j.has(oe)&&j.has(W.menu.parentId)&&W.button.origin!=="unmanaged"){t.push(`Moving the menu of ${W.menu.parentId} to another location — its item "${W.button.label}" (${oe}) comes from another solution and can't be moved with it; move the flyout back`);continue}if(dt(W.button.kind)&&j.has(oe)&&/<Menu[\s>/]/.test(W.button.source?.xml??"")){t.push(`Moving the <${vn[W.button.kind]}> "${W.button.label}" (${oe}) to another location — its menu may hold items of other solutions; move it within its location instead`);continue}an(W.button)?o.push(oe):t.push(`Removing "${W.button.label}" (${oe}) — only your own unmanaged buttons can be deleted; hide it instead`);continue}W.button.hidden&&!se.button.hidden&&s.push(oe),(se.button.kind??"button")!==(W.button.kind??"button")&&t.push(`Changing the kind of "${se.button.label}" (${oe}) — not supported yet`);const $e=ki(W.button,se.button);$e&&dt(se.button.kind)&&t.push(`Editing the <${vn[se.button.kind]}> "${se.button.label}" (${oe}) — CBS shows it read-only; it can be hidden, or moved and deleted when it's your own`),$e&&(wn(se.button.kind)||se.button.menu)&&W.button.origin!=="unmanaged"&&t.push(`Editing the flyout / split button "${se.button.label}" (${oe}) itself — only your own can be edited; its menu items can be edited, hidden or added to`),Vn(Jr(W.button),Jr(se.button))||t.push(`Adding, removing or changing menu sections of "${se.button.label}" (${oe}) — not supported yet for an existing menu; add, edit or remove its items instead`),(se.button.icon??"")!==(W.button.icon??"")&&!Rx(se.button)&&!$x(se.button)&&t.push(`Changing the icon of "${se.button.label}" (${oe}) to a built-in icon — not supported yet; choose an SVG web resource`),((se.menu||W.menu?se.menu?.controlsId!==W.menu?.controlsId:se.groupId!==W.groupId)||se.button.sequence!==W.button.sequence)&&(W.button.origin==="unmanaged"?l.push({id:oe,groupId:se.groupId,sequence:se.button.sequence,...se.menu?{controlsId:se.menu.controlsId}:{}}):t.push(`Moving or re-ordering "${se.button.label}" (${oe}) — only your own unmanaged buttons, and copies made with "Customise button", can be moved; undo the move, then hide it and add a new button instead`))}for(const[H,W]of P){if(Q.has(H))continue;O.has(W.button.id)||O.set(W.button.id,{groupId:W.groupId,sequence:W.button.sequence,...W.menu?{controlsId:W.menu.controlsId}:{}});const oe=Kc(W.button.source?.attributes.PopulateDynamically);wn(W.button.kind)&&!oe&&!cn(W.button).some(se=>!se.hidden)&&I.push({id:W.button.id,label:W.button.label})}const be=new Map(L.tabs.flatMap(H=>H.groups.map(W=>[W.id,W]))),Ae=new Map(L.tabs.map(H=>[H.id,H])),tt=L.tabs.map(H=>H.id).filter(H=>F.tabs.some(W=>W.id===H)),Be=F.tabs.map(H=>H.id).filter(H=>Ae.has(H)),Le=H=>!y.has(H),Y=tt.filter(Le),Qe=Be.filter(Le).find((H,W)=>H!==Y[W]);if(Qe){const H=F.tabs.find(W=>W.id===Qe);t.push(e.layer?`Reordering tab "${H.label}" (${H.id}) — only tabs your customizations add can be reordered; drag it back`:`Reordering tab "${H.label}" (${H.id}) — your unmanaged customizations couldn't be read, so it isn't known whether the tab is yours; use Retry, or drag it back`)}for(const H of F.tabs){const W=Ae.get(H.id);W&&y.has(H.id)&&W.sequence!==H.sequence&&c.push({id:H.id,sequence:H.sequence})}for(const H of F.tabs){const W=Ae.get(H.id);if(W)for(const oe of H.groups){const se=W.groups.find($e=>$e.id===oe.id);se&&y.has(oe.id)&&se.sequence!==oe.sequence&&d.push({id:oe.id,sequence:oe.sequence})}}const zn=new Set(F.tabs.map(H=>H.id)),Yt=new Set(F.tabs.flatMap(H=>H.groups.map(W=>W.id)));for(const H of F.tabs){const W=zt(H.label);W&&S.add(W);const oe=Ae.get(H.id);if(!oe){C.add(`${H.id}.Title`);const se=zt(H.source?.titleToken);se&&C.add(se),H.commandId&&f.add(H.commandId),F.location==="Application"&&(H.tabDisplayRules??[]).length===0&&t.push(`New tab ${H.id} has no tab display rule, so it would never be shown — add one in Tab rules`),n.push(`New tab "${H.label}" (${H.id}): ${Hd}`)}oe&&oe.label!==H.label&&$("tab",H.id,oe.label,H.label),oe&&!Vn(oe.tabDisplayRules??[],H.tabDisplayRules??[])&&(y.has(H.id)?H.commandId?r.push(H.id):t.push(`Changing the display rules of tab ${H.id} — the tab has no Command to attach them to`):t.push(`Changing the display rules of tab ${H.id} — only tabs your unmanaged customizations add can be changed`));for(const se of H.groups){const $e=zt(se.label);$e&&S.add($e);const ue=be.get(se.id);if(!ue){C.add(`${se.id}.Title`);const Pe=se.source?.attributes.Command;Pe&&f.add(Pe);const Jt=zt(se.source?.titleToken);Jt&&C.add(Jt)}ue&&ue.template!==se.template&&t.push(`Re-templating group ${se.id} — not supported yet`),ue&&ue.label!==se.label&&$("group",se.id,ue.label,se.label)}}const z=(H,W)=>t.push(`Removing ${H} ${W} — only tabs and groups your unmanaged customizations add can be deleted; hide it instead`);for(const H of L.tabs){if(!zn.has(H.id)){y.has(H.id)?i.push(H.id):z("tab",H.id);continue}for(const W of H.groups)Yt.has(W.id)||(y.has(W.id)?i.push(W.id):z("group",W.id))}}for(let F=o.length-1;F>=0;F--){const L=O.get(o[F]);L&&(l.push({id:o[F],...L}),o.splice(F,1))}for(const F of e.deletedOrphans??[]){for(const L of F.deleteControlIds)o.includes(L)||o.push(L);for(const L of F.deleteContainerIds)i.includes(L)||i.push(L)}for(const F of I)l.some(L=>L.id===F.id)||t.push(`New flyout / split button "${F.label}" has no menu items — add at least one item to its menu`);const w=e.layer?.commandIds?Xn(e.layer.commandIds):null,A=new Set(e.uncustomisedCommandIds??[]),B=[...A].filter(F=>w?w.has(F):f.has(F)&&!e.excludeCommandIds?.has(F));for(const F of B)e.layer?.commandRefIds&&!Ra(F,e.layer.commandRefIds)&&t.push(`Uncustomising ${F} — it is your own command (your customizations' buttons use it and no other solution defines it); undo the uncustomise`);B.includes(Ve)&&f.has(Ve)&&t.push(`Uncustomising ${Ve} — its "Open record" buttons still use it; undo the uncustomise and turn the record open override off in the Advanced section instead`);for(const F of e.excludeCommandIds??[])f.delete(F);const k=new Set(e.customisedCommandIds??[]),v=new Map(e.baselineCommands.map(F=>[F.id,F])),T=e.commands.filter(F=>f.has(F.id)&&!A.has(F.id)&&(!v.has(F.id)||!Vn(v.get(F.id),F)||k.has(F.id)&&!w?.has(F.id))).map(F=>F.id);for(const F of e.commands){if(!T.includes(F.id))continue;F.actions.some(G=>G.kind==="powerFx"||G.kind==="customApi")&&t.push(`Power Fx / Custom API action in command ${F.id} — classic ribbon commands can't run these; remove the action (#28)`);const L=F.id===Ve?jy(F):null;L&&t.push(L)}const R=new Set,D=new Set;for(const F of e.commands)if(!(!f.has(F.id)||A.has(F.id))){F.enableRules.forEach(L=>R.add(L)),F.displayRules.forEach(L=>D.add(L));for(const L of F.rawRuleRefs??[]){const G=Tx.exec(L.xml);G&&(G[1]==="EnableRule"?R:D).add(G[2])}}const q=(F,L,G)=>{const U=new Map(L.map(te=>[te.id,te]));return F.filter(te=>G.has(te.id)&&(!U.has(te.id)||!Vn(U.get(te.id),te))).map(te=>te.id)},X=q(e.enableRules,e.baselineEnableRules,R),ne=q(e.displayRules,e.baselineDisplayRules,D),re=[];if(e.locLabels&&e.baselineLocLabels){const F=new Map(e.baselineLocLabels.map(L=>[L.id,L]));for(const L of e.locLabels){const G=F.get(L.id);if(G&&Vn(G,L)||C.has(L.id))continue;if(S.has(L.id)){x.has(L.id)?re.push(L.id):t.push(`Translations of label ${L.id} — it is defined by another solution; change the text in the properties pane instead`);continue}const U=N.get(L.id);U&&t.push(`Translations for "${U.label}" (${U.id}) — its text isn't a translatable label yet; change the text in the properties pane first, then add translations`)}}const le=(e.unhiddenLayerHideIds??[]).filter(F=>!s.includes(F));return{hasChanges:b||T.length>0||B.length>0||X.length>0||ne.length>0||o.length>0||s.length>0||le.length>0||i.length>0||l.length>0||re.length>0||r.length>0||c.length>0||d.length>0||u.length>0,editedCommandIds:T,uncustomisedCommandIds:B,editedEnableRuleIds:X,editedDisplayRuleIds:ne,deletedButtonIds:o,unhiddenButtonIds:[...s,...le],deletedContainerIds:i,movedButtons:l,editedLocLabelIds:re,editedTabIds:r,resequencedTabs:c,resequencedGroups:d,renamedLabels:u,unsupported:[...new Set(t)],warnings:[...new Set(n)]}}const Zr=["HomepageGrid","Form","SubGrid","Application"];function Ox(e){return e.length<=1?e[0]??"":`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`}function Mx(e){if(e.includes("Application"))return"the application ribbon";const t=[...e].sort((n,o)=>Zr.indexOf(n)-Zr.indexOf(o));return`the ${Ox(t.map(n=>Ut[n].label.toLowerCase()))}`}function Dx(e){const{plan:t,buttonName:n,titleOf:o}=e,s=new Map,i=(y,x,S,C={})=>{const N=`${y}|${x}|${S}|${C.detail??""}`,O=s.get(N)??{change:{kind:y,action:x,name:S,...C.detail?{detail:C.detail}:{}},locations:[],preposition:C.preposition};C.location&&!O.locations.includes(C.location)&&O.locations.push(C.location),s.set(N,O)},l=new Map,r=new Map,c=new Map,d=new Map;for(const{current:y,baseline:x}of e.locations){for(const{button:S}of Ct(y).values())l.has(S.id)||l.set(S.id,{button:S,location:y.location});for(const{button:S}of Ct(x).values())r.has(S.id)||r.set(S.id,{button:S,location:x.location});for(const S of x.tabs){c.set(S.id,{kind:"tab",label:S.label,location:x.location});for(const C of S.groups)c.set(C.id,{kind:"group",label:C.label,location:x.location})}for(const S of y.tabs)d.set(S.id,{label:S.label,location:y.location})}const u=new Set(t.movedButtons.map(y=>y.id)),p=new Set,m=new Set;for(const{current:y,baseline:x}of e.locations){const S=y.location,C=new Map(x.tabs.map(I=>[I.id,I]));for(const I of y.tabs){const j=C.get(I.id);if(!j){i("new","Add tab",o(I.label),{location:S,preposition:"to"});continue}const $=new Set(j.groups.map(w=>w.id));for(const w of I.groups)$.has(w.id)||i("new","Add group",o(w.label),{detail:`to tab “${o(I.label)}”`})}const N=Ta(y,x),O=new Set(N.map(I=>I.entry.button.id));for(const{entry:I,change:j}of N){const{button:$}=I;if(u.has($.id))continue;const w=n($);j==="new"?(i("new","Add",w,{location:S,preposition:"to"}),$.commandId&&p.add($.commandId)):j==="hide"?i("hide","Hide",w,{location:S,preposition:"on"}):i("change","Change",w,{location:S,preposition:"on"})}for(const{button:I}of Ct(y).values())I.commandId&&!O.has(I.id)&&m.add(I.commandId)}for(const y of t.unhiddenButtonIds){const x=l.get(y)??r.get(y);i("show","Show",x?n(x.button):y,{location:x?.location,preposition:"again on"})}for(const y of t.movedButtons){const x=l.get(y.id),S=r.get(y.id),C=x&&S&&x.location!==S.location;i("move","Move",x?n(x.button):y.id,{location:C?x.location:void 0,preposition:"to"})}for(const y of t.deletedButtonIds){const x=r.get(y);i("delete","Delete",x?n(x.button):y,{location:x?.location,preposition:"from"})}for(const y of t.deletedContainerIds){const x=c.get(y);i("delete",x?.kind==="group"?"Delete group":"Delete tab",x?o(x.label):y,{location:x?.location,preposition:"from"})}for(const y of t.renamedLabels){const x=c.get(y.containerId);i("change",x?.kind==="group"?"Rename group":"Rename tab",x?o(x.label):y.containerId,{detail:`to “${y.text}”`})}for(const y of t.resequencedTabs){const x=d.get(y.id);i("move","Move tab",x?o(x.label):y.id,{location:x?.location,preposition:"on"})}for(const y of t.resequencedGroups??[]){const x=c.get(y.id);i("move","Move group",x?o(x.label):y.id,{location:x?.location,preposition:"on"})}for(const y of t.editedTabIds){const x=d.get(y);i("change","Change the display rules of tab",x?o(x.label):y)}const g=new Set(e.baselineCommands.map(y=>y.id));for(const y of t.editedCommandIds)g.has(y)?i("change","Change command",y):(!p.has(y)||m.has(y))&&i("new","Add command",y);for(const y of t.uncustomisedCommandIds)i("change","Remove your copy of command",y,{detail:"(the original applies again)"});const b=new Set(e.baselineEnableRuleIds),f=new Set(e.baselineDisplayRuleIds);for(const y of t.editedEnableRuleIds)b.has(y)?i("change","Change enable rule",y):i("new","Add enable rule",y);for(const y of t.editedDisplayRuleIds)f.has(y)?i("change","Change display rule",y):i("new","Add display rule",y);for(const y of t.editedLocLabelIds)i("change","Change the translations of",y);return[...s.values()].map(({change:y,locations:x,preposition:S})=>x.length>0&&S?{...y,detail:`${S} ${Mx(x)}`}:y)}const ti=["HomepageGrid","SubGrid","Form"];function Ex(){const e=M(w=>w.ribbons),t=M(w=>w.baseline),n=M(w=>w.commands),o=M(w=>w.displayRules),s=M(w=>w.enableRules),i=M(w=>w.baselineCommands),l=M(w=>w.baselineEnableRules),r=M(w=>w.baselineDisplayRules),c=M(w=>w.locLabels),d=M(w=>w.baselineLocLabels),u=M(w=>w.layers),p=M(w=>w.pendingUnhides),m=M(w=>w.orphans),g=M(w=>w.pendingOrphanDeletes),b=M(w=>w.customisedCommandIds),f=M(w=>w.uncustomisedCommandIds),y=ae(w=>w.activeEntity),x=ae(w=>w.solutionRibbonComponentIds),S=Ee(),C=Array.isArray(x)&&x.length>0,N=E.useCallback((w,A,B)=>Ax({locations:w.map(k=>({current:e[k],baseline:t[k]})),excludeCommandIds:B,locLabels:c,baselineLocLabels:d,layer:u[A]??void 0,unhiddenLayerHideIds:p[A],deletedOrphans:m[A].filter(k=>g[A].includes(k.id)),customisedCommandIds:b,uncustomisedCommandIds:f[A],commands:n,baselineCommands:i,enableRules:s,baselineEnableRules:l,displayRules:o,baselineDisplayRules:r}),[e,t,n,i,s,l,o,r,c,d,u,p,m,g,b,f]),O=E.useMemo(()=>y?N(ti,"entity"):null,[y,N]),I=E.useMemo(()=>{const w=new Set;if(y)for(const A of ti)for(const B of e[A].tabs)for(const k of B.groups)for(const v of Ne(k))v.commandId&&w.add(v.commandId);return N(["Application"],"application",w)},[N,y,e]),j=I.hasChanges&&C,$=E.useMemo(()=>{const w=(A,B)=>Dx({locations:A.map(k=>({current:e[k],baseline:t[k]})),plan:B,baselineCommands:i,baselineEnableRuleIds:l.map(k=>k.id),baselineDisplayRuleIds:r.map(k=>k.id),buttonName:k=>S(k.label,c,void 0,k.source?.labelToken)||k.id,titleOf:k=>S(k,c)||k});return[...O?.hasChanges?w(ti,O):[],...j?w(["Application"],I):[]]},[O,I,j,e,t,i,l,r,c,S]);return{entityPlan:O,appPlan:I,solutionSupportsAppRibbon:C,includeApplicationRibbon:j,scopes:[...y&&O?.hasChanges?[y.logicalName]:[],...j?["Application ribbon"]:[]],unsupported:[...O?.unsupported??[],...I.unsupported],warnings:[...O?.warnings??[],...I.warnings],changes:$}}function Gd(){const e=je(i=>i.target!==null),{changes:t,unsupported:n}=Ex(),o=M(i=>i.mutationsSincePublish>0),s=M(i=>i.mutationsSincePublish===0&&so(i));return{count:t.length,canPublish:e&&(t.length>0||n.length>0||o||s)}}const Bx=me({combobox:{minWidth:"140px",width:"220px",flexShrink:1,"@media (max-width: 1200px)":{width:"180px"}},input:{minWidth:0,width:"100%"},listbox:{maxHeight:"min(480px, 70vh)"},option:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,minWidth:0,width:"100%"},names:{display:"flex",flexDirection:"column",minWidth:0,flex:1},ellipsis:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},logical:{fontFamily:h.fontFamilyMonospace,color:h.colorNeutralForeground3},muted:{color:h.colorNeutralForeground3,flexShrink:0},empty:{whiteSpace:"normal"}}),Lx="__none";function zx(e,t){const n=t.trim().toLowerCase();return!n||e.displayName.toLowerCase().includes(n)||e.logicalName.toLowerCase().includes(n)}function Px(){const e=Bx(),t=ae(j=>j.entities),n=ae(j=>j.activeEntity),o=ae(j=>j.activeSolution),s=ae(j=>j.solutionEntityIds),i=je(j=>j.requestEntitySwitch),l=Z(j=>j.tablePickerOpen),r=Z(j=>j.setTablePickerOpen),{count:c}=Gd(),[d,u]=E.useState(null),p=E.useRef(null),m=!!o&&s===null,g=!o||m,b=l&&!g;E.useEffect(()=>{b&&document.activeElement!==p.current&&p.current?.focus()},[b]);const f=E.useMemo(()=>{const j=new Set;if(!l)return j;for(const $ of t)lx(qd($.logicalName))&&j.add($.logicalName);return j},[l,t]),y=t.filter(j=>zx(j,d??"")),x=y.filter(j=>j.isCustomEntity),S=y.filter(j=>!j.isCustomEntity),C=j=>{const $=j.logicalName===n?.logicalName,w=$?c:0;return a.jsx(wi,{value:j.logicalName,text:j.displayName,children:a.jsxs("div",{className:e.option,children:[a.jsxs("div",{className:e.names,children:[a.jsx(V,{size:200,weight:$?"semibold":"regular",className:e.ellipsis,children:j.displayName}),a.jsx(V,{size:200,className:Ie(e.logical,e.ellipsis),children:j.logicalName})]}),w>0?a.jsxs(xe,{appearance:"tint",color:"brand",size:"medium",children:[w," change",w===1?"":"s"]}):!$&&f.has(j.logicalName)&&a.jsx(xe,{appearance:"tint",color:"brand",size:"medium",children:"Draft"}),j.isManaged&&a.jsx(dn,{fontSize:12,className:e.muted,"aria-label":"Managed table"})]})},j.logicalName)},N=t.length===0&&o?`No tables in ${o.friendlyName}. Add one in the maker portal (Solutions › ${o.friendlyName} › Add existing › Table) and reload.`:"No tables match.",O=(j,$)=>{if($.optionValue===void 0||j.type==="keydown"&&j.key==="Tab")return;u(null);const w=t.find(A=>A.logicalName===$.optionValue);w&&w.logicalName!==n?.logicalName&&i(w)},I=o?m?"Loading tables…":"Choose table":"Choose a solution first";return a.jsxs(ua,{ref:p,"aria-label":"Table",className:e.combobox,input:{className:e.input},listbox:{className:e.listbox},placeholder:I,disabled:g,freeform:!0,value:d??n?.displayName??"",selectedOptions:n?[n.logicalName]:[],open:b,onOpenChange:(j,$)=>{r($.open),$.open||u(null)},onChange:j=>{u(j.target.value),l||r(!0)},onOptionSelect:O,onFocus:j=>j.currentTarget.select(),children:[x.length>0&&a.jsx(hr,{label:`Custom (${x.length})`,children:x.map(C)}),S.length>0&&a.jsx(hr,{label:`Standard (${S.length})`,children:S.map(C)}),y.length===0&&a.jsx(wi,{value:Lx,text:"",disabled:!0,children:a.jsx("span",{className:e.empty,children:N})})]})}const ni={small:440,medium:600,large:960},Ud=me({surface:{width:"calc(100vw - 32px)",maxHeight:"calc(100vh - 48px)",display:"flex",flexDirection:"column"},small:{maxWidth:`${ni.small}px`},medium:{maxWidth:`${ni.medium}px`},large:{maxWidth:`${ni.large}px`},body:{maxHeight:"calc(100vh - 96px)",minHeight:0},content:{minHeight:0,overflowY:"auto"},wholeRow:{gridColumnStart:1},danger:{backgroundColor:h.colorStatusDangerBackground3,color:h.colorNeutralForegroundOnBrand,":hover":{backgroundColor:h.colorStatusDangerBackground3Hover,color:h.colorNeutralForegroundOnBrand},":hover:active":{backgroundColor:h.colorStatusDangerBackground3Pressed,color:h.colorNeutralForegroundOnBrand}}}),un=({open:e,onOpenChange:t,title:n,size:o="medium",modalType:s="modal",actions:i,startActions:l,children:r,contentClassName:c})=>{const d=Ud(),u=s!=="alert",p=E.useRef(null);return E.useEffect(()=>{e&&p.current?.querySelector("[data-autofocus]")?.focus()},[e]),a.jsx(zh,{modalType:s,open:e,onOpenChange:(m,g)=>t(g.open),children:a.jsx(Ph,{ref:p,className:Ie(d.surface,d[o]),children:a.jsxs(Fh,{className:d.body,children:[a.jsx(_h,{action:u?a.jsx(qh,{action:"close",children:a.jsx(K,{appearance:"subtle","aria-label":"Close",icon:a.jsx(ln,{})})}):void 0,children:n}),a.jsx(Wh,{className:Ie(d.content,c),children:r}),(i||l)&&a.jsxs(a.Fragment,{children:[l&&a.jsx(gr,{position:"start",children:l}),a.jsx(gr,{position:"end",className:l?void 0:d.wholeRow,children:i})]})]})})})},Ga=({className:e,children:t,...n})=>{const o=Ud();return a.jsx(K,{...n,appearance:"primary",className:Ie(o.danger,e),children:t})},rs=e=>e instanceof Error?e.message:String(e),Fx=3e3;function _x(e,t){let n;const o=new Promise((s,i)=>{n=setTimeout(()=>i(new Error(`no answer in ${t/1e3} s`)),t)});return Promise.race([e,o]).finally(()=>clearTimeout(n))}async function Ts(e){const t=[],n=window.toolboxAPI?.utils?.copyToClipboard;if(n)try{return await _x(n(e),Fx),{ok:!0}}catch(o){t.push(`host: ${rs(o)}`)}if(navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),{ok:!0}}catch(o){t.push(`browser: ${rs(o)}`)}return{ok:!1,error:t.join("; ")||"no clipboard is available here"}}async function hI(e,t,n){const o=window.toolboxAPI?.fileSystem?.saveFile;if(o)try{const s=await o(e,t,n);return s?{ok:!0,path:s}:{ok:!1,canceled:!0}}catch(s){return{ok:!1,error:rs(s)}}try{const s=URL.createObjectURL(new Blob([t],{type:"application/xml"})),i=document.createElement("a");return i.href=s,i.download=e,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(s),1e4),{ok:!0}}catch(s){return{ok:!1,error:rs(s)}}}const Ki=48,ks=me({root:{height:`${Ki}px`,display:"flex",alignItems:"center",gap:h.spacingHorizontalS,padding:`0 ${h.spacingHorizontalM}`,backgroundColor:h.colorNeutralBackground3,borderBottom:`1px solid ${h.colorNeutralStroke2}`,flexShrink:0,minWidth:0},brand:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,flexShrink:0},brandMark:{width:"24px",height:"24px",borderRadius:h.borderRadiusMedium,backgroundColor:h.colorBrandBackground,color:h.colorNeutralForegroundOnBrand,display:"flex",alignItems:"center",justifyContent:"center"},brandTitle:{whiteSpace:"nowrap","@media (max-width: 1100px)":{display:"none"}},divider:{width:"1px",alignSelf:"stretch",margin:`${h.spacingVerticalM} 0`,backgroundColor:h.colorNeutralStroke2,flexShrink:0},solutionTrigger:{minWidth:"120px",maxWidth:"260px",flexShrink:1,justifyContent:"flex-start","@media (max-width: 1200px)":{maxWidth:"200px"}},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:h.colorNeutralForeground3,flexShrink:0},solutionPickerSurface:{padding:h.spacingHorizontalM,width:"380px",maxWidth:"calc(100vw - 32px)",display:"flex",flexDirection:"column",gap:h.spacingVerticalS},optionText:{display:"flex",flexDirection:"column",gap:"2px",minWidth:0},search:{flexShrink:0,color:h.colorNeutralForeground3,fontWeight:h.fontWeightRegular},searchText:{"@media (max-width: 1180px)":{display:"none"}},kbd:{marginLeft:h.spacingHorizontalS,padding:"0 4px",border:`1px solid ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusSmall,fontSize:h.fontSizeBase200,"@media (max-width: 1180px)":{display:"none"}},toolsOverflow:{flex:"1 1 0",minWidth:"40px",overflow:"hidden",display:"flex",justifyContent:"flex-end"},toolbar:{flexWrap:"nowrap",minWidth:0},overflowSlot:{display:"inline-flex"},publish:{flexShrink:0},helpBody:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,maxWidth:"320px"},shortcuts:{display:"grid",gridTemplateColumns:"auto 1fr",columnGap:h.spacingHorizontalM,rowGap:h.spacingVerticalXXS,margin:0,fontSize:h.fontSizeBase200,lineHeight:h.lineHeightBase200,"& dt":{fontWeight:h.fontWeightSemibold,whiteSpace:"nowrap"},"& dd":{margin:0}}}),qx=[["Ctrl+K","Search"],["Ctrl+S","Publish"],["Ctrl+Z / Ctrl+Y","Undo / redo"],["Ctrl+D","Duplicate"],["Ctrl+X / Ctrl+V","Move a button"]];function Wx(){const e=ks(),t=Z(d=>d.openBulkPublish),n=Z(d=>d.setCommandPaletteOpen),{count:o,canPublish:s}=Gd(),[i,l]=E.useState(!1),r=o>0?`Publish ${o} change${o===1?"":"s"}`:"Publish",c=a.jsx(K,{appearance:"primary",icon:a.jsx(vm,{}),className:e.publish,disabledFocusable:!s,onClick:s?t:void 0,children:s&&o===0?"Publish changes":r});return a.jsxs("header",{className:e.root,children:[a.jsxs("div",{className:e.brand,children:[a.jsx("div",{className:e.brandMark,"aria-hidden":"true",children:a.jsx(V,{size:100,weight:"bold",children:"CBS"})}),a.jsx(V,{weight:"semibold",size:300,className:e.brandTitle,children:"Command Bar Studio"})]}),a.jsx("div",{className:e.divider}),a.jsx(hx,{compactBelow:1200}),a.jsx("div",{className:e.divider}),a.jsx(Gx,{}),a.jsx(Px,{}),a.jsx(Xx,{onHelp:()=>l(!0)}),a.jsx(pe,{content:"Search buttons, commands, rules (Ctrl+K)",relationship:"label",children:a.jsxs(K,{appearance:"outline",icon:a.jsx(Pl,{}),className:e.search,onClick:()=>n(!0),children:[a.jsx("span",{className:e.searchText,children:"Search"}),a.jsx("span",{className:e.kbd,"aria-hidden":"true",children:"Ctrl K"})]})}),s?c:a.jsx(pe,{content:"No unpublished changes on this table. Make a change and it shows here as Publish 1 change.",relationship:"description",children:c}),a.jsx(un,{open:i,onOpenChange:l,title:"Command Bar Studio",size:"small",children:a.jsx(Kd,{})})]})}function Hx(e){return(e.publisherPrefix||"new")==="new"||/^defaultpublisher/i.test(e.publisherUniqueName??"")}function Gx(){const e=ks(),t=ae(f=>f.solutions),n=ae(f=>f.activeSolution),o=je(f=>f.requestSolutionSwitch),s=Z(f=>f.solutionPickerOpen),i=Z(f=>f.setSolutionPickerOpen),[l,r]=E.useState(""),c=E.useRef(null),d=E.useMemo(()=>t.filter(f=>!f.isManaged).map(f=>({value:f.id,children:f.friendlyName||f.uniqueName,searchText:`${f.friendlyName??""} ${f.uniqueName??""}`.toLowerCase(),solution:f})),[t]),u=uc(l,d,{optionToText:f=>f.searchText,filter:(f,y)=>f.includes(y.toLowerCase()),optionToReactKey:f=>f.value,renderOption:f=>a.jsx(wi,{value:f.value,text:f.solution.friendlyName??f.solution.uniqueName,children:a.jsxs("div",{className:e.optionText,children:[a.jsx(V,{size:200,weight:"semibold",children:f.solution.friendlyName||f.solution.uniqueName}),a.jsxs(V,{size:200,className:e.muted,children:[f.solution.uniqueName," · v",f.solution.version,f.solution.publisherName?` · ${f.solution.publisherName}`:""]})]})},f.value),noOptionsMessage:t.length===0?"Loading solutions…":"No solutions match the filter."}),p=(f,y)=>{const x=t.find(S=>S.id===y.optionValue);x&&(o(x),i(!1),r(""),requestAnimationFrame(()=>{const S=document.activeElement;(!S||S===document.body)&&c.current?.focus()}))},m=n?n.friendlyName||n.uniqueName:"",g=n?Hx(n):!1,b=n?.publisherPrefix||"new";return a.jsxs(ma,{open:s,onOpenChange:(f,y)=>i(y.open),positioning:"below-start",trapFocus:!0,children:[a.jsx(pa,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:n?m:"Choose the solution your changes are saved to",relationship:"description",children:a.jsxs(K,{ref:c,appearance:n?"subtle":"primary",icon:a.jsx(_l,{}),"aria-label":n?`Solution: ${m}`:"Select solution",className:e.solutionTrigger,children:[n?a.jsxs(a.Fragment,{children:[a.jsx("span",{className:e.ellipsis,children:m}),g&&a.jsx(Fl,{"aria-label":"Default publisher",style:{color:h.colorPaletteDarkOrangeForeground1,flexShrink:0}})]}):"Choose solution",a.jsx(it,{fontSize:12,className:e.muted})]})})}),a.jsxs(fa,{className:e.solutionPickerSurface,children:[a.jsx(_e,{label:"Solution your changes are saved to",children:a.jsx(ua,{placeholder:t.length===0?"Loading solutions…":"Search by display name or unique name",value:l,onChange:f=>r(f.target.value),onOptionSelect:p,freeform:!0,clearable:!0,children:u})}),a.jsxs(V,{size:200,className:e.muted,children:[d.length," unmanaged solution",d.length!==1?"s":""," available"]}),n&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[a.jsx(Dt,{size:"small",info:g?`New ids are prefixed "${b}_", the org's default publisher. To use your own prefix, create a solution in make.powerapps.com bound to your publisher.`:`New ids are prefixed "${b}_" (publisher ${n.publisherName||n.publisherUniqueName||b}).`,children:"Publisher prefix"}),a.jsxs(xe,{appearance:"tint",color:g?"warning":"informative",size:"medium",children:[b,"_"]})]})]})]})}async function Ux(e,t){const n=`${e.replace(/\/$/,"")}/main.aspx?pagetype=entitylist&etn=${encodeURIComponent(t)}`;await window.toolboxAPI?.utils.openInConnectionBrowser(n,"primary")}function Vx(){const e=M(g=>g.past),t=M(g=>g.future),n=M(g=>g.undo),o=M(g=>g.redo),s=Z(g=>g.openXmlDrawer),i=Z(g=>g.openImportXml),l=Z(g=>g.openDiffViewer),r=Z(g=>g.rightPaneMode),c=Z(g=>g.setRightPaneMode),d=Z(g=>g.bottomCollapsed),u=Z(g=>g.setBottomCollapsed),p=ae(g=>g.connectionUrl),m=ae(g=>g.activeEntity?.logicalName);return{canUndo:e.length>0,canRedo:t.length>0,undo:n,redo:o,viewXml:()=>s(J.getState().location),importXml:()=>i(),compare:()=>l("compare"),canOpenInApp:!!(p&&m),openInApp:()=>p&&m?void Ux(p,m):void 0,rightPaneMode:r,setRightPaneMode:c,bottomCollapsed:d,setBottomCollapsed:u}}const Vd=e=>a.jsxs(a.Fragment,{children:[a.jsx(fe,{onClick:e.viewXml,children:"View XML"}),a.jsx(fe,{onClick:e.importXml,children:"Import XML…"}),a.jsx(fe,{onClick:e.compare,children:"Compare with published"})]});function Yi(e){return{checkedValues:{properties:[e.rightPaneMode],bottom:e.bottomCollapsed?[]:["show"]},onCheckedValueChange:(t,n)=>{n.name==="properties"&&e.setRightPaneMode(n.checkedItems[0]),n.name==="bottom"&&e.setBottomCollapsed(!n.checkedItems.includes("show"))}}}const Xd=a.jsxs(a.Fragment,{children:[a.jsxs(Uh,{children:[a.jsx(ro,{children:"Properties pane"}),a.jsx(Sn,{name:"properties",value:"docked",children:"Docked"}),a.jsx(Sn,{name:"properties",value:"floating",children:"Floating"}),a.jsx(Sn,{name:"properties",value:"hidden",children:"Hidden"})]}),a.jsx(Mt,{}),a.jsx(mc,{name:"bottom",value:"show",children:"Show the bottom panel"})]});function Xx({onHelp:e}){const t=ks(),n=Vx();return a.jsx(ha,{padding:40,children:a.jsx("div",{className:t.toolsOverflow,children:a.jsxs(Hh,{"aria-label":"Tools",size:"small",className:t.toolbar,children:[a.jsx(Pt,{id:"undo",groupId:"history",children:a.jsx(pe,{content:"Undo (Ctrl+Z)",relationship:"label",children:a.jsx(nn,{icon:a.jsx(aa,{}),disabledFocusable:!n.canUndo,onClick:n.undo})})}),a.jsx(Pt,{id:"redo",groupId:"history",children:a.jsx(pe,{content:"Redo (Ctrl+Y)",relationship:"label",children:a.jsx(nn,{icon:a.jsx(ra,{}),disabledFocusable:!n.canRedo,onClick:n.redo})})}),a.jsx(Gh,{}),a.jsx(Pt,{id:"xml",children:a.jsx("span",{className:t.overflowSlot,children:a.jsxs(Xe,{children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsxs(nn,{icon:a.jsx(On,{}),children:["XML ",a.jsx(it,{fontSize:12})]})}),a.jsx(Ye,{children:a.jsx(Je,{children:Vd(n)})})]})})}),a.jsx(Pt,{id:"open",children:a.jsx(pe,{content:"Open this table in Dynamics 365",relationship:"label",children:a.jsx(nn,{icon:a.jsx(la,{}),disabledFocusable:!n.canOpenInApp,onClick:n.openInApp})})}),a.jsx(Pt,{id:"view",children:a.jsx("span",{className:t.overflowSlot,children:a.jsxs(Xe,{...Yi(n),children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:"View",relationship:"label",children:a.jsx(nn,{icon:a.jsx(ql,{})})})}),a.jsx(Ye,{children:a.jsx(Je,{children:Xd})})]})})}),a.jsx(Pt,{id:"help",children:a.jsx("span",{className:t.overflowSlot,children:a.jsx(Yx,{})})}),a.jsx(Kx,{tools:n,onHelp:e})]})})})}function Kx({tools:e,onHelp:t}){const{ref:n,isOverflowing:o,overflowCount:s}=ga();return o?a.jsxs(Xe,{...Yi(e),children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:`More tools (${s})`,relationship:"label",children:a.jsx(nn,{ref:n,icon:a.jsx(ds,{})})})}),a.jsx(Ye,{children:a.jsxs(Je,{children:[a.jsx(fn,{id:"undo",children:a.jsx(fe,{icon:a.jsx(aa,{}),disabled:!e.canUndo,onClick:e.undo,secondaryContent:"Ctrl+Z",children:"Undo"})}),a.jsx(fn,{id:"redo",children:a.jsx(fe,{icon:a.jsx(ra,{}),disabled:!e.canRedo,onClick:e.redo,secondaryContent:"Ctrl+Y",children:"Redo"})}),a.jsx(fn,{id:"xml",children:a.jsxs(Xe,{children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(fe,{icon:a.jsx(On,{}),children:"XML"})}),a.jsx(Ye,{children:a.jsx(Je,{children:Vd(e)})})]})}),a.jsx(fn,{id:"open",children:a.jsx(fe,{icon:a.jsx(la,{}),disabled:!e.canOpenInApp,onClick:e.openInApp,children:"Open in Dynamics 365"})}),a.jsx(fn,{id:"view",children:a.jsxs(Xe,{...Yi(e),children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(fe,{icon:a.jsx(ql,{}),children:"View"})}),a.jsx(Ye,{children:a.jsx(Je,{children:Xd})})]})}),a.jsx(fn,{id:"help",children:a.jsx(fe,{icon:a.jsx(ca,{}),onClick:t,children:"Help"})})]})})]}):null}function fn({id:e,children:t}){return ba(e)?null:t}const Qr="https://github.com/mohsinonxrm/pptb-mxrm-commandbar-studio#readme";function Kd(){const e=ks(),[t,n]=E.useState("");return a.jsxs("div",{className:e.helpBody,children:[a.jsx(V,{size:200,children:"Your changes are kept as a draft for each table automatically, until you publish or discard them."}),a.jsx("dl",{className:e.shortcuts,children:qx.map(([o,s])=>a.jsxs(E.Fragment,{children:[a.jsx("dt",{children:o}),a.jsx("dd",{children:s})]},o))}),a.jsx(K,{size:"small",onClick:async()=>n((await Ts(Qr)).ok?"yes":"no"),children:"Copy documentation link"}),t==="yes"&&a.jsx(V,{size:200,children:"Copied: paste it into your browser."}),t==="no"&&a.jsxs(V,{size:200,children:["Couldn't copy. The link is ",Qr]})]})}function Yx(){return a.jsxs(ma,{withArrow:!0,children:[a.jsx(pa,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:"Help",relationship:"label",children:a.jsx(nn,{icon:a.jsx(ca,{})})})}),a.jsxs(fa,{"aria-label":"Help",children:[a.jsx(V,{weight:"semibold",children:"Command Bar Studio"}),a.jsx(Kd,{})]})]})}const Yd="cbs.ui.";function Jd(e,t){try{const n=window.localStorage.getItem(Yd+e);return n===null?t:JSON.parse(n)}catch{return t}}function Zd(e,t){try{window.localStorage.setItem(Yd+e,JSON.stringify(t))}catch{}}const Jx=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS,flexShrink:0},more:{alignSelf:"flex-start",fontSize:h.fontSizeBase200}}),el={error:0,warning:1,info:2,success:3};function tl(e){const t=Jd(e,{});return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(n=>typeof n[1]=="string"))}const Ua=({scope:e,messages:t,className:n})=>{const o=Jx(),s=`dismissed.${e}`,[i,l]=E.useState(()=>tl(s)),[r,c]=E.useState(!1),[d,u]=E.useState(e);d!==e&&(u(e),l(tl(s)),c(!1));const p=t.filter(b=>i[b.id]!==(b.signature??"")).sort((b,f)=>el[b.intent]-el[f.intent]);if(p.length===0)return null;const m=r?p:p.slice(0,1),g=b=>{if(b.onDismiss){b.onDismiss();return}const f={...i,[b.id]:b.signature??""};l(f),Zd(s,f)};return a.jsxs("div",{className:n?`${o.root} ${n}`:o.root,children:[a.jsx(Vh,{animate:"both",children:m.map(b=>a.jsxs(Rt,{intent:b.intent,layout:"multiline",children:[a.jsxs($t,{children:[a.jsx(pc,{children:b.title}),b.body]}),(b.actions||b.dismissible!==!1)&&a.jsx(ms,{containerAction:b.dismissible===!1?void 0:a.jsx(K,{appearance:"transparent","aria-label":`Dismiss: ${b.title}`,icon:a.jsx(ln,{}),onClick:()=>g(b)}),children:b.actions})]},b.id))}),p.length>1&&a.jsx($n,{as:"button",className:o.more,"aria-expanded":r,onClick:()=>c(b=>!b),children:r?"Show fewer":`+${p.length-1} more`})]})};function Zx(){const e=je(n=>n.saveFailed),t=je(n=>n.lastSavedAt);return e?{id:"draft-save-failed",intent:"error",title:"Your latest changes can't be saved as a draft",body:t?a.jsxs(a.Fragment,{children:["The browser storage is full. The last saved draft is from"," ",new Date(t).toLocaleString(),"; publish your changes, or the ones made since are lost when Command Bar Studio closes."]}):a.jsx(a.Fragment,{children:"The browser storage is full. Publish your changes, or they are lost when Command Bar Studio closes."}),dismissible:!1}:null}function Qx(){const e=ae(s=>s.connectionNotice),t=ae(s=>s.dismissConnectionNotice);if(!e)return null;const n=`${e.from.name||e.from.url} (${e.from.environment})`,o=`${e.to.name||e.to.url} (${e.to.environment})`;return{id:"connection-changed",intent:e.draftLost?"error":e.to.environment==="Production"?"warning":"info",title:`Connection changed to ${o}`,body:a.jsxs(a.Fragment,{children:["The solution and table loaded from ",n," were closed; pick a solution to continue in ",o,"."," ",e.draftKept&&a.jsxs(a.Fragment,{children:["Your unpublished changes were kept as a draft: switch the tool back to"," ",n," and open the table to restore them."]}),e.draftLost&&a.jsx(a.Fragment,{children:"Your unpublished changes couldn't be saved as a draft (the browser storage is full) and are lost."})]}),onDismiss:t}}function eS(){const e=Zx();return[Qx(),e].filter(n=>n!==null)}const tS=me({slot:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`}});function nS(){const e=tS(),t=eS();return t.length===0?null:a.jsx(Ua,{scope:"shell",messages:t,className:e.slot})}const Qd=E.createContext({}),we=Xt()((e,t)=>({tableLogicalName:null,status:"idle",error:null,commands:[],apps:[],appFilter:"all",selectedCommandId:null,loadToken:0,beginLoad(n){const o=t().loadToken+1;return e({tableLogicalName:n,status:"loading",error:null,commands:[],apps:[],selectedCommandId:null,loadToken:o}),o},finishLoad(n,o){if(n!==t().loadToken)return;const{appFilter:s}=t(),i=s==="all"||o.apps.some(l=>l.id===s);e({status:o.error?"unavailable":"loaded",error:o.error??null,commands:o.commands,apps:o.apps,appFilter:i?s:"all"})},reset(){e(n=>({tableLogicalName:null,status:"idle",error:null,commands:[],apps:[],selectedCommandId:null,appFilter:"all",loadToken:n.loadToken+1}))},setAppFilter(n){e({appFilter:n?n.toLowerCase():"all"})},selectCommand(n){n&&J.getState().clearSelection(),e({selectedCommandId:n})}}));J.subscribe((e,t)=>{if(!we.getState().selectedCommandId)return;(e.selectedButtonId&&e.selectedButtonId!==t.selectedButtonId||e.location!==t.location||e.tabId!==t.tabId)&&we.setState({selectedCommandId:null})});function oS(e){return e instanceof Element?e instanceof HTMLElement&&e.isContentEditable?!0:!!e.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="combobox"], [role="spinbutton"], .monaco-editor'):!1}const sS='[role="dialog"], [role="alertdialog"], [role="menu"], [role="menubar"], [role="listbox"], .fui-PopoverSurface, .fui-MenuPopover',eu=".fui-OverlayDrawer, .fui-InlineDrawer",nl=e=>!!e.closest(eu)&&!e.matches('[role="alertdialog"]');function iS(e){const t=e instanceof Element?e.closest(sS):null;return t&&!nl(t)?!0:Array.from(document.querySelectorAll('[aria-modal="true"], [role="alertdialog"]')).some(n=>!nl(n))}function aS(e){return e instanceof Element&&!!e.closest(eu)}function rS(){const e=Z(N=>N.setCommandPaletteOpen),t=Z(N=>N.openBulkPublish),n=Z(N=>N.announce),o=Z(N=>N.openHideInsteadOfDelete),s=M(N=>N.undo),i=M(N=>N.redo),l=M(N=>N.past),r=M(N=>N.future),c=J(N=>N.selectedButtonId),d=J(N=>N.selectedGroupId),u=J(N=>N.tabId),p=J(N=>N.location),m=M(N=>N.duplicateButton),g=M(N=>N.deleteButton),b=M(N=>N.moveButton),f=M(N=>N.ribbons),y=M(N=>N.baseline),x=J(N=>N.selectButtonInContext),S=J(N=>N.selectGroup),C=E.useRef(null);E.useEffect(()=>{const N=O=>{const j=navigator.platform.toUpperCase().includes("MAC")?O.metaKey:O.ctrlKey,$=O.target,w=O.key??"",A=O.altKey||O.getModifierState?.("AltGraph"),B=!A&&/^Key[A-Z]$/.test(O.code??"")&&!/^[a-z]$/i.test(w)?O.code.slice(3).toLowerCase():w.length===1?w.toLowerCase():w,k=j&&!O.shiftKey&&!A;if(O.key==="Escape"){e(!1);return}if(iS($)){k&&B==="s"&&O.preventDefault();return}if(k&&B==="k"){O.preventDefault(),e(!0),n("Command palette opened");return}if(k&&B==="s"){O.preventDefault(),t(),n("Bulk publish dialog opened");return}const v=oS($);if(k&&B==="z"&&l.length>0&&!v){O.preventDefault(),s(),n("Undo");return}if(j&&!A&&(B==="y"||O.shiftKey&&B==="z")&&!v){O.preventDefault(),r.length>0&&(i(),n("Redo"));return}if(!aS($)){if(k&&B==="d"){!v&&c&&d&&u&&p&&(O.preventDefault(),m(p,u,d,c),n("Button duplicated"));return}if(j&&!A&&B==="x"){if(!v&&c&&d&&u&&p){O.preventDefault();const T=f[p].tabs.find(R=>R.id===u)?.groups.find(R=>R.id===d);if(T&&Ko(T,c)){n("Menu items can't be cut. Delete the item and add a new one to the other menu.");return}C.current={location:p,tabId:u,groupId:d,buttonId:c},n("Button cut. Focus a destination group, then press paste.")}return}if(j&&!A&&B==="v"){const T=C.current;if(!v&&T&&d&&u&&p){O.preventDefault();const R=b({groupId:T.groupId,buttonId:T.buttonId,tabId:T.tabId,location:T.location},{groupId:d,tabId:u,location:p});if(C.current=null,!R){n("The button couldn't be moved there.");return}requestAnimationFrame(()=>{x(p,u,d,R),document.querySelector(`[data-ribbon-btn-id="${R}"]`)?.focus()}),n(R===T.buttonId?"Button pasted to destination group.":"Pasted your copy of the button to the destination group; the original is hidden.")}return}if((O.key==="Delete"||O.key==="Backspace")&&c&&d&&u&&p&&!v){const T=f[p].tabs.find(F=>F.id===u),R=T?.groups.find(F=>F.id===d),D=Ss(R,c);if(!D)return;if(O.preventDefault(),!Cs(D,y[p])){p==="Application"&&u==="Mscrm.GlobalTab"&&D.oob&&!D.custom?n(`"${D.label}" is read-only and can't be deleted.`):D.hidden?n(`"${D.label}" can't be deleted — only your own buttons can. It is already hidden.`):o({location:p,tabId:u,groupId:d,buttonId:c});return}const q=R?Ko(R,c):void 0,X=q?q.section.controls.map(F=>({groupId:d,buttonId:F.id})):T?.groups.flatMap(F=>F.buttons.map(L=>({groupId:F.id,buttonId:L.id})))??[],ne=X.findIndex(F=>F.buttonId===c),re=X[ne+1]??X[ne-1]??(q?{groupId:d,buttonId:q.parent.id}:null),le=d;g(p,u,d,c),requestAnimationFrame(()=>{if(re){x(p,u,re.groupId,re.buttonId),document.querySelector(`[data-ribbon-btn-id="${re.buttonId}"]`)?.focus();return}le&&(S(le),document.querySelector(`[data-add-btn-group-id="${le}"]`)?.focus())}),n("Button deleted")}}};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[e,t,n,o,s,i,l.length,r.length,c,d,u,p,m,g,b,f,y,x,S])}const lS=me({handleV:{width:"4px",cursor:"col-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:h.colorNeutralStroke2},":active":{backgroundColor:h.colorBrandStroke1},userSelect:"none"},handleH:{height:"4px",cursor:"row-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:h.colorNeutralStroke2},":active":{backgroundColor:h.colorBrandStroke1},userSelect:"none"}});function oi({direction:e,onResize:t,"aria-label":n=`Resize ${e} pane`}){const o=lS(),s=E.useRef(0),i=E.useCallback(r=>{r.currentTarget.setPointerCapture(r.pointerId),s.current=e==="vertical"?r.clientX:r.clientY},[e]),l=E.useCallback(r=>{if(!r.currentTarget.hasPointerCapture(r.pointerId))return;const c=e==="vertical"?r.clientX:r.clientY,d=c-s.current;s.current=c,t(d)},[e,t]);return a.jsx("div",{className:e==="vertical"?o.handleV:o.handleH,role:"separator","aria-orientation":e==="vertical"?"vertical":"horizontal","aria-label":n,onPointerDown:i,onPointerMove:l})}class Lt extends et.Component{state={hasError:!1,error:null};static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("[CBS ErrorBoundary]",this.props.label??"panel",t,n)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:a.jsxs(Rt,{intent:"error",style:{margin:8},children:[a.jsxs($t,{children:[a.jsx("strong",{children:this.props.label??"Panel"})," encountered an error:"," ",this.state.error?.message??"Unknown error"]}),a.jsx(ms,{children:a.jsx(K,{size:"small",onClick:this.handleRetry,children:"Retry"})})]}):this.props.children}}const cS=.4,tu=160,nu=200,dS=500,uS=600;function ou(e,t,n){const o=t+n-e*(1-cS);if(o<=0||t+n===0)return{left:t,right:n};const s=(i,l)=>Math.max(Math.min(i,l),Math.round(i-o*i/(t+n)));return{left:s(t,tu),right:n===0?0:s(n,nu)}}function mS(e,t,n,o,s){const i=ou(e,t,n),l=(c,d,u)=>Math.max(d,Math.min(u,c));if(o==="left"){const c=l(i.left+s,tu,dS);return n>0&&i.right!==n?{left:c,right:i.right}:{left:c}}const r=l(i.right-s,nu,uS);return i.left!==t?{left:i.left,right:r}:{right:r}}const pS=E.lazy(()=>ft(()=>import("./EditorDrawer-CvCe9WeO.js"),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url)),fS=E.lazy(()=>ft(()=>import("./BulkPublishModal-DzDZJg0U.js"),__vite__mapDeps([6,3,1,2,7,4,8,9,10,5]),import.meta.url)),hS=E.lazy(()=>ft(()=>import("./NewButtonModal-COYXwEyk.js"),__vite__mapDeps([11,3,1,2,4,5]),import.meta.url)),gS=E.lazy(()=>ft(()=>import("./NewGroupModal-boP_t1fI.js"),__vite__mapDeps([12,3,1,2,4,5]),import.meta.url)),bS=E.lazy(()=>ft(()=>import("./NewTabModal-BI4afbC5.js"),__vite__mapDeps([13,3,1,2,4,5]),import.meta.url)),yS=E.lazy(()=>ft(()=>import("./ImportXmlModal-BD-L1QzJ.js"),__vite__mapDeps([14,3,1,2,8,9,10,7,4,5]),import.meta.url)),xS=E.lazy(()=>ft(()=>import("./CommandPalette-ID3kRJ9l.js"),__vite__mapDeps([15,3,1,2,4,5]),import.meta.url)),SS=E.lazy(()=>ft(()=>import("./IconPickerModal-BLoDLbLR.js"),__vite__mapDeps([16,3,1,2,17,4,5]),import.meta.url)),vS=E.lazy(()=>ft(()=>import("./WebResourceBrowser-BATScmTw.js"),__vite__mapDeps([18,3,1,2,17,4,5]),import.meta.url)),wS=E.lazy(()=>ft(()=>import("./HideInsteadOfDeleteModal-3j9g-E9l.js"),__vite__mapDeps([19,3,1,2,4,5]),import.meta.url)),CS=me({root:{display:"flex",flexDirection:"column",height:"100vh",overflow:"hidden",backgroundColor:h.colorNeutralBackground1,color:h.colorNeutralForeground1,fontFamily:h.fontFamilyBase},body:{display:"flex",flex:1,overflow:"hidden",position:"relative"},leftPane:{flexShrink:0,overflow:"hidden",borderRight:`1px solid ${h.colorNeutralStroke2}`},rightPane:{flexShrink:0,overflow:"hidden",borderLeft:`1px solid ${h.colorNeutralStroke2}`},bottomPanel:{flexShrink:0},rail:{width:"48px",flexShrink:0,display:"flex",flexDirection:"column",alignItems:"center",paddingTop:h.spacingVerticalS,borderRight:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground2},drawerBody:{position:"relative",width:"100%",height:"100%",overflow:"hidden"},belowTopBar:{top:`${Ki+1}px`,height:`calc(100vh - ${Ki+1}px)`}}),IS=[{value:"structure",label:"Structure",icon:a.jsx(Wl,{})},{value:"solution",label:"Solution",icon:a.jsx(Hl,{})}],jS=1200;function RS(){const[e,t]=E.useState(()=>window.innerWidth);return E.useEffect(()=>{const n=()=>t(window.innerWidth);return window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),e}function $S({children:e,leftPane:t,rightPane:n,bottomPanel:o}){const s=CS(),i=Z(Y=>Y.leftPaneWidth),l=Z(Y=>Y.rightPaneWidth),r=Z(Y=>Y.rightPaneMode),c=Z(Y=>Y.setLeftPaneWidth),d=Z(Y=>Y.setRightPaneWidth),u=Z(Y=>Y.bottomPanelHeight),p=Z(Y=>Y.bottomCollapsed),m=Z(Y=>Y.setBottomPanelHeight),g=Z(Y=>Y.announcement),b=RS(),f=b<jS,y=J(Y=>Y.selectedButtonId),x=J(Y=>Y.selectedGroupId),S=ae(Y=>Y.activeEntity?.logicalName??null),[C,N]=E.useState(!1),O=Z(Y=>Y.leftPaneTab),I=Z(Y=>Y.setLeftPaneTab),j=we(Y=>Y.selectedCommandId),[$,w]=E.useState(!1),A=Z(Y=>Y.propertiesRequested),B=Z(Y=>Y.setPropertiesRequested),k=$||f&&A,v=()=>{w(!1),B(!1)},T=!!(y||x||j),R=`${x??""}|${y??""}|${j??""}`,[D,q]=E.useState(R);D!==R&&(q(R),f&&!C&&T&&w(!0));const[X,ne]=E.useState(f);X!==f&&(ne(f),N(!1),w(!1));const re=Z(Y=>Y.structureChoice),[le,F]=E.useState(re);le!==re&&(F(re),N(!1),f&&T&&w(!0));const[L,G]=E.useState(S);L!==S&&(G(S),N(!1));const U=ou(b,i,r==="docked"?l:0),te=Z(Y=>Y.editorStack.length>0||Y.bulkPublishOpen||Y.newButtonGroupId!==null||Y.newGroupOpen||Y.newTabOpen||Y.importXmlOpen||Y.commandPaletteOpen||Y.iconPickerOpen||Y.webResourceBrowserOpen||Y.hideInsteadOfDelete!==null),P=E.useRef(null),Q=E.useRef(!1);rS(),E.useEffect(()=>{A&&!f&&B(!1)},[A,f,B]),E.useEffect(()=>{if(te&&!Q.current){const Y=document.activeElement;P.current=Y instanceof HTMLElement?Y:null}if(!te&&Q.current){const Y=P.current;requestAnimationFrame(()=>{!Y||!Y.isConnected||Y.focus()})}Q.current=te},[te]);const be=r==="docked"?l:0,Ae=E.useCallback((Y,ze)=>{const Qe=mS(b,i,be,Y,ze);Qe.left!==void 0&&c(Qe.left),Qe.right!==void 0&&d(Qe.right)},[b,i,be,c,d]),tt=E.useCallback(Y=>Ae("left",Y),[Ae]),Be=E.useCallback(Y=>Ae("right",Y),[Ae]),Le=E.useCallback(Y=>{const ze=u-Y;m(Math.max(120,Math.min(520,ze)))},[u,m]);return a.jsxs("div",{className:s.root,children:[a.jsx(Wx,{}),a.jsx(nS,{}),a.jsxs("div",{className:s.body,children:[f?a.jsxs("nav",{className:s.rail,"aria-label":"Side panes",children:[IS.map(({value:Y,label:ze,icon:Qe})=>a.jsx(pe,{content:ze,relationship:"label",children:a.jsx(K,{appearance:"subtle",icon:Qe,"aria-pressed":C&&O===Y,onClick:()=>{I(Y),N(!0)}})},Y)),r!=="hidden"&&a.jsx(pe,{content:"Properties",relationship:"label",children:a.jsx(K,{appearance:"subtle",icon:a.jsx(wm,{}),"aria-pressed":k,onClick:()=>k?v():w(!0)})})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:s.leftPane,style:{width:U.left},children:a.jsx(Lt,{label:"Left pane",children:t})}),a.jsx(oi,{direction:"vertical",onResize:tt,"aria-label":"Resize left pane"})]}),a.jsx(Lt,{label:"Ribbon canvas",children:e}),f&&a.jsxs(a.Fragment,{children:[a.jsx(br,{position:"start",size:"small",open:C,onOpenChange:(Y,ze)=>N(ze.open),"aria-label":O==="structure"?"Structure":"Solution",children:a.jsx("div",{className:s.drawerBody,children:a.jsx(Lt,{label:"Left pane",children:t})})}),r!=="hidden"&&a.jsx(br,{position:"end",size:"small",modalType:"non-modal",className:s.belowTopBar,open:k,onOpenChange:(Y,ze)=>ze.open?w(!0):v(),"aria-label":"Properties",children:a.jsx("div",{className:s.drawerBody,children:a.jsx(Qd.Provider,{value:{onClose:v},children:a.jsx(Lt,{label:"Properties pane",children:n})})})})]}),!f&&r==="docked"&&a.jsxs(a.Fragment,{children:[a.jsx(oi,{direction:"vertical",onResize:Be,"aria-label":"Resize right pane"}),a.jsx("div",{className:s.rightPane,style:{width:U.right},children:a.jsx(Lt,{label:"Properties pane",children:n})})]}),!f&&r==="floating"&&a.jsx("div",{style:{position:"absolute",right:8,top:8,bottom:8,width:l,maxWidth:"90vw",border:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground1,boxShadow:h.shadow16,borderRadius:h.borderRadiusMedium,overflow:"hidden",zIndex:10},children:a.jsx(Lt,{label:"Properties pane",children:n})})]}),!p&&a.jsx(oi,{direction:"horizontal",onResize:Le,"aria-label":"Resize bottom panel"}),a.jsx("div",{className:s.bottomPanel,children:a.jsx(Lt,{label:"Bottom panel",children:o})}),a.jsx(Lt,{label:"Panels",children:a.jsxs(E.Suspense,{fallback:null,children:[a.jsx(pS,{}),a.jsx(fS,{}),a.jsx(hS,{}),a.jsx(gS,{}),a.jsx(bS,{}),a.jsx(yS,{}),a.jsx(xS,{}),a.jsx(SS,{}),a.jsx(vS,{}),a.jsx(wS,{})]})}),a.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",left:-9999,top:"auto"},children:g})]})}const NS=["HomepageGrid","SubGrid","Form"];function TS(e,t){const n=new Map;for(const b of Object.values(t.baseline))for(const f of b.tabs)for(const y of f.groups)for(const x of y.buttons)n.set(x.id,x.origin);let o=!1,s=!1,i=Di(e);for(const[b,f]of Object.entries(t.ribbons))for(const y of f.tabs)for(const x of y.groups)for(const S of x.buttons)S.commandId===e&&(NS.includes(b)?o=!0:s=!0,n.has(S.id)&&n.get(S.id)!=="unmanaged"&&(i=!0));const l=o||!s?"entity":"application",r=o&&s,c=t.layers[l],d=c?.commandIds?c.commandIds.includes(e):void 0,u=t.baselineCommands.find(b=>b.id===e),p=(b,f=l)=>({provenance:b,scope:f,sharedWithApplication:r});if(t.reloadRequiredCommandIds.includes(e))return p("reloadRequired");for(const b of["entity","application"])if(t.uncustomisedCommandIds[b].includes(e))return p("uncustomising",b);if(!u||!i&&d!==!1)return p("custom");if(d){const b=c?.commandRefIds?Ra(e,c.commandRefIds):Di(e);return p(b?"customised":"custom")}const m=t.commands.find(b=>b.id===e),g=!!m&&JSON.stringify(m)!==JSON.stringify(u);return t.customisedCommandIds.includes(e)||g?p("customising"):p("oob")}const kS={oob:"Out of the box",customising:"Customised (unpublished)",customised:"Customised in your layer",uncustomising:"Uncustomised (unpublished)",custom:"Custom",reloadRequired:"Uncustomised — reload the table"};function Va(e){const t=M(d=>d.commands),n=M(d=>d.baselineCommands),o=M(d=>d.ribbons),s=M(d=>d.baseline),i=M(d=>d.layers),l=M(d=>d.customisedCommandIds),r=M(d=>d.uncustomisedCommandIds),c=M(d=>d.reloadRequiredCommandIds);return et.useMemo(()=>e&&t.some(d=>d.id===e)?TS(e,{commands:t,baselineCommands:n,ribbons:o,baseline:s,layers:i,customisedCommandIds:l,uncustomisedCommandIds:r,reloadRequiredCommandIds:c}):null,[e,t,n,o,s,i,l,r,c])}function gI(e){return e?.provenance==="oob"||e?.provenance==="uncustomising"||e?.provenance==="reloadRequired"}function AS({location:e,tabId:t,groupId:n,button:o,onDone:s}){const i=M(m=>m.customiseButton),l=M(m=>m.customiseCommand),r=ae(m=>m.activeSolution),c=ae(m=>m.publisherPrefix),d=J(m=>m.selectButtonInContext),u=Z(m=>m.openCommandEditor),p=Va(o.commandId||void 0);return a.jsxs(a.Fragment,{children:[o.origin!=="unmanaged"&&a.jsx(fe,{icon:a.jsx(Cm,{}),disabled:!_a(e,t,o),onClick:()=>{const m=r?.publisherPrefix?.trim()||c?.trim()||"new",g=i(e,t,n,o.id,m);g&&d(e,t,n,g),s()},children:"Customise button (copy, hide original)"}),p?.provenance==="oob"&&a.jsx(fe,{icon:a.jsx(On,{}),onClick:()=>{l(o.commandId)&&u(o.commandId),s()},children:"Customise command"})]})}const Bn=({open:e,title:t,children:n,confirmLabel:o,cancelLabel:s="Cancel",destructive:i=!1,onConfirm:l,onCancel:r})=>a.jsx(un,{open:e,onOpenChange:c=>!c&&r(),title:t,size:"small",modalType:"alert",actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:r,children:s}),i?a.jsx(Ga,{onClick:l,children:o}):a.jsx(K,{appearance:"primary",onClick:l,children:o})]}),children:n}),OS=me({body:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM},options:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS},description:{display:"block",color:h.colorNeutralForeground2,paddingLeft:"32px",marginTop:`-${h.spacingVerticalXS}`}}),su=({open:e,buttonLabel:t,buttonId:n,commandId:o,deleteBlockedReason:s,onConfirmHide:i,onConfirmDisplayRule:l,onCancel:r})=>{const c=OS(),d=Ee(),u=M(x=>x.locLabels),p=M(x=>x.ribbons),m=J(x=>x.location),g=o?Jc(p,o,n??"",x=>d(x.label,u,void 0,x.source?.labelToken),m):[],[b,f]=E.useState(o&&g.length===0?"rules":"button"),y=g.length===0?"No other button uses its command.":`Also hides ${g.length===1?"1 other button":`${g.length} other buttons`} that use${g.length===1?"s":""} its command: ${g.slice(0,4).join(", ")}${g.length>4?", …":""}.`;return a.jsx(un,{open:e,onOpenChange:x=>!x&&r(),size:"medium",title:s?`Can't delete "${t}"`:`Hide "${t}"?`,actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:r,children:"Cancel"}),a.jsx(K,{appearance:"primary",onClick:b==="rules"?l:i,children:"Hide button"})]}),children:a.jsxs("div",{className:c.body,children:[s&&a.jsxs(V,{children:[s," Only buttons your solution adds can be deleted; you can hide this one instead."]}),a.jsxs(Ci,{className:c.options,value:b,onChange:(x,S)=>f(S.value),"aria-label":"How to hide it",children:[a.jsxs("div",{children:[a.jsx(on,{value:"button",label:"Hide this button only"}),a.jsx(V,{size:200,className:c.description,children:"Removes it from this table's ribbon. Show it again under “Hidden by customizations” in Properties. Once a managed solution ships the hide, only a new version of that solution can bring it back."})]}),a.jsxs("div",{children:[a.jsx(on,{value:"rules",disabled:!o,label:"Hide it with display rules on its command"}),a.jsx(V,{size:200,className:c.description,children:o?`Adds two display rules to the command so it never shows. Easy to undo: remove the rules. ${y}`:"Not available: this button has no command."})]})]}),a.jsx(Dt,{size:"small",info:a.jsx(a.Fragment,{children:"“Hide this button only” adds a HideCustomAction to your customizations. The display rules are Mscrm.HideOnModern and Mscrm.ShowOnlyOnModern, which are never both true."}),children:"What each one writes"})]})})};function MS(e,t,n,o,s,i=He){const l=e.groups.filter(c=>c.id!==t&&!(n&&c.buttons.some(d=>d.id===n))).map(c=>({groupId:c.id,text:i(c.label,o,s,c.source?.titleToken).trim()||c.id})),r=new Map;for(const c of l)r.set(c.text,(r.get(c.text)??0)+1);return l.map(c=>(r.get(c.text)??0)>1&&c.text!==c.groupId?{...c,text:`${c.text} (${c.groupId})`}:c)}const DS=me({danger:{color:h.colorPaletteRedForeground1},note:{maxWidth:"280px",whiteSpace:"normal"}});function wo({location:e,tab:t,target:n,onClose:o}){const s=DS(),i=Ee(),l=M($=>$.locLabels),r=M($=>$.baseLanguageCode),c=M($=>$.baseline),d=M($=>$.setButtonProp),u=M($=>$.customizeOobButton),p=M($=>$.duplicateButton),m=M($=>$.moveButton),g=M($=>$.deleteButton),b=M($=>$.hideOobButton),f=J($=>$.selectButtonInContext),y=Z($=>$.openIconPicker),x=Z($=>$.openLocalizationEditor),[S,C]=E.useState(null),[N,O]=E.useState(null),I=$=>i($.label,l,void 0,$.source?.labelToken),j=n&&(()=>{const{button:$,groupId:w}=n,A=Da(e,t.id,$),B=dt($.kind),k=MS(t,w,$.id,l,r,i),v=T=>()=>{T(),o()};return a.jsxs(Xe,{open:!0,onOpenChange:(T,R)=>!R.open&&o(),positioning:{target:n.anchor,position:"below",align:"start"},children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Ye,{children:a.jsxs(Je,{"aria-label":`Actions for ${I($)}`,children:[A&&a.jsx(ro,{className:s.note,children:"Microsoft's global command bar buttons can't be changed."}),!A&&B&&a.jsxs(ro,{className:s.note,children:[yt[$.kind],": shown read-only. You can hide, move or delete it."]}),a.jsx(fe,{icon:a.jsx(Gl,{}),onClick:v(()=>f(e,t.id,w,$.id)),children:"Edit properties"}),a.jsx(fe,{icon:a.jsx(bi,{}),disabled:A||B,onClick:v(()=>{f(e,t.id,w,$.id),y()}),children:"Change icon…"}),a.jsx(fe,{icon:a.jsx(Im,{}),disabled:A||B,onClick:v(()=>x($.id)),children:"Edit labels…"}),a.jsx(Mt,{}),$.hidden?a.jsx(fe,{icon:a.jsx(Mn,{}),disabled:A,onClick:v(()=>d(e,t.id,w,$.id,{hidden:!1})),children:"Show button"}):a.jsx(fe,{icon:a.jsx(Et,{}),disabled:A,onClick:v(()=>$.oob?C(n):d(e,t.id,w,$.id,{hidden:!0})),children:$.oob?"Hide button…":"Hide button"}),($.origin==="oob"||$.origin==="managed")&&a.jsx(fe,{icon:a.jsx(ao,{}),disabled:A||B,onClick:v(()=>u(e,t.id,w,$.id)),children:"Create override…"}),a.jsx(AS,{location:e,tabId:t.id,groupId:w,button:$,onDone:o}),a.jsx(Mt,{}),a.jsx(fe,{icon:a.jsx(yo,{}),disabled:A,onClick:v(()=>p(e,t.id,w,$.id)),children:"Duplicate"}),k.length===0||A?a.jsx(fe,{icon:a.jsx(ar,{}),disabled:!0,secondaryContent:A?void 0:"No other groups",children:"Move to"}):a.jsxs(Xe,{children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(fe,{icon:a.jsx(ar,{}),children:"Move to"})}),a.jsx(Ye,{children:a.jsx(Je,{"aria-label":"Move to group",children:k.map(T=>a.jsx(fe,{onClick:v(()=>{const R=m({groupId:w,buttonId:$.id,tabId:t.id,location:e},{groupId:T.groupId,tabId:t.id,location:e});R&&f(e,t.id,T.groupId,R)}),children:T.text},T.groupId))})})]}),Cs($,c[e])&&a.jsxs(a.Fragment,{children:[a.jsx(Mt,{}),a.jsx(fe,{icon:a.jsx(Dn,{className:s.danger}),className:s.danger,disabled:A,onClick:v(()=>O(n)),children:"Delete…"})]})]})})]})})();return a.jsxs(a.Fragment,{children:[j,N&&a.jsxs(Bn,{open:!0,title:"Delete button",confirmLabel:"Delete button",destructive:!0,onConfirm:()=>{g(e,t.id,N.groupId,N.button.id),O(null)},onCancel:()=>O(null),children:["Delete “",I(N.button),"”? You can undo this until you publish."]}),S&&a.jsx(su,{open:!0,buttonLabel:I(S.button),buttonId:S.button.id,commandId:S.button.commandId,onConfirmHide:()=>{b(e,t.id,S.groupId,S.button.id),C(null)},onConfirmDisplayRule:()=>{M.getState().hideWithDisplayRules(S.button.commandId),C(null)},onCancel:()=>C(null)})]})}const iu=({open:e,initialLabel:t,onRename:n,onCancel:o,noun:s="group"})=>{const[i,l]=E.useState(t),r=i.trim(),c=()=>{r&&(r===t.trim()?o():n(r))};return a.jsx(un,{open:e,onOpenChange:d=>!d&&o(),size:"small",title:`Rename ${s}`,actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:o,children:"Cancel"}),a.jsx(K,{appearance:"primary",onClick:c,disabled:!r,children:"Rename"})]}),children:a.jsx(_e,{label:s==="tab"?"Tab title":"Group title",required:!0,validationState:r?"none":"error",validationMessage:r?void 0:`Enter a title for the ${s}.`,children:a.jsx(Ft,{value:i,onChange:(d,u)=>l(u.value),onKeyDown:d=>{d.key==="Enter"&&(d.preventDefault(),c())},"data-autofocus":!0})})})},ES=e=>e.replace(/^Mscrm\.Templates\./,""),BS=({open:e,currentTemplate:t,customTemplateIds:n=[],loadedGroup:o=!1,onChange:s,onCancel:i})=>{const l=ka(t),[r,c]=E.useState(l),d=[...new Set([...Bb,...n,l])],u=()=>{r===l?i():s(r)};return a.jsxs(un,{open:e,onOpenChange:p=>!p&&i(),size:"small",title:"Change group template",actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:i,children:"Cancel"}),a.jsx(K,{appearance:"primary",onClick:u,disabled:r===l,children:"Change template"})]}),children:[a.jsx(_e,{label:"Group template",hint:"How the group's buttons shrink when the classic ribbon is narrow. Unified Interface ignores it.",children:a.jsx(ya,{value:r,onChange:(p,m)=>c(m.value),children:d.map(p=>a.jsxs("option",{value:p,children:[ES(p),p===l?" (current)":""]},p))})}),o&&a.jsx(Rt,{intent:"warning",style:{marginTop:"12px"},children:a.jsx($t,{children:"This group was loaded from the environment. Publishing can't change an existing group's template yet (it's reported as not supported); groups you add publish theirs."})})]})};function LS(e){if(e instanceof HTMLElement)return e;const{x:t,y:n}=e;return{getBoundingClientRect:()=>({x:t,y:n,top:n,left:t,right:t,bottom:n,width:0,height:0,toJSON:()=>({})})}}function Xa({location:e,tab:t,target:n,onClose:o,moveLabels:s=["Move left","Move right"]}){const i=Ee(),l=M(A=>A.locLabels),r=M(A=>A.baseLanguageCode),c=M(A=>A.baseline),d=M(A=>A.layers),u=M(A=>A.templates),p=M(A=>A.duplicateGroup),m=M(A=>A.setGroupTemplate),g=M(A=>A.renameGroup),b=M(A=>A.deleteGroup),f=M(A=>A.moveGroup),y=M(A=>A.ribbons),x=Z(A=>A.openNewButton),[S,C]=E.useState(null),[N,O]=E.useState(null),[I,j]=E.useState(null);E.useEffect(()=>{n?.action==="rename"&&(C(n.group),o())},[n,o]);const $=A=>i(A.label,l,r,A.source?.titleToken)||A.id,w=n&&!n.action&&(()=>{const{group:A}=n,B=k=>()=>{k(),o()};return a.jsxs(Xe,{open:!0,onOpenChange:(k,v)=>!v.open&&o(),positioning:{position:"below",align:"start",target:LS(n.anchor)},children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Ye,{children:a.jsxs(Je,{"aria-label":`Actions for ${$(A)}`,children:[a.jsx(fe,{icon:a.jsx(ke,{}),onClick:B(()=>x(A.id)),children:"Add button…"}),Ei("group",A.id,c[e],po({layers:d},e))?a.jsx(fe,{icon:a.jsx(rr,{}),onClick:B(()=>C(A)),children:"Rename…"}):a.jsx(fe,{icon:a.jsx(rr,{}),disabled:!0,title:Fo,subText:"Only your own tabs and groups can be renamed",children:"Rename…"}),a.jsx(fe,{icon:a.jsx(yo,{}),onClick:B(()=>p(e,t.id,A.id)),children:"Duplicate group"}),a.jsx(fe,{icon:a.jsx(ao,{}),onClick:B(()=>O(A)),children:"Change template…"}),a.jsx(Mt,{}),[-1,1].map((k,v)=>{const T=Cd({ribbons:y,baseline:c,layers:d},e,t.id,A.id,k),R=t.groups,D=R.findIndex(X=>X.id===A.id),q=!R[D+k];return a.jsx(fe,{icon:k<0?a.jsx(jm,{}):a.jsx(Rm,{}),disabled:!T,subText:T||q?void 0:"Only groups your customizations add can change places",onClick:B(()=>f(e,t.id,A.id,k)),children:s[v]},k)}),Ea(A,c[e],jn({layers:d},e))&&a.jsxs(a.Fragment,{children:[a.jsx(Mt,{}),a.jsx(fe,{icon:a.jsx(Dn,{}),onClick:B(()=>j(A)),children:"Delete group"})]})]})})]})})();return a.jsxs(a.Fragment,{children:[w,S&&a.jsx(iu,{open:!0,initialLabel:He(S.label,l,r),onRename:A=>{g(e,t.id,S.id,A),C(null)},onCancel:()=>C(null)}),N&&a.jsx(BS,{open:!0,currentTemplate:N.template,customTemplateIds:u.map(A=>A.id),loadedGroup:c[e].tabs.some(A=>A.id===t.id&&A.groups.some(B=>B.id===N.id)),onChange:A=>{m(e,t.id,N.id,A),O(null)},onCancel:()=>O(null)}),I&&a.jsxs(Bn,{open:!0,title:"Delete group",confirmLabel:"Delete group",destructive:!0,onConfirm:()=>{b(e,t.id,I.id),j(null)},onCancel:()=>j(null),children:["Delete the group “",$(I),"” and its"," ",I.buttons.length," button",I.buttons.length===1?"":"s","?"]})]})}function au(e){const o=({columns:"layout_column_two",history:"clock_arrow_counterclockwise",window_dev_tools:"code_block"}[e.trim().toLowerCase()]??e).trim().replace(/_\d+_(regular|filled)$/i,"").replace(/_?(regular|filled)$/i,"").replace(/\d+(Regular|Filled)$/i,"").replace(/(Regular|Filled)$/i,"");return o?o.includes("_")?o.toLowerCase():o.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase():"apps_add_in"}const zS={new:ke,plus:ke,addexisting:ke,exporttoexcel:lc,tablegroup:Yl,flows:fr,process:fr,emaillink:Rh,sendbyemail:Xl,failedmail:vi,letter:vi,remove:ln,close:ln,abandon:ln,cancel:pr,cleardefault:pr,assign:jh,activate:jo,saveascomplete:jo,finishstage:jo,setdefault:jo,deactivate:Ih,reactivate:Kl,connection:Io,connect:Io,connectiontoother:Io,connectiontome:Io,addtoqueue:mr,bulletlistadd:mr,queueitemdetail:Ch,ratingempty:Bo,ratingfull:Bo,ratingfullgrey:Bo,report:yi,openinpowerbi:yi,wordtemplates:Es,documenttemplates:Es,applytemplate:Es,dynamics365:wh,formdesign:vh,msteamsicon:Sh,convert:ur,switchprocess:ur,viewhierarchy:xh,linkarticle:Zl,saveandclose:yh,saveandedit:rc,runroutingrule:dr,saveandrunroutingrule:dr,createquickcampaign:bh,pdficonfile:gh,mergerecords:hh,yammericon:cr,post:cr,opportunity:xi,opportunitieslist:xi,case:tc,deletebulk:Dn,foldertrack:ec,sadsmiley:fh,kbrecords:lr,insertkbarticle:lr,salesliterature:ph,follow:Mn,history:mh,contactcard:uh,flash:dh,pin:ch,multiselect:lh,browsecards:Jl,addmembers:rh,distributionlist:nc,health:ah,tools:ih,relationshipassistant:Vl,task:sh,appointment:oh},ru={add:{regular:ke,filled:nh},delete:{regular:Dn,filled:th},edit:{regular:Gl,filled:eh},save:{regular:rc,filled:Qf},copy:{regular:yo,filled:Zf},cut:{regular:Jf,filled:Yf},clipboardpaste:{regular:Kf,filled:Xf},share:{regular:Vf,filled:Uf},mail:{regular:vi,filled:Gf},chat:{regular:Hf,filled:Wf},phone:{regular:qf,filled:_f},search:{regular:Pl,filled:Ff},filter:{regular:ac,filled:Pf},arrowleft:{regular:zf,filled:Lf},arrowright:{regular:Bf,filled:Ef},arrowup:{regular:Df,filled:Mf},arrowdown:{regular:Of,filled:Af},chevrondown:{regular:it,filled:kf},chevronup:{regular:ic,filled:Tf},navigation:{regular:Nf,filled:$f},home:{regular:Rf,filled:jf},settings:{regular:If,filled:Cf},info:{regular:Si,filled:wf},warning:{regular:Fl,filled:vf},checkmark:{regular:sc,filled:Sf},dismiss:{regular:ln,filled:xf},questioncircle:{regular:ca,filled:yf},lockclosed:{regular:dn,filled:bf},lockopen:{regular:gf,filled:hf},shield:{regular:ff,filled:pf},person:{regular:oc,filled:mf},people:{regular:nc,filled:uf},personadd:{regular:df,filled:cf},building:{regular:lf,filled:rf},briefcase:{regular:tc,filled:af},money:{regular:xi,filled:sf},creditcard:{regular:of,filled:nf},cart:{regular:tf,filled:ef},tag:{regular:Qp,filled:Zp},document:{regular:us,filled:Jp},documentbulletlist:{regular:Yp,filled:Kp},folder:{regular:ec,filled:Xp},folderopen:{regular:Vp,filled:Up},attach:{regular:Gp,filled:Hp},arrowdownload:{regular:Wp,filled:qp},arrowupload:{regular:_p,filled:Fp},globe:{regular:Ql,filled:Pp},link:{regular:Zl,filled:zp},open:{regular:la,filled:Lp},calendar:{regular:Bp,filled:Ep},clock:{regular:Dp,filled:Mp},timer:{regular:Op,filled:Ap},star:{regular:Bo,filled:kp},heart:{regular:Tp,filled:Np},thumblike:{regular:$p,filled:Rp},thumbdislike:{regular:jp,filled:Ip},eye:{regular:Mn,filled:Cp},eyeoff:{regular:Et,filled:wp},zoomin:{regular:vp,filled:Sp},zoomout:{regular:xp,filled:yp},maximize:{regular:bp,filled:gp},minimize:{regular:hp,filled:fp},grid:{regular:Jl,filled:pp},list:{regular:mp,filled:up},table:{regular:da,filled:dp},tablesimple:{regular:Yl,filled:cp},code:{regular:On,filled:lp},bug:{regular:rp,filled:ap},play:{regular:ip,filled:sp},pause:{regular:op,filled:np},stop:{regular:tp,filled:ep},refresh:{regular:Kl,filled:Qm},arrowsync:{regular:Zm,filled:Jm},arrowundo:{regular:aa,filled:Ym},arrowredo:{regular:ra,filled:Km},printer:{regular:Xm,filled:Vm},send:{regular:Xl,filled:Um},rocket:{regular:Gm,filled:Hm},sparkle:{regular:Wm,filled:qm},trophy:{regular:_m,filled:Fm},lightbulb:{regular:Vl,filled:Pm},bot:{regular:zm,filled:Lm},databar:{regular:yi,filled:Bm},chartmultiple:{regular:Em,filled:Dm},poll:{regular:Mm,filled:Om},layoutcolumntwo:{regular:Am,filled:km},codeblock:{regular:Tm,filled:Nm},clockarrowcounterclockwise:{regular:Ul,filled:$m}},Ka=({name:e,size:t=20,variant:n="regular",style:o,className:s,"aria-hidden":i=!0})=>{const l=au(e).replace(/_/g,""),r=ru[l],c=(n==="filled"?r?.filled??r?.regular:r?.regular)??zS[l]??ao;return a.jsx(c,{fontSize:t,"aria-hidden":i,className:s,style:{display:"inline-block",verticalAlign:"middle",flexShrink:0,color:h.colorNeutralForeground1,...o}})};async function bI(e,t=32,n="regular"){const o=au(e).replace(/_/g,""),s=ru[o],i=n==="filled"?s?.filled??s?.regular:s?.regular;if(!i)return null;const{renderToStaticMarkup:l}=await ft(async()=>{const{renderToStaticMarkup:c}=await import("./server.browser-xEJRzS2D.js").then(d=>d.s);return{renderToStaticMarkup:c}},__vite__mapDeps([20,1,2]),import.meta.url);let r=l(et.createElement(i,{fontSize:t}));return r.includes("<svg")?(r.includes("xmlns")||(r=r.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),r=r.replace(/width="1em"/,`width="${t}"`).replace(/height="1em"/,`height="${t}"`),r=r.replace(/\s(?:class|aria-hidden|focusable|data-fui-icon|font-size)="[^"]*"/g,""),r):null}function lu(){return window.dataverseAPI}async function PS(){let e="the organization record has no languagecode";for(let t=0;t<2;t++)try{const o=(await lu().queryData("organizations?$select=languagecode")).value?.[0]?.languagecode;if(typeof o=="number")return o}catch(n){e=n instanceof Error?n.message:String(n)}throw new Error(`Couldn't read the organization's base language (${e}).`)}const FS=[/0x80071151/i,/\b80071151\b/i,/Cannot start (?:the requested operation \[\w+\]|another \[\w+\]) because there is (?:another|a previous) \[\w+\] running/i,/installation or removal of another solution at the same time/i];function _S(e){const t=e instanceof Error?`${e.message} ${String(e.code??"")}`:typeof e=="string"?e:JSON.stringify(e??"");return FS.some(n=>n.test(t))}const qS={0:"Import",1:"Uninstall",2:"Export",3:"Publish",4:"PublishAll",5:"LanguageProvision",6:"ImportTranslation",7:"RibbonMetadataGeneration",8:"WorkflowSetState",10:"ExportLite",11:"UpdatingMissingPackages"},cu=30;async function WS(e=cu,t=Date.now()){const n=t-e*6e4;try{return((await lu().queryData("msdyn_solutionhistories?$select=msdyn_name,msdyn_operation,msdyn_status,msdyn_starttime&$orderby=msdyn_starttime desc&$top=25")).value??[]).filter(s=>typeof s.msdyn_operation=="number"&&(s.msdyn_status===0||s.msdyn_status===2)&&s.msdyn_operation!==2&&s.msdyn_operation!==10&&(!s.msdyn_starttime||Date.parse(s.msdyn_starttime)>=n)).map(s=>({operation:qS[s.msdyn_operation??-1]??`operation ${s.msdyn_operation}`,name:s.msdyn_name??"",startedOn:s.msdyn_starttime??""}))}catch{return[]}}const du=e=>new Promise(t=>setTimeout(t,e)),ol=e=>e.map(t=>t.name&&t.name!==t.operation?`${t.operation} (${t.name})`:t.operation).join(", ");async function yI(e={}){const t=e.sleep??du,n=e.now??Date.now,o=n()+(e.timeoutMs??10*6e4);for(;;){const s=await WS(cu,n());if(s.length===0)return;if(n()>=o)throw new Error(`The environment is still busy (${ol(s)} running). Try again when it has finished — Solutions › History shows its progress.`);e.onProgress?.(`Waiting for another operation to finish: ${ol(s)}…`),await t(15e3)}}async function uu(e,t,n={}){const o=n.sleep??du,s=n.now??Date.now,i=s()+(n.timeoutMs??10*6e4);for(let l=0;;l++)try{return await t()}catch(r){if(!_S(r))throw r;const c=Math.min(6e4,15e3*2**l);if(s()+c>i)throw new Error(`${e} kept failing because another solution operation is running in the environment (${r instanceof Error?r.message:String(r)}). Try again when it has finished.`);n.onProgress?.(`${e}: another solution operation is running in the environment — retrying in ${Math.round(c/1e3)} s…`),await o(c)}}function Kt(){const e=window.dataverseAPI;if(!e)throw new Error("dataverseAPI is not available in the current runtime");return e}const mu={1:"html",2:"css",3:"js",4:"xml",5:"png",6:"jpg",7:"gif",8:"xap",9:"xsl",10:"ico",11:"svg",12:"resx"};function pu(e){return mu[e]??"xml"}async function HS(e,t){let n="webresourceset?$select=webresourceid,name,displayname,description,webresourcetype,modifiedon,ismanaged&$orderby=name asc";if(t!==void 0){const s=Object.entries(mu).find(([,i])=>i===t)?.[0];s&&(n+=`&$filter=webresourcetype eq ${s}`)}return(await e.queryData(n)).value.map(s=>{const i=s;return{id:String(i.webresourceid??""),name:String(i.name??""),displayName:i.displayname?String(i.displayname):void 0,description:i.description?String(i.description):void 0,webResourceType:pu(Number(i.webresourcetype??3)),modifiedOn:i.modifiedon?String(i.modifiedon):void 0,isCustom:i.ismanaged===!1}})}async function GS(e,t){const n=await e.retrieve("webresource",t,["content"]);return n.content?String(n.content):""}const fu=61;async function hu(e,t,n,o=ps){await o("Adding the web resource to the solution"),await e.execute({operationName:"AddSolutionComponent",operationType:"action",parameters:{ComponentId:t,ComponentType:fu,SolutionUniqueName:n,AddRequiredComponents:!1}})}class US extends Error{constructor(t){super(`Web resource ${t} already exists; it was left as it is.`),this.name="WebResourceSaveCancelled"}}async function VS(e,t,n,o,s={}){const i=s.guard??kc(),{displayName:l,solutionUniqueName:r,onExisting:c}=s;let d=s.keepExisting??!1;const u=await e.queryData(`webresourceset?$select=webresourceid,ismanaged&$filter=name eq '${t.replace(/'/g,"''")}'&$top=1`),p={name:t,content:n,webresourcetype:o,...l?{displayname:l}:{}};let m;if(u.value.length>0){const g=u.value[0],b=String(g.webresourceid??"");if(!d&&c){const f=g.ismanaged===!0,y=await c({id:b,name:t,managed:f});if(y==="cancel")throw new US(t);if(y==="replace"&&f)throw new Error(`A managed web resource named ${t} already exists, so it can't be replaced. Keep it, or rename the file and upload it again.`);d=y==="keep"}d||(await i("Saving the web resource"),await e.update("webresource",b,p)),m={id:b,created:!1,updated:!d}}else{await i("Saving the web resource");const g=await e.create("webresource",p);m={id:String(g.id??""),created:!0,updated:!1}}if(r&&m.id){try{await hu(e,m.id,r,i)}catch(g){throw new Error(`Web resource ${t} was saved but could not be added to solution ${r}: ${g instanceof Error?g.message:String(g)}`)}m.solutionUniqueName=r}return m}const sl=40,il=(e,t)=>Array.from({length:Math.ceil(e.length/t)},(n,o)=>e.slice(o*t,(o+1)*t)),XS=e=>`'${e.replace(/'/g,"''").replace(/[^A-Za-z0-9/._\-'~]/gu,t=>encodeURIComponent(t))}'`,al=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function KS(e,t,n){const o=t.map(c=>c.split(/[?#]/)[0].trim()).filter(Boolean),s=o.filter((c,d)=>o.findIndex(u=>u.toLowerCase()===c.toLowerCase())===d),i={};for(const c of s)i[c.toLowerCase()]={exists:!1,inSolution:!1};if(s.length===0)return i;const l=new Map;for(const c of il(s,sl)){const d=c.map(p=>`name eq ${XS(p)}`).join(" or "),u=await e.queryData(`webresourceset?$select=webresourceid,name,ismanaged&$filter=${d}`);for(const p of u.value??[]){const m=p,g=String(m.name??"").toLowerCase();if(!(g in i))continue;i[g]={exists:!0,inSolution:!1,managed:m.ismanaged===!0};const b=String(m.webresourceid??"").toLowerCase();al.test(b)&&l.set(b,g)}}const r=n?.replace(/[{}]/g,"");if(r&&al.test(r)&&l.size>0)for(const c of il([...l.keys()],sl)){const d=c.map(p=>`objectid eq ${p}`).join(" or "),u=await e.queryData(`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${r} and componenttype eq ${fu} and (${d})`);for(const p of u.value??[]){const m=l.get(String(p.objectid??"").toLowerCase());m&&(i[m].inSolution=!0)}}return i}async function xI(e,t){return KS(Kt(),e,t)}async function SI(e){return HS(Kt(),e)}async function vI(e){return GS(Kt(),e)}async function YS(e){const t=Kt(),n=e.replace(/'/g,"''"),o=await t.queryData(`webresourceset?$select=webresourceid,name,displayname,webresourcetype,ismanaged&$filter=name eq '${n}'&$top=1`);if(!o.value?.length)return null;const s=o.value[0];return{id:String(s.webresourceid??""),name:String(s.name??""),displayName:s.displayname?String(s.displayname):void 0,webResourceType:pu(Number(s.webresourcetype??3)),isCustom:s.ismanaged===!1}}async function JS(e,t,n,o={}){const s=ae.getState().activeSolution,i=o.solutionUniqueName??(s&&!s.isManaged?s.uniqueName:void 0),l=o.guard??kc(),r=await VS(Kt(),e,t,n,{...o,solutionUniqueName:i,guard:l});if((r.created||r.updated)&&o.publish!==!1)try{await uu(`Publishing web resource ${e}`,()=>gu(r.id,l),{timeoutMs:2*6e4,onProgress:c=>ce.getState().logInfo("webresource",c)}),r.published=!0}catch(c){r.publishWarning=`Web resource ${e} was saved but not published (${c instanceof Error?c.message:String(c)}). Users get the previous version until it's published: save it again, or run Publish All.`,ce.getState().logWarn("webresource",r.publishWarning)}if(!i){const c=s?`the active solution ${s.uniqueName} is managed`:"no solution is selected";r.solutionWarning=`Web resource ${e} was saved but not added to any solution because ${c}. It is only in the Default solution — select an unmanaged solution and save it again so it travels with your customizations.`,ce.getState().logWarn("webresource",r.solutionWarning)}return r}async function wI(e,t,n=ps){const o=t??await YS(e);if(!o?.id)throw new Error(`No web resource named ${e} exists in this environment.`);const s=o.id;if(o.isCustom===!1){const l=`Web resource ${e} is managed, so it isn't added to your solution. The solution that provides it must be installed wherever you import your customizations.`;return ce.getState().logWarn("webresource",l),{solutionWarning:l}}const i=ae.getState().activeSolution;if(!i||i.isManaged){const l=i?`the active solution ${i.uniqueName} is managed`:"no solution is selected",r=`Web resource ${e} was not added to any solution because ${l}. Select an unmanaged solution and pick the icon again so it travels with your customizations.`;return ce.getState().logWarn("webresource",r),{solutionWarning:r}}return await hu(Kt(),s,i.uniqueName,n),{solutionUniqueName:i.uniqueName}}async function gu(e,t=ps){const n=Kt(),o=`<importexportxml><webresources><webresource>${e}</webresource></webresources></importexportxml>`;await t("Publishing the web resource"),await n.execute({operationName:"PublishXml",operationType:"action",parameters:{ParameterXml:o}})}const ZS={5:"image/png",6:"image/jpeg",7:"image/gif",10:"image/x-icon",11:"image/svg+xml"};async function QS(e){const o=(await Kt().queryData(`webresourceset?$select=content,webresourcetype&$filter=name eq '${e.replace(/'/g,"''")}'&$top=1`)).value?.[0],s=ZS[Number(o?.webresourcetype)],i=o?.content;return s&&typeof i=="string"&&i?`data:${s};base64,${i}`:null}const ev=.35,hn=24,rl=new Map;function tv(e){return new Promise(t=>{const n=new Image;n.onload=()=>{try{const o=document.createElement("canvas");o.width=hn,o.height=hn;const s=o.getContext("2d");if(!s)return t("light");s.drawImage(n,0,0,hn,hn);const{data:i}=s.getImageData(0,0,hn,hn);let l=0,r=0;for(let c=0;c<i.length;c+=4){const d=i[c+3]/255;d<.5||(l+=d*(.2126*i[c]+.7152*i[c+1]+.0722*i[c+2]),r+=d*255)}t(r>0&&l/r<ev?"dark":"light")}catch{t("light")}},n.onerror=()=>t("light"),n.src=e})}function nv(e){let t=rl.get(e);return t||(t=tv(e),rl.set(e,t)),t}const ll="$webresource:",ov="invert(1) hue-rotate(180deg)",si=new Map,sv=6;let ii=0;const cl=[];async function iv(e){ii>=sv&&await new Promise(t=>cl.push(t)),ii++;try{return await e()}finally{ii--,cl.shift()?.()}}function av(e,t){let n=si.get(e);return n||(n=iv(()=>QS(t)).catch(()=>(si.delete(e),null)),si.set(e,n)),n}function rv(e){return[e.image32,e.image16,e.source?.modernImage].find(n=>n?.startsWith(ll))?.slice(ll.length).trim()||void 0}function xt({button:e,size:t,style:n}){const o=ae(m=>m.connectionUrl),s=Z(m=>m.themeMode==="dark"),i=rv(e),l=i?`${o}|${i}`:"",[r,c]=E.useState({key:"",src:null}),[d,u]=E.useState(null);E.useEffect(()=>{if(!l||!i)return;let m=!0;return av(l,i).then(g=>{m&&c({key:l,src:g})}),()=>{m=!1}},[l,i]);const p=l&&r.key===l?r.src:null;if(E.useEffect(()=>{if(!s||!p)return;let m=!0;return nv(p).then(g=>{m&&u({src:p,tone:g})}),()=>{m=!1}},[s,p]),p){const g=[s&&d?.src===p&&d.tone==="dark"&&ov,n?.filter!=="none"&&n?.filter].filter(Boolean).join(" ")||void 0;return a.jsx("img",{src:p,width:t,height:t,alt:"","aria-hidden":!0,style:{objectFit:"contain",...n,filter:g}})}return a.jsx(Ka,{name:e.icon||"apps_add_in",size:t,style:n})}const bu="__end__";function lv(e,t){return`slot::${e}::${t??bu}`}function cv(e){return`group::${e}`}function dl(e){if(e.startsWith("slot::")){const[,t,n]=e.split("::");return{kind:"slot",groupId:t,beforeButtonId:n===bu?null:n}}return e.startsWith("group::")?{kind:"group",groupId:e.slice(7)}:null}const gn={root:{display:"flex",gap:h.spacingHorizontalM,flexWrap:"wrap",alignItems:"flex-start",minHeight:"120px",padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`},groupButtons:{display:"flex",gap:h.spacingHorizontalXS,flexWrap:"wrap",minHeight:"72px",alignItems:"flex-start",padding:h.spacingHorizontalXS},groupLabel:{textAlign:"center",fontSize:h.fontSizeBase100,color:h.colorNeutralForeground3,borderTop:`1px solid ${h.colorNeutralStroke2}`,paddingTop:h.spacingVerticalXS,paddingBottom:h.spacingVerticalXS,marginTop:"auto"},emptyTab:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:h.spacingVerticalM,minHeight:"160px",color:h.colorNeutralForeground3,flex:1,padding:"48px",textAlign:"center"},addGroupBtn:{minHeight:"96px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",border:`1px dashed ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusMedium,cursor:"pointer",color:h.colorNeutralForeground3,backgroundColor:"transparent"},addButtonGhost:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",width:"60px",minHeight:"72px",borderRadius:h.borderRadiusMedium,border:`1px dashed ${h.colorNeutralStroke2}`,backgroundColor:"transparent",cursor:"pointer",color:h.colorNeutralForeground3}};function dv({button:e}){const t=M(s=>s.locLabels),o=Ee()(e.label,t,void 0,e.source?.labelToken);return a.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:h.borderRadiusMedium,border:`1px solid ${h.colorBrandStroke1}`,backgroundColor:h.colorNeutralBackground1,boxShadow:h.shadow16,opacity:.9,cursor:"grabbing",pointerEvents:"none",color:e.custom?h.colorBrandForeground1:h.colorNeutralForeground1},children:[a.jsx(xt,{button:e,size:24}),a.jsx("span",{style:{fontSize:h.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:h.colorNeutralForeground1},children:o})]})}function uv({group:e,isDropTarget:t,children:n,...o}){const{setNodeRef:s,isOver:i}=Ca({id:cv(e.id),data:{type:"group",groupId:e.id}});return a.jsx("div",{ref:s,style:{display:"flex",flexDirection:"column",minWidth:"80px",border:`1px solid ${i||t?h.colorBrandStroke1:h.colorNeutralStroke2}`,borderRadius:h.borderRadiusMedium,backgroundColor:i||t?h.colorBrandBackground2:h.colorNeutralBackground2,padding:`${h.spacingVerticalXS} ${h.spacingHorizontalXS}`,transition:"border-color 0.1s, background-color 0.1s"},...o,children:n})}function ul({groupId:e,beforeButtonId:t}){const n=lv(e,t),{setNodeRef:o,isOver:s}=Ca({id:n,data:{type:"slot",groupId:e,beforeButtonId:t}});return a.jsx("div",{ref:o,style:{width:s?"2px":"0px",minHeight:"72px",backgroundColor:h.colorBrandStroke1,borderRadius:"2px",flexShrink:0,transition:"width 0.1s"},"aria-hidden":!0})}function mv({tab:e,location:t}){const n=M(w=>w.locLabels),o=Ee(),s=M(w=>w.baseLanguageCode),i=w=>o(w.label,n,s,w.source?.titleToken)||w.id,l=M(w=>w.moveButton),r=M(w=>w.createGroup),c=Z(w=>w.openNewButton),d=Z(w=>w.openNewGroup),u=J(w=>w.selectButtonInContext),p=J(w=>w.selectGroup),[m,g]=E.useState(null),[b,f]=E.useState(null),[y,x]=E.useState(null),[S,C]=E.useState(null),N=E.useMemo(()=>{if(!y)return null;for(const w of e.groups){const A=w.buttons.find(B=>B.id===y);if(A)return{button:A,groupId:w.id}}return null},[y,e.groups]),O=Cc(Go(Nc,{activationConstraint:{distance:5}}),Go($c));function I(w){x(String(w.active.id))}function j(w){const A=w.over;if(!A){C(null);return}const B=dl(String(A.id));C(B?B.groupId:null)}function $(w){const{active:A,over:B}=w;if(x(null),C(null),!B||!A)return;let k=null;for(const R of e.groups)if(R.buttons.some(D=>D.id===A.id)){k=R.id;break}if(!k)return;const v=dl(String(B.id));if(!v)return;let T=null;v.kind==="slot"?T=l({groupId:k,buttonId:String(A.id),tabId:e.id,location:t},{groupId:v.groupId,beforeButtonId:v.beforeButtonId??void 0,tabId:e.id,location:t}):v.kind==="group"&&v.groupId!==k&&(T=l({groupId:k,buttonId:String(A.id),tabId:e.id,location:t},{groupId:v.groupId,tabId:e.id,location:t})),T&&T!==String(A.id)&&u(t,e.id,v.groupId,T)}return e.groups.length===0?a.jsxs("div",{style:gn.emptyTab,children:[a.jsx(us,{fontSize:36,"aria-hidden":!0}),a.jsx(V,{children:"This tab has no groups yet"}),a.jsxs("button",{type:"button",style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 16px",background:h.colorBrandBackground,color:h.colorNeutralForegroundInverted,border:"none",borderRadius:h.borderRadiusMedium,cursor:"pointer",fontSize:h.fontSizeBase300},onClick:()=>d(),children:[a.jsx(ke,{fontSize:12})," Add first group"]})]}):a.jsxs(a.Fragment,{children:[t==="SubGrid"&&a.jsx(Rt,{intent:"info",style:{margin:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`},children:a.jsxs($t,{children:["Subgrid ribbons support only 3 native controls: ",a.jsx("strong",{children:"Add"}),","," ",a.jsx("strong",{children:"Show List"}),", and ",a.jsx("strong",{children:"Delete"}),". Their icons cannot be changed."]})}),a.jsxs(Ic,{sensors:O,collisionDetection:jc,onDragStart:I,onDragOver:j,onDragEnd:$,children:[a.jsxs("div",{style:gn.root,role:"treegrid","aria-label":"Ribbon canvas","data-ribbon-canvas-root":"1",children:[e.groups.map(w=>a.jsxs(uv,{group:w,isDropTarget:S===w.id,role:"rowgroup","aria-label":i(w),tabIndex:0,"data-ribbon-group-id":w.id,onContextMenu:A=>{A.target.closest("[data-btn]")||(A.preventDefault(),f({group:w,anchor:{x:A.clientX,y:A.clientY}}))},onFocus:()=>p(w.id),onKeyDown:A=>{if((A.key==="Enter"||A.key===" ")&&w.buttons.length>0){A.preventDefault();const B=w.buttons[0];if(!B)return;u(t,e.id,w.id,B.id),document.querySelector(`[data-ribbon-btn-id="${B.id}"]`)?.focus()}},children:[a.jsxs("div",{style:gn.groupButtons,children:[w.buttons.map(A=>a.jsxs(et.Fragment,{children:[y&&a.jsx(ul,{groupId:w.id,beforeButtonId:A.id}),a.jsx(pv,{button:A,groupId:w.id,tabId:e.id,location:t,activeId:y,onContextMenu:B=>g({groupId:w.id,button:A,anchor:B.currentTarget})})]},A.id)),y&&a.jsx(ul,{groupId:w.id,beforeButtonId:null}),a.jsxs("button",{type:"button",style:gn.addButtonGhost,"data-add-btn-group-id":w.id,onClick:()=>c(w.id),title:`Add button to ${i(w)}`,"aria-label":`Add button to ${i(w)}`,children:[a.jsx(ke,{fontSize:16}),a.jsx(V,{size:100,style:{color:"inherit"},children:"Add"})]})]}),a.jsx(pe,{content:`Template: ${w.template||"Flexible2"}`,relationship:"description",children:a.jsx("div",{style:gn.groupLabel,children:i(w)})})]},w.id)),a.jsx("button",{type:"button",style:gn.addGroupBtn,onClick:()=>r({tabId:e.id,location:t,group:{label:"New Group",sequence:(e.groups.length+1)*10,template:"Flexible2",buttons:[]}}),title:"Add group","aria-label":"Add group",children:a.jsx(ke,{fontSize:16})})]}),a.jsx(Rc,{dropAnimation:null,children:N?a.jsx(dv,{button:N.button}):null})]}),a.jsx(wo,{location:t,tab:e,target:m,onClose:()=>g(null)}),a.jsx(Xa,{location:t,tab:e,target:b,onClose:()=>f(null)})]})}const pv=et.memo(function({button:t,groupId:n,tabId:o,location:s,activeId:i,onContextMenu:l}){const r=J(j=>j.selectedButtonId),c=J(j=>j.selectButtonInContext),d=M(j=>j.locLabels),u=Ee(),p=r===t.id,m=s==="Application"&&o==="Mscrm.GlobalTab"&&t.oob&&!t.custom,g=u(t.label,d,void 0,t.source?.labelToken),b=dt(t.kind)?yt[t.kind]:void 0,f=b?` (${b}, read-only)`:"",{attributes:y,listeners:x,setNodeRef:S,isDragging:C}=Ng({id:t.id,data:{type:"button",button:t,groupId:n},disabled:t.managed||m}),N=C||i===t.id,O={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:h.borderRadiusMedium,cursor:"grab",border:p?`1px solid ${h.colorBrandStroke1}`:t.custom?`1px solid ${h.colorBrandStroke2}`:"1px solid transparent",backgroundColor:p?h.colorBrandBackground2:t.managed?h.colorNeutralBackground3:"transparent",opacity:N?.3:t.hidden?.4:1,position:"relative",userSelect:"none",color:t.custom?h.colorBrandForeground1:h.colorNeutralForeground1,transition:"opacity 0.15s, border-color 0.1s, background-color 0.1s"},I=j=>{if(!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(j.key))return;j.preventDefault();const $=j.currentTarget.closest("[data-ribbon-canvas-root='1']");if(!$)return;const w=Array.from($.querySelectorAll(`[data-ribbon-tab-id="${o}"][data-btn="1"]`)),A=w.findIndex(D=>D.dataset.ribbonBtnId===t.id);if(A<0||w.length===0)return;const B=j.key==="ArrowLeft"||j.key==="ArrowUp"?-1:1,k=Math.max(0,Math.min(w.length-1,A+B)),v=w[k],T=v?.dataset.ribbonGroupId,R=v?.dataset.ribbonBtnId;!v||!T||!R||(c(s,o,T,R),v.focus())};return a.jsx(pe,{content:m?"OOB global command bar buttons cannot be customized.":`${g}${f}${t.hidden?" — hidden":""}`,relationship:"label",children:a.jsxs("button",{ref:S,type:"button","data-btn":"1","data-ribbon-tab-id":o,"data-ribbon-group-id":n,"data-ribbon-btn-id":t.id,style:O,"aria-selected":p,"aria-label":`${g}${f}${t.hidden?" — hidden":""}${t.custom?" (custom)":""}${t.managed?" (read-only)":""}`,onClick:()=>c(s,o,n,t.id),onFocus:()=>c(s,o,n,t.id),onKeyDown:j=>{if(j.key==="Enter"||j.key===" "){j.preventDefault(),c(s,o,n,t.id);return}I(j)},onContextMenu:j=>{j.preventDefault(),j.stopPropagation(),c(s,o,n,t.id),l(j)},...y,...x,children:[a.jsx(xt,{button:t,size:24,style:{filter:t.custom?"none":"grayscale(40%) opacity(0.85)"}}),a.jsx("span",{style:{fontSize:h.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:h.colorNeutralForeground1},children:g}),b&&a.jsx("span",{style:{fontSize:h.fontSizeBase100,lineHeight:"1",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:h.colorNeutralForeground3},children:b}),t.menu&&a.jsx(it,{fontSize:10,"aria-label":"Has a menu"}),t.hidden&&a.jsx("span",{style:{position:"absolute",top:2,right:2},"aria-hidden":!0,children:a.jsx(Et,{fontSize:10,style:{color:h.colorNeutralForeground3}})}),t.custom&&!t.managed&&a.jsx(pe,{content:"Yours: added by your customizations",relationship:"label",children:a.jsx(xe,{size:"extra-small",color:"brand",style:{position:"absolute",bottom:4,right:4}})}),(t.managed||m)&&a.jsx("span",{style:{position:"absolute",top:2,left:2},title:m?"OOB global command bar buttons cannot be customized.":"Read-only (managed)",children:a.jsx(dn,{fontSize:10,style:{color:h.colorNeutralForeground3}})})]})})});function fv(e,t,n){if(!t.buttonId||n.groupId===t.groupId&&n.buttonId===t.buttonId)return null;const o=e.find(r=>r.id===n.groupId);if(!o)return null;const s=pt(o.buttons);if(!n.buttonId)return o.id===t.groupId&&s.at(-1)?.id===t.buttonId?null:{groupId:o.id};const i=s.findIndex(r=>r.id===n.buttonId);if(i<0)return null;const l=o.id===t.groupId?s.findIndex(r=>r.id===t.buttonId):-1;if(l>=0&&l<i){const r=s[i+1]?.id;return r?{groupId:o.id,before:r}:{groupId:o.id}}return{groupId:o.id,before:n.buttonId}}const Ya=me({root:{display:"flex",flexWrap:"wrap",alignItems:"flex-start",gap:h.spacingHorizontalM},card:{flex:"1 1 240px",minWidth:"220px",maxWidth:"320px",display:"flex",flexDirection:"column",backgroundColor:h.colorNeutralBackground1,border:`1px solid ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusLarge,boxShadow:h.shadow2,minHeight:0},cardSelected:{border:`1px solid ${h.colorBrandStroke1}`},cardOver:{backgroundColor:h.colorBrandBackground2},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalXS} ${h.spacingVerticalXS} ${h.spacingHorizontalM}`,borderBottom:`1px solid ${h.colorNeutralStroke3}`},titleButton:{flex:1,minWidth:0,display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",padding:0,fontWeight:"inherit",textAlign:"left"},ellipsis:{display:"block",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:h.colorNeutralForeground3},rows:{display:"flex",flexDirection:"column",padding:h.spacingVerticalXS,gap:"2px",minHeight:"8px"},row:{display:"flex",alignItems:"center",justifyContent:"flex-start",gap:h.spacingHorizontalS,width:"100%",maxWidth:"100%",minWidth:0,minHeight:"32px",padding:`0 ${h.spacingHorizontalS}`,fontWeight:h.fontWeightRegular,textAlign:"left"},rowSelected:{backgroundColor:h.colorSubtleBackgroundSelected,border:`1px solid ${h.colorBrandStroke1}`},rowHidden:{color:h.colorNeutralForeground3},handle:{color:h.colorNeutralForeground3,flexShrink:0},handleOff:{visibility:"hidden"},label:{flex:1,minWidth:0},footer:{padding:`0 ${h.spacingHorizontalXS} ${h.spacingVerticalXS}`},overlay:{boxShadow:h.shadow16,backgroundColor:h.colorNeutralBackground1,borderRadius:h.borderRadiusMedium}}),hv=e=>{const t=e.droppableContainers.filter(i=>String(i.id).startsWith("row:")),n=e.droppableContainers.filter(i=>String(i.id).startsWith("card:"));if(e.pointerCoordinates){const i=vr({...e,droppableContainers:t});if(i.length)return i;const l=vr({...e,droppableContainers:n});if(l.length)return l}const o=new Set(t.map(i=>i.data.current?.groupId)),s=n.filter(i=>!o.has(i.data.current?.groupId));return jc({...e,droppableContainers:[...t,...s]})},Ja=(e,t)=>`row:${e}:${t}`,yu=e=>`card:${e}`;function gv({tab:e,location:t}){const n=Ya(),o=Ee(),s=M(v=>v.locLabels),i=M(v=>v.baseLanguageCode),l=M(v=>v.moveButton),r=J(v=>v.selectedGroupId),c=J(v=>v.selectedButtonId),d=J(v=>v.selectGroup),u=J(v=>v.selectButtonInContext),p=Z(v=>v.openNewButton),[m,g]=E.useState(null),[b,f]=E.useState(null),[y,x]=E.useState(null),[S,C]=E.useState(null),N=E.useRef(null),O=v=>o(v.label,s,i,v.source?.titleToken)||v.id,I=v=>o(v.label,s,void 0,v.source?.labelToken)||v.id,j=Cc(Go(Nc,{activationConstraint:{distance:5}}),Go($c,{coordinateGetter:Tg,keyboardCodes:{start:["Space"],cancel:["Escape"],end:["Space","Enter"]}})),$=v=>setTimeout(()=>{if(document.activeElement?.closest('[role="dialog"], [role="alertdialog"]'))return;const T=J.getState().selectedButtonId;(v instanceof HTMLElement&&v.isConnected?v:[...N.current?.querySelectorAll("[data-card-button]")??[]].find(D=>D.dataset.cardButton===T))?.focus()}),w=v=>{const T=String(v??"");for(const R of e.groups){if(T===yu(R.id))return`the end of ${O(R)}`;const D=R.buttons.find(q=>T===Ja(R.id,q.id));if(D)return`${I(D)} in ${O(R)}`}return""},A=v=>v&&typeof v=="object"&&"groupId"in v?v:null,B=v=>{const T=A(v.active.data.current),R=e.groups.find(q=>q.id===T?.groupId),D=R?.buttons.find(q=>q.id===T?.buttonId);R&&D&&x({button:D,groupId:R.id})},k=v=>{x(null),C(null);const T=A(v.active.data.current),R=A(v.over?.data.current);if(!T?.buttonId||!R)return;const D=fv(e.groups,T,R);if(!D)return;const q=l({location:t,tabId:e.id,groupId:T.groupId,buttonId:T.buttonId},{location:t,tabId:e.id,groupId:D.groupId,beforeButtonId:D.before});q&&(u(t,e.id,D.groupId,q),setTimeout(()=>[...N.current?.querySelectorAll("[data-card-button]")??[]].find(X=>X.dataset.cardButton===q)?.focus()))};return a.jsxs(a.Fragment,{children:[a.jsxs(Ic,{sensors:j,collisionDetection:hv,onDragStart:B,onDragOver:v=>C(A(v.over?.data.current)?.groupId??null),onDragEnd:k,onDragCancel:()=>{x(null),C(null)},accessibility:{screenReaderInstructions:{draggable:"To move a button, press Space. Use the arrow keys to move it, Space or Enter to drop it, Escape to cancel."},announcements:{onDragStart:({active:v})=>`Picked up ${w(v.id)}.`,onDragOver:({active:v,over:T})=>T?`${w(v.id)} is over ${w(T.id)}.`:void 0,onDragEnd:({active:v,over:T})=>T?`${w(v.id)} was dropped on ${w(T.id)}.`:`${w(v.id)} was dropped.`,onDragCancel:({active:v})=>`Moving ${w(v.id)} was cancelled.`}},children:[a.jsx("div",{ref:N,className:n.root,"aria-label":`Groups of ${e.id}`,role:"list",children:pt(e.groups).map(v=>a.jsx(bv,{group:v,tab:e,location:t,title:O(v),buttonText:I,selected:r===v.id&&!c,selectedButtonId:r===v.id?c:null,dropping:S===v.id&&!!y,onSelectGroup:()=>d(v.id),onSelectButton:T=>u(t,e.id,v.id,T.id),onGroupMenu:T=>g({group:v,anchor:T}),onButtonMenu:(T,R)=>f({button:T,groupId:v.id,anchor:R}),onAddButton:()=>p(v.id)},v.id))}),a.jsx(Rc,{dropAnimation:null,children:y&&a.jsxs("div",{className:Ie(n.row,n.overlay),children:[a.jsx(cc,{className:n.handle}),a.jsx(xt,{button:y.button,size:16}),a.jsx("span",{className:Ie(n.label,n.ellipsis),children:I(y.button)})]})})]}),a.jsx(Xa,{location:t,tab:e,target:m,onClose:()=>{$(m?.anchor),g(null)}}),a.jsx(wo,{location:t,tab:e,target:b,onClose:()=>{$(b?.anchor),f(null)}})]})}function bv({group:e,tab:t,location:n,title:o,buttonText:s,selected:i,selectedButtonId:l,dropping:r,onSelectGroup:c,onSelectButton:d,onGroupMenu:u,onButtonMenu:p,onAddButton:m}){const g=Ya(),{setNodeRef:b}=Ca({id:yu(e.id),data:{groupId:e.id}}),f=pt(e.buttons);return a.jsxs("section",{ref:b,role:"listitem","aria-label":o,"data-group-card":e.id,className:Ie(g.card,i&&g.cardSelected,r&&g.cardOver),children:[a.jsxs("div",{className:g.header,children:[a.jsx(pe,{content:`${o} (${e.id})`,relationship:"description",children:a.jsxs(K,{appearance:"transparent",className:g.titleButton,"aria-pressed":i,onClick:c,onContextMenu:y=>{y.preventDefault(),u(y.currentTarget)},onKeyDown:y=>{(y.key==="ContextMenu"||y.shiftKey&&y.key==="F10")&&(y.preventDefault(),u(y.currentTarget))},children:[a.jsx(V,{weight:"semibold",size:300,className:g.ellipsis,children:o}),a.jsx(V,{size:200,className:Ie(g.ellipsis,g.muted),children:e.template||"Flexible2"})]})}),a.jsx(pe,{content:"Group options",relationship:"label",children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(dc,{}),"aria-label":`Group options: ${o}`,onClick:y=>u(y.currentTarget)})})]}),a.jsx(kg,{items:f.map(y=>Ja(e.id,y.id)),strategy:Ag,children:a.jsx("div",{className:g.rows,role:"list","aria-label":`Buttons in ${o}`,children:f.map(y=>a.jsx(yv,{button:y,groupId:e.id,text:s(y),locked:y.managed||Da(n,t.id,y),selected:l===y.id,onSelect:()=>d(y),onMenu:x=>p(y,x)},y.id))})}),a.jsx("div",{className:g.footer,children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:m,"aria-label":`Add button to ${o}`,children:"Add button"})})]})}function yv({button:e,groupId:t,text:n,locked:o,selected:s,onSelect:i,onMenu:l}){const r=Ya(),{attributes:c,listeners:d,setNodeRef:u,transform:p,transition:m,isDragging:g}=Og({id:Ja(t,e.id),data:{groupId:t,buttonId:e.id},disabled:{draggable:o,droppable:!1}}),b=e.custom&&!e.managed,f=dt(e.kind)?yt[e.kind]:void 0,y=`${n}${f?` (${f}, read-only)`:""}${e.hidden?", hidden":""}${b?", yours":""}, Sequence ${e.sequence}`;return a.jsx("div",{role:"listitem",style:{opacity:g?.4:1},children:a.jsx(pe,{content:`${n} (${e.id})`,relationship:"description",children:a.jsxs(K,{ref:u,appearance:"subtle",...c,...d,"aria-roledescription":o?void 0:"draggable button","aria-label":y,"aria-pressed":s,"data-card-button":e.id,className:Ie(r.row,s&&r.rowSelected,e.hidden&&r.rowHidden),style:{transform:Mg.Transform.toString(p),transition:m},onClick:i,onContextMenu:x=>{x.preventDefault(),l(x.currentTarget)},onKeyDown:x=>{if(x.key==="ContextMenu"||x.shiftKey&&x.key==="F10"){x.preventDefault(),l(x.currentTarget);return}d?.onKeyDown?.(x)},children:[a.jsx(cc,{"aria-hidden":!0,className:Ie(r.handle,o&&r.handleOff)}),a.jsx(xt,{button:e,size:16}),a.jsx("span",{className:Ie(r.label,r.ellipsis),children:n}),e.hidden?a.jsx(xe,{size:"medium",appearance:"outline",color:"subtle",children:"Hidden"}):b?a.jsx(xe,{size:"medium",appearance:"tint",color:"brand",children:"Yours"}):null,a.jsx(V,{size:200,className:r.muted,children:e.sequence})]})})})}const Kn={Form:0,MainGrid:1,SubGrid:2,AssociatedGrid:3,GlobalHeader:5},xv={0:"Form",1:"Main grid",2:"Subgrid",3:"Associated grid",4:"Quick form",5:"Global header",6:"Dashboard"},xu="appaction_appactionrule_classicrules",Sv=["appactionid","name","uniquename","buttonlabeltext","buttontooltiptitle","buttontooltipdescription","buttonaccessibilitytext","_appmoduleid_value","context","_contextentity_value","contextvalue","location","type","sequence","buttonsequencepriority","hidden","isdisabled","origin","ismanaged","fonticon","_iconwebresourceid_value","_parentappactionid_value","grouptitle","isgrouptitlehidden","onclickeventtype","onclickeventjavascriptfunctionname","onclickeventjavascriptparameters","_onclickeventjavascriptwebresourceid_value","onclickeventformulacomponentlibrary","onclickeventformulacomponentname","onclickeventformulafunctionname","visibilitytype","visibilityformulacomponentlibrary","visibilityformulacomponentname","visibilityformulafunctionname"],ai="@OData.Community.Display.V1.FormattedValue",De=e=>typeof e=="string"&&e.trim()!==""?e:typeof e=="number"?String(e):void 0,Ot=e=>{if(e==null||e==="")return;const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0},Ao=e=>e===!0||e===1||e==="true"||e==="1",tn=e=>{const t=De(e);return t?t.toLowerCase():null};function vv(e){switch(Ot(e)){case 1:return"dropdown";case 2:return"split";case 3:return"group";default:return"button"}}function wv(e){const t=Ot(e);return t===1?"formula":t===2?"javascript":"none"}function Cv(e){const t=Ot(e);return t===1?"formula":t===2?"classicRules":"none"}function Iv(e){const t=Ot(e);return t===1?"migrated":t===2?"enhancedMigrated":"default"}function ml(e,t){const n={componentLibrary:De(e[`${t}componentlibrary`]),componentName:De(e[`${t}componentname`]),functionName:De(e[`${t}functionname`])};return n.componentLibrary||n.componentName||n.functionName?n:void 0}function jv(e){return Array.isArray(e)?e.map(t=>{const n=tn(t.appactionruleid);return n?{id:n,name:De(t.name)??De(t.uniquename)??n,uniqueName:De(t.uniquename),kind:Ot(t.type)===0?"enable":"display"}:null}).filter(t=>t!==null):[]}function Rv(e){const t=tn(e.appactionid);if(!t)return null;const n=Ot(e.location);if(n===void 0)return null;const o=De(e.name)??"",s=De(e.uniquename)??o;return{id:t,name:o,uniqueName:s,label:De(e.buttonlabeltext)??(o||s||t),tooltipTitle:De(e.buttontooltiptitle),tooltipDescription:De(e.buttontooltipdescription),accessibilityText:De(e.buttonaccessibilitytext),appModuleId:tn(e._appmoduleid_value),appName:De(e[`_appmoduleid_value${ai}`]),scope:Ot(e.context)===0?"all":"entity",contextValue:De(e.contextvalue),contextEntityId:tn(e._contextentity_value)??void 0,location:n,type:vv(e.type),sequence:Ot(e.sequence)??Ot(e.buttonsequencepriority)??0,hidden:Ao(e.hidden),disabled:Ao(e.isdisabled),origin:Iv(e.origin),managed:Ao(e.ismanaged),fontIcon:De(e.fonticon),iconWebResourceId:tn(e._iconwebresourceid_value)??void 0,iconWebResourceName:De(e[`_iconwebresourceid_value${ai}`]),parentId:tn(e._parentappactionid_value),groupTitle:De(e.grouptitle),groupTitleHidden:Ao(e.isgrouptitlehidden),action:wv(e.onclickeventtype),jsFunctionName:De(e.onclickeventjavascriptfunctionname),jsParameters:De(e.onclickeventjavascriptparameters),jsWebResourceId:tn(e._onclickeventjavascriptwebresourceid_value)??void 0,jsWebResourceName:De(e[`_onclickeventjavascriptwebresourceid_value${ai}`]),onSelectFormula:ml(e,"onclickeventformula"),visibility:Cv(e.visibilitytype),visibilityFormula:ml(e,"visibilityformula"),classicRules:jv(e[xu])}}function $v(e){const t=new Map;for(const n of e){const o=Rv(n);o&&!t.has(o.id)&&t.set(o.id,o)}return[...t.values()]}function Nv(e){switch(e){case"HomepageGrid":return[Kn.MainGrid];case"SubGrid":return[Kn.SubGrid,Kn.AssociatedGrid];case"Form":return[Kn.Form];case"Application":return[Kn.GlobalHeader]}}function Tv(e,t){if(e.scope==="all")return!0;const n=t.metadataId?.toLowerCase();return n&&e.contextEntityId===n?!0:!!e.contextValue&&e.contextValue.toLowerCase()===t.logicalName.toLowerCase()}function kv(e,t){return t==="all"||e.appModuleId===null||e.appModuleId===t.toLowerCase()}function Av(e,t){const n=new Set(Nv(t.location));return e.filter(o=>n.has(o.location)&&kv(o,t.appFilter)&&Tv(o,t.table))}const Ji=(e,t)=>e.sequence-t.sequence||e.label.localeCompare(t.label)||e.id.localeCompare(t.id);function Su(e){const t=new Set(e.map(l=>l.id)),n=new Map,o=[];for(const l of e)if(l.parentId&&l.parentId!==l.id&&t.has(l.parentId)){const r=n.get(l.parentId)??[];r.push(l),n.set(l.parentId,r)}else o.push(l);const s=new Set,i=l=>{s.add(l.id);const r=(n.get(l.id)??[]).filter(c=>!s.has(c.id)).sort(Ji);return{command:l,children:r.map(i)}};return o.sort(Ji).map(i)}function vu(e){return e.flatMap(t=>[t.command,...vu(t.children)])}const wu=/\{!EntityLogicalName\}/gi,Ov=/(?:![A-Za-z0-9_]+)*!\d+$/;function Mv(e,t){if(e.origin==="default")return[];const n=[],o=s=>{s.includes(".")&&!n.includes(s)&&n.push(s)};for(const s of[e.uniqueName,e.name]){if(!s)continue;const i=s.trim().replace(wu,t).replace(Ov,""),l=i.indexOf("_"),r=i.indexOf(".");l>0&&(r===-1||l<r)&&o(i.slice(l+1)),o(i)}return n}function Zi(e,t){return e.replace(wu,t).toLowerCase()}function pl(e,t){const n=Zi(e,t).split(".");return n.length<4||n[0]!=="mscrm"?null:[n[0],n[1],"*",...n.slice(3)].join(".")}function fl(e,t,n,o={}){const s=new Map,i=new Map;for(const r of t){const c=Zi(r,n);s.has(c)||s.set(c,r);const d=pl(r,n);d&&!i.has(d)&&i.set(d,r)}const l=new Map;for(const r of e){if(r.disabled&&!o.includeDisabled)continue;const c=Mv(r,n),d=c.map(p=>s.get(Zi(p,n))).find(Boolean)??c.map(p=>pl(p,n)).map(p=>p?i.get(p):void 0).find(Boolean);if(!d)continue;const u=l.get(d)??[];u.push({buttonId:d,command:r,effect:r.hidden?"hidden":"replaced"}),l.set(d,u)}return l}function Dv(e,t,n){const o=l=>l.toLowerCase(),s=`mscrm.${o(t)}.${o(n)}.maintab`,i=e.find(l=>l.id==="Mscrm.GlobalTab")?.id;return t==="Application"&&i?i:e.find(l=>o(l.id)===s)?.id??e.find(l=>/maintab$/i.test(l.id)&&!/\.allentities\./i.test(l.id))?.id??i??e[0]?.id}function Cu(e){return(e.menu?.sections??[]).flatMap(t=>t.controls.flatMap(n=>[n,...Cu(n)]))}function Ev(e){const{commands:t,tabs:n,location:o,entityLogicalName:s}=e,i=n.flatMap(x=>x.groups.flatMap(S=>S.buttons)),l=[...i,...i.flatMap(Cu)].map(x=>x.id),r=new Map(t.map(x=>[x.id,x])),c=new Set([...fl(t,l,s,{includeDisabled:!0}).values()].flat().map(x=>x.command.id)),d=new Map,u=(x,S=new Set)=>{const C=d.get(x.id);if(C!==void 0)return C;let N=x.parentId?r.get(x.parentId):void 0;for(const I=new Set;N?.type==="group"&&!c.has(N.id)&&!I.has(N.id);)I.add(N.id),N=N.parentId?r.get(N.parentId):void 0;const O=c.has(x.id)&&(!N||!S.has(N.id)&&u(N,S.add(x.id)));return d.set(x.id,O),O},m=(x=>{for(const[S,C]of x){const N=C.filter(O=>u(O.command));N.length>0?x.set(S,N):x.delete(S)}return x})(fl(t,l,s)),g=new Set([...m.values()].flat().map(x=>x.command.id)),b=x=>{const S=new Set;for(let C=x.parentId;C&&!S.has(C);C=r.get(C)?.parentId??null){S.add(C);const N=r.get(C);if(N&&u(N))return C}},f=new Map,y=[];for(const x of t){const S=b(x);if(!S){u(x)||y.push(x);continue}if(g.has(x.id))continue;const C=f.get(S)??[];C.push(x),f.set(S,C)}for(const x of m.values())for(const S of x){const C=f.get(S.command.id);C&&(S.items=[...C].sort(Ji))}return{commandBarTabId:Dv(n,o,s),nodes:Su(y),overrides:m,unmatchedMigrated:y.filter(x=>x.origin!=="default")}}function Iu(e,t){const n=new Map,o=[];for(const s of t){const i=e.find(r=>r.sequence>s.command.sequence);if(!i){o.push(s);continue}const l=n.get(i.id)??[];l.push(s),n.set(i.id,l)}return{before:n,trailing:o}}function hl(e){if(!e)return;const t=[e.componentName,e.functionName].filter(Boolean).join("."),n=e.componentLibrary?` (component library ${e.componentLibrary})`:"";return`${t||"Power Fx formula"}${n}`}function Bv(e,t){if(!t)return e;const n=new Set([...t].map(o=>o.toLowerCase()));return e.filter(o=>o.appModuleId===null||n.has(o.appModuleId))}function Lv(e,t,n){const o=new Map(t.map(i=>[i.id.toLowerCase(),i])),s=new Map;for(const i of n??[]){const l=o.get(i.toLowerCase());l&&s.set(l.id.toLowerCase(),l)}if(n)return[...s.values()].sort((i,l)=>i.name.localeCompare(l.name)||i.id.localeCompare(l.id));for(const i of e)!i.appModuleId||s.has(i.appModuleId)||s.set(i.appModuleId,o.get(i.appModuleId)??{id:i.appModuleId,name:i.appName??i.appModuleId});return[...s.values()].sort((i,l)=>i.name.localeCompare(l.name)||i.id.localeCompare(l.id))}function ho(e,t){return e.appModuleId===null?"All apps":t?.get(e.appModuleId)??e.appName??e.appModuleId}function Za(e,t){const n=ho(e.command,t),o=e.command.appModuleId===null?"in all apps":`in ${n}`,s=e.effect==="hidden"?`Hidden by modern command ${e.command.label} ${o}`:`Rendered as modern command ${e.command.label} ${o} (migrated)`;return e.items?.length?`${s}; its menu also has ${e.items.map(i=>i.label).join(", ")}`:s}function ju(e,t){if(!e?.length)return"";const n=e.find(o=>o.effect==="hidden");return n?` — ${Za(n,t).replace(/^Hidden/,"hidden")}`:" — modern (migrated)"}const zv={button:"Command",dropdown:"Dropdown",split:"Split button",group:"Group"},Pv={default:"Command designer",migrated:"Migrated from classic",enhancedMigrated:"Enhanced migrated from classic"};function Ru(e,t){const n=[{label:"App",value:ho(e,t)},{label:"Location",value:`${xv[e.location]??`Location ${e.location}`}${e.scope==="all"?" (all tables)":""}`},{label:"Type",value:zv[e.type]},{label:"Order",value:String(e.sequence)},{label:"Origin",value:Pv[e.origin]}];if(e.hidden?n.push({label:"Status",value:"Hidden"}):e.disabled&&n.push({label:"Status",value:e.origin==="default"?"Disabled":"Disabled — the classic (ribbon) equivalent is shown"}),e.visibility==="formula")n.push({label:"Visible (Power Fx)",value:hl(e.visibilityFormula)??"Power Fx formula"});else if(e.visibility==="classicRules"){const o=e.classicRules.filter(s=>s.kind==="display").map(s=>s.name);n.push({label:"Visibility",value:o.length?`Classic rules: ${o.join(", ")}`:"Classic rules"})}if(e.action==="formula")n.push({label:"OnSelect (Power Fx)",value:hl(e.onSelectFormula)??"Power Fx formula"});else if(e.action==="javascript"){const o=e.jsWebResourceName??e.jsWebResourceId,s=e.jsFunctionName??"(no function)";n.push({label:"Action (JavaScript)",value:o?`${s} in ${o}`:s}),e.jsParameters&&n.push({label:"Parameters",value:e.jsParameters})}return n}function Fv(){return window.dataverseAPI}const go=e=>e instanceof Error?e.message:String(e);async function ls(e){const t=[],n=new Set;let o=e;for(;o&&!n.has(o);){n.add(o);const s=await Fv().queryData(o);t.push(...s.value??[]);const i=s["@odata.nextLink"];o=i?i.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}function $u(e){return/\b40[13]\b|0x80040220|prvRead|privilege|unauthori[sz]ed|forbidden|not have permission/i.test(go(e))}const Nu=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function gl(e,t){const n=[`contextvalue eq '${e.logicalName.replace(/'/g,"''")}'`];e.metadataId&&Nu.test(e.metadataId)&&n.push(`_contextentity_value eq ${e.metadataId}`);const o=`statecode eq 0 and (context eq 0 or ${n.join(" or ")}) and (location eq 0 or location eq 1 or location eq 2 or location eq 3 or location eq 5)`,s=t?`&$expand=${xu}($select=appactionruleid,name,uniquename,type)`:"";return`appactions?$select=${Sv.join(",")}&$filter=${o}${s}`}async function _v(e){const t=ce.getState();let n;try{n=await ls(gl(e,!0))}catch(o){if($u(o))throw o;t.logInfo("dataverse",`Modern commands: classic rules couldn't be expanded (${go(o)}); retrying without them.`),n=await ls(gl(e,!1))}return $v(n)}async function qv(e){const t=ce.getState(),n="appmodules?$select=appmoduleid,appmoduleidunique,name,uniquename",o=e.metadataId&&Nu.test(e.metadataId)?`appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 1 and objectid eq ${e.metadataId}`:null,[s,i]=await Promise.all([ls(n),o?ls(o).catch(d=>(t.logInfo("dataverse",`Modern commands: couldn't resolve which apps contain ${e.logicalName} (${go(d)}).`),null)):Promise.resolve(null)]),l=s,r=l.filter(d=>!!d.appmoduleid).map(d=>({id:String(d.appmoduleid).toLowerCase(),name:d.name?.trim()||d.uniquename||String(d.appmoduleid),uniqueName:d.uniquename}));let c=null;if(i){const d=new Set(i.map(u=>u._appmoduleidunique_value).filter(u=>typeof u=="string").map(u=>u.toLowerCase()));c=new Set(l.filter(u=>u.appmoduleid&&u.appmoduleidunique&&d.has(u.appmoduleidunique.toLowerCase())).map(u=>String(u.appmoduleid).toLowerCase()))}return{apps:r,containingAppIds:c}}async function Wv(e){const t=ce.getState(),[n,o]=await Promise.allSettled([_v(e),qv(e)]);if(n.status==="rejected"){const r=go(n.reason);return t.logWarn("dataverse",$u(n.reason)?`No permission to read modern commands (appaction) for ${e.logicalName}; the canvas shows classic commands only. (${r})`:`Modern commands unavailable for ${e.logicalName}: ${r}`),{commands:[],apps:[],error:r}}o.status==="rejected"&&t.logInfo("dataverse",`Modern commands: app list unavailable (${go(o.reason)}); showing app ids from the commands.`);const{apps:s,containingAppIds:i}=o.status==="fulfilled"?o.value:{apps:[],containingAppIds:null},l=Bv(n.value,i);return t.logInfo("dataverse",`Loaded ${l.length} modern command${l.length===1?"":"s"} for ${e.logicalName}.`),{commands:l,apps:Lv(l,s,i)}}function Hv(){const e=ae(n=>n.activeEntity?.logicalName),t=ae(n=>n.activeEntity?.metadataId);E.useEffect(()=>{const n=we.getState();if(!e||typeof window.dataverseAPI>"u"){n.reset();return}const o=n.beginLoad(e);Wv({logicalName:e,metadataId:t}).then(s=>we.getState().finishLoad(o,s))},[e,t])}function Ln(){const e=we(n=>n.apps),t=we(n=>n.commands);return E.useMemo(()=>{const n=new Map;for(const o of t)o.appModuleId&&o.appName&&n.set(o.appModuleId,o.appName);for(const o of e)n.set(o.id,o.name);return n},[e,t])}function Tu(e){const t=we(i=>i.commands),n=we(i=>i.appFilter),o=ae(i=>i.activeEntity?.logicalName),s=ae(i=>i.activeEntity?.metadataId);return E.useMemo(()=>o?Av(t,{location:e,appFilter:n,table:{logicalName:o,metadataId:s}}):[],[t,n,e,o,s])}const Qi=new Set;function Gv(){Qi.clear()}function Qa(e){const t=Tu(e),n=ae(u=>u.activeEntity?.logicalName)??"",o=M(u=>u.ribbons[e]?.tabs),s=M(u=>u.ribbons[e]?.entityLogicalName??""),i=we(u=>u.status==="loaded"?u.tableLogicalName:null),l=(o?.length??0)>0&&(e==="Application"||s.toLowerCase()===n.toLowerCase()),r=E.useMemo(()=>Ev({commands:t,tabs:l?o??[]:[],location:e,entityLogicalName:n}),[t,o,l,e,n]),d=!!n&&i===n&&l?r.unmatchedMigrated.map(u=>u.uniqueName).join(", "):"";return E.useEffect(()=>{const u=`${n}|${e}|${d}`;!d||Qi.has(u)||(Qi.add(u),ce.getState().logInfo("ribbon",`Migrated modern commands without a classic control in ${n} ${e}: ${d}`))},[d,n,e]),r}function As(e,t){const n=Qa(e);return E.useMemo(()=>{const o=t.groups.flatMap(i=>i.buttons.map(l=>({id:l.id,sequence:l.sequence}))),s=t.id===n.commandBarTabId?n.nodes:[];return{nodes:s,placement:Iu(o,s),overrides:n.overrides}},[n,t])}function Uv(e,t){const{overrides:n}=Qa(e);return t&&n.get(t)||Vv}const Vv=[];function Xv(){const e=we(s=>s.selectedCommandId),t=J(s=>s.selectedButtonId),n=J(s=>s.location),o=Tu(n);return E.useMemo(()=>{if(!e||t)return null;const s=o.find(l=>l.id===e);if(!s)return null;let i;for(const l of Su(o))if(i=ku(l,e),i)break;return{command:s,children:i?vu(i.children):[]}},[e,t,o])}function ku(e,t){if(e.command.id===t)return e;for(const n of e.children){const o=ku(n,t);if(o)return o}}function Kv(e,t,n){const o=pt(e.groups).flatMap(r=>pt(r.buttons).map(c=>{const d=n.get(c.id)??[],u=c.hidden||d.length>0&&d.every(g=>g.effect==="hidden"),p=d.find(g=>g.effect==="replaced")?.command;return{item:{kind:"classic",id:c.id,button:c,groupId:r.id,replacedBy:p},hidden:u}})),s=t.filter(r=>!r.command.hidden&&!r.command.disabled),i=Iu(o.map(r=>({id:r.item.id,sequence:r.item.button.sequence})),s),l=r=>({kind:"modern",id:`modern:${r.command.id}`,command:r.command});return[...o.flatMap(({item:r,hidden:c})=>[...(i.before.get(r.id)??[]).map(l),...c?[]:[r]]),...i.trailing.map(l)]}const Au=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS,marginBottom:h.spacingVerticalM},header:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:h.spacingHorizontalS,minWidth:0},muted:{color:h.colorNeutralForeground3},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},bar:{display:"flex",alignItems:"center",gap:"2px",minWidth:0,height:"40px",padding:`0 ${h.spacingHorizontalXS}`,overflow:"hidden",backgroundColor:h.colorNeutralBackground1,border:`1px solid ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusMedium,boxShadow:h.shadow2},command:{flexShrink:0,fontWeight:h.fontWeightRegular,maxWidth:"220px"},selected:{backgroundColor:h.colorSubtleBackgroundSelected,outline:`1px solid ${h.colorBrandStroke1}`},empty:{padding:`0 ${h.spacingHorizontalS}`}});function Yv({tab:e,location:t}){const n=Au(),o=Ee(),s=M(S=>S.locLabels),i=M(S=>S.baseLanguageCode),l=J(S=>S.selectedButtonId),r=J(S=>S.selectButtonInContext),c=we(S=>S.selectedCommandId),d=we(S=>S.selectCommand),u=As(t,e),p=Xh({axis:"horizontal",memorizeCurrent:!0}),m=Kv(e,u.nodes,u.overrides),g=o(e.label,s,i,e.source?.titleToken)||e.id,b=S=>S.kind==="modern"?S.command.label||S.command.uniqueName:S.replacedBy?S.replacedBy.label||S.replacedBy.uniqueName:o(S.button.label,s,void 0,S.button.source?.labelToken)||S.button.id,f=S=>S.kind==="classic"?S.id===l||!l&&!!S.replacedBy&&S.replacedBy.id===c:!l&&S.command.id===c,y=S=>S.kind==="classic"?r(t,e.id,S.groupId,S.button.id):d(S.command.id),x=xo(e.id);return a.jsxs("section",{className:n.root,"aria-label":"How users see it",children:[a.jsxs("div",{className:n.header,children:[a.jsx(V,{weight:"semibold",size:300,children:"How users see it"}),a.jsxs(V,{size:200,className:Ie(n.muted,n.ellipsis),children:[g," · ",m.length," command",m.length===1?"":"s"]}),a.jsx(xe,{appearance:"outline",color:"informative",size:"medium",children:"Preview: rules not applied"}),a.jsx(Dt,{size:"small",info:"The tab's commands in the order Unified Interface lists them, without the ones hidden by your customizations or replaced by a modern command. Display and enable rules aren't evaluated, so some of these may not show, or be disabled, for users. What doesn't fit goes into the ⋮ menu.",infoButton:{"aria-label":"About this preview"}})]}),x?a.jsx(V,{size:200,className:Ie(n.bar,n.empty,n.muted),children:"Unified Interface doesn't show this tab's commands."}):m.length===0?a.jsx(V,{size:200,className:Ie(n.bar,n.empty,n.muted),children:"No commands on this tab are shown."}):a.jsx(ha,{padding:40,children:a.jsxs("div",{className:n.bar,role:"toolbar",...p,"aria-label":`Command bar preview: ${g}`,children:[m.map(S=>a.jsx(Pt,{id:S.id,priority:f(S)?2:1,children:a.jsx(Jv,{item:S,text:b(S),selected:f(S),onChoose:()=>y(S)})},S.id)),a.jsx(Zv,{items:m,textOf:b,isSelected:f,onChoose:y})]})})]})}const Jv=E.forwardRef(function({item:t,text:n,selected:o,onChoose:s},i){const l=Au(),r=t.kind==="classic"&&!!t.button.menu;return a.jsxs(K,{ref:i,appearance:"subtle",size:"small",className:Ie(l.command,o&&l.selected),"aria-current":o||void 0,"data-users-bar":t.id,"aria-description":t.kind==="modern"?"Modern command":t.replacedBy?"Modern command, migrated from this button":t.id,icon:t.kind==="classic"?a.jsx(xt,{button:t.button,size:16}):void 0,onClick:s,children:[a.jsx("span",{className:l.ellipsis,children:n}),r&&a.jsx(it,{fontSize:12,"aria-label":"Has a menu"})]})});function Zv({items:e,textOf:t,isSelected:n,onChoose:o}){const{ref:s,isOverflowing:i,overflowCount:l}=ga();return i?a.jsxs(Xe,{children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(K,{ref:s,appearance:"subtle",size:"small",icon:a.jsx(dc,{}),"aria-label":`${l} more commands`,children:l})}),a.jsx(Ye,{children:a.jsx(Je,{children:e.map(r=>a.jsx(Qv,{item:r,text:t(r),selected:n(r),onChoose:()=>o(r)},r.id))})})]}):null}function Qv({item:e,text:t,selected:n,onChoose:o}){return ba(e.id)?null:a.jsx(fe,{icon:e.kind==="classic"?a.jsx(xt,{button:e.button,size:16}):void 0,secondaryContent:n?"Selected":e.kind==="modern"?"Modern":void 0,onClick:o,children:t})}function Ou(e,t,n=`_copy_${Date.now()}`){return{...Yo(e,`${e.id}${n}`,t),label:e.label??"New Button",kind:e.kind??"button",sequence:void 0,templateAlias:e.templateAlias??"o1",commandId:e.commandId??"",hidden:!1,oob:!1,custom:!0,managed:!1}}const Mu=me({chip:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,height:"32px",padding:`0 ${h.spacingHorizontalS}`,borderRadius:h.borderRadiusMedium,border:`1px dashed ${h.colorPaletteBerryBorderActive}`,backgroundColor:h.colorPaletteBerryBackground1,color:h.colorNeutralForeground1,cursor:"default",whiteSpace:"nowrap",flexShrink:0,userSelect:"none",":hover":{backgroundColor:h.colorPaletteBerryBackground2},":focus-visible":{outline:`2px solid ${h.colorBrandStroke1}`,outlineOffset:"2px"}},selected:{border:`1px solid ${h.colorPaletteBerryForeground2}`,backgroundColor:h.colorPaletteBerryBackground2},muted:{opacity:.5},hidden:{textDecoration:"line-through"},tooltip:{display:"flex",flexDirection:"column",gap:"2px",maxWidth:"360px"},tooltipRow:{fontSize:h.fontSizeBase200,overflowWrap:"anywhere"}});function Du({node:e,appNames:t}){const n=Mu(),o=e.command;return a.jsxs("div",{className:n.tooltip,children:[a.jsx(V,{weight:"semibold",children:o.label}),a.jsx(V,{className:n.tooltipRow,children:"Modern command — read-only in CBS; edit it in the command designer."}),Ru(o,t).map(s=>a.jsxs(V,{className:n.tooltipRow,children:[a.jsxs("b",{children:[s.label,":"]})," ",s.value]},s.label)),e.children.length>0&&a.jsxs(V,{className:n.tooltipRow,children:[a.jsx("b",{children:"Items:"})," ",e.children.map(s=>s.command.label).join(", ")]})]})}function ew({node:e,appNames:t,showApp:n,onDragRejected:o}){const s=Mu(),i=e.command,l=we(b=>b.selectedCommandId),r=we(b=>b.selectCommand),c=J(b=>b.selectedButtonId),d=l===i.id&&!c,u=i.type==="dropdown"||i.type==="split"||e.children.length>0,p=i.fontIcon&&!i.fontIcon.startsWith("$")?i.fontIcon:"apps_add_in",m=`${i.hidden?" — hidden":""}${i.disabled?" — disabled":""}`,g=b=>{b.preventDefault(),b.stopPropagation(),b.dataTransfer.dropEffect="none",o?.()};return a.jsx(pe,{content:a.jsx(Du,{node:e,appNames:t}),relationship:"description",children:a.jsxs("button",{type:"button",draggable:!1,className:Ie(s.chip,d&&s.selected,(i.hidden||i.disabled)&&s.muted,i.hidden&&s.hidden),"aria-pressed":d,"aria-label":`${i.label} — modern command (read-only), ${ho(i,t)}${m}`,onClick:()=>r(i.id),onDragStart:b=>b.preventDefault(),onDragOver:g,onDrop:g,onContextMenu:b=>{b.preventDefault(),r(i.id)},children:[a.jsx(Ka,{name:p,size:16}),a.jsx(V,{size:200,children:i.label}),u&&a.jsx(it,{fontSize:12,"aria-hidden":!0}),i.hidden&&a.jsx(Et,{fontSize:12,"aria-hidden":!0}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:"important",icon:a.jsx(dn,{}),children:"Modern"}),n&&a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",color:"informative",children:ho(i,t)})]})})}function er({overrides:e,appNames:t}){if(!e?.length)return null;const n=e.some(s=>s.effect==="hidden"),o=e.map(s=>Za(s,t)).join(`
132
+ `);return a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:n?"warning":"important",title:o,"aria-label":o,children:n?"Hidden by modern":"Modern (migrated)"})}const Oo="application/x-rw-btn",bl="application/x-rw-se",tw=me({root:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`${h.spacingHorizontalS} 0`,minHeight:"48px"},scrollRow:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,flex:1,minWidth:0,overflowX:"auto",overflowY:"hidden",paddingBottom:h.spacingHorizontalXS},button:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,height:"32px",padding:`0 ${h.spacingHorizontalS}`,borderRadius:h.borderRadiusMedium,border:"1px solid transparent",cursor:"pointer",backgroundColor:"transparent",color:h.colorNeutralForeground1,whiteSpace:"nowrap",flexShrink:0,position:"relative",userSelect:"none",":hover":{backgroundColor:h.colorNeutralBackground3,border:`1px solid ${h.colorNeutralStroke1}`},":focus-visible":{outline:`2px solid ${h.colorBrandStroke1}`,outlineOffset:"2px"}},buttonSelected:{backgroundColor:h.colorBrandBackground2,border:`1px solid ${h.colorBrandStroke1}`},buttonHidden:{opacity:.4,textDecoration:"line-through"},buttonCustom:{border:`1px solid ${h.colorBrandStroke2}`},lockIcon:{position:"absolute",top:"4px",left:"4px",color:h.colorNeutralForeground3,pointerEvents:"none"},dropLine:{width:"2px",height:"24px",backgroundColor:h.colorBrandStroke1,borderRadius:"2px",flexShrink:0},overflowBtn:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,height:"32px",padding:`0 ${h.spacingHorizontalS}`,borderRadius:h.borderRadiusMedium,border:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground2,cursor:"pointer",color:h.colorNeutralForeground3,flexShrink:0},trailingControls:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,flexShrink:0,paddingLeft:h.spacingHorizontalS,borderLeft:`1px solid ${h.colorNeutralStroke2}`,marginLeft:h.spacingHorizontalXS}});function nw({tab:e,location:t}){const n=tw(),o=J(R=>R.selectedButtonId),s=J(R=>R.selectButtonInContext),i=M(R=>R.moveButton),l=M(R=>R.locLabels),r=Ee(),c=M(R=>R.baseLanguageCode),d=(R,D,q)=>r(R,l,c,q)||D,u=Z(R=>R.openNewButton),[p,m]=E.useState(null),[g,b]=E.useState(null),[f,y]=E.useState(null),x=As(t,e),S=Ln(),C=we(R=>R.appFilter==="all"),N=R=>a.jsx(ew,{node:R,appNames:S,showApp:C,onDragRejected:()=>m(null)},R.command.id),O=R=>ju(x.overrides.get(R.id),S),I=R=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&R.oob&&!R.custom,j=R=>dt(R.kind),$=R=>j(R)?` (${yt[R.kind]}, read-only)`:"",w=e.groups.flatMap(R=>R.buttons.map(D=>({button:D,groupId:R.id})));function A(R,D,q){R.dataTransfer.setData(Oo,JSON.stringify({groupId:D,buttonId:q})),R.dataTransfer.effectAllowed="move",b(q)}function B(){b(null),m(null)}function k(R,D){const q=Array.from(R.dataTransfer.types??[]);!q.includes(Oo)&&!q.includes(bl)||(R.preventDefault(),R.dataTransfer.dropEffect=q.includes(Oo)?"move":"copy",m({beforeButtonId:D}))}const v=M(R=>R.createButton);function T(R,D,q){R.preventDefault(),R.stopPropagation();const X=R.dataTransfer.getData(Oo);if(X){try{const re=JSON.parse(X);if(re?.buttonId){const le=i({groupId:re.groupId,buttonId:re.buttonId,tabId:e.id,location:t},{groupId:D,beforeButtonId:q??void 0,tabId:e.id,location:t});le&&le!==re.buttonId&&s(t,e.id,D,le)}}catch{}m(null),b(null);return}const ne=R.dataTransfer.getData(bl);if(ne){try{const le=JSON.parse(ne)?.button;le&&v({location:t,tabId:e.id,groupId:D,button:Ou(le,io(M.getState()))})}catch{}m(null),b(null);return}m(null),b(null)}return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:n.root,children:[a.jsxs("div",{className:n.scrollRow,onDragOver:R=>{R.preventDefault()},onDrop:R=>T(R,e.groups[0]?.id??"",null),children:[w.map(({button:R,groupId:D})=>a.jsxs(et.Fragment,{children:[x.placement.before.get(R.id)?.map(N),p?.beforeButtonId===R.id&&a.jsx("div",{className:n.dropLine,"aria-hidden":!0}),a.jsx(pe,{content:I(R)?"OOB global command bar buttons cannot be customized.":`${r(R.label,l,void 0,R.source?.labelToken)}${$(R)}${R.hidden?" — hidden":""}${O(R)}`,relationship:"label",children:a.jsxs("button",{type:"button",className:[n.button,o===R.id?n.buttonSelected:"",R.hidden?n.buttonHidden:"",R.custom?n.buttonCustom:""].filter(Boolean).join(" "),"aria-selected":o===R.id,"aria-label":`${r(R.label,l,void 0,R.source?.labelToken)}${$(R)}${R.hidden?" — hidden":""}${O(R)}`,onClick:()=>s(t,e.id,D,R.id),onContextMenu:q=>{q.preventDefault(),s(t,e.id,D,R.id),y({button:R,groupId:D,anchor:q.currentTarget})},draggable:!R.managed&&!I(R),onDragStart:q=>A(q,D,R.id),onDragEnd:B,onDragOver:q=>k(q,R.id),onDrop:q=>T(q,D,R.id),style:{opacity:g===R.id?.3:void 0},children:[a.jsx(xt,{button:R,size:16}),a.jsx(V,{size:200,children:r(R.label,l,void 0,R.source?.labelToken)}),j(R)&&a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",color:"informative",children:yt[R.kind]}),R.menu&&a.jsx(it,{fontSize:12,"aria-label":"Has a menu"}),R.hidden&&a.jsx(Et,{fontSize:12,"aria-hidden":!0}),R.custom&&a.jsx(xe,{style:{flexShrink:0},size:"medium",color:"brand",appearance:"tint","aria-label":"Custom",children:"NEW"}),a.jsx(er,{overrides:x.overrides.get(R.id),appNames:S}),I(R)&&a.jsx("span",{className:n.lockIcon,title:"OOB global command bar buttons cannot be customized.",children:a.jsx(dn,{fontSize:12})})]})})]},R.id)),x.placement.trailing.map(N)]}),a.jsx("div",{className:n.trailingControls,children:(()=>{const R=e.groups[0];return R?a.jsx(pe,{content:`Add a new button to "${d(R.label,R.id,R.source?.titleToken)}"`,relationship:"label",children:a.jsxs("button",{type:"button",className:n.overflowBtn,onClick:()=>u(R.id),"aria-label":"Add a new button",children:[a.jsx(ke,{fontSize:14})," Add"]})}):a.jsx(pe,{content:'No groups in this tab yet. Switch to "Classic ribbon" view to add a group first.',relationship:"label",children:a.jsxs("button",{type:"button",className:n.overflowBtn,disabled:!0,children:[a.jsx(ke,{fontSize:14})," Add"]})})})()})]}),a.jsx(wo,{location:t,tab:e,target:f,onClose:()=>y(null)})]})}const ow=me({root:{marginTop:h.spacingVerticalM,display:"flex",flexDirection:"column",gap:h.spacingVerticalXS},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS},row:{cursor:"pointer",backgroundColor:h.colorPaletteBerryBackground1,":hover":{backgroundColor:h.colorPaletteBerryBackground2}},rowSelected:{backgroundColor:h.colorPaletteBerryBackground2,outline:`1px solid ${h.colorPaletteBerryBorderActive}`},hidden:{opacity:.55,textDecoration:"line-through"},mono:{fontFamily:h.fontFamilyMonospace,color:h.colorNeutralForeground3},table:{tableLayout:"fixed",width:"100%"},note:{color:h.colorNeutralForeground3,minWidth:0}}),sw={button:"command",dropdown:"dropdown",split:"split",group:"group"};function iw({tab:e,location:t}){const n=ow(),{nodes:o}=As(t,e),s=Ln(),i=we(m=>m.selectedCommandId),l=we(m=>m.selectCommand),r=J(m=>m.selectedButtonId),[c,d]=E.useState(!0);if(o.length===0)return null;const u=[],p=(m,g)=>{for(const b of m)u.push({node:b,depth:g}),p(b.children,g+1)};return p(o,0),a.jsxs("section",{className:n.root,"aria-label":"Modern commands",children:[a.jsxs("div",{className:n.header,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:c?a.jsx(it,{}):a.jsx($h,{}),"aria-expanded":c,onClick:()=>d(!c),children:a.jsxs(V,{weight:"semibold",size:200,children:["Modern commands (",u.length,")"]})}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:"important",children:"read-only"}),a.jsx(V,{size:200,truncate:!0,wrap:!1,className:n.note,children:"Built with the command designer (appaction). Edit them there."})]}),c&&a.jsxs(Kh,{size:"small",className:n.table,"aria-label":"Modern commands (read-only)",children:[a.jsx(Yh,{children:a.jsxs(yr,{children:[a.jsx(Fn,{style:{width:52},children:"#"}),a.jsx(Fn,{style:{width:"36%"},children:"Label"}),a.jsx(Fn,{style:{width:"20%"},children:"App"}),a.jsx(Fn,{style:{width:96},children:"Type"}),a.jsx(Fn,{children:"Unique name"})]})}),a.jsx(Jh,{children:u.map(({node:m,depth:g})=>{const b=m.command,f=i===b.id&&!r;return a.jsxs(yr,{className:Ie(n.row,f&&n.rowSelected),"aria-selected":f,tabIndex:0,onClick:()=>l(b.id),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),l(b.id))},children:[a.jsx(_n,{children:b.sequence}),a.jsx(_n,{children:a.jsx(pe,{content:a.jsx(Du,{node:m,appNames:s}),relationship:"description",children:a.jsxs("span",{className:b.hidden||b.disabled?n.hidden:void 0,style:{paddingLeft:g*16,display:"flex",gap:4,alignItems:"center",minWidth:0,overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},children:[a.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:b.label}),b.hidden&&a.jsx(Et,{fontSize:12,"aria-label":"hidden"}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"tint",color:"important",children:"Modern"})]})})}),a.jsx(_n,{children:a.jsx(lo,{truncate:!0,children:ho(b,s)})}),a.jsx(_n,{children:a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",children:sw[b.type]})}),a.jsx(_n,{children:a.jsx(lo,{truncate:!0,className:n.mono,children:a.jsx("span",{title:b.uniqueName,children:b.uniqueName})})})]},b.id)})})]})]})}const aw=me({root:{width:"100%",minWidth:0},toolbar:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,padding:`${h.spacingVerticalXS} 0`},search:{flex:1,minWidth:0,maxWidth:"480px"},muted:{color:h.colorNeutralForeground3},grid:{width:"100%",minWidth:0},header:{position:"sticky",top:`calc(-1 * ${h.spacingHorizontalM})`,zIndex:1,backgroundColor:h.colorNeutralBackground1},row:{cursor:"pointer"},rowSelected:{backgroundColor:h.colorSubtleBackgroundSelected,":hover":{backgroundColor:h.colorSubtleBackgroundSelected}},hidden:{color:h.colorNeutralForeground3},mono:{fontFamily:h.fontFamilyMonospace,color:h.colorNeutralForeground3},badge:{marginLeft:h.spacingHorizontalXS,flexShrink:0},labelMain:{display:"flex",alignItems:"center",minWidth:0,overflow:"hidden"},shrink:{minWidth:0},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}),yl={id:"ID",command:"Command"},xl=e=>!!e.target.closest('button, input, [role="switch"], [role="menuitem"]');function rw({tab:e,location:t}){const n=aw(),o=J(v=>v.selectedButtonId),s=J(v=>v.selectButtonInContext),i=M(v=>v.setButtonProp),l=M(v=>v.locLabels),r=M(v=>v.baseLanguageCode),c=Ee(),{overrides:d}=As(t,e),u=Ln(),[p,m]=E.useState(""),[g,b]=E.useState([]),[f,y]=E.useState(null),[x,S]=E.useState(void 0),C=fc({tabBehavior:"unlimited",ignoreDefaultKeydown:{Enter:!0}}),N=E.useMemo(()=>{let v=0;return pt(e.groups).flatMap(T=>pt(T.buttons).map(R=>({button:R,label:c(R.label,l,void 0,R.source?.labelToken)||R.id,groupId:T.id,groupLabel:c(T.label,l,r,T.source?.titleToken)||T.id,order:v++})))},[e,c,l,r]),O=p.toLowerCase().trim(),I=O?N.filter(({button:v,label:T,groupLabel:R})=>v.id.toLowerCase().includes(O)||T.toLowerCase().includes(O)||v.label.toLowerCase().includes(O)||(v.commandId??"").toLowerCase().includes(O)||R.toLowerCase().includes(O)):N,j=v=>s(t,e.id,v.groupId,v.button.id),$=(v,T)=>y({button:v.button,groupId:v.groupId,anchor:T}),w={seq:{defaultWidth:52,minWidth:44,idealWidth:52},label:{defaultWidth:220,minWidth:140,idealWidth:220},kind:{defaultWidth:110,minWidth:80,idealWidth:110},group:{defaultWidth:150,minWidth:90,idealWidth:150},visible:{defaultWidth:72,minWidth:64,idealWidth:72},id:{defaultWidth:240,minWidth:140,idealWidth:240},command:{defaultWidth:220,minWidth:140,idealWidth:220},actions:{defaultWidth:44,minWidth:44,idealWidth:44}},A=v=>a.jsx(V,{size:200,weight:"semibold",children:v}),B=(v,T)=>a.jsx(lo,{truncate:!0,className:T,title:v,children:v}),k=[qe({columnId:"seq",compare:(v,T)=>v.button.sequence-T.button.sequence||v.order-T.order,renderHeaderCell:()=>A("#"),renderCell:({button:v})=>a.jsx(V,{size:200,children:v.sequence})}),qe({columnId:"label",compare:(v,T)=>v.label.localeCompare(T.label)||v.order-T.order,renderHeaderCell:()=>A("Label"),renderCell:({button:v,label:T})=>a.jsx(pe,{content:`${T} (${v.id})`,relationship:"description",children:a.jsxs(lo,{media:a.jsx(xt,{button:v,size:16}),className:Ie(n.shrink,v.hidden&&n.hidden),content:{className:n.shrink},main:{className:n.labelMain},children:[a.jsx("span",{className:n.ellipsis,children:T}),a.jsx("span",{className:n.badge,children:a.jsx(er,{overrides:d.get(v.id),appNames:u})})]})})}),qe({columnId:"kind",compare:(v,T)=>yt[v.button.kind].localeCompare(yt[T.button.kind])||v.order-T.order,renderHeaderCell:()=>A("Kind"),renderCell:({button:v})=>B(yt[v.kind]??v.kind)}),qe({columnId:"group",compare:(v,T)=>v.groupLabel.localeCompare(T.groupLabel)||v.order-T.order,renderHeaderCell:()=>A("Group"),renderCell:({groupLabel:v})=>B(v)}),...g.includes("id")?[qe({columnId:"id",compare:(v,T)=>v.button.id.localeCompare(T.button.id),renderHeaderCell:()=>A("ID"),renderCell:({button:v})=>B(v.id,n.mono)})]:[],...g.includes("command")?[qe({columnId:"command",compare:(v,T)=>(v.button.commandId??"").localeCompare(T.button.commandId??"")||v.order-T.order,renderHeaderCell:()=>A("Command"),renderCell:({button:v})=>B(v.commandId||"—",n.mono)})]:[],qe({columnId:"visible",compare:(v,T)=>Number(v.button.hidden)-Number(T.button.hidden)||v.order-T.order,renderHeaderCell:()=>A("Visible"),renderCell:({button:v,label:T,groupId:R})=>{const D=Da(t,e.id,v);return a.jsx(pe,{content:D?"Microsoft's global command bar buttons can't be changed.":v.hidden?"Hidden":"Shown",relationship:"description",children:a.jsx(xa,{checked:!v.hidden,disabled:D,"aria-label":`Toggle visibility of ${T}`,onChange:(q,X)=>i(t,e.id,R,v.id,{hidden:!X.checked})})})}}),qe({columnId:"actions",renderHeaderCell:()=>a.jsx("span",{className:n.muted}),renderCell:v=>a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ds,{}),"aria-label":`Actions for ${v.label}`,onClick:T=>$(v,T.currentTarget)})})];return a.jsxs("div",{className:n.root,children:[a.jsxs("div",{className:n.toolbar,children:[a.jsx(sn,{size:"small",className:n.search,placeholder:`Filter ${N.length} button${N.length!==1?"s":""}`,"aria-label":"Filter the buttons",value:p,onChange:(v,T)=>m(T.value)}),O&&a.jsxs(V,{size:200,className:n.muted,children:[I.length," match",I.length!==1?"es":""]}),a.jsxs(Xe,{checkedValues:{columns:g},onCheckedValueChange:(v,T)=>b(T.checkedItems),children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Nh,{}),children:"Columns"})}),a.jsx(Ye,{children:a.jsx(Je,{children:Object.keys(yl).map(v=>a.jsx(mc,{name:"columns",value:v,children:yl[v]},v))})})]})]}),a.jsx("div",{...C,children:a.jsxs(Zh,{className:n.grid,items:I,columns:k,columnSizingOptions:w,resizableColumns:!0,sortable:!0,sortState:x,onSortChange:(v,T)=>S(T),getRowId:v=>v.button.id,focusMode:"composite",size:"small","aria-label":`Buttons of ${e.id}`,children:[a.jsx(Qh,{className:n.header,children:a.jsx(xr,{children:({renderHeaderCell:v})=>a.jsx(hc,{children:v()})})}),a.jsx(eg,{children:({item:v,rowId:T})=>{const R=o===v.button.id;return a.jsx(xr,{"aria-selected":R,"data-list-button":v.button.id,className:Ie(n.row,R&&n.rowSelected),onClick:D=>{xl(D)||j(v)},onKeyDown:D=>{xl(D)||(D.key==="Enter"||D.key===" "?(D.preventDefault(),j(v)):(D.key==="ContextMenu"||D.shiftKey&&D.key==="F10")&&(D.preventDefault(),$(v,D.currentTarget)))},onContextMenu:D=>{D.preventDefault(),$(v,D.currentTarget)},children:({renderCell:D})=>a.jsx(gc,{children:D(v)})},T)}})]},g.join("|"))}),I.length===0&&a.jsx(V,{size:200,className:n.muted,as:"p",children:O?"No buttons match.":"This tab has no buttons."}),a.jsx(wo,{location:t,tab:e,target:f,onClose:()=>{const v=f?.anchor;setTimeout(()=>{document.activeElement?.closest('[role="dialog"], [role="alertdialog"]')||v?.isConnected&&v.focus()}),y(null)}}),a.jsx(iw,{tab:e,location:t})]})}const Eu=me({root:{marginTop:h.spacingVerticalM,border:`1px solid ${h.colorNeutralStroke2}`,borderRadius:h.borderRadiusMedium,backgroundColor:h.colorNeutralBackground1,maxWidth:"520px"},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`,borderBottom:`1px solid ${h.colorNeutralStroke2}`},spacer:{flex:1},body:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,padding:h.spacingHorizontalS},section:{display:"flex",flexDirection:"column",gap:"2px"},sectionHeader:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`2px ${h.spacingHorizontalXS}`,color:h.colorNeutralForeground3},item:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,width:"100%",minHeight:"28px",padding:`0 ${h.spacingHorizontalS}`,border:"1px solid transparent",borderRadius:h.borderRadiusMedium,backgroundColor:"transparent",color:h.colorNeutralForeground1,cursor:"pointer",textAlign:"left",":hover":{backgroundColor:h.colorNeutralBackground3},":focus-visible":{outline:`2px solid ${h.colorBrandStroke1}`}},itemSelected:{backgroundColor:h.colorBrandBackground2,border:`1px solid ${h.colorBrandStroke1}`},itemHidden:{opacity:.45,textDecoration:"line-through"},itemRow:{display:"flex",alignItems:"center",gap:"2px"},nested:{marginLeft:h.spacingHorizontalL,paddingLeft:h.spacingHorizontalS,borderLeft:`1px dashed ${h.colorNeutralStroke2}`},empty:{padding:`2px ${h.spacingHorizontalS}`,color:h.colorNeutralForeground3}});function lw({tab:e,location:t}){const n=Eu(),o=J(I=>I.selectedButtonId),s=J(I=>I.selectedGroupId),i=J(I=>I.selectButtonInContext),l=M(I=>I.baseline),r=M(I=>I.locLabels),c=Ee(),d=M(I=>I.addMenuSection),u=M(I=>I.setMenuSectionProp),p=M(I=>I.deleteMenuSection),{overrides:m}=Qa(t),g=Ln(),b=e.groups.find(I=>I.id===s),f=$b(b,o),y=E.useMemo(()=>{const I=new Set;for(const j of l[t]?.tabs??[])for(const $ of j.groups)for(const w of Ne($))I.add(w.id);return I},[l,t]);if(!b||!f||!f.menu&&!wn(f.kind))return null;const x=b.id,S=I=>c(I.label,r,void 0,I.source?.labelToken),C=I=>Kc(I.source?.attributes.PopulateDynamically)?I.source?.attributes.PopulateQueryCommand??"a command":null,N=I=>{const j=[...I.menu?.sections??[]].sort((A,B)=>A.sequence-B.sequence),$=!y.has(I.id),w=C(I);return a.jsxs(a.Fragment,{children:[w&&a.jsxs(Ze,{className:n.empty,children:["Populated when the menu opens, by ",w,". Static items below are kept as they are."]}),j.map(A=>a.jsx(cw,{section:A,parent:I,editable:$,onTitle:B=>u(t,e.id,x,I.id,A.id,{title:B}),onDisplayMode:B=>u(t,e.id,x,I.id,A.id,{displayMode:B}),onDelete:()=>p(t,e.id,x,I.id,A.id),renderItem:O},A.id)),j.length===0&&!w&&a.jsx(Ze,{className:n.empty,children:"No menu sections yet."}),$&&a.jsx("div",{children:a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(ke,{}),onClick:()=>d(t,e.id,x,I.id,""),children:"Add section"})})]})},O=I=>{const j=I.id===o,$=m.get(I.id);return a.jsxs("div",{children:[a.jsxs("div",{className:n.itemRow,children:[a.jsxs("button",{type:"button",className:[n.item,j?n.itemSelected:"",I.hidden?n.itemHidden:""].filter(Boolean).join(" "),"aria-pressed":j,"aria-label":`Menu item ${S(I)}${I.hidden?" — hidden":""}${ju($,g)}`,onClick:()=>i(t,e.id,x,I.id),children:[a.jsx(xt,{button:I,size:16}),a.jsx(V,{size:200,children:S(I)}),I.menu&&a.jsx(it,{fontSize:12,"aria-hidden":!0}),a.jsx(er,{overrides:$,appNames:g}),I.custom&&!y.has(I.id)&&a.jsx(xe,{style:{flexShrink:0},size:"medium",color:"brand",appearance:"tint",children:"NEW"})]}),j&&a.jsx(uw,{item:I,location:t,tabId:e.id,groupId:x,onDeleted:()=>i(t,e.id,x,f.id)})]}),I.menu&&a.jsx("div",{className:n.nested,children:N(I)})]},I.id)};return a.jsxs("section",{className:n.root,"aria-label":`Menu of ${S(f)}`,children:[a.jsxs("div",{className:n.header,children:[a.jsx(it,{"aria-hidden":!0}),a.jsx(V,{weight:"semibold",size:300,children:S(f)}),a.jsx(xe,{style:{flexShrink:0},size:"medium",appearance:"outline",children:f.kind==="splitButton"?"Split button menu":"Flyout menu"}),a.jsx("span",{className:n.spacer}),a.jsxs(Ze,{children:[cn(f).length," item(s)"]})]}),a.jsx("div",{className:n.body,children:N(f)})]})}function cw({section:e,parent:t,editable:n,onTitle:o,onDisplayMode:s,onDelete:i,renderItem:l}){const r=Eu(),c=M(p=>p.locLabels),d=Ee(),u=[...e.controls].sort((p,m)=>p.sequence-m.sequence);return a.jsxs("div",{className:r.section,children:[a.jsx("div",{className:r.sectionHeader,children:n?a.jsxs(a.Fragment,{children:[a.jsx(Ft,{size:"small",placeholder:"Section title (optional)",value:e.title??"","aria-label":"Menu section title",onChange:(p,m)=>o(m.value)}),a.jsxs(ya,{size:"small","aria-label":"Menu section display mode",value:e.displayMode??"Menu16",onChange:(p,m)=>s(m.value),children:[a.jsx("option",{value:"Menu16",children:"16 px icons"}),a.jsx("option",{value:"Menu32",children:"32 px icons"}),a.jsx("option",{value:"Menu",children:"Text only"})]}),a.jsx(pe,{content:"Delete section and its items",relationship:"label",children:a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(Dn,{}),onClick:i})})]}):a.jsx(Ze,{children:d(e.title,c,void 0,e.attributes?.Title)||e.id})}),u.map(p=>l(p)),e.rawContent!==void 0&&a.jsx(Ze,{className:r.empty,children:"Gallery / dynamic content (kept as is)"}),(e.rawControls?.length??0)>0&&a.jsxs(Ze,{className:r.empty,children:[e.rawControls.length," other control(s) CBS doesn't edit (kept as they are)"]}),e.rawContent===void 0&&a.jsx(dw,{parent:t,section:e})]})}function dw({parent:e,section:t}){const n=J(m=>m.location),o=J(m=>m.tabId),s=J(m=>m.selectedGroupId),i=J(m=>m.selectButtonInContext),l=M(m=>m.addMenuItem),r=M(m=>m.upsertCommand),c=ae(m=>m.activeSolution),d=ae(m=>m.publisherPrefix),u=ae(m=>m.activeEntity),p=()=>{if(!s)return;const{ribbons:m,commands:g}=M.getState(),b=new Set(g.map(S=>S.id));for(const S of Object.values(m))for(const C of S.tabs)for(const N of C.groups)for(const O of Ne(N))b.add(O.id);const f=c?.publisherPrefix?.trim()||d?.trim()||"new",{id:y,commandId:x}=fd(f,u?.logicalName??"global",n,"MenuItem",b);l({location:n,tabId:o,groupId:s,parentId:e.id,sectionId:t.id,item:{id:y,label:"Menu item",commandId:x}}),r({id:x,enableRules:[],displayRules:[],actions:[]}),i(n,o,s,y)};return a.jsx("div",{children:a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(ke,{}),onClick:p,children:"Add item"})})}function uw({item:e,location:t,tabId:n,groupId:o,onDeleted:s}){const i=M(c=>c.setButtonProp),l=M(c=>c.deleteButton),r=M(c=>c.baseline[t]);return a.jsxs(a.Fragment,{children:[a.jsx(pe,{content:e.hidden?"Show item":"Hide item",relationship:"label",children:a.jsx(K,{size:"small",appearance:"subtle",icon:e.hidden?a.jsx(Mn,{}):a.jsx(Et,{}),onClick:()=>i(t,n,o,e.id,{hidden:!e.hidden})})}),Cs(e,r)&&a.jsx(pe,{content:"Delete item",relationship:"label",children:a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(Dn,{}),onClick:()=>{l(t,n,o,e.id),s()}})})]})}const mw=me({surface:{maxWidth:"380px",display:"flex",flexDirection:"column",gap:h.spacingVerticalS},ribbonId:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,color:h.colorNeutralForeground3,overflowWrap:"anywhere"}}),pw=({location:e,table:t,compact:n})=>{const o=mw(),s=Ut[e],i=n?a.jsx(pe,{content:"About this location",relationship:"label",children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Si,{})})}):a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Si,{}),children:"About this location"});return a.jsxs(ma,{withArrow:!0,positioning:"below-start",children:[a.jsx(pa,{disableButtonEnhancement:!0,children:i}),a.jsxs(fa,{className:o.surface,"aria-label":`About ${s.title}`,children:[a.jsx(V,{weight:"semibold",children:s.title}),a.jsx(V,{children:s.body}),a.jsx("span",{className:o.ribbonId,children:Ib(e,t)})]})]})},fw=me({popover:{overflowY:"auto"},trigger:{maxWidth:"200px",minWidth:0},label:{color:h.colorNeutralForeground3,flexShrink:0},value:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function hw(){const e=fw(),t=we(c=>c.status),n=we(c=>c.apps),o=we(c=>c.appFilter),s=we(c=>c.setAppFilter),i=we(c=>c.commands.length),l=we(c=>c.error);if(t==="idle")return null;if(t==="loading")return a.jsx(tg,{size:"extra-tiny","aria-label":"Loading modern commands"});if(t==="unavailable")return a.jsx(Dt,{size:"small",info:`Modern commands couldn't be read: ${l??"unknown error"}`,children:"Modern commands unavailable"});const r=o==="all"?"All apps":n.find(c=>c.id===o)?.name??"All apps";return a.jsxs(Xe,{positioning:{autoSize:"height"},checkedValues:{app:[o]},onCheckedValueChange:(c,d)=>s(d.checkedItems[0]??"all"),children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:`${i} modern command${i===1?"":"s"} for this table (read-only). Pick an app to see its command bar.`,relationship:"description",children:a.jsxs(K,{appearance:"subtle",size:"small",className:e.trigger,"aria-label":`App for modern commands: ${r}`,icon:a.jsx(it,{}),iconPosition:"after",children:[a.jsx("span",{className:e.label,children:"App: "}),a.jsx("span",{className:e.value,children:r})]})})}),a.jsx(Ye,{className:e.popover,children:a.jsxs(Je,{children:[a.jsx(Sn,{name:"app",value:"all",children:"All apps"}),n.map(c=>a.jsx(Sn,{name:"app",value:c.id,children:c.name},c.id))]})})]})}const gw=me({row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`0 ${h.spacingHorizontalS}`,minHeight:"40px",borderBottom:`1px solid ${h.colorNeutralStroke2}`,flexShrink:0,minWidth:0},locationRow:{backgroundColor:h.colorNeutralBackground2},locationTabs:{flex:"1 1 0",minWidth:0,overflow:"hidden",display:"flex",alignItems:"center"},spacer:{flex:"1 1 0",minWidth:0},viewValue:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:h.colorNeutralForeground3,flexShrink:0},tableName:{flex:"0 1 auto",maxWidth:"200px",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",paddingRight:h.spacingHorizontalS,borderRight:`1px solid ${h.colorNeutralStroke2}`,fontWeight:h.fontWeightSemibold},pinned:{flexShrink:0}}),Bu=["HomepageGrid","Form","SubGrid","Application"],Lu={HomepageGrid:a.jsx(da,{}),Form:a.jsx(us,{}),SubGrid:a.jsx(Th,{}),Application:a.jsx(Ql,{})},Mo={groups:"Group cards",classic:"Classic ribbon",modern:"Modern command bar",list:"List"};function bw(){const e=gw(),t=J(m=>m.location),n=J(m=>m.setLocation),o=J(m=>m.setTabId),s=J(m=>m.tabId),i=M(m=>m.ribbons),l=!/^(Mscrm|Microsoft)\./.test(s)&&i[t].tabs.some(m=>m.id===s),r=ae(m=>m.activeEntity?.logicalName),c=ae(m=>m.activeEntity?.displayName),d=Z(m=>m.ribbonViewStyle),u=Z(m=>m.setRibbonViewStyle),p=m=>{n(m);const g=mo(i[m].tabs);g&&o(g)};return a.jsxs("div",{className:`${e.row} ${e.locationRow}`,children:[r&&a.jsx(pe,{content:`Table: ${c||r} (${r})`,relationship:"description",children:a.jsx("span",{className:e.tableName,tabIndex:0,children:c||r})}),a.jsx(ha,{minimumVisible:1,padding:48,children:a.jsxs("div",{className:e.locationTabs,children:[a.jsxs(Sa,{size:"small","aria-label":"Where the command bar appears",selectedValue:t,onTabSelect:(m,g)=>p(g.value),children:[Bu.map(m=>a.jsx(Pt,{id:m,priority:m===t?2:1,children:a.jsx(_t,{value:m,icon:Lu[m],children:Ut[m].label})},m)),a.jsx(yw,{onSelect:p})]}),a.jsx(pw,{location:t,table:r,compact:!0}),l&&a.jsx(Dt,{size:"small",info:Hd,infoButton:{"aria-label":"How Unified Interface shows this tab"}})]})}),a.jsx(hw,{}),a.jsxs(Xe,{checkedValues:{view:[d]},onCheckedValueChange:(m,g)=>u(g.checkedItems[0]),children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsxs(K,{appearance:"subtle",size:"small",icon:a.jsx(it,{}),iconPosition:"after","aria-label":`View as: ${Mo[d]}`,className:e.pinned,children:[a.jsx("span",{className:e.muted,children:"View: "}),a.jsx("span",{className:e.viewValue,children:Mo[d]})]})}),a.jsx(Ye,{children:a.jsx(Je,{children:Object.keys(Mo).map(m=>a.jsx(Sn,{name:"view",value:m,children:Mo[m]},m))})})]})]})}function yw({onSelect:e}){const{ref:t,isOverflowing:n,overflowCount:o}=ga();return n?a.jsxs(Xe,{children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(K,{ref:t,appearance:"transparent",size:"small",icon:a.jsx(it,{}),iconPosition:"after","aria-label":`${o} more locations`,children:"More"})}),a.jsx(Ye,{children:a.jsx(Je,{children:Bu.map(s=>a.jsx(xw,{location:s,onSelect:e},s))})})]}):null}function xw({location:e,onSelect:t}){return ba(e)?null:a.jsx(fe,{icon:Lu[e],onClick:()=>t(e),children:Ut[e].label})}const tr=me({empty:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:h.spacingVerticalM,padding:h.spacingHorizontalXXL,textAlign:"center",color:h.colorNeutralForeground3},icon:{fontSize:"40px",color:h.colorNeutralForeground4},body:{maxWidth:"420px"},loading:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM,padding:h.spacingHorizontalM},skeletonRow:{display:"flex",gap:h.spacingHorizontalS},skeletonCards:{display:"flex",gap:h.spacingHorizontalM,flexWrap:"wrap"},card:{flex:"1 1 200px",height:"140px"},status:{color:h.colorNeutralForeground2},error:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,padding:h.spacingHorizontalM,maxWidth:"720px"},details:{margin:0,fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:h.colorNeutralForeground2}});function Sw({kind:e}){const t=tr(),n=Z(s=>s.setSolutionPickerOpen),o=Z(s=>s.setTablePickerOpen);return e==="noSolution"?a.jsxs("div",{className:t.empty,children:[a.jsx(_l,{className:t.icon,"aria-hidden":"true"}),a.jsx(V,{size:500,weight:"semibold",children:"Choose a solution to start"}),a.jsx(V,{className:t.body,children:"Your changes are saved to the solution you pick. Only unmanaged solutions are listed."}),a.jsx(K,{appearance:"primary",onClick:()=>n(!0),children:"Choose solution"})]}):a.jsxs("div",{className:t.empty,children:[a.jsx(da,{className:t.icon,"aria-hidden":"true"}),a.jsx(V,{size:500,weight:"semibold",children:"Pick a table"}),a.jsx(V,{className:t.body,children:"Choose a table from this solution to see and change its command bars."}),a.jsx(K,{appearance:"primary",onClick:()=>o(!0),children:"Choose table"})]})}function vw({table:e,step:t}){const n=tr();return a.jsxs("div",{className:n.loading,children:[a.jsx(ng,{thickness:"medium","aria-label":"Loading"}),a.jsxs(V,{role:"status","aria-live":"polite",className:n.status,children:[e?`Loading ${e}`:"Loading the ribbon",t?` · ${t}`:""]}),a.jsxs(og,{"aria-hidden":"true",className:n.loading,children:[a.jsx("div",{className:n.skeletonRow,children:[70,80,90,60,75].map(o=>a.jsx(Sr,{style:{width:o,height:32}},o))}),a.jsx("div",{className:n.skeletonCards,children:[0,1,2].map(o=>a.jsx(Sr,{className:n.card},o))})]})]})}function ww(e){return/\b401\b|unauthori[sz]ed/i.test(e)?"Your connection may have expired.":/\b403\b|forbidden|privilege/i.test(e)?"Your account may not have permission to read this table's ribbon.":/\b(429|503|504)\b|timeout|timed out/i.test(e)?"Dataverse was busy or didn't answer in time. Try again in a moment.":/\b5\d\d\b/.test(e)?"Dataverse returned an error.":/failed to fetch|network/i.test(e)?"The connection to Dataverse failed.":"Something went wrong while reading it."}function Cw({table:e,error:t,onRetry:n}){const o=tr(),[s,i]=E.useState("");return a.jsxs("div",{className:o.error,children:[a.jsxs(Rt,{intent:"error",layout:"multiline",children:[a.jsxs($t,{children:[a.jsxs(pc,{children:["Couldn't load ",e?`${e}'s`:"the"," ribbon"]}),ww(t)]}),n&&a.jsx(ms,{children:a.jsx(K,{size:"small",appearance:"primary",onClick:n,children:"Retry"})})]}),a.jsx(bc,{collapsible:!0,children:a.jsxs(yc,{value:"details",children:[a.jsx(xc,{size:"small",children:"Details"}),a.jsxs(Sc,{children:[a.jsx("pre",{className:o.details,children:t}),a.jsx(K,{size:"small",onClick:async()=>i((await Ts(t)).ok?"yes":"no"),children:s==="yes"?"Copied":s==="no"?"Couldn't copy":"Copy details"})]})]})})]})}const Iw=me({root:{display:"flex",flexDirection:"column",flex:1,minWidth:0,overflow:"hidden",backgroundColor:h.colorNeutralBackground1},messages:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`},canvas:{flex:1,overflow:"auto",padding:h.spacingHorizontalM}}),jw=me({root:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"80px",gap:h.spacingHorizontalM,color:h.colorNeutralForeground3}});function Rw({isLoadingRibbon:e=!1,loadingTable:t,loadingStep:n=null,ribbonLoadError:o=null,layerReadError:s=null,onRetryRibbonLoad:i,emptyState:l}){const r=Iw(),c=J($=>$.location),d=J($=>$.tabId),u=J($=>$.setTabId),p=M($=>$.ribbons),m=M($=>$.orphans.entity.filter(w=>!$.pendingOrphanDeletes.entity.includes(w.id)&&!w.recentPublish?.published).map(w=>w.id).sort().join("|")),g=m?m.split("|").length:0,b=ae($=>$.connectionUrl),f=J($=>$.clearSelection),y=Z($=>$.ribbonViewStyle),x=Z($=>$.openNewGroup),S=Z($=>$.setPropertiesRequested),[C,N]=E.useState(!1),O=p[c],I=O.tabs.find($=>$.id===d)??O.tabs.find($=>$.id===mo(O.tabs));E.useEffect(()=>{if(!O.tabs.length)return;if(!O.tabs.some(w=>w.id===d)){const w=mo(O.tabs);w&&u(w)}},[O.tabs,d,u]);const j=[];return s&&!e&&!o&&j.push({id:"layer-read",intent:"warning",title:"Couldn't read your unmanaged ribbon customizations",body:`Labels may show as ids, and what you can edit or delete is unknown. Reload before editing. Details: ${s}`,dismissible:!1,actions:i&&a.jsx(K,{size:"small",onClick:()=>_o()?N(!0):i(),children:"Retry"})}),I&&xo(I.id)&&j.push({id:`hidden-tab:${I.id}`,intent:"warning",title:"Unified Interface doesn't show this tab's buttons",body:"They don't come back when the table is reloaded either. Add buttons to the table's main tab instead."}),c!=="Application"&&g>0&&j.push({id:"orphans",intent:"warning",signature:m,title:`${g} of your customizations ${g!==1?"aren't":"isn't"} on the canvas`,body:a.jsxs(a.Fragment,{children:["The ribbon doesn't return ",g!==1?"them":"it",". See"," ",a.jsx("strong",{children:"Orphaned customizations"})," in the Properties pane to delete"," ",g!==1?"them":"it","."]}),actions:a.jsx(K,{size:"small",onClick:()=>{f(),S(!0)},children:"Show"})}),l?a.jsx("main",{className:r.root,"aria-label":"Ribbon canvas",children:a.jsx(Sw,{kind:l})}):a.jsxs("main",{className:r.root,"aria-label":"Ribbon canvas",children:[a.jsx(bw,{}),a.jsx(Ua,{messages:j,scope:`canvas:${b}:${O.entityLogicalName}:${c}`,className:r.messages}),a.jsx("div",{className:r.canvas,children:e?a.jsx(vw,{table:t,step:n}):o?a.jsx(Cw,{table:t,error:o,onRetry:i}):I?a.jsxs(a.Fragment,{children:[y==="groups"?a.jsxs(a.Fragment,{children:[a.jsx(Yv,{tab:I,location:c}),a.jsx(gv,{tab:I,location:c})]}):y==="classic"?a.jsx(mv,{tab:I,location:c}):y==="modern"?a.jsx(nw,{tab:I,location:c}):a.jsx(rw,{tab:I,location:c}),a.jsx(lw,{tab:I,location:c})]}):a.jsx($w,{onAddGroup:x})}),C&&i&&a.jsx(Bn,{open:!0,title:"Reload the ribbon",confirmLabel:"Reload",onConfirm:()=>{N(!1),i()},onCancel:()=>N(!1),children:"You have unpublished changes. Reloading replaces the canvas; your changes are kept in a draft that is offered after the reload. They were made while your labels weren't loaded, so check their texts before you publish: a text can read a label's id."})]})}function $w({onAddGroup:e}){const t=jw();return a.jsxs("div",{className:t.root,children:[a.jsx(us,{fontSize:32,style:{opacity:.4}}),a.jsx(V,{size:300,children:"This tab has no groups yet"}),a.jsx(K,{appearance:"primary",size:"small",icon:a.jsx(ke,{}),onClick:e,children:"Add first group"})]})}let Yn=null;const ea={set(e){Yn=e},invoke(e){const t=Yn;Yn=null,t?.(e)},clear(){Yn=null},hasPending(){return Yn!==null}},Nw=me({field:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS,minWidth:0},row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,minWidth:0},input:{flex:1,minWidth:0,backgroundColor:h.colorNeutralBackground3},srOnly:{position:"absolute",width:"1px",height:"1px",overflow:"hidden",clipPath:"inset(50%)",whiteSpace:"nowrap"},value:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,textOverflow:"ellipsis"}}),zu=({label:e,value:t,action:n,hideLabel:o})=>{const s=Nw(),i=E.useId(),[l,r]=E.useState("idle"),c=E.useRef(void 0);E.useEffect(()=>()=>clearTimeout(c.current),[]);const d=async()=>{const m=await Ts(t);r(m.ok?"copied":"failed"),clearTimeout(c.current),c.current=setTimeout(()=>r("idle"),2e3)},u=l==="copied"?`${e} copied`:l==="failed"?`Couldn't copy the ${e.toLowerCase()}`:`Copy ${e.toLowerCase()}`,p=a.jsxs("div",{className:s.row,children:[a.jsx(pe,{content:t,relationship:"description",withArrow:!0,children:a.jsx(Ft,{id:i,className:s.input,input:{className:s.value},value:t,readOnly:!0,appearance:"filled-darker","aria-label":o?e:void 0})}),a.jsx(pe,{content:u,relationship:"label",children:a.jsx(K,{appearance:"subtle",icon:l==="copied"?a.jsx(sc,{}):a.jsx(yo,{}),onClick:()=>{d()}})}),n,a.jsx("span",{"aria-live":"polite",className:s.srOnly,children:l==="idle"?"":u})]});return o?p:a.jsxs("div",{className:s.field,children:[a.jsx(sg,{htmlFor:i,size:"small",weight:"semibold",children:e}),p]})},Tw=["button","flyout","splitButton","textBox","comboBox","checkBox"],kw=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM,minWidth:0},row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS},localeChips:{display:"flex",flexWrap:"wrap",gap:h.spacingHorizontalXS,alignItems:"center"},iconPreview:{width:"32px",height:"32px",borderRadius:"6px",backgroundColor:h.colorNeutralBackground4,color:h.colorNeutralForeground1,display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${h.colorNeutralStroke2}`,flexShrink:0},keyHint:{overflowWrap:"anywhere"},lockedNote:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,color:h.colorNeutralForeground2},webResLink:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,cursor:"pointer",color:h.colorBrandForeground1,textDecoration:"underline",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1,border:"none",background:"transparent",textAlign:"left"}});function ri({button:e,location:t,tabId:n,groupId:o,part:s}){const i=kw(),l=M(I=>I.setButtonProp),r=M(I=>I.locLabels),c=M(I=>I.baseLanguageCode),d=Z(I=>I.openIconPicker),u=Z(I=>I.openLocalizationEditor),p=Z(I=>I.openWebResourceBrowser),m=M(I=>!I.ribbons[t].tabs.find(j=>j.id===n)?.groups.find(j=>j.id===o)?.buttons.some(j=>j.id===e.id)),g=M(I=>Id(I,t,e.id)),b=M(I=>I.ribbons[t].tabs.find(j=>j.id===n)?.groups.find(j=>j.id===o)),f=Ee(),y=[...new Set([...m?Na:Tw,e.kind])];function x(I){l(t,n,o,e.id,I)}const S=e.origin!=="unmanaged",C={label:f(e.label,r,void 0,e.source?.labelToken),tooltipTitle:f(e.tooltipTitle,r,void 0,e.source?.tooltipTitleToken),tooltipBody:f(e.tooltipBody,r,void 0,e.source?.tooltipBodyToken)},N=(I,j)=>I&&I!==j?{children:`From ${I}`,className:i.keyHint}:void 0,O=Cb(e,r,c);return s==="position"?a.jsxs("div",{className:i.root,children:[a.jsx(_e,{label:"Group",hint:"Use Move to in the button's menu to move it.",children:a.jsx(Ft,{readOnly:!0,appearance:"filled-darker",value:b?f(b.label,r,c,b.source?.titleToken)||b.id:o})}),a.jsx(_e,{label:"Order",hint:"Lower numbers show first within the group. Unified Interface merges the groups into one bar.",children:a.jsx(ig,{value:e.sequence,disabled:S,step:10,min:0,onChange:(I,j)=>x({sequence:Number(j.value??e.sequence)})})})]}):s==="advanced"?a.jsxs("div",{className:i.root,children:[a.jsx(_e,{label:"Kind",hint:g?"A loaded control's kind can't be changed: add a new control instead.":m?"A menu holds buttons and flyouts.":void 0,children:a.jsx(ya,{value:e.kind,disabled:g,onChange:(I,j)=>x({kind:j.value}),children:y.map(I=>a.jsx("option",{value:I,children:yt[I]},I))})}),a.jsx(_e,{label:"Template alias",hint:"Which slot of the group's layout the button uses on the classic ribbon, for example o1.",children:a.jsx(Ft,{value:e.templateAlias,readOnly:S,onChange:(I,j)=>x({templateAlias:j.value})})})]}):a.jsxs("div",{className:i.root,children:[S&&a.jsxs(V,{size:200,className:i.lockedNote,children:[a.jsx(dn,{"aria-hidden":!0})," Customise this button, or create an override, to edit these fields."]}),a.jsx(_e,{label:"Label",hint:S?N(e.label,C.label):void 0,children:a.jsx(Ft,{value:S?C.label:e.label,readOnly:S,appearance:S?"filled-darker":void 0,onChange:(I,j)=>x({label:j.value})})}),a.jsx(_e,{label:"Translations",children:a.jsxs("div",{className:i.localeChips,children:[a.jsx(vc,{"aria-label":"Languages of this button's text",size:"small",children:(O.length?O:[1033]).map(I=>a.jsx(va,{value:String(I),appearance:"brand",children:a.jsxs(wa,{disabled:S,onClick:()=>u(e.id),children:[I===1033?"en-US":String(I),O.length===0?" (default)":""]})},I))}),a.jsx(K,{size:"small",appearance:"subtle",icon:a.jsx(ke,{}),disabled:S,onClick:()=>u(e.id),children:"Add language…"})]})}),a.jsx(_e,{label:"Tooltip title",hint:S?N(e.tooltipTitle,C.tooltipTitle):void 0,children:a.jsx(Ft,{value:S?C.tooltipTitle:e.tooltipTitle??"",readOnly:S,appearance:S?"filled-darker":void 0,onChange:(I,j)=>x({tooltipTitle:j.value})})}),a.jsx(_e,{label:"Tooltip body",hint:S?N(e.tooltipBody,C.tooltipBody):void 0,children:a.jsx(ag,{value:S?C.tooltipBody:e.tooltipBody??"",readOnly:S,appearance:S?"filled-darker":void 0,onChange:(I,j)=>x({tooltipBody:j.value}),resize:"vertical"})}),a.jsx(Lo,{}),a.jsx(_e,{label:"Icon",children:a.jsxs("div",{className:i.row,children:[a.jsx("div",{className:i.iconPreview,children:e.icon?a.jsx(Ka,{name:e.icon,size:20}):a.jsx(bi,{style:{color:h.colorNeutralForeground3}})}),a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(bi,{}),disabled:S,onClick:d,children:"Change…"})]})}),e.icon&&a.jsx(_e,{label:"Modern image",hint:"What Unified Interface shows. Set from the icon you pick.",children:a.jsx(Ft,{value:Oa(e)??"(none)",readOnly:!0})}),e.image16&&a.jsx(_e,{label:"Image16",children:a.jsx("div",{className:i.row,children:a.jsx(pe,{content:e.image16,relationship:"description",children:a.jsx($n,{as:"button",className:i.webResLink,disabled:S,onClick:()=>{ea.set(I=>{x({image16:`$webresource:${I.name}`,icon:I.name.split("/").pop()?.replace(/\..*$/,"")})}),p()},children:e.image16})})})}),e.image32&&a.jsx(_e,{label:"Image32",children:a.jsx("div",{className:i.row,children:a.jsx(pe,{content:e.image32,relationship:"description",children:a.jsx($n,{as:"button",className:i.webResLink,disabled:S,onClick:()=>{ea.set(I=>{x({image32:`$webresource:${I.name}`})}),p()},children:e.image32})})})}),a.jsx(xa,{label:"Visible",checked:!e.hidden,onChange:(I,j)=>x({hidden:!j.checked})}),a.jsx(zu,{label:"Button ID",value:e.id})]})}const Aw=me({row:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:h.spacingHorizontalS}}),Ow={oob:"informative",customising:"warning",customised:"brand",uncustomising:"danger",custom:"success",reloadRequired:"danger"};function Do(e){return e.scope==="application"?"the application ribbon's layer (every table)":e.sharedWithApplication?"this table's layer only (the application ribbon keeps the original)":"this table's layer"}function Mw({commandId:e,compact:t=!1,hideBadge:n=!1}){const o=Aw(),s=Va(e),i=M(x=>x.customiseCommand),l=M(x=>x.uncustomiseCommand),r=M(x=>x.discardCommandChanges),c=M(x=>{const S=x.commands.find(N=>N.id===e),C=x.baselineCommands.find(N=>N.id===e);return!!S&&!!C&&JSON.stringify(S)!==JSON.stringify(C)}),[d,u]=E.useState(null);if(!s)return null;const p=(x,S,C)=>{c?u({what:x,confirmLabel:S,run:C}):C()},m=d&&a.jsxs(Bn,{open:!0,title:"Discard unpublished changes?",confirmLabel:d.confirmLabel,destructive:!0,onConfirm:()=>{d.run(),u(null)},onCancel:()=>u(null),children:[d.what," discards your unpublished changes to ",a.jsx("code",{children:e}),"."]}),{provenance:g}=s,b=g==="oob"?a.jsx(K,{size:"small",appearance:"outline",onClick:()=>i(e),children:"Customise command"}):g==="customising"?a.jsx(K,{size:"small",appearance:"subtle",onClick:()=>p("Discarding the customisation","Discard customisation",()=>r(e)),children:"Discard customisation"}):g==="customised"?a.jsx(K,{size:"small",appearance:"subtle",onClick:()=>p("Uncustomising","Uncustomise",()=>l(e,s.scope)),children:"Uncustomise"}):g==="uncustomising"?a.jsx(K,{size:"small",appearance:"subtle",onClick:()=>r(e),children:"Undo uncustomise"}):null,f=a.jsx(xe,{appearance:g==="oob"?"outline":"filled",color:Ow[g],size:"medium",children:kS[g]});if(t)return a.jsxs("div",{className:o.row,children:[f,b,m]});const y={oob:`Out of the box or from another solution, so it's read-only. Customise it to copy it — actions, parameters and rules — into ${Do(s)} and change it there; its buttons keep using it.`,customising:`On publish, this command is copied into ${Do(s)} and replaces the original there. Rules keep their ids; a rule you edit is written to the layer as well.`,customised:`${Do(s).replace(/^./,x=>x.toUpperCase())} has a copy of this command that replaces the original. Uncustomise to remove the copy so the original applies again.`,uncustomising:`On publish, the copy of this command in ${Do(s)} is removed (with rules only it used) and the original applies again. Reload the table after publishing to see the original definition.`,custom:"Your own command.",reloadRequired:"Your layer's copy of this command was removed, so the original applies. What is shown here is the removed copy: reload the table to load the original before changing or customising it again."};return g==="custom"?n?null:a.jsx("div",{className:o.row,children:f}):a.jsxs(a.Fragment,{children:[a.jsxs(Rt,{layout:"multiline",intent:g==="uncustomising"||g==="reloadRequired"?"warning":"info",children:[a.jsx($t,{children:a.jsxs("div",{className:o.row,children:[!n&&f,a.jsx(V,{size:200,children:y[g]})]})}),b&&a.jsx(ms,{children:b})]}),m]})}const Dw=me({field:{minWidth:0},combobox:{minWidth:0,width:"100%"},listbox:{maxHeight:"280px",maxWidth:"min(480px, 90vw)",overflowWrap:"anywhere"}});function Pu({label:e,options:t,selected:n,onSelect:o,placeholder:s="Type to filter",noOptionsMessage:i="Nothing matches.",hint:l}){const r=Dw(),[c,d]=E.useState(n),[u,p]=E.useState(n);u!==n&&(p(n),d(n));const m=uc(c,t.map(b=>({value:b,children:b})),{noOptionsMessage:i,optionToReactKey:b=>b.value,optionToText:b=>b.value}),g=(b,f)=>{d(f.optionText??""),o(f.optionValue??"")};return a.jsx(_e,{label:e,hint:l,className:r.field,children:a.jsx(ua,{size:"small",freeform:!0,clearable:!0,className:r.combobox,listbox:{className:r.listbox},placeholder:s,value:c,selectedOptions:n?[n]:[],onChange:b=>{d(b.target.value),n&&o("")},onOptionSelect:g,children:m})})}const Ew=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM,minWidth:0},commandRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:h.spacingHorizontalS,padding:`${h.spacingHorizontalXS} ${h.spacingHorizontalS}`,borderRadius:h.borderRadiusMedium,border:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground3},commandId:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,color:h.colorNeutralForeground1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function Bw({button:e,groupId:t,tabId:n,location:o}){const s=Ew(),i=M(f=>f.commands),l=M(f=>f.upsertCommand),r=M(f=>f.setButtonProp),c=M(f=>f.batch),d=Z(f=>f.openCommandEditor),[u,p]=et.useState(""),m=i.find(f=>f.id===e.commandId),g=()=>{const f=new Set(i.map(x=>x.id)),y=La("New","Command",f);c(()=>{l({id:y,enableRules:[],displayRules:[],actions:[]}),r(o,n,t,e.id,{commandId:y})}),d(y)},b=()=>{u&&(r(o,n,t,e.id,{commandId:u}),p(""))};return a.jsx("div",{className:s.root,children:m?a.jsxs(a.Fragment,{children:[a.jsx(zu,{label:"Command ID",value:m.id,action:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(On,{}),onClick:()=>d(m.id),children:"Edit command"})}),a.jsx(Mw,{commandId:m.id,compact:!0}),m.actions.length>0&&a.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:m.actions.map((f,y)=>a.jsx(Bs,{size:"extra-small",appearance:"outline",children:f.kind==="javascript"?`JS: ${f.functionName}`:f.kind==="url"?`URL: ${f.address}`:f.kind==="powerFx"?`Fx: ${f.expression}`:f.kind==="customApi"?`API: ${f.actionName}`:f.kind==="outlookCommand"?`Outlook: ${f.actionType}`:`XML: ${f.tagName}`},y))}),m.enableRules.length>0&&a.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:"Enable rules:"}),m.enableRules.map(f=>a.jsx(Bs,{size:"extra-small",appearance:"outline",color:"success",children:f},f))]}),m.displayRules.length>0&&a.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:"Display rules:"}),m.displayRules.map(f=>a.jsx(Bs,{size:"extra-small",appearance:"outline",color:"informative",children:f},f))]})]}):e.commandId?a.jsx("div",{className:s.commandRow,children:a.jsxs(V,{className:s.commandId,style:{color:h.colorStatusWarningForeground3},children:[e.commandId," (not found)"]})}):a.jsxs(a.Fragment,{children:[a.jsx(Pu,{label:"Use an existing command",options:i.map(f=>f.id),selected:u,onSelect:p,noOptionsMessage:"No command matches."}),a.jsxs("div",{style:{display:"flex",gap:h.spacingHorizontalXS},children:[a.jsx(K,{appearance:"outline",size:"small",disabled:!u,onClick:b,children:"Bind"}),a.jsx(K,{appearance:"outline",size:"small",icon:a.jsx(ke,{}),onClick:g,children:"Create and bind"})]})]})})}const Lw=new Set(["enablerule","displayrule","rule","enable","display","tabdisplayrule","mscrm"]);function zw(e){const t=e.split(".").filter(Boolean);for(let n=t.length-1;n>=0;n--)if(!Lw.has(t[n].toLowerCase()))return t[n];return e}const Pw=({ruleId:e,kind:t,onOpen:n,onRemove:o})=>{const s=zw(e),i=t==="enable"?"enable rule":"display rule";return a.jsxs(va,{value:e,size:"small",appearance:"outline",children:[a.jsx(pe,{content:e,relationship:"description",children:a.jsx(wa,{hasSecondaryAction:!!o,onClick:n,children:s})}),o&&a.jsx(rg,{"aria-label":`Unbind ${i} ${s}`,onClick:o})]})},Fw=me({section:{display:"flex",flexDirection:"column",gap:h.spacingHorizontalXS},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS},pillList:{display:"flex",flexWrap:"wrap",gap:h.spacingHorizontalXS,maxWidth:"100%",minWidth:0},addBtn:{alignSelf:"flex-start"},note:{fontSize:h.fontSizeBase200,color:h.colorNeutralForeground3,fontStyle:"italic"}}),Fu=({kind:e})=>{const t=Fw(),n=J(k=>k.location),o=J(k=>k.tabId),s=J(k=>k.selectedGroupId),i=J(k=>k.selectedButtonId),l=M(k=>k.commands),r=M(k=>k.displayRules),c=M(k=>k.enableRules),d=M(k=>k.upsertCommand),u=M(k=>k.upsertDisplayRule),p=M(k=>k.upsertEnableRule),m=M(k=>k.batch),g=Z(k=>k.openRuleEditor),x=M(k=>k.ribbons)[n].tabs.find(k=>k.id===o)?.groups.find(k=>k.id===s),S=Ss(x,i),C=l.find(k=>k.id===S?.commandId),N=e==="display"?C?.displayRules??[]:C?.enableRules??[],O=e==="display"?r:c,[I,j]=et.useState(""),$=O.filter(k=>!N.includes(k.id)),w=k=>{if(!C)return;const v=N.filter(T=>T!==k);d(e==="display"?{...C,displayRules:v}:{...C,enableRules:v})},A=()=>{if(!C)return;if(e==="display"){const T=new Set(r.map(D=>D.id)),R=uo(Lr(C.id),"Display",T);m(()=>{u({id:R,steps:[]}),d({...C,displayRules:[...C.displayRules,R]})}),g(R,"display");return}const k=new Set(c.map(T=>T.id)),v=uo(Lr(C.id),"Enable",k);m(()=>{p({id:v,steps:[]}),d({...C,enableRules:[...C.enableRules,v]})}),g(v,"enable")},B=()=>{!C||!I||(d(e==="display"?{...C,displayRules:[...C.displayRules,I]}:{...C,enableRules:[...C.enableRules,I]}),j(""))};return a.jsxs("div",{className:t.section,children:[!C&&a.jsx(V,{className:t.note,children:"Bind a command first to manage rules."}),N.length>0&&a.jsx(vc,{className:t.pillList,"aria-label":e==="display"?"Bound display rules":"Bound enable rules",children:N.map(k=>a.jsx(Pw,{ruleId:k,kind:e,onOpen:()=>g(k,e),onRemove:()=>w(k)},k))}),C&&a.jsxs(a.Fragment,{children:[a.jsx(Pu,{label:`Bind an existing ${e} rule`,options:$.map(k=>k.id),selected:I,onSelect:j,noOptionsMessage:"No rule matches."}),a.jsxs("div",{style:{display:"flex",gap:h.spacingHorizontalXS},children:[a.jsx(K,{className:t.addBtn,appearance:"subtle",size:"small",onClick:B,disabled:!I,children:"Bind"}),a.jsxs(K,{className:t.addBtn,appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:A,children:["Create new ",e," rule"]})]})]}),e==="enable"&&a.jsx(Dt,{size:"small",info:"Disabled buttons are hidden in the modern command bar (Unified Interface). In the classic ribbon, they stay visible but do nothing when clicked.",children:"What a failing enable rule does"})]})},_w=()=>a.jsx(Fu,{kind:"display"}),qw=()=>a.jsx(Fu,{kind:"enable"}),Ww=me({section:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS},note:{color:h.colorNeutralForeground2}}),Hw=()=>{const e=Ww(),t=J(p=>p.location),n=J(p=>p.tabId),o=M(p=>p.ribbons[t]),s=M(p=>p.locLabels),i=M(p=>p.baseLanguageCode),l=Ee(),r=o.tabs.find(p=>p.id===n),c=o.scalingByTab?.[n],d=(c?.maxSizes.length??0)+(c?.scales.length??0),u=r?.groups.length??0;return a.jsxs("div",{className:e.section,children:[r?a.jsxs(V,{size:200,className:e.note,children:["“",l(r.label,s,i,r.source?.titleToken)||r.id,"” has ",u," group",u===1?"":"s"," and ",d," scaling step",d===1?"":"s","."]}):a.jsx(V,{size:200,className:e.note,children:"Select a tab to see its scaling."}),a.jsx(V,{size:200,className:e.note,children:"Scaling decides how groups shrink as the classic ribbon narrows; Unified Interface ignores it. Command Bar Studio can't change it yet."})]})},Gw=me({section:{display:"flex",flexDirection:"column",gap:h.spacingHorizontalXS},row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS},note:{fontSize:h.fontSizeBase200,color:h.colorNeutralForeground3}}),Uw=()=>{const e=Gw(),t=J(C=>C.location),n=J(C=>C.selectedButtonId),o=M(C=>C.ribbons),s=Z(C=>C.openCommandEditor),i=M(C=>C.setOpenRecordOverride),l=J(C=>C.clearSelection),r=ae(C=>C.activeSolution),c=ae(C=>C.publisherPrefix),d=o[t],u=hd.includes(t),p=bd(d),m=p.length>0,g=p.map(C=>yd(C)),b=g.includes("theirs"),f=!b&&g.includes("unknown"),y=!m&&!xd(d),x=Fa(d).filter(C=>!gd(C.button)),S=C=>{const N=r?.publisherPrefix?.trim()||c?.trim()||"new";!C&&p.some(O=>O.button.id===n)&&l(),!(!i(t,C,N)||!C)&&s(Ve)};return a.jsxs("div",{className:e.section,children:[u&&a.jsxs("div",{children:[a.jsx(xa,{label:a.jsx(Dt,{info:a.jsxs(a.Fragment,{children:["When on, double-clicking a row of this table's"," ",t==="SubGrid"?"sub-grids (on any form)":"home grid",", selecting its primary column link or pressing Enter runs your command instead of opening the record. Unified Interface only. As Microsoft's recipe requires, an “Open record” button using the command is added here: don't hide it. The Command Editor opens so you can set the script; Publish waits until you do. Turning it off removes that button."]}),children:`Override opening a record from the ${t==="SubGrid"?"sub-grid":"home grid"}`}),checked:m,disabled:b||f||y,onChange:(C,N)=>S(N.checked)}),b&&a.jsx(V,{size:200,className:e.note,children:`The "Open record" button here comes from another solution, so the override can't be turned off from your customizations.`}),f&&a.jsx(V,{size:200,className:e.note,children:`CBS doesn't know yet which solution the "Open record" button here comes from (its solution layers haven't loaded), so it isn't removed — reload the table if this doesn't clear.`}),x.length>0&&a.jsxs(V,{size:200,className:e.note,children:["Also using Mscrm.OpenRecordItem here:"," ",x.map(C=>C.button.id).join(", "),". Turning the override off keeps ",x.length===1?"it":"them"," ","and the command."]}),y&&a.jsx(V,{size:200,className:e.note,children:"This location has no group to put the button in."})]}),t==="Form"&&a.jsxs(V,{size:200,className:e.note,children:["Changes apply to every main form of this table."," ",a.jsx(Dt,{size:"small",info:"Unified Interface doesn't support a ribbon for one form only, so Command Bar Studio changes the table's form ribbon, which all its main forms use.",infoButton:{"aria-label":"Why every form"}})]})]})},Vw=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,minWidth:0},id:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200},pending:{textDecoration:"line-through",color:h.colorNeutralForeground3}});function Xw(){const e=Vw(),t=M(i=>i.layers),n=M(i=>i.pendingUnhides),o=M(i=>i.setLayerHideUnhidden),s=["entity","application"].flatMap(i=>(t[i]?.hides??[]).map(l=>({scope:i,...l})));return s.length===0?null:a.jsxs("section",{className:e.root,"aria-label":"Hidden by customizations",children:[a.jsx(V,{as:"h3",size:300,weight:"semibold",children:"Hidden by customizations"}),a.jsx(Ze,{children:"Hidden by a HideCustomAction in your unmanaged customizations, so they aren't on the canvas. Un-hiding takes effect when you publish; reload afterwards to see them."}),s.map(i=>{const l=n[i.scope].includes(i.location);return a.jsxs("div",{className:e.row,children:[a.jsx(Et,{}),a.jsx(pe,{content:`${i.location} (${i.scope==="entity"?"this table":"application ribbon"})`,relationship:"description",children:a.jsx(V,{className:`${e.id} ${l?e.pending:""}`,children:i.location})}),a.jsx(K,{size:"small",appearance:l?"subtle":"secondary",onClick:()=>o(i.scope,i.location,!l),children:l?"Keep hidden":"Unhide"})]},`${i.scope}:${i.location}`)})]})}const Kw=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"flex-start",gap:h.spacingHorizontalS,minWidth:0},icon:{flexShrink:0,marginTop:"2px",color:h.colorPaletteMarigoldForeground1},text:{display:"flex",flexDirection:"column",flex:1,minWidth:0},mono:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200},why:{color:h.colorNeutralForeground3},pending:{textDecoration:"line-through",color:h.colorNeutralForeground3}});function Yw(){const e=Kw(),t=M(r=>r.orphans),n=M(r=>r.pendingOrphanDeletes),o=M(r=>r.setOrphanDeleted),[s,i]=E.useState(null),l=["entity","application"].flatMap(r=>t[r].map(c=>({scope:r,...c})));return l.length===0?null:a.jsxs("section",{className:e.root,"aria-label":"Orphaned customizations",children:[a.jsx(V,{as:"h3",size:300,weight:"semibold",children:"Orphaned customizations"}),a.jsx(Ze,{children:"In your unmanaged customizations, but the ribbon doesn't return them, so they aren't on the canvas (and, except for tabs, Unified Interface doesn't show them either). Publishing keeps them unless you delete them. For a while after a publish the ribbon can still be the one from before it (10 minutes or more), so what you just published can show up here: don't delete it, reload later."}),l.map(r=>{const c=n[r.scope].includes(r.id),d=r.label&&r.label!==r.id?`“${r.label}” `:"",u=`${r.scope}:${r.id}`,p=!!r.recentPublish?.published,m=c?a.jsx(K,{size:"small",appearance:"subtle","aria-label":`Keep ${r.id}`,onClick:()=>o(r.scope,r.id,!1),children:"Keep"}):p?a.jsx(pe,{content:"Published from here moments ago: reload later — it most likely isn't loaded yet",relationship:"description",children:a.jsx(K,{size:"small",disabledFocusable:!0,"aria-label":`Delete ${r.id}`,children:"Delete"})}):r.recentPublish?a.jsx(K,{size:"small",appearance:"secondary","aria-label":`Delete ${r.id}`,onClick:()=>i({scope:r.scope,id:r.id,minutesAgo:r.recentPublish?.minutesAgo}),children:"Delete…"}):a.jsx(K,{size:"small",appearance:"secondary","aria-label":`Delete ${r.id}`,onClick:()=>o(r.scope,r.id,!0),children:"Delete"});return a.jsxs("div",{className:e.row,children:[a.jsx(kh,{className:e.icon}),a.jsxs("div",{className:e.text,children:[a.jsx(pe,{content:`${r.element} ${r.id} — CustomAction ${r.customActionId} at ${r.location}`,relationship:"description",children:a.jsxs(V,{className:Ie(e.mono,c&&e.pending),children:[d,r.id]})}),a.jsx(Ze,{className:Ie(e.mono,e.why),children:r.location}),a.jsx(Ze,{className:e.why,children:r.why})]}),m]},u)}),s&&a.jsxs(Bn,{open:!0,title:"Delete a recent customization?",confirmLabel:"Delete anyway",destructive:!0,onConfirm:()=>{o(s.scope,s.id,!0),i(null)},onCancel:()=>i(null),children:[s.id," was published",s.minutesAgo!==void 0?` about ${s.minutesAgo} minute${s.minutesAgo===1?"":"s"} ago`:" recently",". The ribbon may not show it yet, so it may not be orphaned at all. Reload the table later to check before deleting it."]})]})}const Jw=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS},field:{display:"flex",flexDirection:"column",gap:"2px",minWidth:0},mono:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,overflowWrap:"anywhere"},xml:{margin:0,maxHeight:"240px",overflow:"auto",padding:h.spacingHorizontalS,borderRadius:h.borderRadiusMedium,backgroundColor:h.colorNeutralBackground3,fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,whiteSpace:"pre-wrap",overflowWrap:"anywhere"}});function Zw({button:e,location:t,tabId:n,groupId:o}){const s=Jw(),i=M(f=>f.locLabels),l=Ee(),r=M(f=>f.setButtonProp),c=M(f=>f.hideOobButton),d=M(f=>f.hideWithDisplayRules),[u,p]=E.useState(!1),m=t==="Application"&&n==="Mscrm.GlobalTab"&&e.oob&&!e.custom,g=yt[e.kind],b=(f,y)=>y?a.jsxs("div",{className:s.field,children:[a.jsx(Ze,{children:f}),a.jsx(V,{className:s.mono,children:y})]}):null;return a.jsxs("section",{className:s.root,"aria-label":`${g} (read-only)`,children:[a.jsxs("div",{className:s.title,children:[a.jsx(dn,{"aria-hidden":!0}),a.jsx(V,{as:"h3",size:300,weight:"semibold",children:"Shown read-only"})]}),a.jsxs(Ze,{children:["Command Bar Studio shows this <",vn[e.kind],"> but doesn't edit it. You can hide it, and move or delete it when your customizations add it; its XML is published as it was loaded."]}),b("Label",l(e.label,i,void 0,e.source?.labelToken)),b("Id",e.id),b("Command",e.commandId||void 0),a.jsx("div",{children:a.jsx(K,{size:"small",disabled:m,icon:e.hidden?a.jsx(Mn,{}):a.jsx(Et,{}),onClick:()=>!e.hidden&&e.oob?p(!0):r(t,n,o,e.id,{hidden:!e.hidden}),children:e.hidden?"Unhide":"Hide"})}),u&&a.jsx(su,{open:!0,buttonLabel:l(e.label,i,void 0,e.source?.labelToken),buttonId:e.id,commandId:e.commandId,onConfirmHide:()=>{c(t,n,o,e.id),p(!1)},onConfirmDisplayRule:()=>{d(e.commandId),p(!1)},onCancel:()=>p(!1)}),e.source?.xml&&a.jsxs("div",{className:s.field,children:[a.jsx(Ze,{children:"XML"}),a.jsx("pre",{className:s.xml,children:e.source.xml})]})]})}const _u=me({root:{display:"flex",flexDirection:"column",gap:h.spacingVerticalS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:h.spacingHorizontalS,flexWrap:"wrap"},grid:{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:h.spacingHorizontalM,rowGap:h.spacingVerticalXS,alignItems:"baseline"},key:{color:h.colorNeutralForeground3,fontSize:h.fontSizeBase200},value:{fontSize:h.fontSizeBase200,overflowWrap:"anywhere",minWidth:0},mono:{fontFamily:h.fontFamilyMonospace},list:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS}});function Tt({label:e,value:t,mono:n}){const o=_u();return t?a.jsxs(a.Fragment,{children:[a.jsx(V,{className:o.key,children:e}),a.jsx(V,{className:`${o.value} ${n?o.mono:""}`,children:t})]}):null}function Qw({command:e,items:t}){const n=_u(),o=Ln(),s=we(r=>r.selectCommand),i=we(r=>e.parentId?r.commands.find(c=>c.id===e.parentId):void 0),l=e.visibility==="formula"||e.action==="formula";return a.jsxs("section",{className:n.root,"aria-label":"Modern command properties",children:[a.jsxs("div",{className:n.title,children:[a.jsx(lg,{children:e.label}),a.jsx(xe,{appearance:"tint",color:"important",children:"Modern"}),e.managed&&a.jsx(xe,{appearance:"outline",color:"informative",children:"Managed"})]}),a.jsx(Rt,{intent:"info",children:a.jsx($t,{children:"Modern commands are read-only in Command Bar Studio and are never published from here. Edit them in the command designer."})}),a.jsxs("div",{className:n.grid,children:[Ru(e,o).map(r=>a.jsx(Tt,{label:r.label,value:r.value},r.label)),a.jsx(Tt,{label:"Tooltip title",value:e.tooltipTitle}),a.jsx(Tt,{label:"Tooltip text",value:e.tooltipDescription}),a.jsx(Tt,{label:"Accessibility text",value:e.accessibilityText}),a.jsx(Tt,{label:"Icon",value:e.fontIcon??e.iconWebResourceName??e.iconWebResourceId}),a.jsx(Tt,{label:"Group title",value:e.groupTitle}),a.jsx(Tt,{label:"Name",value:e.name}),a.jsx(Tt,{label:"Unique name",value:e.uniqueName,mono:!0}),a.jsx(Tt,{label:"Id",value:e.id,mono:!0})]}),l&&a.jsx(Ze,{children:"Power Fx formulas are stored in the app's command component library, not on the command, so only the function reference is shown here."}),i&&a.jsxs(a.Fragment,{children:[a.jsx(Lo,{}),a.jsx(V,{className:n.key,children:"Inside"}),a.jsx($n,{onClick:()=>s(i.id),children:i.label})]}),t.length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Lo,{}),a.jsxs(V,{className:n.key,children:["Items (",t.length,")"]}),a.jsx("div",{className:n.list,children:t.map(r=>a.jsxs($n,{onClick:()=>s(r.id),children:[r.label,r.hidden?" (hidden)":""]},r.id))})]}),e.classicRules.length>0&&a.jsxs(a.Fragment,{children:[a.jsx(Lo,{}),a.jsxs(V,{className:n.key,children:["Classic rules (",e.classicRules.length,")"]}),a.jsx("div",{className:n.list,children:e.classicRules.map(r=>a.jsxs(V,{className:`${n.value} ${n.mono}`,children:[r.kind==="enable"?"Enable":"Display",":"," ",r.uniqueName??r.name]},r.id))})]})]})}const eC=me({slot:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`},list:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS}});function tC({button:e,location:t,tabId:n,groupId:o,overrides:s}){const i=eC(),l=M(x=>x.customizeOobButton),r=M(x=>x.customiseButton),c=M(x=>x.conflicts),d=ae(x=>x.activeSolution),u=ae(x=>x.publisherPrefix),p=J(x=>x.selectButtonInContext),m=Ln(),g=we(x=>x.selectCommand),b=_a(t,n,e),f=[],y=dt(e.kind);if(e.origin==="managed"||e.origin==="oob"&&!y){const x=c.find(j=>j.elementId===e.id),S=e.solutionName??x?.solutions[0]?.solutionName,C=e.publisherName??x?.solutions[0]?.publisher,N=e.origin==="oob"?"Out-of-the-box button":`From the managed solution${S?` ${S}`:""}${C?` by ${C}`:""}`,O=y?void 0:"You can't edit it directly: customise a copy, or create an override, to change it.",I=a.jsxs(a.Fragment,{children:[!y&&b&&a.jsx(K,{size:"small",onClick:()=>{const j=d?.publisherPrefix?.trim()||u?.trim()||"new",$=r(t,n,o,e.id,j);$&&p(t,n,o,$)},children:"Customise button"}),!y&&a.jsx(K,{size:"small",onClick:()=>l(t,n,o,e.id),children:"Create override"})]});f.push({id:"provenance",intent:"info",title:N,body:O,dismissible:!1,actions:I})}if(s.length>0){const x=s.some(S=>S.effect==="hidden");f.push({id:"modern-override",intent:x?"warning":"info",title:x?"Hidden by a modern command":"Shown as a modern command",dismissible:!1,body:a.jsxs("div",{className:i.list,children:[s.map(S=>a.jsxs("span",{children:[Za(S,m),"."," ",a.jsx($n,{inline:!0,onClick:()=>g(S.command.id),children:"View"})]},S.command.id)),a.jsx(Ze,{children:"Matched by the migrated command's unique name. Unified Interface may show the modern command instead of this button."})]})})}return f.length===0?null:a.jsx(Ua,{scope:"properties",messages:f,className:i.slot})}const nC=me({header:{position:"sticky",top:0,zIndex:1,display:"flex",alignItems:"center",gap:h.spacingHorizontalS,minHeight:"52px",padding:`${h.spacingVerticalS} ${h.spacingHorizontalS} ${h.spacingVerticalS} ${h.spacingHorizontalM}`,backgroundColor:h.colorNeutralBackground2,borderBottom:`1px solid ${h.colorNeutralStroke2}`,flexShrink:0},tile:{width:"36px",height:"36px",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:h.borderRadiusMedium,backgroundColor:h.colorNeutralBackground1,border:`1px solid ${h.colorNeutralStroke2}`},text:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS},label:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},badges:{display:"flex",flexWrap:"wrap",gap:h.spacingHorizontalXS},badge:{flexShrink:0,maxWidth:"100%"},badgeText:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function oC(e){return e.origin==="unmanaged"?{text:"Yours",color:"brand"}:e.origin==="managed"?{text:e.solutionName?`Managed · ${e.solutionName}`:"Managed",color:"informative"}:{text:"Out of the box",color:"informative"}}function sC({button:e}){const t=nC(),{onClose:n}=E.useContext(Qd),o=J(u=>u.clearSelection),s=M(u=>u.locLabels),i=Ee(),l=n?{label:"Close properties",run:n}:e?{label:"Clear selection",run:o}:void 0,r=l&&a.jsx(pe,{content:l.label,relationship:"label",children:a.jsx(K,{appearance:"subtle",icon:a.jsx(ln,{}),onClick:l.run})});if(!e)return a.jsxs("div",{className:t.header,children:[a.jsx(V,{size:400,weight:"semibold",className:t.text,children:"Properties"}),r]});const c=i(e.label,s,void 0,e.source?.labelToken)||e.id,d=oC(e);return a.jsxs("div",{className:t.header,children:[a.jsx("div",{className:t.tile,"aria-hidden":!0,children:a.jsx(xt,{button:e,size:20})}),a.jsxs("div",{className:t.text,children:[a.jsx(pe,{content:c,relationship:"description",children:a.jsx(V,{as:"h2",size:400,weight:"semibold",className:t.label,tabIndex:0,children:c})}),a.jsxs("div",{className:t.badges,children:[a.jsx(xe,{size:"medium",appearance:"tint",color:d.color,className:t.badge,children:a.jsx("span",{className:t.badgeText,children:d.text})}),a.jsx(xe,{size:"medium",appearance:"outline",color:"informative",className:t.badge,children:yt[e.kind]})]})]}),r]})}const iC="Mscrm.HideOnModern",aC="Mscrm.ShowOnlyOnModern";function qu(e,t){if(e===iC)return"classic";if(e===aC)return"uci";const n=t?.steps.length===1?t.steps[0]:void 0;if(!(n?.kind!=="CommandClientTypeRule"||n.default!==void 0))return n.type==="Modern"?n.invertResult?"classic":"uci":n.type==="Refresh"&&!n.invertResult?"classic":"other"}function rC(e,t){const n=e.displayRules.map(o=>qu(o,t.find(s=>s.id===o))).filter(o=>o!==void 0);return n.length===0?"all":n.length===1&&n[0]!=="other"?n[0]:"custom"}const lC=me({group:{display:"flex",flexDirection:"column",gap:h.spacingVerticalXXS}});function cC({button:e}){const t=lC(),n=Ee(),o=M(S=>S.commands),s=M(S=>S.displayRules),i=M(S=>S.ribbons),l=J(S=>S.location),r=M(S=>S.locLabels),c=M(S=>S.upsertCommand),d=M(S=>S.upsertDisplayRule),u=M(S=>S.batch),p=Va(e.commandId||void 0),m=o.find(S=>S.id===e.commandId);if(!m)return a.jsx(_e,{label:"Show on",hint:"Bind a command first: where a button shows is set on its command.",children:a.jsx(Ci,{disabled:!0,value:"all",children:a.jsx(on,{value:"all",label:"All clients"})})});const g=rC(m,s),b=p?.provenance==="custom"||p?.provenance==="customising"||p?.provenance==="customised",f=Jc(i,m.id,e.id,S=>n(S.label,r,void 0,S.source?.labelToken),l),y=S=>{const C=m.displayRules.filter($=>qu($,s.find(w=>w.id===$))===void 0);if(S==="all"){c({...m,displayRules:C});return}const N=S==="uci"?"Modern":"Refresh",O=s.find($=>$.steps.length===1&&$.steps[0].kind==="CommandClientTypeRule"&&$.steps[0].type===N&&!$.steps[0].invertResult&&$.steps[0].default===void 0);let I=O?.id??`${m.id}.${N}.DisplayRule`;for(let $=1;!O&&s.some(w=>w.id===I);$++)I=`${m.id}.${N}.DisplayRule.${$}`;const j={kind:"CommandClientTypeRule",type:N};u(()=>{O||d({id:I,steps:[j]}),c({...m,displayRules:[...C,I]})})},x=b?f.length>0?`Also changes ${f.length===1?"1 other button":`${f.length} other buttons`} that use${f.length===1?"s":""} this command: ${f.slice(0,3).join(", ")}${f.length>3?", …":""}.`:"Set by display rules on the button's command.":"Customise the command to change where it shows.";return a.jsx(_e,{label:"Show on",hint:x,children:a.jsxs(Ci,{className:t.group,value:g,disabled:!b,onChange:(S,C)=>C.value!=="custom"&&y(C.value),children:[a.jsx(on,{value:"all",label:"All clients"}),a.jsx(on,{value:"uci",label:"Unified Interface only"}),a.jsx(on,{value:"classic",label:"Classic web client only (not shown in Unified Interface)"}),g==="custom"&&a.jsx(on,{value:"custom",label:"Custom: see Display rules",disabled:!0})]})})}const dC=me({item:{borderBottom:`1px solid ${h.colorNeutralStroke3}`},headerRow:{display:"flex",alignItems:"center",paddingRight:h.spacingHorizontalS},header:{flex:1,minWidth:0,fontWeight:h.fontWeightSemibold},count:{marginLeft:h.spacingHorizontalXS},panel:{display:"flex",flexDirection:"column",gap:h.spacingVerticalM,margin:0,padding:`0 ${h.spacingHorizontalL} ${h.spacingVerticalM}`,minWidth:0}}),uC=({storageKey:e,defaultOpen:t,children:n})=>{const[o,s]=E.useState(()=>Jd(`sections.${e}`,t)),i=(l,r)=>{const c=r.openItems.map(String);s(c),Zd(`sections.${e}`,c)};return a.jsx(bc,{multiple:!0,collapsible:!0,openItems:o,onToggle:i,children:n})},Qt=({value:e,title:t,info:n,count:o,children:s})=>{const i=dC();return a.jsxs(yc,{value:e,className:i.item,children:[a.jsxs("div",{className:i.headerRow,children:[a.jsxs(xc,{size:"small",className:i.header,children:[t,!!o&&a.jsx(yn,{count:o,size:"medium",appearance:"ghost",color:"informative",className:i.count})]}),n&&a.jsx(Dt,{info:n,infoButton:{"aria-label":`About ${t}`}})]}),a.jsx(Sc,{className:i.panel,children:s})]})},mC=me({root:{display:"flex",flexDirection:"column",height:"100%",overflowY:"auto",overflowX:"hidden",backgroundColor:h.colorNeutralBackground2},empty:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",flex:1,gap:h.spacingHorizontalM,color:h.colorNeutralForeground3,padding:h.spacingHorizontalXL,textAlign:"center"},place:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM} 0`,color:h.colorNeutralForeground2}});function pC(){const e=mC(),t=J(y=>y.selectedButtonId),n=J(y=>y.selectedGroupId),o=J(y=>y.location),s=J(y=>y.tabId),c=M(y=>y.ribbons)[o].tabs.find(y=>y.id===s)?.groups.find(y=>y.id===n),d=Ss(c,t),u=c&&d?Ko(c,d.id):void 0,p=M(y=>y.locLabels),m=Ee(),g=Xv(),b=Uv(o,d?.id),f=M(y=>d?.commandId?y.commands.find(x=>x.id===d.commandId):void 0);return a.jsxs("aside",{className:e.root,"aria-label":"Properties",children:[a.jsx(sC,{button:d}),!d&&g?a.jsx(Qw,{command:g.command,items:g.children}):d?a.jsxs(a.Fragment,{children:[a.jsx(tC,{button:d,location:o,tabId:s,groupId:n,overrides:b}),u&&a.jsxs(Ze,{className:e.place,children:["Menu item of “",m(u.parent.label,p,void 0,u.parent.source?.labelToken),"”",u.section.title?` — section “${u.section.title}”`:""]}),dt(d.kind)?a.jsx(Zw,{button:d,location:o,tabId:s,groupId:n}):a.jsxs(uC,{storageKey:"properties.button",defaultOpen:["appearance","position","command","display","enable"],children:[a.jsxs(Qt,{value:"appearance",title:"Appearance",children:[a.jsx(ri,{part:"appearance",button:d,location:o,tabId:s,groupId:n}),a.jsx(cC,{button:d})]}),a.jsx(Qt,{value:"position",title:"Position",children:a.jsx(ri,{part:"position",button:d,location:o,tabId:s,groupId:n})}),a.jsx(Qt,{value:"command",title:"Command",children:a.jsx(Bw,{button:d,groupId:n,tabId:s,location:o})}),a.jsx(Qt,{value:"display",title:"Display rules",count:f?.displayRules.length,info:"All of them must pass for the button to show.",children:a.jsx(_w,{})}),a.jsx(Qt,{value:"enable",title:"Enable rules",count:f?.enableRules.length,info:"All of them must pass for the button to be enabled. Unified Interface hides a button that isn't enabled.",children:a.jsx(qw,{})}),a.jsx(Qt,{value:"scaling",title:"Scaling",info:"Scaling only applies to the classic ribbon. Unified Interface ignores it.",children:a.jsx(Hw,{})}),a.jsxs(Qt,{value:"advanced",title:"Advanced",children:[a.jsx(ri,{part:"advanced",button:d,location:o,tabId:s,groupId:n}),a.jsx(Uw,{})]})]},`${n}|${d.id}`)]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.empty,children:[a.jsx(Ah,{fontSize:32,style:{opacity:.4}}),a.jsx(V,{size:300,children:"Select a button to view its properties"})]}),a.jsx(Xw,{}),a.jsx(Yw,{})]})]})}function Wu(e,t){const n=new Map,o=l=>{l&&n.set(l,(n.get(l)??0)+1)};for(const l of Object.keys(e))for(const r of e[l].tabs){o(r.commandId);for(const c of r.groups){o(c.source?.attributes.Command);for(const d of Ne(c))o(d.commandId),o(d.source?.attributes.PopulateQueryCommand)}}const s=new Map,i=new Map;for(const l of t){for(const r of new Set(l.enableRules))s.set(r,(s.get(r)??0)+1);for(const r of new Set(l.displayRules))i.set(r,(i.get(r)??0)+1)}return{byCommand:n,byEnable:s,byDisplay:i}}const fC=e=>(cg({...e,renderRow:()=>null}),e),Hu=E.createContext(void 0),hC=void 0,gC=()=>{var e;return(e=E.useContext(Hu))!=null?e:hC},bC=Hu.Provider,Gu=E.createContext({current:null}),yC={current:null},Uu=()=>{var e;return(e=E.useContext(Gu))!=null?e:yC},xC=Gu.Provider,Vu=E.createContext({current:null}),SC={current:null},Xu=()=>{var e;return(e=E.useContext(Vu))!=null?e:SC},vC=Vu.Provider,wC=(e,t)=>{const{height:n,itemSize:o,width:s="100%",ariaRowIndexStart:i=2,children:l,listProps:r}=e,c=Uu(),d=Xu(),p=dg({...e,children:l},t),m=E.useCallback(({data:f,index:y,style:x,isScrolling:S})=>{const C=f[y];return E.createElement(bC,{value:i+y},E.createElement(ug,{value:C.rowId},l(C,x,y,S)))},[i,l]),g=E.useCallback(()=>{c.current&&d.current&&d.current.scroll({left:c.current.scrollLeft,behavior:"instant"})},[]),b=E.useCallback(f=>{var y;(y=c.current)==null||y.removeEventListener("scroll",g),c.current=f,f&&f.addEventListener("scroll",g)},[]);return{...p,itemSize:o,height:n,virtualizedRow:m,width:s,ariaRowIndexStart:i,listProps:r,outerRef:b}};function ta(){return ta=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)({}).hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},ta.apply(null,arguments)}function Sl(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function na(e,t){return na=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,o){return n.__proto__=o,n},na(e,t)}function CC(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,na(e,t)}var vl=Number.isNaN||function(t){return typeof t=="number"&&t!==t};function IC(e,t){return!!(e===t||vl(e)&&vl(t))}function jC(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!IC(e[n],t[n]))return!1;return!0}function li(e,t){t===void 0&&(t=jC);var n,o=[],s,i=!1;function l(){for(var r=[],c=0;c<arguments.length;c++)r[c]=arguments[c];return i&&n===this&&t(r,o)||(s=e.apply(this,r),i=!0,n=this,o=r),s}return l}var RC=typeof performance=="object"&&typeof performance.now=="function",wl=RC?function(){return performance.now()}:function(){return Date.now()};function Cl(e){cancelAnimationFrame(e.id)}function $C(e,t){var n=wl();function o(){wl()-n>=t?e.call(null):s.id=requestAnimationFrame(o)}var s={id:requestAnimationFrame(o)};return s}var ci=-1;function Il(e){if(e===void 0&&(e=!1),ci===-1||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",document.body.appendChild(t),ci=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return ci}var bn=null;function jl(e){if(e===void 0&&(e=!1),bn===null||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",n.direction="rtl";var o=document.createElement("div"),s=o.style;return s.width="100px",s.height="100px",t.appendChild(o),document.body.appendChild(t),t.scrollLeft>0?bn="positive-descending":(t.scrollLeft=1,t.scrollLeft===0?bn="negative":bn="positive-ascending"),document.body.removeChild(t),bn}return bn}var NC=150,TC=function(t,n){return t};function kC(e){var t,n=e.getItemOffset,o=e.getEstimatedTotalSize,s=e.getItemSize,i=e.getOffsetForIndexAndAlignment,l=e.getStartIndexForOffset,r=e.getStopIndexForStartIndex,c=e.initInstanceProps,d=e.shouldResetStyleCacheOnItemSizeChange,u=e.validateProps;return t=(function(p){CC(m,p);function m(b){var f;return f=p.call(this,b)||this,f._instanceProps=c(f.props,Sl(f)),f._outerRef=void 0,f._resetIsScrollingTimeoutId=null,f.state={instance:Sl(f),isScrolling:!1,scrollDirection:"forward",scrollOffset:typeof f.props.initialScrollOffset=="number"?f.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},f._callOnItemsRendered=void 0,f._callOnItemsRendered=li(function(y,x,S,C){return f.props.onItemsRendered({overscanStartIndex:y,overscanStopIndex:x,visibleStartIndex:S,visibleStopIndex:C})}),f._callOnScroll=void 0,f._callOnScroll=li(function(y,x,S){return f.props.onScroll({scrollDirection:y,scrollOffset:x,scrollUpdateWasRequested:S})}),f._getItemStyle=void 0,f._getItemStyle=function(y){var x=f.props,S=x.direction,C=x.itemSize,N=x.layout,O=f._getItemStyleCache(d&&C,d&&N,d&&S),I;if(O.hasOwnProperty(y))I=O[y];else{var j=n(f.props,y,f._instanceProps),$=s(f.props,y,f._instanceProps),w=S==="horizontal"||N==="horizontal",A=S==="rtl",B=w?j:0;O[y]=I={position:"absolute",left:A?void 0:B,right:A?B:void 0,top:w?0:j,height:w?"100%":$,width:w?$:"100%"}}return I},f._getItemStyleCache=void 0,f._getItemStyleCache=li(function(y,x,S){return{}}),f._onScrollHorizontal=function(y){var x=y.currentTarget,S=x.clientWidth,C=x.scrollLeft,N=x.scrollWidth;f.setState(function(O){if(O.scrollOffset===C)return null;var I=f.props.direction,j=C;if(I==="rtl")switch(jl()){case"negative":j=-C;break;case"positive-descending":j=N-S-C;break}return j=Math.max(0,Math.min(j,N-S)),{isScrolling:!0,scrollDirection:O.scrollOffset<j?"forward":"backward",scrollOffset:j,scrollUpdateWasRequested:!1}},f._resetIsScrollingDebounced)},f._onScrollVertical=function(y){var x=y.currentTarget,S=x.clientHeight,C=x.scrollHeight,N=x.scrollTop;f.setState(function(O){if(O.scrollOffset===N)return null;var I=Math.max(0,Math.min(N,C-S));return{isScrolling:!0,scrollDirection:O.scrollOffset<I?"forward":"backward",scrollOffset:I,scrollUpdateWasRequested:!1}},f._resetIsScrollingDebounced)},f._outerRefSetter=function(y){var x=f.props.outerRef;f._outerRef=y,typeof x=="function"?x(y):x!=null&&typeof x=="object"&&x.hasOwnProperty("current")&&(x.current=y)},f._resetIsScrollingDebounced=function(){f._resetIsScrollingTimeoutId!==null&&Cl(f._resetIsScrollingTimeoutId),f._resetIsScrollingTimeoutId=$C(f._resetIsScrolling,NC)},f._resetIsScrolling=function(){f._resetIsScrollingTimeoutId=null,f.setState({isScrolling:!1},function(){f._getItemStyleCache(-1,null)})},f}m.getDerivedStateFromProps=function(f,y){return AC(f,y),u(f),null};var g=m.prototype;return g.scrollTo=function(f){f=Math.max(0,f),this.setState(function(y){return y.scrollOffset===f?null:{scrollDirection:y.scrollOffset<f?"forward":"backward",scrollOffset:f,scrollUpdateWasRequested:!0}},this._resetIsScrollingDebounced)},g.scrollToItem=function(f,y){y===void 0&&(y="auto");var x=this.props,S=x.itemCount,C=x.layout,N=this.state.scrollOffset;f=Math.max(0,Math.min(f,S-1));var O=0;if(this._outerRef){var I=this._outerRef;C==="vertical"?O=I.scrollWidth>I.clientWidth?Il():0:O=I.scrollHeight>I.clientHeight?Il():0}this.scrollTo(i(this.props,f,y,N,this._instanceProps,O))},g.componentDidMount=function(){var f=this.props,y=f.direction,x=f.initialScrollOffset,S=f.layout;if(typeof x=="number"&&this._outerRef!=null){var C=this._outerRef;y==="horizontal"||S==="horizontal"?C.scrollLeft=x:C.scrollTop=x}this._callPropsCallbacks()},g.componentDidUpdate=function(){var f=this.props,y=f.direction,x=f.layout,S=this.state,C=S.scrollOffset,N=S.scrollUpdateWasRequested;if(N&&this._outerRef!=null){var O=this._outerRef;if(y==="horizontal"||x==="horizontal")if(y==="rtl")switch(jl()){case"negative":O.scrollLeft=-C;break;case"positive-ascending":O.scrollLeft=C;break;default:var I=O.clientWidth,j=O.scrollWidth;O.scrollLeft=j-I-C;break}else O.scrollLeft=C;else O.scrollTop=C}this._callPropsCallbacks()},g.componentWillUnmount=function(){this._resetIsScrollingTimeoutId!==null&&Cl(this._resetIsScrollingTimeoutId)},g.render=function(){var f=this.props,y=f.children,x=f.className,S=f.direction,C=f.height,N=f.innerRef,O=f.innerElementType,I=f.innerTagName,j=f.itemCount,$=f.itemData,w=f.itemKey,A=w===void 0?TC:w,B=f.layout,k=f.outerElementType,v=f.outerTagName,T=f.style,R=f.useIsScrolling,D=f.width,q=this.state.isScrolling,X=S==="horizontal"||B==="horizontal",ne=X?this._onScrollHorizontal:this._onScrollVertical,re=this._getRangeToRender(),le=re[0],F=re[1],L=[];if(j>0)for(var G=le;G<=F;G++)L.push(E.createElement(y,{data:$,key:A(G,$),index:G,isScrolling:R?q:void 0,style:this._getItemStyle(G)}));var U=o(this.props,this._instanceProps);return E.createElement(k||v||"div",{className:x,onScroll:ne,ref:this._outerRefSetter,style:ta({position:"relative",height:C,width:D,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:S},T)},E.createElement(O||I||"div",{children:L,ref:N,style:{height:X?"100%":U,pointerEvents:q?"none":void 0,width:X?U:"100%"}}))},g._callPropsCallbacks=function(){if(typeof this.props.onItemsRendered=="function"){var f=this.props.itemCount;if(f>0){var y=this._getRangeToRender(),x=y[0],S=y[1],C=y[2],N=y[3];this._callOnItemsRendered(x,S,C,N)}}if(typeof this.props.onScroll=="function"){var O=this.state,I=O.scrollDirection,j=O.scrollOffset,$=O.scrollUpdateWasRequested;this._callOnScroll(I,j,$)}},g._getRangeToRender=function(){var f=this.props,y=f.itemCount,x=f.overscanCount,S=this.state,C=S.isScrolling,N=S.scrollDirection,O=S.scrollOffset;if(y===0)return[0,0,0,0];var I=l(this.props,O,this._instanceProps),j=r(this.props,I,O,this._instanceProps),$=!C||N==="backward"?Math.max(1,x):1,w=!C||N==="forward"?Math.max(1,x):1;return[Math.max(0,I-$),Math.max(0,Math.min(y-1,j+w)),I,j]},m})(E.PureComponent),t.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},t}var AC=function(t,n){t.children,t.direction,t.height,t.layout,t.innerTagName,t.outerTagName,t.width,n.instance},OC=kC({getItemOffset:function(t,n){var o=t.itemSize;return n*o},getItemSize:function(t,n){var o=t.itemSize;return o},getEstimatedTotalSize:function(t){var n=t.itemCount,o=t.itemSize;return o*n},getOffsetForIndexAndAlignment:function(t,n,o,s,i,l){var r=t.direction,c=t.height,d=t.itemCount,u=t.itemSize,p=t.layout,m=t.width,g=r==="horizontal"||p==="horizontal",b=g?m:c,f=Math.max(0,d*u-b),y=Math.min(f,n*u),x=Math.max(0,n*u-b+u+l);switch(o==="smart"&&(s>=x-b&&s<=y+b?o="auto":o="center"),o){case"start":return y;case"end":return x;case"center":{var S=Math.round(x+(y-x)/2);return S<Math.ceil(b/2)?0:S>f+Math.floor(b/2)?f:S}default:return s>=x&&s<=y?s:s<x?x:y}},getStartIndexForOffset:function(t,n){var o=t.itemCount,s=t.itemSize;return Math.max(0,Math.min(o-1,Math.floor(n/s)))},getStopIndexForStartIndex:function(t,n,o){var s=t.direction,i=t.height,l=t.itemCount,r=t.itemSize,c=t.layout,d=t.width,u=s==="horizontal"||c==="horizontal",p=n*r,m=u?d:i,g=Math.ceil((m+o-p)/r);return Math.max(0,Math.min(l-1,n+g-1))},initInstanceProps:function(t){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(t){t.itemSize}});const MC=e=>{const{slots:t,slotProps:n}=mg(e),{dir:o}=wc();return E.createElement(t.root,n.root,E.createElement(OC,{itemSize:e.itemSize,width:e.width,itemData:e.rows,height:e.height,itemCount:e.rows.length,direction:o,outerRef:e.outerRef,...e.listProps},e.virtualizedRow))},Ku=E.forwardRef((e,t)=>{const n=wC(e,t);return fC(n),MC(n)});Ku.displayName="DataGridBody";const DC=(e,t)=>{var n;const{targetDocument:o}=wc(),s=pg({targetDocument:o}),i=E.useRef(null),l=E.useRef(null);let r=e.containerWidthOffset;r===void 0&&(r=e.selectionMode?-44:0,r-=s||0);const c=fg({...e,"aria-rowcount":e.items.length,containerWidthOffset:r},t);return e.resizableColumns&&((n=e.resizableColumnsOptions)==null?void 0:n.autoFitColumns)===!1&&c.root.style&&(c.root.style.minWidth="auto"),{...c,headerRef:i,bodyRef:l}},EC=(e,t)=>E.createElement(vC,{value:e.headerRef},E.createElement(xC,{value:e.bodyRef},hg(e,t))),Yu=E.forwardRef((e,t)=>{const n=DC(e,t);return gg(n),EC(n,bg(n))});Yu.displayName="DataGrid";const BC=(e,t)=>{const n=gC();return yg({...e,"aria-rowindex":n},t)},LC=me({root:{minWidth:"fit-content"}}),zC=e=>{const t=LC();return e.root.className=Ie(t.root,e.root.className),xg(e),e},nr=E.forwardRef((e,t)=>{const n=BC(e,t);return zC(n),Sg(n)});nr.displayName="DataGridRow";const PC=(e,t)=>{const n=Uu(),o=Xu(),s=E.useCallback(()=>{n.current&&o.current&&n.current.scroll({left:o.current.scrollLeft,behavior:"instant"})},[]),i=E.useCallback(r=>{var c;(c=o.current)==null||c.removeEventListener("scroll",s),o.current=r,r&&r.addEventListener("scroll",s)},[]),l=vg(e,t);return l.root.ref=wg(l.root.ref,i),l},FC=me({root:{overflowX:"auto",scrollbarWidth:"none","::-webkit-scrollbar":{width:0,height:0}}}),_C=e=>{const t=FC();return e.root.className=Ie(t.root,e.root.className),Cg(e),e},Ju=E.forwardRef((e,t)=>{const n=PC(e,t);return _C(n),Ig(n)});Ju.displayName="DataGridHeader";const qC=new Set(["mscrm","command","commands","enablerule","enablerules","displayrule","displayrules","rule","button","customaction","template","templates"]);function qo(e){const t=e.split(".").filter(Boolean);for(let n=t.length-1;n>=0;n--)if(!qC.has(t[n].toLowerCase()))return t[n];return e}const di=36,Co=me({row:{cursor:"pointer"},selected:{backgroundColor:h.colorSubtleBackgroundSelected,":hover":{backgroundColor:h.colorSubtleBackgroundSelected}},mono:{fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200},tags:{display:"flex",gap:h.spacingHorizontalXXS,minWidth:0,overflow:"hidden",whiteSpace:"nowrap"},chip:{display:"inline-flex",padding:"0 6px",borderRadius:h.borderRadiusMedium,fontSize:h.fontSizeBase200,border:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground3,flexShrink:0},muted:{color:h.colorNeutralForeground3},empty:{padding:h.spacingVerticalS,color:h.colorNeutralForeground3},box:{flex:1,minHeight:0,minWidth:0,overflowX:"auto",overflowY:"auto"}}),WC={javascript:"JS",url:"URL",powerFx:"Fx",customApi:"API",outlookCommand:"Outlook",raw:"XML"},Ht=e=>a.jsx(V,{size:200,weight:"semibold",children:e}),Zu=(e,t)=>a.jsxs(xe,{size:"medium",appearance:"tint",color:e?"brand":"informative",children:[e??0," ",t,e===1?"":"s"]});function Qu({id:e}){const t=Co();return a.jsx(pe,{content:e,relationship:"description",children:a.jsx(lo,{truncate:!0,className:t.mono,children:e})})}const em=et.createContext(null),ui=e=>!!e.target.closest("button");function HC({item:e,rowId:t,style:n}){const o=Co(),s=et.useContext(em),i=s.idOf(e),l=s.selected===i;return a.jsx(nr,{style:n,"aria-current":l||void 0,"data-element-row":i,className:Ie(o.row,l&&o.selected),onClick:r=>{ui(r)||s.select(i)},onDoubleClick:r=>{ui(r)||s.open(e)},onKeyDown:r=>{ui(r)||(r.key===" "?(r.preventDefault(),s.select(i)):r.key==="Enter"&&(r.preventDefault(),s.open(e)))},children:({renderCell:r})=>a.jsx(gc,{children:r(e)})},t)}const GC=({item:e,rowId:t},n)=>a.jsx(HC,{item:e,rowId:t,style:n}),Rl=34;function tm({items:e,columns:t,sizing:n,idOf:o,label:s,height:i,onOpen:l,emptyText:r}){const c=Co(),[d,u]=E.useState(null),p=E.useRef(null),[m,g]=E.useState(0);E.useLayoutEffect(()=>{const x=Math.floor(p.current?.getBoundingClientRect().height??0);x!==m&&g(x)},[i,m]),E.useEffect(()=>{const x=p.current;if(!x||typeof ResizeObserver>"u")return;const S=new ResizeObserver(([C])=>g(Math.floor(C.contentRect.height)));return S.observe(x),()=>S.disconnect()},[]);const b=fc({tabBehavior:"unlimited",ignoreDefaultKeydown:{Enter:!0}}),f=E.useMemo(()=>({selected:d,select:u,open:l,idOf:o}),[d,l,o]),y=Math.max(di,(m||i+Rl)-Rl);return a.jsx("div",{ref:p,className:c.box,...b,children:e.length===0?a.jsx(V,{as:"p",size:200,className:c.empty,children:r}):a.jsx(em.Provider,{value:f,children:a.jsxs(Yu,{items:e,columns:t,columnSizingOptions:n,resizableColumns:!0,getRowId:o,focusMode:"composite",size:"small","aria-label":s,children:[a.jsx(Ju,{children:a.jsx(nr,{children:({renderHeaderCell:x})=>a.jsx(hc,{children:x()})})}),a.jsx(Ku,{itemSize:di,height:Math.min(y,e.length*di),listProps:{width:"100%",style:{overflowX:"hidden"}},children:GC})]})})})}function $l({id:e,onOpen:t}){return a.jsx(pe,{content:e,relationship:"description",children:a.jsx(va,{size:"extra-small",appearance:"outline",shape:"rounded",children:a.jsx(wa,{onClick:t,children:qo(e)})})})}function UC({commands:e,usage:t,height:n,onOpen:o,onOpenRule:s,emptyText:i}){const l=Co(),r=[qe({columnId:"id",renderHeaderCell:()=>Ht("Command"),renderCell:c=>a.jsx(Qu,{id:c.id})}),qe({columnId:"actions",renderHeaderCell:()=>Ht("Actions"),renderCell:c=>a.jsx("span",{className:l.tags,children:c.actions.length===0?a.jsx("span",{className:l.muted,children:"—"}):c.actions.map((d,u)=>a.jsx("span",{className:l.chip,children:WC[d.kind]??"XML"},u))})}),qe({columnId:"enable",renderHeaderCell:()=>Ht("Enable rules"),renderCell:c=>a.jsx("span",{className:l.tags,children:c.enableRules.map(d=>a.jsx($l,{id:d,onOpen:()=>s(d,"enable")},d))})}),qe({columnId:"display",renderHeaderCell:()=>Ht("Display rules"),renderCell:c=>a.jsx("span",{className:l.tags,children:c.displayRules.map(d=>a.jsx($l,{id:d,onOpen:()=>s(d,"display")},d))})}),qe({columnId:"used",renderHeaderCell:()=>Ht("Used by"),renderCell:c=>Zu(t.get(c.id),"control")}),qe({columnId:"edit",renderHeaderCell:()=>null,renderCell:c=>a.jsx(K,{appearance:"subtle",size:"small","aria-label":`Edit ${c.id}`,onClick:()=>o(c.id),children:"Edit"})})];return a.jsx(tm,{items:e,columns:r,sizing:{id:{defaultWidth:260,minWidth:120},actions:{defaultWidth:84,minWidth:48},enable:{defaultWidth:180,minWidth:80},display:{defaultWidth:180,minWidth:80},used:{defaultWidth:100,minWidth:72},edit:{defaultWidth:60,minWidth:52}},idOf:c=>c.id,label:"Commands",height:n,onOpen:c=>o(c.id),emptyText:i})}function Nl({rules:e,kind:t,usage:n,height:o,onOpen:s,emptyText:i}){const l=Co(),r=[qe({columnId:"id",renderHeaderCell:()=>Ht("Rule"),renderCell:c=>a.jsx(Qu,{id:c.id})}),qe({columnId:"steps",renderHeaderCell:()=>Ht("Steps"),renderCell:c=>a.jsx("span",{className:l.tags,children:c.steps.length===0?a.jsx("span",{className:l.muted,children:"—"}):a.jsxs(a.Fragment,{children:[c.steps.slice(0,3).map((d,u)=>a.jsx("span",{className:l.chip,children:d.kind.replace(/Rule$/,"")},u)),c.steps.length>3&&a.jsxs("span",{className:Ie(l.chip,l.muted),children:["+",c.steps.length-3]})]})})}),qe({columnId:"used",renderHeaderCell:()=>Ht("Used by"),renderCell:c=>Zu(n.get(c.id),"command")}),qe({columnId:"edit",renderHeaderCell:()=>null,renderCell:c=>a.jsx(K,{appearance:"subtle",size:"small","aria-label":`Edit ${c.id}`,onClick:()=>s(c.id),children:"Edit"})})];return a.jsx(tm,{items:e,columns:r,sizing:{id:{defaultWidth:360,minWidth:140},steps:{defaultWidth:260,minWidth:100},used:{defaultWidth:110,minWidth:80},edit:{defaultWidth:60,minWidth:52}},idOf:c=>c.id,label:t==="enable"?"Enable rules":"Display rules",height:o,onOpen:c=>s(c.id),emptyText:i})}const nm=me({root:{display:"flex",flexDirection:"column",borderTop:`1px solid ${h.colorNeutralStroke2}`,backgroundColor:h.colorNeutralBackground2,flexShrink:0},tabRow:{display:"flex",alignItems:"center",borderBottom:`1px solid ${h.colorNeutralStroke2}`,gap:0,paddingRight:h.spacingHorizontalS,flexShrink:0},content:{flex:1,minHeight:0,overflowY:"auto",padding:`${h.spacingHorizontalXS} ${h.spacingHorizontalM}`},gridContent:{overflow:"hidden",display:"flex",flexDirection:"column"},tabCount:{marginLeft:h.spacingHorizontalXS},toolbar:{flexShrink:0,display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,paddingBottom:h.spacingHorizontalXS,borderBottom:`1px solid ${h.colorNeutralStroke3}`,marginBottom:h.spacingHorizontalXS},historyRow:{display:"flex",alignItems:"flex-start",gap:h.spacingHorizontalS,padding:`${h.spacingHorizontalXS} 0`,borderBottom:`1px solid ${h.colorNeutralStroke3}`},historyAvatar:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:h.colorBrandBackground2,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:"2px"},historyContent:{flex:1,minWidth:0},consoleRow:{padding:"2px 0",fontFamily:h.fontFamilyMonospace,fontSize:h.fontSizeBase200,display:"flex",gap:h.spacingHorizontalS},consoleTs:{color:h.colorNeutralForeground4,flexShrink:0,fontSize:h.fontSizeBase200}}),mi="Shown once the table's ribbon is loaded.";function VC(){const e=nm(),t=je(P=>P.target!==null),n=Z(P=>P.activeBottomTab),o=Z(P=>P.setActiveBottomTab),s=Z(P=>P.bottomPanelHeight),i=Z(P=>P.bottomCollapsed),l=Z(P=>P.setBottomCollapsed),r=M(P=>P.commands),c=M(P=>P.displayRules),d=M(P=>P.enableRules),u=M(P=>P.past),p=M(P=>P.ribbons),m=M(P=>P.restore),g=ae(P=>P.currentUserName),b=ce(P=>P.entries),f=ce(P=>P.clear),y=ce(P=>P.logWarn),x=Z(P=>P.openCommandEditor),S=Z(P=>P.openRuleEditor),C=Z(P=>P.openDiffViewer),N=M(P=>P.upsertCommand),O=M(P=>P.upsertEnableRule),I=M(P=>P.upsertDisplayRule),[j,$]=E.useState(""),[w,A]=E.useState(""),[B,k]=E.useState(""),[v,T]=E.useState(""),R=E.useMemo(()=>{const P=j.toLowerCase().trim();return P?r.filter(Q=>Q.id.toLowerCase().includes(P)||Q.enableRules.some(be=>be.toLowerCase().includes(P))||Q.displayRules.some(be=>be.toLowerCase().includes(P))):r},[r,j]),D=E.useMemo(()=>{const P=w.toLowerCase().trim();return P?c.filter(Q=>Q.id.toLowerCase().includes(P)||Q.steps.some(be=>be.kind.toLowerCase().includes(P))):c},[c,w]),q=E.useMemo(()=>{const P=B.toLowerCase().trim();return P?d.filter(Q=>Q.id.toLowerCase().includes(P)||Q.steps.some(be=>be.kind.toLowerCase().includes(P))):d},[d,B]),X=E.useMemo(()=>{const P=v.toLowerCase().trim();return P?u.filter(Q=>Q.op.toLowerCase().includes(P)||Q.target.toLowerCase().includes(P)||Q.detail.toLowerCase().includes(P)||Q.userName.toLowerCase().includes(P)):u},[u,v]),ne=()=>{const P=new Set(r.map(be=>be.id)),Q=La("New","Command",P);N({id:Q,enableRules:[],displayRules:[],actions:[]}),x(Q)},re=()=>{const P=new Set(d.map(be=>be.id)),Q=uo("New","Enable",P);O({id:Q,steps:[]}),S(Q,"enable")},le=()=>{const P=new Set(c.map(be=>be.id)),Q=uo("New","Display",P);I({id:Q,steps:[]}),S(Q,"display")},F=E.useMemo(()=>Wu(p,r),[p,r]),L=i?32:s,G=Math.max(36,s-116),U=n==="commands"||n==="displayRules"||n==="enableRules";function te(P){return P.userName&&P.userName!=="You"?P.userName:g||"You"}return a.jsxs("div",{className:e.root,style:{height:L},children:[a.jsxs("div",{className:e.tabRow,children:[a.jsxs(Sa,{selectedValue:n,onTabSelect:(P,Q)=>{o(Q.value),i&&l(!1)},size:"small",style:{flex:1},children:[a.jsxs(_t,{value:"commands",children:["Commands",a.jsx(yn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:r.length,showZero:!0,overflowCount:9999})]}),a.jsxs(_t,{value:"displayRules",children:["Display rules",a.jsx(yn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:c.length,showZero:!0,overflowCount:9999})]}),a.jsxs(_t,{value:"enableRules",children:["Enable rules",a.jsx(yn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:d.length,showZero:!0,overflowCount:9999})]}),a.jsxs(_t,{value:"history",children:["History",a.jsx(yn,{className:e.tabCount,size:"medium",appearance:"ghost",color:"informative",count:u.length,showZero:!0,overflowCount:9999})]}),a.jsx(_t,{value:"console",children:"Console"})]}),a.jsx(K,{appearance:"subtle",size:"small",icon:i?a.jsx(ic,{}):a.jsx(it,{}),onClick:()=>l(!i),"aria-label":i?"Expand panel":"Collapse panel"})]}),!i&&a.jsxs("div",{className:Ie(e.content,U&&e.gridContent),children:[n==="commands"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:ne,children:"New command"}),a.jsx(sn,{size:"small",placeholder:`Filter ${r.length} command${r.length!==1?"s":""}…`,value:j,"aria-label":"Filter the commands",onChange:(P,Q)=>$(Q.value),style:{minWidth:0,flex:1,maxWidth:360}}),j&&a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[R.length," match",R.length!==1?"es":""]})]}),a.jsx(UC,{commands:R,usage:F.byCommand,height:G,onOpen:x,onOpenRule:S,emptyText:t?j?"No commands match.":"No commands.":mi})]}),n==="displayRules"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:le,children:"New display rule"}),a.jsx(sn,{size:"small",placeholder:`Filter ${c.length} display rule${c.length!==1?"s":""}…`,value:w,"aria-label":"Filter the display rules",onChange:(P,Q)=>A(Q.value),style:{minWidth:0,flex:1,maxWidth:360}}),w&&a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[D.length," match",D.length!==1?"es":""]})]}),a.jsx(Nl,{rules:D,kind:"display",usage:F.byDisplay,height:G,onOpen:P=>S(P,"display"),emptyText:t?w?"No display rules match.":"No display rules.":mi})]}),n==="enableRules"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),onClick:re,children:"New enable rule"}),a.jsx(sn,{size:"small",placeholder:`Filter ${d.length} enable rule${d.length!==1?"s":""}…`,value:B,"aria-label":"Filter the enable rules",onChange:(P,Q)=>k(Q.value),style:{minWidth:0,flex:1,maxWidth:360}}),B&&a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[q.length," match",q.length!==1?"es":""]})]}),a.jsx(Nl,{rules:q,kind:"enable",usage:F.byEnable,height:G,onOpen:P=>S(P,"enable"),emptyText:t?B?"No enable rules match.":"No enable rules.":mi})]}),n==="history"&&a.jsxs(a.Fragment,{children:[u.length>0&&a.jsxs("div",{className:e.toolbar,children:[a.jsx(sn,{size:"small",placeholder:`Filter ${u.length} entr${u.length!==1?"ies":"y"}…`,value:v,"aria-label":"Filter the history",onChange:(P,Q)=>T(Q.value),style:{minWidth:0,flex:1,maxWidth:360}}),v&&a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[X.length," match",X.length!==1?"es":""]})]}),u.length===0?a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:"No history yet — make a change to see it here."}):X.slice().reverse().map((P,Q)=>{const be=u.indexOf(P);return a.jsxs("div",{className:e.historyRow,children:[a.jsx("div",{className:e.historyAvatar,"aria-hidden":!0,children:a.jsx(oc,{fontSize:12,style:{color:h.colorBrandForeground1}})}),a.jsxs("div",{className:e.historyContent,children:[a.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:6},children:[a.jsx(V,{size:200,weight:"semibold",children:P.op}),a.jsxs(V,{size:200,children:["— ",a.jsx("strong",{children:P.target})]}),P.detail&&a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:P.detail})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:2},children:[a.jsxs(V,{size:200,style:{color:h.colorNeutralForeground3},children:[te(P)," ·"," ",new Date(P.ts).toLocaleTimeString()]}),a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Oh,{}),onClick:()=>C("history",be),children:"View diff"}),a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(Ul,{}),title:"Undo this change and every later one (redo brings them back)",onClick:()=>m(be),children:"Undo from here"})]})]})]},Q)})]}),n==="console"&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:e.toolbar,children:[a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(yo,{}),disabled:b.length===0,onClick:()=>{const P=b.slice().reverse().map(Q=>{const be=new Date(Q.ts).toLocaleTimeString();return`${Q.scope} ${be}
133
+ [${Q.level.toUpperCase()}]
134
+ ${Q.message}`}).join(`
135
+
136
+ `);Ts(P).then(Q=>{Q.ok||y("ui",`Couldn't copy the log: ${Q.error}.`)})},title:"Copy all log entries to clipboard",children:"Copy log"}),a.jsx(K,{appearance:"subtle",size:"small",onClick:f,children:"Clear log"})]}),a.jsx("div",{children:b.length===0?a.jsx(V,{size:200,style:{color:h.colorNeutralForeground3},children:"No runtime diagnostics yet."}):b.slice().reverse().map(P=>a.jsx(XC,{ts:`${P.scope} ${new Date(P.ts).toLocaleTimeString()}`,level:P.level,message:P.message},P.id))})]})]})]})}function XC({ts:e,level:t,message:n}){const o=nm(),s=t==="error"?h.colorStatusDangerForeground1:t==="warn"?h.colorStatusWarningForeground1:h.colorNeutralForeground3;return a.jsxs("div",{className:o.consoleRow,children:[a.jsx("span",{className:o.consoleTs,children:e}),a.jsxs("span",{style:{color:s},children:["[",t.toUpperCase(),"]"]}),a.jsx("span",{style:{color:h.colorNeutralForeground1},children:n})]})}const KC=me({root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalS}`,flexShrink:0},search:{flex:1,minWidth:0},body:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden"},selected:{backgroundColor:h.colorSubtleBackgroundSelected,":hover":{backgroundColor:h.colorSubtleBackgroundSelected}},label:{display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},hidden:{color:h.colorNeutralForeground3},muted:{color:h.colorNeutralForeground3},yours:{flexShrink:0,marginLeft:h.spacingHorizontalXS},empty:{padding:`${h.spacingVerticalM} ${h.spacingHorizontalM}`,color:h.colorNeutralForeground3}}),Jn=e=>`tab:${e}`,Wo=(e,t)=>`group:${e}:${t}`,oa=(e,t,n)=>`btn:${e}:${t}:${n}`,Tl=(e,t,n)=>n?t&&oa(e,t,n):t?Wo(e,t):Jn(e),YC=e=>e.target===e.currentTarget,JC=e=>e.key==="ContextMenu"||e.shiftKey&&e.key==="F10";function ZC(){const e=KC(),t=Ee(),n=J(_=>_.location),o=J(_=>_.tabId),s=J(_=>_.selectedGroupId),i=J(_=>_.selectedButtonId),l=J(_=>_.setTabId),r=J(_=>_.selectGroup),c=J(_=>_.selectButtonInContext),d=M(_=>_.ribbons[n].tabs),u=M(_=>_.locLabels),p=M(_=>_.baseLanguageCode),m=M(_=>_.baseline),g=M(_=>_.layers),b=M(_=>_.renameTab),f=M(_=>_.deleteTab),y=M(_=>_.reorderTabs),x=ae(_=>!!_.activeEntity),S=je(_=>_.target!==null),C=Z(_=>_.openNewTab),N=Z(_=>_.openNewGroup),O=Z(_=>_.openTabDisplayRules),I=Z(_=>_.announce),j=Z(_=>_.noteStructureChoice),[$,w]=E.useState(""),[A,B]=E.useState(()=>new Set),[k,v]=E.useState(null),[T,R]=E.useState(null),[D,q]=E.useState(null),[X,ne]=E.useState(null),[re,le]=E.useState(null),[F,L]=E.useState(null),[G,U]=E.useState(null),te=E.useRef(null),P=E.useRef(null),Q=_=>t(_.label,u,p,_.source?.titleToken)||_.id,be=_=>t(_.label,u,p,_.source?.titleToken)||_.id,Ae=_=>t(_.label,u,void 0,_.source?.labelToken)||_.id,tt=d.find(_=>_.id===o);E.useEffect(()=>{const _=[Jn(o)];s&&_.push(Wo(o,s)),B(ie=>_.every(de=>ie.has(de))?ie:new Set([...ie,..._]))},[n,o,s]);const Be=Tl(o,s,i);E.useEffect(()=>{if(!Be)return;[...P.current?.querySelectorAll("[data-structure-key]")??[]].find(ie=>ie.dataset.structureKey===Be)?.scrollIntoView?.({block:"nearest"})},[Be]);const Le=$.trim().toLowerCase(),Y=E.useMemo(()=>{const _=(ye,ge)=>ye.toLowerCase().includes(Le)||ge.toLowerCase().includes(Le),ie=new Set,de=new Set;if(!Le)return{shown:null,opened:de};for(const ye of d){const ge=Jn(ye.id),Ge=_(Q(ye),ye.id);for(const nt of ye.groups){const St=Wo(ye.id,nt.id),mn=_(be(nt),nt.id);for(const Pn of nt.buttons){const ir=_(Ae(Pn),Pn.id);(ir||mn||Ge)&&ie.add(oa(ye.id,nt.id,Pn.id)),ir&&(de.add(ge),de.add(St),ie.add(St),ie.add(ge))}(mn||Ge)&&ie.add(St),mn&&(de.add(ge),ie.add(ge))}Ge&&ie.add(ge)}return{shown:ie,opened:de}},[Le,d,u,p,t]),ze=_=>!Y.shown||Y.shown.has(_),Qe=Le?k??Y.opened:A,zn=(_,ie)=>{const de=String(ie.value),ye=te.current===de&&ie.type==="Click"?!0:ie.open;te.current=null;const ge=new Set(Qe);ye?ge.add(de):ge.delete(de),Le?v(ge):B(ge)},Yt=_=>{(_.id!==o||s||i)&&l(_.id)},z=(_,ie)=>{_.id!==o&&l(_.id),r(ie.id)},H=(_,ie,de)=>c(n,_.id,ie.id,de.id),W=_=>Ei("tab",_.id,m[n],po({layers:g},n)),oe=_=>Ei("group",_.id,m[n],po({layers:g},n)),se=_=>ud(_,m[n],jn({layers:g},n)),$e=(_,ie,de)=>{I(`${de} can't be renamed: ${Fo}.`),ce.getState().logInfo("structure",`${_} ${ie} can't be renamed: ${Fo}.`)},ue=(_,ie)=>{const de=d.map(Ge=>Ge.id),ye=de.indexOf(_.id),ge=ye+ie;ye<0||ge<0||ge>=de.length||y(n,Dg(de,ye,ge))},Pe=_=>setTimeout(()=>{const ie=document.activeElement?.closest('[role="dialog"], [role="alertdialog"]');if(ie&&!ie.contains(P.current))return;const de=J.getState(),ye=Tl(de.tabId,de.selectedGroupId,de.selectedButtonId),ge=[...P.current?.querySelectorAll("[data-structure-key]")??[]].find(Ge=>Ge.dataset.structureKey===ye)??_?.closest('[role="treeitem"]');ge?.isConnected&&ge.focus()}),Jt=d.find(_=>_.id===re)??tt,Os=(_,ie,de,ye)=>({"data-structure-key":_,onClick:()=>{Be!==_&&(te.current=_),ie(),_.startsWith("tab:")||j()},onKeyDown:ge=>{YC(ge)&&(JC(ge)?(ge.preventDefault(),ie(),de(ge.currentTarget)):ge.key==="F2"&&ye&&(ge.preventDefault(),ye()))},onContextMenu:ge=>{ge.target.closest('[role="treeitem"]')===ge.currentTarget&&(ge.preventDefault(),ie(),de(ge.currentTarget))}}),Ms=(_,ie,de)=>a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ds,{}),"aria-label":`Actions for ${_}`,onClick:ye=>{ie(),de(ye.currentTarget)}}),bm=(_,ie,de)=>{const ye=oa(_.id,ie.id,de.id);if(!ze(ye))return null;const ge=Ae(de),Ge=Be===ye,nt=de.custom&&!de.managed,St=()=>H(_,ie,de),mn=Pn=>{le(_.id),ne({button:de,groupId:ie.id,anchor:Pn})};return a.jsx(qt,{itemType:"leaf",value:ye,"aria-selected":Ge,"aria-description":de.id,...Os(ye,St,mn),children:a.jsx(Wt,{className:Ge?e.selected:void 0,iconBefore:a.jsx(xt,{button:de,size:16}),aside:de.hidden?a.jsx(xe,{size:"medium",appearance:"outline",color:"subtle",children:"Hidden"}):a.jsx(V,{size:200,className:e.muted,"aria-label":`Sequence ${de.sequence}`,children:de.sequence}),actions:Ms(ge,St,mn),children:a.jsxs("span",{style:{display:"flex",alignItems:"center",minWidth:0},children:[a.jsx("span",{className:Ie(e.label,de.hidden&&e.hidden),children:ge}),nt&&a.jsx(pe,{content:"Yours: added by your customizations",relationship:"label",children:a.jsx(xe,{size:"extra-small",color:"brand",className:e.yours})})]})})},ye)},ym=(_,ie)=>{const de=Wo(_.id,ie.id);if(!ze(de))return null;const ye=be(ie),ge=Be===de,Ge=()=>z(_,ie),nt=St=>{le(_.id),q({group:ie,anchor:St})};return a.jsxs(qt,{itemType:"branch",value:de,"aria-selected":ge,"aria-description":ie.id,...Os(de,Ge,nt,()=>{if(!oe(ie))return $e("Group",ie.id,ye);Ge(),le(_.id),q({group:ie,anchor:document.body,action:"rename"})}),children:[a.jsx(Wt,{className:ge?e.selected:void 0,iconBefore:a.jsx(Dh,{}),aside:a.jsx(V,{size:200,className:e.muted,"aria-label":`${ie.buttons.length} controls`,children:ie.buttons.length}),actions:Ms(ye,Ge,nt),children:a.jsx("span",{className:e.label,children:ye})}),a.jsx(Zn,{children:pt(ie.buttons).map(St=>bm(_,ie,St))})]},de)},xm=_=>{const ie=Jn(_.id);if(!ze(ie))return null;const de=Q(_),ye=Be===ie,ge=nt=>R({tab:_,anchor:nt}),Ge=()=>{W(_)?L(_):$e("Tab",_.id,de)};return a.jsxs(qt,{itemType:"branch",value:ie,"aria-selected":ye,"aria-description":_.id,...Os(ie,()=>Yt(_),ge,Ge),children:[a.jsx(Wt,{className:ye?e.selected:void 0,iconBefore:a.jsx(Mh,{}),aside:a.jsx(V,{size:200,className:e.muted,"aria-label":`${_.groups.length} groups`,children:_.groups.length}),actions:Ms(de,()=>Yt(_),ge),children:a.jsx("span",{className:e.label,children:de})}),a.jsx(Zn,{children:pt(_.groups).map(nt=>ym(_,nt))})]},ie)},Ds=T?d.findIndex(_=>_.id===T.tab.id):-1,sr=T?T.tab.tabDisplayRules.reduce((_,ie)=>_+ie.rules.length,0):0,Sm=d.filter(_=>ze(Jn(_.id)));return a.jsxs("div",{className:e.root,children:[a.jsxs("div",{className:e.header,children:[a.jsx(sn,{size:"small",className:e.search,placeholder:"Filter tabs, groups, buttons","aria-label":"Filter the structure",value:$,disabled:!x||!S,onChange:(_,ie)=>{w(ie.value),v(null)}}),a.jsx(pe,{content:"Add tab",relationship:"label",children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{}),disabled:!x||!S,onClick:C})})]}),a.jsx("div",{className:e.body,children:x?S?d.length===0?a.jsx(V,{as:"p",size:200,className:e.empty,children:"This location has no tabs."}):Sm.length===0?a.jsxs(V,{as:"p",size:200,className:e.empty,children:["Nothing matches “",$.trim(),"”."]}):a.jsx(Zn,{ref:P,size:"small","aria-label":"Ribbon structure",openItems:Qe,onOpenChange:zn,children:d.map(xm)}):a.jsx(V,{as:"p",size:200,className:e.empty,children:"Shown once the table's ribbon is loaded."}):a.jsx(V,{as:"p",size:200,className:e.empty,children:"Choose a table to see its tabs, groups and buttons."})}),T&&a.jsxs(Xe,{open:!0,onOpenChange:(_,ie)=>{ie.open||(R(null),Pe(T.anchor))},positioning:{target:T.anchor,position:"below",align:"start"},children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Ye,{children:a.jsxs(Je,{"aria-label":`Actions for ${Q(T.tab)}`,children:[W(T.tab)?a.jsx(fe,{secondaryContent:"F2",onClick:()=>L(T.tab),children:"Rename…"}):a.jsx(fe,{disabled:!0,title:Fo,subText:"Only your own tabs and groups can be renamed",children:"Rename…"}),a.jsx(fe,{icon:a.jsx(Mn,{}),secondaryContent:sr>0?String(sr):void 0,onClick:()=>O(n,T.tab.id),children:"Tab display rules…"}),a.jsx(fe,{icon:a.jsx(ke,{}),onClick:()=>{Yt(T.tab),N()},children:"Add group…"}),a.jsx(Mt,{}),a.jsx(fe,{disabled:Ds<=0,onClick:()=>ue(T.tab,-1),children:"Move up"}),a.jsx(fe,{disabled:Ds<0||Ds>=d.length-1,onClick:()=>ue(T.tab,1),children:"Move down"}),a.jsx(Mt,{}),a.jsx(fe,{disabled:!se(T.tab),onClick:()=>U(T.tab),children:"Delete tab…"})]})})]}),Jt&&a.jsx(Xa,{location:n,tab:Jt,moveLabels:["Move up","Move down"],target:D,onClose:()=>{Pe(D?.anchor instanceof HTMLElement?D.anchor:void 0),q(null)}}),Jt&&a.jsx(wo,{location:n,tab:Jt,target:X,onClose:()=>{Pe(X?.anchor),ne(null)}}),F&&a.jsx(iu,{open:!0,noun:"tab",initialLabel:He(F.label,u,p),onRename:_=>{b(n,F.id,_),L(null)},onCancel:()=>L(null)}),G&&a.jsxs(Bn,{open:!0,title:"Delete tab",confirmLabel:"Delete tab",destructive:!0,onConfirm:()=>{f(n,G.id),U(null)},onCancel:()=>U(null),children:["Delete the tab “",Q(G),"” and its groups and buttons?"]})]})}const QC="application/x-rw-se",e0=me({root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},header:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS,padding:`${h.spacingVerticalS} ${h.spacingHorizontalS}`,flexShrink:0},search:{flex:1,minWidth:0},body:{flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden"},name:{display:"block",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},muted:{color:h.colorNeutralForeground3,whiteSpace:"nowrap"},meta:{display:"flex",alignItems:"center",gap:h.spacingHorizontalXS},empty:{padding:`${h.spacingVerticalS} ${h.spacingHorizontalM}`,color:h.colorNeutralForeground3}}),pi=100,t0=e=>e.key==="ContextMenu"||e.shiftKey&&e.key==="F10";function n0(){const e=e0(),t=Ee(),n=M(z=>z.commands),o=M(z=>z.displayRules),s=M(z=>z.enableRules),i=M(z=>z.templates),l=M(z=>z.ribbons),r=M(z=>z.baseline),c=M(z=>z.locLabels),d=M(z=>z.baseLanguageCode),u=M(z=>z.upsertCommand),p=M(z=>z.upsertEnableRule),m=M(z=>z.upsertDisplayRule),g=M(z=>z.createButton),b=J(z=>z.location),f=J(z=>z.tabId),y=J(z=>z.selectButtonInContext),x=Z(z=>z.openCommandEditor),S=Z(z=>z.openRuleEditor),C=Z(z=>z.announce),N=Z(z=>z.noteStructureChoice),[O,I]=E.useState(""),[j,$]=E.useState(()=>new Set(["buttons"])),[w,A]=E.useState(null),[B,k]=E.useState({}),v=E.useMemo(()=>{const z=[];for(const H of Object.keys(l)){const W=new Set(r[H].tabs.flatMap(oe=>oe.groups.flatMap(se=>Ne(se))).map(oe=>oe.id));for(const oe of l[H].tabs)for(const se of oe.groups)for(const $e of Ne(se))$e.custom&&z.push({button:$e,location:H,tabId:oe.id,groupId:se.id,isNew:!W.has($e.id)})}return z},[l,r]),T=E.useMemo(()=>Wu(l,n),[l,n]),R=z=>t(z.label,c,void 0,z.source?.labelToken)||z.id,D=O.trim().toLowerCase(),q=(...z)=>!D||z.some(H=>H.toLowerCase().includes(D)),X=v.filter(z=>q(R(z.button),z.button.id)),ne=n.filter(z=>q(z.id)),le=[...s.map(z=>({id:z.id,kind:"enable"})),...o.map(z=>({id:z.id,kind:"display"}))].filter(z=>q(z.id)),F=i.filter(z=>q(z.id)),L=D?new Set([["buttons",X],["commands",ne],["rules",le],["templates",F]].filter(([,z])=>z.length>0).map(([z])=>z)):null,[G,U]=E.useState(null),te=L?G?.q===D?G.open:L:j,P=()=>{const z=La("New","Command",new Set(n.map(H=>H.id)));u({id:z,enableRules:[],displayRules:[],actions:[]}),x(z)},Q=z=>{const H=uo("New",z==="enable"?"Enable":"Display",new Set([...s.map(W=>W.id),...o.map(W=>W.id)]));z==="enable"?p({id:H,steps:[]}):m({id:H,steps:[]}),S(H,z)},be=z=>{y(z.location,z.tabId,z.groupId,z.button.id),N()},Ae=l[b].tabs.find(z=>z.id===f),tt=Ae?pt(Ae.groups):[],Be=!!w&&w.row.location==="Application"!=(b==="Application"),Le=(z,H,W)=>{Ae&&(g({location:b,tabId:Ae.id,groupId:H,button:Ou(z.button,io(M.getState()))}),C(`A copy of ${R(z.button)} was added to ${W}.`))},Y=(z,H,W,oe,se,$e={},ue)=>a.jsx(qt,{itemType:"leaf",value:z,"aria-description":oe,onClick:se,...$e,children:a.jsx(Wt,{aside:W,actions:ue,children:a.jsx("span",{className:e.name,title:oe,children:H})})},z),ze=(z,H,W,oe,se)=>{const $e=te.has(z),ue=B[z]??pi;return a.jsxs(qt,{itemType:"branch",value:z,children:[a.jsx(Wt,{aside:a.jsx(yn,{size:"medium",appearance:"ghost",color:"informative",count:W.length,showZero:!0}),children:H}),a.jsx(Zn,{children:$e&&(W.length===0?zn(se):[...W.slice(0,ue).map(Pe=>et.cloneElement(oe(Pe),{"data-branch-row":z})),...W.length>ue?[a.jsx(qt,{itemType:"leaf",value:`more:${z}`,onClick:()=>{setTimeout(()=>{document.querySelectorAll(`[data-branch-row="${z}"]`)[ue]?.focus()}),k(Pe=>({...Pe,[z]:ue+pi}))},children:a.jsx(Wt,{children:a.jsxs("span",{className:e.muted,children:["Show"," ",Math.min(pi,W.length-ue)," ","more of ",W.length-ue]})})},`more:${z}`)]:[]])})]},z)},Qe=z=>z?`used ${z}×`:"not used",zn=z=>a.jsx(qt,{itemType:"leaf",value:`none:${z}`,"aria-disabled":!0,children:a.jsx(Wt,{children:a.jsx("span",{className:e.muted,children:z})})}),Yt=z=>{const H=`button:${z.location}:${z.button.id}`,W=oe=>A({row:z,anchor:oe});return Y(H,R(z.button),a.jsxs("span",{className:e.meta,children:[a.jsx(xe,{size:"medium",appearance:"outline",children:Ut[z.location].label}),z.isNew&&a.jsx(xe,{size:"medium",color:"brand",appearance:"tint",children:"New"})]}),`${z.button.id} · ${Ut[z.location].label}`,()=>be(z),{draggable:!0,onDragStart:oe=>{oe.dataTransfer.setData(QC,JSON.stringify({button:z.button})),oe.dataTransfer.effectAllowed="copy"},onContextMenu:oe=>{oe.preventDefault(),W(oe.currentTarget)},onKeyDown:oe=>{oe.target===oe.currentTarget&&t0(oe)&&(oe.preventDefault(),W(oe.currentTarget))}},a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ds,{}),"aria-label":`Actions for ${R(z.button)}`,onClick:oe=>W(oe.currentTarget)}))};return a.jsxs("div",{className:e.root,children:[a.jsxs("div",{className:e.header,children:[a.jsx(sn,{size:"small",className:e.search,placeholder:"Search buttons, commands, rules","aria-label":"Search the solution's elements",contentBefore:a.jsx(ac,{}),value:O,onChange:(z,H)=>I(H.value)}),a.jsxs(Xe,{children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx(pe,{content:"New command or rule",relationship:"label",children:a.jsx(K,{appearance:"subtle",size:"small",icon:a.jsx(ke,{})})})}),a.jsx(Ye,{children:a.jsxs(Je,{children:[a.jsx(fe,{icon:a.jsx(On,{}),onClick:P,children:"New command"}),a.jsx(fe,{icon:a.jsx(ao,{}),onClick:()=>Q("enable"),children:"New enable rule"}),a.jsx(fe,{icon:a.jsx(ao,{}),onClick:()=>Q("display"),children:"New display rule"})]})})]})]}),a.jsx("div",{className:e.body,children:a.jsxs(Zn,{size:"small","aria-label":"Solution elements",openItems:te,onOpenChange:(z,H)=>{const W=new Set(te);H.open?W.add(String(H.value)):W.delete(String(H.value)),D?U({q:D,open:W}):$(W)},children:[ze("buttons","Buttons",X,Yt,D?"No buttons match.":"None of your buttons yet."),ze("commands","Commands",ne,z=>Y(`command:${z.id}`,qo(z.id),a.jsx(V,{size:200,className:e.muted,children:Qe(T.byCommand.get(z.id))}),z.id,()=>x(z.id)),D?"No commands match.":"No commands."),ze("rules","Rules",le,z=>Y(`rule:${z.kind}:${z.id}`,qo(z.id),a.jsxs("span",{className:e.meta,children:[a.jsx(V,{size:200,className:e.muted,children:Qe((z.kind==="enable"?T.byEnable:T.byDisplay).get(z.id))}),a.jsx(xe,{size:"medium",appearance:"tint",color:z.kind==="enable"?"success":"informative",children:z.kind==="enable"?"Enable":"Display"})]}),z.id,()=>S(z.id,z.kind)),D?"No rules match.":"No rules."),ze("templates","Templates",F,z=>a.jsx(qt,{itemType:"leaf",value:`template:${z.id}`,"aria-description":z.id,children:a.jsx(Wt,{iconBefore:a.jsx(lc,{}),children:a.jsx("span",{className:e.name,title:z.id,children:qo(z.id)})})},`template:${z.id}`),D?"No templates match.":"No templates.")]})}),w&&a.jsxs(Xe,{open:!0,onOpenChange:(z,H)=>!H.open&&A(null),positioning:{target:w.anchor,position:"below",align:"start"},children:[a.jsx(Ke,{disableButtonEnhancement:!0,children:a.jsx("span",{hidden:!0})}),a.jsx(Ye,{children:a.jsxs(Je,{"aria-label":`Actions for ${R(w.row.button)}`,children:[a.jsx(fe,{onClick:()=>be(w.row),children:"Go to button"}),a.jsx(Mt,{}),a.jsx(ro,{children:"Add a copy to a group of this tab"}),Be&&a.jsx(ro,{children:b==="Application"?"A table's button can't go on the application ribbon.":"An application ribbon button can't go on a table's ribbon."}),tt.length===0?a.jsx(fe,{disabled:!0,children:"No groups on this tab"}):tt.map(z=>{const H=t(z.label,c,d,z.source?.titleToken)||z.id;return a.jsxs(fe,{disabled:Be,onClick:()=>Le(w.row,z.id,H),children:["Add to ",H]},z.id)})]})})]},`${w.row.location}:${w.row.button.id}`)]})}const o0=me({root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},tabs:{flexShrink:0,padding:`0 ${h.spacingHorizontalXS}`,borderBottom:`1px solid ${h.colorNeutralStroke2}`},body:{flex:1,minHeight:0,overflow:"hidden"}});function s0(){const e=o0(),t=Z(o=>o.leftPaneTab),n=Z(o=>o.setLeftPaneTab);return a.jsxs("div",{className:e.root,children:[a.jsxs(Sa,{size:"small",className:e.tabs,"aria-label":"Left pane",selectedValue:t,onTabSelect:(o,s)=>n(s.value),children:[a.jsx(_t,{value:"structure",icon:a.jsx(Wl,{}),children:"Structure"}),a.jsx(_t,{value:"solution",icon:a.jsx(Hl,{}),children:"Solution"})]}),a.jsx("div",{className:e.body,role:"tabpanel","aria-label":t==="structure"?"Structure":"Solution",children:t==="structure"?a.jsx(ZC,{}):a.jsx(n0,{})})]})}function or(){return window.dataverseAPI}async function i0(){const e=or();ce.getState().logInfo("dataverse","Loading solutions...");const s=((await e.queryData("solutions?$select=solutionid,uniquename,friendlyname,version,ismanaged,versionnumber,isvisible&$expand=publisherid($select=publisherid,uniquename,friendlyname,customizationprefix,customizationoptionvalueprefix)&$filter=isvisible eq true and uniquename ne 'Active' and uniquename ne 'Default'&$orderby=friendlyname asc")).value??[]).map(l=>{const r=l.publisherid??{};return{id:String(l.solutionid??""),uniqueName:String(l.uniquename??""),friendlyName:String(l.friendlyname??""),version:String(l.version??""),isManaged:!!l.ismanaged,publisherId:r.publisherid??"",publisherUniqueName:r.uniquename??"",publisherName:r.friendlyname??"",publisherPrefix:r.customizationprefix??"",publisherOptionValuePrefix:typeof r.customizationoptionvalueprefix=="number"?r.customizationoptionvalueprefix:void 0,versionNumber:l.versionnumber}});ce.getState().logInfo("dataverse",`Loaded ${s.length} solution(s).`);const i=s.filter(l=>!l.isManaged).slice(0,5);for(const l of i)ce.getState().logInfo("dataverse",` • "${l.friendlyName||l.uniqueName}" → prefix="${l.publisherPrefix||"(empty)"}" (publisher: ${l.publisherName||l.publisherUniqueName||"(empty)"})`);return s}async function a0(e){if(!e)return[];const t=or();ce.getState().logInfo("dataverse",`Loading solution entity components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 1`,i=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return ce.getState().logInfo("dataverse",`Solution contains ${i.length} table component(s).`),i}async function r0(e){if(!e)return[];const t=or();ce.getState().logInfo("dataverse",`Loading solution ribbon components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 50`,i=((await t.queryData(n)).value??[]).map(l=>l.objectid).filter(Boolean);return ce.getState().logInfo("dataverse",`Solution contains ${i.length} ribbon-customization component(s).`),i}function l0(){return window.dataverseAPI}async function c0(e){if(e.length===0)return[];const t=l0(),n=ce.getState();n.logInfo("dataverse",`Loading metadata for ${e.length} solution entit${e.length===1?"y":"ies"}...`);const o="MetadataId,LogicalName,SchemaName,DisplayName,IsCustomEntity,IsIntersect",s=d=>({metadataId:String(d.MetadataId??""),logicalName:String(d.LogicalName??""),schemaName:d.SchemaName?String(d.SchemaName):void 0,displayName:d.DisplayName?.UserLocalizedLabel?.Label??String(d.LogicalName??""),isCustomEntity:!!d.IsCustomEntity,isManaged:!1,isIntersect:!!d.IsIntersect}),i=async d=>{try{return s(await t.queryData(`EntityDefinitions(${d})?$select=${o}`))}catch(u){return n.logWarn("dataverse",`Could not resolve entity for component ${d}: ${u instanceof Error?u.message:String(u)}`),null}},l=[];for(let d=0;d<e.length;d+=40)l.push(e.slice(d,d+40));const c=(await Promise.all(l.map(async d=>{try{const p=((await t.queryData(`EntityDefinitions?$select=${o}&$filter=${d.map(g=>`MetadataId eq ${g}`).join(" or ")}`)).value??[]).map(s),m=new Set(p.map(g=>g.metadataId.toLowerCase()));for(const g of d)m.has(g.toLowerCase())||n.logWarn("dataverse",`Could not resolve entity for component ${g}: not found.`);return p}catch(u){n.logWarn("dataverse",`Couldn't read ${d.length} tables in one request (${u instanceof Error?u.message:String(u)}); reading them one at a time.`);const p=[];for(const m of d)p.push(await i(m));return p}}))).flat().filter(d=>d!==null&&!d.isIntersect).sort((d,u)=>d.displayName.localeCompare(u.displayName));return n.logInfo("dataverse",`Loaded metadata for ${c.length} table(s).`),c}async function om(e){const t=atob(e),n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t.charCodeAt(i);const o=Yy(n),s=Object.entries(o).find(([i])=>i.toLowerCase().endsWith("ribbonxml.xml"));if(!s){const i=Object.keys(o);throw new Error(`Dataverse returned a ribbon package without RibbonXml.xml (it has ${i.length>0?i.join(", "):"no files"}).`)}return $s(s[1])}const sm=30,d0=sm*6e4,im=(e,t)=>`cbs:lastPublish:${e.replace(/\/+$/,"")}:${t}`;function am(e,t){try{const n=sessionStorage.getItem(e);if(!n)return null;const o=JSON.parse(n);if(typeof o.at!="number"||!o.publishedAt||typeof o.publishedAt!="object")return null;const s=Object.fromEntries(Object.entries(o.publishedAt).filter(i=>typeof i[1]=="number"&&t-i[1]<d0));return{at:o.at,publishedAt:s}}catch{return null}}function CI(e,t,n,o=Date.now()){const s=im(e,t),i={...am(s,o)?.publishedAt??{}};for(const l of n){const r=/^customActions:ca:(.+)$/.exec(l)?.[1];r&&(i[r]=o)}try{sessionStorage.setItem(s,JSON.stringify({at:o,publishedAt:i}))}catch{}}function u0(e,t,n=Date.now()){return am(im(e,t),n)}const kl=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]),fi=new Set(["Tab","Group"]),Al=/^(.+)\._children$/;function Ol(e){return e?Array.from(e.children):[]}function bo(e,t){return t?e.split("{!EntityLogicalName}").join(t):e}function m0(e,t){const n=new Map,o=(s,i)=>n.set(bo(s,t),i);for(const s of e)for(const i of s.tabs){o(`${i.id}.Groups`,i.id);for(const l of i.groups){o(`${l.id}.Controls`,i.id);for(const r of Ne(l))for(const c of r.menu?.sections??[])o(c.controlsId,i.id)}}return n}function p0(e,t){const n=new Set,o=s=>n.add(bo(s,t));for(const s of e)for(const i of s.tabs){o(i.id);for(const l of i.groups){o(l.id);for(const r of Ne(l))o(r.id)}}return n}function Ml(e){return[e,...Array.from(e.getElementsByTagName("*"))].flatMap(t=>t.getAttribute("Id")??[])}function f0(e,t,n,o={}){const{locLabels:s=[],languageCode:i=1033}=o,l=[...t],r=j=>bo(j,n),c=p0(l,n),d=m0(l,n),u=[...fs(e).map(j=>j.location),...o.otherHides??[]].map(r),p=new Set(u),m=new Set,g=[...e.customActions.values()].map(j=>new DOMParser().parseFromString(j,"application/xml").documentElement);for(const j of g)if(j.tagName==="CustomAction")for(const $ of Array.from(j.getElementsByTagName("*")))p.has(r($.getAttribute("Id")??""))&&Ml($).forEach(w=>m.add(r(w)));const b=j=>m.has(j)||u.some($=>j===$||j.startsWith(`${$}.`)),f=new Set(["Mscrm.Tabs",`Mscrm.SubGrid.${n}.ContextualTabs`]),y=(j,$)=>{const w=d.get($);return w&&xo(w)?{reason:"hidden-tab",why:`It is on the tab ${w}, which Unified Interface doesn't show; the ribbon doesn't return what is added there.`}:w||f.has($)?{reason:"not-returned",why:j==="Tab"?`The ribbon doesn't return this tab at ${$}, so Command Bar Studio can't place it (it may still show in Unified Interface).`:`${$} is on the canvas, but the ribbon doesn't return this ${j.toLowerCase()} there (for example a control added to a new group in a separate CustomAction).`}:{reason:"missing-location",why:/^(Mscrm|Microsoft)\./.test($)?`${$} isn't in this table's ribbon as loaded: it is not shown — possibly hidden by another solution — or it was removed.`:`${$} isn't in this table's ribbon as loaded: the group, tab or menu was removed or renamed, the Location is misspelled, or it is hidden by another solution.`}},x=j=>{const $=j.getAttribute("LabelText")??j.getAttribute("Title")??j.getAttribute("Alt")??"";return He($,s,i)||(j.getAttribute("Id")??"")},S=[],C=(j,$,w)=>{const A=j.getAttribute("Id")??"",B=Al.exec($)?.[1]??$;if(!A||c.has(r(A))||b(r(A))||b(r(B)))return;const k=fi.has(j.tagName);S.push({orphan:{id:A,element:j.tagName,label:x(j),location:$,customActionId:w,...y(j.tagName,r(B)),deleteControlIds:k?[]:[A],deleteContainerIds:k?[A]:[]},parent:B,inside:new Set(Ml(j))})};for(const j of g){if(j.tagName!=="CustomAction")continue;const $=j.getAttribute("Location")??"";if(!Al.test($)||/\.Scaling\._children$/.test($))continue;const w=Ol(Ol(j).find(k=>k.tagName==="CommandUIDefinition"))[0],A=w?.getAttribute("Id");if(!w||!A||!(fi.has(w.tagName)||kl.has(w.tagName)))continue;const B=j.getAttribute("Id")??"";if(!c.has(r(A))){C(w,$,B);continue}for(const k of Array.from(w.getElementsByTagName("*"))){const v=k.parentElement;v?.tagName!=="Controls"&&v?.tagName!=="Groups"||!fi.has(k.tagName)&&!kl.has(k.tagName)||C(k,`${v.getAttribute("Id")??""}._children`,B)}}const N=j=>S.find($=>$!==j&&$.inside.has(j.parent)&&!j.inside.has($.parent)),O=j=>{const $=new Set([j]);let w=j;for(let A=N(w);A&&!$.has(A);A=N(w))$.add(A),w=A;return w},I=S.filter(j=>!N(j));for(const j of S){const $=O(j);if($===j||!I.includes($))continue;const w=(A,B)=>B.forEach(k=>A.includes(k)||A.push(k));w($.orphan.deleteControlIds,j.orphan.deleteControlIds),w($.orphan.deleteContainerIds,j.orphan.deleteContainerIds)}return I.map(j=>j.orphan)}function h0(e,t,n=Date.now()){if(!t)return e;const o=sm*6e4,s=i=>Math.max(0,Math.floor((n-i)/6e4));return e.map(i=>{const l=t.publishedAt[i.customActionId];if(l!==void 0&&n-l<o){const c=s(l);return{...i,recentPublish:{minutesAgo:c,published:!0},why:`Published from here ${c} min before this table was loaded: the ribbon may not have caught up yet (it can lag 10 minutes or more). Reload the table later before deleting it. ${i.why}`}}if(n-t.at>=o)return i;const r=s(t.at);return{...i,recentPublish:{minutesAgo:r,published:!1},why:`The table was published from here ${r} min before this table was loaded, and the ribbon may not have caught up yet. ${i.why}`}})}const rm=window.dataverseAPI;function Eo(e){const t=new Set,n=[];for(const o of e)t.has(o.id)||(t.add(o.id),n.push(o));return n}function lm(e){const t=new Set;for(const n of e.tabDisplayRules)for(const o of n.rules)o.kind==="EntityRule"&&(o.context==="Form"&&t.add("Form"),o.context==="HomePageGrid"&&t.add("HomepageGrid"),(o.context==="SubGridStandard"||o.context==="SubGridAssociated")&&t.add("SubGrid"));return["HomepageGrid","Form","SubGrid"].filter(n=>t.has(n))}function cm(e){return lm(e)[0]}function g0(e,t,n={}){const o={HomepageGrid:[],SubGrid:[],Form:[]};for(const i of e)i.id.startsWith("Mscrm.Form.")?o.Form.push(i):i.id.startsWith("Mscrm.SubGrid.")?o.SubGrid.push(i):i.id.startsWith("Mscrm.HomepageGrid.")?o.HomepageGrid.push(i):o[cm(i)??"HomepageGrid"].push(i);const s=i=>{const l=Object.fromEntries(o[i].filter(r=>n[r.id]).map(r=>[r.id,n[r.id]]));return{location:i,entityLogicalName:t,tabs:o[i],...Object.keys(l).length>0?{scalingByTab:l}:{}}};return{HomepageGrid:s("HomepageGrid"),SubGrid:s("SubGrid"),Form:s("Form")}}const b0="Microsoft.Dynamics.CRM.RibbonLocationFilters'All'";function y0(e){return`RetrieveEntityRibbon(EntityName=@e,RibbonLocationFilter=@f)?@e='${encodeURIComponent(e.replace(/'/g,"''"))}'&@f=${b0}`}async function x0(e,t=[]){ce.getState().logInfo("dataverse",`RetrieveEntityRibbon(${e}, All)`);const n=await rm.queryData(y0(e));if(typeof n?.CompressedEntityXml!="string"||!n.CompressedEntityXml)throw new Error(`Dataverse returned no ribbon for ${e} (RetrieveEntityRibbon had no CompressedEntityXml).`);const o=await om(n.CompressedEntityXml),s=Is(o,"HomepageGrid",e,t),i=g0(s.ribbon.tabs,e,s.ribbon.scalingByTab);if(s.ribbon.templateLayouts)for(const l of Object.values(i))l.templateLayouts=s.ribbon.templateLayouts;return ce.getState().logInfo("dataverse",`RetrieveEntityRibbon succeeded for ${e} (Form=${i.Form.tabs.length}, HomepageGrid=${i.HomepageGrid.tabs.length}, SubGrid=${i.SubGrid.tabs.length})`),{ribbons:i,commands:s.commands,displayRules:s.displayRules,enableRules:s.enableRules,locLabels:s.locLabels}}const dm=5*6e4;let sa=null,ia=0,um=0;function S0(e={}){sa=null,ia++,e.afterPublish&&(um=Date.now()+dm)}async function v0(e=[]){const t=ce.getState(),n=ae.getState().connectionUrl,o=sa;let s;if(o&&o.environment===n&&Date.now()-o.at<dm)s=o.xml,t.logInfo("dataverse","RetrieveApplicationRibbon (reused from this session)");else{const i=ia;t.logInfo("dataverse","RetrieveApplicationRibbon()");const r=(await rm.execute({operationName:"RetrieveApplicationRibbon",operationType:"function"}))?.CompressedApplicationRibbonXml;if(typeof r!="string"||!r)throw new Error("Dataverse returned no application ribbon (RetrieveApplicationRibbon had no CompressedApplicationRibbonXml).");s=await om(r),i===ia&&Date.now()>=um&&(sa={environment:n,at:Date.now(),xml:s}),t.logInfo("dataverse","RetrieveApplicationRibbon succeeded")}return Is(s,"Application","{!EntityLogicalName}",e)}function hi(e,t,n,o=[]){const s={added:[],replaced:[]};if(n.commandDefinitions.size+n.enableRules.size+n.displayRules.size===0)return s;const i=vy(n),l=(g,b)=>JSON.stringify(g,Dl)===JSON.stringify(b,Dl),r=(g,b)=>{const f=new Map(b.map(y=>[y.id,y]));for(let y=0;y<g.length;y++){const x=f.get(g[y].id);x&&!l(x,g[y])&&(g[y]=x,s.replaced.push(x.id))}};r(t.commands,i.commands),r(t.enableRules,i.enableRules),r(t.displayRules,i.displayRules);const c=new Set(t.commands.map(g=>g.id)),d=new Set(o.filter(g=>!c.has(g)&&n.commandDefinitions.has(g)));for(const g of e)for(const b of g.tabs)for(const f of b.groups)for(const y of Ne(f))y.commandId&&!c.has(y.commandId)&&n.commandDefinitions.has(y.commandId)&&d.add(y.commandId);const u=i.commands.filter(g=>d.has(g.id));t.commands.push(...u),s.added.push(...u.map(g=>g.id));const p=new Set(t.enableRules.map(g=>g.id)),m=new Set(t.displayRules.map(g=>g.id));for(const g of t.commands){for(const b of g.enableRules){const f=i.enableRules.find(y=>y.id===b);f&&!p.has(b)&&(t.enableRules.push(f),p.add(b),s.added.push(b))}for(const b of g.displayRules){const f=i.displayRules.find(y=>y.id===b);f&&!m.has(b)&&(t.displayRules.push(f),m.add(b),s.added.push(b))}}return s}function Dl(e,t){if(typeof t!="string"||!t.trimStart().startsWith("<"))return t;try{return Nn(t)}catch{return t}}function w0(e,t){const n=(o,s)=>new Map([...o].filter(([i])=>!s?.has(i)));return{...e,commandDefinitions:n(e.commandDefinitions,t?.commandDefinitions),enableRules:n(e.enableRules,t?.enableRules),displayRules:n(e.displayRules,t?.displayRules)}}function C0(e,t,n){if(n!==1033)for(const o of e)for(const s of o.tabs)for(const i of s.groups)for(const l of Ne(i)){for(const d of l.menu?.sections??[]){const u=d.attributes?.Title;u?.startsWith("$LocLabels:")&&(d.title=He(u,t,n))}const r=l.source;if(!r)continue;const c=[[r.labelToken,"label"],[r.tooltipTitleToken,"tooltipTitle"],[r.tooltipBodyToken,"tooltipBody"]];for(const[d,u]of c)d?.startsWith("$LocLabels:")&&(l[u]=He(d,t,n))}}function El(e,t,n,o){const s=new Set(Object.values(e).flatMap(m=>m?.tabs.map(g=>g.id)??[])),i=new Set(fs(t).map(m=>m.location)),l=n?`Mscrm.SubGrid.${n}.ContextualTabs._children`:null,r=[];for(const m of Hc(t.customActions).values()){const g=new DOMParser().parseFromString(m,"application/xml").documentElement;if(g.tagName!=="CustomAction")continue;const b=bo(g.getAttribute("Location")??"",n??void 0);if(b!=="Mscrm.Tabs._children"&&b!==l)continue;const f=Array.from(g.getElementsByTagName("CommandUIDefinition")[0]?.children??[])[0],y=f?.tagName==="Tab"?f.getAttribute("Id"):null;!y||s.has(bo(y,n??void 0))||r.push({xml:new XMLSerializer().serializeToString(f),subGrid:b===l})}if(r.length===0)return[];const c=`<RibbonDefinitions><RibbonDefinition><UI><Ribbon><Tabs>${r.map(m=>m.xml).join("")}</Tabs></Ribbon></UI><RuleDefinitions><TabDisplayRules>${[...t.tabDisplayRules.values()].join("")}</TabDisplayRules></RuleDefinitions></RibbonDefinition></RibbonDefinitions>`,d=Is(c,n?"HomepageGrid":"Application",n??"{!EntityLogicalName}",o);d.ribbon.tabs=d.ribbon.tabs.filter(m=>!i.has(m.id));for(const m of d.ribbon.tabs){m.groups=m.groups.filter(g=>!i.has(g.id));for(const g of m.groups){g.buttons=g.buttons.filter(b=>!i.has(b.id));for(const b of Ne(g))i.has(b.id)&&Zc(g,b.id)}}const u=new Set(r.filter(m=>m.subGrid).map(m=>new DOMParser().parseFromString(m.xml,"application/xml").documentElement.getAttribute("Id"))),p=m=>n?u.has(m.id)?"SubGrid":cm(m)??"HomepageGrid":"Application";for(const m of d.ribbon.tabs){const g=n&&!u.has(m.id)?lm(m).slice(1):[];g.length>0&&ce.getState().logWarn("ribbon",`Tab ${m.id} shows on the ${p(m)} and on the ${g.join(" and ")} (its display rules); Command Bar Studio lists it under ${p(m)} only.`);const b=e[p(m)];if(!b)continue;b.tabs.push(m),b.tabs.sort((y,x)=>y.sequence-x.sequence);const f=d.ribbon.scalingByTab?.[m.id];f&&(b.scalingByTab={...b.scalingByTab??{},[m.id]:f})}return d.ribbon.tabs.map(m=>m.id)}function gi(e,t){if(t.added.length+t.replaced.length===0)return;const n=[t.added.length>0?`${t.added.length} missing (${t.added.join(", ")})`:"",t.replaced.length>0?`${t.replaced.length} out of date (${t.replaced.join(", ")})`:""].filter(Boolean);ce.getState().logWarn("ribbon",`${e} returned command / rule definitions that don't match your unmanaged customizations — ${n.join("; ")}. It can lag behind for a few minutes after a publish; loaded them from the unmanaged layer.`)}async function I0(e,t){const n=ce.getState();t?.("Reading your customizations…");const o=[],s=f=>y=>(o.push(`${f}: ${y instanceof Error?y.message:String(y)}`),null),[i,l,r]=await Promise.all([zi(e).catch(s(`the ${e} table's customizations`)),zi(null).catch(s("the application ribbon's customizations")),PS().catch(f=>{n.logWarn("dataverse",`${f instanceof Error?f.message:String(f)} Labels are shown in English; publishing reads it again and stops if it still can't.`)})]),c=i?Pi(i):[],d=l?Pi(l):[];t?.("Reading the table's ribbon and the application ribbon…");const[u,p]=await Promise.all([x0(e,[...c,...d]),v0(d)]);if(i){const f=El(u.ribbons,i,e,[...c,...d]);f.length>0&&n.logInfo("ribbon",`Loaded tab(s) ${f.join(", ")} from the table's unmanaged layer.`);const y=Xo(i);for(const x of Object.values(u.ribbons))Or(x,y);gi("RetrieveEntityRibbon",hi(Object.values(u.ribbons),u,i,[Ve]))}l&&(El({Application:p.ribbon},l,null,d),Or(p.ribbon,Xo(l)),gi("RetrieveApplicationRibbon",hi([p.ribbon],p,l)),gi("RetrieveEntityRibbon",hi(Object.values(u.ribbons),u,w0(l,i))));const m=Eo([...u.locLabels,...p.locLabels]),g=r??1033;t?.("Matching labels and ownership…"),C0([...Object.values(u.ribbons),p.ribbon],m,g);const b=i?f0(i,Object.values(u.ribbons),e,{locLabels:m,languageCode:g,otherHides:l?fs(l).map(f=>f.location):[]}):[];return b.length>0&&n.logWarn("ribbon",`${b.length} element(s) of the table's unmanaged customizations aren't on the canvas — the ribbon doesn't return them (see "Orphaned customizations"): ${b.map(f=>`${f.id} at ${f.location}`).join(", ")}.`),{ribbons:{HomepageGrid:u.ribbons.HomepageGrid,SubGrid:u.ribbons.SubGrid,Form:u.ribbons.Form,Application:p.ribbon},commands:Eo([...u.commands,...p.commands]),displayRules:Eo([...u.displayRules,...p.displayRules]),enableRules:Eo([...u.enableRules,...p.enableRules]),locLabels:m,layers:{entity:i?Qo(i):null,application:l?Qo(l):null},baseLanguageCode:r,orphans:b,...o.length>0?{layerReadError:o.join("; ")}:{}}}const j0="System",cs="{!EntityLogicalName}",Ho=new Map;function R0(e){if(!e||!e.includes("<"))return[];try{const t=new DOMParser().parseFromString(e,"application/xml");if(t.querySelector("parsererror"))return[];const n=t.getElementsByTagName("CommandUIDefinition")[0];if(!n)return[];const o=[];for(const s of Array.from(n.getElementsByTagName("*"))){const i=s.getAttribute("Id");i&&o.push(i)}return o}catch{return[]}}async function $0(e){const t=e.filter(n=>!Ho.has(n));for(let n=0;n<t.length;n+=40){const o=t.slice(n,n+40),s=await Cn(`solutions?$select=solutionid,uniquename&$expand=publisherid($select=friendlyname)&$filter=${o.map(i=>`solutionid eq ${i}`).join(" or ")}`);for(const i of o)Ho.set(i,null);for(const i of s){const l=i.publisherid;Ho.set(String(i.solutionid),{uniqueName:String(i.uniquename??""),publisherName:l?.friendlyname})}}}async function N0(e){const t=ce.getState(),n=new Map;if(!e||e===cs)return n;try{const o=e.replace(/'/g,"''"),s=await Cn(`ribbondiffs?$select=rdx,solutionid&$filter=(entity eq '${o}' or entity eq null) and ismanaged eq true and difftype le 1&$orderby=solutionid`),i=new Map;for(const l of s){const r=String(l.solutionid??"");if(r)for(const c of R0(String(l.rdx??""))){const d=c.split(cs).join(e);for(const u of d===c?[c]:[c,d])i.has(u)||i.set(u,new Set),i.get(u).add(r)}}await $0([...new Set([...i.values()].flatMap(l=>[...l]))]);for(const[l,r]of i){const c=[...r].map(d=>Ho.get(d)).find(d=>d&&d.uniqueName!==j0);c&&n.set(l,{origin:"managed",solutionName:c.uniqueName,publisherName:c.publisherName})}t.logInfo("provenance",`${s.length} managed CustomAction(s) for ${e}: ${n.size} control(s) from managed solutions.`)}catch(o){t.logWarn("provenance",`Couldn't read which managed solutions add ${e}'s controls (${o instanceof Error?o.message:String(o)}); their owners aren't shown. This is non-fatal.`)}return n}async function T0(e){if(!e||e===cs)return[];try{const t=e.replace(/'/g,"''"),n=await Cn(`ribbondiffs?$select=rdx&$filter=(entity eq '${t}' or entity eq null) and ismanaged eq true and difftype eq 3&$orderby=solutionid`),o=[],s=new DOMParser;for(const i of n){const l=s.parseFromString(String(i.rdx??""),"application/xml");if(!l.querySelector("parsererror"))for(const r of Array.from(l.getElementsByTagName("LocLabel"))){const c=r.getAttribute("Id");if(!c)continue;const d=Array.from(r.getElementsByTagName("Title")).map(p=>({languageCode:Number(p.getAttribute("languagecode")),description:p.getAttribute("description")??""})).filter(p=>Number.isFinite(p.languageCode)&&p.description);if(d.length===0)continue;o.push({id:c,titles:d});const u=c.split(cs).join(e);u!==c&&o.push({id:u,titles:d})}}return ce.getState().logInfo("provenance",`${o.length} label text(s) from managed solutions for ${e}.`),o}catch(t){return ce.getState().logWarn("provenance",`Couldn't read the managed solutions' label texts for ${e} (${t instanceof Error?t.message:String(t)}); their ids are shown. This is non-fatal.`),[]}}function k0(){return window.dataverseAPI}async function A0(){const e=k0();ce.getState().logInfo("dataverse","Resolving current user via WhoAmI...");const t=await e.execute({operationName:"WhoAmI",operationType:"function"}),n=typeof t.UserId=="string"?t.UserId:"";if(!n)return ce.getState().logWarn("dataverse","WhoAmI returned no user id."),{id:"",name:""};const s=(await e.retrieve("systemuser",n,["fullname"])).fullname?.trim(),i={id:n,name:s&&s.length>0?s:"Current User"};return ce.getState().logInfo("dataverse",`Current user resolved: ${i.name}.`),i}function O0(){E.useEffect(()=>{const e=dx();return e>0&&ce.getState().logInfo("ribbon",`Discarded ${e} unsaved-changes draft(s) older than ${Ed} days, or saved by an earlier version of Command Bar Studio (they can't be restored correctly).`),mx()},[])}function M0(){const e=je(i=>i.pending),t=je(i=>i.pendingBaselineChanged),n=je(i=>i.restoreError),o=je(i=>i.restoreDraft),s=je(i=>i.discardDraft);return e?a.jsxs(un,{open:!0,onOpenChange:()=>{},modalType:"alert",size:"small",title:"Unpublished changes",actions:a.jsxs(a.Fragment,{children:[a.jsx(Ga,{onClick:s,children:"Discard changes"}),a.jsx(K,{appearance:"primary",disabled:!!n,onClick:()=>o(),"data-autofocus":!0,children:"Restore changes"})]}),children:[a.jsxs(V,{block:!0,children:["You have unpublished changes to this table from a previous session (saved"," ",new Date(e.savedAt).toLocaleString(),"). Restore them on top of the ribbon as it is now, or discard them?"]}),t&&a.jsx(Rt,{intent:"warning",layout:"multiline",style:{marginTop:"12px"},children:a.jsx($t,{children:"The table's ribbon has changed since then (published from another session, or by someone else): review the publish plan before publishing."})}),n&&a.jsx(Rt,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:a.jsxs($t,{children:["These changes couldn't be restored (",n,"). Discard them to continue; the details are in the runtime log."]})})]}):null}function D0(){const e=je(d=>d.pendingSwitch),t=je(d=>d.pending!==null),n=je(d=>d.saveFailed),o=je(d=>d.resolveSwitch),s=ae(d=>d.activeEntity),i=ae(d=>d.activeSolution);if(!e)return null;const l=s?.displayName||s?.logicalName||"this table",r=e.kind==="entity"?`table ${e.entity.displayName||e.entity.logicalName}`:`solution ${e.solution.friendlyName||e.solution.uniqueName}`,c=i?.friendlyName||i?.uniqueName||"this solution";return a.jsxs(un,{open:!0,onOpenChange:d=>!d&&o("cancel"),modalType:"alert",size:"small",title:"Unpublished changes",actions:a.jsxs(a.Fragment,{children:[a.jsx(K,{appearance:"secondary",onClick:()=>o("cancel"),children:"Cancel"}),a.jsxs(Ga,{onClick:()=>o("discard"),children:["Discard",t?" and switch":" changes"]}),!t&&a.jsx(K,{appearance:"primary",disabled:n,onClick:()=>o("keep"),children:"Keep as draft"})]}),children:[a.jsxs(V,{block:!0,children:[l," has changes that aren't published. Switch to ",r,"?"]}),a.jsx(V,{block:!0,style:{marginTop:"8px"},children:t?a.jsxs(a.Fragment,{children:["Changes made since opening ",l," aren't saved: the unsaved changes of your previous session are kept until you restore or discard them."]}):a.jsxs(a.Fragment,{children:[a.jsx("strong",{children:"Keep as draft"})," saves them on this computer: they are offered again when you open ",l," in ",c,". ",a.jsx("strong",{children:"Discard changes"})," ","deletes them."]})}),n&&!t&&a.jsx(Rt,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:a.jsx($t,{children:"The changes can't be saved as a draft: the browser storage is full. Publish them first, or discard them to switch."})})]})}function E0(){const e=ae(w=>w.setSolutions),t=ae(w=>w.setEntities),n=ae(w=>w.setCurrentUser),o=ae(w=>w.setSolutionEntityIds),s=ae(w=>w.setSolutionRibbonComponentIds),i=ae(w=>w.activeSolution),l=ae(w=>w.activeEntity),r=ae(w=>w.connectionVersion),c=M(w=>w.loadWorkspace),d=J(w=>w.setTabId),u=Z(w=>w.themeMode),p=ce(w=>w.logInfo),m=ce(w=>w.logWarn),g=ce(w=>w.logError);O0(),Hv();const[b,f]=E.useState("idle"),[y,x]=E.useState(null),[S,C]=E.useState(null),[N,O]=E.useState(null),[I,j]=E.useState(0);E.useEffect(()=>{p("runtime","Loading solutions and current user...");let w=!1;return i0().then(A=>{w||(e(A),p("runtime",`Loaded ${A.length} solution(s). Pick one to load its tables.`))}).catch(A=>{w||g("runtime",`Failed to load solutions: ${A instanceof Error?A.message:String(A)}`)}),A0().then(A=>{w||!A.id||(n(A.id,A.name),p("runtime",`Current user: ${A.name}.`))}).catch(A=>{m("runtime",`Failed to resolve current user: ${A instanceof Error?A.message:String(A)}`)}),()=>{w=!0}},[e,n,p,m,g,r]),E.useEffect(()=>{if(!i){o(null),s(null),t([]);return}let w=!1;return(async()=>{try{const[A,B]=await Promise.all([a0(i.id),r0(i.id)]);if(w)return;if(o(A),s(B),A.length===0){t([]);return}const k=await c0(A);if(w)return;t(k)}catch(A){if(w)return;g("runtime",`Failed to load solution tables: ${A instanceof Error?A.message:String(A)}`),o([]),s([]),t([])}})(),()=>{w=!0}},[i,t,o,s,g]),E.useEffect(()=>{if(je.getState().beginLoad(),!l?.logicalName){f("idle"),x(null),O(null);return}let w=!1;const A=qd(l.logicalName);return f("loading"),x(null),O(null),C(null),p("ribbon",`Loading ribbon workspace for ${l.logicalName}...`),Xi.getState().setManaged([]),T0(l.logicalName).then(B=>{w||Xi.getState().setManaged(B)}),Promise.all([I0(l.logicalName,B=>{w||C(B)}),N0(l.logicalName).catch(()=>new Map)]).then(([B,k])=>{if(w)return;const v=new Set([...B.layers?.entity?.controlIds??[],...B.layers?.application?.controlIds??[]]);iy(B.ribbons,k,v);const T=[],R=new Set;for(const re of Object.values(B.ribbons))for(const le of re.tabs)for(const F of le.groups)for(const L of Ne(F))L.origin==="managed"&&!R.has(L.id)&&(R.add(L.id),T.push({elementId:L.id,elementKind:"button",solutions:[{solutionId:"",solutionName:L.solutionName??"Managed Solution",publisher:L.publisherName??"",managed:!0,wins:!0,importedOn:void 0}]}));M.getState().setConflicts(T),c({ribbons:B.ribbons,commands:B.commands,displayRules:B.displayRules,enableRules:B.enableRules,locLabels:B.locLabels,layers:B.layers,baseLanguageCode:B.baseLanguageCode,baseLanguageUnknown:B.baseLanguageCode===void 0,labelsUnknown:B.layerReadError!==void 0,orphans:{entity:h0(B.orphans??[],u0(ae.getState().connectionUrl,l.logicalName))}});const{location:D,tabId:q}=J.getState(),X=B.ribbons[D]?.tabs??[];if(!(X.some(re=>re.id===q)&&!xo(q))){const re=mo(X);re&&d(re)}je.getState().workspaceLoaded(A),O(B.layerReadError??null),B.layerReadError&&m("ribbon",`Unmanaged layer not read: ${B.layerReadError}`),f("idle"),p("ribbon",`Ribbon workspace loaded for ${l.logicalName}.`)}).catch(B=>{if(w)return;const k=B instanceof Error?B.message:"Failed to load ribbon";f("error"),x(k),g("ribbon",`Ribbon load failed for ${l.logicalName}: ${k}`)}),()=>{w=!0}},[l?.logicalName,c,I,d,p,m,g]);function $(){S0(),j(w=>w+1)}return a.jsxs(jg,{theme:u==="dark"?Rg:$g,children:[a.jsx($S,{leftPane:a.jsx(s0,{}),rightPane:a.jsx(pC,{}),bottomPanel:a.jsx(VC,{}),children:a.jsx(Rw,{isLoadingRibbon:b==="loading",loadingTable:l?.displayName??l?.logicalName,loadingStep:S,ribbonLoadError:y,layerReadError:N,onRetryRibbonLoad:$,emptyState:i?l?void 0:"noTable":"noSolution"})}),a.jsx(M0,{}),a.jsx(D0,{})]})}const B0=5e3,Bl=3e4,mm="1.2.7";function Ll(e,t,n){let o;return Promise.race([e,new Promise((s,i)=>{o=setTimeout(()=>i(new Error(n)),t)})]).finally(()=>clearTimeout(o))}async function L0(e){const{toolboxAPI:t,dataverseAPI:n}=e;if(!t||!n)throw new Error("Command Bar Studio must be opened from Power Platform ToolBox: the toolbox APIs (toolboxAPI / dataverseAPI) aren't available.");const o=t.connections?.getActiveConnection;if(typeof o!="function")throw new Error(`This version of Power Platform ToolBox doesn't provide the connection API Command Bar Studio uses. Update Power Platform ToolBox (desktop app or VS Code extension) to ${mm} or later.`);const s=[];let i="light";try{const r=t.utils?.getCurrentTheme;if(typeof r!="function")throw new Error("the host has no theme API");i=await Ll(r(),B0,"the host didn't answer")==="dark"?"dark":"light"}catch(r){s.push(`Couldn't read the host theme (${fm(r)}); using the light theme.`)}const l=await Ll(o(),Bl,`Power Platform ToolBox didn't return the active connection within ${Bl/1e3} seconds. Make sure a connection is active and signed in, then open Command Bar Studio again.`);if(!l)throw new Error("No active connection: connect to an environment in Power Platform ToolBox, then open Command Bar Studio again.");return{connection:l,theme:i,warnings:s}}function pm(e,t,n="Command Bar Studio couldn't start"){const o=e.ownerDocument,s=(c,d)=>{const u=o.createElement(c);return d&&(u.textContent=d),u},i=s("div");i.setAttribute("role","alert"),i.style.cssText="font-family: 'Segoe UI', system-ui, sans-serif; padding: 24px; max-width: 720px; line-height: 1.5;",i.append(s("h1",n));const l=s("p",fm(t));l.style.fontWeight="600",i.append(l);const r=s("ul");for(const c of["Close the Command Bar Studio tab and open the tool again.",`Use Power Platform ToolBox ${mm} or later (desktop app or VS Code extension).`,"Make sure a connection is active and signed in.","If it keeps happening, report it at https://github.com/mohsinonxrm/pptb-mxrm-commandbar-studio/issues with this message."])r.append(s("li",c));i.append(r),e.replaceChildren(i)}function fm(e){return e instanceof Error?e.message:String(e)}class z0 extends E.Component{state={error:void 0};box=E.createRef();static getDerivedStateFromError(t){return{error:t??new Error("Unknown error")}}componentDidCatch(t,n){console.error("[CBS RootErrorBoundary]",t,n),ce.getState().logError("app",t instanceof Error?t.message:String(t))}componentDidMount(){this.componentDidUpdate()}componentDidUpdate(){this.state.error!==void 0&&this.box.current&&pm(this.box.current,this.state.error,"Command Bar Studio stopped working")}render(){return this.state.error===void 0?this.props.children:a.jsx("div",{ref:this.box})}}function P0(e){return e.replace(/([A-Z])/g,(t,n,o)=>(o>0?"_":"")+t.toLowerCase())}function F0(e){const t=new TextEncoder().encode(e);let n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return btoa(n)}function hm(e,t="regular"){return`${P0(e)}${t==="filled"?".filled":""}.svg`}function _0(e,t,n="regular"){const o=e.trim().replace(/_+$/,"");if(!o)throw new Error("A publisher prefix is required to name the icon web resource");return`${o}_/icons/cbs/${hm(t,n)}`}const q0=11,W0=2*6e4,zl={save:JS,publish:gu},gm=new Set;function H0(){gm.clear()}async function II(e,t,n,o,s={}){const i=s.save??zl.save,l=s.publish??zl.publish,r=s.published??gm,c=_0(n,e,t),d=await o(e,20,t);if(!d)throw new Error(`Could not convert the Fluent icon "${e}" to SVG`);const u=await i(c,F0(d),q0,{displayName:`${hm(e,t)} (CBS icon)`,keepExisting:!0,guard:s.guard,publish:!1}),p={name:c,id:u.id,created:u.created};if(!r.has(u.id))try{await uu(`Publishing icon web resource ${c}`,()=>l(u.id,s.guard),{timeoutMs:W0,...s.busy}),r.add(u.id)}catch(m){p.publishError=m instanceof Error?m.message:String(m)}return p}const G0=["commandEditorOpen","ruleEditorOpen","iconPickerOpen","newGroupOpen","importXmlOpen","webResourceBrowserOpen","newTabOpen"];function U0(e){if(!e)return"none";const t=ae.getState(),n=ce.getState();if(Uo(e)===Uo({id:t.connectionId,url:t.connectionUrl}))return e.name===t.connectionName&&e.environment===t.environment?"none":(t.setConnection(e.url,e.name,e.environment,e.id),n.logInfo("startup",`Connection details updated: ${e.name} (${e.environment}).`),"details");const s=`${t.connectionName||t.connectionUrl} (${t.environment})`,i=`${e.name} (${e.environment})`,{hadChanges:l,kept:r}=je.getState().releaseForConnectionChange();M.getState().resetWorkspace(),J.getState().clearSelection(),we.getState().reset(),H0(),Gv(),ea.clear(),t.switchConnection(e,{draftKept:l&&r,draftLost:l&&!r});try{Z.setState({...Object.fromEntries(G0.map(c=>[c,!1])),editorStack:[]})}catch(c){n.logWarn("startup",`Couldn't close the open panels after the connection change: ${c instanceof Error?c.message:String(c)}`)}return n.logWarn("startup",`The tool's connection changed from ${s} to ${i}. The loaded solution and table were closed.`),l&&r&&n.logInfo("startup",`The unpublished changes were kept as a draft for ${s}.`),l&&!r&&n.logError("startup",`The unpublished changes on ${s} couldn't be saved as a draft (browser storage full) and are lost.`),"switched"}async function V0(){const e=ce.getState().logInfo,t=window,n=t.toolboxAPI,{connection:o,theme:s,warnings:i}=await L0({toolboxAPI:n,dataverseAPI:t.dataverseAPI});e("startup","Connected to PPTB host runtime.");for(const m of i)ce.getState().logWarn("startup",m);e("startup",`Host theme loaded: ${s}.`);const{setConnection:l}=ae.getState(),{setThemeMode:r}=Z.getState(),c=await Ia().catch(()=>null)??o;l(c.url,c.name,c.environment,c.id),r(s),e("startup",`Connected to ${c.name} (${c.environment}).`),Ug(m=>U0(m));const d=()=>{n.utils.getCurrentTheme().then(m=>{Z.getState().setThemeMode(m==="dark"?"dark":"light")}).catch(m=>{ce.getState().logWarn("startup",`Theme refresh failed: ${m instanceof Error?m.message:String(m)}`)})};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&d()}),n.events?.on((m,g)=>{g?.event==="settings:updated"&&d()});const u=document.getElementById("root");if(!u)throw new Error("No #root element found");_g.createRoot(u).render(a.jsx(E.StrictMode,{children:a.jsx(z0,{children:a.jsx(E0,{})})}))}V0().catch(e=>{ce.getState().logError("startup",e instanceof Error?e.message:String(e)),console.error(e);const t=document.getElementById("root")??document.body;pm(t,e)});export{CI as $,nI as A,Q0 as B,m0 as C,he as D,S0 as E,kc as F,ce as G,PS as H,zu as I,yI as J,lI as K,mI as L,os as M,lb as N,uu as O,_S as P,tI as Q,ae as R,Ia as S,Wd as T,pI as U,fI as V,Ex as W,ti as X,un as Y,Ts as Z,xI as _,M as a,dI as a0,Ve as a1,gd as a2,Kc as a3,Ar as a4,xo as a5,J as a6,fd as a7,Bb as a8,Wn as a9,nr as aA,Ku as aB,ea as aC,su as aD,cI as aE,gI as aF,Mw as aG,Pw as aH,uo as aI,YS as aJ,vI as aK,jn as aL,hI as aM,vt as aN,so as aO,aI as aP,ys as aQ,bs as aR,gs as aS,Br as aa,uI as ab,Hd as ac,Is as ad,dt as ae,Oc as af,ki as ag,Jo as ah,He as ai,Ee as aj,je as ak,Ss as al,Ut as am,SI as an,Ka as ao,P0 as ap,_0 as aq,Ma as ar,hx as as,II as at,bI as au,wI as av,JS as aw,US as ax,Yu as ay,Ju as az,Z as b,Rb as c,oy as d,En as e,Qb as f,rI as g,ty as h,Di as i,ey as j,zi as k,Gc as l,ja as m,Qc as n,Xo as o,Z0 as p,Uc as q,Ra as r,Ne as s,Ec as t,Va as u,oI as v,sI as w,$a as x,iI as y,eI as z};