@mohsinonxrm/pptb-commandbar-studio 0.7.0 → 0.8.0

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 (45) hide show
  1. package/CHANGELOG.md +189 -0
  2. package/README.md +13 -10
  3. package/SECURITY.md +9 -8
  4. package/dist/assets/BulkPublishModal-mJ41AWew.js +36 -0
  5. package/dist/assets/CommandEditorPanel-BiP1kPHY.js +1 -0
  6. package/dist/assets/CommandPalette-q51_0qRZ.js +1 -0
  7. package/dist/assets/{ConflictDrawer-DAQi31Y8.js → ConflictDrawer-CdWv_PbN.js} +1 -1
  8. package/dist/assets/{DiffViewer-DVIsuwXy.js → DiffViewer-BQP5f73U.js} +1 -1
  9. package/dist/assets/HideInsteadOfDeleteModal-C9r6ah5p.js +1 -0
  10. package/dist/assets/IconPickerModal-B81Tnf5i.js +1 -0
  11. package/dist/assets/{ImportXmlModal-2-0E4Ib_.js → ImportXmlModal-C0cMaS59.js} +1 -1
  12. package/dist/assets/LocalizationEditor-DniDtrZV.js +1 -0
  13. package/dist/assets/{MonacoEditor-DGzdcWNE.js → MonacoEditor-uzfuRCpJ.js} +1 -1
  14. package/dist/assets/{NewButtonModal-CKKbFpLd.js → NewButtonModal-BXpX1Ld5.js} +1 -1
  15. package/dist/assets/{NewGroupModal-BpXuxZKo.js → NewGroupModal-Bh7lXq52.js} +1 -1
  16. package/dist/assets/{NewTabModal-CoBSto1f.js → NewTabModal-Pntdk3in.js} +1 -1
  17. package/dist/assets/RuleEditorPanel-BUGKgc0N.js +1 -0
  18. package/dist/assets/{ScalingEditorPanel-L_j0ox4f.js → ScalingEditorPanel-p3-Yw3CO.js} +1 -1
  19. package/dist/assets/TabDisplayRulesPanel-CSNshwaw.js +1 -0
  20. package/dist/assets/{UrlComposerModal-BhcG5L1S.js → UrlComposerModal-WKSTwUcW.js} +1 -1
  21. package/dist/assets/WebResourceBrowser-BK-gVU2g.js +1 -0
  22. package/dist/assets/XmlDrawer-CQJElnD1.js +2 -0
  23. package/dist/assets/{dnd-BmqIZ1-i.js → dnd-Cq8OftAq.js} +1 -1
  24. package/dist/assets/fluent-icons-BqJj6rDi.js +1 -0
  25. package/dist/assets/{fluent-ui-Dde22_ZN.js → fluent-ui-QADO660t.js} +1 -1
  26. package/dist/assets/index-Di2_5czx.js +136 -0
  27. package/dist/assets/{useReplaceWebResourceConfirm-Mb36NTI7.js → useReplaceWebResourceConfirm-BUWBVNSC.js} +1 -1
  28. package/dist/assets/useStableKeys-p2OkzZWO.js +1 -0
  29. package/dist/assets/xmlValidator-BkeotXuB.js +3 -0
  30. package/dist/index.html +4 -4
  31. package/package.json +1 -1
  32. package/dist/assets/BulkPublishModal-B0Ecmiq1.js +0 -36
  33. package/dist/assets/CommandEditorPanel-FdBZ2zNj.js +0 -1
  34. package/dist/assets/CommandPalette-BL4yGqtx.js +0 -1
  35. package/dist/assets/CrmParameterEditor-CQD0gNNH.js +0 -1
  36. package/dist/assets/HideInsteadOfDeleteModal-BBfhx5dO.js +0 -1
  37. package/dist/assets/IconPickerModal-D97ew6l_.js +0 -1
  38. package/dist/assets/LocalizationEditor-7sYCHKMx.js +0 -1
  39. package/dist/assets/RuleEditorPanel-Dg2vnxrc.js +0 -1
  40. package/dist/assets/TabDisplayRulesPanel-W1SMJTlj.js +0 -1
  41. package/dist/assets/WebResourceBrowser-CQemLOXD.js +0 -1
  42. package/dist/assets/XmlDrawer-BOOdH0HN.js +0 -2
  43. package/dist/assets/fluent-icons-DUgjkNjy.js +0 -1
  44. package/dist/assets/index-DUEHURiA.js +0 -136
  45. package/dist/assets/xmlValidator-BB2o3QUU.js +0 -3
@@ -0,0 +1,136 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./XmlDrawer-CQJElnD1.js","./fluent-icons-BqJj6rDi.js","./monaco-BIO15LCS.js","./monaco-DdLsZAcA.css","./MonacoEditor-uzfuRCpJ.js","./fluent-ui-QADO660t.js","./dnd-Cq8OftAq.js","./CommandEditorPanel-BiP1kPHY.js","./useStableKeys-p2OkzZWO.js","./crmParameters-rgfZhhzN.js","./RuleEditorPanel-BUGKgc0N.js","./ruleKinds-B9hACGaq.js","./BulkPublishModal-mJ41AWew.js","./xmlValidator-BkeotXuB.js","./NewButtonModal-BXpX1Ld5.js","./NewGroupModal-Bh7lXq52.js","./NewTabModal-Pntdk3in.js","./ImportXmlModal-C0cMaS59.js","./CommandPalette-q51_0qRZ.js","./LocalizationEditor-DniDtrZV.js","./IconPickerModal-B81Tnf5i.js","./useReplaceWebResourceConfirm-BUWBVNSC.js","./TabDisplayRulesPanel-CSNshwaw.js","./ScalingEditorPanel-p3-Yw3CO.js","./ConflictDrawer-CdWv_PbN.js","./WebResourceBrowser-BK-gVU2g.js","./UrlComposerModal-WKSTwUcW.js","./DiffViewer-BQP5f73U.js","./HideInsteadOfDeleteModal-C9r6ah5p.js","./server.browser-xEJRzS2D.js"])))=>i.map(i=>d[i]);
2
+ import{y as r,z as me,i as It,B as nd,E as wt,F as ra,G as aa,H as co,J as od,Q as la,K as jt,L as on,M as ca,N as id,O as da,P as sd,U as ua,V as rd,X as ad,Y as ld,Z as cd,$ as dd,a0 as ud,a1 as md,a2 as pd,a3 as fd,a4 as wi,a5 as hd,a6 as gd,a7 as bd,a8 as ma,a9 as yd,aa as xd,ab as Sd,ac as vd,ad as wd,ae as Cd,af as Id,ag as pa,ah as Rd,ai as jd,aj as $d,ak as Nd,al as Td,am as kd,an as Ad,ao as fa,ap as Dd,aq as Ed,ar as Od,as as Md,at as Bd,au as zd,av as Ld,aw as Pd,ax as Fd,ay as _d,az as ha,aA as qd,aB as ga,aC as Wd,aD as Hd,aE as Gd,aF as ba,aG as Ud,aH as Xd,aI as Vd,aJ as Kd,aK as Jd,aL as Yd,aM as Zd,aN as Qd,aO as eu,aP as st,aQ as tu,aR as nu,aS as ou,aT as iu,aU as su,aV as ru,aW as au,aX as lu,aY as to,aZ as cu,a_ as du,a$ as uu,b0 as mu,b1 as pu,b2 as fu,b3 as hu,b4 as gu,b5 as bu,b6 as ya,b7 as yu,b8 as xa,b9 as xu,ba as Su,bb as vu,bc as wu,bd as Cu,be as Iu,bf as Ru,bg as ju,bh as $u,bi as Sa,bj as Nu,bk as Tu,bl as ku,bm as ko,bn as Au,bo as Du,bp as Eu,bq as Ou,br as Mu,bs as Bu,bt as zu,bu as Ci,bv as Lu,bw as va,bx as Pu,by as Fu,bz as _u,bA as qu,bB as Wu,bC as wa,bD as Hu,bE as Ca,bF as Gu,bG as Uu,bH as Xu,bI as Vu,bJ as Ku,bK as Lt,bL as Ju,bM as Yu,h as Ot,g as Zu,bN as Qu,w as em,x as tm,bO as nm,bP as om,bQ as im,bR as sm,bS as rm,bT as am,bU as lm,bV as cm,bW as Ia,bX as dm,bY as um,A as mm,bZ as pm,s as fm,b_ as hm,b$ as gm,c0 as bm,c1 as ym,c2 as xm,c3 as Sm,c4 as vm,c5 as wm,c6 as Cm,c7 as Im,c8 as Rm,c9 as jm,ca as Ii,cb as $m,cc as Nm,cd as Tm,ce as km,cf as Am,cg as Dm,ch as Em,ci as kn,cj as Om,ck as Ra,cl as Mm,cm as Ao,cn as Bm,co as Bt,cp as zm,cq as Ae,cr as Lm,cs as Pm,ct as Fm,cu as _m,cv as qm,cw as Wm,cx as Hm,cy as Gm,cz as Um,cA as Xm,cB as Vm,cC as Gs,cD as Km,cE as Us,cF as Jm,cG as Ym,cH as Zm,cI as Xs,cJ as Qm,cK as ep,cL as tp,cM as np,cN as op,cO as Xo,cP as ip,cQ as Vs,cR as Hn,cS as sp,cT as Gn,cU as rp,cV as Ks,cW as ap,cX as Js,cY as ja,cZ as An,c_ as uo,c$ as $a,d0 as Na,d1 as Ys,m as Qt,d2 as lp,d3 as cp,d4 as dp}from"./fluent-icons-BqJj6rDi.js";import{l as up,m as mp,R as Je,_ as De,a as z}from"./monaco-BIO15LCS.js";import{a as pp,T as Ee,t as p,b as q,B as ue,u as fp,P as Ta,c as ka,d as Z,e as Aa,F as ze,C as hp,O as gp,S as $t,M as Re,f as je,g as Xt,h as be,D as sn,i as rn,j as an,k as ln,l as cn,m as dn,I as Ue,n as Ri,o as ji,p as $i,q as Ni,s as vt,v as bp,w as yp,x as xp,y as Sp,z as Da,A as vp,E as wp,G as Cp,H as Ip,J as Rp,K as jp,L as $p,N as Np,Q as Tp,R as kp,U as Ap,V as Dp,W as Ep,X as Op,Y as Zs,Z as Ft,_ as Mp,$ as _t,a0 as ht,a1 as cs,a2 as Ea,a3 as Oa,a4 as Fe,a5 as ds,a6 as Bp,a7 as nt,a8 as zp,a9 as Vo,aa as Pt,ab as Ti,ac as us,ad as ot,ae as Lp,af as Pp,ag as Fp,ah as _p}from"./fluent-ui-QADO660t.js";import{u as qp,a as Ma,b as mo,K as Ba,P as za,D as La,c as Wp,d as Hp,e as Pa,f as Gp,S as Up,h as Xp,g as Vp,C as Kp}from"./dnd-Cq8OftAq.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))o(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&o(a)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function o(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();function Jp(e){return new Worker(""+new URL("editor.worker-D1TDBLlL.js",import.meta.url).href,{name:e?.name})}function Yp(e){return new Worker(""+new URL("json.worker-BggoxaER.js",import.meta.url).href,{name:e?.name})}function Zp(e){return new Worker(""+new URL("ts.worker-BrLZGe_E.js",import.meta.url).href,{name:e?.name})}function Qp(e){return new Worker(""+new URL("css.worker-C_6RgliQ.js",import.meta.url).href,{name:e?.name})}function ef(e){return new Worker(""+new URL("html.worker-CLyYFd_g.js",import.meta.url).href,{name:e?.name})}up.config({monaco:mp});self.MonacoEnvironment={getWorker(e,t){return t==="json"?new Yp:t==="typescript"||t==="javascript"?new Zp:t==="css"||t==="scss"||t==="less"?new Qp:t==="html"||t==="handlebars"||t==="razor"?new ef:new Jp}};var Un={},Qs;function tf(){if(Qs)return Un;Qs=1;var e=pp();return Un.createRoot=e.createRoot,Un.hydrateRoot=e.hydrateRoot,Un}var nf=tf();const er=e=>{let t;const n=new Set,o=(d,u)=>{const m=typeof d=="function"?d(t):d;if(!Object.is(m,t)){const f=t;t=u??(typeof m!="object"||m===null)?m:Object.assign({},t,m),n.forEach(y=>y(t,f))}},i=()=>t,l={setState:o,getState:i,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(o,i,l);return l},of=(e=>e?er(e):er),sf=e=>e;function rf(e,t=sf){const n=Je.useSyncExternalStore(e.subscribe,Je.useCallback(()=>t(e.getState()),[e,t]),Je.useCallback(()=>t(e.getInitialState()),[e,t]));return Je.useDebugValue(n),n}const af=e=>{const t=of(e),n=o=>rf(t,o);return Object.assign(n,t),n},Nt=(e=>af);function po(e){if(!e||!e.id&&!e.url)return"";const t=(e.url??"").trim().replace(/\/+$/,"").toLowerCase();return`${e.id??""}|${t}`}function Fa(){return window.toolboxAPI?.connections}async function ms(){const e=Fa();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 ki 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 Cn,Ai=0;function tr(e){const t=po(e);Cn!==void 0&&t!==Cn&&Ai++,Cn=t}async function Do(e){const t=Fa();if(Cn===void 0||!t?.getConnection&&!t?.getActiveConnection)return;let n;try{n=po(await ms())}catch{throw new ki(e)}if(n!==Cn)throw new ki(e)}function lf(e){const t=window.toolboxAPI?.events;if(typeof t?.on!="function")return()=>{};let n=0;const o=(i,s)=>{const a=s?.event;if(a!=="connection:updated"&&a!=="connection:created"&&a!=="connection:deleted")return;const l=++n;ms().then(c=>{l===n&&e(c)}).catch(()=>{})};return t.on(o),()=>t.off?.(o)}function _a(){const e=Ai;return async t=>{if(Ai!==e)throw new ki(t);await Do(t)}}const Di=new Set;function cf(e){return Di.add(e),()=>Di.delete(e)}const oe=Nt()((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,i,s=t().connectionId)=>{tr({id:s,url:n}),e({connectionId:s,connectionUrl:n,connectionName:o,environment:i})},switchConnection:(n,o)=>{const i=t();tr(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:i.connectionVersion+1,connectionNotice:{...o,from:{name:i.connectionName,url:i.connectionUrl,environment:i.environment},to:{name:n.name,url:n.url,environment:n.environment}}})},dismissConnectionNotice:()=>e({connectionNotice:null}),setSolutions:n=>e({solutions:n}),setActiveSolution:n=>{De(async()=>{const{useRuntimeLogStore:i}=await Promise.resolve().then(()=>gf);return{useRuntimeLogStore:i}},void 0,import.meta.url).then(({useRuntimeLogStore:i})=>{i.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??""))&&i.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 i of Di)i()},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})})),df=e=>(t,n,o)=>{const i=o.subscribe;return o.subscribe=((a,l,c)=>{let d=a;if(l){const u=c?.equalityFn||Object.is;let m=a(o.getState());d=f=>{const y=a(f);if(!u(m,y)){const x=m;l(m=y,x)}},c?.fireImmediately&&l(m,m)}return i(d)}),e(t,n,o)},uf=df;function mf(e,t){let n;try{n=e()}catch{return}return{getItem:i=>{var s;const a=c=>c===null?null:JSON.parse(c,void 0),l=(s=n.getItem(i))!=null?s:null;return l instanceof Promise?l.then(a):a(l)},setItem:(i,s)=>n.setItem(i,JSON.stringify(s,void 0)),removeItem:i=>n.removeItem(i)}}const Ei=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(o){return Ei(o)(n)},catch(o){return this}}}catch(n){return{then(o){return this},catch(o){return Ei(o)(n)}}}},pf=(e,t)=>(n,o,i)=>{let s={storage:mf(()=>window.localStorage),partialize:S=>S,version:0,merge:(S,v)=>({...v,...S}),...t},a=!1,l=0;const c=new Set,d=new Set;let u=s.storage;if(!u)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),n(...S)},o,i);const m=()=>{const S=s.partialize({...o()});return u.setItem(s.name,{state:S,version:s.version})},f=i.setState;i.setState=(S,v)=>(f(S,v),m());const y=e((...S)=>(n(...S),m()),o,i);i.getInitialState=()=>y;let x;const h=()=>{var S,v;if(!u)return;const b=++l;a=!1,c.forEach(C=>{var I;return C((I=o())!=null?I:y)});const w=((v=s.onRehydrateStorage)==null?void 0:v.call(s,(S=o())!=null?S:y))||void 0;return Ei(u.getItem.bind(u))(s.name).then(C=>{if(C)if(typeof C.version=="number"&&C.version!==s.version){if(s.migrate){const I=s.migrate(C.state,C.version);return I instanceof Promise?I.then($=>[!0,$]):[!0,I]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,C.state];return[!1,void 0]}).then(C=>{var I;if(b!==l)return;const[$,j]=C;if(x=s.merge(j,(I=o())!=null?I:y),n(x,!0),$)return m()}).then(()=>{b===l&&(w?.(o(),void 0),x=o(),a=!0,d.forEach(C=>C(x)))}).catch(C=>{b===l&&w?.(void 0,C)})};return i.persist={setOptions:S=>{s={...s,...S},S.storage&&(u=S.storage)},clearStorage:()=>{++l,u?.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>h(),hasHydrated:()=>a,onHydrate:S=>(c.add(S),()=>{c.delete(S)}),onFinishHydration:S=>(d.add(S),()=>{d.delete(S)})},s.skipHydration||h(),x||y},ff=pf,hf=e=>({leftPaneWidth:260,rightPaneWidth:340,bottomPanelHeight:220,bottomCollapsed:!1,rightPaneMode:"docked",themeMode:"light",ribbonViewStyle:"modern",activeBottomTab:"commands",commandEditorOpen:!1,commandEditorId:null,ruleEditorOpen:!1,ruleEditorId:null,ruleEditorKind:null,xmlDrawerOpen:!1,bulkPublishOpen:!1,iconPickerOpen:!1,localizationEditorOpen:!1,localizationEditorButtonId:null,newGroupOpen:!1,newButtonGroupId:null,importXmlOpen:!1,importXmlSeed:"",importXmlNote:"",conflictDrawerOpen:!1,conflictElementId:null,webResourceBrowserOpen:!1,urlComposerOpen:!1,diffViewerOpen:!1,diffViewerMode:"compare",tabDisplayRulesOpen:!1,scalingEditorOpen:!1,commandPaletteOpen:!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({commandEditorOpen:!0,commandEditorId:t}),closeCommandEditor:()=>e({commandEditorOpen:!1,commandEditorId:null}),openRuleEditor:(t,n)=>e({ruleEditorOpen:!0,ruleEditorId:t,ruleEditorKind:n}),closeRuleEditor:()=>e({ruleEditorOpen:!1,ruleEditorId:null,ruleEditorKind:null}),openXmlDrawer:()=>e({xmlDrawerOpen:!0}),closeXmlDrawer:()=>e({xmlDrawerOpen:!1}),openBulkPublish:()=>e({bulkPublishOpen:!0}),closeBulkPublish:()=>e({bulkPublishOpen:!1}),openIconPicker:()=>e({iconPickerOpen:!0}),closeIconPicker:()=>e({iconPickerOpen:!1}),openLocalizationEditor:t=>e({localizationEditorOpen:!0,localizationEditorButtonId:t}),closeLocalizationEditor:()=>e({localizationEditorOpen:!1,localizationEditorButtonId:null}),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}),openConflictDrawer:t=>e({conflictDrawerOpen:!0,conflictElementId:t}),closeConflictDrawer:()=>e({conflictDrawerOpen:!1,conflictElementId:null}),openWebResourceBrowser:()=>e({webResourceBrowserOpen:!0}),closeWebResourceBrowser:()=>e({webResourceBrowserOpen:!1}),openUrlComposer:()=>e({urlComposerOpen:!0}),closeUrlComposer:()=>e({urlComposerOpen:!1}),openDiffViewer:t=>e({diffViewerOpen:!0,diffViewerMode:t}),closeDiffViewer:()=>e({diffViewerOpen:!1}),openTabDisplayRules:()=>e({tabDisplayRulesOpen:!0}),closeTabDisplayRules:()=>e({tabDisplayRulesOpen:!1}),openScalingEditor:()=>e({scalingEditorOpen:!0}),closeScalingEditor:()=>e({scalingEditorOpen:!1}),setCommandPaletteOpen:t=>e({commandPaletteOpen:t}),openNewTab:()=>e({newTabOpen:!0}),closeNewTab:()=>e({newTabOpen:!1}),openHideInsteadOfDelete:t=>e({hideInsteadOfDelete:t}),closeHideInsteadOfDelete:()=>e({hideInsteadOfDelete:null}),announce:t=>e({announcement:t})}),ee=Nt()(ff(hf,{name:"cbs:ui",partialize:e=>({leftPaneWidth:e.leftPaneWidth,rightPaneWidth:e.rightPaneWidth,bottomPanelHeight:e.bottomPanelHeight,bottomCollapsed:e.bottomCollapsed,rightPaneMode:e.rightPaneMode,themeMode:e.themeMode,ribbonViewStyle:e.ribbonViewStyle})})),ne=Nt()((e,t)=>({entries:[],append:n=>{const i={id:`${Date.now()}-${t().entries.length+1}`,ts:new Date().toISOString(),...n};e({entries:[...t().entries,i].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:[]})})),gf=Object.freeze(Object.defineProperty({__proto__:null,useRuntimeLogStore:ne},Symbol.toStringTag,{value:"Module"})),bf=new Set(["Default","InvertResult","PropertyValue","ExpectedValue","TrackedInCrm","PassParams","AllowCustomRelationship","AllowSystemRelationship"]),nr=["EnableRules","DisplayRules","Actions"];function yf(e,t){return bf.has(t)||e.tagName==="BoolParameter"&&t==="Value"}function xf(e){const t=e.trim();return t==="1"?"true":t==="0"?"false":t}function Sf(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;")}function no(e,t,n){const o=Array.from(e.attributes).map(a=>[a.name,yf(e,a.name)?xf(a.value):a.value]).sort(([a],[l])=>a<l?-1:a>l?1:0).map(([a,l])=>` ${a}="${Sf(l)}"`).join(""),i=[];let s=[];for(const a of Array.from(e.childNodes))if(a.nodeType===1)s.push(a);else if(a.nodeType===3||a.nodeType===4){const l=(a.textContent??"").trim();l&&i.push(`${n} #text ${l}`)}if(t.normalizeCommands&&e.tagName==="CommandDefinition"){const a=new Map(s.map(d=>[d.tagName,d])),l=s.filter(d=>!nr.includes(d.tagName)),c=nr.map(d=>{const u=a.get(d);return u?no(u,t,`${n} `):`${n} <${d}/>`});s=[],i.push(...c,...l.map(d=>no(d,t,`${n} `)))}for(const a of s)i.push(no(a,t,`${n} `));return i.length===0?`${n}<${e.tagName}${o}/>`:`${n}<${e.tagName}${o}>
3
+ ${i.join(`
4
+ `)}
5
+ ${n}</${e.tagName}>`}function qa(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 en(e,t={}){const n=typeof e=="string"?qa(e):e;return no(n,t,"")}function vf(e,t,n={}){try{return en(e,n)===en(t,n)}catch{return!1}}const Vt={button:"Button",flyout:"FlyoutAnchor",splitButton:"SplitButton",textBox:"TextBox",comboBox:"ComboBox",checkBox:"CheckBox",toggleButton:"ToggleButton",label:"Label",dropDown:"DropDown",mruSplitButton:"MRUSplitButton",spinner:"Spinner",galleryButton:"GalleryButton"},Wa=Object.fromEntries(Object.entries(Vt).map(([e,t])=>[t,e])),wf=new Set(["toggleButton","label","dropDown","mruSplitButton","spinner","galleryButton"]);function rt(e){return!!e&&wf.has(e)}const Ha=["Command","QueryCommand","MenuCommand","PopulateQueryCommand","CommandMenuOpen","CommandMenuClose","CommandPreview","CommandPreviewRevert","CommandRevert"],Ga=new RegExp(`\\s(?:${Ha.join("|")})="([^"]+)"`,"g");function Ua(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),rt(e.kind))for(const o of e.source?.xml?.matchAll(Ga)??[])t.add(o[1]);return[...t]}function Cf(e,t,n){const o=i=>i.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;");return e.replace(Ga,(i,s)=>s===t||s===o(t)?i.replace(`"${s}"`,`"${o(n)}"`):i)}const fo={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 Xa(e,t){const n=t.length>0?Math.min(...t):1/0,o=e.filter(i=>i<n);return{after:o.length>0?Math.max(...o):0,before:n}}function Va(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 Ka(e,t,n){const o=[],i=[],s=new Set([...t.maxSizes,...t.scales]),a=(f,y)=>{o.push({tabId:e,id:f.id,kind:f.kind,groupId:f.groupId,from:f.sequence,to:y}),s.add(y)},l=n.filter(f=>f.kind==="Scale"),c=[];for(const f of l)s.has(f.sequence)?c.push(f):s.add(f.sequence);for(const f of c)a(f,Math.max(0,...s)+1);const d=[...t.scales,...l.map(f=>o.find(y=>y.id===f.id&&y.kind==="Scale")?.to??f.sequence)],u=Xa(t.maxSizes,d),m=[];for(const f of n.filter(y=>y.kind==="MaxSize"))f.sequence<u.before&&!s.has(f.sequence)?s.add(f.sequence):m.push(f);for(const f of m){const y=Va(u,s);y===void 0?i.push(`The scaling of tab ${e} has no free position for MaxSize ${f.id} (Sequence ${f.sequence}): it must come before the first Scale (${u.before}) and use a Sequence no other step uses`):a(f,y)}return{changes:o,problems:i}}function If(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 un(){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 Ja(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 gt(e,t){return e?Array.from(e.children).filter(n=>n.tagName===t):[]}function pe(e,t){return gt(e,t)[0]}function Ya(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 ov(e){const t=un(),o=Ja(e).documentElement;if(o.tagName!=="RibbonDiffXml")throw new Error(`Expected <RibbonDiffXml> root, got <${o.tagName}>`);const i=tn();for(const l of Array.from(pe(o,"CustomActions")?.children??[])){const c=Ya(l);c&&t.customActions.set(c,i.serializeToString(l))}const s=pe(pe(o,"Templates"),"RibbonTemplates");for(const l of Array.from(s?.children??[])){const c=l.getAttribute("Id");c&&t.templates.set(c,i.serializeToString(l))}for(const l of gt(pe(o,"CommandDefinitions"),"CommandDefinition")){const c=l.getAttribute("Id");c&&t.commandDefinitions.set(c,i.serializeToString(l))}const a=pe(o,"RuleDefinitions");for(const l of gt(pe(a,"TabDisplayRules"),"TabDisplayRule")){const c=l.getAttribute("TabCommand");c&&t.tabDisplayRules.set(c,i.serializeToString(l))}for(const l of gt(pe(a,"DisplayRules"),"DisplayRule")){const c=l.getAttribute("Id");c&&t.displayRules.set(c,i.serializeToString(l))}for(const l of gt(pe(a,"EnableRules"),"EnableRule")){const c=l.getAttribute("Id");c&&t.enableRules.set(c,i.serializeToString(l))}for(const l of gt(pe(o,"LocLabels"),"LocLabel")){const c=l.getAttribute("Id");c&&t.locLabels.set(c,i.serializeToString(l))}return t}function fe(e){return Ja(e).documentElement}function Rf(e){const t=un();for(const n of e.diffs){const o=n.rdx?.trim();if(!o)continue;const i=fe(o);switch(n.difftype){case 3:{const s=i.getAttribute("Id")??n.diffid;s&&t.locLabels.set(s,o);break}case 2:{const s=i.getAttribute("Id")??n.diffid;s&&t.templates.set(s,o);break}default:{const s=Ya(i);s&&t.customActions.set(s,o)}}}for(const n of e.commands){const o=n.commanddefinition?.trim(),i=n.command??(o?fe(o).getAttribute("Id"):null);o&&i&&t.commandDefinitions.set(i,o)}for(const n of e.rules){const o=n.ruledefinition?.trim();if(!o)continue;const i=fe(o);if(n.ruletype===3||i.tagName==="TabDisplayRule"){const s=i.getAttribute("TabCommand")??n.ruleid;s&&t.tabDisplayRules.set(s,o)}else if(n.ruletype===1||i.tagName==="EnableRule"){const s=i.getAttribute("Id")??n.ruleid;s&&t.enableRules.set(s,o)}else{const s=i.getAttribute("Id")??n.ruleid;s&&t.displayRules.set(s,o)}}return t}function ps(e,t){const n=un();for(const o of Object.keys(n)){for(const[i,s]of e[o])n[o].set(i,s);for(const[i,s]of t[o])n[o].set(i,s)}return n}function iv(e){const t=(n,o)=>Array.from(n.values()).map(i=>`${o}${i}`).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 jf(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 or(e,t){const n=fe(t);if(e==="commandDefinitions")for(const o of Array.from(n.getElementsByTagName("JavaScriptFunction")))jf(o)&&o.parentNode?.replaceChild(n.ownerDocument.createElement("PlatformJavaScriptFunction"),o);if(e==="locLabels")for(const o of Array.from(n.getElementsByTagName("Titles"))){const i=Array.from(o.children).sort((s,a)=>Number(s.getAttribute("languagecode"))-Number(a.getAttribute("languagecode")));for(const s of i)o.appendChild(s)}return en(n,{normalizeCommands:e==="commandDefinitions"})}const Za=(e,t,n)=>{try{return or(e,t)===or(e,n)}catch{return t===n}},ir=e=>Array.from(fe(e).getElementsByTagName("Title")).map(t=>`${t.getAttribute("languagecode")}=${t.getAttribute("description")??""}`);function $f(e,t,n){if(e!=="locLabels")return Za(e,t,n);try{const o=new Set(ir(t)),i=ir(n);return i.length>0&&i.every(s=>o.has(s))}catch{return t===n}}function sv(e,t){const n=[];for(const o of Object.keys(t))for(const[i,s]of t[o]){const a=e[o].get(i);(a===void 0||!Za(o,a,s))&&n.push(`${o}:${i}`)}return n}function rv(e,t,n={}){const o=[],i=[],s=[],a=new Set(n.contentKeys??[]);for(const l of Object.keys(e)){for(const[c,d]of e[l]){const u=t[l].get(c);u===void 0?o.push(`${l}:${c}`):a.has(`${l}:${c}`)&&!$f(l,d,u)&&s.push(`${l}:${c}`)}for(const c of t[l].keys())e[l].has(c)||i.push(`${l}:${c}`)}return{missing:o,unexpected:i,differing:s}}function av(e){return Object.values(e).reduce((t,n)=>t+n.size,0)}function Ko(e){const t=fe(e);return t.tagName!=="CustomAction"?null:pe(t,"CommandUIDefinition")?.firstElementChild??null}function it(e){return!!e&&e.endsWith("._children")}const Nf=new Set(["Menu","MenuSection","Controls"]);function Oi(e){return e.tagName==="Tab"||e.tagName==="Group"?[]:Array.from(e.getElementsByTagName("*")).filter(t=>!Nf.has(t.tagName)&&!!t.getAttribute("Id")&&t.parentElement?.tagName==="Controls")}const Dn=e=>e?.tagName==="Tab"||e?.tagName==="Group",sr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;");function Qa(e){return Array.from(e.getElementsByTagName("Controls")).flatMap(t=>Array.from(t.children))}function el(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 ho(e){return Dn(e)?Qa(e):Oi(e)}function go(e){const t=new Set;for(const n of e.customActions.values()){const o=fe(n);if(o.tagName!=="CustomAction"||!it(o.getAttribute("Location")))continue;const i=pe(o,"CommandUIDefinition")?.firstElementChild,s=i?.getAttribute("Id");if(s&&t.add(s),i)for(const a of ho(i)){const l=a.getAttribute("Id");l&&t.add(l)}}return t}function tl(e,t){const n=new Map(e),o=tn(),i=t?new Set(t):void 0;for(let s=!0;s;){s=!1;const a=new Map;for(const[l,c]of n){const d=fe(c);if(d.tagName!=="CustomAction"||!it(d.getAttribute("Location")))continue;const u=pe(d,"CommandUIDefinition")?.firstElementChild;if(Dn(u))for(const m of[u,...Array.from(u.getElementsByTagName("Group"))]){const f=m.getAttribute("Id");f&&!a.has(f)&&a.set(f,l)}}for(const[l,c]of n){const d=fe(c);if(d.tagName!=="CustomAction")continue;const u=/^(.+)\.(Controls|Groups|Scaling)\._children$/.exec(d.getAttribute("Location")??""),m=pe(d,"CommandUIDefinition")?.firstElementChild,f=u?a.get(u[1]):void 0;if(!u||!m||!f||f===l||i&&!i.has(l)&&!i.has(f))continue;const[,y,x]=u,h=fe(n.get(f)),S=el(h,y);if(!S||S.tagName!==(x==="Controls"?"Group":"Tab"))continue;const v=h.ownerDocument;let b=pe(S,x);if(!b){b=v.createElement(x),b.setAttribute("Id",`${y}.${x}`);const $=x==="Scaling"?pe(S,"Groups"):void 0;S.insertBefore(b,$??null)}const w=v.importNode(m,!0),C=d.getAttribute("Sequence");!w.getAttribute("Sequence")&&C&&w.setAttribute("Sequence",C);const I=w.tagName==="MaxSize"?pe(b,"Scale"):void 0;b.insertBefore(w,I??null),n.set(f,o.serializeToString(h)),i?.add(f),n.delete(l),s=!0;break}}return n}function Tf(e,t){const n=pe(e,"CommandUIDefinition")?.firstElementChild??null;return n?n.getAttribute("Id")===t?n:ho(n).find(o=>o.getAttribute("Id")===t)??null:null}function nl(e){const t=new Set;for(const n of e.customActions.values()){const o=fe(n);if(o.tagName!=="CustomAction"||!it(o.getAttribute("Location")))continue;const i=pe(o,"CommandUIDefinition")?.firstElementChild;if(!i||i.tagName!=="Tab"&&i.tagName!=="Group")continue;const s=i.getAttribute("Id");s&&t.add(s);for(const a of Array.from(i.getElementsByTagName("Group"))){const l=a.getAttribute("Id");l&&t.add(l)}}return t}function Eo(e){const t=[];for(const n of e.customActions.values()){const o=fe(n);if(o.tagName!=="HideCustomAction")continue;const i=o.getAttribute("Location");i&&t.push({hideActionId:o.getAttribute("HideActionId")??"",location:i})}return t}function kf(e){const t=[],n=e.getAttribute("Id");n&&t.push(n);for(const o of Array.from(e.getElementsByTagName("*"))){const i=o.getAttribute("Id");i&&t.push(i)}return t}function In(e){const t=[];for(const n of[e,...Array.from(e.getElementsByTagName("*"))])for(const o of Ha){const i=n.getAttribute(o);i&&t.push(i)}return t}function ol(e){const t=new Set;for(const n of e.customActions.values()){const o=fe(n);if(o.tagName==="CustomAction")for(const i of In(o))t.add(i)}return t}function Af(e){return/^(Mscrm|Microsoft)\./.test(e)}function fs(e,t){if(Af(e))return!0;for(const n of t)if(n===e)return!1;return!0}function Df(e){const t=e?.match(/^(.+)\.(?:Controls|Groups)\._children$/);return t?t[1]:null}function oo(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 rr(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 Ef(e,t,n){const o=gt(e,"Menu")[0],i=gt(t,"Menu")[0];if(!o){for(const l of Oi(t))n(l.getAttribute("Id")??"")&&l.parentNode?.removeChild(l);return oo(t,e)}const s=o.cloneNode(!0),a=(l,c)=>[s,...Array.from(s.getElementsByTagName("*"))].find(d=>d.getAttribute("Id")===c&&(l?d.tagName===l:d.parentElement?.tagName==="Controls"));if(i){for(const l of Array.from(i.getElementsByTagName("MenuSection"))){const c=a("MenuSection",l.getAttribute("Id")??"");if(c){rr(l,c);continue}const d=a("Menu",l.parentElement?.getAttribute("Id")??"");if(!d)continue;const u=l.cloneNode(!0);for(const m of Array.from(u.getElementsByTagName("*")))m.parentElement?.tagName==="Controls"&&n(m.getAttribute("Id")??"")&&m.parentNode?.removeChild(m);d.appendChild(u)}for(const l of Oi(t)){const c=l.getAttribute("Id")??"";if(n(c))continue;const d=a(null,c);if(d){rr(l,d);continue}const u=a("Controls",l.parentElement?.getAttribute("Id")??"");u&&u.appendChild(l.cloneNode(!0))}}for(const l of gt(t,"Menu"))t.removeChild(l);return t.appendChild(s),t}const Jo=/\$LocLabels:([^"'\s]+)/g;function ar(e){const t=new Set;for(const n of e)for(const o of In(fe(n)))t.add(o);return t}function Of(e){const t=new Set;for(const n of e){const o=fe(n);for(const i of[o,...Array.from(o.getElementsByTagName("*"))])for(const s of Array.from(i.attributes))s.value.startsWith("$LocLabels:")&&t.add(s.value.slice(11))}return t}function Xn(e){const t={EnableRule:new Set,DisplayRule:new Set};for(const n of e){const o=fe(n);for(const i of["EnableRule","DisplayRule"])for(const s of Array.from(o.getElementsByTagName(i))){const a=s.getAttribute("Id");a&&t[i].add(a)}}return t}function lv(e,t,n={}){const o=new Set(n.editedCommandIds??[]),i=new Set(n.editedEnableRuleIds??[]),s=new Set(n.editedDisplayRuleIds??[]),a=new Set(n.deletedControlIds??[]),l=new Set(n.unhiddenControlIds??[]),c=new Set(n.retainedCommandIds??[]),d=tn(),u=ps(e,un()),m=new Map,f=new Map,y=[];for(const[D,N]of e.customActions){const M=Ko(N),k=fe(N);if(k.tagName!=="CustomAction")continue;const B=k.getAttribute("Location");if(M?.getAttribute("Id")&&it(B)){m.set(M.getAttribute("Id"),D);for(const G of ho(M)){const X=G.getAttribute("Id");X&&y.push([X,D])}}else B&&f.set(B,D)}for(const[D,N]of y)m.has(D)||m.set(D,N);const x=(D,N)=>{const M=u.customActions.get(D);if(!M)return{ca:null,el:null,nested:!1};const k=fe(M),B=Tf(k,N);return{ca:k,el:B,nested:!!B&&B.parentElement?.tagName!=="CommandUIDefinition"}},h=new Set;for(const[D,N]of t.customActions){const M=fe(N),k=Ko(N),B=k?.getAttribute("Id")??null,G=B?m.get(B):void 0,X=M.tagName==="CustomAction"&&it(M.getAttribute("Location"));X&&B&&h.add(B);const Q=k?.tagName==="Tab"||k?.tagName==="Group";if(X&&Q)for(const U of Qa(k)){const g=U.getAttribute("Id");if(!g)continue;h.add(g);const O=m.get(g),V=O?x(O,g):null;!O||!V?.ca||!V.el||(V.nested?(V.el.parentNode.removeChild(V.el),u.customActions.set(O,d.serializeToString(V.ca))):u.customActions.delete(O))}const ie=M.tagName==="CustomAction"&&k&&B&&G&&!(X&&Q),F=ie?x(G,B):null;if(ie&&F?.ca&&F.el&&F.nested){const{ca:U,el:g}=F;if(X)g.parentNode.removeChild(g),u.customActions.set(D,N);else{const O=oo(U.ownerDocument.importNode(k,!0),g);g.parentNode.replaceChild(O,g)}u.customActions.set(G,d.serializeToString(U));continue}if(ie&&F?.ca&&F.el){const{ca:U,el:g,nested:O}=F;if(X&&O){g.parentNode.removeChild(g),u.customActions.set(G,d.serializeToString(U)),u.customActions.set(D,N);continue}let V=U.ownerDocument.importNode(k,!0);if(X?V=Ef(g,V,de=>{const Se=m.get(de);return!!Se&&Se!==G}):V=oo(V,g),g.parentNode.replaceChild(V,g),!O){X&&U.setAttribute("Location",M.getAttribute("Location"));const de=k.getAttribute("Sequence")??(X?M.getAttribute("Sequence"):null);de&&U.setAttribute("Sequence",de)}u.customActions.set(G,d.serializeToString(U));continue}const _=M.getAttribute("Location"),L=M.tagName==="CustomAction"&&_?f.get(_):void 0;if(L&&k){const U=Ko(e.customActions.get(L)),g=fe(N),O=pe(g,"CommandUIDefinition");O?.firstElementChild&&oo(O.firstElementChild,U),u.customActions.delete(L),u.customActions.set(D,d.serializeToString(g));continue}u.customActions.set(D,N)}for(const{id:D,sequence:N}of n.resequencedContainers??[])for(const[M,k]of u.customActions){const B=fe(k),G=pe(B,"CommandUIDefinition")?.firstElementChild;B.tagName!=="CustomAction"||G?.getAttribute("Id")!==D||(B.setAttribute("Sequence",String(N)),G.setAttribute("Sequence",String(N)),u.customActions.set(M,tn().serializeToString(B)))}for(const D of n.movedControls??[]){const N=m.get(D.id),M=N?x(N,D.id):null;if(!N||!M?.ca||!M.el){if(h.has(D.id))continue;throw new Error(`Can't move ${D.id}: it isn't in this table's unmanaged customizations.`)}const{ca:k,el:B}=M,G=D.controlsId??`${D.groupId}.Controls`;if(B.setAttribute("Sequence",String(D.sequence)),!M.nested)k.setAttribute("Location",`${G}._children`),k.setAttribute("Sequence",String(D.sequence));else if(B.parentElement?.getAttribute("Id")!==G){const X=Array.from(k.getElementsByTagName("Controls")).find(Q=>Q.getAttribute("Id")===G);if(B.parentNode.removeChild(B),X)X.appendChild(B);else{let Q=`${D.id}.CustomAction`;for(;u.customActions.has(`ca:${Q}`);)Q+="_";u.customActions.set(`ca:${Q}`,`<CustomAction Id="${sr(Q)}" Location="${sr(`${G}._children`)}" Sequence="${D.sequence}"><CommandUIDefinition>${d.serializeToString(B)}</CommandUIDefinition></CustomAction>`)}}u.customActions.set(N,d.serializeToString(k))}const S=new Set,v=new Set;for(const[D,N]of Array.from(u.customActions)){const M=fe(N);if(M.tagName==="HideCustomAction"){l.has(M.getAttribute("Location")??"")&&u.customActions.delete(D);continue}const k=pe(M,"CommandUIDefinition")?.firstElementChild??null,B=k?.getAttribute("Id");if(!k||!it(M.getAttribute("Location")))continue;if(B&&a.has(B)&&!h.has(B)){u.customActions.delete(D);for(const X of N.matchAll(Jo))v.add(X[1]);for(const X of In(k))S.add(X);continue}const G=ho(k).filter(X=>{const Q=X.getAttribute("Id")??"";return a.has(Q)&&!h.has(Q)});if(G.length!==0){for(const X of G){const Q=d.serializeToString(X);for(const ie of Q.matchAll(Jo))v.add(ie[1]);for(const ie of In(X))S.add(ie);X.parentNode?.removeChild(X)}u.customActions.set(D,d.serializeToString(M))}}const b=new Set,w=new Set(n.deletedContainerIds??[]),C=(D,N)=>{for(const M of kf(D))w.add(M);for(const M of In(D))S.add(M);for(const M of[D,...Array.from(D.getElementsByTagName("Tab"))]){const k=M.tagName==="Tab"?M.getAttribute("Command"):null;k&&b.add(k)}for(const M of N.matchAll(Jo))v.add(M[1])};for(let D=w.size>0;D;){D=!1;for(const[N,M]of Array.from(u.customActions)){const k=fe(M),B=k.getAttribute("Location");if(k.tagName==="HideCustomAction"){B&&w.has(B)&&(u.customActions.delete(N),D=!0);continue}const G=pe(k,"CommandUIDefinition")?.firstElementChild??null,X=G?.getAttribute("Id")??null,Q=Df(B);if(!!X&&w.has(X)&&it(B)||!!Q&&w.has(Q)||!it(B)&&!!B&&w.has(B)||!!G?.getAttribute("GroupId")&&w.has(G.getAttribute("GroupId"))){u.customActions.delete(N),G&&C(G,M),D=!0;continue}if(G?.tagName!=="Tab")continue;const F=Array.from(G.getElementsByTagName("*")).filter(_=>_.tagName==="Group"?w.has(_.getAttribute("Id")??""):(_.tagName==="MaxSize"||_.tagName==="Scale")&&w.has(_.getAttribute("GroupId")??""));if(F.length!==0){for(const _ of F)C(_,d.serializeToString(_)),_.parentNode?.removeChild(_);u.customActions.set(N,d.serializeToString(k)),D=!0}}}const I=new Set;for(const[D,N]of u.customActions)e.customActions.get(D)!==N&&I.add(D);u.customActions=tl(u.customActions,I);const $=(D,N)=>{for(const[M,k]of t[D])e[D].has(M)&&!N.has(M)||u[D].set(M,k)};$("commandDefinitions",o),$("enableRules",i),$("displayRules",s);const j=ar(u.customActions.values());for(const D of S){if(c.has(D)||!u.commandDefinitions.has(D)||j.has(D))continue;const N=u.commandDefinitions.get(D);u.commandDefinitions.delete(D);const M=Xn([N]),k=Xn(u.commandDefinitions.values());for(const B of M.EnableRule)k.EnableRule.has(B)||u.enableRules.delete(B);for(const B of M.DisplayRule)k.DisplayRule.has(B)||u.displayRules.delete(B)}const R={EnableRule:new Set(n.retainedEnableRuleIds??[]),DisplayRule:new Set(n.retainedDisplayRuleIds??[])},T=ol(u);for(const D of n.uncustomisedCommandIds??[]){const N=u.commandDefinitions.get(D);if(N===void 0||t.commandDefinitions.has(D)||!fs(D,T))continue;u.commandDefinitions.delete(D);const M=Xn(u.commandDefinitions.values()),k=Xn([N]);for(const B of["EnableRule","DisplayRule"])for(const G of k[B]){const X=B==="EnableRule"?u.enableRules:u.displayRules;(B==="EnableRule"?t.enableRules:t.displayRules).has(G)||R[B].has(G)||M[B].has(G)||X.delete(G)}}for(const[D,N]of t.tabDisplayRules)u.tabDisplayRules.set(D,N);for(const[D,N]of t.templates)u.templates.set(D,N);const A=Of(u.customActions.values());for(const D of v)!t.locLabels.has(D)&&!A.has(D)&&u.locLabels.delete(D);const W=ar(u.customActions.values());for(const D of b)!t.tabDisplayRules.has(D)&&!W.has(D)&&u.tabDisplayRules.delete(D);for(const D of n.removedTabCommands??[])t.tabDisplayRules.has(D)||u.tabDisplayRules.delete(D);for(const[D,N]of t.locLabels){if(e.locLabels.get(D)){const k=Array.from(fe(N).querySelectorAll("Title")).map(B=>B.getAttribute("description"));if(k.length>0&&k.every(B=>B===D))continue}u.locLabels.set(D,N)}return u}function cv(e,t,n){const o=ps(e,un());for(const[i,s]of o.customActions){const a=fe(s);if(a.tagName!=="CustomAction"||!it(a.getAttribute("Location")))continue;const l=pe(a,"CommandUIDefinition")?.firstElementChild;if(!Dn(l))continue;const c=el(l,t);if(!(!c||!Dn(c))){c.setAttribute("Title",n),o.customActions.set(i,tn().serializeToString(a));break}}return o}function hs(e){const t=[],n=(o,i,s)=>({id:o.getAttribute("Id")??"",kind:o.tagName,groupId:o.getAttribute("GroupId")??"",sequence:Number(o.getAttribute("Sequence")??"0"),size:o.getAttribute("Size")??"",tabId:i,key:s});for(const[o,i]of e.customActions){const s=fe(i);if(s.tagName!=="CustomAction")continue;const a=pe(s,"CommandUIDefinition")?.firstElementChild;if(!a)continue;const l=/^(.+)\.Scaling\._children$/.exec(s.getAttribute("Location")??"");if(l&&(a.tagName==="MaxSize"||a.tagName==="Scale")&&t.push(n(a,l[1],o)),a.tagName==="Tab"&&it(s.getAttribute("Location"))){const c=a.getAttribute("Id")??"";for(const d of Array.from(pe(a,"Scaling")?.children??[]))(d.tagName==="MaxSize"||d.tagName==="Scale")&&t.push(n(d,c,o))}}return t}function dv(e,t){const n=hs(e),o=new Map;for(const c of n)o.set(c.tabId,[...o.get(c.tabId)??[],c]);const i=[],s=[];for(const[c,d]of o){const u=Ka(c,t[c]??{maxSizes:[],scales:[]},d);i.push(...u.changes),s.push(...u.problems)}if(i.length===0)return{parts:e,changes:i,problems:s};const a=ps(e,un()),l=tn();for(const c of i){const d=n.find(y=>y.id===c.id&&y.kind===c.kind&&y.tabId===c.tabId),u=fe(a.customActions.get(d.key)),m=pe(u,"CommandUIDefinition").firstElementChild;(m.tagName==="Tab"?Array.from(pe(m,"Scaling")?.children??[]).find(y=>y.tagName===c.kind&&y.getAttribute("Id")===c.id):m)?.setAttribute("Sequence",String(c.to)),m.tagName!=="Tab"&&u.setAttribute("Sequence",String(c.to)),a.customActions.set(d.key,l.serializeToString(u))}return{parts:a,changes:i,problems:s}}function Mf(e,t){const n=new Map;for(const i of t.customActions.values()){const s=fe(i);if(s.tagName!=="CustomAction"||!it(s.getAttribute("Location")))continue;const a=pe(s,"CommandUIDefinition")?.firstElementChild;if(Dn(a))for(const l of[a,...Array.from(a.getElementsByTagName("Group"))]){const c=l.getAttribute("Id"),d=l.getAttribute("Title");c&&d?.startsWith("$LocLabels:")&&n.set(c,d)}}for(const i of e.tabs){const s=n.get(i.id);s&&(i.label=s);for(const a of i.groups){const l=n.get(a.id);l&&(a.label=l)}}const o=new Set(e.tabs.map(i=>i.id));for(const i of hs(t)){if(!o.has(i.tabId))continue;e.scalingByTab=e.scalingByTab??{};const s=e.scalingByTab[i.tabId]=e.scalingByTab[i.tabId]??{tabId:i.tabId,maxSizes:[],scales:[]},a=i.kind==="MaxSize"?s.maxSizes:s.scales,l={id:i.id,groupId:i.groupId,size:i.size,sequence:i.sequence},c=a.findIndex(d=>d.id===i.id);c>=0?a[c]=l:a.push(l)}}function Be(e,t,n=1033){if(!e)return"";const o=e.match(/^\$LocLabels:(.+)$/);if(o){const s=o[1],a=t.find(l=>l.id===s);if(a){const l=a.titles.find(u=>u.languageCode===n),c=a.titles.find(u=>u.languageCode===1033),d=a.titles[0];return l?.description??c?.description??d?.description??s}return s}const i=e.match(/^\$Resources(?:\([^)]*\))?:(.+)$/);return i?i[1]:e}function Rn(e){return!!e&&/^\$Resources(\([^)]*\))?:/.test(e)}function il(e){return`$LocLabels:${e}`}function sl(e){const t=e.match(/^\$LocLabels:(.+)$/);return t?t[1]:null}const lr=128;function Oo(e,t){const n=`${e}.${t}`;if(n.length<=lr)return n;const o=Bf(e),i=lr-t.length-o.length-2;return`${e.slice(0,i)}_${o}.${t}`}function Bf(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 Mo(e){return Oo(e,"LabelText")}function Bo(e){return Oo(e,"ToolTipTitle")}function zo(e){return Oo(e,"ToolTipDescription")}function zf(e){return Oo(e,"Title")}function Lf(e,t){const n=(o,i)=>(o?sl(o):null)??i;return{label:n(t?.labelToken,Mo(e)),tooltipTitle:n(t?.tooltipTitleToken,Bo(e)),tooltipBody:n(t?.tooltipBodyToken,zo(e))}}function uv(e,t,n,o,i=1033){const s=e?sl(e):null;return s?o.some(a=>a.id===s)?s:(n??"")===Be(e,[...o],i)?null:t:t}function Pf(e,t,n=1033){const o=new Set(Object.values(Lf(e.id,e.source))),i=new Set;for(const s of t)o.has(s.id)&&s.titles.forEach(a=>i.add(a.languageCode));return[...i].sort((s,a)=>s===n?-1:a===n?1:s-a)}function Ff(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 Kt=e=>e==="flyout"||e==="splitButton",gs=["button","flyout"],rl=e=>["true","1"].includes(e?.trim().toLowerCase()??"");function zt(e){const t=[];for(const n of e.menu?.sections??[])for(const o of n.controls)t.push(o),t.push(...zt(o));return t}function al(e){return e.flatMap(t=>[t,...zt(t)])}function Ne(e){return al(e.buttons)}function Lo(e,t){for(const n of e)for(const o of n.menu?.sections??[]){const i=o.controls.findIndex(a=>a.id===t);if(i>=0)return{parent:n,section:o,index:i};const s=Lo(o.controls,t);if(s)return s}}function bo(e,t){if(!e.buttons.some(n=>n.id===t))return Lo(e.buttons,t)}function mn(e,t){if(!e||!t)return;const n=e.buttons.find(i=>i.id===t);if(n)return n;const o=Lo(e.buttons,t);return o?.section.controls[o.index]}function _f(e,t){if(!(!e||!t))return e.buttons.find(n=>n.id===t||zt(n).some(o=>o.id===t))}function ll(e,t){const n=Lo(e.buttons,t);return n?(n.section.controls.splice(n.index,1),!0):!1}function Yo(e){return{id:`${e}.Menu`,sections:[Mi(e,[])]}}function Mi(e,t,n){let o=t.length+1;const i=new Set(t.map(a=>a.id));for(;i.has(`${e}.MenuSection${o}`);)o++;const s=`${e}.MenuSection${o}`;return{id:s,title:n,sequence:o*10,displayMode:"Menu16",controlsId:`${s}.Controls`,controls:[]}}function qf(e,t,n,o){if(!e)return;const i=new Set,s=new Map,a=c=>{const d=s.get(c);if(d)return d;let u=c.startsWith(t)?`${n}${c.slice(t.length)}`:`${n}.${c.split(".").pop()||"Item"}`;for(let m=2;i.has(u);m++)u=`${u.replace(/_\d+$/,"")}_${m}`;return i.add(u),s.set(c,u),u},l=c=>c.replace(/(\sId=")([^"]*)(")/g,(d,u,m,f)=>`${u}${a(m)}${f}`);return{...e,id:a(e.id),sections:e.sections.map(c=>({...c,id:a(c.id),controlsId:a(c.controlsId),controls:c.controls.map(d=>yo(d,a(d.id),o)),...c.rawControls?{rawControls:c.rawControls.map(d=>({...d,xml:l(d.xml)}))}:{},...c.rawContent!==void 0?{rawContent:l(c.rawContent)}:{}}))}}function Wf(e,t,n){return e.replace(/(\s(?:Id|InitialItem)=")([^"]*)(")/g,(o,i,s,a)=>`${i}${s.startsWith(t)?`${n}${s.slice(t.length)}`:`${n}.${s}`}${a}`)}const Hf=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand"];function jn(e,t){return!!t&&!!e?.startsWith("$LocLabels:")&&!t.has(e.slice(11))}function yo(e,t,n){const o=Hf.filter(u=>e.source?.attributes[u]!==void 0),i=Ff(e.source),s={...i?.attributes??{},...Object.fromEntries(o.map(u=>[u,e.source.attributes[u]]))},a=u=>Rn(u)||jn(u,n)?u:void 0,l={labelToken:a(e.source?.labelToken),tooltipTitleToken:a(e.source?.tooltipTitleToken),tooltipBodyToken:a(e.source?.tooltipBodyToken)},c=Object.fromEntries(Object.entries(l).filter(([,u])=>u!==void 0)),d=e.source?.xml?Wf(e.source.xml,e.id,t):void 0;return{...e,id:t,source:Object.keys(s).length+Object.keys(c).length>0||d?{...i?.modernImage?{modernImage:i.modernImage}:{},...c,attributes:s,...d?{xml:d}:{}}:void 0,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0,menu:qf(e.menu,e.id,t,n)}}const Gf=["label","icon","image16","image32","tooltipTitle","tooltipBody","commandId","templateAlias"];function Bi(e,t){for(const n of Gf)if((e[n]??"")!==(t[n]??""))return!0;return!1}function Mt(e){const t=new Map,n=new Map,o=(i,s,a,l)=>{const c=n.get(i.id)??0;n.set(i.id,c+1);const d=`${i.id}#${c}`;t.set(d,l?{button:i,groupId:s,tabId:a,menu:l}:{button:i,groupId:s,tabId:a});for(const u of i.menu?.sections??[])for(const m of u.controls)o(m,s,a,{parentKey:d,parentId:i.id,sectionId:u.id,controlsId:u.controlsId})};for(const i of e.tabs)for(const s of i.groups)for(const a of s.buttons)o(a,s.id,i.id);return t}function cl(e,t){const n=Mt(t),o=Mt(e),i=a=>{for(let l=a.menu?.parentKey;l;l=o.get(l)?.menu?.parentKey)if(!n.has(l))return!0;return!1},s=[];for(const[a,l]of o){const c=n.get(a)?.button,d=l.button;if(i(l)){d.hidden&&s.push({entry:l,change:"hide"});continue}c?d.hidden&&!c.hidden?s.push({entry:l,change:"hide"}):Bi(c,d)&&s.push({entry:l,change:"override"}):(d.hidden&&(d.oob||d.managed)||s.push({entry:l,change:"new"}),d.hidden&&s.push({entry:l,change:"hide"}))}return s}function dl(e){return e.commandId||`${e.id}.Command`}function Uf(e,t){return e==="SubGrid"?`Mscrm.SubGrid.${t}.ContextualTabs._children`:"Mscrm.Tabs._children"}function ul(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 Xf(e,t,n){const o=dl(e),i=(e.tabDisplayRules??[]).map(s=>({...s,tabCommand:s.tabCommand||o}));return{...e,commandId:o,tabDisplayRules:i.length>0?i:ul(t,n,o)}}function mv(e){const{current:t,baseline:n,commands:o,enableRules:i,displayRules:s,locLabels:a}=e,l=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 U of L.groups)u.add(U.id)}const m=Mt(n),f=new Map;for(const[L,U]of Mt(t))f.set(U.button,m.get(L)?.button);const y=t.tabs.filter(L=>!d.has(L.id)).map(L=>Xf(L,e.location,e.entityLogicalName)),x=[],h=[],S=[],v=[],b=[],w=L=>b.push(L),C=[],I=L=>{const U=[];for(const g of L.buttons)g.hidden||f.get(g)||(U.push(Po(g,a,w,l,!0)),C.push(g,...zt(g)));return U},$=new Set,j=pl(t,n).steps;for(const L of y){const U=new Map(L.groups.map(g=>[g.id,I(g)]));for(const g of L.groups)for(const O of g.buttons)!O.hidden&&!f.get(O)&&$.add(O);x.push(nh(L,t.scalingByTab?.[L.id],Uf(e.location,e.entityLogicalName),U,j,w,l,a))}const R=[];for(const L of t.tabs)if(d.has(L.id)){for(const U of L.groups)if(!u.has(U.id)){for(const O of U.buttons)!O.hidden&&!f.get(O)&&$.add(O);h.push(th(U,L.id,I(U),w,l,a));const g=j.get(U.id);g&&R.push(Li(L.id,"MaxSize",g))}}h.push(...R);for(const{entry:L,change:U}of cl(t,n)){const{button:g,groupId:O,menu:V}=L;if(!$.has(g))if(U==="hide")v.push(eh(g));else if(U==="new"){const de=V?`${V.controlsId}._children`:`${O}.Controls._children`;S.push(Zf(g,de,a,w,l)),C.push(g,...zt(g))}else S.push(Qf(g,a,w,l)),C.push(g)}const T=new Set;for(const L of C)for(const U of Ua(L))T.add(U);for(const L of t.tabs)for(const U of L.groups){const g=U.source?.attributes.Command;g&&!u.has(U.id)&&T.add(g)}const A=[];for(const L of y){const U=L.commandId;T.add(U),o.some(g=>g.id===U)||A.push({id:U,enableRules:[],displayRules:[],actions:[]})}const W=[...o.filter(L=>T.has(L.id)&&(!ei(L.id)||L.actions.length>0)),...A],D=new Set,N=new Set;for(const L of W)L.enableRules.forEach(U=>D.add(U)),L.displayRules.forEach(U=>N.add(U));const M=i.filter(L=>D.has(L.id)&&!ei(L.id)),k=s.filter(L=>N.has(L.id)&&!ei(L.id)),B=dh(b),G=W.map(ph).join(`
33
+ `),X=M.map(fh).join(`
34
+ `),Q=k.map(hh).join(`
35
+ `),ie=B.map(gh).join(`
36
+ `),F=[...x,...h,...Kf(t,n,d),...S,...v],_=y.filter(L=>L.tabDisplayRules.length>0).map(L=>bh(L,c)).filter(Boolean).join(`
37
+ `);return`<RibbonDiffXml>
38
+ <CustomActions>
39
+ ${F.join(`
40
+ `)}
41
+ </CustomActions>
42
+ <Templates><RibbonTemplates Id="Mscrm.Templates"/></Templates>
43
+ <CommandDefinitions>
44
+ ${G}
45
+ </CommandDefinitions>
46
+ <RuleDefinitions>
47
+ <TabDisplayRules>
48
+ ${_}
49
+ </TabDisplayRules>
50
+ <DisplayRules>
51
+ ${Q}
52
+ </DisplayRules>
53
+ <EnableRules>
54
+ ${X}
55
+ </EnableRules>
56
+ </RuleDefinitions>
57
+ <LocLabels>
58
+ ${ie}
59
+ </LocLabels>
60
+ </RibbonDiffXml>`}function Vf(e,t){const n=new Set,o=new Set;for(const x of t.tabs){n.add(x.id);for(const h of x.groups)o.add(h.id)}let i=0,s=0,a=0,l=0,c=0,d=0;for(const x of e.tabs){n.has(x.id)||l++,x.tabDisplayRules&&x.tabDisplayRules.length>0&&(d+=x.tabDisplayRules.length);for(const h of x.groups)!o.has(h.id)&&n.has(x.id)&&c++}for(const{change:x}of cl(e,t))x==="hide"?a++:x==="new"?i++:s++;const u=e.scalingByTab??{},m=t.scalingByTab??{};let f=0;for(const[x,h]of Object.entries(u))JSON.stringify(h)!==JSON.stringify(m[x])&&f++;const y=i+s+a+l+c+f>0;return{newButtons:i,overriddenButtons:s,hiddenButtons:a,newTabs:l,newGroups:c,scalingChanges:f,tabDisplayRules:d,hasAnyChange:y}}function Kf(e,t,n){const o=[],i=[];for(const[s,a]of Object.entries(e.scalingByTab??{})){if(!n.has(s))continue;const l=t.scalingByTab?.[s],c=(d,u)=>u?.some(m=>JSON.stringify(m)===JSON.stringify(d))??!1;for(const d of a.maxSizes)c(d,l?.maxSizes)||o.push(Li(s,"MaxSize",d));for(const d of a.scales)c(d,l?.scales)||i.push(Li(s,"Scale",d))}return[...o,...i]}function zi(e,t){const n=e==="Scale"&&t.popupSize?` PopupSize="${ae(t.popupSize)}"`:"";return`<${e} Id="${ae(t.id)}" GroupId="${ae(t.groupId)}" Sequence="${t.sequence}" Size="${ae(t.size)}"${n}/>`}function Li(e,t,n){return`<CustomAction Id="${ae(n.id)}.CustomAction"
61
+ Location="${ae(e)}.Scaling._children"
62
+ Sequence="${n.sequence}">
63
+ <CommandUIDefinition>
64
+ ${zi(t,n)}
65
+ </CommandUIDefinition>
66
+ </CustomAction>`}const ml={"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"},Jf=Object.keys(ml);function Yf(e){return ml[bs(e.template)]}function pl(e,t){const n=new Map,o=[],i=new Set(t.tabs.map(a=>a.id)),s=new Set(t.tabs.flatMap(a=>a.groups.map(l=>l.id)));for(const a of e.tabs){const l=!i.has(a.id),c=e.scalingByTab?.[a.id],d=(c?.maxSizes??[]).map(y=>y.sequence),u=(c?.scales??[]).map(y=>y.sequence),m=new Set([...d,...u]);if(l&&m.size<d.length+u.length&&o.push(`The scaling of new tab ${a.id} uses a Sequence more than once — give every MaxSize and Scale its own`),l&&d.length>0)continue;const f=Xa(d,u);for(const y of a.groups){if(!l&&s.has(y.id)||c?.maxSizes.some(S=>S.groupId===y.id))continue;const x=Yf(y);if(!x)continue;const h=Va(f,m);if(h===void 0){o.push(`No free scaling position for the new group "${y.label}" (${y.id}) on tab ${a.id}: its MaxSize must come after the tab's last MaxSize (${f.after}) and before its first Scale (${f.before}), and no Sequence is free there`);continue}m.add(h),n.set(y.id,{id:`${y.id}.MaxSize`,groupId:y.id,size:x,sequence:h})}}return{steps:n,problems:o}}function Zf(e,t,n,o,i=1033){return`<CustomAction Id="${ae(e.id)}.CustomAction"
67
+ Location="${ae(t)}"
68
+ Sequence="${e.sequence}">
69
+ <CommandUIDefinition>
70
+ ${Po(e,n,o,i,!0)}
71
+ </CommandUIDefinition>
72
+ </CustomAction>`}function Qf(e,t,n,o=1033){return`<CustomAction Id="${ae(e.id)}.Override.CustomAction"
73
+ Location="${ae(e.id)}"
74
+ Sequence="${e.sequence}">
75
+ <CommandUIDefinition>
76
+ ${Po(e,t,n,o)}
77
+ </CommandUIDefinition>
78
+ </CustomAction>`}function eh(e,t){return`<HideCustomAction HideActionId="${ae(e.id)}.HideAction"
79
+ Location="${ae(e.id)}"/>`}function th(e,t,n,o,i=1033,s=[]){return`<CustomAction Id="${ae(e.id)}.CustomAction"
80
+ Location="${ae(t)}.Groups._children"
81
+ Sequence="${e.sequence}">
82
+ <CommandUIDefinition>
83
+ ${fl(e,o,n,i,s)}
84
+ </CommandUIDefinition>
85
+ </CustomAction>`}function nh(e,t,n,o,i,s,a=1033,l=[]){const c=hl(e,s,a,l),d=e.commandId?` Command="${ae(e.commandId)}"`:"",u=e.groups.map(x=>fl(x,s,o.get(x.id)??[],a,l)).join(`
86
+ `),f=[...(t?.maxSizes.length?t.maxSizes:e.groups.map(x=>i.get(x.id)).filter(x=>!!x)).map(x=>zi("MaxSize",x)),...(t?.scales??[]).map(x=>zi("Scale",x))],y=f.length===0?`<Scaling Id="${ae(e.id)}.Scaling"/>`:`<Scaling Id="${ae(e.id)}.Scaling">
87
+ ${f.join(`
88
+ `)}
89
+ </Scaling>`;return`<CustomAction Id="${ae(e.id)}.CustomAction"
90
+ Location="${ae(n)}"
91
+ Sequence="${e.sequence}">
92
+ <CommandUIDefinition>
93
+ <Tab Id="${ae(e.id)}"${d} Title="${ae(c)}"${gl(e,l,s)} Sequence="${e.sequence}"${bl(e)}>
94
+ ${y}
95
+ <Groups Id="${ae(e.id)}.Groups">
96
+ ${u}
97
+ </Groups>
98
+ </Tab>
99
+ </CommandUIDefinition>
100
+ </CustomAction>`}function fl(e,t,n=[],o=1033,i=[]){const s=hl(e,t,o,i),a=bs(e.template),l=n.length===0?`<Controls Id="${ae(e.id)}.Controls"/>`:`<Controls Id="${ae(e.id)}.Controls">
101
+ ${n.join(`
102
+ `)}
103
+ </Controls>`;return`<Group Id="${ae(e.id)}" Title="${ae(s)}"${gl(e,i,t)} Sequence="${e.sequence}" Template="${ae(a)}"${bl(e)}>
104
+ ${l}
105
+ </Group>`}function hl(e,t,n,o){const i=`${e.id}.Title`;if(e.source&&e.label){const s=$n(e.label,e.source.titleToken,i,o,t,n);if(s)return s}return t({id:i,titles:[{languageCode:n,description:e.label}]}),il(i)}function gl(e,t,n){const o=e.description,i=o?.startsWith("$LocLabels:")?t.find(s=>s.id===o.slice(11)):void 0;return i&&n(i),Y("Description",o)}const oh=new Set(["Id","Command","Title","Description","Sequence","Template"]);function bl(e){const t="buttons"in e;return Object.entries(e.source?.attributes??{}).filter(([n])=>t&&n==="Command"||!oh.has(n)).filter(([n])=>!ys.has(n)).map(([n,o])=>` ${n}="${ae(o)}"`).join("")}function bs(e){const t=e?.trim();return t?t.includes(".")?t:`Mscrm.Templates.${t}`:"Mscrm.Templates.Flexible2"}function ih(e,t,n,o,i=1033){const s=e??"";if(s.startsWith("$LocLabels:")){const c=s.slice(11),d=n.find(u=>u.id===c);return d&&o(d),s}if(Rn(s))return s;const a=[{languageCode:i,description:s}],l=n.find(c=>c.id===t);if(l)for(const c of l.titles)c.languageCode!==i&&a.push(c);return o({id:t,titles:a}),il(t)}const sh=["ToolTipTitle","ToolTipDescription","ToolTipHelpKeyWord","ToolTipShortcutKey","ToolTipImage32by32","ToolTipImage32by32Class","ToolTipImage32by32Left","ToolTipImage32by32Top"],Zo=["Image16by16","Image16by16Class","Image16by16Left","Image16by16Top","Image32by32","Image32by32Class","Image32by32Left","Image32by32Top","ModernImage"],qt=["Id","Command","Sequence","TemplateAlias",...sh],Qo=["PopulateDynamically","PopulateOnlyOnce","PopulateQueryCommand","CacheMenuVersions"],rh={Button:new Set([...qt,...Zo,"Alt","CommandType","CommandValueId","Description","LabelCss","LabelText","MenuItemId","ModernCommandType","Priority"]),FlyoutAnchor:new Set([...qt,...Zo,...Qo,"Alt","CommandMenuClose","CommandType","LabelText","ModernCommandType","ToolTipSelectedItemTitle"]),SplitButton:new Set([...qt,...Zo,...Qo,"Alt","CommandMenuClose","CommandMenuOpen","CommandType","LabelText","MenuAlt","MenuCommand","ToolTipSelectedItemTitle"]),CheckBox:new Set([...qt,"Alt","LabelText","MenuItemId","QueryCommand"]),TextBox:new Set([...qt,"ImeEnabled","MaxLength","QueryCommand","ShowAsLabel","Width"]),ComboBox:new Set([...qt,...Qo,"AllowFreeForm","Alt","AltArrow","AutoComplete","AutoCompleteDelay","CommandMenuClose","CommandMenuOpen","CommandPreview","CommandPreviewRevert","ImeEnabled","InitialItem","QueryCommand","ToolTipSelectedItemTitle","Width"])},ys=new Set(["SolutionUniqueName"]);function ah(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 $n(e,t,n,o,i,s=1033){if(t!==void 0&&(e??"")===Be(t,o,s)){if(t.startsWith("$LocLabels:")){const c=o.find(d=>d.id===t.slice(11));c&&i(c)}return t}if(!e)return;const a=t?.startsWith("$LocLabels:")?t.slice(11):void 0,l=a&&o.some(c=>c.id===a)?a:n;return ih(e,l,o,i,s)}function xs(e){const t=e.source,n=l=>!!l?.startsWith("$webresource:"),o=l=>l&&!l.startsWith("/")&&/[/.]/.test(l)?Ss(l):l,i=o(e.image32),s=o(e.image16),a=[[e.image32,i,"Image32by32"],[e.image16,s,"Image16by16"]].filter(([l,c,d])=>n(c)&&l!==t?.attributes[d]).map(([,l])=>l);return t&&ah(t.modernImage)===e.icon&&a.length===0?t.modernImage:a[0]??[i,s,e.icon].find(n)}function Po(e,t,n,o=1033,i=!1){const s=uh(e.kind),a=e.source;if(a?.xml&&rt(e.kind))return mh(e,a.xml,t,n);const l=new Map;for(const[x,h]of Object.entries(a?.attributes??{}))ys.has(x)||l.set(x,h);const c=(x,h)=>h===void 0||h===""?l.delete(x):l.set(x,h);c("Id",e.id),c("Command",e.commandId||void 0),c("LabelText",$n(e.label,a?.labelToken,Mo(e.id),t,n,o)??""),l.has("LabelText")||l.set("LabelText",""),c("ToolTipTitle",$n(e.tooltipTitle,a?.tooltipTitleToken,Bo(e.id),t,n,o)),c("ToolTipDescription",$n(e.tooltipBody,a?.tooltipBodyToken,zo(e.id),t,n,o)),c("TemplateAlias",e.templateAlias),c("Sequence",a&&!("Sequence"in a.attributes)&&e.sequence===0?void 0:String(e.sequence));const d=x=>!!x&&(x.startsWith("$webresource:")||x.includes("/")||x.includes(".")),u=x=>d(x)?Ss(x):void 0;c("ModernImage",xs(e)),c("Image16by16",u(e.image16)),c("Image32by32",u(e.image32));const m=rh[s];if(m)for(const x of[...l.keys()])m.has(x)||l.delete(x);const f=Array.from(l.entries()).map(([x,h])=>`${x}="${ae(h)}"`).join(" "),y=i&&e.menu&&lh.has(s)?ch(e.menu,t,n,o):"";return y?`<${s} ${f}>${y}</${s}>`:`<${s} ${f}/>`}const lh=new Set(["FlyoutAnchor","SplitButton","ComboBox"]);function ch(e,t,n,o){const i=e.sections.map(l=>{const c=new Map(Object.entries(l.attributes??{})),d=(y,x)=>x===void 0||x===""?c.delete(y):c.set(y,x);d("Id",l.id),d("Title",$n(l.title,l.attributes?.Title,zf(l.id),t,n,o));const u=!!l.attributes&&!("Sequence"in l.attributes)&&l.sequence===0;d("Sequence",u?void 0:String(l.sequence)),d("DisplayMode",l.displayMode);const m=Array.from(c.entries()).map(([y,x])=>` ${y}="${ae(x)}"`).join("");if(l.rawContent!==void 0)return`<MenuSection${m}>${l.rawContent}</MenuSection>`;const f=l.controls.map(y=>Po(y,t,n,o,!0));for(const y of[...l.rawControls??[]].sort((x,h)=>x.index-h.index))f.splice(Math.min(y.index,f.length),0,y.xml);return`<MenuSection${m}><Controls Id="${ae(l.controlsId)}">${f.join("")}</Controls></MenuSection>`}),s=new Map(Object.entries(e.attributes??{}));return s.set("Id",e.id),`<Menu${Array.from(s.entries()).map(([l,c])=>` ${l}="${ae(c)}"`).join("")}>${i.join("")}</Menu>`}function ei(e){return/^(Mscrm|Microsoft)\./.test(e)}function dh(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 uh(e){return Vt[e]??"Button"}function mh(e,t,n,o){const i=new DOMParser().parseFromString(t,"application/xml").documentElement;for(const a of[i,...Array.from(i.getElementsByTagName("*"))])for(const l of ys)a.removeAttribute(l);i.setAttribute("Id",e.id),(i.hasAttribute("Sequence")||e.sequence!==0)&&i.setAttribute("Sequence",String(e.sequence));const s=new XMLSerializer().serializeToString(i);for(const a of s.matchAll(/\$LocLabels:([^"'\s<]+)/g)){const l=n.find(c=>c.id===a[1]);l&&o(l)}return s}function Ss(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 yl(e){const t=(e??"").trim();return t.startsWith("/")?t:Ss(t)}function Y(e,t){return t===void 0?"":` ${e}="${ae(String(t))}"`}function ut(e,t,n,o){return n.length===0?`<${e}${t}/>`:`<${e}${t}>
106
+ ${n.map(i=>`${o} ${i}`).join(`
107
+ `)}
108
+ ${o}</${e}>`}function xl(e,t=" "){switch(e.kind){case"javascript":return ut("JavaScriptFunction",`${Y("FunctionName",e.functionName)}${Y("Library",yl(e.library))}`,e.params.map(n=>Pi(n,!1)),t);case"url":return ut("Url",`${Y("Address",e.address)}${Y("PassParams",e.passParams)}${Y("WinMode",e.winMode)}${Y("WinParams",e.winParams)}`,e.params.map(n=>Pi(n,!0)),t);case"outlookCommand":return`<OutlookCommand${Y("ActionType",e.actionType)}${Y("Data",e.data)}/>`;case"raw":return e.xml;default:return""}}function ph(e){const t=" ",n=(a,l)=>{const c=[...l];for(const d of e.rawRuleRefs??[])d.container===a&&c.splice(Math.min(d.index,c.length),0,d.xml);return c},o=n("EnableRules",e.enableRules.map(a=>`<EnableRule Id="${ae(a)}"/>`)),i=n("DisplayRules",e.displayRules.map(a=>`<DisplayRule Id="${ae(a)}"/>`)),s=e.actions.map(a=>xl(a,`${t} `)).filter(Boolean);return`<CommandDefinition Id="${ae(e.id)}">
109
+ ${t} ${ut("EnableRules","",o,`${t} `)}
110
+ ${t} ${ut("DisplayRules","",i,`${t} `)}
111
+ ${t} ${ut("Actions","",s,`${t} `)}
112
+ ${t}</CommandDefinition>`}function Pi(e,t){const n=t?Y("Name",e.name??""):"";switch(e.kind){case"CrmParameter":return`<CrmParameter${n}${Y("Value",e.value)}/>`;case"BoolParameter":return`<BoolParameter${n}${Y("Value",e.value)}/>`;case"IntParameter":return`<IntParameter${n}${Y("Value",e.value)}/>`;case"DecimalParameter":return`<DecimalParameter${n}${Y("Value",e.value)}/>`;case"StringParameter":return`<StringParameter${n}${Y("Value",e.value)}/>`}}function fh(e){return ut("EnableRule",Y("Id",e.id),e.steps.map(t=>Fo(t," "))," ")}function hh(e){return ut("DisplayRule",Y("Id",e.id),e.steps.map(t=>Fo(t," "))," ")}function Fo(e,t=""){if(e.kind==="RawRule")return e.xml;if(e.kind==="OrRule"){const i=e.groups.map(s=>ut("Or","",s.map(a=>Fo(a,`${t} `)),`${t} `));return ut("OrRule","",i,t)}const n=`${Y("Default",e.default)}${Y("InvertResult",e.invertResult)}`,o=(i,s)=>`<${i}${s}${n}/>`;switch(e.kind){case"SelectionCountRule":return o("SelectionCountRule",`${Y("AppliesTo",e.appliesTo)}${Y("Minimum",e.minimum)}${Y("Maximum",e.maximum)}`);case"EntityRule":return o("EntityRule",`${Y("EntityName",e.entityName)}${Y("AppliesTo",e.appliesTo)}${Y("Context",e.context)}`);case"FormStateRule":return o("FormStateRule",Y("State",e.state));case"CommandClientTypeRule":return o("CommandClientTypeRule",Y("Type",e.type));case"CrmClientTypeRule":return o("CrmClientTypeRule",Y("Type",e.type));case"CustomRule":return ut("CustomRule",`${Y("FunctionName",e.functionName)}${Y("Library",e.library===void 0?void 0:yl(e.library))}${n}`,(e.params??[]).map(i=>Pi(i,!1)),t);case"FeatureControlRule":return o("FeatureControlRule",`${Y("FeatureControlBit",e.featureControlBit)}${Y("ExpectedValue",e.expectedValue)}`);case"MiscellaneousPrivilegeRule":return o("MiscellaneousPrivilegeRule",`${Y("PrivilegeName",e.privilegeName)}${Y("PrivilegeDepth",e.privilegeDepth)}`);case"FormTypeRule":return o("FormTypeRule",Y("Type",e.type));case"ValueRule":return o("ValueRule",`${Y("Field",e.field)}${Y("Value",e.value)}`);case"SkuRule":return o("SkuRule",Y("Sku",e.sku));case"HideForTabletExperienceRule":return o("HideForTabletExperienceRule","");case"OrganizationSettingRule":return o("OrganizationSettingRule",Y("Setting",e.setting));case"EntityPrivilegeRule":return o("EntityPrivilegeRule",`${Y("PrivilegeType",e.privilegeType)}${Y("PrivilegeDepth",e.privilegeDepth)}${Y("AppliesTo",e.appliesTo)}${Y("EntityName",e.entityName)}`);case"EntityPropertyRule":return o("EntityPropertyRule",`${Y("EntityName",e.entityName)}${Y("AppliesTo",e.appliesTo)}${Y("PropertyName",e.propertyName)}${Y("PropertyValue",e.propertyValue)}`);case"DeviceTypeRule":return o("DeviceTypeRule",Y("Type",e.type));case"RelationshipTypeRule":return o("RelationshipTypeRule",`${Y("AppliesTo",e.appliesTo)}${Y("RelationshipType",e.relationshipType)}${Y("AllowCustomRelationship",e.allowCustomRelationship)}${Y("AllowSystemRelationship",e.allowSystemRelationship)}`);case"RecordPrivilegeRule":return o("RecordPrivilegeRule",`${Y("PrivilegeType",e.privilegeType)}${Y("AppliesTo",e.appliesTo)}`);case"FormEntityContextRule":return o("FormEntityContextRule",Y("EntityName",e.entityName));case"PageRule":return o("PageRule",Y("Address",e.address));case"ReferencingAttributeRequiredRule":return o("ReferencingAttributeRequiredRule","");case"OutlookItemTrackingRule":return o("OutlookItemTrackingRule",`${Y("TrackedInCrm",e.trackedInCrm)}${Y("AppliesTo",e.appliesTo)}`);case"OutlookRenderTypeRule":return o("OutlookRenderTypeRule",Y("Type",e.type));case"OutlookVersionRule":return o("OutlookVersionRule",Y("Version",e.version));case"CrmOfflineAccessStateRule":return o("CrmOfflineAccessStateRule",Y("State",e.state));case"CrmOutlookClientTypeRule":return o("CrmOutlookClientTypeRule",Y("Type",e.type));case"CrmOutlookClientVersionRule":return o("CrmOutlookClientVersionRule",`${Y("Major",e.major)}${Y("Minor",e.minor)}${Y("Build",e.build)}${Y("Revision",e.revision)}`);case"OptionSetRule":return o("OptionSetRule",`${Y("OptionSet",e.optionSet)}${Y("StateCode",e.stateCode)}${Y("ObjectTypeCode",e.objectTypeCode)}`);default:{const i=e;throw new Error(`Unknown rule kind: ${i.kind}`)}}}function gh(e){const t=e.titles.map(n=>`<Title languagecode="${n.languageCode}" description="${ae(n.description)}"/>`).join(`
113
+ `);return`<LocLabel Id="${ae(e.id)}">
114
+ <Titles>
115
+ ${t}
116
+ </Titles>
117
+ </LocLabel>`}function bh(e,t){const n=new Map;for(const o of e.tabDisplayRules){const i=o.rules.map(s=>s.kind==="EntityRule"?`<EntityRule${Y("EntityName",s.entityName)}${Y("AppliesTo",s.appliesTo)}${Y("Context",s.context)}/>`:s.kind==="PageRule"&&t?`<PageRule${Y("Address",s.address)}/>`:"").filter(Boolean);n.set(o.tabCommand,[...n.get(o.tabCommand)??[],...i])}return[...n].filter(([,o])=>o.length>0).map(([o,i])=>`<TabDisplayRule TabCommand="${ae(o)}">
118
+ ${i.join(`
119
+ `)}
120
+ </TabDisplayRule>`).join(`
121
+ `)}function ae(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function pv(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="${ae(o.localizedName)}" OriginalName="${ae(o.localizedName)}">${ae(o.schemaName)}</Name>
126
+ ${o.ribbonDiffXml}
127
+ </Entity>`).join(`
128
+ `)}
129
+ </Entities>`}
130
+ ${e.applicationRibbonDiffXml??""}
131
+ </ImportExportXml>`}function Fi(e){return/^(Mscrm|Microsoft)\./.test(e)}function xo(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 yh(e,t){return t?"unmanaged":Fi(e)?"oob":"unmanaged"}function cr(e,t){for(const n of e.tabs)for(const o of n.groups)for(const i of Ne(o))t.has(i.id)?xo(i,{origin:"unmanaged"}):i.origin==="unmanaged"&&xo(i,{origin:"managed"})}function Dt(e){return e.origin==="unmanaged"}function Fn(e,t){return vl(Sl(t),[e])}function Sl(e){const t=new Map;for(const n of e.tabs)for(const o of n.groups)for(const i of Ne(o))t.set(i.id,(t.get(i.id)??!0)&&Dt(i));return t}function vl(e,t){return al(t).every(n=>e.get(n.id)??Dt(n))}function So(e,t,n){return t?n?"has"in n?n.has(e):n.includes(e):!1:!0}function vs(e,t,n){const o=t.tabs.some(i=>i.groups.some(s=>s.id===e.id));return So(e.id,o,n)&&vl(Sl(t),e.buttons)}const ws="Only tabs and groups your unmanaged customizations add (with a translatable title), or new ones, can be renamed";function wl(e,t,n,o){const i=e==="tab"?n.tabs.find(a=>a.id===t):new Map(n.tabs.flatMap(a=>a.groups.map(l=>[l.id,l]))).get(t);if(!i)return!0;if(!So(t,!0,o?.containerIds))return!1;const s=/^\$LocLabels:(.+)$/.exec(i.label??"")?.[1];return!!s&&So(s,!0,o?.locLabelIds)}function Cl(e,t,n){const o=t.tabs.some(i=>i.id===e.id);return So(e.id,o,n)&&e.groups.every(i=>vs(i,t,n))}function fv(e,t){const n=t.tabs.flatMap(a=>a.groups.flatMap(l=>Ne(l))).filter(a=>a.id===e.id),o=n.find(a=>!Dt(a)),i=o??n[0]??e,s=i.origin==="oob"?"the out-of-the-box ribbon":i.origin==="managed"?i.solutionName?`the managed solution "${i.solutionName}"`:"a managed solution":void 0;return o&&n.some(Dt)?`The ribbon also places a button with this id from ${s??"another solution"}, and that one can't be deleted.`:s&&Dt(e)?`It is your override of a button from ${s}: the original stays in the ribbon underneath it.`:s?`It comes from ${s}.`:Dt(i)?"Its menu holds items from another solution.":"It comes from another solution."}function xh(e,t,n=new Set){if(t.size!==0)for(const o of Object.keys(e))for(const i of e[o].tabs)for(const s of i.groups)for(const a of Ne(s)){const l=t.get(a.id);l&&!n.has(a.id)&&a.origin!=="oob"&&xo(a,l)}}function _o(e,t,n,o=[]){const s=new DOMParser().parseFromString(e,"application/xml"),a=s.querySelector("parsererror");if(a)throw new Error(`Ribbon XML parse error: ${a.textContent??"Unknown"}`);const l=Sh(s),c=vh(s);Ch(s,l);const d=new $h,u=Nh(s,d),m=kh(s,d),f=Ah(s,d);d.flush();const y=[...Oh(s)];for(const v of o)y.some(b=>b.id===v.id)||y.push(v);const x=new Set,h=new Set;s.querySelectorAll("CustomAction").forEach(v=>{const b=v.querySelector("CommandUIDefinition");if(b?.firstElementChild){const w=b.firstElementChild.getAttribute("Id")??"";w&&x.add(w)}}),s.querySelectorAll("HideCustomAction").forEach(v=>{const b=v.getAttribute("Location")??"";b&&h.add(b)});for(const v of l)for(const b of v.groups)for(const w of Ne(b)){const C=x.has(w.id);xo(w,{origin:yh(w.id,C)}),w.hidden=h.has(w.id),w.source&&(w.source.labelToken=w.source.attributes.LabelText,w.source.tooltipTitleToken=w.source.attributes.ToolTipTitle,w.source.tooltipBodyToken=w.source.attributes.ToolTipDescription),w.label=Be(w.label,y),w.tooltipTitle&&(w.tooltipTitle=Be(w.tooltipTitle,y)),w.tooltipBody&&(w.tooltipBody=Be(w.tooltipBody,y));for(const I of w.menu?.sections??[])I.title&&(I.title=Be(I.title,y))}const S=wh(s,l);return{ribbon:{location:t,entityLogicalName:n,tabs:l,...Object.keys(c).length>0?{scalingByTab:c}:{},...Object.keys(S).length?{templateLayouts:S}:{}},commands:u,displayRules:f,enableRules:m,locLabels:y}}const Il="Ribbon > Tabs > Tab, Ribbon > ContextualTabs > ContextualGroup > Tab";function dr(e){const t=e.getAttribute("Description");return t===null?{}:{description:t}}function Sh(e){const t=[];return e.querySelectorAll(Il).forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const i=n.getAttribute("Title")??o,s=[];n.querySelectorAll(":scope > Groups > Group").forEach(a=>{const l=a.getAttribute("Id")??"";if(!l)return;const c=a.getAttribute("Title")??a.getAttribute("Label")??l,d=parseInt(a.getAttribute("Sequence")??"0",10),u=a.getAttribute("Template")??"",m=[];a.querySelectorAll(":scope > Controls > *").forEach(f=>{Wa[f.tagName]&&Rl(f,m)}),s.push({id:l,label:c,sequence:d,template:u,...dr(a),buttons:m})}),t.push({id:o,label:i,sequence:parseInt(n.getAttribute("Sequence")??"0",10),commandId:n.getAttribute("Command")??void 0,...dr(n),tabDisplayRules:[],groups:s})}),t.sort((n,o)=>n.sequence-o.sequence)}function vh(e){const t={};return e.querySelectorAll(Il).forEach(n=>{const o=n.getAttribute("Id"),i=Array.from(n.children).find(l=>l.tagName==="Scaling");if(!o||!i||t[o])return;const s=l=>({id:l.getAttribute("Id")??"",groupId:l.getAttribute("GroupId")??"",size:l.getAttribute("Size")??"",sequence:parseInt(l.getAttribute("Sequence")??"0",10),...l.getAttribute("PopupSize")?{popupSize:l.getAttribute("PopupSize")}:{}}),a=Array.from(i.children);t[o]={tabId:o,maxSizes:a.filter(l=>l.tagName==="MaxSize").map(s),scales:a.filter(l=>l.tagName==="Scale").map(s)}}),t}function wh(e,t){const n=new Set(t.flatMap(i=>i.groups.map(s=>s.template)).filter(Boolean)),o={};return e.querySelectorAll("GroupTemplate").forEach(i=>{const s=i.getAttribute("Id");!s||!n.has(s)||(o[s]=Array.from(i.querySelectorAll(":scope > Layout")).map(a=>a.getAttribute("Title")??"").filter(Boolean))}),o}function Ch(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 i=o.getAttribute("TabCommand")??"",s=n.get(i);if(!s)return;const a=[];for(const c of Array.from(o.children))c.tagName==="EntityRule"?a.push({kind:"EntityRule",entityName:c.getAttribute("EntityName")??void 0,appliesTo:c.getAttribute("AppliesTo")??void 0,context:c.getAttribute("Context")??void 0}):c.tagName==="PageRule"&&a.push({kind:"PageRule",address:c.getAttribute("Address")??""});if(a.length===0)return;const l=s.tabDisplayRules.find(c=>c.tabCommand===i);l?l.rules.push(...a):s.tabDisplayRules.push({tabCommand:i,rules:a})})}function Rl(e,t){const n=e.getAttribute("Id")??"";if(!n)return;const o=Wa[e.tagName]??"button",i=rt(o),s=e.getAttribute("LabelText")??n,a=jh(e.getAttribute("ModernImage")??void 0),l=parseInt(e.getAttribute("Sequence")??"0",10),c=e.getAttribute("TemplateAlias")??"",d=e.getAttribute("Command")??"";t.push({id:n,label:s,icon:a,sequence:l,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:_i(e),...i?{xml:nn().serializeToString(e)}:{}},menu:i?void 0:Rh(e)})}const Ih=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]);function _i(e){return Object.fromEntries(Array.from(e.attributes).map(t=>[t.name,t.value]))}function Rh(e){const t=_e(e).find(i=>i.tagName==="Menu");if(!t)return;const n=_i(t),o=[];for(const i of _e(t)){if(i.tagName!=="MenuSection")continue;const s=i.getAttribute("Id")??"",a=_e(i).find(u=>u.tagName==="Controls"),l=[],c=[];_e(a).forEach((u,m)=>{Ih.has(u.tagName)&&u.getAttribute("Id")?Rl(u,l):c.push({index:m,xml:nn().serializeToString(u)})});const d=_i(i);o.push({id:s,title:i.getAttribute("Title")??void 0,sequence:parseInt(i.getAttribute("Sequence")??"0",10),displayMode:i.getAttribute("DisplayMode")??void 0,controlsId:a?.getAttribute("Id")??`${s}.Controls`,controls:l,attributes:d,...c.length?{rawControls:c}:{},...a?{}:{rawContent:_e(i).map(u=>nn().serializeToString(u)).join("")}})}return{id:t.getAttribute("Id")??`${e.getAttribute("Id")}.Menu`,sections:o,attributes:n}}function jh(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 nn=()=>new XMLSerializer;function _e(e){return e?Array.from(e.childNodes).filter(t=>t.nodeType===Node.ELEMENT_NODE):[]}class $h{pending=[];add(t){this.pending.push(t)}flush(){for(const t of[0,1]){const n=this.pending.filter(s=>s.phase===t);if(n.length===0)continue;const o=n.map(s=>s.generate());let i=null;try{const s=qa(`<v>${o.map(a=>`<i>${a}</i>`).join("")}</v>`);i=_e(s).map(a=>_e(a)[0])}catch{i=null}n.forEach((s,a)=>{(i?i[a]&&en(i[a])===en(s.source):vf(o[a],s.source))||s.fallback()})}this.pending=[]}}function Nh(e,t){const n=[];return e.querySelectorAll("CommandDefinition").forEach(o=>{const i=o.getAttribute("Id")??"";if(!i)return;const s=_e(o),a=f=>s.find(y=>y.tagName===f),l=[],c=(f,y)=>{const x=[];return _e(a(f)).forEach((h,S)=>{const v=h.getAttribute("Id");h.tagName===y&&v&&h.attributes.length===1&&_e(h).length===0?x.push(v):l.push({container:f,index:S,xml:nn().serializeToString(h)})}),x},d=c("EnableRules","EnableRule"),u=c("DisplayRules","DisplayRule"),m=[];_e(a("Actions")).forEach((f,y)=>{const x=Th(f);if(!x){m.push(ur(f));return}m.push(x),t.add({source:f,generate:()=>xl(x),fallback:()=>m[y]=ur(f),phase:0})}),n.push({id:i,enableRules:d,displayRules:u,actions:m,...l.length>0?{rawRuleRefs:l}:{}})}),n}function ur(e){return{kind:"raw",tagName:e.tagName,xml:nn().serializeToString(e)}}function Th(e){switch(e.tagName){case"JavaScriptFunction":{const t=qi(e);return t?{kind:"javascript",library:e.getAttribute("Library")??"",functionName:e.getAttribute("FunctionName")??"",params:t}:null}case"Url":{const t=qi(e);if(!t)return null;const n=e.getAttribute("WinMode");return{kind:"url",address:e.getAttribute("Address")??"",passParams:bt(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 bt(e){if(e===null)return;const t=e.trim();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}function qi(e){const t=[];for(const n of _e(e)){const o=n.getAttribute("Name")??void 0,i=n.getAttribute("Value")??"";switch(n.tagName){case"CrmParameter":t.push({kind:"CrmParameter",name:o,value:i});break;case"BoolParameter":t.push({kind:"BoolParameter",name:o,value:bt(i)??!1});break;case"IntParameter":t.push({kind:"IntParameter",name:o,value:parseInt(i,10)});break;case"DecimalParameter":t.push({kind:"DecimalParameter",name:o,value:parseFloat(i)});break;case"StringParameter":t.push({kind:"StringParameter",name:o,value:i});break;default:return null}}return t}function kh(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > EnableRules > EnableRule").forEach(o=>{const i=o.getAttribute("Id")??"";i&&n.push({id:i,steps:Cs(o,t)})}),n}function Ah(e,t){const n=[];return e.querySelectorAll("RuleDefinitions > DisplayRules > DisplayRule").forEach(o=>{const i=o.getAttribute("Id")??"";i&&n.push({id:i,steps:Cs(o,t)})}),n}function Cs(e,t){const n=[];return _e(e).forEach((o,i)=>{const s=Eh(o,t);if(!s){n.push(mr(o));return}n.push(s),t.add({source:o,generate:()=>Fo(n[i]),fallback:()=>n[i]=mr(o),phase:s.kind==="OrRule"?1:0})}),n}function mr(e){return{kind:"RawRule",tagName:e.tagName,xml:nn().serializeToString(e)}}function Dh(e){const t={},n=bt(e.getAttribute("Default")),o=bt(e.getAttribute("InvertResult"));return n!==void 0&&(t.default=n),o!==void 0&&(t.invertResult=o),t}function fn(e,t){const n=e.getAttribute(t);return n===null?void 0:parseInt(n,10)}function Ve(e,t){return e.getAttribute(t)??void 0}function ge(e,t){return e.getAttribute(t)??""}function Eh(e,t){const n=Dh(e);switch(e.tagName){case"OrRule":{const o=_e(e);return o.some(i=>i.tagName!=="Or")?null:{kind:"OrRule",groups:o.map(i=>Cs(i,t))}}case"SelectionCountRule":return{kind:"SelectionCountRule",minimum:fn(e,"Minimum"),maximum:fn(e,"Maximum"),appliesTo:Ve(e,"AppliesTo"),...n};case"EntityRule":return{kind:"EntityRule",entityName:Ve(e,"EntityName"),context:Ve(e,"Context"),appliesTo:Ve(e,"AppliesTo"),...n};case"FormStateRule":return{kind:"FormStateRule",state:ge(e,"State"),...n};case"CommandClientTypeRule":return{kind:"CommandClientTypeRule",type:ge(e,"Type"),...n};case"CustomRule":{const o=qi(e);return o?{kind:"CustomRule",library:ge(e,"Library"),functionName:ge(e,"FunctionName"),...o.length>0?{params:o}:{},...n}:null}case"FeatureControlRule":{const o=bt(e.getAttribute("ExpectedValue"));return o===void 0?null:{kind:"FeatureControlRule",featureControlBit:ge(e,"FeatureControlBit"),expectedValue:o,...n}}case"MiscellaneousPrivilegeRule":return{kind:"MiscellaneousPrivilegeRule",privilegeName:ge(e,"PrivilegeName"),privilegeDepth:Ve(e,"PrivilegeDepth"),...n};case"CrmClientTypeRule":return{kind:"CrmClientTypeRule",type:ge(e,"Type"),...n};case"FormTypeRule":return{kind:"FormTypeRule",type:ge(e,"Type"),...n};case"ValueRule":return{kind:"ValueRule",field:ge(e,"Field"),value:ge(e,"Value"),...n};case"SkuRule":return{kind:"SkuRule",sku:ge(e,"Sku"),...n};case"HideForTabletExperienceRule":return{kind:"HideForTabletExperienceRule",...n};case"OrganizationSettingRule":return{kind:"OrganizationSettingRule",setting:ge(e,"Setting"),...n};case"EntityPrivilegeRule":return{kind:"EntityPrivilegeRule",entityName:Ve(e,"EntityName"),appliesTo:Ve(e,"AppliesTo"),privilegeType:ge(e,"PrivilegeType"),privilegeDepth:ge(e,"PrivilegeDepth"),...n};case"EntityPropertyRule":{const o=bt(e.getAttribute("PropertyValue"));return o===void 0?null:{kind:"EntityPropertyRule",entityName:Ve(e,"EntityName"),appliesTo:Ve(e,"AppliesTo"),propertyName:ge(e,"PropertyName"),propertyValue:o,...n}}case"DeviceTypeRule":return{kind:"DeviceTypeRule",type:ge(e,"Type"),...n};case"OptionSetRule":return{kind:"OptionSetRule",optionSet:ge(e,"OptionSet"),stateCode:ge(e,"StateCode"),objectTypeCode:ge(e,"ObjectTypeCode"),...n};case"RecordPrivilegeRule":return{kind:"RecordPrivilegeRule",privilegeType:ge(e,"PrivilegeType"),appliesTo:Ve(e,"AppliesTo"),...n};case"FormEntityContextRule":return{kind:"FormEntityContextRule",entityName:ge(e,"EntityName"),...n};case"PageRule":return{kind:"PageRule",address:ge(e,"Address"),...n};case"RelationshipTypeRule":return{kind:"RelationshipTypeRule",appliesTo:"SelectedEntity",relationshipType:Ve(e,"RelationshipType"),allowCustomRelationship:bt(e.getAttribute("AllowCustomRelationship")),allowSystemRelationship:bt(e.getAttribute("AllowSystemRelationship")),...n};case"ReferencingAttributeRequiredRule":return{kind:"ReferencingAttributeRequiredRule",...n};case"OutlookItemTrackingRule":{const o=bt(e.getAttribute("TrackedInCrm"));return o===void 0?null:{kind:"OutlookItemTrackingRule",trackedInCrm:o,appliesTo:Ve(e,"AppliesTo"),...n}}case"OutlookRenderTypeRule":return{kind:"OutlookRenderTypeRule",type:ge(e,"Type"),...n};case"OutlookVersionRule":return{kind:"OutlookVersionRule",version:ge(e,"Version"),...n};case"CrmOfflineAccessStateRule":return{kind:"CrmOfflineAccessStateRule",state:ge(e,"State"),...n};case"CrmOutlookClientTypeRule":return{kind:"CrmOutlookClientTypeRule",type:ge(e,"Type"),...n};case"CrmOutlookClientVersionRule":return{kind:"CrmOutlookClientVersionRule",major:parseInt(ge(e,"Major"),10),minor:fn(e,"Minor"),build:fn(e,"Build"),revision:fn(e,"Revision"),...n};default:return null}}function Oh(e){const t=[];return e.querySelectorAll("LocLabel").forEach(n=>{const o=n.getAttribute("Id")??"";if(!o)return;const i=[];n.querySelectorAll("Title").forEach(s=>{const a=parseInt(s.getAttribute("languagecode")??"1033",10),l=s.getAttribute("description")??"";i.push({languageCode:a,description:l})}),t.push({id:o,titles:i})}),t}function vo(e){return{controlIds:[...go(e)],containerIds:[...nl(e)],locLabelIds:[...e.locLabels.keys()],hides:Eo(e),scalingStepIds:hs(e).map(t=>t.id),commandIds:[...e.commandDefinitions.keys()],commandRefIds:[...ol(e)]}}async function hv(e){try{return vo(await Wi(e))}catch{return null}}function Mh(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=_o(t,"HomepageGrid","");return{commands:n.commands,enableRules:n.enableRules,displayRules:n.displayRules}}function Bh(){return window.dataverseAPI}async function Jt(e){const t=[];let n=e;for(;n;){const o=await Bh().queryData(n);t.push(...o.value??[]);const i=o["@odata.nextLink"];n=i?i.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}async function Wi(e){const t=e===null?"entity eq null and ismanaged eq false":`entity eq '${e.replace(/'/g,"''")}' and ismanaged eq false`,[n,o,i]=await Promise.all([Jt(`ribbondiffs?$select=diffid,difftype,rdx,sequence&$filter=${t}&$orderby=sequence asc,diffid asc`),Jt(`ribboncommands?$select=command,commanddefinition&$filter=${t}&$orderby=command asc`),Jt(`ribbonrules?$select=ruleid,ruletype,ruledefinition&$filter=${t}&$orderby=ruleid asc`)]);return Rf({diffs:n,commands:o,rules:i})}function Hi(e){const t=[];for(const[n,o]of e.locLabels){const i=new DOMParser().parseFromString(o,"application/xml"),s=Array.from(i.querySelectorAll("Title")).map(a=>({languageCode:Number(a.getAttribute("languagecode")??1033),description:a.getAttribute("description")??""}));t.push({id:n,titles:s})}return t}function pr(e,t,n,o){const s=`${Rs()}.${Yt(e)}.${Yt(t)}.${Yt(n)}`;return js(s,o)}function Is(e,t,n){const i=`${Rs()}.${Yt(e)}.${Yt(t)}.Command`;return js(i,n)}function En(e,t,n){const i=`${Rs()}.${Yt(e)}.${t}Rule`;return js(i,n)}function fr(e){return e.replace(/\.Command$/,"").split(".").pop()||"Rule"}function Rs(){try{return oe.getState().publisherPrefix||"new"}catch{return"new"}}function Yt(e){return e.replace(/[^a-zA-Z0-9._]/g,"").replace(/^[^a-zA-Z]/,"x")}function js(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}${n}`);)n++;return`${e}${n}`}function jl(e,t,n,o,i){const s=o.replace(/[^a-zA-Z0-9_]/g,"")||"Button",a=`${e}.${t}.${n}.${s}`;let l=a;for(let c=2;i.has(`${l}.Button`)||i.has(`${l}.Command`);c++)l=`${a}${c}`;return{id:`${l}.Button`,commandId:`${l}.Command`}}function gv(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 te=Nt()(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,i){e({location:t,tabId:n,selectedGroupId:o,selectedButtonId:i})},clearSelection(){e({selectedButtonId:null,selectedGroupId:null})}}));function qo(e){return/\.AllEntities\./.test(e)||/\.VisualizationTab$/.test(e)}function Nn(e){const t=e.filter(n=>!qo(n.id));return(t.find(n=>/\.MainTab$/.test(n.id))??t[0]??e[0])?.id}const Pe="Mscrm.OpenRecordItem",$l=["HomepageGrid","SubGrid"],zh=/\.(HomepageGrid|SubGrid)\.OpenRecordItem\d*\.Button$/;function Nl(e){return e.commandId===Pe&&zh.test(e.id)}function $s(e){const t=[];for(const n of e?.tabs??[])for(const o of n.groups)for(const i of Ne(o))i.commandId===Pe&&t.push({tabId:n.id,groupId:o.id,button:i});return t}function Tl(e){return $s(e).filter(t=>Nl(t.button))}function kl(e){const t=e.button.origin;return t==="unmanaged"?"yours":t===void 0?"unknown":"theirs"}function Al(e){const t=e?.tabs??[],n=Nn(t.filter(s=>s.groups.length>0)),o=t.find(s=>s.id===n),i=o?.groups.find(s=>/\.Management$/.test(s.id))??o?.groups[0];return o&&i?{tabId:o.id,groupId:i.id}:null}function Lh(){return{id:Pe,enableRules:[],displayRules:[],actions:[{kind:"javascript",library:"$webresource:",functionName:"YourNamespace.openRecord",params:[{kind:"CrmParameter",value:"SelectedControlSelectedItemReferences"}]}]}}function Ph(e){for(const t of e.actions){if(t.kind!=="javascript")continue;if(!t.library.trim().replace(/^\$webresource:/i,"").trim()||!t.functionName.trim())return`${Pe} has a JavaScript action without a web resource or function — set them in the Command Editor, or turn the override off`}return null}const Fh=["Mscrm.HideOnModern","Mscrm.ShowOnlyOnModern"];function hn(e,t){const n=new Set;for(const o of[t,e.baseline])for(const i of Object.values(o??{}))for(const s of i.tabs){n.add(s.id);for(const a of s.groups){n.add(a.id);for(const l of Ne(a))n.add(l.id)}}for(const o of Object.values(e.layers??{})){for(const i of o?.containerIds??[])n.add(i);for(const i of o?.controlIds??[])n.add(i)}return n}function Tn(e,t){return Wo(e,t)?.containerIds}function Wo(e,t){return e.layers[t==="Application"?"application":"entity"]}function We(e){return JSON.parse(JSON.stringify(e))}function ct(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 Ce(e,t,n,o,i="info"){return{ts:new Date().toISOString(),userId:"",userName:"You",op:e,target:t,detail:n,icon:o,color:i}}let Ge=null;const _h=1e3;function Oe(e,t,n,o){if(Ge)return Ge.meta||(Ge.meta=n),t;const i=e.past[e.past.length-1];if(o&&i?.coalesceKey===o&&e.future.length===0&&Date.parse(n.ts)-Date.parse(i.ts)<_h)return{...t,past:[...e.past.slice(0,-1),{...i,...n}],mutationsSincePublish:e.mutationsSincePublish+1};const s={...n,coalesceKey:o,snapshot:ct(e)};return{...t,past:[...e.past,s].slice(-80),future:[],mutationsSincePublish:e.mutationsSincePublish+1}}function Ie(e,t,n,o){const i=We(e.ribbons);return t(i),Oe(e,{ribbons:i},n,o)}function io(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 gn(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,i)=>i===n?t:o)}const hr={entity:null,application:null},ti={entity:[],application:[]},gr=["HomepageGrid","SubGrid","Form"];function Dl(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 so(e,t,n){let o=t;for(;o>0&&n(e[o-1]);)o--;let i=t;for(;i<e.length-1&&n(e[i+1]);)i++;const s=o>0?e[o-1].sequence:0,a=i<e.length-1?e[i+1].sequence:1/0;if(a-s-1>=i-o+1){let d=s;for(let u=o;u<=i;u++){const m=i-u,f=e[u];f.sequence>d&&f.sequence<=a-1-m||(f.sequence=a===1/0?d+10:d+Math.max(1,Math.min(10,Math.floor((a-d)/(m+2))))),d=f.sequence}return}const l=new Set(e.filter((d,u)=>u!==t).map(d=>d.sequence));let c=(t>0?e[t-1].sequence:0)+1;for(;l.has(c);)c++;e[t].sequence=c}function br(e,t,n){const o=e[t],i=Dl(o.sequence,e[t-1]?.sequence,e[t+1]?.sequence);if(i!==void 0){o.sequence=i;return}if(so(e,t,n),!((e[t-1]?.sequence??-1/0)<o.sequence&&o.sequence<(e[t+1]?.sequence??1/0))){e.splice(t,1);const a=e.findIndex(l=>l.sequence>o.sequence);e.splice(a<0?e.length:a,0,o)}}function ni(){const{activeSolution:e,publisherPrefix:t}=oe.getState();return e?.publisherPrefix?.trim()||t?.trim()||"new"}function oi(e,t){const n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(`${o}.`)||n.startsWith(`${o}_`)?e:`${t}.${e}`}const ii={HomepageGrid:{location:"HomepageGrid",entityLogicalName:"",tabs:[]},SubGrid:{location:"SubGrid",entityLogicalName:"",tabs:[]},Form:{location:"Form",entityLogicalName:"",tabs:[]},Application:{location:"Application",entityLogicalName:"",tabs:[]}};function et(e,t,n,o,i){const s=e[t].tabs.find(l=>l.id===n)?.groups.find(l=>l.id===o),a=mn(s,i);return s&&a?{group:s,button:a}:void 0}function El(e,t,n){return(e.baseline[t]?.tabs??[]).some(o=>o.groups.some(i=>Ne(i).some(s=>s.id===n)))}function He(e,t,n){return e==="Application"&&t==="Mscrm.GlobalTab"&&n.oob===!0&&n.custom!==!0}function Ns(e,t,n){return n.origin!=="unmanaged"&&!n.hidden&&n.kind!=="flyout"&&n.kind!=="splitButton"&&!rt(n.kind)&&!He(e,t,n)}function qh(e,t,n){for(const o of e.baseline[t].tabs)for(const i of o.groups){const s=i.buttons.find(a=>a.id===n);if(s)return s}}function Wh(e,t,n){if(t.location!==n.location||t.tabId!==n.tabId||t.groupId!==n.groupId)return!1;const o=e.buttons.findIndex(s=>s.id===t.buttonId),i=e.buttons[o+1]?.id;return n.beforeButtonId?n.beforeButtonId===t.buttonId||n.beforeButtonId===i:i===void 0}const wo=/^\$LocLabels:/,ro=e=>e.labelsUnknown?void 0:new Set(e.locLabels.map(t=>t.id));function Hh(e,t){if(!e)return;const n=i=>i&&(!wo.test(i)||jn(i,t))?i:void 0,o={};for(const[i,s]of Object.entries(e.attributes))i!=="Id"&&!wo.test(s)&&(o[i]=s);return{...e,labelToken:n(e.labelToken),tooltipTitleToken:n(e.tooltipTitleToken),tooltipBodyToken:n(e.tooltipBodyToken),attributes:o}}const si=(e,t)=>({entity:e.entity.filter(n=>n!==t),application:e.application.filter(n=>n!==t)});function yr(e,t){const n=e.baselineCommands.find(i=>i.id===t),o=e.commands.find(i=>i.id===t);return!n||!o||JSON.stringify(n)===JSON.stringify(o)?e.commands:e.commands.map(i=>i.id===t?JSON.parse(JSON.stringify(n)):i)}const E=Nt()(uf((e,t)=>({ribbons:We(ii),baseline:We(ii),baselineCommands:[],baselineEnableRules:[],baselineDisplayRules:[],baselineLocLabels:[],layers:{...hr},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:We(n),baseline:We(n),mutationsSincePublish:0,past:[],future:[]}),Ge&&(Ge={snapshot:ct(t()),meta:null})},setConflicts(n){e({conflicts:n})},applyImport(n,o){e(i=>Oe(i,{ribbons:{...i.ribbons,...We(n.ribbons)},commands:[...n.commands],enableRules:[...n.enableRules],displayRules:[...n.displayRules],locLabels:[...n.locLabels]},Ce("imported","RibbonDiffXml",o,"arrow_upload","success")))},loadWorkspace(n){const o=We(n.ribbons);e({ribbons:o,baseline:We(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:{...hr,...n.layers??{}},pendingUnhides:{...ti},orphans:{entity:[],application:[],...n.orphans??{}},pendingOrphanDeletes:{...ti},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:[]}),Ge&&(Ge={snapshot:ct(t()),meta:null})},restoreWorkspace(n,o){const i=JSON.parse(JSON.stringify(n));e(s=>{const a=c=>{const d=s.layers[c];return d?i.pendingUnhides[c].filter(u=>d.hides.some(m=>m.location===u)):i.pendingUnhides[c]},l={...i,pendingUnhides:{entity:a("entity"),application:a("application")}};return JSON.stringify(ct({...s,...l}))===JSON.stringify(ct(s))?s:Oe(s,l,Ce("restored","unsaved changes",o,"history"))})},resetWorkspace(){t().loadWorkspace({ribbons:ii,commands:[],displayRules:[],enableRules:[],locLabels:[]})},undo(){t().restore(t().past.length-1)},redo(){const n=t();if(n.future.length===0||Ge)return;const[o,...i]=n.future;e({...o.snapshot,past:[...n.past,{...o,snapshot:ct(n)}],future:i,mutationsSincePublish:io({...n,...o.snapshot})?n.mutationsSincePublish+1:0})},restore(n){const o=t(),{past:i}=o;if(n<0||n>=i.length||Ge)return;let s=ct(o),a=o.future;for(let c=i.length-1;c>=n;c--)a=[{...i[c],coalesceKey:void 0,snapshot:s},...a],s=i[c].snapshot;const l=i.length-n;e({...s,past:i.slice(0,n),future:a,mutationsSincePublish:io({...o,...s})?Math.max(1,o.mutationsSincePublish-l):0})},batch(n){if(Ge){n();return}Ge={snapshot:ct(t()),meta:null};try{n()}finally{const{snapshot:o,meta:i}=Ge;Ge=null,i&&e(s=>({past:[...s.past,{...i,snapshot:o}].slice(-80),future:[],mutationsSincePublish:s.mutationsSincePublish+1}))}},moveButton(n,o){const i=t(),a=i.ribbons[n.location].tabs.find(m=>m.id===n.tabId)?.groups.find(m=>m.id===n.groupId),l=a?.buttons.find(m=>m.id===n.buttonId),c=i.ribbons[o.location].tabs.find(m=>m.id===o.tabId)?.groups.find(m=>m.id===o.groupId);if(!l||!a||!c)return null;const d=qh(i,n.location,l.id)?.origin;if(d!==void 0&&d!=="unmanaged"&&!l.menu&&!Kt(l.kind)&&!He(n.location,n.tabId,l)){if(Wh(a,n,o))return null;const m=h=>(ne.getState().logWarn("ribbon",`Can't move ${l.id}: ${h}`),null);if(l.hidden)return m("it's hidden — move your copy of it instead.");if(n.location==="Application"!=(o.location==="Application"))return m("it isn't yours, and a copy can't move between the table's ribbon and the application ribbon.");const f=ni();let y=null,x=!1;return t().batch(()=>{const h=t().customiseButton(n.location,n.tabId,n.groupId,n.buttonId,f);h&&(x=!0,y=t().moveButton({...n,buttonId:h},o),ne.getState().logInfo("ribbon",`${l.id} isn't yours, so it can't be moved: moved your copy ${h} instead and hid the original.`))}),x&&!y&&t().undo(),x?y:m("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 He(n.location,n.tabId,l)?null:(e(m=>Ie(m,f=>{const y=f[n.location].tabs.find($=>$.id===n.tabId);if(!y)return;const x=y.groups.find($=>$.id===n.groupId);if(!x)return;const h=x.buttons.findIndex($=>$.id===n.buttonId);if(h===-1||He(n.location,n.tabId,x.buttons[h]))return;const v=(n.tabId===o.tabId&&n.location===o.location?y:f[o.location].tabs.find($=>$.id===o.tabId))?.groups.find($=>$.id===o.groupId);if(!v)return;const[b]=x.buttons.splice(h,1),w=o.beforeButtonId?v.buttons.findIndex($=>$.id===o.beforeButtonId):v.buttons.length,C=w<0?v.buttons.length:w;v.buttons.splice(C,0,b);const I=Dl(b.sequence,v.buttons[C-1]?.sequence,v.buttons[C+1]?.sequence);if(I!==void 0)b.sequence=I;else{const $=new Set(m.layers[o.location==="Application"?"application":"entity"]?.controlIds??[]),j=new Set(m.baseline[o.location].tabs.flatMap(R=>R.groups.flatMap(T=>T.buttons.map(A=>A.id))));so(v.buttons,C,R=>R===b||$.has(R.id)||!j.has(R.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,i,s,a){const c=Object.values(a).every(d=>typeof d=="string")?`button:${n}:${s}:${Object.keys(a).sort().join(",")}`:void 0;e(d=>{const u=m=>{const f=et(m,n,o,i,s);return!f||a.kind===void 0||a.kind===f.button.kind||!El(d,n,s)&&(f.group.buttons.includes(f.button)||gs.includes(a.kind))};return Object.keys(a).length===1&&!u(d.ribbons)?{}:Ie(d,m=>{const f=et(m,n,o,i,s)?.button;if(!f||He(n,o,f))return;const y=f.kind,x=u(m);Object.assign(f,a),x||(f.kind=y),Kt(f.kind)&&!f.menu&&(f.menu=Yo(f.id))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:a.label??s,detail:Object.keys(a).join(", "),icon:"edit",color:"info"},c)})},deleteButton(n,o,i,s){const a=t(),l=et(a.ribbons,n,o,i,s)?.button;if(l&&!Fn(l,a.baseline[n])){ne.getState().logWarn("ribbon",`"${l.label}" (${s}) was not deleted: only your own buttons can be deleted — hide it instead.`);return}e(c=>Ie(c,d=>{const u=et(d,n,o,i,s);if(!u)return;const{group:m,button:f}=u;He(n,o,f)||ll(m,s)||(m.buttons=m.buttons.filter(y=>y.id!==s))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:s,detail:i,icon:"delete",color:"danger"}))},addMenuItem({location:n,tabId:o,groupId:i,parentId:s,sectionId:a,item:l}){e(c=>Ie(c,d=>{const u=et(d,n,o,i,s)?.button;if(!u||He(n,o,u))return;u.menu=u.menu??Yo(u.id),u.menu.sections.length===0&&u.menu.sections.push(Mi(u.id,[]));const m=u.menu.sections.find(y=>y.id===a)??u.menu.sections[0],f=m.controls[m.controls.length-1]?.sequence??0;m.controls.push({...l,kind:l.kind??"button",sequence:l.sequence??f+10,templateAlias:l.templateAlias??"",hidden:!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"})},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:l.label,detail:`menu of ${s}`,icon:"add",color:"success"}))},addMenuSection(n,o,i,s,a){e(l=>Ie(l,c=>{const d=et(c,n,o,i,s)?.button;!d||He(n,o,d)||(d.menu=d.menu??{id:`${d.id}.Menu`,sections:[]},d.menu.sections.push(Mi(d.id,d.menu.sections,a)))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:a??"Menu section",detail:`menu of ${s}`,icon:"add",color:"success"}))},setMenuSectionProp(n,o,i,s,a,l){e(c=>Ie(c,d=>{const u=et(d,n,o,i,s)?.button,m=u?.menu?.sections.find(f=>f.id===a);!u||!m||He(n,o,u)||Object.assign(m,l)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:a,detail:Object.keys(l).join(", "),icon:"edit",color:"info"}))},deleteMenuSection(n,o,i,s,a){e(l=>Ie(l,c=>{const d=et(c,n,o,i,s)?.button;!d?.menu||He(n,o,d)||(d.menu.sections=d.menu.sections.filter(u=>u.id!==a))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:a,detail:`menu of ${s}`,icon:"delete",color:"danger"}))},duplicateButton(n,o,i,s){e(a=>Ie(a,l=>{const c=et(l,n,o,i,s);if(c){const{group:d,button:u}=c;if(He(n,o,u))return;const m=ro(a),f=Rn(u.source?.labelToken)||jn(u.source?.labelToken,m),y={...yo(u,`${oi(u.id,ni())}_copy_${Date.now()}`,m),label:rt(u.kind)||f?u.label:`${u.label} (copy)`,sequence:u.sequence},x=bo(d,s),h=x?x.section.controls:d.buttons,S=h.findIndex(w=>w.id===s);h.splice(S+1,0,y);const v=new Set(Wo(a,n)?.controlIds??[]),b=new Set((a.baseline[n]?.tabs??[]).flatMap(w=>w.groups.flatMap(Ne)).map(w=>w.id));br(h,S+1,w=>w===y||v.has(w.id)||!b.has(w.id))}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:s,detail:i,icon:"copy",color:"info"}))},createButton({tabId:n,groupId:o,location:i,button:s}){e(a=>Ie(a,l=>{const d=l[i].tabs.find(u=>u.id===n)?.groups.find(u=>u.id===o);if(d){const u=new Set(d.buttons.map(x=>x.sequence)),m=Math.max(0,...d.buttons.map(x=>x.sequence))+10,f=s.sequence!==void 0&&!u.has(s.sequence)?s.sequence:m,y={...s,id:s.id??`new_${Date.now()}`,label:s.label??"New Button",kind:s.kind??"button",sequence:f,templateAlias:s.templateAlias??"o1",commandId:s.commandId??"",hidden:s.hidden??!1,oob:!1,custom:!0,managed:!1,origin:"unmanaged"};Kt(y.kind)&&!y.menu&&(y.menu=Yo(y.id)),d.buttons.push(y)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:s.label??"New Button",detail:o,icon:"add",color:"success"}))},createGroup({tabId:n,location:o,group:i}){e(s=>Ie(s,a=>{const l=a[o].tabs.find(c=>c.id===n);if(l){const c=a[o],d=o==="Application"?"global":c.entityLogicalName,u={id:i.id??pr(d,`${o}.${i.label??"New Group"}`,"Group",hn(s,a)),label:i.label??"New Group",sequence:i.sequence!==void 0&&!l.groups.some(m=>m.sequence===i.sequence)?i.sequence:Math.max(0,...l.groups.map(m=>m.sequence))+10,template:i.template??"Flexible2",buttons:i.buttons??[]};l.groups.push(u)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"added",target:i.label??"New Group",detail:n,icon:"add",color:"success"}))},renameGroup(n,o,i,s){e(a=>Ie(a,l=>{const d=l[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===i);d&&(d.label=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:i,detail:s,icon:"edit",color:"info"}))},duplicateGroup(n,o,i){let s=null;if(e(a=>Ie(a,l=>{const c=l[n].tabs.find(C=>C.id===o);if(!c)return;const d=c.groups.find(C=>C.id===i);if(!d)return;const u=`_copy_${Date.now()}`,m=ni(),f=ro(a),y=a.baseLanguageCode,x=d.source?.titleToken,h=x!==void 0&&Be(x,a.locLabels,y)===d.label?x:d.label,S=Rn(h)||jn(h,f),v={...JSON.parse(JSON.stringify(d)),id:`${oi(d.id,m)}${u}`,label:S?Be(h,a.locLabels,y):`${Be(d.label,a.locLabels,y)} (copy)`,source:S?{titleToken:h,attributes:{}}:void 0,description:void 0,sequence:d.sequence,buttons:d.buttons.map(C=>yo(C,`${oi(C.id,m)}${u}`,f))},b=c.groups.findIndex(C=>C.id===i);c.groups.splice(b+1,0,v);const w=new Set((a.baseline[n]?.tabs??[]).flatMap(C=>C.groups.map(I=>I.id)));br(c.groups,b+1,C=>C===v||!w.has(C.id)),S&&(s={copyId:v.id,title:h})},{ts:new Date().toISOString(),userId:"",userName:"You",op:"duplicated",target:i,detail:o,icon:"copy",color:"info"})),s){const{copyId:a,title:l}=s;ne.getState().logInfo("ribbon",`Duplicate group ${i}: the copy ${a} keeps its title ${l}, which comes from ${Rn(l)?"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,i,s){e(a=>Ie(a,l=>{const d=l[n].tabs.find(u=>u.id===o)?.groups.find(u=>u.id===i);d&&(d.template=s)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:i,detail:`template → ${s}`,icon:"edit",color:"info"}))},deleteGroup(n,o,i){const s=t(),a=s.ribbons[n].tabs.find(l=>l.id===o)?.groups.find(l=>l.id===i);if(a&&!vs(a,s.baseline[n],Tn(s,n))){ne.getState().logWarn("ribbon",`Group "${a.label}" (${i}) was not deleted: only your own groups, with only your own buttons in them, can be deleted — hide its buttons instead.`);return}e(l=>Ie(l,c=>{const d=c[n].tabs.find(u=>u.id===o);d&&(d.groups=d.groups.filter(u=>u.id!==i))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"deleted",target:i,detail:o,icon:"delete",color:"danger"}))},createTab(n,o){e(i=>o.id&&hn(i,i.ribbons).has(o.id)?{}:Ie(i,s=>{const a=s[n],l=n==="Application"?"global":a.entityLogicalName,c=o.id??pr(l,`${n}.${o.label??"New Tab"}`,"Tab",hn(i,s)),d=dl({...o,id:c}),u={id:c,label:o.label??"New Tab",sequence:o.sequence!==void 0&&!a.tabs.some(m=>m.sequence===o.sequence)?o.sequence:Math.max(0,...a.tabs.map(m=>m.sequence))+10,commandId:d,tabDisplayRules:o.tabDisplayRules?.length?o.tabDisplayRules:ul(n,a.entityLogicalName,d),groups:[]};a.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,i){e(s=>Ie(s,a=>{const l=a[n].tabs.find(c=>c.id===o);l&&(l.label=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"renamed",target:o,detail:i,icon:"edit",color:"info"}))},deleteTab(n,o){const i=t(),s=i.ribbons[n].tabs.find(a=>a.id===o);if(s&&!Cl(s,i.baseline[n],Tn(i,n))){ne.getState().logWarn("ribbon",`Tab "${s.label}" (${o}) was not deleted: only your own tabs, with only your own groups and buttons in them, can be deleted.`);return}e(a=>Ie(a,l=>{l[n].tabs=l[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(i=>Ie(i,s=>{const a=s[n].tabs,l=o.map(m=>a.find(f=>f.id===m)).filter(m=>m!==void 0);s[n].tabs=l;const c=new Set(i.baseline[n]?.tabs.map(m=>m.id)??[]),d=new Set(Tn(i,n)??[]),u=m=>!c.has(m.id)||d.has(m.id);for(let m=1;m<l.length;m++)l[m].sequence>l[m-1].sequence||(u(l[m])?so(l,m,u):u(l[m-1])&&so(l,m-1,u));for(const m of l.filter(u)){const f=l.indexOf(m);if((l[f-1]?.sequence??-1/0)<m.sequence&&m.sequence<(l[f+1]?.sequence??1/0))continue;l.splice(f,1);const x=l.findIndex(h=>h.sequence>m.sequence);l.splice(x<0?l.length:x,0,m)}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"reordered",target:"Tabs",detail:n,icon:"arrow_sort",color:"info"}))},setTabDisplayRules(n,o,i){e(s=>Ie(s,a=>{const l=a[n].tabs.find(c=>c.id===o);l&&(l.tabDisplayRules=i)},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} display rules`,detail:`${i.length} rule(s)`,icon:"eye",color:"info"}))},setScaling(n,o,i){e(s=>Ie(s,a=>{const l=a[n];l.scalingByTab=l.scalingByTab??{},l.scalingByTab[o]={tabId:o,maxSizes:[...i.maxSizes],scales:[...i.scales]}},{ts:new Date().toISOString(),userId:"",userName:"You",op:"edited",target:`${o} scaling`,detail:`${i.maxSizes.length} MaxSize, ${i.scales.length} Scale`,icon:"resize",color:"info"}))},hideOobButton(n,o,i,s){e(a=>Ie(a,l=>{const c=et(l,n,o,i,s)?.button;c&&(He(n,o,c)||(c.hidden=!0))},{ts:new Date().toISOString(),userId:"",userName:"You",op:"hid",target:s,detail:i,icon:"eye_off",color:"warn"}))},customizeOobButton(n,o,i,s){e(a=>Ie(a,l=>{const c=et(l,n,o,i,s)?.button;if(c){if(He(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:s,detail:"OOB override",icon:"edit",color:"info"}))},customiseButton(n,o,i,s,a){const l=t(),c=l.ribbons[n].tabs.find(v=>v.id===o)?.groups.find(v=>v.id===i)?.buttons.find(v=>v.id===s);if(!c||!Ns(n,o,c))return null;const d=hn(l,l.ribbons),u=`${(a||"new").trim()}.${c.id}`;let m=u;for(let v=2;d.has(m);v++)m=`${u}.${v}`;const f=[],y=[],x=ro(l),h=[[c.source?.labelToken,Mo(m)],[c.source?.tooltipTitleToken,Bo(m)],[c.source?.tooltipBodyToken,zo(m)]];for(const[v,b]of h){if(!v||!wo.test(v))continue;const w=l.locLabels.find(C=>C.id===v.replace(wo,""));w?f.push({id:b,titles:w.titles.map(C=>({...C}))}):jn(v,x)&&y.push(v)}y.length>0&&ne.getState().logInfo("ribbon",`Customise button ${c.id}: ${y.join(", ")} ${y.length===1?"is":"are"} defined by another solution, so the copy ${m} uses ${y.length===1?"it":"them"} too. Edit the copy's text to give it a label of its own.`);const S=new Set(f.map(v=>v.id));return e(v=>{const b=We(v.ribbons),w=b[n].tabs.find(R=>R.id===o)?.groups.find(R=>R.id===i),C=w?.buttons.findIndex(R=>R.id===s)??-1;if(!w||C<0)return{};const I=w.buttons[C],$={...I,id:m,source:Hh(I.source,x),hidden:!1,custom:!0,oob:!1,managed:!1,origin:"unmanaged",solutionName:void 0,publisherName:void 0},j=w.buttons[C+1]?.sequence;return(j===void 0||I.sequence+1<j)&&($.sequence=I.sequence+1),I.hidden=!0,w.buttons.splice(C+1,0,$),Oe(v,{ribbons:b,...f.length>0?{locLabels:[...v.locLabels.filter(R=>!S.has(R.id)),...f]}:{}},Ce("customised",s,`copied to ${m}, original hidden`+(y.length>0?" (keeps another solution's labels)":""),"copy"))}),m},customiseCommand(n){const o=t();return!o.commands.some(i=>i.id===n)||o.reloadRequiredCommandIds.includes(n)?!1:(e(i=>Oe(i,{customisedCommandIds:[...i.customisedCommandIds.filter(s=>s!==n),n],uncustomisedCommandIds:si(i.uncustomisedCommandIds,n)},Ce("customised",n,"command copied to your layer on publish","code"))),!0)},uncustomiseCommand(n,o){e(i=>Oe(i,{commands:yr(i,n),customisedCommandIds:i.customisedCommandIds.filter(s=>s!==n),uncustomisedCommandIds:{...si(i.uncustomisedCommandIds,n),[o]:[...i.uncustomisedCommandIds[o].filter(s=>s!==n),n]}},Ce("uncustomised",n,`command removed from the ${o==="entity"?"table's":"application ribbon's"} layer on publish`,"arrow_undo")))},discardCommandChanges(n){const o=t(),i=yr(o,n);(i!==o.commands||o.customisedCommandIds.includes(n)||o.uncustomisedCommandIds.entity.includes(n)||o.uncustomisedCommandIds.application.includes(n))&&e(a=>Oe(a,{commands:i,customisedCommandIds:a.customisedCommandIds.filter(l=>l!==n),uncustomisedCommandIds:si(a.uncustomisedCommandIds,n)},Ce("discarded",n,"command changes","arrow_undo")))},setOpenRecordOverride(n,o,i){if(!$l.includes(n))return!1;const s=t(),a=s.ribbons[n],l=Tl(a);if(o){if(l.length>0)return!0;const c=Al(a);if(!c)return!1;const d=hn(s,s.ribbons);for(const m of s.commands)d.add(m.id);const{id:u}=jl(i,a.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 ${Pe} action for the selected row, as opening a row does.`,kind:"button",templateAlias:"o1",commandId:Pe,hidden:!1,oob:!1,custom:!0,managed:!1}}),t().commands.some(m=>m.id===Pe)||t().upsertCommand(Lh())}),!0}return l.length===0?!0:l.some(c=>kl(c)!=="yours")?!1:(t().batch(()=>{for(const u of l)t().deleteButton(n,u.tabId,u.groupId,u.button.id);const c=t();!Object.values(c.ribbons).some(u=>$s(u).length>0)&&!c.baselineCommands.some(u=>u.id===Pe)&&e(u=>Oe(u,{commands:u.commands.filter(m=>m.id!==Pe)},Ce("removed",Pe,"grid open override","delete","danger")))}),!0)},hideWithDisplayRules(n){const o=n?t().commands.find(s=>s.id===n):void 0;if(!o)return!1;const i=[...o.displayRules];for(const s of Fh)i.includes(s)||i.push(s);return e(s=>{const a=gn(s.commands,{...o,displayRules:i});return a?Oe(s,{commands:a},Ce("hid",o.id,"with display rules","eye_off","warn")):s}),!0},upsertCommand(n){e(o=>{const i=gn(o.commands,n);if(!i)return o;const s=i.length>o.commands.length;return Oe(o,{commands:i},s?Ce("added",n.id,"command","add","success"):Ce("edited",n.id,"command","edit"),s?void 0:`command:${n.id}`)})},renameCommandId(n,o){const i=t();return!n||!o||n===o?!0:i.commands.some(s=>s.id===o)?!1:(e(s=>{const a=We(s.ribbons);for(const c of Object.keys(a))for(const d of a[c].tabs)for(const u of d.groups)for(const m of Ne(u))m.commandId===n&&(m.commandId=o),m.source?.xml&&(m.source.xml=Cf(m.source.xml,n,o));const l=s.commands.map(c=>c.id===n?{...c,id:o}:c);return Oe(s,{ribbons:a,commands:l},Ce("renamed",n,`command -> ${o}`,"edit"))}),!0)},upsertDisplayRule(n){e(o=>{const i=gn(o.displayRules,n);if(!i)return o;const s=i.length>o.displayRules.length;return Oe(o,{displayRules:i},s?Ce("added",n.id,"display rule","add","success"):Ce("edited",n.id,"display rule","edit"),s?void 0:`displayRule:${n.id}`)})},renameDisplayRuleId(n,o){const i=t();return!n||!o||n===o?!0:i.displayRules.some(s=>s.id===o)?!1:(e(s=>{const a=s.displayRules.map(c=>c.id===n?{...c,id:o}:c),l=s.commands.map(c=>({...c,displayRules:c.displayRules.map(d=>d===n?o:d)}));return Oe(s,{displayRules:a,commands:l},Ce("renamed",n,`display rule -> ${o}`,"edit"))}),!0)},upsertEnableRule(n){e(o=>{const i=gn(o.enableRules,n);if(!i)return o;const s=i.length>o.enableRules.length;return Oe(o,{enableRules:i},s?Ce("added",n.id,"enable rule","add","success"):Ce("edited",n.id,"enable rule","edit"),s?void 0:`enableRule:${n.id}`)})},renameEnableRuleId(n,o){const i=t();return!n||!o||n===o?!0:i.enableRules.some(s=>s.id===o)?!1:(e(s=>{const a=s.enableRules.map(c=>c.id===n?{...c,id:o}:c),l=s.commands.map(c=>({...c,enableRules:c.enableRules.map(d=>d===n?o:d)}));return Oe(s,{enableRules:a,commands:l},Ce("renamed",n,`enable rule -> ${o}`,"edit"))}),!0)},upsertLocLabel(n){e(o=>{const i=gn(o.locLabels,n);return i?Oe(o,{locLabels:i},Ce("edited",n.id,"label","translate"),`locLabel:${n.id}`):o})},setLayerHideUnhidden(n,o,i){e(s=>{if(s.pendingUnhides[n].includes(o)===i)return s;const a=s.pendingUnhides[n].filter(l=>l!==o);return i&&a.push(o),Oe(s,{pendingUnhides:{...s.pendingUnhides,[n]:a}},i?Ce("un-hid",o,"on publish","eye"):Ce("kept hidden",o,"by customizations","eye_off"))})},setOrphanDeleted(n,o,i){e(s=>{const a=s.orphans[n].find(c=>c.id===o);if(!a||i&&a.recentPublish?.published||s.pendingOrphanDeletes[n].includes(o)===i)return s;const l=s.pendingOrphanDeletes[n].filter(c=>c!==o);return i&&l.push(o),Oe(s,{pendingOrphanDeletes:{...s.pendingOrphanDeletes,[n]:l}},i?Ce("deleted",o,"not on the canvas — removed on publish","delete","danger"):Ce("kept",o,"not on the canvas","arrow_undo"))})},setLayerSnapshot(n,o){e(i=>({layers:{...i.layers,[n]:o}}))},markPublished(n,o){e(i=>{const s=Object.keys(i.ribbons),a=n??s,l=We(i.baseline),c=We(i.ribbons);let d=i.locLabels,u=i.baselineLocLabels;const m=(N,M)=>[...N.filter(k=>!M.some(B=>B.id===k.id)),...M];for(const[N,M]of Object.entries(o??{})){const k=N==="entity"?gr:["Application"];for(const G of k)a.includes(G)&&Mf(c[G],M);const B=Hi(M);d=m(d,B),u=m(u,JSON.parse(JSON.stringify(B)))}for(const N of a)l[N]=We(c)[N];const f=s.every(N=>a.includes(N)),y={...i.layers},x={...i.pendingUnhides},h={entity:[],application:[]},S=[["entity",gr.every(N=>a.includes(N))],["application",a.includes("Application")]];for(const[N,M]of S){const k=o?.[N];if(!M||!k)continue;const B=y[N],G=(X,Q)=>[...new Set([...X,...Q])];y[N]=B?{...B,containerIds:G(B.containerIds,nl(k)),controlIds:G(B.controlIds,go(k)),locLabelIds:G(B.locLabelIds,new Set(k.locLabels.keys()))}:vo(k)}for(const[N,M]of S){if(!M||x[N].length===0)continue;const k=y[N];k&&(y[N]={...k,hides:k.hides.filter(B=>!x[N].includes(B.location))}),h[N]=x[N],x[N]=[]}const v={...i.orphans},b={...i.pendingOrphanDeletes},w={entity:[],application:[]};for(const[N,M]of S)!M||b[N].length===0||(v[N]=v[N].filter(k=>!b[N].includes(k.id)),w[N]=b[N],b[N]=[]);const C={...i.uncustomisedCommandIds},I=[...i.reloadRequiredCommandIds],$={entity:[],application:[]};for(const[N,M]of S)if(M){for(const k of C[N])I.includes(k)||I.push(k);$[N]=C[N],C[N]=[]}const j=(N,M)=>({entity:N.entity.filter(k=>!M.entity.includes(k)),application:N.application.filter(k=>!M.application.includes(k))}),R=N=>({...N,snapshot:{...N.snapshot,pendingUnhides:j(N.snapshot.pendingUnhides,h),pendingOrphanDeletes:j(N.snapshot.pendingOrphanDeletes??ti,w),uncustomisedCommandIds:j(N.snapshot.uncustomisedCommandIds,$)}}),T=[h,$,w].reduce((N,M)=>N+M.entity.length+M.application.length,0)>0,A=i.past.map((N,M)=>{const k=T?R(N):N;return M===i.past.length-1&&k.coalesceKey?{...k,coalesceKey:void 0}:k}),W={ribbons:c,locLabels:d,baselineLocLabels:u,baseline:l,layers:y,pendingUnhides:x,uncustomisedCommandIds:C,orphans:v,pendingOrphanDeletes:b,...f?{baselineCommands:JSON.parse(JSON.stringify(i.commands)),baselineEnableRules:JSON.parse(JSON.stringify(i.enableRules)),baselineDisplayRules:JSON.parse(JSON.stringify(i.displayRules)),baselineLocLabels:JSON.parse(JSON.stringify(d)),customisedCommandIds:[]}:{}},D=io({...i,...W});return{...W,past:A,future:T?i.future.map(R):i.future,reloadRequiredCommandIds:I,mutationsSincePublish:D?Math.max(1,i.mutationsSincePublish):0}})}})));cf(()=>{E.getState().resetWorkspace(),te.getState().clearSelection()});var $e=Uint8Array,Xe=Uint16Array,Ts=Int32Array,Ho=new $e([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]),Go=new $e([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]),Gi=new $e([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ol=function(e,t){for(var n=new Xe(31),o=0;o<31;++o)n[o]=t+=1<<e[o-1];for(var i=new Ts(n[30]),o=1;o<30;++o)for(var s=n[o];s<n[o+1];++s)i[s]=s-n[o]<<5|o;return{b:n,r:i}},Ml=Ol(Ho,2),Bl=Ml.b,Ui=Ml.r;Bl[28]=258,Ui[258]=28;var zl=Ol(Go,0),Gh=zl.b,xr=zl.r,Xi=new Xe(32768);for(var xe=0;xe<32768;++xe){var xt=(xe&43690)>>1|(xe&21845)<<1;xt=(xt&52428)>>2|(xt&13107)<<2,xt=(xt&61680)>>4|(xt&3855)<<4,Xi[xe]=((xt&65280)>>8|(xt&255)<<8)>>1}var mt=(function(e,t,n){for(var o=e.length,i=0,s=new Xe(t);i<o;++i)e[i]&&++s[e[i]-1];var a=new Xe(t);for(i=1;i<t;++i)a[i]=a[i-1]+s[i-1]<<1;var l;if(n){l=new Xe(1<<t);var c=15-t;for(i=0;i<o;++i)if(e[i])for(var d=i<<4|e[i],u=t-e[i],m=a[e[i]-1]++<<u,f=m|(1<<u)-1;m<=f;++m)l[Xi[m]>>c]=d}else for(l=new Xe(o),i=0;i<o;++i)e[i]&&(l[i]=Xi[a[e[i]-1]++]>>15-e[i]);return l}),Rt=new $e(288);for(var xe=0;xe<144;++xe)Rt[xe]=8;for(var xe=144;xe<256;++xe)Rt[xe]=9;for(var xe=256;xe<280;++xe)Rt[xe]=7;for(var xe=280;xe<288;++xe)Rt[xe]=8;var On=new $e(32);for(var xe=0;xe<32;++xe)On[xe]=5;var Uh=mt(Rt,9,0),Xh=mt(Rt,9,1),Vh=mt(On,5,0),Kh=mt(On,5,1),ri=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},tt=function(e,t,n){var o=t/8|0;return(e[o]|e[o+1]<<8)>>(t&7)&n},ai=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},ks=function(e){return(e+7)/8|0},_n=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new $e(e.subarray(t,n))},Jh=["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"],Le=function(e,t,n){var o=new Error(t||Jh[e]);if(o.code=e,Error.captureStackTrace&&Error.captureStackTrace(o,Le),!n)throw o;return o},Yh=function(e,t,n,o){var i=e.length,s=o?o.length:0;if(!i||t.f&&!t.l)return n||new $e(0);var a=!n,l=a||t.i!=2,c=t.i;a&&(n=new $e(i*3));var d=function(le){var H=n.length;if(le>H){var P=new $e(Math.max(H*2,le));P.set(n),n=P}},u=t.f||0,m=t.p||0,f=t.b||0,y=t.l,x=t.d,h=t.m,S=t.n,v=i*8;do{if(!y){u=tt(e,m,1);var b=tt(e,m+1,3);if(m+=3,b)if(b==1)y=Xh,x=Kh,h=9,S=5;else if(b==2){var $=tt(e,m,31)+257,j=tt(e,m+10,15)+4,R=$+tt(e,m+5,31)+1;m+=14;for(var T=new $e(R),A=new $e(19),W=0;W<j;++W)A[Gi[W]]=tt(e,m+W*3,7);m+=j*3;for(var D=ri(A),N=(1<<D)-1,M=mt(A,D,1),W=0;W<R;){var k=M[tt(e,m,N)];m+=k&15;var w=k>>4;if(w<16)T[W++]=w;else{var B=0,G=0;for(w==16?(G=3+tt(e,m,3),m+=2,B=T[W-1]):w==17?(G=3+tt(e,m,7),m+=3):w==18&&(G=11+tt(e,m,127),m+=7);G--;)T[W++]=B}}var X=T.subarray(0,$),Q=T.subarray($);h=ri(X),S=ri(Q),y=mt(X,h,1),x=mt(Q,S,1)}else Le(1);else{var w=ks(m)+4,C=e[w-4]|e[w-3]<<8,I=w+C;if(I>i){c&&Le(0);break}l&&d(f+C),n.set(e.subarray(w,I),f),t.b=f+=C,t.p=m=I*8,t.f=u;continue}if(m>v){c&&Le(0);break}}l&&d(f+131072);for(var ie=(1<<h)-1,F=(1<<S)-1,_=m;;_=m){var B=y[ai(e,m)&ie],L=B>>4;if(m+=B&15,m>v){c&&Le(0);break}if(B||Le(2),L<256)n[f++]=L;else if(L==256){_=m,y=null;break}else{var U=L-254;if(L>264){var W=L-257,g=Ho[W];U=tt(e,m,(1<<g)-1)+Bl[W],m+=g}var O=x[ai(e,m)&F],V=O>>4;O||Le(3),m+=O&15;var Q=Gh[V];if(V>3){var g=Go[V];Q+=ai(e,m)&(1<<g)-1,m+=g}if(m>v){c&&Le(0);break}l&&d(f+131072);var de=f+U;if(f<Q){var Se=s-Q,ve=Math.min(Q,de);for(Se+f<0&&Le(3);f<ve;++f)n[f]=o[Se+f]}for(;f<de;++f)n[f]=n[f-Q]}}t.l=y,t.p=_,t.b=f,t.f=u,y&&(u=1,t.m=h,t.d=x,t.n=S)}while(!u);return f!=n.length&&a?_n(n,0,f):n.subarray(0,f)},pt=function(e,t,n){n<<=t&7;var o=t/8|0;e[o]|=n,e[o+1]|=n>>8},bn=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},li=function(e,t){for(var n=[],o=0;o<e.length;++o)e[o]&&n.push({s:o,f:e[o]});var i=n.length,s=n.slice();if(!i)return{t:Pl,l:0};if(i==1){var a=new $e(n[0].s+1);return a[n[0].s]=1,{t:a,l:1}}n.sort(function(I,$){return I.f-$.f}),n.push({s:-1,f:25001});var l=n[0],c=n[1],d=0,u=1,m=2;for(n[0]={s:-1,f:l.f+c.f,l,r:c};u!=i-1;)l=n[n[d].f<n[m].f?d++:m++],c=n[d!=u&&n[d].f<n[m].f?d++:m++],n[u++]={s:-1,f:l.f+c.f,l,r:c};for(var f=s[0].s,o=1;o<i;++o)s[o].s>f&&(f=s[o].s);var y=new Xe(f+1),x=Vi(n[u-1],y,0);if(x>t){var o=0,h=0,S=x-t,v=1<<S;for(s.sort(function($,j){return y[j.s]-y[$.s]||$.f-j.f});o<i;++o){var b=s[o].s;if(y[b]>t)h+=v-(1<<x-y[b]),y[b]=t;else break}for(h>>=S;h>0;){var w=s[o].s;y[w]<t?h-=1<<t-y[w]++-1:++o}for(;o>=0&&h;--o){var C=s[o].s;y[C]==t&&(--y[C],++h)}x=t}return{t:new $e(y),l:x}},Vi=function(e,t,n){return e.s==-1?Math.max(Vi(e.l,t,n+1),Vi(e.r,t,n+1)):t[e.s]=n},Sr=function(e){for(var t=e.length;t&&!e[--t];);for(var n=new Xe(++t),o=0,i=e[0],s=1,a=function(c){n[o++]=c},l=1;l<=t;++l)if(e[l]==i&&l!=t)++s;else{if(!i&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(i),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(i);s=1,i=e[l]}return{c:n.subarray(0,o),n:t}},yn=function(e,t){for(var n=0,o=0;o<t.length;++o)n+=e[o]*t[o];return n},Ll=function(e,t,n){var o=n.length,i=ks(t+2);e[i]=o&255,e[i+1]=o>>8,e[i+2]=e[i]^255,e[i+3]=e[i+1]^255;for(var s=0;s<o;++s)e[i+s+4]=n[s];return(i+4+o)*8},vr=function(e,t,n,o,i,s,a,l,c,d,u){pt(t,u++,n),++i[256];for(var m=li(i,15),f=m.t,y=m.l,x=li(s,15),h=x.t,S=x.l,v=Sr(f),b=v.c,w=v.n,C=Sr(h),I=C.c,$=C.n,j=new Xe(19),R=0;R<b.length;++R)++j[b[R]&31];for(var R=0;R<I.length;++R)++j[I[R]&31];for(var T=li(j,7),A=T.t,W=T.l,D=19;D>4&&!A[Gi[D-1]];--D);var N=d+5<<3,M=yn(i,Rt)+yn(s,On)+a,k=yn(i,f)+yn(s,h)+a+14+3*D+yn(j,A)+2*j[16]+3*j[17]+7*j[18];if(c>=0&&N<=M&&N<=k)return Ll(t,u,e.subarray(c,c+d));var B,G,X,Q;if(pt(t,u,1+(k<M)),u+=2,k<M){B=mt(f,y,0),G=f,X=mt(h,S,0),Q=h;var ie=mt(A,W,0);pt(t,u,w-257),pt(t,u+5,$-1),pt(t,u+10,D-4),u+=14;for(var R=0;R<D;++R)pt(t,u+3*R,A[Gi[R]]);u+=3*D;for(var F=[b,I],_=0;_<2;++_)for(var L=F[_],R=0;R<L.length;++R){var U=L[R]&31;pt(t,u,ie[U]),u+=A[U],U>15&&(pt(t,u,L[R]>>5&127),u+=L[R]>>12)}}else B=Uh,G=Rt,X=Vh,Q=On;for(var R=0;R<l;++R){var g=o[R];if(g>255){var U=g>>18&31;bn(t,u,B[U+257]),u+=G[U+257],U>7&&(pt(t,u,g>>23&31),u+=Ho[U]);var O=g&31;bn(t,u,X[O]),u+=Q[O],O>3&&(bn(t,u,g>>5&8191),u+=Go[O])}else bn(t,u,B[g]),u+=G[g]}return bn(t,u,B[256]),u+G[256]},Zh=new Ts([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Pl=new $e(0),Qh=function(e,t,n,o,i,s){var a=s.z||e.length,l=new $e(o+a+5*(1+Math.ceil(a/7e3))+i),c=l.subarray(o,l.length-i),d=s.l,u=(s.r||0)&7;if(t){u&&(c[0]=s.r>>3);for(var m=Zh[t-1],f=m>>13,y=m&8191,x=(1<<n)-1,h=s.p||new Xe(32768),S=s.h||new Xe(x+1),v=Math.ceil(n/3),b=2*v,w=function(re){return(e[re]^e[re+1]<<v^e[re+2]<<b)&x},C=new Ts(25e3),I=new Xe(288),$=new Xe(32),j=0,R=0,T=s.i||0,A=0,W=s.w||0,D=0;T+2<a;++T){var N=w(T),M=T&32767,k=S[N];if(h[M]=k,S[N]=M,W<=T){var B=a-T;if((j>7e3||A>24576)&&(B>423||!d)){u=vr(e,c,0,C,I,$,R,A,D,T-D,u),A=j=R=0,D=T;for(var G=0;G<286;++G)I[G]=0;for(var G=0;G<30;++G)$[G]=0}var X=2,Q=0,ie=y,F=M-k&32767;if(B>2&&N==w(T-F))for(var _=Math.min(f,B)-1,L=Math.min(32767,T),U=Math.min(258,B);F<=L&&--ie&&M!=k;){if(e[T+X]==e[T+X-F]){for(var g=0;g<U&&e[T+g]==e[T+g-F];++g);if(g>X){if(X=g,Q=F,g>_)break;for(var O=Math.min(F,g-2),V=0,G=0;G<O;++G){var de=T-F+G&32767,Se=h[de],ve=de-Se&32767;ve>V&&(V=ve,k=de)}}}M=k,k=h[M],F+=M-k&32767}if(Q){C[A++]=268435456|Ui[X]<<18|xr[Q];var le=Ui[X]&31,H=xr[Q]&31;R+=Ho[le]+Go[H],++I[257+le],++$[H],W=T+X,++j}else C[A++]=e[T],++I[e[T]]}}for(T=Math.max(T,W);T<a;++T)C[A++]=e[T],++I[e[T]];u=vr(e,c,d,C,I,$,R,A,D,T-D,u),d||(s.r=u&7|c[u/8|0]<<3,u-=7,s.h=S,s.p=h,s.i=T,s.w=W)}else{for(var T=s.w||0;T<a+d;T+=65535){var P=T+65535;P>=a&&(c[u/8|0]=d,P=a),u=Ll(c,u+1,e.subarray(T,P))}s.i=a}return _n(l,0,o+ks(u)+i)},eg=(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})(),tg=function(){var e=-1;return{p:function(t){for(var n=e,o=0;o<t.length;++o)n=eg[n&255^t[o]]^n>>>8;e=n},d:function(){return~e}}},ng=function(e,t,n,o,i){if(!i&&(i={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),a=new $e(s.length+e.length);a.set(s),a.set(e,s.length),e=a,i.w=s.length}return Qh(e,t.level==null?6:t.level,t.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,n,o,i)},Fl=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},dt=function(e,t){return e[t]|e[t+1]<<8},Ke=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},ci=function(e,t){return Ke(e,t)+Ke(e,t+4)*4294967296},Me=function(e,t,n){for(;n;++t)e[t]=n,n>>>=8};function _l(e,t){return ng(e,t||{},0,0)}function ql(e,t){return Yh(e,{i:2},t&&t.out,t&&t.dictionary)}var Wl=function(e,t,n,o){for(var i in e){var s=e[i],a=t+i,l=o;Array.isArray(s)&&(l=Fl(o,s[1]),s=s[0]),ArrayBuffer.isView(s)?n[a]=[s,l]:(n[a+="/"]=[new $e(0),l],Wl(s,a,n,o))}},wr=typeof TextEncoder<"u"&&new TextEncoder,Ki=typeof TextDecoder<"u"&&new TextDecoder,og=0;try{Ki.decode(Pl,{stream:!0}),og=1}catch{}var ig=function(e){for(var t="",n=0;;){var o=e[n++],i=(o>127)+(o>223)+(o>239);if(n+i>e.length)return{s:t,r:_n(e,n-1)};i?i==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)):i&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 Co(e,t){if(t){for(var n=new $e(e.length),o=0;o<e.length;++o)n[o]=e.charCodeAt(o);return n}if(wr)return wr.encode(e);for(var i=e.length,s=new $e(e.length+(e.length>>1)),a=0,l=function(u){s[a++]=u},o=0;o<i;++o){if(a+5>s.length){var c=new $e(a+8+(i-o<<1));c.set(s),s=c}var d=e.charCodeAt(o);d<128||t?l(d):d<2048?(l(192|d>>6),l(128|d&63)):d>55295&&d<57344?(d=65536+(d&1047552)|e.charCodeAt(++o)&1023,l(240|d>>18),l(128|d>>12&63),l(128|d>>6&63),l(128|d&63)):(l(224|d>>12),l(128|d>>6&63),l(128|d&63))}return _n(s,0,a)}function Uo(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(Ki)return Ki.decode(e);var i=ig(e),s=i.s,n=i.r;return n.length&&Le(8),s}}var sg=function(e,t){return t+30+dt(e,t+26)+dt(e,t+28)},rg=function(e,t,n){var o=dt(e,t+28),i=dt(e,t+30),s=Uo(e.subarray(t+46,t+46+o),!(dt(e,t+8)&2048)),a=t+46+o,l=ag(e,a,i,n,Ke(e,t+20),Ke(e,t+24),Ke(e,t+42)),c=l[0],d=l[1],u=l[2];return[dt(e,t+10),c,d,s,a+i+dt(e,t+32),u]},ag=function(e,t,n,o,i,s,a){var l=i==4294967295,c=s==4294967295,d=a==4294967295,u=t+n,m=l+c+d;if(o&&m){for(;t+4<u;t+=4+dt(e,t+2))if(dt(e,t)==1)return[l?ci(e,t+4+8*c):i,c?ci(e,t+4):s,d?ci(e,t+4+8*(c+l)):a,1];o<2&&Le(13)}return[i,s,a,0]},Ji=function(e){var t=0;if(e)for(var n in e){var o=e[n].length;o>65535&&Le(9),t+=o+4}return t},Cr=function(e,t,n,o,i,s,a,l){var c=o.length,d=n.extra,u=l&&l.length,m=Ji(d);Me(e,t,a!=null?33639248:67324752),t+=4,a!=null&&(e[t++]=20,e[t++]=n.os),e[t]=20,t+=2,e[t++]=n.flag<<1|(s<0&&8),e[t++]=i&&8,e[t++]=n.compression&255,e[t++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),y=f.getFullYear()-1980;if((y<0||y>119)&&Le(10),Me(e,t,y<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),t+=4,s!=-1&&(Me(e,t,n.crc),Me(e,t+4,s<0?-s-2:s),Me(e,t+8,n.size)),Me(e,t+12,c),Me(e,t+14,m),t+=16,a!=null&&(Me(e,t,u),Me(e,t+6,n.attrs),Me(e,t+10,a),t+=14),e.set(o,t),t+=c,m)for(var x in d){var h=d[x],S=h.length;Me(e,t,+x),Me(e,t+2,S),e.set(h,t+4),t+=4+S}return u&&(e.set(l,t),t+=u),t},lg=function(e,t,n,o,i){Me(e,t,101010256),Me(e,t+8,n),Me(e,t+10,n),Me(e,t+12,o),Me(e,t+16,i)};function bv(e,t){t||(t={});var n={},o=[];Wl(e,"",n,t);var i=0,s=0;for(var a in n){var l=n[a],c=l[0],d=l[1],u=d.level==0?0:8,m=Co(a),f=m.length,y=d.comment,x=y&&Co(y),h=x&&x.length,S=Ji(d.extra);f>65535&&Le(11);var v=u?_l(c,d):c,b=v.length,w=tg();w.p(c),o.push(Fl(d,{size:c.length,crc:w.d(),c:v,f:m,m:x,u:f!=a.length||x&&y.length!=h,o:i,compression:u})),i+=30+f+S+b,s+=76+2*(f+S)+(h||0)+b}for(var C=new $e(s+22),I=i,$=s-i,j=0;j<o.length;++j){var m=o[j];Cr(C,m.o,m,m.f,m.u,m.c.length);var R=30+m.f.length+Ji(m.extra);C.set(m.c,m.o+R),Cr(C,i,m,m.f,m.u,m.c.length,m.o,m.m),i+=16+R+(m.m?m.m.length:0)}return lg(C,i,o.length,$,I),C}function cg(e,t){for(var n={},o=e.length-22;Ke(e,o)!=101010256;--o)(!o||e.length-o>65558)&&Le(13);var i=dt(e,o+8);if(!i)return{};var s=Ke(e,o+16),a=Ke(e,o-20)==117853008;if(a){var l=Ke(e,o-12);a=Ke(e,l)==101075792,a&&(i=Ke(e,l+32),s=Ke(e,l+48))}for(var c=0;c<i;++c){var d=rg(e,s,a),u=d[0],m=d[1],f=d[2],y=d[3],x=d[4],h=d[5],S=sg(e,h);s=x,u?u==8?n[y]=ql(e.subarray(S,S+m),{out:new $e(f)}):Le(14,"unknown compression type "+u):n[y]=_n(e,S,S+m)}return n}const As=4,Hl=30,Gl=`cbs:draft:v${As}:`,dg=["cbs:ribbon:","cbs:draft:"],Zt={commands:"baselineCommands",enableRules:"baselineEnableRules",displayRules:"baselineDisplayRules",locLabels:"baselineLocLabels"},Ds=["HomepageGrid","SubGrid","Form","Application"];function Ul(e){return{orgUrl:e.orgUrl.trim().replace(/\/+$/,"").toLowerCase(),solutionId:e.solutionId.trim().toLowerCase(),entityLogicalName:e.entityLogicalName.trim().toLowerCase()}}function Mn(e){const t=Ul(e);return`${Gl}${encodeURIComponent(t.orgUrl)}:${encodeURIComponent(t.solutionId)}:${encodeURIComponent(t.entityLogicalName)}`}function Yi(e,t){return!e||!t?!1:Mn(e)===Mn(t)}function ug(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 Vn=null;function Xl(e){const t=[e.baseline,e.baselineCommands,e.baselineEnableRules,e.baselineDisplayRules,e.baselineLocLabels,e.layers,e.baseLanguageCode];if(Vn&&Vn.of.every((o,i)=>o===t[i]))return Vn.value;const n=ug(JSON.stringify(t));return Vn={of:t,value:n},n}const Ir=new WeakMap;function Kn(e){let t=Ir.get(e);return t===void 0&&(t=JSON.stringify(e),Ir.set(e,t)),t}const Ut=e=>JSON.parse(JSON.stringify(e)),qn={},Vl={list:"groups",child:{list:"buttons",child:qn}};function Kl(e){const t=new Map;for(const n of e)t.set(n.id,t.has(n.id)?null:n);return t}function di(e,t,n){if(!n.list||!Array.isArray(e[n.list]))return e;const o=t?.[n.list]??[];return{...e,[n.list]:Zi(e[n.list],o,n.child??qn)}}function Jn(e,t,n){if(!n.list||e[n.list]===void 0)return e;const o=t?.[n.list]??[];return{...e,[n.list]:Qi(e[n.list],o,n.child??qn)}}function Zi(e,t,n){const o=Kl(t),i=new Set(e.map(s=>s.id));if(i.size===e.length&&o.size===t.length){const s=t.filter(l=>i.has(l.id)),a=e.slice(s.length);if(s.every((l,c)=>e[c].id===l.id)&&a.every(l=>!o.has(l.id)))return{set:e.slice(0,s.length).filter(l=>Kn(o.get(l.id))!==Kn(l)).map(l=>di(l,o.get(l.id),n)),drop:t.filter(l=>!i.has(l.id)).map(l=>l.id),add:a.map(l=>di(l,void 0,n))}}return e.map(s=>{const a=o.get(s.id)??void 0;return a&&Kn(a)===Kn(s)?s.id:di(s,a,n)})}function Qi(e,t,n){const o=Kl(t);if(Array.isArray(e)){const c=[];for(const d of e)if(typeof d!="string")c.push(Jn(d,o.get(d.id)??void 0,n));else{const u=o.get(d);u&&c.push(Ut(u))}return c}const i=new Set(e.drop),s=new Map(e.set.map(c=>[c.id,c])),a=[];for(const c of e.add)o.has(c.id)?s.set(c.id,c):a.push(c);const l=new Set(t.map(c=>c.id));return[...t.filter(c=>!i.has(c.id)).map(c=>s.has(c.id)?Jn(s.get(c.id),c,n):Ut(c)),...[...s.values()].filter(c=>!l.has(c.id)).map(c=>Jn(c,void 0,n)),...a.map(c=>Jn(c,void 0,n))]}const mg=e=>!Array.isArray(e)&&e.set.length+e.drop.length+e.add.length===0,Io=e=>e;function pg(e){const t=ct(e),n={};for(const s of Ds){const a=t.ribbons[s],l=e.baseline[s];if(!a)continue;const c=Zi(a.tabs,l?.tabs??[],Vl),d={};for(const[m,f]of Object.entries(a))m!=="tabs"&&JSON.stringify(f)!==JSON.stringify(l?.[m])&&(d[m]=f);const u=Object.keys(l??{}).filter(m=>m!=="tabs"&&!(m in a));(!mg(c)||Object.keys(d).length+u.length>0)&&(n[s]={props:d,unset:u,tabs:c})}const o={};for(const s of Object.keys(Zt))o[s]=Zi(Io(t[s]),Io(e[Zt[s]]),qn);const i={...t};delete i.ribbons;for(const s of Object.keys(Zt))delete i[s];return{ribbons:n,lists:o,other:i}}function fg(e,t){const{delta:n}=e,o={};for(const s of Ds){const a=n.ribbons[s],l=t.baseline[s];if(!a){o[s]=Ut(l);continue}const c={...Ut(l),...Ut(a.props)};for(const d of a.unset)delete c[d];c.tabs=Qi(a.tabs,Io(l?.tabs??[]),Vl),o[s]=c}const i={...ct(t),...Ut(n.other),ribbons:o};for(const s of Object.keys(Zt))i[s]=Qi(n.lists[s],Io(t[Zt[s]]),qn);return i}function hg(e){return btoa(Uo(_l(Co(JSON.stringify(e)),{level:9}),!0))}function gg(e){return JSON.parse(Uo(ql(Co(atob(e),!0))))}const Ct=e=>Array.isArray(e),ui=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Rr=e=>{if(Ct(e))return!0;const t=e;return!!t&&typeof t=="object"&&Ct(t.set)&&Ct(t.drop)&&Ct(t.add)},bg=e=>!!e&&typeof e=="object"&&Ct(e.entity)&&Ct(e.application);function yg(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(([i,s])=>Ds.includes(i)&&Rr(s?.tabs)&&ui(s?.props)&&Ct(s?.unset))&&ui(t.lists)&&Object.keys(Zt).every(i=>Rr(t.lists[i]))&&ui(t.other)&&["pendingUnhides","uncustomisedCommandIds"].every(i=>!(i in o)||bg(o[i]))&&(!("customisedCommandIds"in o)||Ct(o.customisedCommandIds))}function xg(e,t){try{const n={format:As,key:Ul(e),savedAt:new Date().toISOString(),baselineFingerprint:Xl(t),data:hg(pg(t))};return localStorage.setItem(Mn(e),JSON.stringify(n)),n.savedAt}catch{return null}}function Sg(e){const t=Mn(e);let n;try{n=localStorage.getItem(t)}catch{return null}if(!n)return null;try{const o=JSON.parse(n);if(o.format===As&&Yi(o.key,e)&&typeof o.data=="string"){const i=gg(o.data);if(yg(i)){const s=o;return{format:s.format,key:s.key,savedAt:s.savedAt,baselineFingerprint:s.baselineFingerprint,delta:i}}}}catch{}return Ro(e),null}function Ro(e){try{localStorage.removeItem(Mn(e))}catch{}}function vg(e,t){try{const n=Date.parse(JSON.parse(e??"").savedAt??"");return!(t-n<=Hl*864e5)}catch{return!0}}function wg(e=Date.now()){const t=[];try{for(let n=0;n<localStorage.length;n++){const o=localStorage.key(n);o&&(o.startsWith(Gl)?vg(localStorage.getItem(o),e):dg.some(i=>o.startsWith(i)))&&t.push(o)}for(const n of t)localStorage.removeItem(n)}catch{return 0}return t.length}function Jl(e){return e.mutationsSincePublish>0||io(e)}function ao(){return we.getState().target!==null&&Jl(E.getState())}let Et=null;function kt(e){const{target:t,pending:n}=we.getState();if(!t||n)return!0;const o=e.ribbons.HomepageGrid.entityLogicalName;if(o&&o.toLowerCase()!==t.entityLogicalName.toLowerCase())return!0;let i=!0;if(!Jl(e))Et!==null&&e.future.some(l=>l.op==="restored"&&l.ts===Et)||(Ro(t),we.setState({lastSavedAt:null}));else{const a=xg(t,e);i=a!==null,a&&we.setState({lastSavedAt:a})}const{saveFailed:s}=we.getState();return!i&&!s&&ne.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."),i===s&&we.setState({saveFailed:!i}),i}const Cg=["mutationsSincePublish","ribbons","commands","enableRules","displayRules","locLabels","pendingUnhides","customisedCommandIds","uncustomisedCommandIds","baseline","baselineCommands","baselineEnableRules","baselineDisplayRules","baselineLocLabels","layers"];function Ig(){return E.subscribe((e,t)=>{e.baseline!==t.baseline&&(Et=null),!Cg.every(n=>e[n]===t[n])&&kt(e)})}function Rg(e){const t=oe.getState();return{orgUrl:t.connectionUrl,solutionId:t.activeSolution?.id??"",entityLogicalName:e}}function jg(){const e=E.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 mi(e){we.setState({target:null,pending:null,pendingBaselineChanged:!1});const t=oe.getState();e.kind==="entity"?t.setActiveEntity(e.entity):t.setActiveSolution(e.solution)}const we=Nt()((e,t)=>({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null,beginLoad(){Et=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,saveFailed:!1,lastSavedAt:null})},workspaceLoaded(n){const o=Sg(n);Et=null,e({target:n,pending:o,restoreError:null,lastSavedAt:o?.savedAt??null,pendingBaselineChanged:!!o&&o.baselineFingerprint!==Xl(E.getState())})},restoreDraft(){const{target:n,pending:o}=t();if(!n||!o||!Yi(n,o.key))return!1;const i=E.getState();try{i.restoreWorkspace(fg(o,i),`saved ${new Date(o.savedAt).toLocaleString()}`)}catch(l){const c=l instanceof Error?l.message:String(l);return ne.getState().logError("ribbon",`The unsaved changes saved ${o.savedAt} couldn't be restored: ${c}`),e({restoreError:c}),!1}const s=E.getState(),a=s.past[s.past.length-1];return s.past.length>i.past.length&&a?.op==="restored"&&(Et=a.ts),e({pending:null,pendingBaselineChanged:!1,restoreError:null}),kt(s),!0},discardDraft(){const{target:n,pending:o}=t();o&&(Ro(o.key),e({pending:null,pendingBaselineChanged:!1,restoreError:null,lastSavedAt:null}),n&&Yi(n,o.key)&&kt(E.getState()))},requestEntitySwitch(n){oe.getState().activeEntity?.logicalName!==n.logicalName&&(ao()?(kt(E.getState()),e({pendingSwitch:{kind:"entity",entity:n}})):mi({kind:"entity",entity:n}))},requestSolutionSwitch(n){oe.getState().activeSolution?.id!==n.id&&(ao()?(kt(E.getState()),e({pendingSwitch:{kind:"solution",solution:n}})):mi({kind:"solution",solution:n}))},resolveSwitch(n){const{pendingSwitch:o,target:i,pending:s}=t();if(o){if(n==="cancel"){e({pendingSwitch:null});return}n==="keep"&&!kt(E.getState())||(n==="discard"&&i&&!s&&Ro(i),e({pendingSwitch:null,target:null,pending:null,pendingBaselineChanged:!1,saveFailed:!1}),jg(),mi(o))}},releaseForConnectionChange(){const n=ao(),o=n?kt(E.getState()):!1;return Et=null,e({target:null,pending:null,pendingBaselineChanged:!1,restoreError:null,pendingSwitch:null,saveFailed:!1,lastSavedAt:null}),{hadChanges:n,kept:o}}})),Yl=e=>e?.trim().toLowerCase()==="production",yv=e=>Yl(e),xv=(e,t)=>t.trim()!==""&&e.trim().toLowerCase()===t.trim().toLowerCase();function $g({prefix:e}){const t=oe(s=>s.connectionName),n=oe(s=>s.connectionUrl),o=oe(s=>s.environment);if(!t&&!n)return null;const i=Yl(o);return r.jsx(Ee,{content:n||t,relationship:"description",children:r.jsxs("span",{"data-testid":"environment-badge",style:{display:"inline-flex",alignItems:"center",gap:p.spacingHorizontalXS,minWidth:0},children:[e&&r.jsx(q,{size:200,wrap:!1,style:{color:p.colorNeutralForeground3},children:e}),r.jsx(q,{size:200,weight:"semibold",truncate:!0,wrap:!1,style:{maxWidth:180},children:t||n}),o&&r.jsx(ue,{size:"small",appearance:i?"filled":"tint",color:i?"warning":"informative",children:o})]})})}const jo=e=>e instanceof Error?e.message:String(e),Ng=3e3;function Tg(e,t){let n;const o=new Promise((i,s)=>{n=setTimeout(()=>s(new Error(`no answer in ${t/1e3} s`)),t)});return Promise.race([e,o]).finally(()=>clearTimeout(n))}async function Zl(e){const t=[],n=window.toolboxAPI?.utils?.copyToClipboard;if(n)try{return await Tg(n(e),Ng),{ok:!0}}catch(o){t.push(`host: ${jo(o)}`)}if(navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),{ok:!0}}catch(o){t.push(`browser: ${jo(o)}`)}return{ok:!1,error:t.join("; ")||"no clipboard is available here"}}async function Sv(e,t,n){const o=window.toolboxAPI?.fileSystem?.saveFile;if(o)try{const i=await o(e,t,n);return i?{ok:!0,path:i}:{ok:!1,canceled:!0}}catch(i){return{ok:!1,error:jo(i)}}try{const i=URL.createObjectURL(new Blob([t],{type:"application/xml"})),s=document.createElement("a");return s.href=i,s.download=e,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e4),{ok:!0}}catch(i){return{ok:!1,error:jo(i)}}}const kg=me({root:{height:"40px",display:"flex",alignItems:"center",gap:p.spacingHorizontalS,padding:`0 ${p.spacingHorizontalM}`,backgroundColor:p.colorNeutralBackground3,borderBottom:`1px solid ${p.colorNeutralStroke2}`,flexShrink:0},brand:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS,marginRight:p.spacingHorizontalS},brandMark:{width:"24px",height:"24px",borderRadius:"4px",backgroundColor:p.colorBrandBackground,display:"flex",alignItems:"center",justifyContent:"center"},spacer:{flex:1},sep:{width:"1px",height:"20px",backgroundColor:p.colorNeutralStroke2,margin:`0 ${p.spacingHorizontalXS}`},paletteButton:{height:"28px",minWidth:"260px","@media (max-width: 1100px)":{minWidth:"120px"},overflow:"hidden",whiteSpace:"nowrap",display:"flex",alignItems:"center",gap:p.spacingHorizontalS,padding:`0 ${p.spacingHorizontalS}`,border:`1px solid ${p.colorNeutralStroke1}`,borderRadius:p.borderRadiusMedium,backgroundColor:p.colorNeutralBackground1,cursor:"pointer",color:p.colorNeutralForeground3,fontSize:p.fontSizeBase200,"&:hover":{border:`1px solid ${p.colorNeutralStroke1Hover}`,backgroundColor:p.colorNeutralBackground1Hover}},kbd:{padding:"1px 4px",border:`1px solid ${p.colorNeutralStroke2}`,borderRadius:"3px",fontSize:p.fontSizeBase100,backgroundColor:p.colorNeutralBackground2},brandTitle:{whiteSpace:"nowrap","@media (max-width: 1100px)":{display:"none"}},solutionTrigger:{minWidth:0,flexShrink:1,whiteSpace:"nowrap",overflow:"hidden"},ellipsis:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},solutionPickerSurface:{padding:p.spacingHorizontalM,minWidth:"360px",display:"flex",flexDirection:"column",gap:p.spacingVerticalS},solutionPickerHint:{color:p.colorNeutralForeground3}});function Ag(){const e=kg(),t=E(b=>b.past),n=E(b=>b.future),o=E(b=>b.undo),i=E(b=>b.redo),s=oe(b=>b.solutions),a=oe(b=>b.activeSolution),l=we(b=>b.requestSolutionSwitch),c=ee(b=>b.openBulkPublish),d=ee(b=>b.openXmlDrawer),u=ee(b=>b.setCommandPaletteOpen),[m,f]=z.useState(!1),[y,x]=z.useState(""),h=z.useMemo(()=>s.filter(b=>!b.isManaged).map(b=>({value:b.id,children:b.friendlyName||b.uniqueName,searchText:`${b.friendlyName??""} ${b.uniqueName??""}`.toLowerCase(),solution:b})),[s]),S=fp(y,h,{optionToText:b=>b.searchText,filter:(b,w)=>b.includes(w.toLowerCase()),optionToReactKey:b=>b.value,renderOption:b=>r.jsx(gp,{value:b.value,text:b.solution.friendlyName??b.solution.uniqueName,children:r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[r.jsx(q,{size:200,weight:"semibold",children:b.solution.friendlyName||b.solution.uniqueName}),r.jsxs(q,{size:100,style:{color:p.colorNeutralForeground3},children:[b.solution.uniqueName," · v",b.solution.version,b.solution.publisherName?` · ${b.solution.publisherName}`:""]})]})},b.value),noOptionsMessage:s.length===0?"Loading solutions…":"No solutions match the filter."}),v=(b,w)=>{const C=s.find(I=>I.id===w.optionValue);C&&(l(C),f(!1),x(""))};return r.jsxs("header",{className:e.root,children:[r.jsxs("div",{className:e.brand,children:[r.jsx("div",{className:e.brandMark,children:r.jsx(q,{size:100,weight:"bold",style:{color:"white",lineHeight:1},children:"CBS"})}),r.jsx(q,{weight:"semibold",size:300,className:e.brandTitle,children:"Command Bar Studio"})]}),r.jsx("div",{className:e.sep}),r.jsx($g,{}),r.jsx("div",{className:e.sep}),r.jsxs(Ta,{open:m,onOpenChange:(b,w)=>f(w.open),positioning:"below-start",trapFocus:!0,children:[r.jsx(ka,{disableButtonEnhancement:!0,children:r.jsxs(Z,{appearance:a?"subtle":"primary",size:"small",icon:r.jsx(nd,{}),iconPosition:"before","aria-label":"Select solution",className:e.solutionTrigger,title:a?.friendlyName,children:[r.jsx(q,{size:200,children:"Solution: "}),r.jsx(q,{size:200,weight:"semibold",className:e.ellipsis,children:a?.friendlyName??"Select solution…"}),a&&r.jsxs(r.Fragment,{children:[r.jsx(ue,{appearance:"tint",color:a.isManaged?"informative":"success",size:"small",style:{marginLeft:p.spacingHorizontalXS,flexShrink:0},children:a.isManaged?"Managed":"Unmanaged"}),(()=>{const b=a.publisherPrefix||"new",w=b==="new"||/^defaultpublisher/i.test(a.publisherUniqueName??"");return r.jsxs(ue,{appearance:"tint",color:w?"warning":"informative",size:"small",title:w?`Imports will land under the org's default publisher "${b}". To use your own publisher, create a new solution in maker.powerapps.com bound to it.`:`Publisher: ${a.publisherName||a.publisherUniqueName||b}`,style:{marginLeft:p.spacingHorizontalXS,flexShrink:0},children:[b,"_"]})})()]}),r.jsx(It,{fontSize:12,style:{marginLeft:p.spacingHorizontalXS,color:p.colorNeutralForeground3}})]})}),r.jsxs(Aa,{className:e.solutionPickerSurface,children:[r.jsx(q,{size:200,weight:"semibold",children:"Select an unmanaged solution"}),r.jsx(ze,{label:"Solution",children:r.jsx(hp,{placeholder:s.length===0?"Loading solutions…":"Search by display name or unique name",value:y,onChange:b=>x(b.target.value),onOptionSelect:v,freeform:!0,clearable:!0,children:S})}),r.jsxs(q,{size:100,className:e.solutionPickerHint,children:[h.length," unmanaged solution",h.length!==1?"s":""," available"]})]})]}),r.jsx("div",{className:e.spacer}),r.jsxs("button",{type:"button",className:e.paletteButton,onClick:()=>u(!0),"aria-label":"Search buttons, commands, rules (Ctrl+K)",children:[r.jsx(wt,{fontSize:14}),r.jsx("span",{className:e.ellipsis,style:{flex:1,textAlign:"left"},children:"Search buttons, commands, rules…"}),r.jsx("kbd",{className:e.kbd,children:"Ctrl"}),r.jsx("kbd",{className:e.kbd,children:"K"})]}),r.jsx("div",{className:e.sep}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(ra,{}),disabled:t.length===0,onClick:o,title:"Undo (Ctrl+Z)","aria-label":"Undo"}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(aa,{}),disabled:n.length===0,onClick:i,title:"Redo (Ctrl+Shift+Z)","aria-label":"Redo"}),r.jsx("div",{className:e.sep}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(co,{}),onClick:()=>{d()},title:"Import / Export RibbonDiffXml","aria-label":"Import/Export"}),r.jsx(Dg,{}),r.jsx("div",{className:e.sep}),r.jsx(Z,{appearance:"primary",size:"small",icon:r.jsx(od,{}),onClick:c,children:"Publish All"})]})}const jr="https://github.com/mohsinonxrm/pptb-mxrm-commandbar-studio#readme";function Dg(){const[e,t]=z.useState("");return r.jsxs(Ta,{withArrow:!0,onOpenChange:()=>t(""),children:[r.jsx(ka,{disableButtonEnhancement:!0,children:r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(la,{}),title:"Help","aria-label":"Help"})}),r.jsx(Aa,{"aria-label":"Help",children:r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:p.spacingVerticalS,maxWidth:320},children:[r.jsx(q,{weight:"semibold",children:"Command Bar Studio"}),r.jsx(q,{size:200,children:"Your changes are kept as a draft for each table automatically, until you publish or discard them."}),r.jsxs(q,{size:200,children:[r.jsx("strong",{children:"Ctrl+K"})," search · ",r.jsx("strong",{children:"Ctrl+S"})," publish ·"," ",r.jsx("strong",{children:"Ctrl+Z"})," / ",r.jsx("strong",{children:"Ctrl+Y"})," undo / redo ·"," ",r.jsx("strong",{children:"Ctrl+D"})," duplicate · ",r.jsx("strong",{children:"Ctrl+X"})," /"," ",r.jsx("strong",{children:"Ctrl+V"})," move a button"]}),r.jsx(Z,{size:"small",onClick:async()=>t((await Zl(jr)).ok?"yes":"no"),children:"Copy documentation link"}),e==="yes"&&r.jsx(q,{size:200,children:"Copied: paste it into your browser."}),e==="no"&&r.jsxs(q,{size:200,children:["Couldn't copy. The link is ",jr]})]})})]})}const Eg=me({root:{height:"36px",display:"flex",alignItems:"center",gap:p.spacingHorizontalS,padding:`0 ${p.spacingHorizontalM}`,backgroundColor:p.colorNeutralBackground2,borderBottom:`1px solid ${p.colorNeutralStroke2}`,flexShrink:0,position:"relative"},breadcrumb:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,color:p.colorNeutralForeground3,fontSize:p.fontSizeBase200},separator:{color:p.colorNeutralForeground4},activeSegment:{color:p.colorNeutralForeground1,fontWeight:p.fontWeightSemibold},spacer:{flex:1}});function Og(){const e=Eg(),t=E(m=>m.mutationsSincePublish),n=oe(m=>m.activeSolution),o=oe(m=>m.activeEntity),i=oe(m=>m.connectionUrl),s=ee(m=>m.openXmlDrawer),a=ee(m=>m.openImportXml),l=ee(m=>m.openDiffViewer),c=ee(m=>m.rightPaneMode),d=ee(m=>m.setRightPaneMode);async function u(){if(!i||!o?.logicalName)return;const m=`${i.replace(/\/$/,"")}/main.aspx?pagetype=entitylist&etn=${encodeURIComponent(o.logicalName)}`;await window.toolboxAPI?.utils.openInConnectionBrowser(m,"primary")}return r.jsxs("div",{className:e.root,children:[r.jsxs("nav",{"aria-label":"Breadcrumb",className:e.breadcrumb,children:[r.jsx("span",{children:"Solutions"}),r.jsx("span",{className:e.separator,children:"›"}),r.jsx("span",{children:n?.friendlyName??"—"}),r.jsx("span",{className:e.separator,children:"›"}),r.jsx("span",{children:"Tables"}),r.jsx("span",{className:e.separator,children:"›"}),r.jsx("span",{className:e.activeSegment,children:o?.displayName??"Select a table"})]}),r.jsx("div",{className:e.spacer}),t>0&&r.jsxs(ue,{appearance:"tint",color:"warning",children:[t," change",t!==1?"s":""," since publish"]}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(jt,{}),onClick:()=>{u()},disabled:!o?.logicalName,children:"Preview in app"}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(on,{}),onClick:s,children:"RibbonDiffXml"}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(co,{}),onClick:()=>a(),children:"Import / Export"}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(ca,{}),onClick:()=>l("compare"),children:"Compare"}),r.jsxs($t,{size:"small",value:c,onChange:(m,f)=>d(f.value),"aria-label":"Properties pane mode",children:[r.jsx("option",{value:"docked",children:"Properties: Docked"}),r.jsx("option",{value:"floating",children:"Properties: Floating"}),r.jsx("option",{value:"hidden",children:"Properties: Hidden"})]})]})}function Mg(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 Bg='[role="dialog"], [role="alertdialog"], [role="menu"], [role="menubar"], [role="listbox"], .fui-PopoverSurface, .fui-MenuPopover',Ql=".fui-OverlayDrawer, .fui-InlineDrawer",$r=e=>!!e.closest(Ql)&&!e.matches('[role="alertdialog"]');function zg(e){const t=e instanceof Element?e.closest(Bg):null;return t&&!$r(t)?!0:Array.from(document.querySelectorAll('[aria-modal="true"], [role="alertdialog"]')).some(n=>!$r(n))}function Lg(e){return e instanceof Element&&!!e.closest(Ql)}function Pg(){const e=ee(C=>C.setCommandPaletteOpen),t=ee(C=>C.openBulkPublish),n=ee(C=>C.announce),o=ee(C=>C.openHideInsteadOfDelete),i=E(C=>C.undo),s=E(C=>C.redo),a=E(C=>C.past),l=E(C=>C.future),c=te(C=>C.selectedButtonId),d=te(C=>C.selectedGroupId),u=te(C=>C.tabId),m=te(C=>C.location),f=E(C=>C.duplicateButton),y=E(C=>C.deleteButton),x=E(C=>C.moveButton),h=E(C=>C.ribbons),S=E(C=>C.baseline),v=te(C=>C.selectButtonInContext),b=te(C=>C.selectGroup),w=z.useRef(null);z.useEffect(()=>{const C=I=>{const j=navigator.platform.toUpperCase().includes("MAC")?I.metaKey:I.ctrlKey,R=I.target,T=I.key??"",A=I.altKey||I.getModifierState?.("AltGraph"),W=!A&&/^Key[A-Z]$/.test(I.code??"")&&!/^[a-z]$/i.test(T)?I.code.slice(3).toLowerCase():T.length===1?T.toLowerCase():T,D=j&&!I.shiftKey&&!A;if(I.key==="Escape"){e(!1);return}if(zg(R)){D&&W==="s"&&I.preventDefault();return}if(D&&W==="k"){I.preventDefault(),e(!0),n("Command palette opened");return}if(D&&W==="s"){I.preventDefault(),t(),n("Bulk publish dialog opened");return}const N=Mg(R);if(D&&W==="z"&&a.length>0&&!N){I.preventDefault(),i(),n("Undo");return}if(j&&!A&&(W==="y"||I.shiftKey&&W==="z")&&!N){I.preventDefault(),l.length>0&&(s(),n("Redo"));return}if(!Lg(R)){if(D&&W==="d"){!N&&c&&d&&u&&m&&(I.preventDefault(),f(m,u,d,c),n("Button duplicated"));return}if(j&&!A&&W==="x"){if(!N&&c&&d&&u&&m){I.preventDefault();const M=h[m].tabs.find(k=>k.id===u)?.groups.find(k=>k.id===d);if(M&&bo(M,c)){n("Menu items can't be cut. Delete the item and add a new one to the other menu.");return}w.current={location:m,tabId:u,groupId:d,buttonId:c},n("Button cut. Focus a destination group, then press paste.")}return}if(j&&!A&&W==="v"){const M=w.current;if(!N&&M&&d&&u&&m){I.preventDefault();const k=x({groupId:M.groupId,buttonId:M.buttonId,tabId:M.tabId,location:M.location},{groupId:d,tabId:u,location:m});if(w.current=null,!k){n("The button couldn't be moved there.");return}requestAnimationFrame(()=>{v(m,u,d,k),document.querySelector(`[data-ribbon-btn-id="${k}"]`)?.focus()}),n(k===M.buttonId?"Button pasted to destination group.":"Pasted your copy of the button to the destination group; the original is hidden.")}return}if((I.key==="Delete"||I.key==="Backspace")&&c&&d&&u&&m&&!N){const M=h[m].tabs.find(_=>_.id===u),k=M?.groups.find(_=>_.id===d),B=mn(k,c);if(!B)return;if(I.preventDefault(),!Fn(B,S[m])){m==="Application"&&u==="Mscrm.GlobalTab"&&B.oob&&!B.custom?n(`"${B.label}" is read-only and can't be deleted.`):B.hidden?n(`"${B.label}" can't be deleted — only your own buttons can. It is already hidden.`):o({location:m,tabId:u,groupId:d,buttonId:c});return}const G=k?bo(k,c):void 0,X=G?G.section.controls.map(_=>({groupId:d,buttonId:_.id})):M?.groups.flatMap(_=>_.buttons.map(L=>({groupId:_.id,buttonId:L.id})))??[],Q=X.findIndex(_=>_.buttonId===c),ie=X[Q+1]??X[Q-1]??(G?{groupId:d,buttonId:G.parent.id}:null),F=d;y(m,u,d,c),requestAnimationFrame(()=>{if(ie){v(m,u,ie.groupId,ie.buttonId),document.querySelector(`[data-ribbon-btn-id="${ie.buttonId}"]`)?.focus();return}F&&(b(F),document.querySelector(`[data-add-btn-group-id="${F}"]`)?.focus())}),n("Button deleted")}}};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e,t,n,o,i,s,a.length,l.length,c,d,u,m,f,y,x,h,S,v,b])}const Fg=me({handleV:{width:"4px",cursor:"col-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:p.colorNeutralStroke2},":active":{backgroundColor:p.colorBrandStroke1},userSelect:"none"},handleH:{height:"4px",cursor:"row-resize",backgroundColor:"transparent",flexShrink:0,":hover":{backgroundColor:p.colorNeutralStroke2},":active":{backgroundColor:p.colorBrandStroke1},userSelect:"none"}});function pi({direction:e,onResize:t,"aria-label":n=`Resize ${e} pane`}){const o=Fg(),i=z.useRef(0),s=z.useCallback(l=>{l.currentTarget.setPointerCapture(l.pointerId),i.current=e==="vertical"?l.clientX:l.clientY},[e]),a=z.useCallback(l=>{if(!l.currentTarget.hasPointerCapture(l.pointerId))return;const c=e==="vertical"?l.clientX:l.clientY,d=c-i.current;i.current=c,t(d)},[e,t]);return r.jsx("div",{className:e==="vertical"?o.handleV:o.handleH,role:"separator","aria-orientation":e==="vertical"?"vertical":"horizontal","aria-label":n,onPointerDown:s,onPointerMove:a})}class Wt extends Je.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:r.jsxs(Re,{intent:"error",style:{margin:8},children:[r.jsxs(je,{children:[r.jsx("strong",{children:this.props.label??"Panel"})," encountered an error:"," ",this.state.error?.message??"Unknown error"]}),r.jsx(Xt,{children:r.jsx(Z,{size:"small",onClick:this.handleRetry,children:"Retry"})})]}):this.props.children}}const _g=.4,ec=160,tc=200,qg=500,Wg=600;function nc(e,t,n){const o=t+n-e*(1-_g);if(o<=0||t+n===0)return{left:t,right:n};const i=(s,a)=>Math.max(Math.min(s,a),Math.round(s-o*s/(t+n)));return{left:i(t,ec),right:n===0?0:i(n,tc)}}function Hg(e,t,n,o,i){const s=nc(e,t,n),a=(c,d,u)=>Math.max(d,Math.min(u,c));if(o==="left"){const c=a(s.left+i,ec,qg);return n>0&&s.right!==n?{left:c,right:s.right}:{left:c}}const l=a(s.right-i,tc,Wg);return s.left!==t?{left:s.left,right:l}:{right:l}}const Gg=z.lazy(()=>De(()=>import("./XmlDrawer-CQJElnD1.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),Ug=z.lazy(()=>De(()=>import("./CommandEditorPanel-BiP1kPHY.js"),__vite__mapDeps([7,1,2,3,8,9,5,6,4]),import.meta.url)),Xg=z.lazy(()=>De(()=>import("./RuleEditorPanel-BUGKgc0N.js"),__vite__mapDeps([10,1,2,3,11,5,8,9,6]),import.meta.url)),Vg=z.lazy(()=>De(()=>import("./BulkPublishModal-mJ41AWew.js"),__vite__mapDeps([12,1,2,3,13,11,9,5,6]),import.meta.url)),Kg=z.lazy(()=>De(()=>import("./NewButtonModal-BXpX1Ld5.js"),__vite__mapDeps([14,1,2,3,5,6]),import.meta.url)),Jg=z.lazy(()=>De(()=>import("./NewGroupModal-Bh7lXq52.js"),__vite__mapDeps([15,1,2,3,5,6]),import.meta.url)),Yg=z.lazy(()=>De(()=>import("./NewTabModal-Pntdk3in.js"),__vite__mapDeps([16,1,2,3,5,6]),import.meta.url)),Zg=z.lazy(()=>De(()=>import("./ImportXmlModal-C0cMaS59.js"),__vite__mapDeps([17,1,2,3,13,11,9,4,5,6]),import.meta.url)),Qg=z.lazy(()=>De(()=>import("./CommandPalette-q51_0qRZ.js"),__vite__mapDeps([18,1,2,3,5,6]),import.meta.url)),eb=z.lazy(()=>De(()=>import("./LocalizationEditor-DniDtrZV.js"),__vite__mapDeps([19,1,2,3,5,6]),import.meta.url)),tb=z.lazy(()=>De(()=>import("./IconPickerModal-B81Tnf5i.js"),__vite__mapDeps([20,1,2,3,21,5,6]),import.meta.url)),nb=z.lazy(()=>De(()=>import("./TabDisplayRulesPanel-CSNshwaw.js"),__vite__mapDeps([22,1,2,3,5,6]),import.meta.url)),ob=z.lazy(()=>De(()=>import("./ScalingEditorPanel-p3-Yw3CO.js"),__vite__mapDeps([23,1,2,3,5,6]),import.meta.url)),ib=z.lazy(()=>De(()=>import("./ConflictDrawer-CdWv_PbN.js"),__vite__mapDeps([24,1,2,3,5,6]),import.meta.url)),sb=z.lazy(()=>De(()=>import("./WebResourceBrowser-BK-gVU2g.js"),__vite__mapDeps([25,1,2,3,21,5,6]),import.meta.url)),rb=z.lazy(()=>De(()=>import("./UrlComposerModal-WKSTwUcW.js"),__vite__mapDeps([26,1,2,3,5,6]),import.meta.url)),ab=z.lazy(()=>De(()=>import("./DiffViewer-BQP5f73U.js"),__vite__mapDeps([27,2,3,1,5,6]),import.meta.url)),lb=z.lazy(()=>De(()=>import("./HideInsteadOfDeleteModal-C9r6ah5p.js"),__vite__mapDeps([28,1,2,3,5,6]),import.meta.url)),cb=me({root:{display:"flex",flexDirection:"column",height:"100vh",overflow:"hidden",backgroundColor:p.colorNeutralBackground1,color:p.colorNeutralForeground1,fontFamily:p.fontFamilyBase},body:{display:"flex",flex:1,overflow:"hidden",position:"relative"},leftPane:{flexShrink:0,overflow:"hidden",borderRight:`1px solid ${p.colorNeutralStroke2}`},rightPane:{flexShrink:0,overflow:"hidden",borderLeft:`1px solid ${p.colorNeutralStroke2}`},bottomPanel:{flexShrink:0}});function db(){const[e,t]=z.useState(()=>window.innerWidth);return z.useEffect(()=>{const n=()=>t(window.innerWidth);return window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),e}function ub({children:e,leftPane:t,rightPane:n,bottomPanel:o}){const i=cb(),s=ee(R=>R.leftPaneWidth),a=ee(R=>R.rightPaneWidth),l=ee(R=>R.rightPaneMode),c=ee(R=>R.setLeftPaneWidth),d=ee(R=>R.setRightPaneWidth),u=ee(R=>R.bottomPanelHeight),m=ee(R=>R.bottomCollapsed),f=ee(R=>R.setBottomPanelHeight),y=ee(R=>R.announcement),x=db(),h=nc(x,s,l==="docked"?a:0),S=ee(R=>R.xmlDrawerOpen||R.commandEditorOpen||R.ruleEditorOpen||R.bulkPublishOpen||R.newButtonGroupId!==null||R.newGroupOpen||R.newTabOpen||R.importXmlOpen||R.commandPaletteOpen||R.localizationEditorOpen||R.iconPickerOpen||R.tabDisplayRulesOpen||R.scalingEditorOpen||R.conflictDrawerOpen||R.webResourceBrowserOpen||R.urlComposerOpen||R.diffViewerOpen||R.hideInsteadOfDelete!==null),v=z.useRef(null),b=z.useRef(!1);Pg(),z.useEffect(()=>{if(S&&!b.current){const R=document.activeElement;v.current=R instanceof HTMLElement?R:null}if(!S&&b.current){const R=v.current;requestAnimationFrame(()=>{!R||!R.isConnected||R.focus()})}b.current=S},[S]);const w=l==="docked"?a:0,C=z.useCallback((R,T)=>{const A=Hg(x,s,w,R,T);A.left!==void 0&&c(A.left),A.right!==void 0&&d(A.right)},[x,s,w,c,d]),I=z.useCallback(R=>C("left",R),[C]),$=z.useCallback(R=>C("right",R),[C]),j=z.useCallback(R=>{const T=u-R;f(Math.max(120,Math.min(520,T)))},[u,f]);return r.jsxs("div",{className:i.root,children:[r.jsx(Ag,{}),r.jsx(Og,{}),r.jsxs("div",{className:i.body,children:[r.jsx("div",{className:i.leftPane,style:{width:h.left},children:r.jsx(Wt,{label:"Left pane",children:t})}),r.jsx(pi,{direction:"vertical",onResize:I,"aria-label":"Resize left pane"}),r.jsx(Wt,{label:"Ribbon canvas",children:e}),l==="docked"&&r.jsxs(r.Fragment,{children:[r.jsx(pi,{direction:"vertical",onResize:$,"aria-label":"Resize right pane"}),r.jsx("div",{className:i.rightPane,style:{width:h.right},children:r.jsx(Wt,{label:"Properties pane",children:n})})]}),l==="floating"&&r.jsx("div",{style:{position:"absolute",right:8,top:8,bottom:8,width:a,maxWidth:"90vw",border:`1px solid ${p.colorNeutralStroke2}`,backgroundColor:p.colorNeutralBackground1,boxShadow:p.shadow16,borderRadius:p.borderRadiusMedium,overflow:"hidden",zIndex:10},children:r.jsx(Wt,{label:"Properties pane",children:n})})]}),!m&&r.jsx(pi,{direction:"horizontal",onResize:j,"aria-label":"Resize bottom panel"}),r.jsx("div",{className:i.bottomPanel,children:r.jsx(Wt,{label:"Bottom panel",children:o})}),r.jsx(Wt,{label:"Panels",children:r.jsxs(z.Suspense,{fallback:null,children:[r.jsx(Gg,{}),r.jsx(Ug,{}),r.jsx(Xg,{}),r.jsx(Vg,{}),r.jsx(Kg,{}),r.jsx(Jg,{}),r.jsx(Yg,{}),r.jsx(Zg,{}),r.jsx(Qg,{}),r.jsx(eb,{}),r.jsx(tb,{}),r.jsx(nb,{}),r.jsx(ob,{}),r.jsx(ib,{}),r.jsx(sb,{}),r.jsx(rb,{}),r.jsx(ab,{}),r.jsx(lb,{})]})}),r.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:y})]})}const es=Nt()(e=>({managed:{},setManaged:t=>e({managed:Object.fromEntries(t.map(n=>[n.id,n]))})})),mb=new Set(["label","labeltext","tabname","tabheading","title","tooltip","tooltiptitle","tooltipdescription","alt","button","tab","group","flyout","menu","name","text"]),pb=/^([A-Za-z_$][\w$]*(\.[\w$!{}-]+){2,}|[A-Z][\w$]*\.[\w$!{}-]+)$/;function fb(e){if(!pb.test(e))return;const n=e.split(".").filter(o=>o&&!mb.has(o.toLowerCase())).at(-1);if(!(!n||/^(Mscrm|Ribbon|\{!EntityLogicalName\})$/i.test(n)))return n.replace(/_/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").trim()}function hb(e,t){return e.titles.find(n=>n.languageCode===t)?.description??e.titles.find(n=>n.languageCode===1033)?.description??e.titles[0]?.description}const gb=/^\$(Resources(\([^)]*\))?|LocLabels):/;function bb(e,t,n,o,i){const s=Be(e,t,n);if(!s)return s;const a=i!==void 0&&Be(i,t,n)===(e??"");if(!gb.test(a?i:e??""))return s;const l=o[s];return l?hb(l,n)??s:fb(s)??s}function at(){const e=es(n=>n.managed),t=E(n=>n.baseLanguageCode);return z.useCallback((n,o,i,s)=>bb(n,o,i??t??1033,e,s),[e,t])}const oc="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.",xn=(e,t)=>JSON.stringify(e)===JSON.stringify(t),yb=e=>[e.icon,e.image16,e.image32].some(t=>!!t&&t.startsWith("$webresource:")),xb=e=>!!e.source&&xs(e)===e.source.modernImage&&(e.source.modernImage!==void 0||!e.icon),Sb=/^\$LocLabels:(.+)$/,St=e=>e?Sb.exec(e)?.[1]??null:null,vb=/^\s*<(EnableRule|DisplayRule)\b[^>]*?\sId="([^"]+)"/,Sn=e=>new Set(e??[]);function wb(e){const t=[];for(const n of Object.values(e.source?.attributes??{})){const o=St(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 Nr(e){return(e.menu?.sections??[]).map(t=>({id:t.id,title:t.title??"",sequence:t.sequence,displayMode:t.displayMode??"",controlsId:t.controlsId}))}function vv(e){const t=[],n=[],o=[],i=[],s=[],a=[],l=[],c=[],d=[],u=new Map,m=(F,_)=>{const L=St(F);L&&u.set(L,new Set([...u.get(L)??[],_]))};for(const{baseline:F}of e.locations)for(const _ of F.tabs){m(_.label,_.id);for(const L of _.groups){m(L.label,L.id);for(const U of Ne(L))for(const g of Object.values(U.source?.attributes??{}))m(g,U.id)}}const f=new Set([...(e.locLabels??[]).map(F=>F.id),...Sn(e.layer?.locLabelIds)]);let y=!1;const x=new Set,h=Sn(e.layer?.containerIds),S=Sn(e.layer?.locLabelIds),v=new Set,b=new Set,w=new Map,C=new Map,I=[],$=new Set(e.locations.flatMap(({current:F})=>Array.from(Mt(F).values(),_=>_.button.id))),j=(F,_,L,U)=>{const g=St(L);if(h.has(_)&&g&&S.has(g)&&!St(U)&&U.trim())if([...u.get(g)??[]].some(O=>O!==_)){let O=`${_}.Title`;for(let V=2;O===g||f.has(O);V++)O=`${_}.Title${V}`;f.add(O),d.push({id:O,text:U,containerId:_,newLabel:!0})}else d.push({id:g,text:U,containerId:_});else t.push(`Renaming ${F} ${_} — only tabs and groups your unmanaged customizations add (with a translatable title) can be renamed`)};for(const{current:F,baseline:_}of e.locations){const L=Vf(F,_);L.newButtons+L.overriddenButtons+L.hiddenButtons+L.newTabs+L.newGroups>0&&(y=!0),L.scalingChanges>0&&t.push(`Scaling changes on ${F.location} (not supported yet)`);const U=pl(F,_);t.push(...U.problems);const g=Sn(e.layer?.scalingStepIds);for(const[J,K]of Object.entries(_.scalingByTab??{})){const he=F.tabs.find(ce=>ce.id===J),se=[...K.maxSizes.filter(ce=>g.has(ce.id)).map(ce=>({...ce,kind:"MaxSize"})),...K.scales.filter(ce=>g.has(ce.id)).map(ce=>({...ce,kind:"Scale"})),...(he?.groups??[]).map(ce=>U.steps.get(ce.id)).filter(ce=>!!ce).map(ce=>({...ce,kind:"MaxSize"}))];if(se.length===0)continue;const Ze=Ka(J,{maxSizes:K.maxSizes.filter(ce=>!g.has(ce.id)).map(ce=>ce.sequence),scales:K.scales.filter(ce=>!g.has(ce.id)).map(ce=>ce.sequence)},se);n.push(...Ze.changes.map(If)),t.push(...Ze.problems)}const O=Mt(F),V=Mt(_);for(const{button:J}of O.values())for(const K of Ua(J))x.add(K);for(const[J,{button:K,menu:he}]of O){const se=wb(K);se.forEach(Qe=>v.add(Qe));const Ze=V.get(J)?.button,ce=!Ze||Bi(Ze,K);ce&&he&&!gs.includes(K.kind??"button")&&t.push(`Menu item "${K.label}" (${K.id}) is a ${Vt[K.kind]??K.kind} — a menu can hold buttons and flyouts only; change its Kind`);for(const Qe of[Mo(K.id),Bo(K.id),zo(K.id)])ce?b.add(Qe):se.includes(Qe)||w.set(Qe,K);ce&&se.forEach(Qe=>b.add(Qe))}for(const[J,K]of V){const he=K.button.id,se=O.get(J);if(!se){if(K.menu&&$.has(he)&&$.has(K.menu.parentId)&&K.button.origin!=="unmanaged"){t.push(`Moving the menu of ${K.menu.parentId} to another location — its item "${K.button.label}" (${he}) comes from another solution and can't be moved with it; move the flyout back`);continue}if(rt(K.button.kind)&&$.has(he)&&/<Menu[\s>/]/.test(K.button.source?.xml??"")){t.push(`Moving the <${Vt[K.button.kind]}> "${K.button.label}" (${he}) to another location — its menu may hold items of other solutions; move it within its location instead`);continue}Dt(K.button)?o.push(he):t.push(`Removing "${K.button.label}" (${he}) — only your own unmanaged buttons can be deleted; hide it instead`);continue}K.button.hidden&&!se.button.hidden&&i.push(he),(se.button.kind??"button")!==(K.button.kind??"button")&&t.push(`Changing the kind of "${se.button.label}" (${he}) — not supported yet`);const Ze=Bi(K.button,se.button);Ze&&rt(se.button.kind)&&t.push(`Editing the <${Vt[se.button.kind]}> "${se.button.label}" (${he}) — CBS shows it read-only; it can be hidden, or moved and deleted when it's your own`),Ze&&(Kt(se.button.kind)||se.button.menu)&&K.button.origin!=="unmanaged"&&t.push(`Editing the flyout / split button "${se.button.label}" (${he}) itself — only your own can be edited; its menu items can be edited, hidden or added to`),xn(Nr(K.button),Nr(se.button))||t.push(`Adding, removing or changing menu sections of "${se.button.label}" (${he}) — not supported yet for an existing menu; add, edit or remove its items instead`),(se.button.icon??"")!==(K.button.icon??"")&&!yb(se.button)&&!xb(se.button)&&t.push(`Changing the icon of "${se.button.label}" (${he}) to a built-in icon — not supported yet; choose an SVG web resource`),((se.menu||K.menu?se.menu?.controlsId!==K.menu?.controlsId:se.groupId!==K.groupId)||se.button.sequence!==K.button.sequence)&&(K.button.origin==="unmanaged"?a.push({id:he,groupId:se.groupId,sequence:se.button.sequence,...se.menu?{controlsId:se.menu.controlsId}:{}}):t.push(`Moving or re-ordering "${se.button.label}" (${he}) — 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[J,K]of O){if(V.has(J))continue;C.has(K.button.id)||C.set(K.button.id,{groupId:K.groupId,sequence:K.button.sequence,...K.menu?{controlsId:K.menu.controlsId}:{}});const he=rl(K.button.source?.attributes.PopulateDynamically);Kt(K.button.kind)&&!he&&!zt(K.button).some(se=>!se.hidden)&&I.push({id:K.button.id,label:K.button.label})}const de=new Map(_.tabs.flatMap(J=>J.groups.map(K=>[K.id,K]))),Se=new Map(_.tabs.map(J=>[J.id,J])),ve=_.tabs.map(J=>J.id).filter(J=>F.tabs.some(K=>K.id===J)),le=F.tabs.map(J=>J.id).filter(J=>Se.has(J)),H=J=>!h.has(J),P=ve.filter(H),Te=le.filter(H).find((J,K)=>J!==P[K]);if(Te){const J=F.tabs.find(K=>K.id===Te);t.push(e.layer?`Reordering tab "${J.label}" (${J.id}) — only tabs your customizations add can be reordered; drag it back`:`Reordering tab "${J.label}" (${J.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 J of F.tabs){const K=Se.get(J.id);K&&h.has(J.id)&&K.sequence!==J.sequence&&c.push({id:J.id,sequence:J.sequence})}const Ye=new Set(F.tabs.map(J=>J.id)),qe=new Set(F.tabs.flatMap(J=>J.groups.map(K=>K.id)));for(const J of F.tabs){const K=St(J.label);K&&v.add(K);const he=Se.get(J.id);if(!he){b.add(`${J.id}.Title`);const se=St(J.source?.titleToken);se&&b.add(se),J.commandId&&x.add(J.commandId),F.location==="Application"&&(J.tabDisplayRules??[]).length===0&&t.push(`New tab ${J.id} has no tab display rule, so it would never be shown — add one in Tab rules`),n.push(`New tab "${J.label}" (${J.id}): ${oc}`)}he&&he.label!==J.label&&j("tab",J.id,he.label,J.label),he&&!xn(he.tabDisplayRules??[],J.tabDisplayRules??[])&&(h.has(J.id)?J.commandId?l.push(J.id):t.push(`Changing the display rules of tab ${J.id} — the tab has no Command to attach them to`):t.push(`Changing the display rules of tab ${J.id} — only tabs your unmanaged customizations add can be changed`));for(const se of J.groups){const Ze=St(se.label);Ze&&v.add(Ze);const ce=de.get(se.id);if(!ce){b.add(`${se.id}.Title`);const Qe=se.source?.attributes.Command;Qe&&x.add(Qe);const Hs=St(se.source?.titleToken);Hs&&b.add(Hs)}ce&&ce.template!==se.template&&t.push(`Re-templating group ${se.id} — not supported yet`),ce&&ce.label!==se.label&&j("group",se.id,ce.label,se.label)}}const lt=(J,K)=>t.push(`Removing ${J} ${K} — only tabs and groups your unmanaged customizations add can be deleted; hide it instead`);for(const J of _.tabs){if(!Ye.has(J.id)){h.has(J.id)?s.push(J.id):lt("tab",J.id);continue}for(const K of J.groups)qe.has(K.id)||(h.has(K.id)?s.push(K.id):lt("group",K.id))}}for(let F=o.length-1;F>=0;F--){const _=C.get(o[F]);_&&(a.push({id:o[F],..._}),o.splice(F,1))}for(const F of e.deletedOrphans??[]){for(const _ of F.deleteControlIds)o.includes(_)||o.push(_);for(const _ of F.deleteContainerIds)s.includes(_)||s.push(_)}for(const F of I)a.some(_=>_.id===F.id)||t.push(`New flyout / split button "${F.label}" has no menu items — add at least one item to its menu`);const R=e.layer?.commandIds?Sn(e.layer.commandIds):null,T=new Set(e.uncustomisedCommandIds??[]),A=[...T].filter(F=>R?R.has(F):x.has(F)&&!e.excludeCommandIds?.has(F));for(const F of A)e.layer?.commandRefIds&&!fs(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`);A.includes(Pe)&&x.has(Pe)&&t.push(`Uncustomising ${Pe} — 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??[])x.delete(F);const W=new Set(e.customisedCommandIds??[]),D=new Map(e.baselineCommands.map(F=>[F.id,F])),N=e.commands.filter(F=>x.has(F.id)&&!T.has(F.id)&&(!D.has(F.id)||!xn(D.get(F.id),F)||W.has(F.id)&&!R?.has(F.id))).map(F=>F.id);for(const F of e.commands){if(!N.includes(F.id))continue;F.actions.some(L=>L.kind==="powerFx"||L.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 _=F.id===Pe?Ph(F):null;_&&t.push(_)}const M=new Set,k=new Set;for(const F of e.commands)if(!(!x.has(F.id)||T.has(F.id))){F.enableRules.forEach(_=>M.add(_)),F.displayRules.forEach(_=>k.add(_));for(const _ of F.rawRuleRefs??[]){const L=vb.exec(_.xml);L&&(L[1]==="EnableRule"?M:k).add(L[2])}}const B=(F,_,L)=>{const U=new Map(_.map(g=>[g.id,g]));return F.filter(g=>L.has(g.id)&&(!U.has(g.id)||!xn(U.get(g.id),g))).map(g=>g.id)},G=B(e.enableRules,e.baselineEnableRules,M),X=B(e.displayRules,e.baselineDisplayRules,k),Q=[];if(e.locLabels&&e.baselineLocLabels){const F=new Map(e.baselineLocLabels.map(_=>[_.id,_]));for(const _ of e.locLabels){const L=F.get(_.id);if(L&&xn(L,_)||b.has(_.id))continue;if(v.has(_.id)){S.has(_.id)?Q.push(_.id):t.push(`Translations of label ${_.id} — it is defined by another solution; change the text in the properties pane instead`);continue}const U=w.get(_.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 ie=(e.unhiddenLayerHideIds??[]).filter(F=>!i.includes(F));return{hasChanges:y||N.length>0||A.length>0||G.length>0||X.length>0||o.length>0||i.length>0||ie.length>0||s.length>0||a.length>0||Q.length>0||l.length>0||c.length>0||d.length>0,editedCommandIds:N,uncustomisedCommandIds:A,editedEnableRuleIds:G,editedDisplayRuleIds:X,deletedButtonIds:o,unhiddenButtonIds:[...i,...ie],deletedContainerIds:s,movedButtons:a,editedLocLabelIds:Q,editedTabIds:l,resequencedTabs:c,renamedLabels:d,unsupported:[...new Set(t)],warnings:[...new Set(n)]}}const Cb=["HomepageGrid","SubGrid","Form"];function Ib(e,t){const n=new Map;for(const x of Object.values(t.baseline))for(const h of x.tabs)for(const S of h.groups)for(const v of S.buttons)n.set(v.id,v.origin);let o=!1,i=!1,s=Fi(e);for(const[x,h]of Object.entries(t.ribbons))for(const S of h.tabs)for(const v of S.groups)for(const b of v.buttons)b.commandId===e&&(Cb.includes(x)?o=!0:i=!0,n.has(b.id)&&n.get(b.id)!=="unmanaged"&&(s=!0));const a=o||!i?"entity":"application",l=o&&i,c=t.layers[a],d=c?.commandIds?c.commandIds.includes(e):void 0,u=t.baselineCommands.find(x=>x.id===e),m=(x,h=a)=>({provenance:x,scope:h,sharedWithApplication:l});if(t.reloadRequiredCommandIds.includes(e))return m("reloadRequired");for(const x of["entity","application"])if(t.uncustomisedCommandIds[x].includes(e))return m("uncustomising",x);if(!u||!s&&d!==!1)return m("custom");if(d){const x=c?.commandRefIds?fs(e,c.commandRefIds):Fi(e);return m(x?"customised":"custom")}const f=t.commands.find(x=>x.id===e),y=!!f&&JSON.stringify(f)!==JSON.stringify(u);return t.customisedCommandIds.includes(e)||y?m("customising"):m("oob")}const Rb={oob:"Out of the box",customising:"Customised (unpublished)",customised:"Customised in your layer",uncustomising:"Uncustomised (unpublished)",custom:"Custom",reloadRequired:"Uncustomised — reload the table"};function ic(e){const t=E(d=>d.commands),n=E(d=>d.baselineCommands),o=E(d=>d.ribbons),i=E(d=>d.baseline),s=E(d=>d.layers),a=E(d=>d.customisedCommandIds),l=E(d=>d.uncustomisedCommandIds),c=E(d=>d.reloadRequiredCommandIds);return Je.useMemo(()=>e&&t.some(d=>d.id===e)?Ib(e,{commands:t,baselineCommands:n,ribbons:o,baseline:i,layers:s,customisedCommandIds:a,uncustomisedCommandIds:l,reloadRequiredCommandIds:c}):null,[e,t,n,o,i,s,a,l,c])}function wv(e){return e?.provenance==="uncustomising"||e?.provenance==="reloadRequired"}function sc({location:e,tabId:t,groupId:n,button:o,onDone:i}){const s=E(f=>f.customiseButton),a=E(f=>f.customiseCommand),l=oe(f=>f.activeSolution),c=oe(f=>f.publisherPrefix),d=te(f=>f.selectButtonInContext),u=ee(f=>f.openCommandEditor),m=ic(o.commandId||void 0);return r.jsxs(r.Fragment,{children:[o.origin!=="unmanaged"&&r.jsx(be,{icon:r.jsx(id,{}),disabled:!Ns(e,t,o),onClick:()=>{const f=l?.publisherPrefix?.trim()||c?.trim()||"new",y=s(e,t,n,o.id,f);y&&d(e,t,n,y),i()},children:"Customise button (copy, hide original)"}),m?.provenance==="oob"&&r.jsx(be,{icon:r.jsx(on,{}),onClick:()=>{a(o.commandId)&&u(o.commandId),i()},children:"Customise command"})]})}function rc(e,t,n,o,i,s=Be){const a=e.groups.filter(c=>c.id!==t&&!(n&&c.buttons.some(d=>d.id===n))).map(c=>({groupId:c.id,text:s(c.label,o,i,c.source?.titleToken).trim()||c.id})),l=new Map;for(const c of a)l.set(c.text,(l.get(c.text)??0)+1);return a.map(c=>(l.get(c.text)??0)>1&&c.text!==c.groupId?{...c,text:`${c.text} (${c.groupId})`}:c)}const Es=({open:e,buttonLabel:t,commandId:n,deleteBlockedReason:o,onConfirmHide:i,onConfirmDisplayRule:s,onCancel:a})=>r.jsx(sn,{open:e,onOpenChange:()=>a(),children:r.jsxs(rn,{style:{maxWidth:"560px"},children:[r.jsxs(an,{children:[r.jsx(da,{style:{marginRight:"8px",color:"var(--colorStatusWarningForeground1)"}}),o?`Can't delete "${t}"`:`Hide "${t}"`]}),r.jsxs(ln,{children:[r.jsxs(cn,{children:[o&&r.jsxs(q,{style:{display:"block",marginBottom:"12px"},children:[o," Only buttons your solution adds can be deleted — you can hide this one instead."]}),r.jsx(Re,{intent:"warning",children:r.jsxs(je,{children:[r.jsx(q,{weight:"semibold",children:"A HideCustomAction removes the button from the ribbon."})," ","To show it again, use Unhide under “Hidden by customizations” in the Properties pane; in a managed solution a hide can't be undone with a patch."]})}),r.jsxs(q,{style:{display:"block",marginTop:"12px"},children:["The reversible alternative adds the display rules ",r.jsx("code",{children:"Mscrm.HideOnModern"})," +"," ",r.jsx("code",{children:"Mscrm.ShowOnlyOnModern"})," (never both true) to the button's command",n?r.jsxs(r.Fragment,{children:[" ",r.jsx("code",{children:n}),". Every button that uses this command is hidden too."]}):r.jsx(r.Fragment,{children:". This button has no command, so only the HideCustomAction is available."})]})]}),r.jsxs(dn,{children:[r.jsx(Z,{appearance:"secondary",onClick:a,children:"Cancel"}),r.jsx(Z,{appearance:"secondary",onClick:s,disabled:!n,children:"Use display rules (reversible)"}),r.jsx(Z,{appearance:"primary",onClick:i,children:"Use HideCustomAction (permanent)"})]})]})]})}),jb=({open:e,initialLabel:t,onRename:n,onCancel:o})=>{const[i,s]=z.useState(t),a=i.trim(),l=()=>{a&&(a===t.trim()?o():n(a))};return r.jsx(sn,{open:e,onOpenChange:(c,d)=>!d.open&&o(),children:r.jsx(rn,{style:{maxWidth:"440px"},children:r.jsxs(ln,{children:[r.jsx(an,{children:"Rename group"}),r.jsx(cn,{children:r.jsx(ze,{label:"Group title",required:!0,validationState:a?"none":"error",validationMessage:a?void 0:"Enter a title for the group.",children:r.jsx(Ue,{value:i,onChange:(c,d)=>s(d.value),onKeyDown:c=>{c.key==="Enter"&&(c.preventDefault(),l())},autoFocus:!0})})}),r.jsxs(dn,{children:[r.jsx(Z,{appearance:"secondary",onClick:o,children:"Cancel"}),r.jsx(Z,{appearance:"primary",onClick:l,disabled:!a,children:"Rename"})]})]})})})},$b=e=>e.replace(/^Mscrm\.Templates\./,""),Nb=({open:e,currentTemplate:t,customTemplateIds:n=[],loadedGroup:o=!1,onChange:i,onCancel:s})=>{const a=bs(t),[l,c]=z.useState(a),d=[...new Set([...Jf,...n,a])],u=()=>{l===a?s():i(l)};return r.jsx(sn,{open:e,onOpenChange:(m,f)=>!f.open&&s(),children:r.jsx(rn,{style:{maxWidth:"480px"},children:r.jsxs(ln,{children:[r.jsx(an,{children:"Change group template"}),r.jsxs(cn,{children:[r.jsx(ze,{label:"Group template",children:r.jsx($t,{value:l,onChange:(m,f)=>c(f.value),children:d.map(m=>r.jsxs("option",{value:m,children:[$b(m),m===a?" (current)":""]},m))})}),r.jsx(q,{size:200,style:{display:"block",marginTop:"8px"},children:"The group template defines how buttons scale when the ribbon is resized."}),o&&r.jsx(Re,{intent:"warning",style:{marginTop:"12px"},children:r.jsx(je,{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."})})]}),r.jsxs(dn,{children:[r.jsx(Z,{appearance:"secondary",onClick:s,children:"Cancel"}),r.jsx(Z,{appearance:"primary",onClick:u,disabled:l===a,children:"Change template"})]})]})})})},Tb=me({destructive:{backgroundColor:p.colorStatusDangerBackground3,color:p.colorNeutralForegroundOnBrand,":hover":{backgroundColor:p.colorStatusDangerBackground3Hover,color:p.colorNeutralForegroundOnBrand},":hover:active":{backgroundColor:p.colorStatusDangerBackground3Pressed,color:p.colorNeutralForegroundOnBrand}}}),$o=({open:e,title:t,children:n,confirmLabel:o,cancelLabel:i="Cancel",destructive:s=!1,onConfirm:a,onCancel:l})=>{const c=Tb();return r.jsx(sn,{modalType:"alert",open:e,onOpenChange:(d,u)=>!u.open&&l(),children:r.jsx(rn,{style:{maxWidth:"480px"},children:r.jsxs(ln,{children:[r.jsx(an,{children:t}),r.jsx(cn,{children:n}),r.jsxs(dn,{children:[r.jsx(Z,{appearance:"secondary",onClick:l,children:i}),r.jsx(Z,{appearance:"primary",className:s?c.destructive:void 0,onClick:a,children:o})]})]})})})};function ac(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 kb={new:Ae,plus:Ae,addexisting:Ae,exporttoexcel:ja,tablegroup:ha,flows:Js,process:Js,emaillink:ap,sendbyemail:pa,failedmail:Ii,letter:Ii,remove:Ot,close:Ot,abandon:Ot,cancel:Ks,cleardefault:Ks,assign:rp,activate:Gn,saveascomplete:Gn,finishstage:Gn,setdefault:Gn,deactivate:sp,reactivate:fa,connection:Hn,connect:Hn,connectiontoother:Hn,connectiontome:Hn,addtoqueue:Vs,bulletlistadd:Vs,queueitemdetail:ip,ratingempty:to,ratingfull:to,ratingfullgrey:to,report:wi,openinpowerbi:wi,wordtemplates:Xo,documenttemplates:Xo,applytemplate:Xo,dynamics365:op,formdesign:np,msteamsicon:tp,convert:co,switchprocess:co,viewhierarchy:ep,linkarticle:ya,saveandclose:Qm,saveandedit:Ra,runroutingrule:Xs,saveandrunroutingrule:Xs,createquickcampaign:Zm,pdficonfile:Ym,mergerecords:Jm,yammericon:Us,post:Us,opportunity:Ci,opportunitieslist:Ci,case:va,deletebulk:Bt,foldertrack:Sa,sadsmiley:Km,kbrecords:Gs,insertkbarticle:Gs,salesliterature:Vm,follow:jt,history:Xm,contactcard:Um,flash:Gm,pin:Hm,multiselect:Wm,browsecards:ba,addmembers:qm,distributionlist:wa,health:_m,tools:Fm,relationshipassistant:ma,task:Pm,appointment:Lm},lc={add:{regular:Ae,filled:zm},delete:{regular:Bt,filled:Bm},edit:{regular:Ao,filled:Mm},save:{regular:Ra,filled:Om},copy:{regular:kn,filled:Em},cut:{regular:Dm,filled:Am},clipboardpaste:{regular:km,filled:Tm},share:{regular:Nm,filled:$m},mail:{regular:Ii,filled:jm},chat:{regular:Rm,filled:Im},phone:{regular:Cm,filled:wm},search:{regular:wt,filled:vm},filter:{regular:Sm,filled:xm},arrowleft:{regular:ym,filled:bm},arrowright:{regular:gm,filled:hm},arrowup:{regular:fm,filled:pm},arrowdown:{regular:mm,filled:um},chevrondown:{regular:It,filled:dm},chevronup:{regular:Ia,filled:cm},navigation:{regular:lm,filled:am},home:{regular:rm,filled:sm},settings:{regular:im,filled:om},info:{regular:nm,filled:tm},warning:{regular:da,filled:em},checkmark:{regular:Qu,filled:Zu},dismiss:{regular:Ot,filled:Yu},questioncircle:{regular:la,filled:Ju},lockclosed:{regular:Lt,filled:Ku},lockopen:{regular:Vu,filled:Xu},shield:{regular:Uu,filled:Gu},person:{regular:Ca,filled:Hu},people:{regular:wa,filled:Wu},personadd:{regular:qu,filled:_u},building:{regular:Fu,filled:Pu},briefcase:{regular:va,filled:Lu},money:{regular:Ci,filled:zu},creditcard:{regular:Bu,filled:Mu},cart:{regular:Ou,filled:Eu},tag:{regular:Du,filled:Au},document:{regular:ko,filled:ku},documentbulletlist:{regular:Tu,filled:Nu},folder:{regular:Sa,filled:$u},folderopen:{regular:ju,filled:Ru},attach:{regular:Iu,filled:Cu},arrowdownload:{regular:wu,filled:vu},arrowupload:{regular:Su,filled:xu},globe:{regular:xa,filled:yu},link:{regular:ya,filled:bu},open:{regular:gu,filled:hu},calendar:{regular:fu,filled:pu},clock:{regular:mu,filled:uu},timer:{regular:du,filled:cu},star:{regular:to,filled:lu},heart:{regular:au,filled:ru},thumblike:{regular:su,filled:iu},thumbdislike:{regular:ou,filled:nu},eye:{regular:jt,filled:tu},eyeoff:{regular:st,filled:eu},zoomin:{regular:Qd,filled:Zd},zoomout:{regular:Yd,filled:Jd},maximize:{regular:Kd,filled:Vd},minimize:{regular:Xd,filled:Ud},grid:{regular:ba,filled:Gd},list:{regular:Hd,filled:Wd},table:{regular:ga,filled:qd},tablesimple:{regular:ha,filled:_d},code:{regular:on,filled:Fd},bug:{regular:Pd,filled:Ld},play:{regular:zd,filled:Bd},pause:{regular:Md,filled:Od},stop:{regular:Ed,filled:Dd},refresh:{regular:fa,filled:Ad},arrowsync:{regular:kd,filled:Td},arrowundo:{regular:ra,filled:Nd},arrowredo:{regular:aa,filled:$d},printer:{regular:jd,filled:Rd},send:{regular:pa,filled:Id},rocket:{regular:Cd,filled:wd},sparkle:{regular:vd,filled:Sd},trophy:{regular:xd,filled:yd},lightbulb:{regular:ma,filled:bd},bot:{regular:gd,filled:hd},databar:{regular:wi,filled:fd},chartmultiple:{regular:pd,filled:md},poll:{regular:ud,filled:dd},layoutcolumntwo:{regular:cd,filled:ld},codeblock:{regular:ad,filled:rd},clockarrowcounterclockwise:{regular:ua,filled:sd}},Os=({name:e,size:t=20,variant:n="regular",style:o,className:i,"aria-hidden":s=!0})=>{const a=ac(e).replace(/_/g,""),l=lc[a],c=(n==="filled"?l?.filled??l?.regular:l?.regular)??kb[a]??An;return r.jsx(c,{fontSize:t,"aria-hidden":s,className:i,style:{display:"inline-block",verticalAlign:"middle",flexShrink:0,color:p.colorNeutralForeground1,...o}})};async function Cv(e,t=32,n="regular"){const o=ac(e).replace(/_/g,""),i=lc[o],s=n==="filled"?i?.filled??i?.regular:i?.regular;if(!s)return null;const{renderToStaticMarkup:a}=await De(async()=>{const{renderToStaticMarkup:c}=await import("./server.browser-xEJRzS2D.js").then(d=>d.s);return{renderToStaticMarkup:c}},__vite__mapDeps([29,2,3]),import.meta.url);let l=a(Je.createElement(s,{fontSize:t}));return l.includes("<svg")?(l.includes("xmlns")||(l=l.replace("<svg",'<svg xmlns="http://www.w3.org/2000/svg"')),l=l.replace(/width="1em"/,`width="${t}"`).replace(/height="1em"/,`height="${t}"`),l=l.replace(/\s(?:class|aria-hidden|focusable|data-fui-icon|font-size)="[^"]*"/g,""),l):null}function cc(){return window.dataverseAPI}async function Ab(){let e="the organization record has no languagecode";for(let t=0;t<2;t++)try{const o=(await cc().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 Db=[/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 Eb(e){const t=e instanceof Error?`${e.message} ${String(e.code??"")}`:typeof e=="string"?e:JSON.stringify(e??"");return Db.some(n=>n.test(t))}const Ob={0:"Import",1:"Uninstall",2:"Export",3:"Publish",4:"PublishAll",5:"LanguageProvision",6:"ImportTranslation",7:"RibbonMetadataGeneration",8:"WorkflowSetState",10:"ExportLite",11:"UpdatingMissingPackages"},dc=30;async function Mb(e=dc,t=Date.now()){const n=t-e*6e4;try{return((await cc().queryData("msdyn_solutionhistories?$select=msdyn_name,msdyn_operation,msdyn_status,msdyn_starttime&$orderby=msdyn_starttime desc&$top=25")).value??[]).filter(i=>typeof i.msdyn_operation=="number"&&(i.msdyn_status===0||i.msdyn_status===2)&&i.msdyn_operation!==2&&i.msdyn_operation!==10&&(!i.msdyn_starttime||Date.parse(i.msdyn_starttime)>=n)).map(i=>({operation:Ob[i.msdyn_operation??-1]??`operation ${i.msdyn_operation}`,name:i.msdyn_name??"",startedOn:i.msdyn_starttime??""}))}catch{return[]}}const uc=e=>new Promise(t=>setTimeout(t,e)),Tr=e=>e.map(t=>t.name&&t.name!==t.operation?`${t.operation} (${t.name})`:t.operation).join(", ");async function Iv(e={}){const t=e.sleep??uc,n=e.now??Date.now,o=n()+(e.timeoutMs??10*6e4);for(;;){const i=await Mb(dc,n());if(i.length===0)return;if(n()>=o)throw new Error(`The environment is still busy (${Tr(i)} running). Try again when it has finished — Solutions › History shows its progress.`);e.onProgress?.(`Waiting for another operation to finish: ${Tr(i)}…`),await t(15e3)}}async function mc(e,t,n={}){const o=n.sleep??uc,i=n.now??Date.now,s=i()+(n.timeoutMs??10*6e4);for(let a=0;;a++)try{return await t()}catch(l){if(!Eb(l))throw l;const c=Math.min(6e4,15e3*2**a);if(i()+c>s)throw new Error(`${e} kept failing because another solution operation is running in the environment (${l instanceof Error?l.message:String(l)}). 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 Tt(){const e=window.dataverseAPI;if(!e)throw new Error("dataverseAPI is not available in the current runtime");return e}const pc={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 fc(e){return pc[e]??"xml"}async function Bb(e,t){let n="webresourceset?$select=webresourceid,name,displayname,description,webresourcetype,modifiedon,ismanaged&$orderby=name asc";if(t!==void 0){const i=Object.entries(pc).find(([,s])=>s===t)?.[0];i&&(n+=`&$filter=webresourcetype eq ${i}`)}return(await e.queryData(n)).value.map(i=>{const s=i;return{id:String(s.webresourceid??""),name:String(s.name??""),displayName:s.displayname?String(s.displayname):void 0,description:s.description?String(s.description):void 0,webResourceType:fc(Number(s.webresourcetype??3)),modifiedOn:s.modifiedon?String(s.modifiedon):void 0,isCustom:s.ismanaged===!1}})}async function zb(e,t){const n=await e.retrieve("webresource",t,["content"]);return n.content?String(n.content):""}const hc=61;async function gc(e,t,n,o=Do){await o("Adding the web resource to the solution"),await e.execute({operationName:"AddSolutionComponent",operationType:"action",parameters:{ComponentId:t,ComponentType:hc,SolutionUniqueName:n,AddRequiredComponents:!1}})}class Lb extends Error{constructor(t){super(`Web resource ${t} already exists; it was left as it is.`),this.name="WebResourceSaveCancelled"}}async function Pb(e,t,n,o,i={}){const s=i.guard??_a(),{displayName:a,solutionUniqueName:l,onExisting:c}=i;let d=i.keepExisting??!1;const u=await e.queryData(`webresourceset?$select=webresourceid,ismanaged&$filter=name eq '${t.replace(/'/g,"''")}'&$top=1`),m={name:t,content:n,webresourcetype:o,...a?{displayname:a}:{}};let f;if(u.value.length>0){const y=u.value[0],x=String(y.webresourceid??"");if(!d&&c){const h=y.ismanaged===!0,S=await c({id:x,name:t,managed:h});if(S==="cancel")throw new Lb(t);if(S==="replace"&&h)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=S==="keep"}d||(await s("Saving the web resource"),await e.update("webresource",x,m)),f={id:x,created:!1,updated:!d}}else{await s("Saving the web resource");const y=await e.create("webresource",m);f={id:String(y.id??""),created:!0,updated:!1}}if(l&&f.id){try{await gc(e,f.id,l,s)}catch(y){throw new Error(`Web resource ${t} was saved but could not be added to solution ${l}: ${y instanceof Error?y.message:String(y)}`)}f.solutionUniqueName=l}return f}const kr=40,Ar=(e,t)=>Array.from({length:Math.ceil(e.length/t)},(n,o)=>e.slice(o*t,(o+1)*t)),Fb=e=>`'${e.replace(/'/g,"''").replace(/[^A-Za-z0-9/._\-'~]/gu,t=>encodeURIComponent(t))}'`,Dr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function _b(e,t,n){const o=t.map(c=>c.split(/[?#]/)[0].trim()).filter(Boolean),i=o.filter((c,d)=>o.findIndex(u=>u.toLowerCase()===c.toLowerCase())===d),s={};for(const c of i)s[c.toLowerCase()]={exists:!1,inSolution:!1};if(i.length===0)return s;const a=new Map;for(const c of Ar(i,kr)){const d=c.map(m=>`name eq ${Fb(m)}`).join(" or "),u=await e.queryData(`webresourceset?$select=webresourceid,name,ismanaged&$filter=${d}`);for(const m of u.value??[]){const f=m,y=String(f.name??"").toLowerCase();if(!(y in s))continue;s[y]={exists:!0,inSolution:!1,managed:f.ismanaged===!0};const x=String(f.webresourceid??"").toLowerCase();Dr.test(x)&&a.set(x,y)}}const l=n?.replace(/[{}]/g,"");if(l&&Dr.test(l)&&a.size>0)for(const c of Ar([...a.keys()],kr)){const d=c.map(m=>`objectid eq ${m}`).join(" or "),u=await e.queryData(`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${l} and componenttype eq ${hc} and (${d})`);for(const m of u.value??[]){const f=a.get(String(m.objectid??"").toLowerCase());f&&(s[f].inSolution=!0)}}return s}async function Rv(e,t){return _b(Tt(),e,t)}async function jv(e){return Bb(Tt(),e)}async function $v(e){return zb(Tt(),e)}async function qb(e){const t=Tt(),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 i=o.value[0];return{id:String(i.webresourceid??""),name:String(i.name??""),displayName:i.displayname?String(i.displayname):void 0,webResourceType:fc(Number(i.webresourcetype??3)),isCustom:i.ismanaged===!1}}async function Wb(e,t,n,o={}){const i=oe.getState().activeSolution,s=o.solutionUniqueName??(i&&!i.isManaged?i.uniqueName:void 0),a=o.guard??_a(),l=await Pb(Tt(),e,t,n,{...o,solutionUniqueName:s,guard:a});if((l.created||l.updated)&&o.publish!==!1)try{await mc(`Publishing web resource ${e}`,()=>bc(l.id,a),{timeoutMs:2*6e4,onProgress:c=>ne.getState().logInfo("webresource",c)}),l.published=!0}catch(c){l.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.`,ne.getState().logWarn("webresource",l.publishWarning)}if(!s){const c=i?`the active solution ${i.uniqueName} is managed`:"no solution is selected";l.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.`,ne.getState().logWarn("webresource",l.solutionWarning)}return l}async function Nv(e,t,n=Do){const o=t??await qb(e);if(!o?.id)throw new Error(`No web resource named ${e} exists in this environment.`);const i=o.id;if(o.isCustom===!1){const a=`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 ne.getState().logWarn("webresource",a),{solutionWarning:a}}const s=oe.getState().activeSolution;if(!s||s.isManaged){const a=s?`the active solution ${s.uniqueName} is managed`:"no solution is selected",l=`Web resource ${e} was not added to any solution because ${a}. Select an unmanaged solution and pick the icon again so it travels with your customizations.`;return ne.getState().logWarn("webresource",l),{solutionWarning:l}}return await gc(Tt(),i,s.uniqueName,n),{solutionUniqueName:s.uniqueName}}async function bc(e,t=Do){const n=Tt(),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 Hb={5:"image/png",6:"image/jpeg",7:"image/gif",10:"image/x-icon",11:"image/svg+xml"};async function Gb(e){const o=(await Tt().queryData(`webresourceset?$select=content,webresourcetype&$filter=name eq '${e.replace(/'/g,"''")}'&$top=1`)).value?.[0],i=Hb[Number(o?.webresourcetype)],s=o?.content;return i&&typeof s=="string"&&s?`data:${i};base64,${s}`:null}const Er="$webresource:",fi=new Map,Ub=6;let hi=0;const Or=[];async function Xb(e){hi>=Ub&&await new Promise(t=>Or.push(t)),hi++;try{return await e()}finally{hi--,Or.shift()?.()}}function Vb(e,t){let n=fi.get(e);return n||(n=Xb(()=>Gb(t)).catch(()=>(fi.delete(e),null)),fi.set(e,n)),n}function Kb(e){return[e.image32,e.image16,e.source?.modernImage].find(n=>n?.startsWith(Er))?.slice(Er.length).trim()||void 0}function Wn({button:e,size:t,style:n}){const o=oe(c=>c.connectionUrl),i=Kb(e),s=i?`${o}|${i}`:"",[a,l]=z.useState({key:"",src:null});return z.useEffect(()=>{if(!s||!i)return;let c=!0;return Vb(s,i).then(d=>{c&&l({key:s,src:d})}),()=>{c=!1}},[s,i]),s&&a.key===s&&a.src?r.jsx("img",{src:a.src,width:t,height:t,alt:"","aria-hidden":!0,style:{objectFit:"contain",...n}}):r.jsx(Os,{name:e.icon||"apps_add_in",size:t,style:n})}const yc="__end__";function Jb(e,t){return`slot::${e}::${t??yc}`}function Yb(e){return`group::${e}`}function Mr(e){if(e.startsWith("slot::")){const[,t,n]=e.split("::");return{kind:"slot",groupId:t,beforeButtonId:n===yc?null:n}}return e.startsWith("group::")?{kind:"group",groupId:e.slice(7)}:null}const Ht={root:{display:"flex",gap:p.spacingHorizontalM,flexWrap:"wrap",alignItems:"flex-start",minHeight:"120px",padding:`${p.spacingVerticalS} ${p.spacingHorizontalM}`},groupButtons:{display:"flex",gap:p.spacingHorizontalXS,flexWrap:"wrap",minHeight:"72px",alignItems:"flex-start",padding:p.spacingHorizontalXS},groupLabel:{textAlign:"center",fontSize:p.fontSizeBase100,color:p.colorNeutralForeground3,borderTop:`1px solid ${p.colorNeutralStroke2}`,paddingTop:p.spacingVerticalXS,paddingBottom:p.spacingVerticalXS,marginTop:"auto"},emptyTab:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:p.spacingVerticalM,minHeight:"160px",color:p.colorNeutralForeground3,flex:1,padding:"48px",textAlign:"center"},addGroupBtn:{minHeight:"96px",width:"40px",display:"flex",alignItems:"center",justifyContent:"center",border:`1px dashed ${p.colorNeutralStroke2}`,borderRadius:p.borderRadiusMedium,cursor:"pointer",color:p.colorNeutralForeground3,backgroundColor:"transparent"},addButtonGhost:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",width:"60px",minHeight:"72px",borderRadius:p.borderRadiusMedium,border:`1px dashed ${p.colorNeutralStroke2}`,backgroundColor:"transparent",cursor:"pointer",color:p.colorNeutralForeground3}};function Zb({button:e}){const t=E(i=>i.locLabels),o=at()(e.label,t,void 0,e.source?.labelToken);return r.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:p.borderRadiusMedium,border:`1px solid ${p.colorBrandStroke1}`,backgroundColor:p.colorNeutralBackground1,boxShadow:p.shadow16,opacity:.9,cursor:"grabbing",pointerEvents:"none",color:e.custom?p.colorBrandForeground1:p.colorNeutralForeground1},children:[r.jsx(Wn,{button:e,size:24}),r.jsx("span",{style:{fontSize:p.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:p.colorNeutralForeground1},children:o})]})}function Qb({group:e,isDropTarget:t,children:n,...o}){const{setNodeRef:i,isOver:s}=Pa({id:Yb(e.id),data:{type:"group",groupId:e.id}});return r.jsx("div",{ref:i,style:{display:"flex",flexDirection:"column",minWidth:"80px",border:`1px solid ${s||t?p.colorBrandStroke1:p.colorNeutralStroke2}`,borderRadius:p.borderRadiusMedium,backgroundColor:s||t?p.colorBrandBackground2:p.colorNeutralBackground2,padding:`${p.spacingVerticalXS} ${p.spacingHorizontalXS}`,transition:"border-color 0.1s, background-color 0.1s"},...o,children:n})}function Br({groupId:e,beforeButtonId:t}){const n=Jb(e,t),{setNodeRef:o,isOver:i}=Pa({id:n,data:{type:"slot",groupId:e,beforeButtonId:t}});return r.jsx("div",{ref:o,style:{width:i?"2px":"0px",minHeight:"72px",backgroundColor:p.colorBrandStroke1,borderRadius:"2px",flexShrink:0,transition:"width 0.1s"},"aria-hidden":!0})}function ey({tab:e,location:t}){const n=E(P=>P.locLabels),o=at(),i=E(P=>P.baseLanguageCode),s=P=>o(P.label,n,i,P.source?.titleToken)||P.id,a=E(P=>P.baseline),l=E(P=>P.templates),c=E(P=>P.moveButton),d=E(P=>P.createGroup),u=E(P=>P.deleteButton),m=E(P=>P.layers),f=E(P=>P.duplicateButton),y=E(P=>P.duplicateGroup),x=E(P=>P.setGroupTemplate),h=E(P=>P.hideOobButton),S=E(P=>P.customizeOobButton),v=E(P=>P.setButtonProp),b=E(P=>P.renameGroup),w=E(P=>P.deleteGroup),C=ee(P=>P.openNewButton),I=ee(P=>P.openNewGroup),$=ee(P=>P.openIconPicker),j=ee(P=>P.openLocalizationEditor),R=te(P=>P.selectButtonInContext),T=te(P=>P.selectGroup),[A,W]=z.useState(null),[D,N]=z.useState(null),[M,k]=z.useState(null),[B,G]=z.useState(null),[X,Q]=z.useState(null),[ie,F]=z.useState(null),[_,L]=z.useState(null),[U,g]=z.useState(null),O=z.useMemo(()=>{if(!_)return null;for(const P of e.groups){const re=P.buttons.find(Te=>Te.id===_);if(re)return{button:re,groupId:P.id}}return null},[_,e.groups]),V=Ma(mo(za,{activationConstraint:{distance:5}}),mo(Ba)),de=P=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&P.oob&&!P.custom,Se=P=>rt(P.kind);function ve(P){L(String(P.active.id))}function le(P){const re=P.over;if(!re){g(null);return}const Te=Mr(String(re.id));g(Te?Te.groupId:null)}function H(P){const{active:re,over:Te}=P;if(L(null),g(null),!Te||!re)return;let Ye=null;for(const J of e.groups)if(J.buttons.some(K=>K.id===re.id)){Ye=J.id;break}if(!Ye)return;const qe=Mr(String(Te.id));if(!qe)return;let lt=null;qe.kind==="slot"?lt=c({groupId:Ye,buttonId:String(re.id),tabId:e.id,location:t},{groupId:qe.groupId,beforeButtonId:qe.beforeButtonId??void 0,tabId:e.id,location:t}):qe.kind==="group"&&qe.groupId!==Ye&&(lt=c({groupId:Ye,buttonId:String(re.id),tabId:e.id,location:t},{groupId:qe.groupId,tabId:e.id,location:t})),lt&&lt!==String(re.id)&&R(t,e.id,qe.groupId,lt)}return e.groups.length===0?r.jsxs("div",{style:Ht.emptyTab,children:[r.jsx(ko,{fontSize:36,"aria-hidden":!0}),r.jsx(q,{children:"This tab has no groups yet"}),r.jsxs("button",{type:"button",style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 16px",background:p.colorBrandBackground,color:p.colorNeutralForegroundInverted,border:"none",borderRadius:p.borderRadiusMedium,cursor:"pointer",fontSize:p.fontSizeBase300},onClick:()=>I(),children:[r.jsx(Ae,{fontSize:12})," Add first group"]})]}):r.jsxs(r.Fragment,{children:[t==="SubGrid"&&r.jsx(Re,{intent:"info",style:{margin:`${p.spacingVerticalS} ${p.spacingHorizontalM} 0`},children:r.jsxs(je,{children:["Subgrid ribbons support only 3 native controls: ",r.jsx("strong",{children:"Add"}),","," ",r.jsx("strong",{children:"Show List"}),", and ",r.jsx("strong",{children:"Delete"}),". Their icons cannot be changed."]})}),r.jsxs(La,{sensors:V,collisionDetection:Wp,onDragStart:ve,onDragOver:le,onDragEnd:H,children:[r.jsxs("div",{style:Ht.root,role:"treegrid","aria-label":"Ribbon canvas","data-ribbon-canvas-root":"1",children:[e.groups.map(P=>r.jsxs(Qb,{group:P,isDropTarget:U===P.id,role:"rowgroup","aria-label":s(P),tabIndex:0,"data-ribbon-group-id":P.id,onContextMenu:re=>{re.target.closest("[data-btn]")||(re.preventDefault(),N({group:P,x:re.clientX,y:re.clientY}))},onFocus:()=>T(P.id),onKeyDown:re=>{if((re.key==="Enter"||re.key===" ")&&P.buttons.length>0){re.preventDefault();const Te=P.buttons[0];if(!Te)return;R(t,e.id,P.id,Te.id),document.querySelector(`[data-ribbon-btn-id="${Te.id}"]`)?.focus()}},children:[r.jsxs("div",{style:Ht.groupButtons,children:[P.buttons.map(re=>r.jsxs(Je.Fragment,{children:[_&&r.jsx(Br,{groupId:P.id,beforeButtonId:re.id}),r.jsx(ty,{button:re,groupId:P.id,tabId:e.id,location:t,activeId:_,onContextMenu:Te=>W({groupId:P.id,button:re,x:Te.clientX,y:Te.clientY})})]},re.id)),_&&r.jsx(Br,{groupId:P.id,beforeButtonId:null}),r.jsxs("button",{type:"button",style:Ht.addButtonGhost,"data-add-btn-group-id":P.id,onClick:()=>C(P.id),title:`Add button to ${s(P)}`,"aria-label":`Add button to ${s(P)}`,children:[r.jsx(Ae,{fontSize:16}),r.jsx(q,{size:100,style:{color:"inherit"},children:"Add"})]})]}),r.jsx(Ee,{content:`Template: ${P.template||"Flexible2"}`,relationship:"description",children:r.jsx("div",{style:Ht.groupLabel,children:s(P)})})]},P.id)),r.jsx("button",{type:"button",style:Ht.addGroupBtn,onClick:()=>d({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:r.jsx(Ae,{fontSize:16})})]}),r.jsx(Hp,{dropAnimation:null,children:O?r.jsx(Zb,{button:O.button}):null})]}),A&&r.jsxs(Ri,{open:!0,onOpenChange:(P,re)=>!re.open&&W(null),positioning:{position:"below",align:"start",target:{getBoundingClientRect:()=>({x:A.x,y:A.y,top:A.y,left:A.x,right:A.x,bottom:A.y,width:0,height:0,toJSON:()=>({})})}},children:[r.jsx(ji,{disableButtonEnhancement:!0,children:r.jsx("span",{style:{display:"none"}})}),r.jsx($i,{children:r.jsxs(Ni,{children:[de(A.button)&&r.jsx(be,{disabled:!0,icon:r.jsx(Lt,{}),children:"OOB global command bar buttons cannot be customized."}),de(A.button)&&r.jsx(vt,{}),r.jsx(be,{icon:r.jsx(Ao,{}),onClick:()=>{R(t,e.id,A.groupId,A.button.id),W(null)},children:"Edit properties"}),r.jsx(be,{icon:r.jsx(uo,{}),disabled:de(A.button)||Se(A.button),onClick:()=>{R(t,e.id,A.groupId,A.button.id),$(),W(null)},children:"Change icon…"}),r.jsx(be,{icon:r.jsx($a,{}),disabled:de(A.button)||Se(A.button),onClick:()=>{j(A.button.id),W(null)},children:"Edit labels…"}),r.jsx(vt,{}),A.button.hidden?r.jsx(be,{icon:r.jsx(jt,{}),disabled:de(A.button),onClick:()=>{v(t,e.id,A.groupId,A.button.id,{hidden:!1}),W(null)},children:"Show button"}):r.jsx(be,{icon:r.jsx(st,{}),disabled:de(A.button),onClick:()=>{A.button.oob?k(A):v(t,e.id,A.groupId,A.button.id,{hidden:!0}),W(null)},children:"Hide button"}),(A.button.origin==="oob"||A.button.origin==="managed")&&r.jsx(be,{icon:r.jsx(An,{}),disabled:de(A.button)||Se(A.button),onClick:()=>{S(t,e.id,A.groupId,A.button.id),W(null)},children:"Create override…"}),r.jsx(sc,{location:t,tabId:e.id,groupId:A.groupId,button:A.button,onDone:()=>W(null)}),r.jsx(vt,{}),r.jsx(be,{icon:r.jsx(kn,{}),disabled:de(A.button),onClick:()=>{f(t,e.id,A.groupId,A.button.id),W(null)},children:"Duplicate"}),rc(e,A.groupId,A.button.id,n,i,o).map(P=>r.jsxs(be,{icon:r.jsx(Na,{}),disabled:de(A.button),onClick:()=>{const re=c({groupId:A.groupId,buttonId:A.button.id,tabId:e.id,location:t},{groupId:P.groupId,tabId:e.id,location:t});re&&R(t,e.id,P.groupId,re),W(null)},children:["Move to: ",P.text]},P.groupId)),Fn(A.button,a[t])&&r.jsxs(r.Fragment,{children:[r.jsx(vt,{}),r.jsx(be,{icon:r.jsx(Bt,{}),disabled:de(A.button),onClick:()=>{u(t,e.id,A.groupId,A.button.id),W(null)},children:"Delete"})]})]})})]}),D&&r.jsxs(Ri,{open:!0,onOpenChange:(P,re)=>!re.open&&N(null),positioning:{position:"below",align:"start",target:{getBoundingClientRect:()=>({x:D.x,y:D.y,top:D.y,left:D.x,right:D.x,bottom:D.y,width:0,height:0,toJSON:()=>({})})}},children:[r.jsx(ji,{disableButtonEnhancement:!0,children:r.jsx("span",{style:{display:"none"}})}),r.jsx($i,{children:r.jsxs(Ni,{children:[wl("group",D.group.id,a[t],Wo({layers:m},t))?r.jsx(be,{icon:r.jsx(Ys,{}),onClick:()=>{G(D.group),N(null)},children:"Rename…"}):r.jsx(be,{icon:r.jsx(Ys,{}),disabled:!0,title:ws,subText:"Only your own tabs and groups can be renamed",children:"Rename…"}),r.jsx(be,{icon:r.jsx(kn,{}),onClick:()=>{y(t,e.id,D.group.id),N(null)},children:"Duplicate group"}),r.jsx(be,{icon:r.jsx(An,{}),onClick:()=>{Q(D.group),N(null)},children:"Change template…"}),vs(D.group,a[t],Tn({layers:m},t))&&r.jsxs(r.Fragment,{children:[r.jsx(vt,{}),r.jsx(be,{icon:r.jsx(Bt,{}),onClick:()=>{F(D.group),N(null)},children:"Delete group"})]})]})})]}),B&&r.jsx(jb,{open:!0,initialLabel:s(B),onRename:P=>{b(t,e.id,B.id,P),G(null)},onCancel:()=>G(null)}),X&&r.jsx(Nb,{open:!0,currentTemplate:X.template,customTemplateIds:l.map(P=>P.id),loadedGroup:a[t].tabs.some(P=>P.id===e.id&&P.groups.some(re=>re.id===X.id)),onChange:P=>{x(t,e.id,X.id,P),Q(null)},onCancel:()=>Q(null)}),ie&&r.jsxs($o,{open:!0,title:"Delete group",confirmLabel:"Delete group",destructive:!0,onConfirm:()=>{w(t,e.id,ie.id),F(null)},onCancel:()=>F(null),children:["Delete the group “",s(ie),"” and its ",ie.buttons.length," button",ie.buttons.length===1?"":"s","?"]}),M&&r.jsx(Es,{open:!0,buttonLabel:o(M.button.label,n,void 0,M.button.source?.labelToken),onConfirmHide:()=>{h(t,e.id,M.groupId,M.button.id),k(null)},commandId:M.button.commandId,onConfirmDisplayRule:()=>{E.getState().hideWithDisplayRules(M.button.commandId),k(null)},onCancel:()=>k(null)})]})}const ty=Je.memo(function({button:t,groupId:n,tabId:o,location:i,activeId:s,onContextMenu:a}){const l=te(j=>j.selectedButtonId),c=te(j=>j.selectButtonInContext),d=E(j=>j.locLabels),u=at(),m=l===t.id,f=i==="Application"&&o==="Mscrm.GlobalTab"&&t.oob&&!t.custom,y=u(t.label,d,void 0,t.source?.labelToken),x=rt(t.kind)?fo[t.kind]:void 0,h=x?` (${x}, read-only)`:"",{attributes:S,listeners:v,setNodeRef:b,isDragging:w}=qp({id:t.id,data:{type:"button",button:t,groupId:n},disabled:t.managed||f}),C=w||s===t.id,I={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"4px",width:"60px",minHeight:"72px",padding:"4px",borderRadius:p.borderRadiusMedium,cursor:"grab",border:m?`1px solid ${p.colorBrandStroke1}`:t.custom?`1px solid ${p.colorBrandStroke2}`:"1px solid transparent",backgroundColor:m?p.colorBrandBackground2:t.managed?p.colorNeutralBackground3:"transparent",opacity:C?.3:t.hidden?.4:1,position:"relative",userSelect:"none",color:t.custom?p.colorBrandForeground1:p.colorNeutralForeground1,transition:"opacity 0.15s, border-color 0.1s, background-color 0.1s"},$=j=>{if(!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(j.key))return;j.preventDefault();const R=j.currentTarget.closest("[data-ribbon-canvas-root='1']");if(!R)return;const T=Array.from(R.querySelectorAll(`[data-ribbon-tab-id="${o}"][data-btn="1"]`)),A=T.findIndex(B=>B.dataset.ribbonBtnId===t.id);if(A<0||T.length===0)return;const W=j.key==="ArrowLeft"||j.key==="ArrowUp"?-1:1,D=Math.max(0,Math.min(T.length-1,A+W)),N=T[D],M=N?.dataset.ribbonGroupId,k=N?.dataset.ribbonBtnId;!N||!M||!k||(c(i,o,M,k),N.focus())};return r.jsx(Ee,{content:f?"OOB global command bar buttons cannot be customized.":`${y}${h}${t.hidden?" — hidden":""}`,relationship:"label",children:r.jsxs("button",{ref:b,type:"button","data-btn":"1","data-ribbon-tab-id":o,"data-ribbon-group-id":n,"data-ribbon-btn-id":t.id,style:I,"aria-selected":m,"aria-label":`${y}${h}${t.hidden?" — hidden":""}${t.custom?" (custom)":""}${t.managed?" (read-only)":""}`,onClick:()=>c(i,o,n,t.id),onFocus:()=>c(i,o,n,t.id),onKeyDown:j=>{if(j.key==="Enter"||j.key===" "){j.preventDefault(),c(i,o,n,t.id);return}$(j)},onContextMenu:j=>{j.preventDefault(),j.stopPropagation(),c(i,o,n,t.id),a(j)},...S,...v,children:[r.jsx(Wn,{button:t,size:24,style:{filter:t.custom?"none":"grayscale(40%) opacity(0.85)"}}),r.jsx("span",{style:{fontSize:p.fontSizeBase100,textAlign:"center",lineHeight:"1.2",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:p.colorNeutralForeground1},children:y}),x&&r.jsx("span",{style:{fontSize:p.fontSizeBase100,lineHeight:"1",maxWidth:"56px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:p.colorNeutralForeground3},children:x}),t.menu&&r.jsx(It,{fontSize:10,"aria-label":"Has a menu"}),t.hidden&&r.jsx("span",{style:{position:"absolute",top:2,right:2},"aria-hidden":!0,children:r.jsx(st,{fontSize:10,style:{color:p.colorNeutralForeground3}})}),t.custom&&!t.managed&&r.jsx(ue,{size:"extra-small",color:"brand",appearance:"tint",style:{position:"absolute",bottom:2,right:2},"aria-label":"Custom",children:"NEW"}),(t.managed||f)&&r.jsx("span",{style:{position:"absolute",top:2,left:2},title:f?"OOB global command bar buttons cannot be customized.":"Read-only (managed)",children:r.jsx(Lt,{fontSize:10,style:{color:p.colorNeutralForeground3}})})]})})}),ye=Nt()((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:i}=t(),s=i==="all"||o.apps.some(a=>a.id===i);e({status:o.error?"unavailable":"loaded",error:o.error??null,commands:o.commands,apps:o.apps,appFilter:s?i:"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&&te.getState().clearSelection(),e({selectedCommandId:n})}}));te.subscribe((e,t)=>{if(!ye.getState().selectedCommandId)return;(e.selectedButtonId&&e.selectedButtonId!==t.selectedButtonId||e.location!==t.location||e.tabId!==t.tabId)&&ye.setState({selectedCommandId:null})});const vn={Form:0,MainGrid:1,SubGrid:2,AssociatedGrid:3,GlobalHeader:5},xc={0:"Form",1:"Main grid",2:"Subgrid",3:"Associated grid",4:"Quick form",5:"Global header",6:"Dashboard"},Sc="appaction_appactionrule_classicrules",ny=["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"],gi="@OData.Community.Display.V1.FormattedValue",ke=e=>typeof e=="string"&&e.trim()!==""?e:typeof e=="number"?String(e):void 0,yt=e=>{if(e==null||e==="")return;const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0},Yn=e=>e===!0||e===1||e==="true"||e==="1",At=e=>{const t=ke(e);return t?t.toLowerCase():null};function oy(e){switch(yt(e)){case 1:return"dropdown";case 2:return"split";case 3:return"group";default:return"button"}}function iy(e){const t=yt(e);return t===1?"formula":t===2?"javascript":"none"}function sy(e){const t=yt(e);return t===1?"formula":t===2?"classicRules":"none"}function ry(e){const t=yt(e);return t===1?"migrated":t===2?"enhancedMigrated":"default"}function zr(e,t){const n={componentLibrary:ke(e[`${t}componentlibrary`]),componentName:ke(e[`${t}componentname`]),functionName:ke(e[`${t}functionname`])};return n.componentLibrary||n.componentName||n.functionName?n:void 0}function ay(e){return Array.isArray(e)?e.map(t=>{const n=At(t.appactionruleid);return n?{id:n,name:ke(t.name)??ke(t.uniquename)??n,uniqueName:ke(t.uniquename),kind:yt(t.type)===0?"enable":"display"}:null}).filter(t=>t!==null):[]}function ly(e){const t=At(e.appactionid);if(!t)return null;const n=yt(e.location);if(n===void 0)return null;const o=ke(e.name)??"",i=ke(e.uniquename)??o;return{id:t,name:o,uniqueName:i,label:ke(e.buttonlabeltext)??(o||i||t),tooltipTitle:ke(e.buttontooltiptitle),tooltipDescription:ke(e.buttontooltipdescription),accessibilityText:ke(e.buttonaccessibilitytext),appModuleId:At(e._appmoduleid_value),appName:ke(e[`_appmoduleid_value${gi}`]),scope:yt(e.context)===0?"all":"entity",contextValue:ke(e.contextvalue),contextEntityId:At(e._contextentity_value)??void 0,location:n,type:oy(e.type),sequence:yt(e.sequence)??yt(e.buttonsequencepriority)??0,hidden:Yn(e.hidden),disabled:Yn(e.isdisabled),origin:ry(e.origin),managed:Yn(e.ismanaged),fontIcon:ke(e.fonticon),iconWebResourceId:At(e._iconwebresourceid_value)??void 0,iconWebResourceName:ke(e[`_iconwebresourceid_value${gi}`]),parentId:At(e._parentappactionid_value),groupTitle:ke(e.grouptitle),groupTitleHidden:Yn(e.isgrouptitlehidden),action:iy(e.onclickeventtype),jsFunctionName:ke(e.onclickeventjavascriptfunctionname),jsParameters:ke(e.onclickeventjavascriptparameters),jsWebResourceId:At(e._onclickeventjavascriptwebresourceid_value)??void 0,jsWebResourceName:ke(e[`_onclickeventjavascriptwebresourceid_value${gi}`]),onSelectFormula:zr(e,"onclickeventformula"),visibility:sy(e.visibilitytype),visibilityFormula:zr(e,"visibilityformula"),classicRules:ay(e[Sc])}}function cy(e){const t=new Map;for(const n of e){const o=ly(n);o&&!t.has(o.id)&&t.set(o.id,o)}return[...t.values()]}function dy(e){switch(e){case"HomepageGrid":return[vn.MainGrid];case"SubGrid":return[vn.SubGrid,vn.AssociatedGrid];case"Form":return[vn.Form];case"Application":return[vn.GlobalHeader]}}function uy(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 my(e,t){return t==="all"||e.appModuleId===null||e.appModuleId===t.toLowerCase()}function py(e,t){const n=new Set(dy(t.location));return e.filter(o=>n.has(o.location)&&my(o,t.appFilter)&&uy(o,t.table))}const ts=(e,t)=>e.sequence-t.sequence||e.label.localeCompare(t.label)||e.id.localeCompare(t.id);function vc(e){const t=new Set(e.map(a=>a.id)),n=new Map,o=[];for(const a of e)if(a.parentId&&a.parentId!==a.id&&t.has(a.parentId)){const l=n.get(a.parentId)??[];l.push(a),n.set(a.parentId,l)}else o.push(a);const i=new Set,s=a=>{i.add(a.id);const l=(n.get(a.id)??[]).filter(c=>!i.has(c.id)).sort(ts);return{command:a,children:l.map(s)}};return o.sort(ts).map(s)}function wc(e){return e.flatMap(t=>[t.command,...wc(t.children)])}const Cc=/\{!EntityLogicalName\}/gi,fy=/(?:![A-Za-z0-9_]+)*!\d+$/;function hy(e,t){if(e.origin==="default")return[];const n=[],o=i=>{i.includes(".")&&!n.includes(i)&&n.push(i)};for(const i of[e.uniqueName,e.name]){if(!i)continue;const s=i.trim().replace(Cc,t).replace(fy,""),a=s.indexOf("_"),l=s.indexOf(".");a>0&&(l===-1||a<l)&&o(s.slice(a+1)),o(s)}return n}function ns(e,t){return e.replace(Cc,t).toLowerCase()}function Lr(e,t){const n=ns(e,t).split(".");return n.length<4||n[0]!=="mscrm"?null:[n[0],n[1],"*",...n.slice(3)].join(".")}function Pr(e,t,n,o={}){const i=new Map,s=new Map;for(const l of t){const c=ns(l,n);i.has(c)||i.set(c,l);const d=Lr(l,n);d&&!s.has(d)&&s.set(d,l)}const a=new Map;for(const l of e){if(l.disabled&&!o.includeDisabled)continue;const c=hy(l,n),d=c.map(m=>i.get(ns(m,n))).find(Boolean)??c.map(m=>Lr(m,n)).map(m=>m?s.get(m):void 0).find(Boolean);if(!d)continue;const u=a.get(d)??[];u.push({buttonId:d,command:l,effect:l.hidden?"hidden":"replaced"}),a.set(d,u)}return a}function gy(e,t,n){const o=a=>a.toLowerCase(),i=`mscrm.${o(t)}.${o(n)}.maintab`,s=e.find(a=>a.id==="Mscrm.GlobalTab")?.id;return t==="Application"&&s?s:e.find(a=>o(a.id)===i)?.id??e.find(a=>/maintab$/i.test(a.id)&&!/\.allentities\./i.test(a.id))?.id??s??e[0]?.id}function Ic(e){return(e.menu?.sections??[]).flatMap(t=>t.controls.flatMap(n=>[n,...Ic(n)]))}function by(e){const{commands:t,tabs:n,location:o,entityLogicalName:i}=e,s=n.flatMap(v=>v.groups.flatMap(b=>b.buttons)),a=[...s,...s.flatMap(Ic)].map(v=>v.id),l=new Map(t.map(v=>[v.id,v])),c=new Set([...Pr(t,a,i,{includeDisabled:!0}).values()].flat().map(v=>v.command.id)),d=new Map,u=(v,b=new Set)=>{const w=d.get(v.id);if(w!==void 0)return w;let C=v.parentId?l.get(v.parentId):void 0;for(const $=new Set;C?.type==="group"&&!c.has(C.id)&&!$.has(C.id);)$.add(C.id),C=C.parentId?l.get(C.parentId):void 0;const I=c.has(v.id)&&(!C||!b.has(C.id)&&u(C,b.add(v.id)));return d.set(v.id,I),I},f=(v=>{for(const[b,w]of v){const C=w.filter(I=>u(I.command));C.length>0?v.set(b,C):v.delete(b)}return v})(Pr(t,a,i)),y=new Set([...f.values()].flat().map(v=>v.command.id)),x=v=>{const b=new Set;for(let w=v.parentId;w&&!b.has(w);w=l.get(w)?.parentId??null){b.add(w);const C=l.get(w);if(C&&u(C))return w}},h=new Map,S=[];for(const v of t){const b=x(v);if(!b){u(v)||S.push(v);continue}if(y.has(v.id))continue;const w=h.get(b)??[];w.push(v),h.set(b,w)}for(const v of f.values())for(const b of v){const w=h.get(b.command.id);w&&(b.items=[...w].sort(ts))}return{commandBarTabId:gy(n,o,i),nodes:vc(S),overrides:f,unmatchedMigrated:S.filter(v=>v.origin!=="default")}}function yy(e,t){const n=new Map,o=[];for(const i of t){const s=e.find(l=>l.sequence>i.command.sequence);if(!s){o.push(i);continue}const a=n.get(s.id)??[];a.push(i),n.set(s.id,a)}return{before:n,trailing:o}}function Fr(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 xy(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 Sy(e,t,n){const o=new Map(t.map(s=>[s.id.toLowerCase(),s])),i=new Map;for(const s of n??[]){const a=o.get(s.toLowerCase());a&&i.set(a.id.toLowerCase(),a)}if(n)return[...i.values()].sort((s,a)=>s.name.localeCompare(a.name)||s.id.localeCompare(a.id));for(const s of e)!s.appModuleId||i.has(s.appModuleId)||i.set(s.appModuleId,o.get(s.appModuleId)??{id:s.appModuleId,name:s.appName??s.appModuleId});return[...i.values()].sort((s,a)=>s.name.localeCompare(a.name)||s.id.localeCompare(a.id))}function Bn(e,t){return e.appModuleId===null?"All apps":t?.get(e.appModuleId)??e.appName??e.appModuleId}function Ms(e,t){const n=Bn(e.command,t),o=e.command.appModuleId===null?"in all apps":`in ${n}`,i=e.effect==="hidden"?`Hidden by modern command ${e.command.label} ${o}`:`Rendered as modern command ${e.command.label} ${o} (migrated)`;return e.items?.length?`${i}; its menu also has ${e.items.map(s=>s.label).join(", ")}`:i}function Rc(e,t){if(!e?.length)return"";const n=e.find(o=>o.effect==="hidden");return n?` — ${Ms(n,t).replace(/^Hidden/,"hidden")}`:" — modern (migrated)"}const vy={button:"Command",dropdown:"Dropdown",split:"Split button",group:"Group"},wy={default:"Command designer",migrated:"Migrated from classic",enhancedMigrated:"Enhanced migrated from classic"};function jc(e,t){const n=[{label:"App",value:Bn(e,t)},{label:"Location",value:`${xc[e.location]??`Location ${e.location}`}${e.scope==="all"?" (all tables)":""}`},{label:"Type",value:vy[e.type]},{label:"Order",value:String(e.sequence)},{label:"Origin",value:wy[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:Fr(e.visibilityFormula)??"Power Fx formula"});else if(e.visibility==="classicRules"){const o=e.classicRules.filter(i=>i.kind==="display").map(i=>i.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:Fr(e.onSelectFormula)??"Power Fx formula"});else if(e.action==="javascript"){const o=e.jsWebResourceName??e.jsWebResourceId,i=e.jsFunctionName??"(no function)";n.push({label:"Action (JavaScript)",value:o?`${i} in ${o}`:i}),e.jsParameters&&n.push({label:"Parameters",value:e.jsParameters})}return n}function Cy(){return window.dataverseAPI}const zn=e=>e instanceof Error?e.message:String(e);async function No(e){const t=[],n=new Set;let o=e;for(;o&&!n.has(o);){n.add(o);const i=await Cy().queryData(o);t.push(...i.value??[]);const s=i["@odata.nextLink"];o=s?s.replace(/^.*\/api\/data\/v[\d.]+\//,""):void 0}return t}function $c(e){return/\b40[13]\b|0x80040220|prvRead|privilege|unauthori[sz]ed|forbidden|not have permission/i.test(zn(e))}const Nc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function _r(e,t){const n=[`contextvalue eq '${e.logicalName.replace(/'/g,"''")}'`];e.metadataId&&Nc.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)`,i=t?`&$expand=${Sc}($select=appactionruleid,name,uniquename,type)`:"";return`appactions?$select=${ny.join(",")}&$filter=${o}${i}`}async function Iy(e){const t=ne.getState();let n;try{n=await No(_r(e,!0))}catch(o){if($c(o))throw o;t.logInfo("dataverse",`Modern commands: classic rules couldn't be expanded (${zn(o)}); retrying without them.`),n=await No(_r(e,!1))}return cy(n)}async function Ry(e){const t=ne.getState(),n="appmodules?$select=appmoduleid,appmoduleidunique,name,uniquename",o=e.metadataId&&Nc.test(e.metadataId)?`appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 1 and objectid eq ${e.metadataId}`:null,[i,s]=await Promise.all([No(n),o?No(o).catch(d=>(t.logInfo("dataverse",`Modern commands: couldn't resolve which apps contain ${e.logicalName} (${zn(d)}).`),null)):Promise.resolve(null)]),a=i,l=a.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(s){const d=new Set(s.map(u=>u._appmoduleidunique_value).filter(u=>typeof u=="string").map(u=>u.toLowerCase()));c=new Set(a.filter(u=>u.appmoduleid&&u.appmoduleidunique&&d.has(u.appmoduleidunique.toLowerCase())).map(u=>String(u.appmoduleid).toLowerCase()))}return{apps:l,containingAppIds:c}}async function jy(e){const t=ne.getState(),[n,o]=await Promise.allSettled([Iy(e),Ry(e)]);if(n.status==="rejected"){const l=zn(n.reason);return t.logWarn("dataverse",$c(n.reason)?`No permission to read modern commands (appaction) for ${e.logicalName}; the canvas shows classic commands only. (${l})`:`Modern commands unavailable for ${e.logicalName}: ${l}`),{commands:[],apps:[],error:l}}o.status==="rejected"&&t.logInfo("dataverse",`Modern commands: app list unavailable (${zn(o.reason)}); showing app ids from the commands.`);const{apps:i,containingAppIds:s}=o.status==="fulfilled"?o.value:{apps:[],containingAppIds:null},a=xy(n.value,s);return t.logInfo("dataverse",`Loaded ${a.length} modern command${a.length===1?"":"s"} for ${e.logicalName}.`),{commands:a,apps:Sy(a,i,s)}}function $y(){const e=oe(n=>n.activeEntity?.logicalName),t=oe(n=>n.activeEntity?.metadataId);z.useEffect(()=>{const n=ye.getState();if(!e||typeof window.dataverseAPI>"u"){n.reset();return}const o=n.beginLoad(e);jy({logicalName:e,metadataId:t}).then(i=>ye.getState().finishLoad(o,i))},[e,t])}function pn(){const e=ye(n=>n.apps),t=ye(n=>n.commands);return z.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 Tc(e){const t=ye(s=>s.commands),n=ye(s=>s.appFilter),o=oe(s=>s.activeEntity?.logicalName),i=oe(s=>s.activeEntity?.metadataId);return z.useMemo(()=>o?py(t,{location:e,appFilter:n,table:{logicalName:o,metadataId:i}}):[],[t,n,e,o,i])}const os=new Set;function Ny(){os.clear()}function Bs(e){const t=Tc(e),n=oe(u=>u.activeEntity?.logicalName)??"",o=E(u=>u.ribbons[e]?.tabs),i=E(u=>u.ribbons[e]?.entityLogicalName??""),s=ye(u=>u.status==="loaded"?u.tableLogicalName:null),a=(o?.length??0)>0&&(e==="Application"||i.toLowerCase()===n.toLowerCase()),l=z.useMemo(()=>by({commands:t,tabs:a?o??[]:[],location:e,entityLogicalName:n}),[t,o,a,e,n]),d=!!n&&s===n&&a?l.unmatchedMigrated.map(u=>u.uniqueName).join(", "):"";return z.useEffect(()=>{const u=`${n}|${e}|${d}`;!d||os.has(u)||(os.add(u),ne.getState().logInfo("ribbon",`Migrated modern commands without a classic control in ${n} ${e}: ${d}`))},[d,n,e]),l}function zs(e,t){const n=Bs(e);return z.useMemo(()=>{const o=t.groups.flatMap(s=>s.buttons.map(a=>({id:a.id,sequence:a.sequence}))),i=t.id===n.commandBarTabId?n.nodes:[];return{nodes:i,placement:yy(o,i),overrides:n.overrides}},[n,t])}function Ty(e,t){const{overrides:n}=Bs(e);return t&&n.get(t)||ky}const ky=[];function Ay(){const e=ye(i=>i.selectedCommandId),t=te(i=>i.selectedButtonId),n=te(i=>i.location),o=Tc(n);return z.useMemo(()=>{if(!e||t)return null;const i=o.find(a=>a.id===e);if(!i)return null;let s;for(const a of vc(o))if(s=kc(a,e),s)break;return{command:i,children:s?wc(s.children):[]}},[e,t,o])}function kc(e,t){if(e.command.id===t)return e;for(const n of e.children){const o=kc(n,t);if(o)return o}}const Ac=me({chip:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,height:"32px",padding:`0 ${p.spacingHorizontalS}`,borderRadius:p.borderRadiusMedium,border:`1px dashed ${p.colorPaletteBerryBorderActive}`,backgroundColor:p.colorPaletteBerryBackground1,color:p.colorNeutralForeground1,cursor:"default",whiteSpace:"nowrap",flexShrink:0,userSelect:"none",":hover":{backgroundColor:p.colorPaletteBerryBackground2},":focus-visible":{outline:`2px solid ${p.colorBrandStroke1}`,outlineOffset:"2px"}},selected:{border:`1px solid ${p.colorPaletteBerryForeground2}`,backgroundColor:p.colorPaletteBerryBackground2},muted:{opacity:.5},hidden:{textDecoration:"line-through"},tooltip:{display:"flex",flexDirection:"column",gap:"2px",maxWidth:"360px"},tooltipRow:{fontSize:p.fontSizeBase200,overflowWrap:"anywhere"}});function Dc({node:e,appNames:t}){const n=Ac(),o=e.command;return r.jsxs("div",{className:n.tooltip,children:[r.jsx(q,{weight:"semibold",children:o.label}),r.jsx(q,{className:n.tooltipRow,children:"Modern command — read-only in CBS; edit it in the command designer."}),jc(o,t).map(i=>r.jsxs(q,{className:n.tooltipRow,children:[r.jsxs("b",{children:[i.label,":"]})," ",i.value]},i.label)),e.children.length>0&&r.jsxs(q,{className:n.tooltipRow,children:[r.jsx("b",{children:"Items:"})," ",e.children.map(i=>i.command.label).join(", ")]})]})}function Dy({node:e,appNames:t,showApp:n,onDragRejected:o}){const i=Ac(),s=e.command,a=ye(x=>x.selectedCommandId),l=ye(x=>x.selectCommand),c=te(x=>x.selectedButtonId),d=a===s.id&&!c,u=s.type==="dropdown"||s.type==="split"||e.children.length>0,m=s.fontIcon&&!s.fontIcon.startsWith("$")?s.fontIcon:"apps_add_in",f=`${s.hidden?" — hidden":""}${s.disabled?" — disabled":""}`,y=x=>{x.preventDefault(),x.stopPropagation(),x.dataTransfer.dropEffect="none",o?.()};return r.jsx(Ee,{content:r.jsx(Dc,{node:e,appNames:t}),relationship:"description",children:r.jsxs("button",{type:"button",draggable:!1,className:Qt(i.chip,d&&i.selected,(s.hidden||s.disabled)&&i.muted,s.hidden&&i.hidden),"aria-pressed":d,"aria-label":`${s.label} — modern command (read-only), ${Bn(s,t)}${f}`,onClick:()=>l(s.id),onDragStart:x=>x.preventDefault(),onDragOver:y,onDrop:y,onContextMenu:x=>{x.preventDefault(),l(s.id)},children:[r.jsx(Os,{name:m,size:16}),r.jsx(q,{size:200,children:s.label}),u&&r.jsx(It,{fontSize:12,"aria-hidden":!0}),s.hidden&&r.jsx(st,{fontSize:12,"aria-hidden":!0}),r.jsx(ue,{size:"extra-small",appearance:"tint",color:"important",icon:r.jsx(Lt,{}),children:"Modern"}),n&&r.jsx(ue,{size:"extra-small",appearance:"outline",color:"informative",children:Bn(s,t)})]})})}function Ls({overrides:e,appNames:t}){if(!e?.length)return null;const n=e.some(i=>i.effect==="hidden"),o=e.map(i=>Ms(i,t)).join(`
132
+ `);return r.jsx(ue,{size:"extra-small",appearance:"tint",color:n?"warning":"important",title:o,"aria-label":o,children:n?"Hidden by modern":"Modern (migrated)"})}const Zn="application/x-rw-btn",qr="application/x-rw-se",Ey=me({root:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,padding:`${p.spacingHorizontalS} 0`,minHeight:"48px"},scrollRow:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,flex:1,minWidth:0,overflowX:"auto",overflowY:"hidden",paddingBottom:p.spacingHorizontalXS},button:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,height:"32px",padding:`0 ${p.spacingHorizontalS}`,borderRadius:p.borderRadiusMedium,border:"1px solid transparent",cursor:"pointer",backgroundColor:"transparent",color:p.colorNeutralForeground1,whiteSpace:"nowrap",position:"relative",userSelect:"none",":hover":{backgroundColor:p.colorNeutralBackground3,border:`1px solid ${p.colorNeutralStroke1}`},":focus-visible":{outline:`2px solid ${p.colorBrandStroke1}`,outlineOffset:"2px"}},buttonSelected:{backgroundColor:p.colorBrandBackground2,border:`1px solid ${p.colorBrandStroke1}`},buttonHidden:{opacity:.4,textDecoration:"line-through"},buttonCustom:{border:`1px solid ${p.colorBrandStroke2}`},lockIcon:{position:"absolute",top:"4px",left:"4px",color:p.colorNeutralForeground3,pointerEvents:"none"},dropLine:{width:"2px",height:"24px",backgroundColor:p.colorBrandStroke1,borderRadius:"2px",flexShrink:0},overflowBtn:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,height:"32px",padding:`0 ${p.spacingHorizontalS}`,borderRadius:p.borderRadiusMedium,border:`1px solid ${p.colorNeutralStroke2}`,backgroundColor:p.colorNeutralBackground2,cursor:"pointer",color:p.colorNeutralForeground3,flexShrink:0},trailingControls:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,flexShrink:0,paddingLeft:p.spacingHorizontalS,borderLeft:`1px solid ${p.colorNeutralStroke2}`,marginLeft:p.spacingHorizontalXS}});function Oy({tab:e,location:t}){const n=Ey(),o=te(g=>g.selectedButtonId),i=te(g=>g.selectButtonInContext),s=E(g=>g.moveButton),a=E(g=>g.deleteButton),l=E(g=>g.baseline),c=E(g=>g.duplicateButton),d=E(g=>g.hideOobButton),u=E(g=>g.setButtonProp),m=E(g=>g.customizeOobButton),f=E(g=>g.locLabels),y=at(),x=E(g=>g.baseLanguageCode),h=(g,O,V)=>y(g,f,x,V)||O,S=ee(g=>g.openIconPicker),v=ee(g=>g.openLocalizationEditor),b=ee(g=>g.openNewButton),[w,C]=z.useState(null),[I,$]=z.useState(null),[j,R]=z.useState(null),[T,A]=z.useState(null),W=zs(t,e),D=pn(),N=ye(g=>g.appFilter==="all"),M=g=>r.jsx(Dy,{node:g,appNames:D,showApp:N,onDragRejected:()=>C(null)},g.command.id),k=g=>Rc(W.overrides.get(g.id),D),B=g=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&g.oob&&!g.custom,G=g=>rt(g.kind),X=g=>G(g)?` (${fo[g.kind]}, read-only)`:"",Q=e.groups.flatMap(g=>g.buttons.map(O=>({button:O,groupId:g.id})));function ie(g,O,V){g.dataTransfer.setData(Zn,JSON.stringify({groupId:O,buttonId:V})),g.dataTransfer.effectAllowed="move",$(V)}function F(){$(null),C(null)}function _(g,O){const V=Array.from(g.dataTransfer.types??[]);!V.includes(Zn)&&!V.includes(qr)||(g.preventDefault(),g.dataTransfer.dropEffect=V.includes(Zn)?"move":"copy",C({beforeButtonId:O}))}const L=E(g=>g.createButton);function U(g,O,V){g.preventDefault(),g.stopPropagation();const de=g.dataTransfer.getData(Zn);if(de){try{const ve=JSON.parse(de);if(ve?.buttonId){const le=s({groupId:ve.groupId,buttonId:ve.buttonId,tabId:e.id,location:t},{groupId:O,beforeButtonId:V??void 0,tabId:e.id,location:t});le&&le!==ve.buttonId&&i(t,e.id,O,le)}}catch{}C(null),$(null);return}const Se=g.dataTransfer.getData(qr);if(Se){try{const le=JSON.parse(Se)?.button;if(le){const H=`_copy_${Date.now()}`;L({location:t,tabId:e.id,groupId:O,button:{...yo(le,`${le.id}${H}`,ro(E.getState())),label:le.label??"New Button",kind:le.kind??"button",sequence:void 0,templateAlias:le.templateAlias??"o1",commandId:le.commandId??"",hidden:!1,oob:!1,custom:!0,managed:!1}})}}catch{}C(null),$(null);return}C(null),$(null)}return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:n.root,children:[r.jsxs("div",{className:n.scrollRow,onDragOver:g=>{g.preventDefault()},onDrop:g=>U(g,e.groups[0]?.id??"",null),children:[Q.map(({button:g,groupId:O})=>r.jsxs(Je.Fragment,{children:[W.placement.before.get(g.id)?.map(M),w?.beforeButtonId===g.id&&r.jsx("div",{className:n.dropLine,"aria-hidden":!0}),r.jsx(Ee,{content:B(g)?"OOB global command bar buttons cannot be customized.":`${y(g.label,f,void 0,g.source?.labelToken)}${X(g)}${g.hidden?" — hidden":""}${k(g)}`,relationship:"label",children:r.jsxs("button",{type:"button",className:[n.button,o===g.id?n.buttonSelected:"",g.hidden?n.buttonHidden:"",g.custom?n.buttonCustom:""].filter(Boolean).join(" "),"aria-selected":o===g.id,"aria-label":`${y(g.label,f,void 0,g.source?.labelToken)}${X(g)}${g.hidden?" — hidden":""}${k(g)}`,onClick:()=>i(t,e.id,O,g.id),onContextMenu:V=>{V.preventDefault(),i(t,e.id,O,g.id),R({button:g,groupId:O,x:V.clientX,y:V.clientY})},draggable:!g.managed&&!B(g),onDragStart:V=>ie(V,O,g.id),onDragEnd:F,onDragOver:V=>_(V,g.id),onDrop:V=>U(V,O,g.id),style:{opacity:I===g.id?.3:void 0},children:[r.jsx(Wn,{button:g,size:16}),r.jsx(q,{size:200,children:y(g.label,f,void 0,g.source?.labelToken)}),G(g)&&r.jsx(ue,{size:"extra-small",appearance:"outline",color:"informative",children:fo[g.kind]}),g.menu&&r.jsx(It,{fontSize:12,"aria-label":"Has a menu"}),g.hidden&&r.jsx(st,{fontSize:12,"aria-hidden":!0}),g.custom&&r.jsx(ue,{size:"extra-small",color:"brand",appearance:"tint","aria-label":"Custom",children:"NEW"}),r.jsx(Ls,{overrides:W.overrides.get(g.id),appNames:D}),B(g)&&r.jsx("span",{className:n.lockIcon,title:"OOB global command bar buttons cannot be customized.",children:r.jsx(Lt,{fontSize:12})})]})})]},g.id)),W.placement.trailing.map(M)]}),r.jsx("div",{className:n.trailingControls,children:(()=>{const g=e.groups[0];return g?r.jsx(Ee,{content:`Add a new button to "${h(g.label,g.id,g.source?.titleToken)}"`,relationship:"label",children:r.jsxs("button",{type:"button",className:n.overflowBtn,onClick:()=>b(g.id),"aria-label":"Add a new button",children:[r.jsx(Ae,{fontSize:14})," Add"]})}):r.jsx(Ee,{content:'No groups in this tab yet. Switch to "Classic ribbon" view to add a group first.',relationship:"label",children:r.jsxs("button",{type:"button",className:n.overflowBtn,disabled:!0,children:[r.jsx(Ae,{fontSize:14})," Add"]})})})()})]}),j&&r.jsxs(Ri,{open:!0,onOpenChange:(g,O)=>!O.open&&R(null),positioning:{position:"below",align:"start",target:{getBoundingClientRect:()=>({x:j.x,y:j.y,top:j.y,left:j.x,right:j.x,bottom:j.y,width:0,height:0,toJSON:()=>({})})}},children:[r.jsx(ji,{disableButtonEnhancement:!0,children:r.jsx("span",{style:{display:"none"}})}),r.jsx($i,{children:r.jsxs(Ni,{children:[B(j.button)&&r.jsx(be,{disabled:!0,children:"OOB global command bar buttons cannot be customized."}),B(j.button)&&r.jsx(vt,{}),r.jsx(be,{icon:r.jsx(Ao,{}),onClick:()=>{i(t,e.id,j.groupId,j.button.id),R(null)},children:"Edit properties"}),r.jsx(be,{icon:r.jsx(uo,{}),disabled:B(j.button)||G(j.button),onClick:()=>{i(t,e.id,j.groupId,j.button.id),S(),R(null)},children:"Change icon…"}),r.jsx(be,{icon:r.jsx($a,{}),disabled:B(j.button)||G(j.button),onClick:()=>{v(j.button.id),R(null)},children:"Edit labels…"}),r.jsx(vt,{}),j.button.hidden?r.jsx(be,{icon:r.jsx(jt,{}),disabled:B(j.button),onClick:()=>{u(t,e.id,j.groupId,j.button.id,{hidden:!1}),R(null)},children:"Show button"}):r.jsx(be,{icon:r.jsx(st,{}),disabled:B(j.button),onClick:()=>{j.button.oob?A(j):u(t,e.id,j.groupId,j.button.id,{hidden:!0}),R(null)},children:"Hide button"}),(j.button.origin==="oob"||j.button.origin==="managed")&&r.jsx(be,{icon:r.jsx(An,{}),disabled:B(j.button)||G(j.button),onClick:()=>{m(t,e.id,j.groupId,j.button.id),R(null)},children:"Create override…"}),r.jsx(sc,{location:t,tabId:e.id,groupId:j.groupId,button:j.button,onDone:()=>R(null)}),r.jsx(vt,{}),r.jsx(be,{icon:r.jsx(kn,{}),disabled:B(j.button),onClick:()=>{c(t,e.id,j.groupId,j.button.id),R(null)},children:"Duplicate"}),Fn(j.button,l[t])&&r.jsx(be,{icon:r.jsx(Bt,{}),disabled:B(j.button),onClick:()=>{a(t,e.id,j.groupId,j.button.id),R(null)},children:"Delete"}),rc(e,j.groupId,j.button.id,f,x,y).map(g=>r.jsxs(be,{icon:r.jsx(Na,{}),disabled:B(j.button),onClick:()=>{const O=s({groupId:j.groupId,buttonId:j.button.id,tabId:e.id,location:t},{groupId:g.groupId,tabId:e.id,location:t});O&&i(t,e.id,g.groupId,O),R(null)},children:["Move to: ",g.text]},g.groupId))]})})]}),T&&r.jsx(Es,{open:!0,buttonLabel:y(T.button.label,f,void 0,T.button.source?.labelToken),onConfirmHide:()=>{d(t,e.id,T.groupId,T.button.id),A(null)},commandId:T.button.commandId,onConfirmDisplayRule:()=>{E.getState().hideWithDisplayRules(T.button.commandId),A(null)},onCancel:()=>A(null)})]})}const My=e=>(bp({...e,renderRow:()=>null}),e),Ec=z.createContext(void 0),By=void 0,zy=()=>{var e;return(e=z.useContext(Ec))!=null?e:By},Ly=Ec.Provider,Oc=z.createContext({current:null}),Py={current:null},Mc=()=>{var e;return(e=z.useContext(Oc))!=null?e:Py},Fy=Oc.Provider,Bc=z.createContext({current:null}),_y={current:null},zc=()=>{var e;return(e=z.useContext(Bc))!=null?e:_y},qy=Bc.Provider,Wy=(e,t)=>{const{height:n,itemSize:o,width:i="100%",ariaRowIndexStart:s=2,children:a,listProps:l}=e,c=Mc(),d=zc(),m=yp({...e,children:a},t),f=z.useCallback(({data:h,index:S,style:v,isScrolling:b})=>{const w=h[S];return z.createElement(Ly,{value:s+S},z.createElement(xp,{value:w.rowId},a(w,v,S,b)))},[s,a]),y=z.useCallback(()=>{c.current&&d.current&&d.current.scroll({left:c.current.scrollLeft,behavior:"instant"})},[]),x=z.useCallback(h=>{var S;(S=c.current)==null||S.removeEventListener("scroll",y),c.current=h,h&&h.addEventListener("scroll",y)},[]);return{...m,itemSize:o,height:n,virtualizedRow:f,width:i,ariaRowIndexStart:s,listProps:l,outerRef:x}};function is(){return is=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},is.apply(null,arguments)}function Wr(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function ss(e,t){return ss=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,o){return n.__proto__=o,n},ss(e,t)}function Hy(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,ss(e,t)}var Hr=Number.isNaN||function(t){return typeof t=="number"&&t!==t};function Gy(e,t){return!!(e===t||Hr(e)&&Hr(t))}function Uy(e,t){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!Gy(e[n],t[n]))return!1;return!0}function bi(e,t){t===void 0&&(t=Uy);var n,o=[],i,s=!1;function a(){for(var l=[],c=0;c<arguments.length;c++)l[c]=arguments[c];return s&&n===this&&t(l,o)||(i=e.apply(this,l),s=!0,n=this,o=l),i}return a}var Xy=typeof performance=="object"&&typeof performance.now=="function",Gr=Xy?function(){return performance.now()}:function(){return Date.now()};function Ur(e){cancelAnimationFrame(e.id)}function Vy(e,t){var n=Gr();function o(){Gr()-n>=t?e.call(null):i.id=requestAnimationFrame(o)}var i={id:requestAnimationFrame(o)};return i}var yi=-1;function Xr(e){if(e===void 0&&(e=!1),yi===-1||e){var t=document.createElement("div"),n=t.style;n.width="50px",n.height="50px",n.overflow="scroll",document.body.appendChild(t),yi=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return yi}var Gt=null;function Vr(e){if(e===void 0&&(e=!1),Gt===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"),i=o.style;return i.width="100px",i.height="100px",t.appendChild(o),document.body.appendChild(t),t.scrollLeft>0?Gt="positive-descending":(t.scrollLeft=1,t.scrollLeft===0?Gt="negative":Gt="positive-ascending"),document.body.removeChild(t),Gt}return Gt}var Ky=150,Jy=function(t,n){return t};function Yy(e){var t,n=e.getItemOffset,o=e.getEstimatedTotalSize,i=e.getItemSize,s=e.getOffsetForIndexAndAlignment,a=e.getStartIndexForOffset,l=e.getStopIndexForStartIndex,c=e.initInstanceProps,d=e.shouldResetStyleCacheOnItemSizeChange,u=e.validateProps;return t=(function(m){Hy(f,m);function f(x){var h;return h=m.call(this,x)||this,h._instanceProps=c(h.props,Wr(h)),h._outerRef=void 0,h._resetIsScrollingTimeoutId=null,h.state={instance:Wr(h),isScrolling:!1,scrollDirection:"forward",scrollOffset:typeof h.props.initialScrollOffset=="number"?h.props.initialScrollOffset:0,scrollUpdateWasRequested:!1},h._callOnItemsRendered=void 0,h._callOnItemsRendered=bi(function(S,v,b,w){return h.props.onItemsRendered({overscanStartIndex:S,overscanStopIndex:v,visibleStartIndex:b,visibleStopIndex:w})}),h._callOnScroll=void 0,h._callOnScroll=bi(function(S,v,b){return h.props.onScroll({scrollDirection:S,scrollOffset:v,scrollUpdateWasRequested:b})}),h._getItemStyle=void 0,h._getItemStyle=function(S){var v=h.props,b=v.direction,w=v.itemSize,C=v.layout,I=h._getItemStyleCache(d&&w,d&&C,d&&b),$;if(I.hasOwnProperty(S))$=I[S];else{var j=n(h.props,S,h._instanceProps),R=i(h.props,S,h._instanceProps),T=b==="horizontal"||C==="horizontal",A=b==="rtl",W=T?j:0;I[S]=$={position:"absolute",left:A?void 0:W,right:A?W:void 0,top:T?0:j,height:T?"100%":R,width:T?R:"100%"}}return $},h._getItemStyleCache=void 0,h._getItemStyleCache=bi(function(S,v,b){return{}}),h._onScrollHorizontal=function(S){var v=S.currentTarget,b=v.clientWidth,w=v.scrollLeft,C=v.scrollWidth;h.setState(function(I){if(I.scrollOffset===w)return null;var $=h.props.direction,j=w;if($==="rtl")switch(Vr()){case"negative":j=-w;break;case"positive-descending":j=C-b-w;break}return j=Math.max(0,Math.min(j,C-b)),{isScrolling:!0,scrollDirection:I.scrollOffset<j?"forward":"backward",scrollOffset:j,scrollUpdateWasRequested:!1}},h._resetIsScrollingDebounced)},h._onScrollVertical=function(S){var v=S.currentTarget,b=v.clientHeight,w=v.scrollHeight,C=v.scrollTop;h.setState(function(I){if(I.scrollOffset===C)return null;var $=Math.max(0,Math.min(C,w-b));return{isScrolling:!0,scrollDirection:I.scrollOffset<$?"forward":"backward",scrollOffset:$,scrollUpdateWasRequested:!1}},h._resetIsScrollingDebounced)},h._outerRefSetter=function(S){var v=h.props.outerRef;h._outerRef=S,typeof v=="function"?v(S):v!=null&&typeof v=="object"&&v.hasOwnProperty("current")&&(v.current=S)},h._resetIsScrollingDebounced=function(){h._resetIsScrollingTimeoutId!==null&&Ur(h._resetIsScrollingTimeoutId),h._resetIsScrollingTimeoutId=Vy(h._resetIsScrolling,Ky)},h._resetIsScrolling=function(){h._resetIsScrollingTimeoutId=null,h.setState({isScrolling:!1},function(){h._getItemStyleCache(-1,null)})},h}f.getDerivedStateFromProps=function(h,S){return Zy(h,S),u(h),null};var y=f.prototype;return y.scrollTo=function(h){h=Math.max(0,h),this.setState(function(S){return S.scrollOffset===h?null:{scrollDirection:S.scrollOffset<h?"forward":"backward",scrollOffset:h,scrollUpdateWasRequested:!0}},this._resetIsScrollingDebounced)},y.scrollToItem=function(h,S){S===void 0&&(S="auto");var v=this.props,b=v.itemCount,w=v.layout,C=this.state.scrollOffset;h=Math.max(0,Math.min(h,b-1));var I=0;if(this._outerRef){var $=this._outerRef;w==="vertical"?I=$.scrollWidth>$.clientWidth?Xr():0:I=$.scrollHeight>$.clientHeight?Xr():0}this.scrollTo(s(this.props,h,S,C,this._instanceProps,I))},y.componentDidMount=function(){var h=this.props,S=h.direction,v=h.initialScrollOffset,b=h.layout;if(typeof v=="number"&&this._outerRef!=null){var w=this._outerRef;S==="horizontal"||b==="horizontal"?w.scrollLeft=v:w.scrollTop=v}this._callPropsCallbacks()},y.componentDidUpdate=function(){var h=this.props,S=h.direction,v=h.layout,b=this.state,w=b.scrollOffset,C=b.scrollUpdateWasRequested;if(C&&this._outerRef!=null){var I=this._outerRef;if(S==="horizontal"||v==="horizontal")if(S==="rtl")switch(Vr()){case"negative":I.scrollLeft=-w;break;case"positive-ascending":I.scrollLeft=w;break;default:var $=I.clientWidth,j=I.scrollWidth;I.scrollLeft=j-$-w;break}else I.scrollLeft=w;else I.scrollTop=w}this._callPropsCallbacks()},y.componentWillUnmount=function(){this._resetIsScrollingTimeoutId!==null&&Ur(this._resetIsScrollingTimeoutId)},y.render=function(){var h=this.props,S=h.children,v=h.className,b=h.direction,w=h.height,C=h.innerRef,I=h.innerElementType,$=h.innerTagName,j=h.itemCount,R=h.itemData,T=h.itemKey,A=T===void 0?Jy:T,W=h.layout,D=h.outerElementType,N=h.outerTagName,M=h.style,k=h.useIsScrolling,B=h.width,G=this.state.isScrolling,X=b==="horizontal"||W==="horizontal",Q=X?this._onScrollHorizontal:this._onScrollVertical,ie=this._getRangeToRender(),F=ie[0],_=ie[1],L=[];if(j>0)for(var U=F;U<=_;U++)L.push(z.createElement(S,{data:R,key:A(U,R),index:U,isScrolling:k?G:void 0,style:this._getItemStyle(U)}));var g=o(this.props,this._instanceProps);return z.createElement(D||N||"div",{className:v,onScroll:Q,ref:this._outerRefSetter,style:is({position:"relative",height:w,width:B,overflow:"auto",WebkitOverflowScrolling:"touch",willChange:"transform",direction:b},M)},z.createElement(I||$||"div",{children:L,ref:C,style:{height:X?"100%":g,pointerEvents:G?"none":void 0,width:X?g:"100%"}}))},y._callPropsCallbacks=function(){if(typeof this.props.onItemsRendered=="function"){var h=this.props.itemCount;if(h>0){var S=this._getRangeToRender(),v=S[0],b=S[1],w=S[2],C=S[3];this._callOnItemsRendered(v,b,w,C)}}if(typeof this.props.onScroll=="function"){var I=this.state,$=I.scrollDirection,j=I.scrollOffset,R=I.scrollUpdateWasRequested;this._callOnScroll($,j,R)}},y._getRangeToRender=function(){var h=this.props,S=h.itemCount,v=h.overscanCount,b=this.state,w=b.isScrolling,C=b.scrollDirection,I=b.scrollOffset;if(S===0)return[0,0,0,0];var $=a(this.props,I,this._instanceProps),j=l(this.props,$,I,this._instanceProps),R=!w||C==="backward"?Math.max(1,v):1,T=!w||C==="forward"?Math.max(1,v):1;return[Math.max(0,$-R),Math.max(0,Math.min(S-1,j+T)),$,j]},f})(z.PureComponent),t.defaultProps={direction:"ltr",itemData:void 0,layout:"vertical",overscanCount:2,useIsScrolling:!1},t}var Zy=function(t,n){t.children,t.direction,t.height,t.layout,t.innerTagName,t.outerTagName,t.width,n.instance},Qy=Yy({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,i,s,a){var l=t.direction,c=t.height,d=t.itemCount,u=t.itemSize,m=t.layout,f=t.width,y=l==="horizontal"||m==="horizontal",x=y?f:c,h=Math.max(0,d*u-x),S=Math.min(h,n*u),v=Math.max(0,n*u-x+u+a);switch(o==="smart"&&(i>=v-x&&i<=S+x?o="auto":o="center"),o){case"start":return S;case"end":return v;case"center":{var b=Math.round(v+(S-v)/2);return b<Math.ceil(x/2)?0:b>h+Math.floor(x/2)?h:b}default:return i>=v&&i<=S?i:i<v?v:S}},getStartIndexForOffset:function(t,n){var o=t.itemCount,i=t.itemSize;return Math.max(0,Math.min(o-1,Math.floor(n/i)))},getStopIndexForStartIndex:function(t,n,o){var i=t.direction,s=t.height,a=t.itemCount,l=t.itemSize,c=t.layout,d=t.width,u=i==="horizontal"||c==="horizontal",m=n*l,f=u?d:s,y=Math.ceil((f+o-m)/l);return Math.max(0,Math.min(a-1,n+y-1))},initInstanceProps:function(t){},shouldResetStyleCacheOnItemSizeChange:!0,validateProps:function(t){t.itemSize}});const ex=e=>{const{slots:t,slotProps:n}=Sp(e),{dir:o}=Da();return z.createElement(t.root,n.root,z.createElement(Qy,{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))},Ps=z.forwardRef((e,t)=>{const n=Wy(e,t);return My(n),ex(n)});Ps.displayName="DataGridBody";const tx=(e,t)=>{var n;const{targetDocument:o}=Da(),i=vp({targetDocument:o}),s=z.useRef(null),a=z.useRef(null);let l=e.containerWidthOffset;l===void 0&&(l=e.selectionMode?-44:0,l-=i||0);const c=wp({...e,"aria-rowcount":e.items.length,containerWidthOffset:l},t);return e.resizableColumns&&((n=e.resizableColumnsOptions)==null?void 0:n.autoFitColumns)===!1&&c.root.style&&(c.root.style.minWidth="auto"),{...c,headerRef:s,bodyRef:a}},nx=(e,t)=>z.createElement(qy,{value:e.headerRef},z.createElement(Fy,{value:e.bodyRef},Cp(e,t))),Fs=z.forwardRef((e,t)=>{const n=tx(e,t);return Ip(n),nx(n,Rp(n))});Fs.displayName="DataGrid";const ox=(e,t)=>{const n=zy();return jp({...e,"aria-rowindex":n},t)},ix=me({root:{minWidth:"fit-content"}}),sx=e=>{const t=ix();return e.root.className=Qt(t.root,e.root.className),$p(e),e},Ln=z.forwardRef((e,t)=>{const n=ox(e,t);return sx(n),Np(n)});Ln.displayName="DataGridRow";const rx=(e,t)=>{const n=Mc(),o=zc(),i=z.useCallback(()=>{n.current&&o.current&&n.current.scroll({left:o.current.scrollLeft,behavior:"instant"})},[]),s=z.useCallback(l=>{var c;(c=o.current)==null||c.removeEventListener("scroll",i),o.current=l,l&&l.addEventListener("scroll",i)},[]),a=Tp(e,t);return a.root.ref=kp(a.root.ref,s),a},ax=me({root:{overflowX:"auto",scrollbarWidth:"none","::-webkit-scrollbar":{width:0,height:0}}}),lx=e=>{const t=ax();return e.root.className=Qt(t.root,e.root.className),Ap(e),e},_s=z.forwardRef((e,t)=>{const n=rx(e,t);return lx(n),Dp(n)});_s.displayName="DataGridHeader";const cx=me({root:{marginTop:p.spacingVerticalM,display:"flex",flexDirection:"column",gap:p.spacingVerticalXS},header:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS},row:{cursor:"pointer",backgroundColor:p.colorPaletteBerryBackground1,":hover":{backgroundColor:p.colorPaletteBerryBackground2}},rowSelected:{backgroundColor:p.colorPaletteBerryBackground2,outline:`1px solid ${p.colorPaletteBerryBorderActive}`},hidden:{opacity:.55,textDecoration:"line-through"},mono:{fontFamily:p.fontFamilyMonospace,color:p.colorNeutralForeground3}}),dx={button:"command",dropdown:"dropdown",split:"split",group:"group"};function ux({tab:e,location:t}){const n=cx(),{nodes:o}=zs(t,e),i=pn(),s=ye(u=>u.selectedCommandId),a=ye(u=>u.selectCommand),l=te(u=>u.selectedButtonId);if(o.length===0)return null;const c=[],d=(u,m)=>{for(const f of u)c.push({node:f,depth:m}),d(f.children,m+1)};return d(o,0),r.jsxs("section",{className:n.root,"aria-label":"Modern commands",children:[r.jsxs("div",{className:n.header,children:[r.jsx(q,{weight:"semibold",size:200,children:"Modern commands"}),r.jsx(ue,{size:"small",appearance:"tint",color:"important",children:"read-only"}),r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"Built with the command designer (appaction). Edit them in the command designer."})]}),r.jsxs(Ep,{size:"small","aria-label":"Modern commands (read-only)",children:[r.jsx(Op,{children:r.jsxs(Zs,{children:[r.jsx(Ft,{style:{width:56},children:"#"}),r.jsx(Ft,{children:"Label"}),r.jsx(Ft,{children:"App"}),r.jsx(Ft,{children:"Location"}),r.jsx(Ft,{style:{width:90},children:"Type"}),r.jsx(Ft,{children:"Unique name"})]})}),r.jsx(Mp,{children:c.map(({node:u,depth:m})=>{const f=u.command,y=s===f.id&&!l;return r.jsxs(Zs,{className:Qt(n.row,y&&n.rowSelected),"aria-selected":y,tabIndex:0,onClick:()=>a(f.id),onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),a(f.id))},children:[r.jsx(_t,{children:f.sequence}),r.jsx(_t,{children:r.jsx(Ee,{content:r.jsx(Dc,{node:u,appNames:i}),relationship:"description",children:r.jsxs("span",{className:f.hidden||f.disabled?n.hidden:void 0,style:{paddingLeft:m*16,display:"inline-flex",gap:4,alignItems:"center"},children:[f.label,f.hidden&&r.jsx(st,{fontSize:12,"aria-label":"hidden"}),r.jsx(ue,{size:"extra-small",appearance:"tint",color:"important",children:"Modern"})]})})}),r.jsx(_t,{children:Bn(f,i)}),r.jsx(_t,{children:xc[f.location]??f.location}),r.jsx(_t,{children:r.jsx(ue,{size:"small",appearance:"outline",children:dx[f.type]})}),r.jsx(_t,{children:r.jsx("span",{className:n.mono,title:f.uniqueName,children:f.uniqueName})})]},f.id)})})]})]})}const mx=me({root:{width:"100%"},gridWrap:{height:"min(560px, calc(100vh - 320px))",minHeight:"260px"},row:{cursor:"pointer",":hover":{backgroundColor:p.colorNeutralBackground3}},rowSelected:{backgroundColor:p.colorBrandBackground2},iconCell:{width:"20px",height:"20px",borderRadius:"3px",backgroundColor:p.colorNeutralBackground4,display:"flex",alignItems:"center",justifyContent:"center",fontSize:p.fontSizeBase100,color:p.colorNeutralForeground3},clip:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"100%"}});function px({tab:e,location:t}){const n=mx(),o=te(b=>b.selectedButtonId),i=te(b=>b.selectButtonInContext),s=E(b=>b.setButtonProp),a=E(b=>b.locLabels),l=at(),c=E(b=>b.baseLanguageCode),d=b=>t==="Application"&&e.id==="Mscrm.GlobalTab"&&b.oob&&!b.custom,[u,m]=z.useState(""),{overrides:f}=zs(t,e),y=pn(),x=e.groups.flatMap(b=>b.buttons.map(w=>({button:w,label:l(w.label,a,void 0,w.source?.labelToken),groupId:b.id,groupLabel:l(b.label,a,c,b.source?.titleToken)}))),h=z.useMemo(()=>{const b=u.toLowerCase().trim();return b?x.filter(({button:w,label:C,groupLabel:I})=>w.id.toLowerCase().includes(b)||w.label.toLowerCase().includes(b)||C.toLowerCase().includes(b)||(w.commandId??"").toLowerCase().includes(b)||I.toLowerCase().includes(b)):x},[x,u]),S={seq:{defaultWidth:56,minWidth:48,idealWidth:56},icon:{defaultWidth:48,minWidth:40,idealWidth:48},label:{defaultWidth:260,minWidth:140,idealWidth:260},id:{defaultWidth:280,minWidth:160,idealWidth:280},kind:{defaultWidth:90,minWidth:72,idealWidth:90},group:{defaultWidth:160,minWidth:100,idealWidth:160},command:{defaultWidth:280,minWidth:160,idealWidth:280},visible:{defaultWidth:80,minWidth:64,idealWidth:80}},v=[ht({columnId:"seq",renderHeaderCell:()=>r.jsx(q,{size:200,weight:"semibold",children:"#"}),renderCell:({button:b})=>r.jsx(q,{size:200,children:b.sequence})}),ht({columnId:"icon",renderHeaderCell:()=>r.jsx(q,{size:200,weight:"semibold",children:"Icon"}),renderCell:({button:b})=>r.jsx("div",{className:n.iconCell,children:r.jsx(Wn,{button:b,size:16})})}),ht({columnId:"label",renderHeaderCell:()=>r.jsx(q,{size:200,weight:"semibold",children:"Label"}),renderCell:({button:b,label:w})=>r.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,minWidth:0},children:[r.jsx(q,{size:200,className:n.clip,title:w,children:w}),r.jsx(Ls,{overrides:f.get(b.id),appNames:y})]})}),ht({columnId:"id",renderHeaderCell:()=>r.jsx(q,{size:200,weight:"semibold",children:"ID"}),renderCell:({button:b})=>r.jsx(q,{size:200,font:"monospace",className:n.clip,title:b.id,style:{color:p.colorNeutralForeground3},children:b.id})}),ht({columnId:"kind",renderHeaderCell:()=>r.jsx(q,{size:200,weight:"semibold",children:"Kind"}),renderCell:({button:b})=>r.jsx(ue,{size:"small",appearance:"outline",children:b.kind})}),ht({columnId:"group",renderHeaderCell:()=>r.jsx(q,{size:200,weight:"semibold",children:"Group"}),renderCell:({groupLabel:b})=>r.jsx(q,{size:200,className:n.clip,title:b,children:b})}),ht({columnId:"command",renderHeaderCell:()=>r.jsx(q,{size:200,weight:"semibold",children:"Command"}),renderCell:({button:b})=>r.jsx(q,{size:200,font:"monospace",className:n.clip,title:b.commandId||"",style:{color:p.colorNeutralForeground3},children:b.commandId||"—"})}),ht({columnId:"visible",renderHeaderCell:()=>r.jsx(q,{size:200,weight:"semibold",children:"Visible"}),renderCell:({button:b,label:w,groupId:C})=>r.jsx(cs,{checked:!b.hidden,label:b.hidden?r.jsx(st,{fontSize:14}):void 0,disabled:d(b),title:d(b)?"OOB global command bar buttons cannot be customized.":void 0,"aria-label":`Toggle visibility of ${w}`,onChange:(I,$)=>s(t,e.id,C,b.id,{hidden:!$.checked})})})];return r.jsxs("div",{className:n.root,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS,padding:`${p.spacingVerticalXS} 0`},children:[r.jsx(Ue,{size:"small",contentBefore:r.jsx(wt,{}),placeholder:`Filter ${x.length} button${x.length!==1?"s":""}…`,value:u,onChange:(b,w)=>m(w.value),style:{minWidth:0,flex:1,maxWidth:480}}),u&&r.jsxs(q,{size:100,style:{color:p.colorNeutralForeground3},children:[h.length," match",h.length!==1?"es":""]})]}),r.jsxs(Fs,{className:n.gridWrap,items:h,columns:v,columnSizingOptions:S,resizableColumns:!0,getRowId:b=>b.button.id,focusMode:"composite",sortable:!0,selectionMode:"single",selectedItems:o?new Set([o]):new Set,onSelectionChange:(b,w)=>{const C=[...w.selectedItems][0],I=h.find($=>$.button.id===C);I&&i(t,e.id,I.groupId,I.button.id)},children:[r.jsx(_s,{children:r.jsx(Ln,{children:({renderHeaderCell:b})=>r.jsx(Ea,{children:b()})})}),r.jsx(Ps,{itemSize:42,height:420,listProps:{width:"100%"},children:({item:b,rowId:w},C)=>r.jsx(Ln,{style:C,className:o===b.button.id?n.rowSelected:n.row,children:({renderCell:I})=>r.jsx(Oa,{children:I(b)})},w)})]}),r.jsx(ux,{tab:e,location:t})]})}const Lc=me({root:{marginTop:p.spacingVerticalM,border:`1px solid ${p.colorNeutralStroke2}`,borderRadius:p.borderRadiusMedium,backgroundColor:p.colorNeutralBackground1,maxWidth:"520px"},header:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS,padding:`${p.spacingVerticalS} ${p.spacingHorizontalM}`,borderBottom:`1px solid ${p.colorNeutralStroke2}`},spacer:{flex:1},body:{display:"flex",flexDirection:"column",gap:p.spacingVerticalS,padding:p.spacingHorizontalS},section:{display:"flex",flexDirection:"column",gap:"2px"},sectionHeader:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,padding:`2px ${p.spacingHorizontalXS}`,color:p.colorNeutralForeground3},item:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS,width:"100%",minHeight:"28px",padding:`0 ${p.spacingHorizontalS}`,border:"1px solid transparent",borderRadius:p.borderRadiusMedium,backgroundColor:"transparent",color:p.colorNeutralForeground1,cursor:"pointer",textAlign:"left",":hover":{backgroundColor:p.colorNeutralBackground3},":focus-visible":{outline:`2px solid ${p.colorBrandStroke1}`}},itemSelected:{backgroundColor:p.colorBrandBackground2,border:`1px solid ${p.colorBrandStroke1}`},itemHidden:{opacity:.45,textDecoration:"line-through"},itemRow:{display:"flex",alignItems:"center",gap:"2px"},nested:{marginLeft:p.spacingHorizontalL,paddingLeft:p.spacingHorizontalS,borderLeft:`1px dashed ${p.colorNeutralStroke2}`},empty:{padding:`2px ${p.spacingHorizontalS}`,color:p.colorNeutralForeground3}});function fx({tab:e,location:t}){const n=Lc(),o=te($=>$.selectedButtonId),i=te($=>$.selectedGroupId),s=te($=>$.selectButtonInContext),a=E($=>$.baseline),l=E($=>$.locLabels),c=at(),d=E($=>$.addMenuSection),u=E($=>$.setMenuSectionProp),m=E($=>$.deleteMenuSection),{overrides:f}=Bs(t),y=pn(),x=e.groups.find($=>$.id===i),h=_f(x,o),S=z.useMemo(()=>{const $=new Set;for(const j of a[t]?.tabs??[])for(const R of j.groups)for(const T of Ne(R))$.add(T.id);return $},[a,t]);if(!x||!h||!h.menu&&!Kt(h.kind))return null;const v=x.id,b=$=>c($.label,l,void 0,$.source?.labelToken),w=$=>rl($.source?.attributes.PopulateDynamically)?$.source?.attributes.PopulateQueryCommand??"a command":null,C=$=>{const j=[...$.menu?.sections??[]].sort((A,W)=>A.sequence-W.sequence),R=!S.has($.id),T=w($);return r.jsxs(r.Fragment,{children:[T&&r.jsxs(Fe,{className:n.empty,children:["Populated when the menu opens, by ",T,". Static items below are kept as they are."]}),j.map(A=>r.jsx(hx,{section:A,parent:$,editable:R,onTitle:W=>u(t,e.id,v,$.id,A.id,{title:W}),onDisplayMode:W=>u(t,e.id,v,$.id,A.id,{displayMode:W}),onDelete:()=>m(t,e.id,v,$.id,A.id),renderItem:I},A.id)),j.length===0&&!T&&r.jsx(Fe,{className:n.empty,children:"No menu sections yet."}),R&&r.jsx("div",{children:r.jsx(Z,{size:"small",appearance:"subtle",icon:r.jsx(Ae,{}),onClick:()=>d(t,e.id,v,$.id,""),children:"Add section"})})]})},I=$=>{const j=$.id===o,R=f.get($.id);return r.jsxs("div",{children:[r.jsxs("div",{className:n.itemRow,children:[r.jsxs("button",{type:"button",className:[n.item,j?n.itemSelected:"",$.hidden?n.itemHidden:""].filter(Boolean).join(" "),"aria-pressed":j,"aria-label":`Menu item ${b($)}${$.hidden?" — hidden":""}${Rc(R,y)}`,onClick:()=>s(t,e.id,v,$.id),children:[r.jsx(Wn,{button:$,size:16}),r.jsx(q,{size:200,children:b($)}),$.menu&&r.jsx(It,{fontSize:12,"aria-hidden":!0}),r.jsx(Ls,{overrides:R,appNames:y}),$.custom&&!S.has($.id)&&r.jsx(ue,{size:"extra-small",color:"brand",appearance:"tint",children:"NEW"})]}),j&&r.jsx(bx,{item:$,location:t,tabId:e.id,groupId:v,onDeleted:()=>s(t,e.id,v,h.id)})]}),$.menu&&r.jsx("div",{className:n.nested,children:C($)})]},$.id)};return r.jsxs("section",{className:n.root,"aria-label":`Menu of ${b(h)}`,children:[r.jsxs("div",{className:n.header,children:[r.jsx(It,{"aria-hidden":!0}),r.jsx(q,{weight:"semibold",size:300,children:b(h)}),r.jsx(ue,{size:"small",appearance:"outline",children:h.kind==="splitButton"?"Split button menu":"Flyout menu"}),r.jsx("span",{className:n.spacer}),r.jsxs(Fe,{children:[zt(h).length," item(s)"]})]}),r.jsx("div",{className:n.body,children:C(h)})]})}function hx({section:e,parent:t,editable:n,onTitle:o,onDisplayMode:i,onDelete:s,renderItem:a}){const l=Lc(),c=E(m=>m.locLabels),d=at(),u=[...e.controls].sort((m,f)=>m.sequence-f.sequence);return r.jsxs("div",{className:l.section,children:[r.jsx("div",{className:l.sectionHeader,children:n?r.jsxs(r.Fragment,{children:[r.jsx(Ue,{size:"small",placeholder:"Section title (optional)",value:e.title??"","aria-label":"Menu section title",onChange:(m,f)=>o(f.value)}),r.jsxs($t,{size:"small","aria-label":"Menu section display mode",value:e.displayMode??"Menu16",onChange:(m,f)=>i(f.value),children:[r.jsx("option",{value:"Menu16",children:"16 px icons"}),r.jsx("option",{value:"Menu32",children:"32 px icons"}),r.jsx("option",{value:"Menu",children:"Text only"})]}),r.jsx(Ee,{content:"Delete section and its items",relationship:"label",children:r.jsx(Z,{size:"small",appearance:"subtle",icon:r.jsx(Bt,{}),onClick:s})})]}):r.jsx(Fe,{children:d(e.title,c,void 0,e.attributes?.Title)||e.id})}),u.map(m=>a(m)),e.rawContent!==void 0&&r.jsx(Fe,{className:l.empty,children:"Gallery / dynamic content (kept as is)"}),(e.rawControls?.length??0)>0&&r.jsxs(Fe,{className:l.empty,children:[e.rawControls.length," other control(s) CBS doesn't edit (kept as they are)"]}),e.rawContent===void 0&&r.jsx(gx,{parent:t,section:e})]})}function gx({parent:e,section:t}){const n=te(f=>f.location),o=te(f=>f.tabId),i=te(f=>f.selectedGroupId),s=te(f=>f.selectButtonInContext),a=E(f=>f.addMenuItem),l=E(f=>f.upsertCommand),c=oe(f=>f.activeSolution),d=oe(f=>f.publisherPrefix),u=oe(f=>f.activeEntity),m=()=>{if(!i)return;const{ribbons:f,commands:y}=E.getState(),x=new Set(y.map(b=>b.id));for(const b of Object.values(f))for(const w of b.tabs)for(const C of w.groups)for(const I of Ne(C))x.add(I.id);const h=c?.publisherPrefix?.trim()||d?.trim()||"new",{id:S,commandId:v}=jl(h,u?.logicalName??"global",n,"MenuItem",x);a({location:n,tabId:o,groupId:i,parentId:e.id,sectionId:t.id,item:{id:S,label:"Menu item",commandId:v}}),l({id:v,enableRules:[],displayRules:[],actions:[]}),s(n,o,i,S)};return r.jsx("div",{children:r.jsx(Z,{size:"small",appearance:"subtle",icon:r.jsx(Ae,{}),onClick:m,children:"Add item"})})}function bx({item:e,location:t,tabId:n,groupId:o,onDeleted:i}){const s=E(c=>c.setButtonProp),a=E(c=>c.deleteButton),l=E(c=>c.baseline[t]);return r.jsxs(r.Fragment,{children:[r.jsx(Ee,{content:e.hidden?"Show item":"Hide item",relationship:"label",children:r.jsx(Z,{size:"small",appearance:"subtle",icon:e.hidden?r.jsx(jt,{}):r.jsx(st,{}),onClick:()=>s(t,n,o,e.id,{hidden:!e.hidden})})}),Fn(e,l)&&r.jsx(Ee,{content:"Delete item",relationship:"label",children:r.jsx(Z,{size:"small",appearance:"subtle",icon:r.jsx(Bt,{}),onClick:()=>{a(t,n,o,e.id),i()}})})]})}function yx(){const e=ye(a=>a.status),t=ye(a=>a.apps),n=ye(a=>a.appFilter),o=ye(a=>a.setAppFilter),i=ye(a=>a.commands.length),s=ye(a=>a.error);return e==="idle"?null:e==="loading"?r.jsx(ds,{size:"extra-tiny","aria-label":"Loading modern commands"}):e==="unavailable"?r.jsx(Ee,{content:`Modern commands couldn't be read: ${s??"unknown error"}`,relationship:"label",children:r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"Modern: n/a"})}):r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS},children:[r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"App:"}),r.jsx(Ee,{content:`${i} modern command${i===1?"":"s"} for this table (read-only). Pick an app to see its command bar.`,relationship:"description",children:r.jsxs($t,{value:n,onChange:(a,l)=>o(l.value),size:"small","aria-label":"App for modern commands",style:{height:"26px",width:"170px"},children:[r.jsx("option",{value:"all",children:"All apps"}),t.map(a=>r.jsx("option",{value:a.id,children:a.name},a.id))]})})]})}const xx=me({root:{display:"flex",flexDirection:"column",flex:1,overflow:"hidden",backgroundColor:p.colorNeutralBackground1},locationRow:{display:"flex",alignItems:"center",gap:0,padding:`0 ${p.spacingHorizontalM}`,borderBottom:`1px solid ${p.colorNeutralStroke2}`,backgroundColor:p.colorNeutralBackground2,flexShrink:0,height:"36px"},locationTab:{height:"36px",padding:`0 ${p.spacingHorizontalM}`,display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,cursor:"pointer",borderBottom:"2px solid transparent",fontSize:p.fontSizeBase200,color:p.colorNeutralForeground2,":hover":{color:p.colorNeutralForeground1,backgroundColor:p.colorNeutralBackground3}},locationTabActive:{color:p.colorBrandForeground1,borderBottomColor:p.colorBrandStroke1,fontWeight:p.fontWeightSemibold},spacer:{flex:1},tabStrip:{display:"flex",alignItems:"center",gap:0,padding:`0 ${p.spacingHorizontalM}`,borderBottom:`1px solid ${p.colorNeutralStroke2}`,backgroundColor:p.colorNeutralBackground1,flexShrink:0,height:"32px"},ribbonTab:{height:"32px",padding:`0 ${p.spacingHorizontalM}`,display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"center",cursor:"pointer",borderBottom:"2px solid transparent",":hover":{backgroundColor:p.colorNeutralBackground3}},ribbonTabActive:{borderBottomColor:p.colorBrandStroke1},ribbonTabLabel:{fontSize:p.fontSizeBase200,fontWeight:p.fontWeightSemibold,lineHeight:1.2},ribbonTabMeta:{fontSize:p.fontSizeBase100,color:p.colorNeutralForeground3,lineHeight:1.2},addTabBtn:{height:"24px",width:"24px",minWidth:"24px",marginLeft:p.spacingHorizontalXS,borderRadius:p.borderRadiusMedium,border:`1px dashed ${p.colorNeutralStroke2}`,backgroundColor:"transparent",color:p.colorNeutralForeground3,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",":hover":{border:`1px solid ${p.colorNeutralStroke1}`,backgroundColor:p.colorNeutralBackground2}},inlineTabInput:{height:"28px",fontSize:p.fontSizeBase200,fontWeight:p.fontWeightSemibold,minWidth:"60px",maxWidth:"140px"},canvas:{flex:1,overflow:"auto",padding:p.spacingHorizontalM}}),Sx=me({root:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"80px",gap:p.spacingHorizontalM,color:p.colorNeutralForeground3}}),vx=[{value:"HomepageGrid",label:"Home Grid",icon:r.jsx(ga,{}),desc:"Mscrm.HomepageGrid.{entity}"},{value:"SubGrid",label:"Sub Grid",icon:r.jsx(lp,{}),desc:"Mscrm.SubGrid.{entity}"},{value:"Form",label:"Form",icon:r.jsx(ko,{}),desc:"Mscrm.Form.{entity}"},{value:"Application",label:"Application",icon:r.jsx(xa,{}),desc:"applicationRibbon.xml"}];function wx({isLoadingRibbon:e=!1,loadingTable:t,loadingStep:n=null,ribbonLoadError:o=null,layerReadError:i=null,onRetryRibbonLoad:s}){const a=xx(),l=te(H=>H.location),c=te(H=>H.tabId),d=te(H=>H.setLocation),u=te(H=>H.setTabId),m=E(H=>H.ribbons),f=E(H=>H.renameTab),y=E(H=>H.deleteTab),x=E(H=>H.locLabels),h=at(),S=E(H=>H.baseLanguageCode),v=E(H=>H.baseline),b=E(H=>H.layers),w=E(H=>H.orphans.entity.filter(P=>!H.pendingOrphanDeletes.entity.includes(P.id)&&!P.recentPublish?.published).length),C=te(H=>H.clearSelection),I=E(H=>H.reorderTabs),$=ee(H=>H.ribbonViewStyle),j=ee(H=>H.setRibbonViewStyle),R=ee(H=>H.openXmlDrawer),T=ee(H=>H.openTabDisplayRules),A=ee(H=>H.openNewGroup),W=ee(H=>H.openNewTab),[D,N]=z.useState(null),[M,k]=z.useState(""),B=z.useRef(null),[G,X]=z.useState(null),[Q,ie]=z.useState(!1),F=G?m[l].tabs.find(H=>H.id===G):void 0;z.useEffect(()=>{D&&B.current&&B.current.focus()},[D]);function _(){const H=m[l].tabs.find(P=>P.id===D);H&&M.trim()&&M.trim()!==Be(H.label,x,S)&&f(l,H.id,M.trim()),N(null)}function L(H){return Cl(H,v[l],Tn({layers:b},l))}function U(H){return wl("tab",H.id,v[l],Wo({layers:b},l))}const[g,O]=z.useState(null);function V(H){if(!U(H)){O(H.id),ne.getState().logInfo("canvas",`Tab ${H.id} can't be renamed: ${ws}.`);return}N(H.id),k(Be(H.label,x,S))}const de=Ma(mo(za,{activationConstraint:{distance:5}}),mo(Ba)),Se=z.useCallback(H=>{const{active:P,over:re}=H;if(!re||P.id===re.id)return;const Te=m[l].tabs.map(lt=>lt.id),Ye=Te.indexOf(String(P.id)),qe=Te.indexOf(String(re.id));Ye<0||qe<0||I(l,Gp(Te,Ye,qe))},[l,m,I]),ve=m[l],le=ve.tabs.find(H=>H.id===c)??ve.tabs.find(H=>H.id===Nn(ve.tabs));return z.useEffect(()=>{if(!ve.tabs.length)return;if(!ve.tabs.some(P=>P.id===c)){const P=Nn(ve.tabs);P&&u(P)}},[ve.tabs,c,u]),r.jsxs("main",{className:a.root,"aria-label":"Ribbon canvas",children:[r.jsxs("div",{className:a.locationRow,role:"tablist","aria-label":"Ribbon location",children:[vx.map(H=>r.jsxs("div",{role:"tab","aria-selected":l===H.value,className:`${a.locationTab} ${l===H.value?a.locationTabActive:""}`,onClick:()=>{d(H.value);const P=Nn(m[H.value].tabs);P&&u(P)},title:H.desc,tabIndex:l===H.value?0:-1,children:[H.icon,r.jsx(q,{size:200,children:H.label})]},H.value)),r.jsx("div",{className:a.spacer}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS},children:[r.jsx(yx,{}),r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"View as:"}),r.jsxs($t,{value:$,onChange:(H,P)=>j(P.value),size:"small",style:{height:"26px",width:"170px"},children:[r.jsx("option",{value:"classic",children:"Classic ribbon"}),r.jsx("option",{value:"modern",children:"Modern command bar"}),r.jsx("option",{value:"list",children:"List view"})]}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(on,{}),onClick:R,children:"XML"})]})]}),i&&!e&&!o&&r.jsxs(Re,{intent:"warning",layout:"multiline",style:{flexShrink:0},children:[r.jsxs(je,{children:["Couldn't read your unmanaged ribbon customizations, so labels may show as ids and ownership (what you can edit or delete) is unknown. Reload before editing. Details:"," ",i]}),s&&r.jsx(Xt,{children:r.jsx(Z,{size:"small",onClick:()=>ao()?ie(!0):s(),children:"Retry"})})]}),l==="Form"&&r.jsx(Re,{intent:"info",style:{flexShrink:0},children:r.jsx(je,{children:"Form ribbon customizations target the legacy web client. On Unified Interface, form commands render in a flat command bar — tab layout and scaling are ignored, but button visibility and command actions work as configured (same behaviour as Ribbon Workbench). Microsoft does not officially support the tabbed ribbon UI on Unified Interface."})}),l==="SubGrid"&&r.jsx(Re,{intent:"info",style:{flexShrink:0},children:r.jsx(je,{children:"Subgrid ribbons support only 3 native controls: Add, Show List, and Delete. Their icons cannot be changed."})}),l==="Application"&&r.jsx(Re,{intent:"info",style:{flexShrink:0},children:r.jsx(je,{children:"Buttons added to GlobalTab appear in the persistent global command bar at the top of every page. OOB GlobalTab buttons are read-only and cannot be customized."})}),le&&!/^(Mscrm|Microsoft)\./.test(le.id)&&r.jsx(Re,{intent:"info",style:{flexShrink:0},children:r.jsx(je,{children:oc})}),le&&qo(le.id)&&r.jsx(Re,{intent:"warning",style:{flexShrink:0},children:r.jsx(je,{children:"Unified Interface doesn't show this tab's buttons on the command bar, and they don't come back when the table is reloaded. Add buttons to the table's main tab instead."})}),l!=="Application"&&w>0&&r.jsxs(Re,{intent:"warning",style:{flexShrink:0},children:[r.jsxs(je,{children:[w," element",w!==1?"s":""," of your customizations for this table",w!==1?" aren't":" isn't"," on the canvas: the ribbon doesn't return"," ",w!==1?"them":"it",". See ",r.jsx("strong",{children:"Orphaned customizations"})," in the Properties pane to delete ",w!==1?"them":"it","."]}),r.jsx(Xt,{children:r.jsx(Z,{size:"small",onClick:C,children:"Show"})})]}),r.jsx(La,{sensors:de,onDragEnd:Se,children:r.jsx(Up,{items:ve.tabs.map(H=>H.id),strategy:Xp,children:r.jsxs("div",{className:a.tabStrip,role:"tablist","aria-label":"Ribbon tabs",children:[ve.tabs.map(H=>r.jsx(Ix,{tab:H,isActive:le?.id===H.id,isEditing:D===H.id,editValue:M,inputRef:H.id===D?B:void 0,onSelect:()=>{D!==H.id&&u(H.id),g!==H.id&&O(null)},onDoubleClick:()=>{u(H.id),V(H)},onF2:()=>V(H),renameRefused:g===H.id,onDelete:le?.id===H.id&&L(H)?()=>X(H.id):void 0,onEditChange:k,onEditCommit:_,onEditCancel:()=>N(null),styles:a},H.id)),r.jsx("button",{type:"button",className:a.addTabBtn,title:"Add tab","aria-label":"Add tab",onClick:W,children:r.jsx(Ae,{fontSize:12})}),r.jsx("div",{className:a.spacer}),r.jsxs(Z,{appearance:"subtle",size:"small",icon:r.jsx(jt,{}),onClick:T,children:["Tab rules",le&&le.tabDisplayRules.length>0&&r.jsx(ue,{size:"small",appearance:"tint",color:"brand",style:{marginLeft:4},children:le.tabDisplayRules.reduce((H,P)=>H+P.rules.length,0)})]})]})})}),r.jsx("div",{className:a.canvas,children:e?r.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%"},children:r.jsx(ds,{label:r.jsxs(r.Fragment,{children:[t?`Loading ${t}`:"Loading the ribbon",n&&r.jsxs(r.Fragment,{children:[r.jsx("br",{}),r.jsx("span",{style:{fontSize:"12px",opacity:.8},children:n})]})]})})}):o?r.jsxs(Re,{intent:"error",children:[r.jsxs(je,{children:["Failed to load ribbon definition. ",o]}),s&&r.jsx(Xt,{containerAction:r.jsx(Z,{appearance:"primary",size:"small",onClick:s,children:"Retry"})})]}):le?r.jsxs(r.Fragment,{children:[$==="classic"?r.jsx(ey,{tab:le,location:l}):$==="modern"?r.jsx(Oy,{tab:le,location:l}):r.jsx(px,{tab:le,location:l}),r.jsx(fx,{tab:le,location:l})]}):r.jsx(Cx,{onAddGroup:A})}),Q&&s&&r.jsx($o,{open:!0,title:"Reload the ribbon",confirmLabel:"Reload",onConfirm:()=>{ie(!1),s()},onCancel:()=>ie(!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."}),F&&r.jsxs($o,{open:!0,title:"Delete tab",confirmLabel:"Delete tab",destructive:!0,onConfirm:()=>{y(l,F.id),X(null)},onCancel:()=>X(null),children:["Delete the tab “",h(F.label,x,S,F.source?.titleToken),"” and its groups and buttons?"]})]})}function Cx({onAddGroup:e}){const t=Sx();return r.jsxs("div",{className:t.root,children:[r.jsx(ko,{fontSize:32,style:{opacity:.4}}),r.jsx(q,{size:300,children:"This tab has no groups yet"}),r.jsx(Z,{appearance:"primary",size:"small",icon:r.jsx(Ae,{}),onClick:e,children:"Add first group"})]})}function Ix({tab:e,isActive:t,isEditing:n,editValue:o,inputRef:i,onSelect:s,onDoubleClick:a,onF2:l,onEditChange:c,onEditCommit:d,onEditCancel:u,onDelete:m,renameRefused:f,styles:y}){const{attributes:x,listeners:h,setNodeRef:S,transform:v,transition:b,isDragging:w}=Vp({id:e.id}),C=E(T=>T.locLabels),I=at(),$=E(T=>T.baseLanguageCode),j=I(e.label,C,$,e.source?.titleToken),R={transform:Kp.Transform.toString(v),transition:b,opacity:w?.5:1,touchAction:"none"};return r.jsx("div",{ref:S,style:R,...x,...h,className:`${y.ribbonTab} ${t?y.ribbonTabActive:""}`,role:"tab","aria-selected":t,tabIndex:t?0:-1,onClick:s,onDoubleClick:a,title:f?`${ws}.`:void 0,onKeyDown:T=>{T.key==="F2"&&l()},children:n?r.jsx(Ue,{ref:i,className:y.inlineTabInput,value:o,onChange:(T,A)=>c(A.value),onBlur:d,onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),d()),T.key==="Escape"&&(T.preventDefault(),u()),T.stopPropagation()},onClick:T=>T.stopPropagation(),size:"small","aria-label":"Rename tab"}):r.jsxs(r.Fragment,{children:[r.jsx(q,{className:y.ribbonTabLabel,children:j}),r.jsx(q,{className:y.ribbonTabMeta,children:e.id}),m&&r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(Ot,{}),"aria-label":`Delete tab ${j}`,title:"Delete this tab and everything in it",onPointerDown:T=>T.stopPropagation(),onClick:T=>{T.stopPropagation(),m()}})]})})}let wn=null;const rs={set(e){wn=e},invoke(e){const t=wn;wn=null,t?.(e)},clear(){wn=null},hasPending(){return wn!==null}},Rx=["button","flyout","splitButton","textBox","comboBox","checkBox"],jx=me({root:{padding:`${p.spacingHorizontalM}`,display:"flex",flexDirection:"column",gap:p.spacingHorizontalS},sectionLabel:{color:p.colorNeutralForeground3,textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:p.spacingHorizontalXS,marginTop:p.spacingHorizontalS},row:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS},localeChips:{display:"flex",flexWrap:"wrap",gap:p.spacingHorizontalXS,alignItems:"center"},iconPreview:{width:"32px",height:"32px",borderRadius:"6px",backgroundColor:p.colorNeutralBackground4,color:p.colorNeutralForeground1,display:"flex",alignItems:"center",justifyContent:"center",border:`1px solid ${p.colorNeutralStroke2}`,flexShrink:0},webResLink:{fontFamily:p.fontFamilyMonospace,fontSize:p.fontSizeBase200,cursor:"pointer",color:p.colorBrandForeground1,textDecoration:"underline",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flex:1,border:"none",background:"transparent",textAlign:"left"}});function $x({button:e,location:t,tabId:n,groupId:o}){const i=jx(),s=E(I=>I.setButtonProp),a=E(I=>I.locLabels),l=E(I=>I.baseLanguageCode),c=ee(I=>I.openIconPicker),d=ee(I=>I.openLocalizationEditor),u=ee(I=>I.openWebResourceBrowser),m=E(I=>I.customizeOobButton),f=E(I=>I.customiseButton),y=oe(I=>I.activeSolution),x=oe(I=>I.publisherPrefix),h=te(I=>I.selectButtonInContext),S=E(I=>!I.ribbons[t].tabs.find($=>$.id===n)?.groups.find($=>$.id===o)?.buttons.some($=>$.id===e.id)),v=E(I=>El(I,t,e.id)),b=[...new Set([...S?gs:Rx,e.kind])];function w(I){s(t,n,o,e.id,I)}const C=Pf(e,a,l);return r.jsxs("div",{className:i.root,children:[(e.origin==="oob"||e.origin==="managed")&&r.jsx(Re,{intent:"warning",children:r.jsx(je,{children:r.jsxs(q,{size:200,children:[e.origin==="oob"?r.jsxs(r.Fragment,{children:["This is an ",r.jsx("strong",{children:"out-of-the-box"})," (system) button. To change it, create an override."]}):r.jsxs(r.Fragment,{children:["This button comes from a ",r.jsx("strong",{children:"managed solution"}),e.solutionName?r.jsxs(r.Fragment,{children:[" ","(",r.jsx("strong",{children:e.solutionName}),")"]}):null,e.publisherName?r.jsxs(r.Fragment,{children:[" by ",e.publisherName]}):null,". You can't edit it directly — create an override to change it."]})," ",r.jsx(Z,{size:"small",appearance:"subtle",onClick:()=>m(t,n,o,e.id),children:"Create override"}),Ns(t,n,e)&&r.jsx(Z,{size:"small",appearance:"subtle",title:"Copy the button into your solution and hide the original, so the copy can be changed and moved",onClick:()=>{const I=y?.publisherPrefix?.trim()||x?.trim()||"new",$=f(t,n,o,e.id,I);$&&h(t,n,o,$)},children:"Customise button"})]})})}),r.jsx(q,{size:100,weight:"semibold",className:i.sectionLabel,children:"Identity"}),r.jsx(ze,{label:"Label",children:r.jsx(Ue,{value:e.label,onChange:(I,$)=>w({label:$.value})})}),r.jsx(ze,{label:"Translations",children:r.jsxs("div",{className:i.localeChips,children:[C.map(I=>r.jsx(ue,{appearance:"filled",color:"informative",style:{cursor:"pointer"},onClick:()=>d(e.id),children:I===1033?"en-US":String(I)},I)),C.length===0&&r.jsx(ue,{appearance:"outline",color:"informative",children:"en-US (default)"}),r.jsx(Z,{size:"small",appearance:"subtle",icon:r.jsx(Ae,{}),onClick:()=>d(e.id),children:"Add language…"})]})}),r.jsx(ze,{label:"Tooltip title",children:r.jsx(Ue,{value:e.tooltipTitle??"",onChange:(I,$)=>w({tooltipTitle:$.value})})}),r.jsx(ze,{label:"Tooltip body",children:r.jsx(Bp,{value:e.tooltipBody??"",onChange:(I,$)=>w({tooltipBody:$.value}),resize:"vertical"})}),r.jsx(nt,{}),r.jsx(ze,{label:"Icon",children:r.jsxs("div",{className:i.row,children:[r.jsx("div",{className:i.iconPreview,children:e.icon?r.jsx(Os,{name:e.icon,size:20}):r.jsx(uo,{style:{color:p.colorNeutralForeground3}})}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(uo,{}),onClick:c,children:"Change…"})]})}),e.icon&&r.jsx(ze,{label:"ModernImage (auto)",children:r.jsx(Ue,{value:xs(e)??"(none)",readOnly:!0,contentAfter:r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"auto"})})}),e.image16&&r.jsx(ze,{label:"Image16",children:r.jsx("div",{className:i.row,children:r.jsx("button",{type:"button",className:i.webResLink,onClick:()=>{rs.set(I=>{w({image16:`$webresource:${I.name}`,icon:I.name.split("/").pop()?.replace(/\..*$/,"")})}),u()},title:e.image16,children:e.image16})})}),e.image32&&r.jsx(ze,{label:"Image32",children:r.jsx("div",{className:i.row,children:r.jsx("button",{type:"button",className:i.webResLink,onClick:()=>{rs.set(I=>{w({image32:`$webresource:${I.name}`})}),u()},title:e.image32,children:e.image32})})}),r.jsx(nt,{}),r.jsx(ze,{label:"Kind",hint:v?"A loaded control's kind can't be changed: add a new control instead.":S?"A menu holds buttons and flyouts.":void 0,children:r.jsx($t,{value:e.kind,disabled:v,onChange:(I,$)=>w({kind:$.value}),children:b.map(I=>r.jsx("option",{value:I,children:I},I))})}),r.jsxs("div",{className:i.row,style:{justifyContent:"space-between"},children:[r.jsx(q,{size:200,children:"Visible"}),r.jsx(cs,{checked:!e.hidden,"aria-label":"Toggle button visibility",onChange:(I,$)=>w({hidden:!$.checked})})]}),r.jsx(ze,{label:"Sequence",children:r.jsx(zp,{value:e.sequence,step:10,min:0,onChange:(I,$)=>w({sequence:Number($.value??e.sequence)})})}),r.jsx(ze,{label:"Template alias",children:r.jsx(Ue,{value:e.templateAlias,onChange:(I,$)=>w({templateAlias:$.value})})})]})}const Nx=me({row:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:p.spacingHorizontalS}}),Tx={oob:"informative",customising:"warning",customised:"brand",uncustomising:"danger",custom:"success",reloadRequired:"danger"};function Qn(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 kx({commandId:e,compact:t=!1}){const n=Nx(),o=ic(e),i=E(S=>S.customiseCommand),s=E(S=>S.uncustomiseCommand),a=E(S=>S.discardCommandChanges),l=E(S=>{const v=S.commands.find(w=>w.id===e),b=S.baselineCommands.find(w=>w.id===e);return!!v&&!!b&&JSON.stringify(v)!==JSON.stringify(b)}),[c,d]=z.useState(null);if(!o)return null;const u=(S,v,b)=>{l?d({what:S,confirmLabel:v,run:b}):b()},m=c&&r.jsxs($o,{open:!0,title:"Discard unpublished changes?",confirmLabel:c.confirmLabel,destructive:!0,onConfirm:()=>{c.run(),d(null)},onCancel:()=>d(null),children:[c.what," discards your unpublished changes to ",r.jsx("code",{children:e}),"."]}),{provenance:f}=o,y=f==="oob"?r.jsx(Z,{size:"small",appearance:"outline",onClick:()=>i(e),children:"Customise command"}):f==="customising"?r.jsx(Z,{size:"small",appearance:"subtle",onClick:()=>u("Discarding the customisation","Discard customisation",()=>a(e)),children:"Discard customisation"}):f==="customised"?r.jsx(Z,{size:"small",appearance:"subtle",onClick:()=>u("Uncustomising","Uncustomise",()=>s(e,o.scope)),children:"Uncustomise"}):f==="uncustomising"?r.jsx(Z,{size:"small",appearance:"subtle",onClick:()=>a(e),children:"Undo uncustomise"}):null,x=r.jsx(ue,{appearance:f==="oob"?"outline":"filled",color:Tx[f],size:"small",children:Rb[f]});if(t)return r.jsxs("div",{className:n.row,children:[x,y,m]});const h={oob:`Defined out of the box or by another solution. Customise it to copy the command — its actions, parameters and rule references — into ${Qn(o)}, where you can change it without touching its buttons. Editing it customises it too.`,customising:`On publish, this command is copied into ${Qn(o)} and replaces the original there. Rules keep their ids; a rule you edit is written to the layer as well.`,customised:`${Qn(o).replace(/^./,S=>S.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 ${Qn(o)} 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 r.jsx(Re,{intent:f==="uncustomising"||f==="reloadRequired"?"warning":"info",children:r.jsxs(je,{children:[r.jsxs("div",{className:n.row,children:[x,r.jsx(q,{size:200,children:h[f]}),y]}),m]})})}const Ax=me({root:{padding:`${p.spacingHorizontalM}`,display:"flex",flexDirection:"column",gap:p.spacingHorizontalS},sectionLabel:{color:p.colorNeutralForeground3,textTransform:"uppercase",letterSpacing:"0.5px",marginBottom:p.spacingHorizontalXS},commandRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:p.spacingHorizontalS,padding:`${p.spacingHorizontalXS} ${p.spacingHorizontalS}`,borderRadius:p.borderRadiusMedium,border:`1px solid ${p.colorNeutralStroke2}`,backgroundColor:p.colorNeutralBackground3},commandId:{fontFamily:p.fontFamilyMonospace,fontSize:p.fontSizeBase200,color:p.colorNeutralForeground1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function Dx({button:e,groupId:t,tabId:n,location:o}){const i=Ax(),s=E(h=>h.commands),a=E(h=>h.upsertCommand),l=E(h=>h.setButtonProp),c=E(h=>h.batch),d=ee(h=>h.openCommandEditor),[u,m]=Je.useState(""),f=s.find(h=>h.id===e.commandId),y=()=>{const h=new Set(s.map(v=>v.id)),S=Is("New","Command",h);c(()=>{a({id:S,enableRules:[],displayRules:[],actions:[]}),l(o,n,t,e.id,{commandId:S})}),d(S)},x=()=>{u&&(l(o,n,t,e.id,{commandId:u}),m(""))};return r.jsxs("div",{className:i.root,children:[r.jsx(nt,{}),r.jsx(q,{size:100,weight:"semibold",className:i.sectionLabel,children:"Command"}),f?r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:i.commandRow,children:[r.jsx(q,{className:i.commandId,children:f.id}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(on,{}),onClick:()=>d(f.id),children:"Edit"})]}),r.jsx(kx,{commandId:f.id,compact:!0}),f.actions.length>0&&r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:f.actions.map((h,S)=>r.jsx(Vo,{size:"extra-small",appearance:"outline",children:h.kind==="javascript"?`JS: ${h.functionName}`:h.kind==="url"?`URL: ${h.address}`:h.kind==="powerFx"?`Fx: ${h.expression}`:h.kind==="customApi"?`API: ${h.actionName}`:h.kind==="outlookCommand"?`Outlook: ${h.actionType}`:`XML: ${h.tagName}`},S))}),f.enableRules.length>0&&r.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"Enable rules:"}),f.enableRules.map(h=>r.jsx(Vo,{size:"extra-small",appearance:"outline",color:"success",children:h},h))]}),f.displayRules.length>0&&r.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:[r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"Display rules:"}),f.displayRules.map(h=>r.jsx(Vo,{size:"extra-small",appearance:"outline",color:"informative",children:h},h))]})]}):e.commandId?r.jsx("div",{className:i.commandRow,children:r.jsxs(q,{className:i.commandId,style:{color:p.colorStatusWarningForeground3},children:[e.commandId," (not found)"]})}):r.jsxs(r.Fragment,{children:[r.jsx(ze,{label:"Bind existing command",style:{width:"100%",minWidth:0},children:r.jsxs($t,{size:"small",value:u,onChange:(h,S)=>m(S.value),style:{width:"100%",minWidth:0},children:[r.jsx("option",{value:"",children:"Select command…"}),s.map(h=>r.jsx("option",{value:h.id,children:h.id},h.id))]})}),r.jsxs("div",{style:{display:"flex",gap:p.spacingHorizontalXS},children:[r.jsx(Z,{appearance:"outline",size:"small",onClick:x,children:"Bind selected"}),r.jsx(Z,{appearance:"outline",size:"small",icon:r.jsx(Ae,{}),onClick:y,children:"Create and bind"})]})]})]})}const Ex=me({section:{display:"flex",flexDirection:"column",gap:p.spacingHorizontalXS},header:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS},pillList:{display:"flex",flexWrap:"wrap",gap:p.spacingHorizontalXS,maxWidth:"100%",minWidth:0},pill:{display:"inline-flex",alignItems:"center",gap:"4px",padding:`2px ${p.spacingHorizontalXS}`,border:`1px solid ${p.colorNeutralStroke2}`,borderRadius:p.borderRadiusCircular,fontSize:p.fontSizeBase200,fontFamily:p.fontFamilyMonospace,cursor:"pointer",backgroundColor:p.colorNeutralBackground2,maxWidth:"100%",minWidth:0,":hover":{backgroundColor:p.colorNeutralBackground3}},pillLabel:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},addBtn:{alignSelf:"flex-start"},note:{fontSize:p.fontSizeBase100,color:p.colorNeutralForeground3,fontStyle:"italic"}}),Pc=({kind:e})=>{const t=Ex(),n=te(N=>N.location),o=te(N=>N.tabId),i=te(N=>N.selectedGroupId),s=te(N=>N.selectedButtonId),a=E(N=>N.commands),l=E(N=>N.displayRules),c=E(N=>N.enableRules),d=E(N=>N.upsertCommand),u=E(N=>N.upsertDisplayRule),m=E(N=>N.upsertEnableRule),f=E(N=>N.batch),y=ee(N=>N.openRuleEditor),v=E(N=>N.ribbons)[n].tabs.find(N=>N.id===o)?.groups.find(N=>N.id===i),b=mn(v,s),w=a.find(N=>N.id===b?.commandId),C=e==="display"?w?.displayRules??[]:w?.enableRules??[],I=e==="display"?l:c,[$,j]=Je.useState(""),R=I.filter(N=>!C.includes(N.id)),T=N=>{if(!w)return;const M=C.filter(k=>k!==N);d(e==="display"?{...w,displayRules:M}:{...w,enableRules:M})},A=e==="display"?"Display rules (ALL must pass)":"Enable rules (ALL must pass)",W=()=>{if(!w)return;if(e==="display"){const k=new Set(l.map(G=>G.id)),B=En(fr(w.id),"Display",k);f(()=>{u({id:B,steps:[]}),d({...w,displayRules:[...w.displayRules,B]})}),y(B,"display");return}const N=new Set(c.map(k=>k.id)),M=En(fr(w.id),"Enable",N);f(()=>{m({id:M,steps:[]}),d({...w,enableRules:[...w.enableRules,M]})}),y(M,"enable")},D=()=>{!w||!$||(d(e==="display"?{...w,displayRules:[...w.displayRules,$]}:{...w,enableRules:[...w.enableRules,$]}),j(""))};return r.jsxs("div",{className:t.section,children:[r.jsxs("div",{className:t.header,children:[r.jsx(q,{size:200,weight:"semibold",children:A}),C.length>0&&r.jsx(ue,{appearance:"tint",size:"small",color:"informative",children:C.length})]}),!w&&r.jsx(q,{className:t.note,children:"Bind a command first to manage rules."}),r.jsx("div",{className:t.pillList,children:C.map(N=>{const M=I.find(k=>k.id===N);return r.jsxs("div",{className:t.pill,children:[r.jsx("span",{className:t.pillLabel,onClick:()=>y(N,e==="display"?"display":"enable"),title:`${N} — ${M?.steps.length??0} step(s)`,children:N}),r.jsx("button",{style:{background:"none",border:"none",cursor:"pointer",padding:0,display:"flex",color:p.colorNeutralForeground3},onClick:()=>T(N),"aria-label":`Remove rule ${N}`,children:r.jsx(Ot,{style:{fontSize:12}})})]},N)})}),w&&r.jsxs(r.Fragment,{children:[r.jsx(ze,{label:`Bind existing ${e} rule`,style:{width:"100%",minWidth:0},children:r.jsxs($t,{size:"small",value:$,onChange:(N,M)=>j(M.value),style:{width:"100%",minWidth:0},children:[r.jsx("option",{value:"",children:"Select rule…"}),R.map(N=>r.jsx("option",{value:N.id,children:N.id},N.id))]})}),r.jsxs("div",{style:{display:"flex",gap:p.spacingHorizontalXS},children:[r.jsx(Z,{className:t.addBtn,appearance:"subtle",size:"small",onClick:D,disabled:!$,children:"Bind selected"}),r.jsxs(Z,{className:t.addBtn,appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:W,children:["Create new ",e," rule"]})]})]}),e==="enable"&&r.jsxs(q,{className:t.note,children:["Note: Disabled buttons are ",r.jsx("strong",{children:"hidden"})," in the modern command bar (Unified Interface). In the classic ribbon (Legacy client), disabled buttons remain visible but do not respond to clicks."]})]})},Ox=()=>r.jsx(Pc,{kind:"display"}),Mx=()=>r.jsx(Pc,{kind:"enable"}),Bx=me({section:{display:"flex",flexDirection:"column",gap:p.spacingHorizontalXS},header:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS},stepRow:{display:"flex",flexDirection:"column",gap:"8px",padding:`${p.spacingVerticalXS} ${p.spacingHorizontalXS}`,border:`1px solid ${p.colorNeutralStroke2}`,borderRadius:p.borderRadiusMedium,backgroundColor:p.colorNeutralBackground2},stepBadge:{alignSelf:"flex-start"},note:{fontSize:p.fontSizeBase100,color:p.colorNeutralForeground3,fontStyle:"italic"},warningNote:{fontSize:p.fontSizeBase100,color:p.colorStatusWarningForeground1,backgroundColor:p.colorStatusWarningBackground1,padding:`2px ${p.spacingHorizontalXS}`,borderRadius:p.borderRadiusSmall}}),zx=()=>{const e=Bx(),t=ee(c=>c.openScalingEditor),n=te(c=>c.location),o=te(c=>c.tabId),a=E(c=>c.ribbons)[n].tabs.find(c=>c.id===o),l=a?.groups.length??0;return r.jsxs("div",{className:e.section,children:[r.jsxs("div",{className:e.header,children:[r.jsx(q,{size:200,weight:"semibold",children:"Scaling"}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(Ao,{}),onClick:t,children:"Edit scaling"})]}),r.jsx("div",{className:e.warningNote,children:"⚠ Scaling applies only to the Classic ribbon (Legacy client / Outlook list views). The modern command bar (Unified Interface) ignores scaling."}),a?r.jsxs(q,{size:100,className:e.note,children:["Tab ",r.jsx("strong",{children:a.label})," has ",l," group(s). Open the Scaling Editor to configure MaxSize and Scale steps."]}):r.jsx(q,{size:100,className:e.note,children:"Select a tab to configure scaling."})]})},Lx=me({section:{display:"flex",flexDirection:"column",gap:p.spacingHorizontalXS},row:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS},note:{fontSize:p.fontSizeBase100,color:p.colorNeutralForeground3}}),Px=[{label:"Show on Unified Interface (Modern)",value:"Modern"},{label:"Show on legacy web client (Refresh)",value:"Refresh"},{label:"Show on classic ribbon (Legacy)",value:"Legacy"}],Fx=()=>{const e=Lx(),t=te(k=>k.location),n=te(k=>k.tabId),o=te(k=>k.selectedGroupId),i=te(k=>k.selectedButtonId),s=E(k=>k.ribbons),a=E(k=>k.upsertCommand),l=E(k=>k.upsertDisplayRule),c=E(k=>k.batch),d=E(k=>k.commands),u=E(k=>k.displayRules),m=ee(k=>k.openCommandEditor),f=E(k=>k.setOpenRecordOverride),y=te(k=>k.clearSelection),x=oe(k=>k.activeSolution),h=oe(k=>k.publisherPrefix),S=s[t],b=S.tabs.find(k=>k.id===n)?.groups.find(k=>k.id===o),w=mn(b,i),C=$l.includes(t),I=Tl(S),$=I.length>0,j=I.map(k=>kl(k)),R=j.includes("theirs"),T=!R&&j.includes("unknown"),A=!$&&!Al(S),W=$s(S).filter(k=>!Nl(k.button)),D=k=>{const B=x?.publisherPrefix?.trim()||h?.trim()||"new";!k&&I.some(G=>G.button.id===i)&&y(),!(!f(t,k,B)||!k)&&m(Pe)},N=()=>{if(w?.commandId)return d.find(k=>k.id===w.commandId)},M=k=>{const B=N();if(!B)return;let X=u.find(L=>L.steps.length===1&&L.steps[0].kind==="CommandClientTypeRule"&&L.steps[0].type===k&&!L.steps[0].invertResult&&L.steps[0].default===void 0)?.id,Q;if(!X){const L=`${B.id}.${k}.DisplayRule`;X=L;let U=1;for(;u.some(O=>O.id===X);)X=`${L}.${U}`,U+=1;Q={id:X,steps:[{kind:"CommandClientTypeRule",type:k}]}}const ie=L=>{const U=u.find(O=>O.id===L),g=U?.steps.length===1?U.steps[0]:void 0;return g?.kind==="CommandClientTypeRule"&&g.type!==k&&!g.invertResult&&g.default===void 0},F=X,_=B.displayRules.filter(L=>!ie(L));c(()=>{Q&&l(Q),(!_.includes(F)||_.length!==B.displayRules.length)&&a({...B,displayRules:_.includes(F)?_:[..._,F]})})};return r.jsxs("div",{className:e.section,children:[r.jsx(q,{size:200,weight:"semibold",children:"Advanced"}),w&&r.jsx("div",{children:r.jsxs(q,{size:100,className:e.note,children:["Tab: ",r.jsx("code",{style:{fontFamily:p.fontFamilyMonospace},children:n})]})}),C&&r.jsxs("div",{children:[r.jsx(cs,{label:`Override default record open behavior on the ${t==="SubGrid"?"sub-grid":"home grid"} (Mscrm.OpenRecordItem)`,checked:$,disabled:R||T||A,onChange:(k,B)=>D(B.checked)}),r.jsxs(q,{size:100,className:e.note,children:[`When enabled, the table gets a CommandDefinition with Id="Mscrm.OpenRecordItem" whose action runs instead of opening the record when a user double-clicks a row of this table's `,t==="SubGrid"?"sub-grids (on any form)":"home grid",`, selects its primary column link or presses Enter on it. As in Microsoft's recipe, an "Open record" button using the command is added to this location's command bar — the override only reaches a grid through a button there; don't hide that button. `,r.jsx("strong",{children:"Unified Interface only."})," The Command Editor will open so you can set the real web resource and function name; Publish is blocked until you do. Turning it off removes that button, and the command once no button uses it."]}),R&&r.jsx(q,{size:100,className:e.note,children:`The "Open record" button here comes from another solution, so the override can't be turned off from your customizations.`}),T&&r.jsx(q,{size:100,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.`}),W.length>0&&r.jsxs(q,{size:100,className:e.note,children:["Also using Mscrm.OpenRecordItem here:"," ",W.map(k=>k.button.id).join(", "),". Turning the override off keeps ",W.length===1?"it":"them"," and the command."]}),A&&r.jsx(q,{size:100,className:e.note,children:"This location has no group to put the button in."})]}),t==="Form"&&r.jsx(q,{size:100,className:e.note,children:"Form command bar changes apply to every main form of this table (ImportExportXml/Entities/Entity/RibbonDiffXml). Form-specific ribbons (systemform/form/RibbonDiffXml) aren't supported on Unified Interface, so CBS doesn't write them (#14)."}),r.jsxs("div",{children:[r.jsx(q,{size:100,weight:"semibold",className:e.note,children:"Client type filter (adds a CommandClientTypeRule):"}),r.jsxs(q,{size:100,className:e.note,children:[r.jsx("strong",{children:"Modern"})," = Unified Interface (web, tablets and phones) |"," ",r.jsx("strong",{children:"Refresh"})," = legacy updated web client | ",r.jsx("strong",{children:"Legacy"})," = classic ribbon / Outlook"]}),r.jsx("div",{className:e.row,style:{marginTop:"4px"},children:Px.map(k=>r.jsx(ue,{appearance:"outline",style:{cursor:"pointer"},title:`Add CommandClientTypeRule: ${k.value}`,onClick:()=>M(k.value),children:k.label},k.value))})]})]})},_x=me({banner:{marginBottom:p.spacingHorizontalXS}}),qx=()=>{const e=_x(),t=te(v=>v.selectedButtonId),n=te(v=>v.selectedGroupId),o=te(v=>v.location),i=te(v=>v.tabId),s=E(v=>v.conflicts),a=E(v=>v.ribbons),l=ee(v=>v.openConflictDrawer),u=a[o].tabs.find(v=>v.id===i)?.groups.find(v=>v.id===n),m=mn(u,t),f=s.find(v=>v.elementId===t),y=m?.origin==="managed";if(!t||!y&&!f)return null;const x=m?.solutionName??f?.solutions[0]?.solutionName,h=m?.publisherName??f?.solutions[0]?.publisher,S=f?.solutions.length??(y?1:0);return r.jsxs(Re,{intent:"warning",className:e.banner,children:[r.jsx(je,{children:r.jsx(q,{children:S>1?`This button is customized by ${S} solutions. The last imported solution wins.`:`This button belongs to a managed solution${x?` “${x}”`:""}${h?` by ${h}`:""}. Customizing it will create an unmanaged override.`})}),r.jsx(Xt,{children:r.jsx(Z,{appearance:"transparent",size:"small",onClick:()=>t&&l(t),children:"View solution layers"})})]})},Wx=me({root:{display:"flex",flexDirection:"column",gap:p.spacingVerticalXS,padding:`${p.spacingVerticalS} ${p.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS,minWidth:0},id:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:p.fontFamilyMonospace,fontSize:p.fontSizeBase200},pending:{textDecoration:"line-through",color:p.colorNeutralForeground3}});function Hx(){const e=Wx(),t=E(s=>s.layers),n=E(s=>s.pendingUnhides),o=E(s=>s.setLayerHideUnhidden),i=["entity","application"].flatMap(s=>(t[s]?.hides??[]).map(a=>({scope:s,...a})));return i.length===0?null:r.jsxs("section",{className:e.root,"aria-label":"Hidden by customizations",children:[r.jsx(Pt,{children:"Hidden by customizations"}),r.jsx(Fe,{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."}),i.map(s=>{const a=n[s.scope].includes(s.location);return r.jsxs("div",{className:e.row,children:[r.jsx(st,{}),r.jsx(Ee,{content:`${s.location} (${s.scope==="entity"?"this table":"application ribbon"})`,relationship:"description",children:r.jsx(q,{className:`${e.id} ${a?e.pending:""}`,children:s.location})}),r.jsx(Z,{size:"small",appearance:a?"subtle":"secondary",onClick:()=>o(s.scope,s.location,!a),children:a?"Keep hidden":"Unhide"})]},`${s.scope}:${s.location}`)})]})}const Gx=me({root:{display:"flex",flexDirection:"column",gap:p.spacingVerticalXS,padding:`${p.spacingVerticalS} ${p.spacingHorizontalM}`,textAlign:"left",width:"100%",boxSizing:"border-box"},row:{display:"flex",alignItems:"flex-start",gap:p.spacingHorizontalS,minWidth:0},icon:{flexShrink:0,marginTop:"2px",color:p.colorPaletteMarigoldForeground1},text:{display:"flex",flexDirection:"column",flex:1,minWidth:0},mono:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:p.fontFamilyMonospace,fontSize:p.fontSizeBase200},why:{color:p.colorNeutralForeground3},pending:{textDecoration:"line-through",color:p.colorNeutralForeground3}});function Ux(){const e=Gx(),t=E(l=>l.orphans),n=E(l=>l.pendingOrphanDeletes),o=E(l=>l.setOrphanDeleted),[i,s]=z.useState(null),a=["entity","application"].flatMap(l=>t[l].map(c=>({scope:l,...c})));return a.length===0?null:r.jsxs("section",{className:e.root,"aria-label":"Orphaned customizations",children:[r.jsx(Pt,{children:"Orphaned customizations"}),r.jsx(Fe,{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."}),a.map(l=>{const c=n[l.scope].includes(l.id),d=l.label&&l.label!==l.id?`“${l.label}” `:"",u=`${l.scope}:${l.id}`,m=!!l.recentPublish?.published,f=c?r.jsx(Z,{size:"small",appearance:"subtle","aria-label":`Keep ${l.id}`,onClick:()=>o(l.scope,l.id,!1),children:"Keep"}):m?r.jsx(Ee,{content:"Published from here moments ago: reload later — it most likely isn't loaded yet",relationship:"description",children:r.jsx(Z,{size:"small",disabledFocusable:!0,"aria-label":`Delete ${l.id}`,children:"Delete"})}):l.recentPublish&&i!==u?r.jsx(Z,{size:"small",appearance:"secondary","aria-label":`Delete ${l.id}`,onClick:()=>s(u),children:"Delete…"}):l.recentPublish?r.jsx(Z,{size:"small",appearance:"primary","aria-label":`Delete ${l.id} anyway`,onClick:()=>{s(null),o(l.scope,l.id,!0)},children:"Delete anyway"}):r.jsx(Z,{size:"small",appearance:"secondary","aria-label":`Delete ${l.id}`,onClick:()=>o(l.scope,l.id,!0),children:"Delete"});return r.jsxs("div",{className:e.row,children:[r.jsx(cp,{className:e.icon}),r.jsxs("div",{className:e.text,children:[r.jsx(Ee,{content:`${l.element} ${l.id} — CustomAction ${l.customActionId} at ${l.location}`,relationship:"description",children:r.jsxs(q,{className:Qt(e.mono,c&&e.pending),children:[d,l.id]})}),r.jsx(Fe,{className:Qt(e.mono,e.why),children:l.location}),r.jsx(Fe,{className:e.why,children:l.why})]}),f]},u)})]})}const Xx=me({root:{display:"flex",flexDirection:"column",gap:p.spacingVerticalS,padding:`${p.spacingVerticalS} ${p.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS},field:{display:"flex",flexDirection:"column",gap:"2px",minWidth:0},mono:{fontFamily:p.fontFamilyMonospace,fontSize:p.fontSizeBase200,overflowWrap:"anywhere"},xml:{margin:0,maxHeight:"240px",overflow:"auto",padding:p.spacingHorizontalS,borderRadius:p.borderRadiusMedium,backgroundColor:p.colorNeutralBackground3,fontFamily:p.fontFamilyMonospace,fontSize:p.fontSizeBase100,whiteSpace:"pre-wrap",overflowWrap:"anywhere"}});function Vx({button:e,location:t,tabId:n,groupId:o}){const i=Xx(),s=E(h=>h.locLabels),a=at(),l=E(h=>h.setButtonProp),c=E(h=>h.hideOobButton),d=E(h=>h.hideWithDisplayRules),[u,m]=z.useState(!1),f=t==="Application"&&n==="Mscrm.GlobalTab"&&e.oob&&!e.custom,y=fo[e.kind],x=(h,S)=>S?r.jsxs("div",{className:i.field,children:[r.jsx(Fe,{children:h}),r.jsx(q,{className:i.mono,children:S})]}):null;return r.jsxs("section",{className:i.root,"aria-label":`${y} (read-only)`,children:[r.jsxs("div",{className:i.title,children:[r.jsx(Lt,{"aria-hidden":!0}),r.jsx(Pt,{children:y})]}),r.jsxs(Fe,{children:["Command Bar Studio shows this <",Vt[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."]}),x("Label",a(e.label,s,void 0,e.source?.labelToken)),x("Id",e.id),x("Command",e.commandId||void 0),r.jsx("div",{children:r.jsx(Z,{size:"small",disabled:f,icon:e.hidden?r.jsx(jt,{}):r.jsx(st,{}),onClick:()=>!e.hidden&&e.oob?m(!0):l(t,n,o,e.id,{hidden:!e.hidden}),children:e.hidden?"Unhide":"Hide"})}),u&&r.jsx(Es,{open:!0,buttonLabel:a(e.label,s,void 0,e.source?.labelToken),commandId:e.commandId,onConfirmHide:()=>{c(t,n,o,e.id),m(!1)},onConfirmDisplayRule:()=>{d(e.commandId),m(!1)},onCancel:()=>m(!1)}),e.source?.xml&&r.jsxs("div",{className:i.field,children:[r.jsx(Fe,{children:"XML"}),r.jsx("pre",{className:i.xml,children:e.source.xml})]})]})}const qs=me({root:{display:"flex",flexDirection:"column",gap:p.spacingVerticalS,padding:`${p.spacingVerticalS} ${p.spacingHorizontalM}`},title:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS,flexWrap:"wrap"},grid:{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:p.spacingHorizontalM,rowGap:p.spacingVerticalXS,alignItems:"baseline"},key:{color:p.colorNeutralForeground3,fontSize:p.fontSizeBase200},value:{fontSize:p.fontSizeBase200,overflowWrap:"anywhere",minWidth:0},mono:{fontFamily:p.fontFamilyMonospace},list:{display:"flex",flexDirection:"column",gap:p.spacingVerticalXXS}});function ft({label:e,value:t,mono:n}){const o=qs();return t?r.jsxs(r.Fragment,{children:[r.jsx(q,{className:o.key,children:e}),r.jsx(q,{className:`${o.value} ${n?o.mono:""}`,children:t})]}):null}function Kx({command:e,items:t}){const n=qs(),o=pn(),i=ye(l=>l.selectCommand),s=ye(l=>e.parentId?l.commands.find(c=>c.id===e.parentId):void 0),a=e.visibility==="formula"||e.action==="formula";return r.jsxs("section",{className:n.root,"aria-label":"Modern command properties",children:[r.jsxs("div",{className:n.title,children:[r.jsx(Pt,{children:e.label}),r.jsx(ue,{appearance:"tint",color:"important",children:"Modern"}),e.managed&&r.jsx(ue,{appearance:"outline",color:"informative",children:"Managed"})]}),r.jsx(Re,{intent:"info",children:r.jsx(je,{children:"Modern commands are read-only in Command Bar Studio and are never published from here. Edit them in the command designer."})}),r.jsxs("div",{className:n.grid,children:[jc(e,o).map(l=>r.jsx(ft,{label:l.label,value:l.value},l.label)),r.jsx(ft,{label:"Tooltip title",value:e.tooltipTitle}),r.jsx(ft,{label:"Tooltip text",value:e.tooltipDescription}),r.jsx(ft,{label:"Accessibility text",value:e.accessibilityText}),r.jsx(ft,{label:"Icon",value:e.fontIcon??e.iconWebResourceName??e.iconWebResourceId}),r.jsx(ft,{label:"Group title",value:e.groupTitle}),r.jsx(ft,{label:"Name",value:e.name}),r.jsx(ft,{label:"Unique name",value:e.uniqueName,mono:!0}),r.jsx(ft,{label:"Id",value:e.id,mono:!0})]}),a&&r.jsx(Fe,{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."}),s&&r.jsxs(r.Fragment,{children:[r.jsx(nt,{}),r.jsx(q,{className:n.key,children:"Inside"}),r.jsx(Ti,{onClick:()=>i(s.id),children:s.label})]}),t.length>0&&r.jsxs(r.Fragment,{children:[r.jsx(nt,{}),r.jsxs(q,{className:n.key,children:["Items (",t.length,")"]}),r.jsx("div",{className:n.list,children:t.map(l=>r.jsxs(Ti,{onClick:()=>i(l.id),children:[l.label,l.hidden?" (hidden)":""]},l.id))})]}),e.classicRules.length>0&&r.jsxs(r.Fragment,{children:[r.jsx(nt,{}),r.jsxs(q,{className:n.key,children:["Classic rules (",e.classicRules.length,")"]}),r.jsx("div",{className:n.list,children:e.classicRules.map(l=>r.jsxs(q,{className:`${n.value} ${n.mono}`,children:[l.kind==="enable"?"Enable":"Display",":"," ",l.uniqueName??l.name]},l.id))})]})]})}function Jx({overrides:e}){const t=qs(),n=pn(),o=ye(s=>s.selectCommand);if(e.length===0)return null;const i=e.some(s=>s.effect==="hidden");return r.jsx("section",{className:t.root,"aria-label":"Modern command overrides",children:r.jsx(Re,{intent:i?"warning":"info",children:r.jsx(je,{children:r.jsxs("div",{className:t.list,children:[e.map(s=>r.jsxs("span",{children:[Ms(s,n),"."," ",r.jsx(Ti,{inline:!0,onClick:()=>o(s.command.id),children:"View"})]},s.command.id)),r.jsx(Fe,{children:"Matched by the migrated command's unique name. Unified Interface may show the modern command instead of this button."})]})})})})}const Yx=me({root:{display:"flex",flexDirection:"column",height:"100%",overflowY:"auto",backgroundColor:p.colorNeutralBackground2,borderLeft:`1px solid ${p.colorNeutralStroke2}`},header:{padding:`${p.spacingHorizontalS} ${p.spacingHorizontalM}`,borderBottom:`1px solid ${p.colorNeutralStroke2}`,flexShrink:0},empty:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",flex:1,gap:p.spacingHorizontalM,color:p.colorNeutralForeground3,padding:p.spacingHorizontalXL,textAlign:"center"},section:{padding:`${p.spacingHorizontalS} ${p.spacingHorizontalM}`}});function Zx(){const e=Yx(),t=te(h=>h.selectedButtonId),n=te(h=>h.selectedGroupId),o=te(h=>h.location),i=te(h=>h.tabId),c=E(h=>h.ribbons)[o].tabs.find(h=>h.id===i)?.groups.find(h=>h.id===n),d=mn(c,t),u=c&&d?bo(c,d.id):void 0,m=E(h=>h.locLabels),f=at(),y=Ay(),x=Ty(o,d?.id);return r.jsxs("aside",{className:e.root,"aria-label":"Properties",children:[r.jsx("div",{className:e.header,children:r.jsx(Pt,{children:"Properties"})}),!d&&y?r.jsx(Kx,{command:y.command,items:y.children}):d?r.jsxs(r.Fragment,{children:[r.jsx(qx,{}),r.jsx(Jx,{overrides:x}),u&&r.jsx("div",{className:e.section,children:r.jsxs(Fe,{children:["Menu item of “",f(u.parent.label,m,void 0,u.parent.source?.labelToken),"”",u.section.title?` — section “${u.section.title}”`:""]})}),rt(d.kind)?r.jsx(Vx,{button:d,location:o,tabId:i,groupId:n}):r.jsxs(r.Fragment,{children:[r.jsx($x,{button:d,location:o,tabId:i,groupId:n}),r.jsx(nt,{}),r.jsx("div",{className:e.section,children:r.jsx(Dx,{button:d,groupId:n,tabId:i,location:o})}),r.jsx(nt,{}),r.jsx("div",{className:e.section,children:r.jsx(Ox,{})}),r.jsx(nt,{}),r.jsx("div",{className:e.section,children:r.jsx(Mx,{})}),r.jsx(nt,{}),r.jsx("div",{className:e.section,children:r.jsx(zx,{})}),r.jsx(nt,{}),r.jsx("div",{className:e.section,children:r.jsx(Fx,{})})]})]}):r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.empty,children:[r.jsx(dp,{fontSize:32,style:{opacity:.4}}),r.jsx(q,{size:300,children:"Select a button to view its properties"})]}),r.jsx(Hx,{}),r.jsx(Ux,{})]})]})}const Fc=me({root:{display:"flex",flexDirection:"column",borderTop:`1px solid ${p.colorNeutralStroke2}`,backgroundColor:p.colorNeutralBackground2,flexShrink:0},tabRow:{display:"flex",alignItems:"center",borderBottom:`1px solid ${p.colorNeutralStroke2}`,gap:0,paddingRight:p.spacingHorizontalS,flexShrink:0},content:{flex:1,overflowY:"auto",padding:`${p.spacingHorizontalXS} ${p.spacingHorizontalM}`},toolbar:{display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,paddingBottom:p.spacingHorizontalXS,borderBottom:`1px solid ${p.colorNeutralStroke3}`,marginBottom:p.spacingHorizontalXS},table:{width:"100%",borderCollapse:"collapse",fontSize:p.fontSizeBase200},th:{textAlign:"left",padding:`4px ${p.spacingHorizontalS}`,fontWeight:p.fontWeightSemibold,color:p.colorNeutralForeground3,fontSize:p.fontSizeBase100,borderBottom:`1px solid ${p.colorNeutralStroke2}`,whiteSpace:"nowrap"},td:{padding:`4px ${p.spacingHorizontalS}`,borderBottom:`1px solid ${p.colorNeutralStroke3}`,verticalAlign:"middle"},mono:{fontFamily:p.fontFamilyMonospace,fontSize:p.fontSizeBase200,cursor:"pointer",color:p.colorBrandForeground1,":hover":{textDecoration:"underline"}},chip:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:p.borderRadiusMedium,fontSize:p.fontSizeBase100,border:`1px solid ${p.colorNeutralStroke2}`,backgroundColor:p.colorNeutralBackground3,marginRight:"3px",fontFamily:p.fontFamilyMonospace},historyRow:{display:"flex",alignItems:"flex-start",gap:p.spacingHorizontalS,padding:`${p.spacingHorizontalXS} 0`,borderBottom:`1px solid ${p.colorNeutralStroke3}`},historyAvatar:{width:"24px",height:"24px",borderRadius:"50%",backgroundColor:p.colorBrandBackground2,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:"2px"},historyContent:{flex:1,minWidth:0},consoleRow:{padding:"2px 0",fontFamily:p.fontFamilyMonospace,fontSize:p.fontSizeBase200,display:"flex",gap:p.spacingHorizontalS},consoleTs:{color:p.colorNeutralForeground4,flexShrink:0,fontSize:p.fontSizeBase100}});function Qx(){const e=Fc(),t=ee(g=>g.activeBottomTab),n=ee(g=>g.setActiveBottomTab),o=ee(g=>g.bottomPanelHeight),i=ee(g=>g.bottomCollapsed),s=ee(g=>g.setBottomCollapsed),a=E(g=>g.commands),l=E(g=>g.displayRules),c=E(g=>g.enableRules),d=E(g=>g.past),u=E(g=>g.ribbons),m=E(g=>g.restore),f=oe(g=>g.currentUserName),y=ne(g=>g.entries),x=ne(g=>g.clear),h=ne(g=>g.logWarn),S=ee(g=>g.openCommandEditor),v=ee(g=>g.openRuleEditor),b=ee(g=>g.openDiffViewer),w=E(g=>g.upsertCommand),C=E(g=>g.upsertEnableRule),I=E(g=>g.upsertDisplayRule),[$,j]=z.useState(""),[R,T]=z.useState(""),[A,W]=z.useState(""),[D,N]=z.useState(""),M=z.useMemo(()=>{const g=$.toLowerCase().trim();return g?a.filter(O=>O.id.toLowerCase().includes(g)||O.enableRules.some(V=>V.toLowerCase().includes(g))||O.displayRules.some(V=>V.toLowerCase().includes(g))):a},[a,$]),k=z.useMemo(()=>{const g=R.toLowerCase().trim();return g?l.filter(O=>O.id.toLowerCase().includes(g)||O.steps.some(V=>V.kind.toLowerCase().includes(g))):l},[l,R]),B=z.useMemo(()=>{const g=A.toLowerCase().trim();return g?c.filter(O=>O.id.toLowerCase().includes(g)||O.steps.some(V=>V.kind.toLowerCase().includes(g))):c},[c,A]),G=z.useMemo(()=>{const g=D.toLowerCase().trim();return g?d.filter(O=>O.op.toLowerCase().includes(g)||O.target.toLowerCase().includes(g)||O.detail.toLowerCase().includes(g)||O.userName.toLowerCase().includes(g)):d},[d,D]),X=()=>{const g=new Set(a.map(V=>V.id)),O=Is("New","Command",g);w({id:O,enableRules:[],displayRules:[],actions:[]}),S(O)},Q=()=>{const g=new Set(c.map(V=>V.id)),O=En("New","Enable",g);C({id:O,steps:[]}),v(O,"enable")},ie=()=>{const g=new Set(l.map(V=>V.id)),O=En("New","Display",g);I({id:O,steps:[]}),v(O,"display")},F=z.useMemo(()=>{const g={};for(const O of Object.values(u))for(const V of O.tabs)for(const de of V.groups)for(const Se of Ne(de))Se.commandId&&(g[Se.commandId]=(g[Se.commandId]??0)+1);return g},[u]),_=z.useMemo(()=>{const g={};for(const O of a)for(const V of[...O.enableRules,...O.displayRules])g[V]=(g[V]??0)+1;return g},[a]),L=i?32:o;function U(g){return g.userName&&g.userName!=="You"?g.userName:f||"You"}return r.jsxs("div",{className:e.root,style:{height:L},children:[r.jsxs("div",{className:e.tabRow,children:[r.jsxs(us,{selectedValue:t,onTabSelect:(g,O)=>n(O.value),size:"small",style:{flex:1},children:[r.jsxs(ot,{value:"commands",children:["Commands (",a.length,")"]}),r.jsxs(ot,{value:"displayRules",children:["Display rules (",l.length,")"]}),r.jsxs(ot,{value:"enableRules",children:["Enable rules (",c.length,")"]}),r.jsxs(ot,{value:"history",children:["History (",d.length,")"]}),r.jsx(ot,{value:"console",children:"Console"})]}),r.jsx(Z,{appearance:"subtle",size:"small",icon:i?r.jsx(Ia,{}):r.jsx(It,{}),onClick:()=>s(!i),"aria-label":i?"Expand panel":"Collapse panel"})]}),!i&&r.jsxs("div",{className:e.content,children:[t==="commands"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.toolbar,children:[r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:X,children:"New command"}),r.jsx(Ue,{size:"small",contentBefore:r.jsx(wt,{}),placeholder:`Filter ${a.length} command${a.length!==1?"s":""}…`,value:$,onChange:(g,O)=>j(O.value),style:{minWidth:0,flex:1,maxWidth:360}}),$&&r.jsxs(q,{size:100,style:{color:p.colorNeutralForeground3},children:[M.length," match",M.length!==1?"es":""]})]}),r.jsxs("table",{className:e.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{className:e.th,children:"Command"}),r.jsx("th",{className:e.th,children:"Actions"}),r.jsx("th",{className:e.th,children:"Enable rules"}),r.jsx("th",{className:e.th,children:"Display rules"}),r.jsx("th",{className:e.th,children:"Refs"}),r.jsx("th",{className:e.th})]})}),r.jsx("tbody",{children:M.map(g=>r.jsxs("tr",{children:[r.jsx("td",{className:e.td,children:r.jsx("span",{className:e.mono,onClick:()=>S(g.id),role:"button",tabIndex:0,onKeyDown:O=>O.key==="Enter"&&S(g.id),children:g.id})}),r.jsxs("td",{className:e.td,children:[g.actions.map((O,V)=>r.jsx("span",{className:e.chip,children:O.kind==="javascript"?"JS":O.kind==="url"?"URL":O.kind==="powerFx"?"Fx":O.kind==="customApi"?"API":O.kind==="outlookCommand"?"Outlook":"XML"},V)),g.actions.length===0&&r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"—"})]}),r.jsx("td",{className:e.td,children:g.enableRules.map(O=>r.jsx(Ee,{content:O,relationship:"label",children:r.jsx("span",{className:e.chip,style:{cursor:"pointer",color:p.colorBrandForeground1},onClick:()=>v(O,"enable"),children:O.split(".").pop()})},O))}),r.jsx("td",{className:e.td,children:g.displayRules.map(O=>r.jsx(Ee,{content:O,relationship:"label",children:r.jsx("span",{className:e.chip,style:{cursor:"pointer",color:p.colorBrandForeground1},onClick:()=>v(O,"display"),children:O.split(".").pop()})},O))}),r.jsx("td",{className:e.td,children:r.jsx(ue,{size:"small",appearance:"tint",color:F[g.id]?"brand":"informative",children:F[g.id]??0})}),r.jsx("td",{className:e.td,children:r.jsx(Z,{appearance:"subtle",size:"small",onClick:()=>S(g.id),children:"Edit"})})]},g.id))})]})]}),t==="displayRules"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.toolbar,children:[r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:ie,children:"New display rule"}),r.jsx(Ue,{size:"small",contentBefore:r.jsx(wt,{}),placeholder:`Filter ${l.length} display rule${l.length!==1?"s":""}…`,value:R,onChange:(g,O)=>T(O.value),style:{minWidth:0,flex:1,maxWidth:360}}),R&&r.jsxs(q,{size:100,style:{color:p.colorNeutralForeground3},children:[k.length," match",k.length!==1?"es":""]})]}),r.jsx(Kr,{rules:k,kind:"display",ruleRefs:_,onEdit:g=>v(g,"display"),styles:e})]}),t==="enableRules"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.toolbar,children:[r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:Q,children:"New enable rule"}),r.jsx(Ue,{size:"small",contentBefore:r.jsx(wt,{}),placeholder:`Filter ${c.length} enable rule${c.length!==1?"s":""}…`,value:A,onChange:(g,O)=>W(O.value),style:{minWidth:0,flex:1,maxWidth:360}}),A&&r.jsxs(q,{size:100,style:{color:p.colorNeutralForeground3},children:[B.length," match",B.length!==1?"es":""]})]}),r.jsx(Kr,{rules:B,kind:"enable",ruleRefs:_,onEdit:g=>v(g,"enable"),styles:e})]}),t==="history"&&r.jsxs(r.Fragment,{children:[d.length>0&&r.jsxs("div",{className:e.toolbar,children:[r.jsx(Ue,{size:"small",contentBefore:r.jsx(wt,{}),placeholder:`Filter ${d.length} entr${d.length!==1?"ies":"y"}…`,value:D,onChange:(g,O)=>N(O.value),style:{minWidth:0,flex:1,maxWidth:360}}),D&&r.jsxs(q,{size:100,style:{color:p.colorNeutralForeground3},children:[G.length," match",G.length!==1?"es":""]})]}),d.length===0?r.jsx(q,{size:200,style:{color:p.colorNeutralForeground3},children:"No history yet — make a change to see it here."}):G.slice().reverse().map((g,O)=>{const V=d.indexOf(g);return r.jsxs("div",{className:e.historyRow,children:[r.jsx("div",{className:e.historyAvatar,"aria-hidden":!0,children:r.jsx(Ca,{fontSize:12,style:{color:p.colorBrandForeground1}})}),r.jsxs("div",{className:e.historyContent,children:[r.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:6},children:[r.jsx(q,{size:200,weight:"semibold",children:g.op}),r.jsxs(q,{size:200,children:["— ",r.jsx("strong",{children:g.target})]}),g.detail&&r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:g.detail})]}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginTop:2},children:[r.jsxs(q,{size:100,style:{color:p.colorNeutralForeground3},children:[U(g)," ·"," ",new Date(g.ts).toLocaleTimeString()]}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(ca,{}),onClick:()=>b("history"),children:"View diff"}),r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(ua,{}),title:"Undo this change and every later one (redo brings them back)",onClick:()=>m(V),children:"Undo from here"})]})]})]},O)})]}),t==="console"&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:e.toolbar,children:[r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(kn,{}),disabled:y.length===0,onClick:()=>{const g=y.slice().reverse().map(O=>{const V=new Date(O.ts).toLocaleTimeString();return`${O.scope} ${V}
133
+ [${O.level.toUpperCase()}]
134
+ ${O.message}`}).join(`
135
+
136
+ `);Zl(g).then(O=>{O.ok||h("ui",`Couldn't copy the log: ${O.error}.`)})},title:"Copy all log entries to clipboard",children:"Copy log"}),r.jsx(Z,{appearance:"subtle",size:"small",onClick:x,children:"Clear log"})]}),r.jsx("div",{children:y.length===0?r.jsx(q,{size:200,style:{color:p.colorNeutralForeground3},children:"No runtime diagnostics yet."}):y.slice().reverse().map(g=>r.jsx(eS,{ts:`${g.scope} ${new Date(g.ts).toLocaleTimeString()}`,level:g.level,message:g.message},g.id))})]})]})]})}function Kr({rules:e,kind:t,ruleRefs:n,onEdit:o,styles:i}){return r.jsxs("table",{className:i.table,children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{className:i.th,children:"Rule"}),r.jsx("th",{className:i.th,children:"Steps"}),r.jsx("th",{className:i.th,children:"Used by"}),r.jsx("th",{className:i.th,children:"Type"}),r.jsx("th",{className:i.th})]})}),r.jsx("tbody",{children:e.map(s=>r.jsxs("tr",{children:[r.jsx("td",{className:i.td,children:r.jsx("span",{className:i.mono,onClick:()=>o(s.id),role:"button",tabIndex:0,onKeyDown:a=>a.key==="Enter"&&o(s.id),children:s.id})}),r.jsxs("td",{className:i.td,children:[s.steps.slice(0,3).map((a,l)=>r.jsx("span",{className:i.chip,children:a.kind.replace(/Rule$/,"")},l)),s.steps.length>3&&r.jsxs("span",{className:i.chip,style:{color:p.colorNeutralForeground3},children:["+",s.steps.length-3]}),s.steps.length===0&&r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"—"})]}),r.jsx("td",{className:i.td,children:r.jsxs(ue,{size:"small",appearance:"tint",color:n[s.id]?"brand":"informative",children:[n[s.id]??0," cmd",n[s.id]!==1?"s":""]})}),r.jsx("td",{className:i.td,children:r.jsx(ue,{size:"small",appearance:"outline",color:t==="enable"?"success":"informative",children:t})}),r.jsx("td",{className:i.td,children:r.jsx(Z,{appearance:"subtle",size:"small",onClick:()=>o(s.id),children:"Edit"})})]},s.id))})]})}function eS({ts:e,level:t,message:n}){const o=Fc(),i=t==="error"?p.colorStatusDangerForeground1:t==="warn"?p.colorStatusWarningForeground1:p.colorNeutralForeground3;return r.jsxs("div",{className:o.consoleRow,children:[r.jsx("span",{className:o.consoleTs,children:e}),r.jsxs("span",{style:{color:i},children:["[",t.toUpperCase(),"]"]}),r.jsx("span",{style:{color:p.colorNeutralForeground1},children:n})]})}const _c=me({root:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",backgroundColor:p.colorNeutralBackground2},header:{padding:`${p.spacingHorizontalS} ${p.spacingHorizontalM}`,borderBottom:`1px solid ${p.colorNeutralStroke2}`,flexShrink:0},searchBox:{padding:`${p.spacingHorizontalXS} ${p.spacingHorizontalS}`,flexShrink:0},scrollArea:{flex:1,overflow:"hidden",padding:`0 ${p.spacingHorizontalXS} ${p.spacingHorizontalXS}`},gridWrap:{height:"100%"},cell:{padding:0,minWidth:0,alignSelf:"stretch"},sectionHeader:{flex:1,alignSelf:"stretch",padding:`${p.spacingHorizontalXS} ${p.spacingHorizontalS}`,display:"flex",alignItems:"center",gap:p.spacingHorizontalXS,cursor:"pointer",userSelect:"none",":hover":{backgroundColor:p.colorNeutralBackground3}},entityRow:{flex:1,alignSelf:"stretch",minWidth:0,display:"flex",alignItems:"center",gap:p.spacingHorizontalS,padding:`${p.spacingHorizontalS} ${p.spacingHorizontalM}`,cursor:"pointer",borderRadius:p.borderRadiusMedium,borderLeft:"3px solid transparent",":hover":{backgroundColor:p.colorNeutralBackground3}},entityRowActive:{borderLeftColor:p.colorBrandStroke1,backgroundColor:p.colorBrandBackground2,":hover":{backgroundColor:p.colorBrandBackground2Hover}},entityName:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}});function tS(){const e=_c(),t=oe(b=>b.entities),n=oe(b=>b.activeEntity),o=we(b=>b.requestEntitySwitch),i=oe(b=>b.activeSolution),s=oe(b=>b.solutionEntityIds),[a,l]=z.useState(""),[c,d]=z.useState(!0),[u,m]=z.useState(!0),f=t,y=z.useMemo(()=>{const b=a.toLowerCase();return f.filter(w=>w.displayName.toLowerCase().includes(b)||w.logicalName.toLowerCase().includes(b))},[f,a]),x=y.filter(b=>b.isCustomEntity),h=y.filter(b=>!b.isCustomEntity),S=z.useMemo(()=>[...x.length>0?[{kind:"header",id:"custom-header",label:"CUSTOM",count:x.length}]:[],...c?x.map(b=>({kind:"entity",id:`custom-${b.logicalName}`,entity:b})):[],...h.length>0?[{kind:"header",id:"standard-header",label:"STANDARD",count:h.length}]:[],...u?h.map(b=>({kind:"entity",id:`std-${b.logicalName}`,entity:b})):[]],[x,c,h,u]),v=[ht({columnId:"table",renderHeaderCell:()=>r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:"Entity"}),renderCell:b=>{if(b.kind==="header"){const w=b.label==="CUSTOM"?c:u;return r.jsx("div",{className:e.sectionHeader,onClick:()=>b.label==="CUSTOM"?d(C=>!C):m(C=>!C),role:"button",tabIndex:0,"aria-expanded":w,onKeyDown:C=>{C.key!=="Enter"&&C.key!==" "||(C.preventDefault(),b.label==="CUSTOM"?d(I=>!I):m(I=>!I))},children:r.jsxs(q,{size:100,weight:"semibold",style:{color:p.colorNeutralForeground3},children:[w?"▾":"▸"," ",b.label," (",b.count,")"]})})}return r.jsx(nS,{entity:b.entity,isActive:n?.logicalName===b.entity.logicalName,onClick:()=>o(b.entity)})}})];return r.jsxs("div",{className:e.root,children:[r.jsx("div",{className:e.header,children:r.jsx(Pt,{children:"Tables"})}),r.jsx("div",{className:e.searchBox,children:r.jsx(Ue,{contentBefore:r.jsx(wt,{}),placeholder:"Search tables…",size:"small",value:a,onChange:(b,w)=>l(w.value),style:{width:"100%"}})}),r.jsxs("div",{className:e.scrollArea,children:[!i&&r.jsx("div",{style:{padding:24,textAlign:"center"},children:r.jsx(q,{size:200,style:{color:p.colorNeutralForeground3},children:"Select a solution from the top bar to see its tables."})}),i&&s===null&&r.jsx("div",{style:{padding:24,textAlign:"center"},children:r.jsx(ds,{size:"small",label:"Loading solution tables…"})}),i&&s!==null&&f.length===0&&r.jsx("div",{style:{padding:24,textAlign:"center"},children:r.jsxs(q,{size:200,style:{color:p.colorNeutralForeground3},children:["No tables to show for ",r.jsx("em",{children:i.friendlyName}),".",r.jsx("br",{}),r.jsx("br",{}),"Add a table to the solution in the maker portal (Solutions ›"," ",r.jsx("em",{children:i.friendlyName})," › Add existing › Table) and reload."]})}),i&&s!==null&&f.length>0&&r.jsxs(Fs,{className:e.gridWrap,items:S,columns:v,getRowId:b=>b.id,focusMode:"none",children:[r.jsx(_s,{children:r.jsx(Ln,{children:({renderHeaderCell:b})=>r.jsx(Ea,{children:b()})})}),r.jsx(Ps,{itemSize:52,height:420,listProps:{width:"100%"},children:({item:b,rowId:w},C)=>r.jsx(Ln,{style:C,children:({renderCell:I})=>r.jsx(Oa,{className:e.cell,children:I(b)})},w)})]})]})]})}function nS({entity:e,isActive:t,onClick:n}){const o=_c();return r.jsxs("div",{className:`${o.entityRow} ${t?o.entityRowActive:""}`,onClick:n,role:"button",tabIndex:0,"aria-pressed":t,onKeyDown:i=>{i.key!=="Enter"&&i.key!==" "||(i.preventDefault(),n())},children:[r.jsxs("div",{className:o.entityName,children:[r.jsx(q,{size:200,weight:t?"semibold":"regular",children:e.displayName}),r.jsx("br",{}),r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3},children:e.logicalName})]}),e.isManaged&&r.jsx(Lt,{fontSize:12,style:{color:p.colorNeutralForeground3},"aria-label":"Managed"})]})}const oS="application/x-rw-se",Jr={HomepageGrid:"Home",SubGrid:"Sub",Form:"Form",Application:"App"},iS=me({root:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",backgroundColor:p.colorNeutralBackground2},header:{padding:`${p.spacingHorizontalS} ${p.spacingHorizontalM}`,borderBottom:`1px solid ${p.colorNeutralStroke2}`,flexShrink:0},tabs:{flexShrink:0,borderBottom:`1px solid ${p.colorNeutralStroke2}`},scrollArea:{flex:1,overflowY:"auto",padding:p.spacingHorizontalXS},item:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS,padding:`${p.spacingHorizontalXS} ${p.spacingHorizontalS}`,cursor:"pointer",borderRadius:p.borderRadiusMedium,":hover":{backgroundColor:p.colorNeutralBackground3}},draggableItem:{display:"flex",alignItems:"center",gap:p.spacingHorizontalS,padding:`${p.spacingHorizontalXS} ${p.spacingHorizontalS}`,cursor:"grab",borderRadius:p.borderRadiusMedium,userSelect:"none",":hover":{backgroundColor:p.colorNeutralBackground3},":active":{cursor:"grabbing"}},itemName:{flex:1,fontFamily:p.fontFamilyMonospace,fontSize:p.fontSizeBase200,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},gripHandle:{color:p.colorNeutralForeground4,fontSize:p.fontSizeBase200,flexShrink:0,lineHeight:1}});function sS(){const e=iS(),[t,n]=z.useState("commands"),o=E(S=>S.commands),i=E(S=>S.displayRules),s=E(S=>S.enableRules),a=E(S=>S.templates),l=E(S=>S.ribbons),c=E(S=>S.baseline),d=E(S=>S.upsertCommand),u=E(S=>S.upsertEnableRule),m=ee(S=>S.openCommandEditor),f=ee(S=>S.openRuleEditor),y=z.useMemo(()=>{const S=[];for(const v of Object.keys(l)){const b=l[v],w=c[v];for(const C of b.tabs)for(const I of C.groups)for(const $ of Ne(I)){if(!$.custom)continue;const j=w.tabs.flatMap(R=>R.groups).flatMap(R=>Ne(R)).some(R=>R.id===$.id);S.push({button:$,location:v,tabId:C.id,groupId:I.id,isNew:!j})}}return S},[l,c]),x=()=>{const S=new Set(o.map(b=>b.id)),v=Is("New","Command",S);d({id:v,enableRules:[],displayRules:[],actions:[]}),m(v)},h=()=>{const S=new Set([...s.map(b=>b.id),...i.map(b=>b.id)]),v=En("New","Enable",S);u({id:v,steps:[]}),f(v,"enable")};return r.jsxs("div",{className:e.root,children:[r.jsx("div",{className:e.header,children:r.jsx(Pt,{children:"Solution Elements"})}),r.jsxs(us,{className:e.tabs,selectedValue:t,onTabSelect:(S,v)=>n(v.value),size:"small",children:[r.jsxs(ot,{value:"buttons",children:["Buttons (",y.length,")"]}),r.jsxs(ot,{value:"commands",children:["Commands (",o.length,")"]}),r.jsxs(ot,{value:"rules",children:["Rules (",s.length+i.length,")"]}),r.jsxs(ot,{value:"templates",children:["Templates (",a.length,")"]})]}),r.jsxs("div",{className:e.scrollArea,children:[t==="buttons"&&r.jsxs(r.Fragment,{children:[r.jsx(q,{size:100,style:{color:p.colorNeutralForeground3,padding:`4px ${p.spacingHorizontalS}`,display:"block"},children:"Drag onto the ribbon canvas to add a button"}),y.map(({button:S,location:v,isNew:b})=>r.jsx(Ee,{content:`${S.id} · ${Jr[v]} ribbon`,relationship:"label",children:r.jsxs("div",{className:e.draggableItem,draggable:!0,onDragStart:w=>{w.dataTransfer.setData(oS,JSON.stringify({button:S})),w.dataTransfer.effectAllowed="copy"},title:"Drag onto a ribbon group to add this button",children:[r.jsx("span",{className:e.gripHandle,children:"⋮⋮"}),r.jsx(An,{fontSize:14,style:{color:p.colorNeutralForeground3,flexShrink:0}}),r.jsx(q,{className:e.itemName,children:S.label||S.id}),r.jsx(ue,{size:"small",appearance:"outline",children:Jr[v]}),b&&r.jsx(ue,{size:"small",color:"brand",appearance:"tint",children:"NEW"})]})},`${v}::${S.id}`)),y.length===0&&r.jsxs(q,{size:200,style:{color:p.colorNeutralForeground3,padding:8,display:"block"},children:["No custom buttons yet. Add one from the ribbon canvas — in"," ",r.jsx("strong",{children:"Modern command bar"})," use the ",r.jsx("strong",{children:"+ Add"})," button at the end of the bar; in ",r.jsx("strong",{children:"Classic ribbon"})," use the ",r.jsx("strong",{children:"+"})," ","inside any group."]})]}),t==="commands"&&r.jsxs(r.Fragment,{children:[r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:x,style:{width:"100%",justifyContent:"flex-start",marginBottom:4},children:"New command"}),o.map(S=>r.jsxs("div",{className:e.item,onClick:()=>m(S.id),role:"button",tabIndex:0,onKeyDown:v=>v.key==="Enter"&&m(S.id),children:[r.jsx(on,{fontSize:14,style:{color:p.colorNeutralForeground3}}),r.jsx(q,{className:e.itemName,children:S.id}),r.jsxs(q,{size:100,style:{color:p.colorNeutralForeground3},children:[S.actions.length," action",S.actions.length!==1?"s":""]})]},S.id)),o.length===0&&r.jsx(q,{size:200,style:{color:p.colorNeutralForeground3,padding:8,display:"block"},children:"No commands yet"})]}),t==="rules"&&r.jsxs(r.Fragment,{children:[r.jsx(Z,{appearance:"subtle",size:"small",icon:r.jsx(Ae,{}),onClick:h,style:{width:"100%",justifyContent:"flex-start",marginBottom:4},children:"New rule"}),s.map(S=>r.jsxs("div",{className:e.item,onClick:()=>f(S.id,"enable"),role:"button",tabIndex:0,onKeyDown:v=>v.key==="Enter"&&f(S.id,"enable"),children:[r.jsx(q,{className:e.itemName,children:S.id}),r.jsx(ue,{size:"small",color:"success",appearance:"tint",children:"Enable"})]},S.id)),i.map(S=>r.jsxs("div",{className:e.item,onClick:()=>f(S.id,"display"),role:"button",tabIndex:0,onKeyDown:v=>v.key==="Enter"&&f(S.id,"display"),children:[r.jsx(q,{className:e.itemName,children:S.id}),r.jsx(ue,{size:"small",color:"informative",appearance:"tint",children:"Display"})]},S.id)),s.length===0&&i.length===0&&r.jsx(q,{size:200,style:{color:p.colorNeutralForeground3,padding:8,display:"block"},children:"No rules yet"})]}),t==="templates"&&r.jsxs(r.Fragment,{children:[a.map(S=>r.jsxs("div",{className:e.item,children:[r.jsx(ja,{fontSize:14,style:{color:p.colorNeutralForeground3}}),r.jsx(q,{className:e.itemName,children:S.id})]},S.id)),a.length===0&&r.jsx(q,{size:200,style:{color:p.colorNeutralForeground3,padding:8,display:"block"},children:"No templates defined"})]})]})]})}function Ws(){return window.dataverseAPI}async function rS(){const e=Ws();ne.getState().logInfo("dataverse","Loading solutions...");const i=((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(a=>{const l=a.publisherid??{};return{id:String(a.solutionid??""),uniqueName:String(a.uniquename??""),friendlyName:String(a.friendlyname??""),version:String(a.version??""),isManaged:!!a.ismanaged,publisherId:l.publisherid??"",publisherUniqueName:l.uniquename??"",publisherName:l.friendlyname??"",publisherPrefix:l.customizationprefix??"",publisherOptionValuePrefix:typeof l.customizationoptionvalueprefix=="number"?l.customizationoptionvalueprefix:void 0,versionNumber:a.versionnumber}});ne.getState().logInfo("dataverse",`Loaded ${i.length} solution(s).`);const s=i.filter(a=>!a.isManaged).slice(0,5);for(const a of s)ne.getState().logInfo("dataverse",` • "${a.friendlyName||a.uniqueName}" → prefix="${a.publisherPrefix||"(empty)"}" (publisher: ${a.publisherName||a.publisherUniqueName||"(empty)"})`);return i}async function aS(e){if(!e)return[];const t=Ws();ne.getState().logInfo("dataverse",`Loading solution entity components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 1`,s=((await t.queryData(n)).value??[]).map(a=>a.objectid).filter(Boolean);return ne.getState().logInfo("dataverse",`Solution contains ${s.length} table component(s).`),s}async function lS(e){if(!e)return[];const t=Ws();ne.getState().logInfo("dataverse",`Loading solution ribbon components for ${e}...`);const n=`solutioncomponents?$select=objectid&$filter=_solutionid_value eq ${e} and componenttype eq 50`,s=((await t.queryData(n)).value??[]).map(a=>a.objectid).filter(Boolean);return ne.getState().logInfo("dataverse",`Solution contains ${s.length} ribbon-customization component(s).`),s}function cS(){return window.dataverseAPI}async function dS(e){if(e.length===0)return[];const t=cS(),n=ne.getState();n.logInfo("dataverse",`Loading metadata for ${e.length} solution entit${e.length===1?"y":"ies"}...`);const o="MetadataId,LogicalName,SchemaName,DisplayName,IsCustomEntity,IsIntersect",i=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}),s=async d=>{try{return i(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}},a=[];for(let d=0;d<e.length;d+=40)a.push(e.slice(d,d+40));const c=(await Promise.all(a.map(async d=>{try{const m=((await t.queryData(`EntityDefinitions?$select=${o}&$filter=${d.map(y=>`MetadataId eq ${y}`).join(" or ")}`)).value??[]).map(i),f=new Set(m.map(y=>y.metadataId.toLowerCase()));for(const y of d)f.has(y.toLowerCase())||n.logWarn("dataverse",`Could not resolve entity for component ${y}: not found.`);return m}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 m=[];for(const f of d)m.push(await s(f));return m}}))).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 qc(e){const t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);const o=cg(n),i=Object.entries(o).find(([s])=>s.toLowerCase().endsWith("ribbonxml.xml"));if(!i){const s=Object.keys(o);throw new Error(`Dataverse returned a ribbon package without RibbonXml.xml (it has ${s.length>0?s.join(", "):"no files"}).`)}return Uo(i[1])}const Wc=30,uS=Wc*6e4,Hc=(e,t)=>`cbs:lastPublish:${e.replace(/\/+$/,"")}:${t}`;function Gc(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 i=Object.fromEntries(Object.entries(o.publishedAt).filter(s=>typeof s[1]=="number"&&t-s[1]<uS));return{at:o.at,publishedAt:i}}catch{return null}}function Tv(e,t,n,o=Date.now()){const i=Hc(e,t),s={...Gc(i,o)?.publishedAt??{}};for(const a of n){const l=/^customActions:ca:(.+)$/.exec(a)?.[1];l&&(s[l]=o)}try{sessionStorage.setItem(i,JSON.stringify({at:o,publishedAt:s}))}catch{}}function mS(e,t,n=Date.now()){return Gc(Hc(e,t),n)}const Yr=new Set(["Button","FlyoutAnchor","SplitButton","TextBox","ComboBox","CheckBox"]),xi=new Set(["Tab","Group"]),Zr=/^(.+)\._children$/;function Qr(e){return e?Array.from(e.children):[]}function Pn(e,t){return t?e.split("{!EntityLogicalName}").join(t):e}function pS(e,t){const n=new Map,o=(i,s)=>n.set(Pn(i,t),s);for(const i of e)for(const s of i.tabs){o(`${s.id}.Groups`,s.id);for(const a of s.groups){o(`${a.id}.Controls`,s.id);for(const l of Ne(a))for(const c of l.menu?.sections??[])o(c.controlsId,s.id)}}return n}function fS(e,t){const n=new Set,o=i=>n.add(Pn(i,t));for(const i of e)for(const s of i.tabs){o(s.id);for(const a of s.groups){o(a.id);for(const l of Ne(a))o(l.id)}}return n}function ea(e){return[e,...Array.from(e.getElementsByTagName("*"))].flatMap(t=>t.getAttribute("Id")??[])}function hS(e,t,n,o={}){const{locLabels:i=[],languageCode:s=1033}=o,a=[...t],l=j=>Pn(j,n),c=fS(a,n),d=pS(a,n),u=[...Eo(e).map(j=>j.location),...o.otherHides??[]].map(l),m=new Set(u),f=new Set,y=[...e.customActions.values()].map(j=>new DOMParser().parseFromString(j,"application/xml").documentElement);for(const j of y)if(j.tagName==="CustomAction")for(const R of Array.from(j.getElementsByTagName("*")))m.has(l(R.getAttribute("Id")??""))&&ea(R).forEach(T=>f.add(l(T)));const x=j=>f.has(j)||u.some(R=>j===R||j.startsWith(`${R}.`)),h=new Set(["Mscrm.Tabs",`Mscrm.SubGrid.${n}.ContextualTabs`]),S=(j,R)=>{const T=d.get(R);return T&&qo(T)?{reason:"hidden-tab",why:`It is on the tab ${T}, which Unified Interface doesn't show; the ribbon doesn't return what is added there.`}:T||h.has(R)?{reason:"not-returned",why:j==="Tab"?`The ribbon doesn't return this tab at ${R}, so Command Bar Studio can't place it (it may still show in Unified Interface).`:`${R} 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(R)?`${R} isn't in this table's ribbon as loaded: it is not shown — possibly hidden by another solution — or it was removed.`:`${R} 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.`}},v=j=>{const R=j.getAttribute("LabelText")??j.getAttribute("Title")??j.getAttribute("Alt")??"";return Be(R,i,s)||(j.getAttribute("Id")??"")},b=[],w=(j,R,T)=>{const A=j.getAttribute("Id")??"",W=Zr.exec(R)?.[1]??R;if(!A||c.has(l(A))||x(l(A))||x(l(W)))return;const D=xi.has(j.tagName);b.push({orphan:{id:A,element:j.tagName,label:v(j),location:R,customActionId:T,...S(j.tagName,l(W)),deleteControlIds:D?[]:[A],deleteContainerIds:D?[A]:[]},parent:W,inside:new Set(ea(j))})};for(const j of y){if(j.tagName!=="CustomAction")continue;const R=j.getAttribute("Location")??"";if(!Zr.test(R)||/\.Scaling\._children$/.test(R))continue;const T=Qr(Qr(j).find(D=>D.tagName==="CommandUIDefinition"))[0],A=T?.getAttribute("Id");if(!T||!A||!(xi.has(T.tagName)||Yr.has(T.tagName)))continue;const W=j.getAttribute("Id")??"";if(!c.has(l(A))){w(T,R,W);continue}for(const D of Array.from(T.getElementsByTagName("*"))){const N=D.parentElement;N?.tagName!=="Controls"&&N?.tagName!=="Groups"||!xi.has(D.tagName)&&!Yr.has(D.tagName)||w(D,`${N.getAttribute("Id")??""}._children`,W)}}const C=j=>b.find(R=>R!==j&&R.inside.has(j.parent)&&!j.inside.has(R.parent)),I=j=>{const R=new Set([j]);let T=j;for(let A=C(T);A&&!R.has(A);A=C(T))R.add(A),T=A;return T},$=b.filter(j=>!C(j));for(const j of b){const R=I(j);if(R===j||!$.includes(R))continue;const T=(A,W)=>W.forEach(D=>A.includes(D)||A.push(D));T(R.orphan.deleteControlIds,j.orphan.deleteControlIds),T(R.orphan.deleteContainerIds,j.orphan.deleteContainerIds)}return $.map(j=>j.orphan)}function gS(e,t,n=Date.now()){if(!t)return e;const o=Wc*6e4,i=s=>Math.max(0,Math.floor((n-s)/6e4));return e.map(s=>{const a=t.publishedAt[s.customActionId];if(a!==void 0&&n-a<o){const c=i(a);return{...s,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. ${s.why}`}}if(n-t.at>=o)return s;const l=i(t.at);return{...s,recentPublish:{minutesAgo:l,published:!1},why:`The table was published from here ${l} min before this table was loaded, and the ribbon may not have caught up yet. ${s.why}`}})}const Uc=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 Xc(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 Vc(e){return Xc(e)[0]}function bS(e,t,n={}){const o={HomepageGrid:[],SubGrid:[],Form:[]};for(const s of e)s.id.startsWith("Mscrm.Form.")?o.Form.push(s):s.id.startsWith("Mscrm.SubGrid.")?o.SubGrid.push(s):s.id.startsWith("Mscrm.HomepageGrid.")?o.HomepageGrid.push(s):o[Vc(s)??"HomepageGrid"].push(s);const i=s=>{const a=Object.fromEntries(o[s].filter(l=>n[l.id]).map(l=>[l.id,n[l.id]]));return{location:s,entityLogicalName:t,tabs:o[s],...Object.keys(a).length>0?{scalingByTab:a}:{}}};return{HomepageGrid:i("HomepageGrid"),SubGrid:i("SubGrid"),Form:i("Form")}}const yS="Microsoft.Dynamics.CRM.RibbonLocationFilters'All'";function xS(e){return`RetrieveEntityRibbon(EntityName=@e,RibbonLocationFilter=@f)?@e='${encodeURIComponent(e.replace(/'/g,"''"))}'&@f=${yS}`}async function SS(e,t=[]){ne.getState().logInfo("dataverse",`RetrieveEntityRibbon(${e}, All)`);const n=await Uc.queryData(xS(e));if(typeof n?.CompressedEntityXml!="string"||!n.CompressedEntityXml)throw new Error(`Dataverse returned no ribbon for ${e} (RetrieveEntityRibbon had no CompressedEntityXml).`);const o=await qc(n.CompressedEntityXml),i=_o(o,"HomepageGrid",e,t),s=bS(i.ribbon.tabs,e,i.ribbon.scalingByTab);if(i.ribbon.templateLayouts)for(const a of Object.values(s))a.templateLayouts=i.ribbon.templateLayouts;return ne.getState().logInfo("dataverse",`RetrieveEntityRibbon succeeded for ${e} (Form=${s.Form.tabs.length}, HomepageGrid=${s.HomepageGrid.tabs.length}, SubGrid=${s.SubGrid.tabs.length})`),{ribbons:s,commands:i.commands,displayRules:i.displayRules,enableRules:i.enableRules,locLabels:i.locLabels}}const Kc=5*6e4;let as=null,ls=0,Jc=0;function vS(e={}){as=null,ls++,e.afterPublish&&(Jc=Date.now()+Kc)}async function wS(e=[]){const t=ne.getState(),n=oe.getState().connectionUrl,o=as;let i;if(o&&o.environment===n&&Date.now()-o.at<Kc)i=o.xml,t.logInfo("dataverse","RetrieveApplicationRibbon (reused from this session)");else{const s=ls;t.logInfo("dataverse","RetrieveApplicationRibbon()");const l=(await Uc.execute({operationName:"RetrieveApplicationRibbon",operationType:"function"}))?.CompressedApplicationRibbonXml;if(typeof l!="string"||!l)throw new Error("Dataverse returned no application ribbon (RetrieveApplicationRibbon had no CompressedApplicationRibbonXml).");i=await qc(l),s===ls&&Date.now()>=Jc&&(as={environment:n,at:Date.now(),xml:i}),t.logInfo("dataverse","RetrieveApplicationRibbon succeeded")}return _o(i,"Application","{!EntityLogicalName}",e)}function Si(e,t,n,o=[]){const i={added:[],replaced:[]};if(n.commandDefinitions.size+n.enableRules.size+n.displayRules.size===0)return i;const s=Mh(n),a=(y,x)=>JSON.stringify(y,ta)===JSON.stringify(x,ta),l=(y,x)=>{const h=new Map(x.map(S=>[S.id,S]));for(let S=0;S<y.length;S++){const v=h.get(y[S].id);v&&!a(v,y[S])&&(y[S]=v,i.replaced.push(v.id))}};l(t.commands,s.commands),l(t.enableRules,s.enableRules),l(t.displayRules,s.displayRules);const c=new Set(t.commands.map(y=>y.id)),d=new Set(o.filter(y=>!c.has(y)&&n.commandDefinitions.has(y)));for(const y of e)for(const x of y.tabs)for(const h of x.groups)for(const S of Ne(h))S.commandId&&!c.has(S.commandId)&&n.commandDefinitions.has(S.commandId)&&d.add(S.commandId);const u=s.commands.filter(y=>d.has(y.id));t.commands.push(...u),i.added.push(...u.map(y=>y.id));const m=new Set(t.enableRules.map(y=>y.id)),f=new Set(t.displayRules.map(y=>y.id));for(const y of t.commands){for(const x of y.enableRules){const h=s.enableRules.find(S=>S.id===x);h&&!m.has(x)&&(t.enableRules.push(h),m.add(x),i.added.push(x))}for(const x of y.displayRules){const h=s.displayRules.find(S=>S.id===x);h&&!f.has(x)&&(t.displayRules.push(h),f.add(x),i.added.push(x))}}return i}function ta(e,t){if(typeof t!="string"||!t.trimStart().startsWith("<"))return t;try{return en(t)}catch{return t}}function CS(e,t){const n=(o,i)=>new Map([...o].filter(([s])=>!i?.has(s)));return{...e,commandDefinitions:n(e.commandDefinitions,t?.commandDefinitions),enableRules:n(e.enableRules,t?.enableRules),displayRules:n(e.displayRules,t?.displayRules)}}function IS(e,t,n){if(n!==1033)for(const o of e)for(const i of o.tabs)for(const s of i.groups)for(const a of Ne(s)){for(const d of a.menu?.sections??[]){const u=d.attributes?.Title;u?.startsWith("$LocLabels:")&&(d.title=Be(u,t,n))}const l=a.source;if(!l)continue;const c=[[l.labelToken,"label"],[l.tooltipTitleToken,"tooltipTitle"],[l.tooltipBodyToken,"tooltipBody"]];for(const[d,u]of c)d?.startsWith("$LocLabels:")&&(a[u]=Be(d,t,n))}}function na(e,t,n,o){const i=new Set(Object.values(e).flatMap(f=>f?.tabs.map(y=>y.id)??[])),s=new Set(Eo(t).map(f=>f.location)),a=n?`Mscrm.SubGrid.${n}.ContextualTabs._children`:null,l=[];for(const f of tl(t.customActions).values()){const y=new DOMParser().parseFromString(f,"application/xml").documentElement;if(y.tagName!=="CustomAction")continue;const x=Pn(y.getAttribute("Location")??"",n??void 0);if(x!=="Mscrm.Tabs._children"&&x!==a)continue;const h=Array.from(y.getElementsByTagName("CommandUIDefinition")[0]?.children??[])[0],S=h?.tagName==="Tab"?h.getAttribute("Id"):null;!S||i.has(Pn(S,n??void 0))||l.push({xml:new XMLSerializer().serializeToString(h),subGrid:x===a})}if(l.length===0)return[];const c=`<RibbonDefinitions><RibbonDefinition><UI><Ribbon><Tabs>${l.map(f=>f.xml).join("")}</Tabs></Ribbon></UI><RuleDefinitions><TabDisplayRules>${[...t.tabDisplayRules.values()].join("")}</TabDisplayRules></RuleDefinitions></RibbonDefinition></RibbonDefinitions>`,d=_o(c,n?"HomepageGrid":"Application",n??"{!EntityLogicalName}",o);d.ribbon.tabs=d.ribbon.tabs.filter(f=>!s.has(f.id));for(const f of d.ribbon.tabs){f.groups=f.groups.filter(y=>!s.has(y.id));for(const y of f.groups){y.buttons=y.buttons.filter(x=>!s.has(x.id));for(const x of Ne(y))s.has(x.id)&&ll(y,x.id)}}const u=new Set(l.filter(f=>f.subGrid).map(f=>new DOMParser().parseFromString(f.xml,"application/xml").documentElement.getAttribute("Id"))),m=f=>n?u.has(f.id)?"SubGrid":Vc(f)??"HomepageGrid":"Application";for(const f of d.ribbon.tabs){const y=n&&!u.has(f.id)?Xc(f).slice(1):[];y.length>0&&ne.getState().logWarn("ribbon",`Tab ${f.id} shows on the ${m(f)} and on the ${y.join(" and ")} (its display rules); Command Bar Studio lists it under ${m(f)} only.`);const x=e[m(f)];if(!x)continue;x.tabs.push(f),x.tabs.sort((S,v)=>S.sequence-v.sequence);const h=d.ribbon.scalingByTab?.[f.id];h&&(x.scalingByTab={...x.scalingByTab??{},[f.id]:h})}return d.ribbon.tabs.map(f=>f.id)}function vi(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);ne.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 RS(e,t){const n=ne.getState();t?.("Reading your customizations…");const o=[],i=h=>S=>(o.push(`${h}: ${S instanceof Error?S.message:String(S)}`),null),[s,a,l]=await Promise.all([Wi(e).catch(i(`the ${e} table's customizations`)),Wi(null).catch(i("the application ribbon's customizations")),Ab().catch(h=>{n.logWarn("dataverse",`${h instanceof Error?h.message:String(h)} Labels are shown in English; publishing reads it again and stops if it still can't.`)})]),c=s?Hi(s):[],d=a?Hi(a):[];t?.("Reading the table's ribbon and the application ribbon…");const[u,m]=await Promise.all([SS(e,[...c,...d]),wS(d)]);if(s){const h=na(u.ribbons,s,e,[...c,...d]);h.length>0&&n.logInfo("ribbon",`Loaded tab(s) ${h.join(", ")} from the table's unmanaged layer.`);const S=go(s);for(const v of Object.values(u.ribbons))cr(v,S);vi("RetrieveEntityRibbon",Si(Object.values(u.ribbons),u,s,[Pe]))}a&&(na({Application:m.ribbon},a,null,d),cr(m.ribbon,go(a)),vi("RetrieveApplicationRibbon",Si([m.ribbon],m,a)),vi("RetrieveEntityRibbon",Si(Object.values(u.ribbons),u,CS(a,s))));const f=eo([...u.locLabels,...m.locLabels]),y=l??1033;t?.("Matching labels and ownership…"),IS([...Object.values(u.ribbons),m.ribbon],f,y);const x=s?hS(s,Object.values(u.ribbons),e,{locLabels:f,languageCode:y,otherHides:a?Eo(a).map(h=>h.location):[]}):[];return x.length>0&&n.logWarn("ribbon",`${x.length} element(s) of the table's unmanaged customizations aren't on the canvas — the ribbon doesn't return them (see "Orphaned customizations"): ${x.map(h=>`${h.id} at ${h.location}`).join(", ")}.`),{ribbons:{HomepageGrid:u.ribbons.HomepageGrid,SubGrid:u.ribbons.SubGrid,Form:u.ribbons.Form,Application:m.ribbon},commands:eo([...u.commands,...m.commands]),displayRules:eo([...u.displayRules,...m.displayRules]),enableRules:eo([...u.enableRules,...m.enableRules]),locLabels:f,layers:{entity:s?vo(s):null,application:a?vo(a):null},baseLanguageCode:l,orphans:x,...o.length>0?{layerReadError:o.join("; ")}:{}}}const jS="System",To="{!EntityLogicalName}",lo=new Map;function $S(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 i of Array.from(n.getElementsByTagName("*"))){const s=i.getAttribute("Id");s&&o.push(s)}return o}catch{return[]}}async function NS(e){const t=e.filter(n=>!lo.has(n));for(let n=0;n<t.length;n+=40){const o=t.slice(n,n+40),i=await Jt(`solutions?$select=solutionid,uniquename&$expand=publisherid($select=friendlyname)&$filter=${o.map(s=>`solutionid eq ${s}`).join(" or ")}`);for(const s of o)lo.set(s,null);for(const s of i){const a=s.publisherid;lo.set(String(s.solutionid),{uniqueName:String(s.uniquename??""),publisherName:a?.friendlyname})}}}async function TS(e){const t=ne.getState(),n=new Map;if(!e||e===To)return n;try{const o=e.replace(/'/g,"''"),i=await Jt(`ribbondiffs?$select=rdx,solutionid&$filter=(entity eq '${o}' or entity eq null) and ismanaged eq true and difftype le 1&$orderby=solutionid`),s=new Map;for(const a of i){const l=String(a.solutionid??"");if(l)for(const c of $S(String(a.rdx??""))){const d=c.split(To).join(e);for(const u of d===c?[c]:[c,d])s.has(u)||s.set(u,new Set),s.get(u).add(l)}}await NS([...new Set([...s.values()].flatMap(a=>[...a]))]);for(const[a,l]of s){const c=[...l].map(d=>lo.get(d)).find(d=>d&&d.uniqueName!==jS);c&&n.set(a,{origin:"managed",solutionName:c.uniqueName,publisherName:c.publisherName})}t.logInfo("provenance",`${i.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 kS(e){if(!e||e===To)return[];try{const t=e.replace(/'/g,"''"),n=await Jt(`ribbondiffs?$select=rdx&$filter=(entity eq '${t}' or entity eq null) and ismanaged eq true and difftype eq 3&$orderby=solutionid`),o=[],i=new DOMParser;for(const s of n){const a=i.parseFromString(String(s.rdx??""),"application/xml");if(!a.querySelector("parsererror"))for(const l of Array.from(a.getElementsByTagName("LocLabel"))){const c=l.getAttribute("Id");if(!c)continue;const d=Array.from(l.getElementsByTagName("Title")).map(m=>({languageCode:Number(m.getAttribute("languagecode")),description:m.getAttribute("description")??""})).filter(m=>Number.isFinite(m.languageCode)&&m.description);if(d.length===0)continue;o.push({id:c,titles:d});const u=c.split(To).join(e);u!==c&&o.push({id:u,titles:d})}}return ne.getState().logInfo("provenance",`${o.length} label text(s) from managed solutions for ${e}.`),o}catch(t){return ne.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 AS(){return window.dataverseAPI}async function DS(){const e=AS();ne.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 ne.getState().logWarn("dataverse","WhoAmI returned no user id."),{id:"",name:""};const i=(await e.retrieve("systemuser",n,["fullname"])).fullname?.trim(),s={id:n,name:i&&i.length>0?i:"Current User"};return ne.getState().logInfo("dataverse",`Current user resolved: ${s.name}.`),s}function ES(){z.useEffect(()=>{const e=wg();return e>0&&ne.getState().logInfo("ribbon",`Discarded ${e} unsaved-changes draft(s) older than ${Hl} days, or saved by an earlier version of Command Bar Studio (they can't be restored correctly).`),Ig()},[])}function OS(){const e=we(n=>n.saveFailed),t=we(n=>n.lastSavedAt);return e?r.jsx(Re,{intent:"error",layout:"multiline",style:{position:"absolute",top:0,left:0,right:0,zIndex:1e3},children:r.jsxs(je,{children:["Your latest changes can't be saved as a draft: the browser storage is full."," ",t?r.jsxs(r.Fragment,{children:["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."]}):r.jsx(r.Fragment,{children:"Publish them, or they are lost when Command Bar Studio closes."})]})}):null}function MS(){const e=oe(i=>i.connectionNotice),t=oe(i=>i.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 r.jsxs(Re,{intent:e.draftLost?"error":e.to.environment==="Production"?"warning":"info",layout:"multiline",role:"alert",style:{position:"absolute",top:0,left:0,right:0,zIndex:1e3},children:[r.jsxs(je,{children:[r.jsxs(Lp,{children:["Connection changed to ",o]}),"The solution and table loaded from ",n," were closed; pick a solution to continue in ",o,"."," ",e.draftKept&&r.jsxs(r.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&&r.jsx(r.Fragment,{children:"Your unpublished changes couldn't be saved as a draft (the browser storage is full) and are lost."})]}),r.jsx(Xt,{containerAction:r.jsx(Z,{"aria-label":"Dismiss",appearance:"transparent",icon:r.jsx(Ot,{}),onClick:t})})]})}function BS(){const e=we(s=>s.pending),t=we(s=>s.pendingBaselineChanged),n=we(s=>s.restoreError),o=we(s=>s.restoreDraft),i=we(s=>s.discardDraft);return e?r.jsx(sn,{open:!0,modalType:"alert",children:r.jsx(rn,{style:{maxWidth:"520px"},children:r.jsxs(ln,{children:[r.jsx(an,{children:"Unpublished changes"}),r.jsxs(cn,{children:[r.jsxs(q,{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&&r.jsx(Re,{intent:"warning",layout:"multiline",style:{marginTop:"12px"},children:r.jsx(je,{children:"The table's ribbon has changed since then (published from another session, or by someone else): review the publish plan before publishing."})}),n&&r.jsx(Re,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:r.jsxs(je,{children:["These changes couldn't be restored (",n,"). Discard them to continue; the details are in the runtime log."]})})]}),r.jsxs(dn,{children:[r.jsx(Z,{appearance:"secondary",onClick:i,children:"Discard"}),r.jsx(Z,{appearance:"primary",disabled:!!n,onClick:()=>o(),children:"Restore"})]})]})})}):null}function zS(){const e=we(d=>d.pendingSwitch),t=we(d=>d.pending!==null),n=we(d=>d.saveFailed),o=we(d=>d.resolveSwitch),i=oe(d=>d.activeEntity),s=oe(d=>d.activeSolution);if(!e)return null;const a=i?.displayName||i?.logicalName||"this table",l=e.kind==="entity"?`table ${e.entity.displayName||e.entity.logicalName}`:`solution ${e.solution.friendlyName||e.solution.uniqueName}`,c=s?.friendlyName||s?.uniqueName||"this solution";return r.jsx(sn,{open:!0,modalType:"alert",onOpenChange:(d,u)=>!u.open&&o("cancel"),children:r.jsx(rn,{style:{maxWidth:"520px"},children:r.jsxs(ln,{children:[r.jsx(an,{children:"Unpublished changes"}),r.jsxs(cn,{children:[r.jsxs(q,{block:!0,children:[a," has changes that aren't published. Switch to ",l,"?"]}),r.jsx(q,{block:!0,style:{marginTop:"8px"},children:t?r.jsxs(r.Fragment,{children:["Changes made since opening ",a," aren't saved: the unsaved changes of your previous session are kept until you restore or discard them."]}):r.jsxs(r.Fragment,{children:[r.jsx("strong",{children:"Keep as draft"})," saves them on this computer: they are offered again when you open ",a," ","in ",c,". ",r.jsx("strong",{children:"Discard"})," deletes them."]})}),n&&!t&&r.jsx(Re,{intent:"error",layout:"multiline",style:{marginTop:"12px"},children:r.jsx(je,{children:"The changes can't be saved as a draft: the browser storage is full. Publish them first, or discard them to switch."})})]}),r.jsxs(dn,{children:[r.jsx(Z,{appearance:"secondary",onClick:()=>o("cancel"),children:"Cancel"}),r.jsxs(Z,{appearance:"secondary",onClick:()=>o("discard"),children:["Discard",t?" and switch":""]}),!t&&r.jsx(Z,{appearance:"primary",disabled:n,onClick:()=>o("keep"),children:"Keep as draft"})]})]})})})}const LS=me({leftPaneTabs:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},tabList:{flexShrink:0,borderBottom:`1px solid ${p.colorNeutralStroke2}`},tabContent:{flex:1,overflow:"hidden"}});function PS(){const e=LS(),[t,n]=z.useState("tables");return r.jsxs("div",{className:e.leftPaneTabs,children:[r.jsxs(us,{className:e.tabList,selectedValue:t,onTabSelect:(o,i)=>n(i.value),size:"small",children:[r.jsx(ot,{value:"tables",children:"Tables"}),r.jsx(ot,{value:"elements",children:"Solution"})]}),r.jsx("div",{className:e.tabContent,children:t==="tables"?r.jsx(tS,{}):r.jsx(sS,{})})]})}function FS(){const e=oe(T=>T.setSolutions),t=oe(T=>T.setEntities),n=oe(T=>T.setCurrentUser),o=oe(T=>T.setSolutionEntityIds),i=oe(T=>T.setSolutionRibbonComponentIds),s=oe(T=>T.activeSolution),a=oe(T=>T.activeEntity),l=oe(T=>T.connectionVersion),c=E(T=>T.loadWorkspace),d=te(T=>T.setTabId),u=ee(T=>T.themeMode),m=ne(T=>T.logInfo),f=ne(T=>T.logWarn),y=ne(T=>T.logError);ES(),$y();const[x,h]=z.useState("idle"),[S,v]=z.useState(null),[b,w]=z.useState(null),[C,I]=z.useState(null),[$,j]=z.useState(0);z.useEffect(()=>{m("runtime","Loading solutions and current user...");let T=!1;return rS().then(A=>{T||(e(A),m("runtime",`Loaded ${A.length} solution(s). Pick one to load its tables.`))}).catch(A=>{T||y("runtime",`Failed to load solutions: ${A instanceof Error?A.message:String(A)}`)}),DS().then(A=>{T||!A.id||(n(A.id,A.name),m("runtime",`Current user: ${A.name}.`))}).catch(A=>{f("runtime",`Failed to resolve current user: ${A instanceof Error?A.message:String(A)}`)}),()=>{T=!0}},[e,n,m,f,y,l]),z.useEffect(()=>{if(!s){o(null),i(null),t([]);return}let T=!1;return(async()=>{try{const[A,W]=await Promise.all([aS(s.id),lS(s.id)]);if(T)return;if(o(A),i(W),A.length===0){t([]);return}const D=await dS(A);if(T)return;t(D)}catch(A){if(T)return;y("runtime",`Failed to load solution tables: ${A instanceof Error?A.message:String(A)}`),o([]),i([]),t([])}})(),()=>{T=!0}},[s,t,o,i,y]),z.useEffect(()=>{if(we.getState().beginLoad(),!a?.logicalName){h("idle"),v(null),I(null);return}let T=!1;const A=Rg(a.logicalName);return h("loading"),v(null),I(null),w(null),m("ribbon",`Loading ribbon workspace for ${a.logicalName}...`),es.getState().setManaged([]),kS(a.logicalName).then(W=>{T||es.getState().setManaged(W)}),Promise.all([RS(a.logicalName,W=>{T||w(W)}),TS(a.logicalName).catch(()=>new Map)]).then(([W,D])=>{if(T)return;const N=new Set([...W.layers?.entity?.controlIds??[],...W.layers?.application?.controlIds??[]]);xh(W.ribbons,D,N);const M=[],k=new Set;for(const ie of Object.values(W.ribbons))for(const F of ie.tabs)for(const _ of F.groups)for(const L of Ne(_))L.origin==="managed"&&!k.has(L.id)&&(k.add(L.id),M.push({elementId:L.id,elementKind:"button",solutions:[{solutionId:"",solutionName:L.solutionName??"Managed Solution",publisher:L.publisherName??"",managed:!0,wins:!0,importedOn:void 0}]}));E.getState().setConflicts(M),c({ribbons:W.ribbons,commands:W.commands,displayRules:W.displayRules,enableRules:W.enableRules,locLabels:W.locLabels,layers:W.layers,baseLanguageCode:W.baseLanguageCode,baseLanguageUnknown:W.baseLanguageCode===void 0,labelsUnknown:W.layerReadError!==void 0,orphans:{entity:gS(W.orphans??[],mS(oe.getState().connectionUrl,a.logicalName))}});const{location:B,tabId:G}=te.getState(),X=W.ribbons[B]?.tabs??[];if(!(X.some(ie=>ie.id===G)&&!qo(G))){const ie=Nn(X);ie&&d(ie)}we.getState().workspaceLoaded(A),I(W.layerReadError??null),W.layerReadError&&f("ribbon",`Unmanaged layer not read: ${W.layerReadError}`),h("idle"),m("ribbon",`Ribbon workspace loaded for ${a.logicalName}.`)}).catch(W=>{if(T)return;const D=W instanceof Error?W.message:"Failed to load ribbon";h("error"),v(D),y("ribbon",`Ribbon load failed for ${a.logicalName}: ${D}`)}),()=>{T=!0}},[a?.logicalName,c,$,d,m,f,y]);function R(){vS(),j(T=>T+1)}return r.jsxs(Pp,{theme:u==="dark"?Fp:_p,children:[r.jsxs(ub,{leftPane:r.jsx(PS,{}),rightPane:r.jsx(Zx,{}),bottomPanel:r.jsx(Qx,{}),children:[r.jsx(OS,{}),r.jsx(MS,{}),r.jsx(wx,{isLoadingRibbon:x==="loading",loadingTable:a?.displayName??a?.logicalName,loadingStep:b,ribbonLoadError:S,layerReadError:C,onRetryRibbonLoad:R})]}),r.jsx(BS,{}),r.jsx(zS,{})]})}const _S=5e3,oa=3e4,Yc="1.2.7";function ia(e,t,n){let o;return Promise.race([e,new Promise((i,s)=>{o=setTimeout(()=>s(new Error(n)),t)})]).finally(()=>clearTimeout(o))}async function qS(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 ${Yc} or later.`);const i=[];let s="light";try{const l=t.utils?.getCurrentTheme;if(typeof l!="function")throw new Error("the host has no theme API");s=await ia(l(),_S,"the host didn't answer")==="dark"?"dark":"light"}catch(l){i.push(`Couldn't read the host theme (${Qc(l)}); using the light theme.`)}const a=await ia(o(),oa,`Power Platform ToolBox didn't return the active connection within ${oa/1e3} seconds. Make sure a connection is active and signed in, then open Command Bar Studio again.`);if(!a)throw new Error("No active connection: connect to an environment in Power Platform ToolBox, then open Command Bar Studio again.");return{connection:a,theme:s,warnings:i}}function Zc(e,t,n="Command Bar Studio couldn't start"){const o=e.ownerDocument,i=(c,d)=>{const u=o.createElement(c);return d&&(u.textContent=d),u},s=i("div");s.setAttribute("role","alert"),s.style.cssText="font-family: 'Segoe UI', system-ui, sans-serif; padding: 24px; max-width: 720px; line-height: 1.5;",s.append(i("h1",n));const a=i("p",Qc(t));a.style.fontWeight="600",s.append(a);const l=i("ul");for(const c of["Close the Command Bar Studio tab and open the tool again.",`Use Power Platform ToolBox ${Yc} 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."])l.append(i("li",c));s.append(l),e.replaceChildren(s)}function Qc(e){return e instanceof Error?e.message:String(e)}class WS extends z.Component{state={error:void 0};box=z.createRef();static getDerivedStateFromError(t){return{error:t??new Error("Unknown error")}}componentDidCatch(t,n){console.error("[CBS RootErrorBoundary]",t,n),ne.getState().logError("app",t instanceof Error?t.message:String(t))}componentDidMount(){this.componentDidUpdate()}componentDidUpdate(){this.state.error!==void 0&&this.box.current&&Zc(this.box.current,this.state.error,"Command Bar Studio stopped working")}render(){return this.state.error===void 0?this.props.children:r.jsx("div",{ref:this.box})}}function HS(e){return e.replace(/([A-Z])/g,(t,n,o)=>(o>0?"_":"")+t.toLowerCase())}function GS(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 ed(e,t="regular"){return`${HS(e)}${t==="filled"?".filled":""}.svg`}function US(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/${ed(t,n)}`}const XS=11,VS=2*6e4,sa={save:Wb,publish:bc},td=new Set;function KS(){td.clear()}async function kv(e,t,n,o,i={}){const s=i.save??sa.save,a=i.publish??sa.publish,l=i.published??td,c=US(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 s(c,GS(d),XS,{displayName:`${ed(e,t)} (CBS icon)`,keepExisting:!0,guard:i.guard,publish:!1}),m={name:c,id:u.id,created:u.created};if(!l.has(u.id))try{await mc(`Publishing icon web resource ${c}`,()=>a(u.id,i.guard),{timeoutMs:VS,...i.busy}),l.add(u.id)}catch(f){m.publishError=f instanceof Error?f.message:String(f)}return m}const JS=["commandEditorOpen","ruleEditorOpen","xmlDrawerOpen","iconPickerOpen","localizationEditorOpen","newGroupOpen","importXmlOpen","conflictDrawerOpen","webResourceBrowserOpen","urlComposerOpen","diffViewerOpen","tabDisplayRulesOpen","scalingEditorOpen","newTabOpen"];function YS(e){if(!e)return"none";const t=oe.getState(),n=ne.getState();if(po(e)===po({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 i=`${t.connectionName||t.connectionUrl} (${t.environment})`,s=`${e.name} (${e.environment})`,{hadChanges:a,kept:l}=we.getState().releaseForConnectionChange();E.getState().resetWorkspace(),te.getState().clearSelection(),ye.getState().reset(),KS(),Ny(),rs.clear(),t.switchConnection(e,{draftKept:a&&l,draftLost:a&&!l});try{ee.setState(Object.fromEntries(JS.map(c=>[c,!1])))}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 ${i} to ${s}. The loaded solution and table were closed.`),a&&l&&n.logInfo("startup",`The unpublished changes were kept as a draft for ${i}.`),a&&!l&&n.logError("startup",`The unpublished changes on ${i} couldn't be saved as a draft (browser storage full) and are lost.`),"switched"}async function ZS(){const e=ne.getState().logInfo,t=window,n=t.toolboxAPI,{connection:o,theme:i,warnings:s}=await qS({toolboxAPI:n,dataverseAPI:t.dataverseAPI});e("startup","Connected to PPTB host runtime.");for(const f of s)ne.getState().logWarn("startup",f);e("startup",`Host theme loaded: ${i}.`);const{setConnection:a}=oe.getState(),{setThemeMode:l}=ee.getState(),c=await ms().catch(()=>null)??o;a(c.url,c.name,c.environment,c.id),l(i),e("startup",`Connected to ${c.name} (${c.environment}).`),lf(f=>YS(f));const d=()=>{n.utils.getCurrentTheme().then(f=>{ee.getState().setThemeMode(f==="dark"?"dark":"light")}).catch(f=>{ne.getState().logWarn("startup",`Theme refresh failed: ${f instanceof Error?f.message:String(f)}`)})};document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&d()}),n.events?.on((f,y)=>{y?.event==="settings:updated"&&d()});const u=document.getElementById("root");if(!u)throw new Error("No #root element found");nf.createRoot(u).render(r.jsx(z.StrictMode,{children:r.jsx(WS,{children:r.jsx(FS,{})})}))}ZS().catch(e=>{ne.getState().logError("startup",e instanceof Error?e.message:String(e)),console.error(e);const t=document.getElementById("root")??document.body;Zc(t,e)});export{Yl as $,ol as A,fs as B,kx as C,Ua as D,$g as E,lv as F,cv as G,hs as H,dv as I,sv as J,av as K,iv as L,pS as M,ae as N,vS as O,ne as P,Ab as Q,Iv as R,pv as S,bv as T,Co as U,If as V,mc as W,Eb as X,rv as Y,oe as Z,ms as _,ee as a,yv as a0,xv as a1,vv as a2,Rv as a3,Tv as a4,hv as a5,Pe as a6,Nl as a7,rl as a8,lr as a9,Ss as aA,Nv as aB,Tn as aC,Fs as aD,_s as aE,Ln as aF,Ps as aG,Es as aH,fv as aI,qo as aa,te as ab,jl as ac,hn as ad,pr as ae,gv as af,oc as ag,_o as ah,rt as ai,Wa as aj,Bi as ak,xo as al,Be as am,at as an,we as ao,mn as ap,uv as aq,Mo as ar,Bo as as,zo as at,Os as au,HS as av,US as aw,Lb as ax,kv as ay,Cv as az,ic as b,Zl as c,Ne as d,En as e,qb as f,mv as g,$v as h,wv as i,Wb as j,_a as k,jv as l,un as m,ps as n,bh as o,ov as p,ph as q,hh as r,Sv as s,fh as t,E as u,dl as v,rs as w,Wi as x,go as y,nl as z};